@saluzi/codegraph 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (658) hide show
  1. package/README.md +2 -2
  2. package/dist/bin/codegraph.d.ts +26 -0
  3. package/dist/bin/codegraph.d.ts.map +1 -0
  4. package/dist/bin/codegraph.js +2249 -0
  5. package/dist/bin/codegraph.js.map +1 -0
  6. package/dist/bin/command-supervision.d.ts +49 -0
  7. package/dist/bin/command-supervision.d.ts.map +1 -0
  8. package/dist/bin/command-supervision.js +95 -0
  9. package/dist/bin/command-supervision.js.map +1 -0
  10. package/dist/bin/fatal-handler.d.ts +20 -0
  11. package/dist/bin/fatal-handler.d.ts.map +1 -0
  12. package/dist/bin/fatal-handler.js +118 -0
  13. package/dist/bin/fatal-handler.js.map +1 -0
  14. package/dist/bin/node-version-check.d.ts +37 -0
  15. package/dist/bin/node-version-check.d.ts.map +1 -0
  16. package/dist/bin/node-version-check.js +79 -0
  17. package/dist/bin/node-version-check.js.map +1 -0
  18. package/dist/bin/uninstall.d.ts +14 -0
  19. package/dist/bin/uninstall.d.ts.map +1 -0
  20. package/dist/bin/uninstall.js +36 -0
  21. package/dist/bin/uninstall.js.map +1 -0
  22. package/dist/context/formatter.d.ts +30 -0
  23. package/dist/context/formatter.d.ts.map +1 -0
  24. package/dist/context/formatter.js +263 -0
  25. package/dist/context/formatter.js.map +1 -0
  26. package/dist/context/index.d.ts +119 -0
  27. package/dist/context/index.d.ts.map +1 -0
  28. package/dist/context/index.js +1296 -0
  29. package/dist/context/index.js.map +1 -0
  30. package/dist/context/markers.d.ts +19 -0
  31. package/dist/context/markers.d.ts.map +1 -0
  32. package/dist/context/markers.js +22 -0
  33. package/dist/context/markers.js.map +1 -0
  34. package/dist/db/index.d.ts +201 -0
  35. package/dist/db/index.d.ts.map +1 -0
  36. package/dist/db/index.js +493 -0
  37. package/dist/db/index.js.map +1 -0
  38. package/dist/db/migrations.d.ts +44 -0
  39. package/dist/db/migrations.d.ts.map +1 -0
  40. package/dist/db/migrations.js +212 -0
  41. package/dist/db/migrations.js.map +1 -0
  42. package/dist/db/queries.d.ts +513 -0
  43. package/dist/db/queries.d.ts.map +1 -0
  44. package/dist/db/queries.js +1886 -0
  45. package/dist/db/queries.js.map +1 -0
  46. package/dist/db/schema.sql +194 -0
  47. package/dist/db/sqlite-adapter.d.ts +65 -0
  48. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  49. package/dist/db/sqlite-adapter.js +274 -0
  50. package/dist/db/sqlite-adapter.js.map +1 -0
  51. package/dist/db/wal-valve.d.ts +106 -0
  52. package/dist/db/wal-valve.d.ts.map +1 -0
  53. package/dist/db/wal-valve.js +208 -0
  54. package/dist/db/wal-valve.js.map +1 -0
  55. package/dist/directory.d.ts +183 -0
  56. package/dist/directory.d.ts.map +1 -0
  57. package/dist/directory.js +797 -0
  58. package/dist/directory.js.map +1 -0
  59. package/dist/errors.d.ts +136 -0
  60. package/dist/errors.d.ts.map +1 -0
  61. package/dist/errors.js +219 -0
  62. package/dist/errors.js.map +1 -0
  63. package/dist/extraction/astro-extractor.d.ts +79 -0
  64. package/dist/extraction/astro-extractor.d.ts.map +1 -0
  65. package/dist/extraction/astro-extractor.js +320 -0
  66. package/dist/extraction/astro-extractor.js.map +1 -0
  67. package/dist/extraction/cfml-extractor.d.ts +107 -0
  68. package/dist/extraction/cfml-extractor.d.ts.map +1 -0
  69. package/dist/extraction/cfml-extractor.js +494 -0
  70. package/dist/extraction/cfml-extractor.js.map +1 -0
  71. package/dist/extraction/dfm-extractor.d.ts +31 -0
  72. package/dist/extraction/dfm-extractor.d.ts.map +1 -0
  73. package/dist/extraction/dfm-extractor.js +151 -0
  74. package/dist/extraction/dfm-extractor.js.map +1 -0
  75. package/dist/extraction/extraction-version.d.ts +25 -0
  76. package/dist/extraction/extraction-version.d.ts.map +1 -0
  77. package/dist/extraction/extraction-version.js +28 -0
  78. package/dist/extraction/extraction-version.js.map +1 -0
  79. package/dist/extraction/function-ref.d.ts +118 -0
  80. package/dist/extraction/function-ref.d.ts.map +1 -0
  81. package/dist/extraction/function-ref.js +727 -0
  82. package/dist/extraction/function-ref.js.map +1 -0
  83. package/dist/extraction/generated-detection.d.ts +30 -0
  84. package/dist/extraction/generated-detection.d.ts.map +1 -0
  85. package/dist/extraction/generated-detection.js +83 -0
  86. package/dist/extraction/generated-detection.js.map +1 -0
  87. package/dist/extraction/grammars.d.ts +138 -0
  88. package/dist/extraction/grammars.d.ts.map +1 -0
  89. package/dist/extraction/grammars.js +631 -0
  90. package/dist/extraction/grammars.js.map +1 -0
  91. package/dist/extraction/index.d.ts +232 -0
  92. package/dist/extraction/index.d.ts.map +1 -0
  93. package/dist/extraction/index.js +2409 -0
  94. package/dist/extraction/index.js.map +1 -0
  95. package/dist/extraction/languages/arkts.d.ts +3 -0
  96. package/dist/extraction/languages/arkts.d.ts.map +1 -0
  97. package/dist/extraction/languages/arkts.js +127 -0
  98. package/dist/extraction/languages/arkts.js.map +1 -0
  99. package/dist/extraction/languages/c-cpp.d.ts +110 -0
  100. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  101. package/dist/extraction/languages/c-cpp.js +837 -0
  102. package/dist/extraction/languages/c-cpp.js.map +1 -0
  103. package/dist/extraction/languages/cfquery.d.ts +12 -0
  104. package/dist/extraction/languages/cfquery.d.ts.map +1 -0
  105. package/dist/extraction/languages/cfquery.js +28 -0
  106. package/dist/extraction/languages/cfquery.js.map +1 -0
  107. package/dist/extraction/languages/cfscript.d.ts +3 -0
  108. package/dist/extraction/languages/cfscript.d.ts.map +1 -0
  109. package/dist/extraction/languages/cfscript.js +73 -0
  110. package/dist/extraction/languages/cfscript.js.map +1 -0
  111. package/dist/extraction/languages/cobol.d.ts +33 -0
  112. package/dist/extraction/languages/cobol.d.ts.map +1 -0
  113. package/dist/extraction/languages/cobol.js +499 -0
  114. package/dist/extraction/languages/cobol.js.map +1 -0
  115. package/dist/extraction/languages/csharp.d.ts +25 -0
  116. package/dist/extraction/languages/csharp.d.ts.map +1 -0
  117. package/dist/extraction/languages/csharp.js +175 -0
  118. package/dist/extraction/languages/csharp.js.map +1 -0
  119. package/dist/extraction/languages/dart.d.ts +3 -0
  120. package/dist/extraction/languages/dart.d.ts.map +1 -0
  121. package/dist/extraction/languages/dart.js +374 -0
  122. package/dist/extraction/languages/dart.js.map +1 -0
  123. package/dist/extraction/languages/erlang.d.ts +3 -0
  124. package/dist/extraction/languages/erlang.d.ts.map +1 -0
  125. package/dist/extraction/languages/erlang.js +350 -0
  126. package/dist/extraction/languages/erlang.js.map +1 -0
  127. package/dist/extraction/languages/go.d.ts +3 -0
  128. package/dist/extraction/languages/go.d.ts.map +1 -0
  129. package/dist/extraction/languages/go.js +111 -0
  130. package/dist/extraction/languages/go.js.map +1 -0
  131. package/dist/extraction/languages/index.d.ts +10 -0
  132. package/dist/extraction/languages/index.d.ts.map +1 -0
  133. package/dist/extraction/languages/index.js +71 -0
  134. package/dist/extraction/languages/index.js.map +1 -0
  135. package/dist/extraction/languages/java.d.ts +3 -0
  136. package/dist/extraction/languages/java.d.ts.map +1 -0
  137. package/dist/extraction/languages/java.js +315 -0
  138. package/dist/extraction/languages/java.js.map +1 -0
  139. package/dist/extraction/languages/javascript.d.ts +3 -0
  140. package/dist/extraction/languages/javascript.d.ts.map +1 -0
  141. package/dist/extraction/languages/javascript.js +106 -0
  142. package/dist/extraction/languages/javascript.js.map +1 -0
  143. package/dist/extraction/languages/kotlin.d.ts +3 -0
  144. package/dist/extraction/languages/kotlin.d.ts.map +1 -0
  145. package/dist/extraction/languages/kotlin.js +379 -0
  146. package/dist/extraction/languages/kotlin.js.map +1 -0
  147. package/dist/extraction/languages/lua.d.ts +3 -0
  148. package/dist/extraction/languages/lua.d.ts.map +1 -0
  149. package/dist/extraction/languages/lua.js +150 -0
  150. package/dist/extraction/languages/lua.js.map +1 -0
  151. package/dist/extraction/languages/luau.d.ts +3 -0
  152. package/dist/extraction/languages/luau.d.ts.map +1 -0
  153. package/dist/extraction/languages/luau.js +37 -0
  154. package/dist/extraction/languages/luau.js.map +1 -0
  155. package/dist/extraction/languages/nix.d.ts +3 -0
  156. package/dist/extraction/languages/nix.d.ts.map +1 -0
  157. package/dist/extraction/languages/nix.js +294 -0
  158. package/dist/extraction/languages/nix.js.map +1 -0
  159. package/dist/extraction/languages/objc.d.ts +3 -0
  160. package/dist/extraction/languages/objc.d.ts.map +1 -0
  161. package/dist/extraction/languages/objc.js +175 -0
  162. package/dist/extraction/languages/objc.js.map +1 -0
  163. package/dist/extraction/languages/pascal.d.ts +3 -0
  164. package/dist/extraction/languages/pascal.d.ts.map +1 -0
  165. package/dist/extraction/languages/pascal.js +77 -0
  166. package/dist/extraction/languages/pascal.js.map +1 -0
  167. package/dist/extraction/languages/php.d.ts +3 -0
  168. package/dist/extraction/languages/php.d.ts.map +1 -0
  169. package/dist/extraction/languages/php.js +196 -0
  170. package/dist/extraction/languages/php.js.map +1 -0
  171. package/dist/extraction/languages/python.d.ts +3 -0
  172. package/dist/extraction/languages/python.d.ts.map +1 -0
  173. package/dist/extraction/languages/python.js +56 -0
  174. package/dist/extraction/languages/python.js.map +1 -0
  175. package/dist/extraction/languages/r.d.ts +3 -0
  176. package/dist/extraction/languages/r.d.ts.map +1 -0
  177. package/dist/extraction/languages/r.js +314 -0
  178. package/dist/extraction/languages/r.js.map +1 -0
  179. package/dist/extraction/languages/ruby.d.ts +3 -0
  180. package/dist/extraction/languages/ruby.d.ts.map +1 -0
  181. package/dist/extraction/languages/ruby.js +149 -0
  182. package/dist/extraction/languages/ruby.js.map +1 -0
  183. package/dist/extraction/languages/rust.d.ts +3 -0
  184. package/dist/extraction/languages/rust.d.ts.map +1 -0
  185. package/dist/extraction/languages/rust.js +142 -0
  186. package/dist/extraction/languages/rust.js.map +1 -0
  187. package/dist/extraction/languages/scala.d.ts +3 -0
  188. package/dist/extraction/languages/scala.d.ts.map +1 -0
  189. package/dist/extraction/languages/scala.js +209 -0
  190. package/dist/extraction/languages/scala.js.map +1 -0
  191. package/dist/extraction/languages/solidity.d.ts +3 -0
  192. package/dist/extraction/languages/solidity.d.ts.map +1 -0
  193. package/dist/extraction/languages/solidity.js +293 -0
  194. package/dist/extraction/languages/solidity.js.map +1 -0
  195. package/dist/extraction/languages/swift.d.ts +3 -0
  196. package/dist/extraction/languages/swift.d.ts.map +1 -0
  197. package/dist/extraction/languages/swift.js +152 -0
  198. package/dist/extraction/languages/swift.js.map +1 -0
  199. package/dist/extraction/languages/terraform.d.ts +3 -0
  200. package/dist/extraction/languages/terraform.d.ts.map +1 -0
  201. package/dist/extraction/languages/terraform.js +641 -0
  202. package/dist/extraction/languages/terraform.js.map +1 -0
  203. package/dist/extraction/languages/typescript.d.ts +16 -0
  204. package/dist/extraction/languages/typescript.d.ts.map +1 -0
  205. package/dist/extraction/languages/typescript.js +167 -0
  206. package/dist/extraction/languages/typescript.js.map +1 -0
  207. package/dist/extraction/languages/vbnet.d.ts +11 -0
  208. package/dist/extraction/languages/vbnet.d.ts.map +1 -0
  209. package/dist/extraction/languages/vbnet.js +141 -0
  210. package/dist/extraction/languages/vbnet.js.map +1 -0
  211. package/dist/extraction/liquid-extractor.d.ts +59 -0
  212. package/dist/extraction/liquid-extractor.d.ts.map +1 -0
  213. package/dist/extraction/liquid-extractor.js +357 -0
  214. package/dist/extraction/liquid-extractor.js.map +1 -0
  215. package/dist/extraction/mybatis-extractor.d.ts +68 -0
  216. package/dist/extraction/mybatis-extractor.d.ts.map +1 -0
  217. package/dist/extraction/mybatis-extractor.js +300 -0
  218. package/dist/extraction/mybatis-extractor.js.map +1 -0
  219. package/dist/extraction/parse-pool.d.ts +152 -0
  220. package/dist/extraction/parse-pool.d.ts.map +1 -0
  221. package/dist/extraction/parse-pool.js +387 -0
  222. package/dist/extraction/parse-pool.js.map +1 -0
  223. package/dist/extraction/parse-worker.d.ts +8 -0
  224. package/dist/extraction/parse-worker.d.ts.map +1 -0
  225. package/dist/extraction/parse-worker.js +104 -0
  226. package/dist/extraction/parse-worker.js.map +1 -0
  227. package/dist/extraction/razor-extractor.d.ts +42 -0
  228. package/dist/extraction/razor-extractor.d.ts.map +1 -0
  229. package/dist/extraction/razor-extractor.js +285 -0
  230. package/dist/extraction/razor-extractor.js.map +1 -0
  231. package/dist/extraction/svelte-extractor.d.ts +56 -0
  232. package/dist/extraction/svelte-extractor.d.ts.map +1 -0
  233. package/dist/extraction/svelte-extractor.js +275 -0
  234. package/dist/extraction/svelte-extractor.js.map +1 -0
  235. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  236. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  237. package/dist/extraction/tree-sitter-helpers.js +153 -0
  238. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  239. package/dist/extraction/tree-sitter-types.d.ts +258 -0
  240. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  241. package/dist/extraction/tree-sitter-types.js +10 -0
  242. package/dist/extraction/tree-sitter-types.js.map +1 -0
  243. package/dist/extraction/tree-sitter.d.ts +706 -0
  244. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  245. package/dist/extraction/tree-sitter.js +6506 -0
  246. package/dist/extraction/tree-sitter.js.map +1 -0
  247. package/dist/extraction/vue-extractor.d.ts +51 -0
  248. package/dist/extraction/vue-extractor.d.ts.map +1 -0
  249. package/dist/extraction/vue-extractor.js +254 -0
  250. package/dist/extraction/vue-extractor.js.map +1 -0
  251. package/dist/extraction/wasm/tree-sitter-arkts.wasm +0 -0
  252. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  253. package/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  254. package/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  255. package/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  256. package/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  257. package/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  258. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  259. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  260. package/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  261. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  262. package/dist/extraction/wasm/tree-sitter-r.wasm +0 -0
  263. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  264. package/dist/extraction/wasm/tree-sitter-terraform.wasm +0 -0
  265. package/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  266. package/dist/extraction/wasm-runtime-flags.d.ts +38 -0
  267. package/dist/extraction/wasm-runtime-flags.d.ts.map +1 -0
  268. package/dist/extraction/wasm-runtime-flags.js +106 -0
  269. package/dist/extraction/wasm-runtime-flags.js.map +1 -0
  270. package/dist/graph/index.d.ts +8 -0
  271. package/dist/graph/index.d.ts.map +1 -0
  272. package/dist/graph/index.js +13 -0
  273. package/dist/graph/index.js.map +1 -0
  274. package/dist/graph/queries.d.ts +106 -0
  275. package/dist/graph/queries.d.ts.map +1 -0
  276. package/dist/graph/queries.js +339 -0
  277. package/dist/graph/queries.js.map +1 -0
  278. package/dist/graph/traversal.d.ts +127 -0
  279. package/dist/graph/traversal.d.ts.map +1 -0
  280. package/dist/graph/traversal.js +599 -0
  281. package/dist/graph/traversal.js.map +1 -0
  282. package/dist/index.d.ts +644 -0
  283. package/dist/index.d.ts.map +1 -0
  284. package/dist/index.js +1492 -0
  285. package/dist/index.js.map +1 -0
  286. package/dist/installer/config-writer.d.ts +28 -0
  287. package/dist/installer/config-writer.d.ts.map +1 -0
  288. package/dist/installer/config-writer.js +91 -0
  289. package/dist/installer/config-writer.js.map +1 -0
  290. package/dist/installer/index.d.ts +142 -0
  291. package/dist/installer/index.d.ts.map +1 -0
  292. package/dist/installer/index.js +619 -0
  293. package/dist/installer/index.js.map +1 -0
  294. package/dist/installer/instructions-template.d.ts +41 -0
  295. package/dist/installer/instructions-template.d.ts.map +1 -0
  296. package/dist/installer/instructions-template.js +53 -0
  297. package/dist/installer/instructions-template.js.map +1 -0
  298. package/dist/installer/targets/antigravity.d.ts +57 -0
  299. package/dist/installer/targets/antigravity.d.ts.map +1 -0
  300. package/dist/installer/targets/antigravity.js +308 -0
  301. package/dist/installer/targets/antigravity.js.map +1 -0
  302. package/dist/installer/targets/claude.d.ts +62 -0
  303. package/dist/installer/targets/claude.d.ts.map +1 -0
  304. package/dist/installer/targets/claude.js +454 -0
  305. package/dist/installer/targets/claude.js.map +1 -0
  306. package/dist/installer/targets/codex.d.ts +18 -0
  307. package/dist/installer/targets/codex.d.ts.map +1 -0
  308. package/dist/installer/targets/codex.js +185 -0
  309. package/dist/installer/targets/codex.js.map +1 -0
  310. package/dist/installer/targets/cursor.d.ts +35 -0
  311. package/dist/installer/targets/cursor.d.ts.map +1 -0
  312. package/dist/installer/targets/cursor.js +254 -0
  313. package/dist/installer/targets/cursor.js.map +1 -0
  314. package/dist/installer/targets/gemini.d.ts +26 -0
  315. package/dist/installer/targets/gemini.d.ts.map +1 -0
  316. package/dist/installer/targets/gemini.js +165 -0
  317. package/dist/installer/targets/gemini.js.map +1 -0
  318. package/dist/installer/targets/hermes.d.ts +18 -0
  319. package/dist/installer/targets/hermes.d.ts.map +1 -0
  320. package/dist/installer/targets/hermes.js +359 -0
  321. package/dist/installer/targets/hermes.js.map +1 -0
  322. package/dist/installer/targets/kiro.d.ts +27 -0
  323. package/dist/installer/targets/kiro.d.ts.map +1 -0
  324. package/dist/installer/targets/kiro.js +178 -0
  325. package/dist/installer/targets/kiro.js.map +1 -0
  326. package/dist/installer/targets/opencode.d.ts +38 -0
  327. package/dist/installer/targets/opencode.d.ts.map +1 -0
  328. package/dist/installer/targets/opencode.js +288 -0
  329. package/dist/installer/targets/opencode.js.map +1 -0
  330. package/dist/installer/targets/registry.d.ts +35 -0
  331. package/dist/installer/targets/registry.d.ts.map +1 -0
  332. package/dist/installer/targets/registry.js +91 -0
  333. package/dist/installer/targets/registry.js.map +1 -0
  334. package/dist/installer/targets/shared.d.ts +101 -0
  335. package/dist/installer/targets/shared.d.ts.map +1 -0
  336. package/dist/installer/targets/shared.js +264 -0
  337. package/dist/installer/targets/shared.js.map +1 -0
  338. package/dist/installer/targets/toml.d.ts +52 -0
  339. package/dist/installer/targets/toml.d.ts.map +1 -0
  340. package/dist/installer/targets/toml.js +147 -0
  341. package/dist/installer/targets/toml.js.map +1 -0
  342. package/dist/installer/targets/types.d.ts +108 -0
  343. package/dist/installer/targets/types.d.ts.map +1 -0
  344. package/dist/installer/targets/types.js +16 -0
  345. package/dist/installer/targets/types.js.map +1 -0
  346. package/dist/mcp/daemon-manager.d.ts +42 -0
  347. package/dist/mcp/daemon-manager.d.ts.map +1 -0
  348. package/dist/mcp/daemon-manager.js +129 -0
  349. package/dist/mcp/daemon-manager.js.map +1 -0
  350. package/dist/mcp/daemon-paths.d.ts +73 -0
  351. package/dist/mcp/daemon-paths.d.ts.map +1 -0
  352. package/dist/mcp/daemon-paths.js +165 -0
  353. package/dist/mcp/daemon-paths.js.map +1 -0
  354. package/dist/mcp/daemon-registry.d.ts +47 -0
  355. package/dist/mcp/daemon-registry.d.ts.map +1 -0
  356. package/dist/mcp/daemon-registry.js +233 -0
  357. package/dist/mcp/daemon-registry.js.map +1 -0
  358. package/dist/mcp/daemon.d.ts +290 -0
  359. package/dist/mcp/daemon.d.ts.map +1 -0
  360. package/dist/mcp/daemon.js +862 -0
  361. package/dist/mcp/daemon.js.map +1 -0
  362. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  363. package/dist/mcp/dynamic-boundaries.d.ts.map +1 -0
  364. package/dist/mcp/dynamic-boundaries.js +360 -0
  365. package/dist/mcp/dynamic-boundaries.js.map +1 -0
  366. package/dist/mcp/early-ppid.d.ts +26 -0
  367. package/dist/mcp/early-ppid.d.ts.map +1 -0
  368. package/dist/mcp/early-ppid.js +29 -0
  369. package/dist/mcp/early-ppid.js.map +1 -0
  370. package/dist/mcp/engine.d.ts +122 -0
  371. package/dist/mcp/engine.d.ts.map +1 -0
  372. package/dist/mcp/engine.js +350 -0
  373. package/dist/mcp/engine.js.map +1 -0
  374. package/dist/mcp/index.d.ts +113 -0
  375. package/dist/mcp/index.d.ts.map +1 -0
  376. package/dist/mcp/index.js +506 -0
  377. package/dist/mcp/index.js.map +1 -0
  378. package/dist/mcp/liveness-watchdog.d.ts +35 -0
  379. package/dist/mcp/liveness-watchdog.d.ts.map +1 -0
  380. package/dist/mcp/liveness-watchdog.js +267 -0
  381. package/dist/mcp/liveness-watchdog.js.map +1 -0
  382. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  383. package/dist/mcp/ppid-watchdog.d.ts.map +1 -0
  384. package/dist/mcp/ppid-watchdog.js +64 -0
  385. package/dist/mcp/ppid-watchdog.js.map +1 -0
  386. package/dist/mcp/proxy.d.ts +87 -0
  387. package/dist/mcp/proxy.d.ts.map +1 -0
  388. package/dist/mcp/proxy.js +667 -0
  389. package/dist/mcp/proxy.js.map +1 -0
  390. package/dist/mcp/query-pool.d.ts +108 -0
  391. package/dist/mcp/query-pool.d.ts.map +1 -0
  392. package/dist/mcp/query-pool.js +315 -0
  393. package/dist/mcp/query-pool.js.map +1 -0
  394. package/dist/mcp/query-worker.d.ts +24 -0
  395. package/dist/mcp/query-worker.d.ts.map +1 -0
  396. package/dist/mcp/query-worker.js +87 -0
  397. package/dist/mcp/query-worker.js.map +1 -0
  398. package/dist/mcp/server-instructions.d.ts +34 -0
  399. package/dist/mcp/server-instructions.d.ts.map +1 -0
  400. package/dist/mcp/server-instructions.js +106 -0
  401. package/dist/mcp/server-instructions.js.map +1 -0
  402. package/dist/mcp/session.d.ts +93 -0
  403. package/dist/mcp/session.d.ts.map +1 -0
  404. package/dist/mcp/session.js +357 -0
  405. package/dist/mcp/session.js.map +1 -0
  406. package/dist/mcp/startup-handshake.d.ts +44 -0
  407. package/dist/mcp/startup-handshake.d.ts.map +1 -0
  408. package/dist/mcp/startup-handshake.js +73 -0
  409. package/dist/mcp/startup-handshake.js.map +1 -0
  410. package/dist/mcp/stdin-teardown.d.ts +27 -0
  411. package/dist/mcp/stdin-teardown.d.ts.map +1 -0
  412. package/dist/mcp/stdin-teardown.js +49 -0
  413. package/dist/mcp/stdin-teardown.js.map +1 -0
  414. package/dist/mcp/tools.d.ts +613 -0
  415. package/dist/mcp/tools.d.ts.map +1 -0
  416. package/dist/mcp/tools.js +4477 -0
  417. package/dist/mcp/tools.js.map +1 -0
  418. package/dist/mcp/transport.d.ts +188 -0
  419. package/dist/mcp/transport.d.ts.map +1 -0
  420. package/dist/mcp/transport.js +377 -0
  421. package/dist/mcp/transport.js.map +1 -0
  422. package/dist/mcp/version.d.ts +19 -0
  423. package/dist/mcp/version.d.ts.map +1 -0
  424. package/dist/mcp/version.js +71 -0
  425. package/dist/mcp/version.js.map +1 -0
  426. package/dist/project-config.d.ts +94 -0
  427. package/dist/project-config.d.ts.map +1 -0
  428. package/dist/project-config.js +374 -0
  429. package/dist/project-config.js.map +1 -0
  430. package/dist/resolution/c-fnptr-synthesizer.d.ts +6 -0
  431. package/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -0
  432. package/dist/resolution/c-fnptr-synthesizer.js +1062 -0
  433. package/dist/resolution/c-fnptr-synthesizer.js.map +1 -0
  434. package/dist/resolution/callback-synthesizer.d.ts +15 -0
  435. package/dist/resolution/callback-synthesizer.d.ts.map +1 -0
  436. package/dist/resolution/callback-synthesizer.js +3938 -0
  437. package/dist/resolution/callback-synthesizer.js.map +1 -0
  438. package/dist/resolution/cooperative-yield.d.ts +32 -0
  439. package/dist/resolution/cooperative-yield.d.ts.map +1 -0
  440. package/dist/resolution/cooperative-yield.js +42 -0
  441. package/dist/resolution/cooperative-yield.js.map +1 -0
  442. package/dist/resolution/frameworks/astro.d.ts +9 -0
  443. package/dist/resolution/frameworks/astro.d.ts.map +1 -0
  444. package/dist/resolution/frameworks/astro.js +169 -0
  445. package/dist/resolution/frameworks/astro.js.map +1 -0
  446. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  447. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  448. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  449. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  450. package/dist/resolution/frameworks/cics.d.ts +20 -0
  451. package/dist/resolution/frameworks/cics.d.ts.map +1 -0
  452. package/dist/resolution/frameworks/cics.js +90 -0
  453. package/dist/resolution/frameworks/cics.js.map +1 -0
  454. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  455. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  456. package/dist/resolution/frameworks/csharp.js +241 -0
  457. package/dist/resolution/frameworks/csharp.js.map +1 -0
  458. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  459. package/dist/resolution/frameworks/drupal.d.ts.map +1 -0
  460. package/dist/resolution/frameworks/drupal.js +367 -0
  461. package/dist/resolution/frameworks/drupal.js.map +1 -0
  462. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  463. package/dist/resolution/frameworks/expo-modules.d.ts.map +1 -0
  464. package/dist/resolution/frameworks/expo-modules.js +148 -0
  465. package/dist/resolution/frameworks/expo-modules.js.map +1 -0
  466. package/dist/resolution/frameworks/express.d.ts +8 -0
  467. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  468. package/dist/resolution/frameworks/express.js +308 -0
  469. package/dist/resolution/frameworks/express.js.map +1 -0
  470. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  471. package/dist/resolution/frameworks/fabric.d.ts.map +1 -0
  472. package/dist/resolution/frameworks/fabric.js +354 -0
  473. package/dist/resolution/frameworks/fabric.js.map +1 -0
  474. package/dist/resolution/frameworks/go.d.ts +8 -0
  475. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  476. package/dist/resolution/frameworks/go.js +161 -0
  477. package/dist/resolution/frameworks/go.js.map +1 -0
  478. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  479. package/dist/resolution/frameworks/goframe.d.ts.map +1 -0
  480. package/dist/resolution/frameworks/goframe.js +112 -0
  481. package/dist/resolution/frameworks/goframe.js.map +1 -0
  482. package/dist/resolution/frameworks/index.d.ts +50 -0
  483. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  484. package/dist/resolution/frameworks/index.js +175 -0
  485. package/dist/resolution/frameworks/index.js.map +1 -0
  486. package/dist/resolution/frameworks/java.d.ts +8 -0
  487. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  488. package/dist/resolution/frameworks/java.js +517 -0
  489. package/dist/resolution/frameworks/java.js.map +1 -0
  490. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  491. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  492. package/dist/resolution/frameworks/laravel.js +257 -0
  493. package/dist/resolution/frameworks/laravel.js.map +1 -0
  494. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  495. package/dist/resolution/frameworks/nestjs.d.ts.map +1 -0
  496. package/dist/resolution/frameworks/nestjs.js +698 -0
  497. package/dist/resolution/frameworks/nestjs.js.map +1 -0
  498. package/dist/resolution/frameworks/play.d.ts +19 -0
  499. package/dist/resolution/frameworks/play.d.ts.map +1 -0
  500. package/dist/resolution/frameworks/play.js +111 -0
  501. package/dist/resolution/frameworks/play.js.map +1 -0
  502. package/dist/resolution/frameworks/python.d.ts +10 -0
  503. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  504. package/dist/resolution/frameworks/python.js +400 -0
  505. package/dist/resolution/frameworks/python.js.map +1 -0
  506. package/dist/resolution/frameworks/react-native.d.ts +3 -0
  507. package/dist/resolution/frameworks/react-native.d.ts.map +1 -0
  508. package/dist/resolution/frameworks/react-native.js +410 -0
  509. package/dist/resolution/frameworks/react-native.js.map +1 -0
  510. package/dist/resolution/frameworks/react.d.ts +8 -0
  511. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  512. package/dist/resolution/frameworks/react.js +334 -0
  513. package/dist/resolution/frameworks/react.js.map +1 -0
  514. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  515. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  516. package/dist/resolution/frameworks/ruby.js +302 -0
  517. package/dist/resolution/frameworks/ruby.js.map +1 -0
  518. package/dist/resolution/frameworks/rust.d.ts +8 -0
  519. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  520. package/dist/resolution/frameworks/rust.js +304 -0
  521. package/dist/resolution/frameworks/rust.js.map +1 -0
  522. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  523. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  524. package/dist/resolution/frameworks/svelte.js +253 -0
  525. package/dist/resolution/frameworks/svelte.js.map +1 -0
  526. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  527. package/dist/resolution/frameworks/swift-objc.d.ts.map +1 -0
  528. package/dist/resolution/frameworks/swift-objc.js +252 -0
  529. package/dist/resolution/frameworks/swift-objc.js.map +1 -0
  530. package/dist/resolution/frameworks/swift.d.ts +10 -0
  531. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  532. package/dist/resolution/frameworks/swift.js +400 -0
  533. package/dist/resolution/frameworks/swift.js.map +1 -0
  534. package/dist/resolution/frameworks/terraform.d.ts +38 -0
  535. package/dist/resolution/frameworks/terraform.d.ts.map +1 -0
  536. package/dist/resolution/frameworks/terraform.js +277 -0
  537. package/dist/resolution/frameworks/terraform.js.map +1 -0
  538. package/dist/resolution/frameworks/vue.d.ts +9 -0
  539. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  540. package/dist/resolution/frameworks/vue.js +303 -0
  541. package/dist/resolution/frameworks/vue.js.map +1 -0
  542. package/dist/resolution/go-module.d.ts +26 -0
  543. package/dist/resolution/go-module.d.ts.map +1 -0
  544. package/dist/resolution/go-module.js +78 -0
  545. package/dist/resolution/go-module.js.map +1 -0
  546. package/dist/resolution/goframe-synthesizer.d.ts +29 -0
  547. package/dist/resolution/goframe-synthesizer.d.ts.map +1 -0
  548. package/dist/resolution/goframe-synthesizer.js +163 -0
  549. package/dist/resolution/goframe-synthesizer.js.map +1 -0
  550. package/dist/resolution/import-resolver.d.ts +85 -0
  551. package/dist/resolution/import-resolver.d.ts.map +1 -0
  552. package/dist/resolution/import-resolver.js +1974 -0
  553. package/dist/resolution/import-resolver.js.map +1 -0
  554. package/dist/resolution/index.d.ts +258 -0
  555. package/dist/resolution/index.d.ts.map +1 -0
  556. package/dist/resolution/index.js +1746 -0
  557. package/dist/resolution/index.js.map +1 -0
  558. package/dist/resolution/lru-cache.d.ts +24 -0
  559. package/dist/resolution/lru-cache.d.ts.map +1 -0
  560. package/dist/resolution/lru-cache.js +62 -0
  561. package/dist/resolution/lru-cache.js.map +1 -0
  562. package/dist/resolution/name-matcher.d.ts +112 -0
  563. package/dist/resolution/name-matcher.d.ts.map +1 -0
  564. package/dist/resolution/name-matcher.js +1830 -0
  565. package/dist/resolution/name-matcher.js.map +1 -0
  566. package/dist/resolution/path-aliases.d.ts +68 -0
  567. package/dist/resolution/path-aliases.d.ts.map +1 -0
  568. package/dist/resolution/path-aliases.js +238 -0
  569. package/dist/resolution/path-aliases.js.map +1 -0
  570. package/dist/resolution/strip-comments.d.ts +27 -0
  571. package/dist/resolution/strip-comments.d.ts.map +1 -0
  572. package/dist/resolution/strip-comments.js +492 -0
  573. package/dist/resolution/strip-comments.js.map +1 -0
  574. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  575. package/dist/resolution/swift-objc-bridge.d.ts.map +1 -0
  576. package/dist/resolution/swift-objc-bridge.js +256 -0
  577. package/dist/resolution/swift-objc-bridge.js.map +1 -0
  578. package/dist/resolution/types.d.ts +262 -0
  579. package/dist/resolution/types.d.ts.map +1 -0
  580. package/dist/resolution/types.js +8 -0
  581. package/dist/resolution/types.js.map +1 -0
  582. package/dist/resolution/workspace-packages.d.ts +58 -0
  583. package/dist/resolution/workspace-packages.d.ts.map +1 -0
  584. package/dist/resolution/workspace-packages.js +346 -0
  585. package/dist/resolution/workspace-packages.js.map +1 -0
  586. package/dist/search/identifier-segments.d.ts +60 -0
  587. package/dist/search/identifier-segments.d.ts.map +1 -0
  588. package/dist/search/identifier-segments.js +176 -0
  589. package/dist/search/identifier-segments.js.map +1 -0
  590. package/dist/search/query-parser.d.ts +57 -0
  591. package/dist/search/query-parser.d.ts.map +1 -0
  592. package/dist/search/query-parser.js +177 -0
  593. package/dist/search/query-parser.js.map +1 -0
  594. package/dist/search/query-utils.d.ts +87 -0
  595. package/dist/search/query-utils.d.ts.map +1 -0
  596. package/dist/search/query-utils.js +449 -0
  597. package/dist/search/query-utils.js.map +1 -0
  598. package/dist/sync/git-hooks.d.ts +45 -0
  599. package/dist/sync/git-hooks.d.ts.map +1 -0
  600. package/dist/sync/git-hooks.js +227 -0
  601. package/dist/sync/git-hooks.js.map +1 -0
  602. package/dist/sync/index.d.ts +19 -0
  603. package/dist/sync/index.d.ts.map +1 -0
  604. package/dist/sync/index.js +35 -0
  605. package/dist/sync/index.js.map +1 -0
  606. package/dist/sync/watch-policy.d.ts +48 -0
  607. package/dist/sync/watch-policy.d.ts.map +1 -0
  608. package/dist/sync/watch-policy.js +124 -0
  609. package/dist/sync/watch-policy.js.map +1 -0
  610. package/dist/sync/watcher.d.ts +355 -0
  611. package/dist/sync/watcher.d.ts.map +1 -0
  612. package/dist/sync/watcher.js +848 -0
  613. package/dist/sync/watcher.js.map +1 -0
  614. package/dist/sync/worktree.d.ts +63 -0
  615. package/dist/sync/worktree.d.ts.map +1 -0
  616. package/dist/sync/worktree.js +182 -0
  617. package/dist/sync/worktree.js.map +1 -0
  618. package/dist/telemetry/index.d.ts +143 -0
  619. package/dist/telemetry/index.d.ts.map +1 -0
  620. package/dist/telemetry/index.js +541 -0
  621. package/dist/telemetry/index.js.map +1 -0
  622. package/dist/types.d.ts +415 -0
  623. package/dist/types.d.ts.map +1 -0
  624. package/dist/types.js +91 -0
  625. package/dist/types.js.map +1 -0
  626. package/dist/ui/glyphs.d.ts +42 -0
  627. package/dist/ui/glyphs.d.ts.map +1 -0
  628. package/dist/ui/glyphs.js +78 -0
  629. package/dist/ui/glyphs.js.map +1 -0
  630. package/dist/ui/shimmer-progress.d.ts +11 -0
  631. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  632. package/dist/ui/shimmer-progress.js +90 -0
  633. package/dist/ui/shimmer-progress.js.map +1 -0
  634. package/dist/ui/shimmer-worker.d.ts +2 -0
  635. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  636. package/dist/ui/shimmer-worker.js +118 -0
  637. package/dist/ui/shimmer-worker.js.map +1 -0
  638. package/dist/ui/types.d.ts +17 -0
  639. package/dist/ui/types.d.ts.map +1 -0
  640. package/dist/ui/types.js +3 -0
  641. package/dist/ui/types.js.map +1 -0
  642. package/dist/upgrade/index.d.ts +164 -0
  643. package/dist/upgrade/index.d.ts.map +1 -0
  644. package/dist/upgrade/index.js +646 -0
  645. package/dist/upgrade/index.js.map +1 -0
  646. package/dist/upgrade/remove-binary.d.ts +87 -0
  647. package/dist/upgrade/remove-binary.d.ts.map +1 -0
  648. package/dist/upgrade/remove-binary.js +289 -0
  649. package/dist/upgrade/remove-binary.js.map +1 -0
  650. package/dist/upgrade/update-check.d.ts +92 -0
  651. package/dist/upgrade/update-check.d.ts.map +1 -0
  652. package/dist/upgrade/update-check.js +258 -0
  653. package/dist/upgrade/update-check.js.map +1 -0
  654. package/dist/utils.d.ts +224 -0
  655. package/dist/utils.d.ts.map +1 -0
  656. package/dist/utils.js +583 -0
  657. package/dist/utils.js.map +1 -0
  658. package/package.json +1 -1
@@ -0,0 +1,4477 @@
1
+ "use strict";
2
+ /**
3
+ * MCP Tool Definitions
4
+ *
5
+ * Defines the tools exposed by the CodeGraph MCP server.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.ToolHandler = exports.tools = exports.PathRefusalError = exports.NotIndexedError = void 0;
9
+ exports.normalizeQuerySpelling = normalizeQuerySpelling;
10
+ exports.getExploreBudget = getExploreBudget;
11
+ exports.getExploreOutputBudget = getExploreOutputBudget;
12
+ exports.formatStaleBanner = formatStaleBanner;
13
+ exports.formatStaleFooter = formatStaleFooter;
14
+ exports.formatDegradedBanner = formatDegradedBanner;
15
+ exports.getStaticTools = getStaticTools;
16
+ const directory_1 = require("../directory");
17
+ // Lazy-load the heavy CodeGraph chain off the MCP startup path — see the same
18
+ // helper in engine.ts. ToolHandler must load to answer tools/list (static
19
+ // schemas), but it must NOT drag in sqlite/query layers before the daemon binds;
20
+ // CodeGraph is pulled in only when a tool actually opens a project. require() is
21
+ // sync + cached (CommonJS build).
22
+ const loadCodeGraph = () => require('../index').default;
23
+ const worktree_1 = require("../sync/worktree");
24
+ const query_utils_1 = require("../search/query-utils");
25
+ const fs_1 = require("fs");
26
+ const utils_1 = require("../utils");
27
+ const generated_detection_1 = require("../extraction/generated-detection");
28
+ const dynamic_boundaries_1 = require("./dynamic-boundaries");
29
+ const update_check_1 = require("../upgrade/update-check");
30
+ /**
31
+ * An expected, recoverable "codegraph can't serve this" condition — most
32
+ * importantly a project with no index. The dispatch catch converts these to
33
+ * SUCCESS-shaped responses (guidance text, NO isError): an `isError: true`
34
+ * early in a session teaches the agent the toolset is broken and it stops
35
+ * calling codegraph entirely (observed repeatedly), which is exactly wrong
36
+ * for conditions the agent can simply work around (use built-in tools for
37
+ * that codebase / pass projectPath). isError is reserved for "stop trying"
38
+ * cases: security refusals ({@link PathRefusalError}) and genuine
39
+ * malfunctions.
40
+ */
41
+ class NotIndexedError extends Error {
42
+ }
43
+ exports.NotIndexedError = NotIndexedError;
44
+ /**
45
+ * A security refusal (sensitive system path). Stays `isError: true` WITHOUT
46
+ * retry guidance — abandoning this path is the desired agent reaction.
47
+ */
48
+ class PathRefusalError extends Error {
49
+ }
50
+ exports.PathRefusalError = PathRefusalError;
51
+ const path_1 = require("path");
52
+ /** Maximum output length to prevent context bloat (characters) */
53
+ const MAX_OUTPUT_LENGTH = 15000;
54
+ /**
55
+ * Maximum length for free-form string inputs (query, task, symbol).
56
+ * Bounds memory and CPU when a buggy or hostile MCP client sends a
57
+ * huge payload — without this an attacker could ship a 100MB string
58
+ * and force a full FTS5 scan / OOM the server. 10 000 characters is
59
+ * far beyond any realistic legitimate query.
60
+ */
61
+ const MAX_INPUT_LENGTH = 10_000;
62
+ /**
63
+ * Maximum length for path-like string inputs (projectPath, path
64
+ * filter, glob pattern). Paths beyond a few thousand chars are
65
+ * never legitimate and signal abuse or a bug upstream.
66
+ */
67
+ const MAX_PATH_LENGTH = 4_096;
68
+ /**
69
+ * Rust path roots that have no file-system equivalent — `crate` is the
70
+ * current crate, `super` is the parent module, `self` is the current
71
+ * module. Used by `matchesSymbol` to strip these before file-path
72
+ * matching so `crate::configurator::stage_apply::run` resolves the
73
+ * same as `configurator::stage_apply::run`.
74
+ */
75
+ const RUST_PATH_PREFIXES = new Set(['crate', 'super', 'self']);
76
+ /**
77
+ * Node kinds that contain other symbols. For these, `codegraph_node` with
78
+ * `includeCode=true` returns a structural outline (member names + signatures
79
+ * + line numbers) instead of the full body, which for a large class is a
80
+ * multi-thousand-character wall of source that bloats the agent's context.
81
+ */
82
+ const CONTAINER_NODE_KINDS = new Set([
83
+ 'class', 'struct', 'interface', 'trait', 'protocol', 'enum', 'namespace', 'module',
84
+ ]);
85
+ /** Last `::` / `.` / `/`-separated segment of a qualified symbol. */
86
+ function lastQualifierPart(symbol) {
87
+ const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
88
+ return parts[parts.length - 1] ?? symbol;
89
+ }
90
+ /**
91
+ * Normalize Erlang-native symbol spellings in an explore query into the shapes
92
+ * the rest of the pipeline already understands. Agents working Erlang code
93
+ * name symbols the way the language spells them — `mod:fn/3`, `init/2` — and
94
+ * those tokens previously died in both consumers: the flow-builder's token
95
+ * filter rejects `:` and `/arity` outright, and the search-side field parser
96
+ * eats `mod:fn` as an unknown `field:value`. Measured on cowboy: the agent
97
+ * named `cowboy_stream_h:request_process/3` in two queries, got no body back
98
+ * either time, and fell back to Read.
99
+ *
100
+ * - `fn/3` → `fn` (arity tail after an identifier; a path segment like
101
+ * `src/2fa` doesn't match because the tail must be all digits)
102
+ * - `mod:fn` → `mod.fn` (exactly one colon between identifiers, so it rides
103
+ * the existing Class.method qualified handling; `::`, URLs, drive letters,
104
+ * and times don't match, and the query language's own field prefixes —
105
+ * kind:/lang:/language:/path:/name: — are left alone)
106
+ *
107
+ * Safe cross-language: Lua's `t:m` spelling maps to the same `t.m` its
108
+ * qualified names use, and no other supported spelling contains a bare
109
+ * single-colon identifier pair.
110
+ */
111
+ function normalizeQuerySpelling(query) {
112
+ return query
113
+ .replace(/\b([A-Za-z_][\w@]*)\/(\d{1,3})(?=$|[\s,()[\]/])/g, '$1')
114
+ .replace(/(^|[\s,()[\]])(?!(?:kind|lang|language|path|name):)([a-z_][\w@]*):([A-Za-z_][\w@]*)(?=$|[\s,()[\]])/g, '$1$2.$3');
115
+ }
116
+ /**
117
+ * Calculate the recommended number of codegraph_explore calls based on project size.
118
+ * Larger codebases need more exploration calls to cover their surface area,
119
+ * but smaller ones should use fewer to avoid unnecessary overhead.
120
+ */
121
+ function getExploreBudget(fileCount) {
122
+ if (fileCount < 500)
123
+ return 1;
124
+ if (fileCount < 5000)
125
+ return 2;
126
+ if (fileCount < 15000)
127
+ return 3;
128
+ if (fileCount < 25000)
129
+ return 4;
130
+ return 5;
131
+ }
132
+ function getExploreOutputBudget(fileCount) {
133
+ // Tiered budget, scaled to project size. The budget is a CEILING (relevance
134
+ // still gates WHAT is included), and it MUST stay under the agent's INLINE
135
+ // tool-result cap (~25K chars). Above that, the host externalizes the result
136
+ // to a file the agent then Reads back — re-introducing a read AND the
137
+ // cache-write cost — which is exactly what a 35K vscode explore did in the
138
+ // n=4 README A/B. So even large repos cap at ~24K: the answer is the handful
139
+ // of ~100-line flow windows the agent would have grep-located and read (it
140
+ // natively reads ~6–9 files, median 100-line ranges), NOT a sprawl of 12
141
+ // files. Concentration onto the flow emerges from this cap + the named-file-
142
+ // first sort dropping peripheral files. Invariant: a larger tier must never
143
+ // get a smaller `maxCharsPerFile` than a smaller tier.
144
+ if (fileCount < 150) {
145
+ return {
146
+ // ITER3: revert iter2's aggressive body shrink (forced Read fallback —
147
+ // the per-file 2.5K cap pushed the agent to Read instead of node).
148
+ // Back to the iter1 shape (13K/4/3.8K) but keep the test-file
149
+ // hard-exclude. The cost lever for this tier lives in steering the
150
+ // agent to stop after 1-2 calls, not in this budget.
151
+ maxOutputChars: 13000,
152
+ defaultMaxFiles: 4,
153
+ maxCharsPerFile: 3800,
154
+ gapThreshold: 7,
155
+ maxSymbolsInFileHeader: 5,
156
+ maxEdgesPerRelationshipKind: 4,
157
+ includeRelationships: false,
158
+ includeAdditionalFiles: false,
159
+ includeCompletenessSignal: false,
160
+ includeBudgetNote: false,
161
+ excludeLowValueFiles: true,
162
+ };
163
+ }
164
+ if (fileCount < 500) {
165
+ return {
166
+ // ITER3: same revert/keep-filter pattern as <150.
167
+ maxOutputChars: 18000,
168
+ defaultMaxFiles: 5,
169
+ maxCharsPerFile: 3800,
170
+ gapThreshold: 8,
171
+ maxSymbolsInFileHeader: 6,
172
+ maxEdgesPerRelationshipKind: 6,
173
+ includeRelationships: false,
174
+ includeAdditionalFiles: false,
175
+ includeCompletenessSignal: false,
176
+ includeBudgetNote: false,
177
+ excludeLowValueFiles: true,
178
+ };
179
+ }
180
+ if (fileCount < 5000) {
181
+ return {
182
+ // ~150-line per-file window (the native read unit) × ~6 files, capped at
183
+ // the ~24K inline ceiling so the response is never externalized. Per-file
184
+ // stays ≥ the <500 tier (3800) — monotonic.
185
+ maxOutputChars: 24000,
186
+ defaultMaxFiles: 8,
187
+ maxCharsPerFile: 6500,
188
+ gapThreshold: 12,
189
+ maxSymbolsInFileHeader: 10,
190
+ maxEdgesPerRelationshipKind: 10,
191
+ includeRelationships: true,
192
+ includeAdditionalFiles: true,
193
+ includeCompletenessSignal: true,
194
+ includeBudgetNote: true,
195
+ excludeLowValueFiles: false,
196
+ };
197
+ }
198
+ // Large + very-large repos: SAME ~24K inline ceiling (a bigger response just
199
+ // externalizes — see vscode). More files indexed → more CALLS via
200
+ // getExploreBudget, not a bigger single response. Per-file 7000 (≥ smaller
201
+ // tiers) gives the central file a ~180-line orientation window.
202
+ if (fileCount < 15000) {
203
+ return {
204
+ maxOutputChars: 24000,
205
+ defaultMaxFiles: 8,
206
+ maxCharsPerFile: 7000,
207
+ gapThreshold: 15,
208
+ maxSymbolsInFileHeader: 15,
209
+ maxEdgesPerRelationshipKind: 15,
210
+ includeRelationships: true,
211
+ includeAdditionalFiles: true,
212
+ includeCompletenessSignal: true,
213
+ includeBudgetNote: true,
214
+ excludeLowValueFiles: false,
215
+ };
216
+ }
217
+ return {
218
+ maxOutputChars: 24000,
219
+ defaultMaxFiles: 8,
220
+ maxCharsPerFile: 7000,
221
+ gapThreshold: 15,
222
+ maxSymbolsInFileHeader: 15,
223
+ maxEdgesPerRelationshipKind: 15,
224
+ includeRelationships: true,
225
+ includeAdditionalFiles: true,
226
+ includeCompletenessSignal: true,
227
+ includeBudgetNote: true,
228
+ excludeLowValueFiles: false,
229
+ };
230
+ }
231
+ /**
232
+ * Whether `codegraph_explore` should prefix source lines with their line
233
+ * numbers (cat -n style: `<num>\t<code>`).
234
+ *
235
+ * Line numbers let the agent cite `file:line` straight from the explore
236
+ * payload instead of re-Reading the file just to find a line number — the
237
+ * dominant residual cost on precise-tracing questions (#185 follow-up).
238
+ *
239
+ * Defaults ON. Set `CODEGRAPH_EXPLORE_LINENUMS=0` to disable (used by the
240
+ * A/B harness to measure the payload-cost vs. read-savings tradeoff).
241
+ */
242
+ function exploreLineNumbersEnabled() {
243
+ return process.env.CODEGRAPH_EXPLORE_LINENUMS !== '0';
244
+ }
245
+ /**
246
+ * Adaptive explore sizing (default ON). `codegraph_explore` skeletonizes OFF-SPINE
247
+ * polymorphic-sibling files — a file whose class is one of ≥3 interchangeable
248
+ * implementations of a shared interface (e.g. OkHttp's `: Interceptor` classes) —
249
+ * to class + member signatures (bodies elided), keeping the on-spine exemplar full.
250
+ * This sizes the response to the answer instead of the budget cap on sibling-heavy
251
+ * flows (OkHttp interceptor-chain explore 28.5k→16.6k, ~28% cheaper than native
252
+ * search, reads flat). It is PROVABLY INERT elsewhere: distinct pipeline steps (no
253
+ * ≥3-implementer supertype, e.g. Excalidraw's `renderStaticScene`) and on-spine
254
+ * files keep full source — output is byte-identical to shipped on excalidraw /
255
+ * tokio / django / vscode / gin. Set `CODEGRAPH_ADAPTIVE_EXPLORE=0` to disable.
256
+ */
257
+ function adaptiveExploreEnabled() {
258
+ return process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== '0' && process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== 'false';
259
+ }
260
+ /**
261
+ * How long the FIRST tool call waits on the post-open catch-up reconcile before
262
+ * giving up and serving anyway (issue #905). On a normal repo the reconcile
263
+ * finishes in well under this, so the gate is fully honored and nothing changes.
264
+ * On a very large repo (~100k files) the reconcile takes minutes — blocking the
265
+ * first call on all of it presents as a multi-minute hang — so we wait briefly
266
+ * for a clean answer, then serve and let the reconcile finish in the background
267
+ * (it yields to the event loop, so a concurrent read still runs).
268
+ *
269
+ * `CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS` overrides the default; `0` restores the
270
+ * old unbounded-wait behavior (always block until the reconcile completes).
271
+ */
272
+ const DEFAULT_CATCHUP_GATE_TIMEOUT_MS = 3000;
273
+ function resolveCatchUpGateTimeoutMs() {
274
+ const raw = process.env.CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS;
275
+ if (raw === undefined || raw === '')
276
+ return DEFAULT_CATCHUP_GATE_TIMEOUT_MS;
277
+ const n = Number(raw);
278
+ if (!Number.isFinite(n) || n < 0)
279
+ return DEFAULT_CATCHUP_GATE_TIMEOUT_MS;
280
+ return Math.floor(n);
281
+ }
282
+ /**
283
+ * Prefix each line of a source slice with its 1-based line number, matching
284
+ * the Read tool's `cat -n` convention (number + tab) so the agent treats it
285
+ * the same way it treats Read output.
286
+ *
287
+ * @param slice contiguous source text (already extracted from the file)
288
+ * @param firstLineNumber the 1-based line number of the slice's first line
289
+ */
290
+ function numberSourceLines(slice, firstLineNumber) {
291
+ const out = [];
292
+ const split = slice.split('\n');
293
+ for (let i = 0; i < split.length; i++) {
294
+ out.push(`${firstLineNumber + i}\t${split[i]}`);
295
+ }
296
+ return out.join('\n');
297
+ }
298
+ /**
299
+ * Unique line-prefix for a per-file source section in codegraph_explore output.
300
+ * Issue #778: tool results dropped ATX headings (`####`, `##`, `###`) for bold
301
+ * labels so Markdown-rendering MCP clients (e.g. the Claude Code VSCode
302
+ * extension) stop blowing every header up to H1–H4. The path is bold + a code
303
+ * span so it still reads as a header, and the leading ``**` `` stays a UNIQUE,
304
+ * greppable marker — no other explore line begins with it — that the explore
305
+ * truncation boundary (`handleExplore`) keys off to cut on whole file sections.
306
+ */
307
+ const FILE_SECTION_PREFIX = '**`';
308
+ // Placeholder for codegraph_explore's "Found N symbols across M files." line.
309
+ // The honest N/M can only be known after the final truncation drops trailing
310
+ // sections (#1046), so the header is emitted as this sentinel and substituted
311
+ // at the very end. This bracketed token never occurs in rendered source or a
312
+ // file path, so the final string-replace can't collide.
313
+ const SUMMARY_SENTINEL = '[[codegraph-explore-summary]]';
314
+ function fileSectionHeader(filePath, suffix) {
315
+ return suffix
316
+ ? `${FILE_SECTION_PREFIX}${filePath}\`** — ${suffix}`
317
+ : `${FILE_SECTION_PREFIX}${filePath}\`**`;
318
+ }
319
+ /**
320
+ * Per-file staleness banner emitted at the top of a tool response when the
321
+ * file watcher has pending events for files referenced by the response.
322
+ * The agent uses this to fall back to Read for those specific files
323
+ * without waiting for the debounced sync (issue #403).
324
+ */
325
+ function formatStaleBanner(stale) {
326
+ const now = Date.now();
327
+ const lines = stale.map((p) => {
328
+ const ageMs = Math.max(0, now - p.lastSeenMs);
329
+ const label = p.indexing ? 'indexing in progress' : 'pending sync';
330
+ return ` - ${p.path} (edited ${ageMs}ms ago, ${label})`;
331
+ });
332
+ return ('⚠️ Some files referenced below were edited since the last index sync — ' +
333
+ 'their codegraph entries may be stale:\n' +
334
+ lines.join('\n') +
335
+ '\nFor accurate content of those specific files, Read them directly. ' +
336
+ 'The rest of this response is fresh.');
337
+ }
338
+ /**
339
+ * Compact footer listing pending files that are NOT referenced in this
340
+ * response. Gives the agent a complete project-wide freshness picture
341
+ * without bloating the main banner.
342
+ */
343
+ function formatStaleFooter(stale) {
344
+ const MAX = 5;
345
+ const now = Date.now();
346
+ const shown = stale.slice(0, MAX);
347
+ const lines = shown.map((p) => {
348
+ const ageMs = Math.max(0, now - p.lastSeenMs);
349
+ return ` - ${p.path} (edited ${ageMs}ms ago)`;
350
+ });
351
+ const more = stale.length > MAX ? `\n - …and ${stale.length - MAX} more` : '';
352
+ return (`(Note: ${stale.length} file(s) elsewhere in this project are pending index ` +
353
+ `sync but were not referenced above:\n${lines.join('\n')}${more})`);
354
+ }
355
+ /**
356
+ * Whole-index degradation banner (issue #876). Emitted at the top of a read
357
+ * tool response when live watching has permanently stopped — at which point
358
+ * `getPendingFiles()` is empty, so the per-file banner above can't fire even
359
+ * though the index is now FROZEN and silently drifting stale. Leads with the
360
+ * agent-actionable instruction (Read directly) and carries the reason, which
361
+ * already names the operator remedy (`codegraph sync` / git hooks).
362
+ */
363
+ function formatDegradedBanner(reason) {
364
+ return ('⚠️ CodeGraph auto-sync is DISABLED — live file watching stopped, so the index is ' +
365
+ 'frozen and any file edited since then is stale here. Read files directly to confirm ' +
366
+ 'current content before relying on it.' +
367
+ (reason ? `\n Reason: ${reason}` : ''));
368
+ }
369
+ /**
370
+ * Common projectPath property for cross-project queries
371
+ */
372
+ const projectPathProperty = {
373
+ type: 'string',
374
+ description: 'Absolute path to the project to query (or any directory inside it) — codegraph uses the nearest .codegraph/ index at or above that path. Omit to use this session\'s default project. Pass it to query a second codebase, or when the server root has no index of its own (e.g. a monorepo where only sub-projects are indexed, so there is no default project).',
375
+ };
376
+ /**
377
+ * EVERY codegraph tool is query-only: it reads the pre-built index and never
378
+ * mutates the workspace (indexing is the user's explicit CLI call, never the
379
+ * agent's). Advertising this read-only contract lets clients that gate on it run
380
+ * the tools where a possibly-mutating tool would be blocked — most concretely,
381
+ * Cursor's Ask mode, which rejects any MCP tool lacking `readOnlyHint: true`
382
+ * (issue #1018). `idempotentHint`: a repeated query has no additional effect.
383
+ * `openWorldHint: false`: the domain is the closed local index, not an open
384
+ * external world. Shared so the contract is declared once; a hypothetical
385
+ * mutating tool would simply not reference it.
386
+ */
387
+ const READ_ONLY_ANNOTATIONS = {
388
+ readOnlyHint: true,
389
+ destructiveHint: false,
390
+ idempotentHint: true,
391
+ openWorldHint: false,
392
+ };
393
+ /**
394
+ * All CodeGraph MCP tools
395
+ *
396
+ * Designed for minimal context usage - use codegraph_explore as the primary tool
397
+ * (one call usually answers the whole question), and only use other tools for
398
+ * targeted follow-up queries.
399
+ *
400
+ * All tools support cross-project queries via the optional `projectPath` parameter.
401
+ */
402
+ exports.tools = [
403
+ {
404
+ name: 'codegraph_search',
405
+ description: 'Quick symbol search by name. Returns locations only (no code). Use codegraph_explore instead to get the actual source / understand an area in one call.',
406
+ inputSchema: {
407
+ type: 'object',
408
+ properties: {
409
+ query: {
410
+ type: 'string',
411
+ description: 'Symbol name or partial name (e.g., "auth", "signIn", "UserService")',
412
+ },
413
+ kind: {
414
+ type: 'string',
415
+ description: 'Filter by node kind',
416
+ enum: ['function', 'method', 'class', 'interface', 'type', 'variable', 'route', 'component'],
417
+ },
418
+ limit: {
419
+ type: 'number',
420
+ description: 'Maximum results (default: 10)',
421
+ default: 10,
422
+ },
423
+ projectPath: projectPathProperty,
424
+ },
425
+ required: ['query'],
426
+ },
427
+ annotations: READ_ONLY_ANNOTATIONS,
428
+ },
429
+ {
430
+ name: 'codegraph_callers',
431
+ description: 'List functions that call <symbol>. For the full flow, use codegraph_explore.',
432
+ inputSchema: {
433
+ type: 'object',
434
+ properties: {
435
+ symbol: {
436
+ type: 'string',
437
+ description: 'Name of the function, method, or class to find callers for',
438
+ },
439
+ file: {
440
+ type: 'string',
441
+ description: 'Narrow to the definition in this file (path or suffix) when several same-named symbols exist (e.g. one UserService per app in a monorepo)',
442
+ },
443
+ limit: {
444
+ type: 'number',
445
+ description: 'Maximum number of callers to return (default: 20)',
446
+ default: 20,
447
+ },
448
+ projectPath: projectPathProperty,
449
+ },
450
+ required: ['symbol'],
451
+ },
452
+ annotations: READ_ONLY_ANNOTATIONS,
453
+ },
454
+ {
455
+ name: 'codegraph_callees',
456
+ description: 'List functions that <symbol> calls. For the full flow, use codegraph_explore.',
457
+ inputSchema: {
458
+ type: 'object',
459
+ properties: {
460
+ symbol: {
461
+ type: 'string',
462
+ description: 'Name of the function, method, or class to find callees for',
463
+ },
464
+ file: {
465
+ type: 'string',
466
+ description: 'Narrow to the definition in this file (path or suffix) when several same-named symbols exist',
467
+ },
468
+ limit: {
469
+ type: 'number',
470
+ description: 'Maximum number of callees to return (default: 20)',
471
+ default: 20,
472
+ },
473
+ projectPath: projectPathProperty,
474
+ },
475
+ required: ['symbol'],
476
+ },
477
+ annotations: READ_ONLY_ANNOTATIONS,
478
+ },
479
+ {
480
+ name: 'codegraph_impact',
481
+ description: 'List symbols affected by changing <symbol>. Use before a refactor.',
482
+ inputSchema: {
483
+ type: 'object',
484
+ properties: {
485
+ symbol: {
486
+ type: 'string',
487
+ description: 'Name of the symbol to analyze impact for',
488
+ },
489
+ file: {
490
+ type: 'string',
491
+ description: 'Narrow to the definition in this file (path or suffix) when several same-named symbols exist',
492
+ },
493
+ depth: {
494
+ type: 'number',
495
+ description: 'How many levels of dependencies to traverse (default: 2)',
496
+ default: 2,
497
+ },
498
+ projectPath: projectPathProperty,
499
+ },
500
+ required: ['symbol'],
501
+ },
502
+ annotations: READ_ONLY_ANNOTATIONS,
503
+ },
504
+ {
505
+ name: 'codegraph_node',
506
+ description: 'Two modes. (1) READ A FILE — use INSTEAD of the Read tool: pass `file` (a path or basename) with no `symbol` and it returns that file\'s current on-disk source with line numbers, exactly the shape Read gives you (`<n>\\t<line>`, safe to Edit from), narrowable with `offset`/`limit` just like Read — PLUS a one-line note of which files depend on it. Same bytes as Read, faster (served from the index), with the blast radius attached. Use it whenever you would Read a source file. (2) ONE SYMBOL you can name — its location, signature, verbatim source (includeCode=true) and caller/callee trail in one call, so before changing it you see what calls it and what your edit would break. For an AMBIGUOUS name it returns EVERY matching definition\'s body in one call (so you never Read a file to find the right overload); pass `file`/`line` to pin one. Use codegraph_explore for several related symbols or the full flow.',
507
+ inputSchema: {
508
+ type: 'object',
509
+ properties: {
510
+ symbol: {
511
+ type: 'string',
512
+ description: 'Name of the symbol to read (symbol mode). Omit it and pass `file` alone to read a whole file like Read.',
513
+ },
514
+ includeCode: {
515
+ type: 'boolean',
516
+ description: 'Symbol mode: include the symbol\'s full body (default: false). Ignored in file mode, which always returns source unless `symbolsOnly` is set.',
517
+ default: false,
518
+ },
519
+ file: {
520
+ type: 'string',
521
+ description: 'A file path or basename (e.g. "harness.rs", "src/auth/session.ts"). Pass it ALONE (no symbol) to READ the file like the Read tool — its full source with line numbers + which files depend on it. Or pass it WITH a symbol to disambiguate an overloaded name to the definition in this file.',
522
+ },
523
+ offset: {
524
+ type: 'number',
525
+ description: 'File mode: 1-based line to start reading from, exactly like Read\'s offset. Defaults to the start of the file.',
526
+ },
527
+ limit: {
528
+ type: 'number',
529
+ description: 'File mode: maximum number of lines to return, exactly like Read\'s limit. Defaults to the whole file (capped at 2000 lines, like Read).',
530
+ },
531
+ symbolsOnly: {
532
+ type: 'boolean',
533
+ description: 'File mode: return just the file\'s symbol map + dependents (a cheap structural overview) instead of its source.',
534
+ default: false,
535
+ },
536
+ line: {
537
+ type: 'number',
538
+ description: 'Symbol mode only: disambiguate to the definition at/around this line (use with the file:line a trail showed you).',
539
+ },
540
+ projectPath: projectPathProperty,
541
+ },
542
+ required: [],
543
+ },
544
+ annotations: READ_ONLY_ANNOTATIONS,
545
+ },
546
+ {
547
+ name: 'codegraph_explore',
548
+ description: 'PRIMARY TOOL — call FIRST for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or the symbols you are about to change. Returns the verbatim source of the relevant symbols grouped by file in ONE capped call (Read-equivalent — treat the shown source as already Read; do NOT re-open those files), plus the call path among them. Query can be a natural-language question OR a bag of symbol/file names. Usually the ONLY call you need — more accurate context, in far fewer tokens and round-trips than a search/Read/Grep loop.',
549
+ inputSchema: {
550
+ type: 'object',
551
+ properties: {
552
+ query: {
553
+ type: 'string',
554
+ description: 'Symbol names, file names, or short code terms to explore (e.g., "AuthService loginUser session-manager", "GraphTraverser BFS impact traversal.ts"). For a flow question, name the symbols spanning the flow (e.g. "mutateElement renderScene"). A natural-language question works too — no prior codegraph_search needed.',
555
+ },
556
+ maxFiles: {
557
+ type: 'number',
558
+ description: 'Maximum number of files to include source code from (default: 12)',
559
+ default: 12,
560
+ },
561
+ projectPath: projectPathProperty,
562
+ },
563
+ required: ['query'],
564
+ },
565
+ annotations: READ_ONLY_ANNOTATIONS,
566
+ },
567
+ {
568
+ name: 'codegraph_status',
569
+ description: 'Index health check (files / nodes / edges). Skip unless debugging.',
570
+ inputSchema: {
571
+ type: 'object',
572
+ properties: {
573
+ projectPath: projectPathProperty,
574
+ },
575
+ },
576
+ annotations: READ_ONLY_ANNOTATIONS,
577
+ },
578
+ {
579
+ name: 'codegraph_files',
580
+ description: 'Indexed file tree with language + symbol counts. Faster than Glob for project layout.',
581
+ inputSchema: {
582
+ type: 'object',
583
+ properties: {
584
+ path: {
585
+ type: 'string',
586
+ description: 'Filter to files under this directory path (e.g., "src/components"). Returns all files if not specified.',
587
+ },
588
+ pattern: {
589
+ type: 'string',
590
+ description: 'Filter files matching this glob pattern (e.g., "*.tsx", "**/*.test.ts")',
591
+ },
592
+ format: {
593
+ type: 'string',
594
+ description: 'Output format: "tree" (hierarchical, default), "flat" (simple list), "grouped" (by language)',
595
+ enum: ['tree', 'flat', 'grouped'],
596
+ default: 'tree',
597
+ },
598
+ includeMetadata: {
599
+ type: 'boolean',
600
+ description: 'Include file metadata like language and symbol count (default: true)',
601
+ default: true,
602
+ },
603
+ maxDepth: {
604
+ type: 'number',
605
+ description: 'Maximum directory depth to show (default: unlimited)',
606
+ },
607
+ projectPath: projectPathProperty,
608
+ },
609
+ },
610
+ annotations: READ_ONLY_ANNOTATIONS,
611
+ },
612
+ ];
613
+ /**
614
+ * Return `defs` with `projectPath` marked `required` in each tool's inputSchema.
615
+ *
616
+ * Used for the NO-DEFAULT-PROJECT tool surface (issue #993): when the MCP server
617
+ * has no default project to fall back to — a gateway server started outside any
618
+ * repo, or a monorepo root whose `.codegraph/` indexes live only in sub-projects
619
+ * — every call MUST carry an explicit `projectPath`, so the schema should say so.
620
+ * A `required` field is a HIGH-salience channel (MCP clients surface and often
621
+ * validate it), unlike the instructions text the reporter found too weak to stop
622
+ * the agent omitting the param. When a default project IS open, callers leave
623
+ * projectPath optional and never call this.
624
+ *
625
+ * Pure: clones each tool's schema rather than mutating the shared module-level
626
+ * `tools` array (reused by every session and the static surface). A tool that
627
+ * doesn't expose projectPath, or already requires it, is returned untouched;
628
+ * explore's `['query']` becomes `['query', 'projectPath']`, and a tool with no
629
+ * `required` list (status/files) gains `['projectPath']`.
630
+ */
631
+ function withRequiredProjectPath(defs) {
632
+ return defs.map((tool) => {
633
+ if (!tool.inputSchema.properties.projectPath)
634
+ return tool;
635
+ const required = tool.inputSchema.required ?? [];
636
+ if (required.includes('projectPath'))
637
+ return tool;
638
+ return {
639
+ ...tool,
640
+ inputSchema: { ...tool.inputSchema, required: [...required, 'projectPath'] },
641
+ };
642
+ });
643
+ }
644
+ /**
645
+ * Allowlist-filtered tool definitions WITHOUT an engine — the static surface the
646
+ * proxy answers `tools/list` with before any project is open. Mirrors
647
+ * `ToolHandler.getTools()` in the no-CodeGraph case (the dynamic per-repo budget
648
+ * note in a description only adds once `cg` is loaded; the schemas are static).
649
+ */
650
+ function getStaticTools() {
651
+ const raw = process.env.CODEGRAPH_MCP_TOOLS;
652
+ if (!raw || !raw.trim()) {
653
+ return exports.tools.filter(t => DEFAULT_MCP_TOOLS.has(t.name.replace(/^codegraph_/, '')));
654
+ }
655
+ const allow = new Set(raw.split(',').map(s => s.trim().replace(/^codegraph_/, '')).filter(Boolean));
656
+ return allow.size ? exports.tools.filter(t => allow.has(t.name.replace(/^codegraph_/, ''))) : exports.tools;
657
+ }
658
+ /**
659
+ * The MCP tools served by DEFAULT (short names). Pared to ONLY `codegraph_explore`
660
+ * — the single tool that reliably earns its place: one capped call returns the
661
+ * verbatim source of the relevant symbols grouped by file. Every other tool is a
662
+ * narrower slice of what explore already does, and presence itself steers
663
+ * mis-picks, so they are no longer LISTED to agents.
664
+ *
665
+ * The other defined tools (`node`, `search`, `callers`, plus callees/impact/files/
666
+ * status) remain fully functional — handlers stay, the library API and CLI are
667
+ * untouched, and `CODEGRAPH_MCP_TOOLS=explore,node,...` re-enables any of them.
668
+ */
669
+ const DEFAULT_MCP_TOOLS = new Set(['explore']);
670
+ /**
671
+ * Tool handler that executes tools against a CodeGraph instance
672
+ *
673
+ * Supports cross-project queries via the projectPath parameter.
674
+ * Other projects are opened on-demand and cached for performance.
675
+ */
676
+ class ToolHandler {
677
+ cg;
678
+ // Cache of opened CodeGraph instances for cross-project queries
679
+ projectCache = new Map();
680
+ // The directory the server last searched for a default project. Surfaced in
681
+ // the "not initialized" error so users can see why detection missed.
682
+ defaultProjectHint = null;
683
+ // Per-start-path cache of the git worktree/index mismatch (issue #155). The
684
+ // mismatch is a fixed property of (where the request came from → which
685
+ // .codegraph/ it resolves to), so the up-to-two `git rev-parse` spawns run
686
+ // once and every later tool call reuses the result — never shelling out to
687
+ // git on the hot path. `undefined` = not computed yet; `null` = no mismatch.
688
+ worktreeMismatchCache = new Map();
689
+ // Gate that the MCP engine pokes after `cg.open()` so the first tool call
690
+ // blocks on the post-open filesystem reconcile (catch-up sync). Without
691
+ // this, a tool call that races past `catchUpSync()` serves rows for files
692
+ // that were deleted (or edited) while no MCP server was running — and the
693
+ // per-file staleness banner can't help, because `getPendingFiles()` is
694
+ // populated by the watcher, not by catch-up. The wait is time-boxed
695
+ // (see {@link resolveCatchUpGateTimeoutMs}) so a minutes-long reconcile on a
696
+ // huge repo can't hang the first call (#905); cleared on first await so
697
+ // subsequent calls don't pay any cost.
698
+ catchUpGate = null;
699
+ // Optional worker-thread pool for off-loop read-tool dispatch (daemon mode).
700
+ // When set + healthy, the heavy read tools run on a worker so the daemon's
701
+ // main loop stays free for the MCP transport under concurrent load. Null in
702
+ // direct/in-process mode (one client, no concurrency to parallelize).
703
+ queryPool = null;
704
+ constructor(cg) {
705
+ this.cg = cg;
706
+ }
707
+ /**
708
+ * Engine-only: attach (or detach with null) the worker-thread query pool. The
709
+ * shared daemon sets this once its default project is open; the workers each
710
+ * hold their own WAL read connection and run {@link executeReadTool}. A
711
+ * worker's own ToolHandler never has a pool, so there is no nested off-loading.
712
+ */
713
+ setQueryPool(pool) {
714
+ this.queryPool = pool;
715
+ }
716
+ /**
717
+ * Update the default CodeGraph instance (e.g. after lazy initialization)
718
+ */
719
+ setDefaultCodeGraph(cg) {
720
+ this.cg = cg;
721
+ }
722
+ /**
723
+ * Engine-only: register the catch-up sync promise so the next `execute()`
724
+ * call awaits it before serving. The handler swallows rejections (the
725
+ * engine logs them) so a sync failure never propagates as a tool error;
726
+ * we still want to serve a best-effort result over the same potentially-
727
+ * stale data, which is what would have happened without the gate.
728
+ */
729
+ setCatchUpGate(p) {
730
+ this.catchUpGate = p;
731
+ }
732
+ /**
733
+ * Await the catch-up gate, but no longer than the configured timeout (#905).
734
+ * If the reconcile settles first, we got the fully-reconciled answer. If the
735
+ * timeout wins, we serve the call now and let the reconcile finish in the
736
+ * background — it yields to the event loop (see SYNC_RECONCILE_YIELD_INTERVAL),
737
+ * so a concurrent read still runs against the same connection. Never throws:
738
+ * a failed reconcile is logged by the engine, and we serve best-effort over
739
+ * the same potentially-stale data the un-gated path would have.
740
+ */
741
+ async awaitCatchUpGate(gate) {
742
+ const timeoutMs = resolveCatchUpGateTimeoutMs();
743
+ if (timeoutMs <= 0) {
744
+ // 0 = opt back into the original unbounded wait.
745
+ try {
746
+ await gate;
747
+ }
748
+ catch { /* engine already logged */ }
749
+ return;
750
+ }
751
+ let timer;
752
+ const timedOut = new Promise((resolve) => {
753
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
754
+ timer.unref?.();
755
+ });
756
+ try {
757
+ const outcome = await Promise.race([
758
+ gate.then(() => 'done', () => 'done'),
759
+ timedOut,
760
+ ]);
761
+ if (outcome === 'timeout') {
762
+ process.stderr.write(`[CodeGraph MCP] Catch-up reconcile still running after ${timeoutMs}ms; serving this tool call now and finishing the reconcile in the background (#905). ` +
763
+ `Set CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS=0 to always wait for it.\n`);
764
+ }
765
+ }
766
+ finally {
767
+ if (timer)
768
+ clearTimeout(timer);
769
+ }
770
+ }
771
+ /**
772
+ * Record the directory the server tried to resolve the default project from.
773
+ * Used only to make the "no default project" error actionable.
774
+ */
775
+ setDefaultProjectHint(searchedPath) {
776
+ this.defaultProjectHint = searchedPath;
777
+ }
778
+ /**
779
+ * Whether a default CodeGraph instance is available
780
+ */
781
+ hasDefaultCodeGraph() {
782
+ return this.cg !== null;
783
+ }
784
+ /**
785
+ * Optional allowlist of exposed tools, parsed from the CODEGRAPH_MCP_TOOLS
786
+ * env var (comma-separated short names, e.g. "trace,search,node,context").
787
+ * Unset/empty → every tool is exposed. Lets an operator (or an A/B harness)
788
+ * trim the tool surface without rebuilding the client config; the ablated
789
+ * tool is then truly absent from ListTools rather than merely denied on call.
790
+ * Matching is on the short form, so "node" and "codegraph_node" both work.
791
+ */
792
+ toolAllowlist() {
793
+ const raw = process.env.CODEGRAPH_MCP_TOOLS;
794
+ if (!raw || !raw.trim())
795
+ return null;
796
+ const short = (s) => s.trim().replace(/^codegraph_/, '');
797
+ const set = new Set(raw.split(',').map(short).filter(Boolean));
798
+ return set.size ? set : null;
799
+ }
800
+ /** Whether a tool name passes the CODEGRAPH_MCP_TOOLS allowlist (if any). */
801
+ isToolAllowed(name) {
802
+ const allow = this.toolAllowlist();
803
+ return !allow || allow.has(name.replace(/^codegraph_/, ''));
804
+ }
805
+ /**
806
+ * Get tool definitions with dynamic descriptions based on project size.
807
+ * The codegraph_explore tool description includes a budget recommendation
808
+ * scaled to the number of indexed files. Honors the CODEGRAPH_MCP_TOOLS
809
+ * allowlist so a trimmed surface is reflected in ListTools.
810
+ */
811
+ getTools() {
812
+ const allow = this.toolAllowlist();
813
+ // No explicit allowlist → the default 4-tool surface (see
814
+ // DEFAULT_MCP_TOOLS for the evidence). An allowlist replaces the
815
+ // default entirely, so any defined tool can be re-enabled.
816
+ let visible = allow
817
+ ? exports.tools.filter(t => allow.has(t.name.replace(/^codegraph_/, '')))
818
+ : exports.tools.filter(t => DEFAULT_MCP_TOOLS.has(t.name.replace(/^codegraph_/, '')));
819
+ // No default project loaded → no-root-index case (#993): a gateway server
820
+ // started outside any repo, or a monorepo root whose indexes live in
821
+ // sub-projects. With nothing to fall back to, EVERY call needs an explicit
822
+ // projectPath, so mark it required in the schema — a high-salience nudge the
823
+ // agent acts on, where SERVER_INSTRUCTIONS_NO_ROOT_INDEX's prose alone
824
+ // wasn't enough (the reporter had to add an AGENTS.md note). `this.cg` is
825
+ // settled by `retryInitIfNeeded()` before `handleToolsList` calls us, so a
826
+ // null here means "genuinely no default", not a startup race. When a default
827
+ // IS open we leave projectPath optional (below): a bare call falls back to
828
+ // it, exactly as in the common single-project launch.
829
+ if (!this.cg)
830
+ return withRequiredProjectPath(visible);
831
+ try {
832
+ const stats = this.cg.getStats();
833
+ const budget = getExploreBudget(stats.fileCount);
834
+ // Tiny-repo tool gating: on projects under TINY_REPO_FILE_THRESHOLD
835
+ // files, only expose the core trio (search, node, explore) — one
836
+ // below even the 4-tool default: at this scale callers, too, reduces
837
+ // to one grep. (Historical note: the audit below ran when context and
838
+ // trace still existed; its "5 core tools" are today's trio.)
839
+ //
840
+ // n=2 audits ruled out cutting below 5 tools:
841
+ // - 3-tool gate (search + context + trace): cost regressed on
842
+ // cobra/ky/sinatra. The agent fell back to raw Reads to cover
843
+ // what codegraph_node + codegraph_explore would have answered.
844
+ // - 1-tool gate (search only): catastrophic regression — express
845
+ // went from -43% WIN to +107% LOSS. With only search, the agent
846
+ // can't navigate the call graph structurally and reads everything.
847
+ //
848
+ // 5 is the empirical lower bound. Tools beyond search/context/
849
+ // node/explore/trace pay overhead that the agent doesn't recoup
850
+ // on tiny-repo flow questions.
851
+ // ITER4: raise threshold 150 → 500 so single-file frameworks
852
+ // (sinatra at 159, slim_framework around 200) also get the
853
+ // 5-tool surface. The empirical 5-tool floor was set on <150
854
+ // probes; iter3 measurement showed sinatra is structurally the
855
+ // SAME problem as cobra (single-file WITHOUT-arm Read wins),
856
+ // so it deserves the same gating.
857
+ const TINY_REPO_FILE_THRESHOLD = 500;
858
+ const TINY_REPO_CORE_TOOLS = new Set([
859
+ 'codegraph_explore',
860
+ 'codegraph_search',
861
+ 'codegraph_node',
862
+ ]);
863
+ if (stats.fileCount < TINY_REPO_FILE_THRESHOLD) {
864
+ visible = visible.filter(t => TINY_REPO_CORE_TOOLS.has(t.name));
865
+ }
866
+ return visible.map(tool => {
867
+ if (tool.name === 'codegraph_explore') {
868
+ return {
869
+ ...tool,
870
+ description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
871
+ };
872
+ }
873
+ return tool;
874
+ });
875
+ }
876
+ catch {
877
+ return visible;
878
+ }
879
+ }
880
+ /**
881
+ * Get CodeGraph instance for a project
882
+ *
883
+ * If projectPath is provided, opens that project's CodeGraph (cached).
884
+ * Otherwise returns the default CodeGraph instance.
885
+ *
886
+ * Walks up parent directories to find the nearest .codegraph/ folder,
887
+ * similar to how git finds .git/ directories.
888
+ */
889
+ getCodeGraph(projectPath) {
890
+ if (!projectPath) {
891
+ if (!this.cg) {
892
+ const searched = this.defaultProjectHint ?? process.cwd();
893
+ throw new NotIndexedError('No CodeGraph project is loaded for this session.\n' +
894
+ `Searched for a .codegraph/ directory starting from: ${searched}\n` +
895
+ 'Either the server root has no index of its own (e.g. a monorepo where only ' +
896
+ "sub-projects are indexed), or the MCP client launched the server outside your " +
897
+ 'project without reporting the workspace root. Either way, target the project ' +
898
+ 'explicitly:\n' +
899
+ ' • Pass projectPath to the tool call, e.g. projectPath: "/absolute/path/to/your/project" ' +
900
+ '(any project that has a .codegraph/ — including a sub-project of a monorepo)\n' +
901
+ ' • Or add --path to the server\'s MCP config args: ["serve", "--mcp", "--path", "/absolute/path/to/your/project"]\n' +
902
+ 'If a project simply has no index, use your built-in tools (Read/Grep/Glob) for THAT ' +
903
+ "project (the user can run 'codegraph init' there to enable it) — you can still query " +
904
+ 'other indexed projects by projectPath in the same session.');
905
+ }
906
+ return this.freshen(this.cg);
907
+ }
908
+ // Reject sensitive system directories before opening. Only validate a
909
+ // path that actually exists — a nested or not-yet-created sub-path of a
910
+ // real project must still be allowed to resolve UP to its .codegraph/
911
+ // root below (issue #238), so we don't run the existence-checking
912
+ // validator on paths that are meant to walk up.
913
+ if ((0, fs_1.existsSync)(projectPath)) {
914
+ const pathError = (0, utils_1.validateProjectPath)(projectPath);
915
+ if (pathError) {
916
+ throw new PathRefusalError(pathError);
917
+ }
918
+ }
919
+ // Always RE-RESOLVE the nearest .codegraph/ from the input path. The walk
920
+ // is cheap (a few existsSync up the tree) and is the only thing that
921
+ // notices a path whose index root CHANGED since it was first seen — most
922
+ // importantly a git worktree that gained its own .codegraph/ after the
923
+ // (long-lived) server first resolved it up to the parent checkout. We used
924
+ // to short-circuit on a `projectCache[projectPath]` entry before resolving,
925
+ // which pinned that first resolution for the server's whole lifetime, so a
926
+ // worktree kept being served the parent checkout's index until restart
927
+ // (#926). The DB connection itself is still cached (by resolved root,
928
+ // below), so re-resolving costs only the stat walk, never a reopen.
929
+ const resolvedRoot = (0, directory_1.findNearestCodeGraphRoot)(projectPath);
930
+ if (!resolvedRoot) {
931
+ throw new NotIndexedError(`The project at ${projectPath} isn't indexed with codegraph (no .codegraph/ directory found ` +
932
+ 'walking up from it), so codegraph cannot query it. Use your built-in tools (Read/Grep/Glob) ' +
933
+ "for that codebase instead, and don't call codegraph for it again this session. " +
934
+ "Indexing is the user's decision — they can run 'codegraph init' in that project to enable it.");
935
+ }
936
+ // If the path resolves to the default project, reuse the already-open
937
+ // default instance rather than opening a SECOND connection to the same DB.
938
+ // A duplicate connection serializes reads against the watcher's auto-sync
939
+ // writes; when WAL isn't in effect (e.g. a filesystem without shared-memory
940
+ // support) that surfaces as intermittent
941
+ // "database is locked" on concurrent tool calls. See issue #238. The
942
+ // default instance is owned/closed by the server, so it's never cached.
943
+ if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
944
+ return this.freshen(this.cg);
945
+ }
946
+ // Cache the open DB connection by RESOLVED ROOT only — never by the input
947
+ // path. One key per instance means closeAll() closes each exactly once, and
948
+ // a changed resolution maps to a different entry instead of a stale hit.
949
+ const cached = this.projectCache.get(resolvedRoot);
950
+ if (cached)
951
+ return this.freshen(cached);
952
+ const cg = loadCodeGraph().openSync(resolvedRoot);
953
+ this.projectCache.set(resolvedRoot, cg);
954
+ return cg;
955
+ }
956
+ /**
957
+ * Heal a long-lived connection whose `.codegraph/` was removed and recreated
958
+ * at the same path (a worktree recreated, or `rm -rf .codegraph` + re-init)
959
+ * before handing it to a tool. Otherwise the daemon keeps serving the
960
+ * pre-removal snapshot from its now-unlinked file handle until restart — and
961
+ * because the daemon registry is keyed by path, a same-path recreate routes
962
+ * new clients straight back to this same stale daemon (#925). The check is one
963
+ * stat() and a no-op unless the inode actually changed; it never throws into a
964
+ * tool call.
965
+ */
966
+ freshen(cg) {
967
+ try {
968
+ if (cg.reopenIfReplaced()) {
969
+ process.stderr.write('[CodeGraph MCP] The index was replaced on disk (e.g. a git worktree ' +
970
+ 'recreated at the same path); reopened the live database in place.\n');
971
+ }
972
+ }
973
+ catch {
974
+ // Best-effort self-heal — a failed reopen must never break the tool call;
975
+ // the (still stale) handle keeps serving and the next call retries.
976
+ }
977
+ return cg;
978
+ }
979
+ /**
980
+ * Close all cached project connections
981
+ */
982
+ closeAll() {
983
+ for (const cg of this.projectCache.values()) {
984
+ cg.close();
985
+ }
986
+ this.projectCache.clear();
987
+ this.worktreeMismatchCache.clear();
988
+ }
989
+ /**
990
+ * Validate that a value is a non-empty string within length bounds.
991
+ *
992
+ * The `maxLength` cap protects against MCP clients that ship huge
993
+ * payloads (10MB+ query strings either by accident or maliciously).
994
+ * Without this, a single oversized input can pin the FTS5 index or
995
+ * exhaust memory before any real work runs.
996
+ */
997
+ validateString(value, name, maxLength = MAX_INPUT_LENGTH) {
998
+ if (typeof value !== 'string' || value.length === 0) {
999
+ return this.errorResult(`${name} must be a non-empty string`);
1000
+ }
1001
+ if (value.length > maxLength) {
1002
+ return this.errorResult(`${name} exceeds maximum length of ${maxLength} characters (got ${value.length})`);
1003
+ }
1004
+ return value;
1005
+ }
1006
+ /**
1007
+ * Validate an optional path-like string input. Returns the value if
1008
+ * valid (or undefined), or a ToolResult with the error.
1009
+ */
1010
+ validateOptionalPath(value, name) {
1011
+ if (value === undefined || value === null)
1012
+ return undefined;
1013
+ if (typeof value !== 'string') {
1014
+ return this.errorResult(`${name} must be a string`);
1015
+ }
1016
+ if (value.length > MAX_PATH_LENGTH) {
1017
+ return this.errorResult(`${name} exceeds maximum length of ${MAX_PATH_LENGTH} characters (got ${value.length})`);
1018
+ }
1019
+ return value;
1020
+ }
1021
+ /**
1022
+ * Cached git worktree/index mismatch for a tool call's effective project.
1023
+ *
1024
+ * The "effective project" is what the request targets: an explicit
1025
+ * `projectPath` arg, else the directory the server resolved its default
1026
+ * project from (`defaultProjectHint`), else cwd. Memoized per start path —
1027
+ * see `worktreeMismatchCache`. Best-effort: if the project can't be resolved
1028
+ * (e.g. nothing initialized yet), it reports "no mismatch" so a tool is never
1029
+ * broken by this check.
1030
+ */
1031
+ worktreeMismatchFor(projectPath) {
1032
+ const startPath = projectPath ?? this.defaultProjectHint ?? process.cwd();
1033
+ // The verdict depends on BOTH the start path AND the index root it resolves
1034
+ // to, so the cache must be keyed on the pair. Resolve the index root first
1035
+ // (cheap — getCodeGraph re-walks to the nearest .codegraph/, no git), then
1036
+ // key on `(startPath, indexRoot)`. The moment that root changes — most
1037
+ // importantly when a git worktree gains its own index and the walk-up stops
1038
+ // there instead of at the parent checkout — the key changes and the verdict
1039
+ // is recomputed, instead of serving the stale "borrowed the parent's index"
1040
+ // warning for the server's whole lifetime. Keying on startPath alone pinned
1041
+ // that first verdict until restart (#926).
1042
+ let indexRoot;
1043
+ try {
1044
+ indexRoot = this.getCodeGraph(projectPath).getProjectRoot();
1045
+ }
1046
+ catch {
1047
+ // No resolvable project (or any other resolution error) → nothing to warn.
1048
+ return null;
1049
+ }
1050
+ const cacheKey = `${startPath}\u0000${indexRoot}`;
1051
+ const cached = this.worktreeMismatchCache.get(cacheKey);
1052
+ if (cached !== undefined)
1053
+ return cached;
1054
+ const mismatch = (0, worktree_1.detectWorktreeIndexMismatch)(startPath, indexRoot);
1055
+ this.worktreeMismatchCache.set(cacheKey, mismatch);
1056
+ return mismatch;
1057
+ }
1058
+ /**
1059
+ * Prefix a successful read-tool result with a compact worktree-mismatch
1060
+ * notice when the resolved index belongs to a different git working tree than
1061
+ * the caller's (issue #155). Without this, an agent in a nested worktree
1062
+ * silently trusts main-branch results. No-op on error results and when there
1063
+ * is no mismatch. `codegraph_status` is excluded — it embeds its own verbose
1064
+ * warning — so it stays out of this path.
1065
+ */
1066
+ withWorktreeNotice(result, projectPath) {
1067
+ if (result.isError)
1068
+ return result;
1069
+ const mismatch = this.worktreeMismatchFor(projectPath);
1070
+ if (!mismatch)
1071
+ return result;
1072
+ const notice = (0, worktree_1.worktreeMismatchNotice)(mismatch);
1073
+ const [first, ...rest] = result.content;
1074
+ if (first && first.type === 'text') {
1075
+ return { ...result, content: [{ type: 'text', text: `${notice}\n\n${first.text}` }, ...rest] };
1076
+ }
1077
+ return result;
1078
+ }
1079
+ /**
1080
+ * Annotate a successful read-tool result with per-file staleness — the
1081
+ * non-blocking answer to issue #403. The file watcher tracks every event
1082
+ * it sees per path; here we intersect "files referenced in this response"
1083
+ * against that pending set and prepend a compact banner so the agent can
1084
+ * fall back to Read for those *specific* files without waiting for the
1085
+ * debounced sync to fire. Other pending files in the project (not
1086
+ * referenced by this response) get a small footer so the agent has a
1087
+ * complete picture without bloating the banner.
1088
+ *
1089
+ * Cost when nothing is pending — the common case — is one boolean check.
1090
+ * No I/O, no parsing of markdown beyond a per-pending-file substring scan.
1091
+ */
1092
+ withStalenessNotice(result, projectPath) {
1093
+ if (result.isError)
1094
+ return result;
1095
+ let cg;
1096
+ try {
1097
+ cg = this.getCodeGraph(projectPath);
1098
+ }
1099
+ catch {
1100
+ return result; // no default project — leave as is
1101
+ }
1102
+ // Cross-project `projectPath` calls open a cached CodeGraph WITHOUT a
1103
+ // watcher (watchers are only attached to the default session project).
1104
+ // When the cross-project path happens to be the same project as the
1105
+ // default cg, the cached instance is the wrong one — its pendingFiles is
1106
+ // permanently empty. Detect the equal-path case and prefer the default
1107
+ // cg so the staleness signal still fires when an agent passes the
1108
+ // explicit projectPath form of its own project.
1109
+ if (this.cg && cg !== this.cg) {
1110
+ try {
1111
+ const sameProject = (0, path_1.resolve)(this.cg.getProjectRoot()) === (0, path_1.resolve)(cg.getProjectRoot());
1112
+ if (sameProject)
1113
+ cg = this.cg;
1114
+ }
1115
+ catch {
1116
+ /* getProjectRoot may throw on a closed instance — leave cg as is */
1117
+ }
1118
+ }
1119
+ // Whole-index degradation (#876): once live watching has permanently
1120
+ // stopped, getPendingFiles() is empty so the per-file banner below can't
1121
+ // fire — but the index is now FROZEN and silently drifting stale. Surface
1122
+ // one global notice instead, so the agent Reads for current content rather
1123
+ // than trusting a response off a no-longer-updating index. (Cross-project
1124
+ // calls open a watcher-less CodeGraph, so this is false there — correct: we
1125
+ // only know degraded state for the default session project.)
1126
+ let degraded = false;
1127
+ try {
1128
+ degraded = cg.isWatcherDegraded?.() ?? false;
1129
+ }
1130
+ catch {
1131
+ degraded = false;
1132
+ }
1133
+ if (degraded) {
1134
+ const [head, ...tail] = result.content;
1135
+ if (!head || head.type !== 'text')
1136
+ return result;
1137
+ let reason = null;
1138
+ try {
1139
+ reason = cg.getWatcherDegradedReason?.() ?? null;
1140
+ }
1141
+ catch {
1142
+ reason = null;
1143
+ }
1144
+ const composed = `${formatDegradedBanner(reason)}\n\n${head.text}`;
1145
+ return { ...result, content: [{ type: 'text', text: composed }, ...tail] };
1146
+ }
1147
+ // Defensive: some test fakes inject a partial CodeGraph stub without the
1148
+ // newer pending-files API. Treat missing/throwing as "no pending files."
1149
+ let pending = [];
1150
+ try {
1151
+ pending = cg.getPendingFiles?.() ?? [];
1152
+ }
1153
+ catch {
1154
+ return result;
1155
+ }
1156
+ if (pending.length === 0)
1157
+ return result;
1158
+ const [first, ...rest] = result.content;
1159
+ if (!first || first.type !== 'text')
1160
+ return result;
1161
+ const text = first.text;
1162
+ const inResponse = [];
1163
+ const elsewhere = [];
1164
+ for (const p of pending) {
1165
+ // Substring match against the project-relative POSIX path — that's
1166
+ // exactly the format both the watcher and every codegraph response
1167
+ // emit, so a plain includes() is sufficient and avoids regex pitfalls.
1168
+ if (text.includes(p.path))
1169
+ inResponse.push(p);
1170
+ else
1171
+ elsewhere.push(p);
1172
+ }
1173
+ let banner = '';
1174
+ if (inResponse.length > 0) {
1175
+ banner = formatStaleBanner(inResponse);
1176
+ }
1177
+ let footer = '';
1178
+ if (elsewhere.length > 0) {
1179
+ footer = formatStaleFooter(elsewhere);
1180
+ }
1181
+ if (!banner && !footer)
1182
+ return result;
1183
+ const composed = [banner, text, footer].filter(Boolean).join('\n\n');
1184
+ return { ...result, content: [{ type: 'text', text: composed }, ...rest] };
1185
+ }
1186
+ /**
1187
+ * Execute a tool by name
1188
+ */
1189
+ async execute(toolName, args) {
1190
+ try {
1191
+ // Block the first tool call on the engine's post-open reconcile so we
1192
+ // never serve rows for files deleted/edited while no MCP server was
1193
+ // running. The wait is time-boxed (#905): a huge-repo reconcile takes
1194
+ // minutes, and blocking the first call on all of it reads as a hang, so
1195
+ // we wait briefly then serve and let it finish in the background. The
1196
+ // gate is cleared after first await — subsequent calls pay nothing.
1197
+ // Catch-up failures are logged by the engine; we proceed regardless so a
1198
+ // transient sync error never breaks tools.
1199
+ if (this.catchUpGate) {
1200
+ const gate = this.catchUpGate;
1201
+ this.catchUpGate = null;
1202
+ await this.awaitCatchUpGate(gate);
1203
+ }
1204
+ // Honor the optional tool allowlist (CODEGRAPH_MCP_TOOLS): a trimmed
1205
+ // surface rejects ablated tools defensively even if a client cached them.
1206
+ if (!this.isToolAllowed(toolName)) {
1207
+ return this.errorResult(`Tool ${toolName} is disabled via CODEGRAPH_MCP_TOOLS`);
1208
+ }
1209
+ // Cross-cutting input validation. All tools accept an optional
1210
+ // `projectPath` and most accept either `query`, `task`, or
1211
+ // `symbol` — bound their lengths centrally so individual handlers
1212
+ // can stay focused on tool-specific logic.
1213
+ const pathCheck = this.validateOptionalPath(args.projectPath, 'projectPath');
1214
+ if (typeof pathCheck === 'object' && pathCheck !== undefined) {
1215
+ return pathCheck;
1216
+ }
1217
+ // The `path` and `pattern` properties used by codegraph_files are
1218
+ // also path-shaped — apply the same cap.
1219
+ if (args.path !== undefined) {
1220
+ const check = this.validateOptionalPath(args.path, 'path');
1221
+ if (typeof check === 'object' && check !== undefined)
1222
+ return check;
1223
+ }
1224
+ if (args.pattern !== undefined) {
1225
+ const check = this.validateOptionalPath(args.pattern, 'pattern');
1226
+ if (typeof check === 'object' && check !== undefined)
1227
+ return check;
1228
+ }
1229
+ // codegraph_status reports watcher state (pending files, degraded mode,
1230
+ // worktree warning) and embeds its own sections — it must run on the MAIN
1231
+ // thread against the watched default instance, so it is NEVER off-loaded to
1232
+ // a worker (whose read connection has no watcher). It also skips the
1233
+ // auto-banner wrapper to avoid duplicating its own pending-files section.
1234
+ if (toolName === 'codegraph_status') {
1235
+ return await this.handleStatus(args);
1236
+ }
1237
+ // Read tools: off-load the CPU-heavy dispatch to the worker pool when one
1238
+ // is attached, healthy, AND has finished its first cold start (daemon
1239
+ // mode), so the daemon's single event loop stays free for the MCP
1240
+ // transport under concurrent load — otherwise N concurrent explores
1241
+ // serialize AND starve the transport until the whole batch drains
1242
+ // (clients then time out). Before the first worker is warm, calls run
1243
+ // in-process: a call queued behind a cold start sat invisible until the
1244
+ // 45s busy backstop — the daemon's first tool call stalling for however
1245
+ // long a worker spawn takes on a loaded machine (the #662 flake). With
1246
+ // no pool (direct mode) or a degraded one, dispatch runs in-process
1247
+ // exactly as before. Either way the result flows through the
1248
+ // cross-cutting notices — worktree-index mismatch (#155) and per-file
1249
+ // staleness (#403) — which need the watched MAIN instance and so are
1250
+ // always applied here, never in the worker.
1251
+ const result = (this.queryPool && this.queryPool.healthy && this.queryPool.ready)
1252
+ ? await this.queryPool.run(toolName, args)
1253
+ : await this.executeReadTool(toolName, args);
1254
+ const withWorktree = this.withWorktreeNotice(result, args.projectPath);
1255
+ return this.withStalenessNotice(withWorktree, args.projectPath);
1256
+ }
1257
+ catch (err) {
1258
+ // Expected condition, not a malfunction: answer as a SUCCESS so the
1259
+ // agent keeps trusting the toolset for projects that ARE indexed.
1260
+ // (An isError here teaches session-long abandonment — see NotIndexedError.)
1261
+ if (err instanceof NotIndexedError) {
1262
+ return this.textResult(err.message);
1263
+ }
1264
+ // Security refusal: a clean error, no retry encouragement.
1265
+ if (err instanceof PathRefusalError) {
1266
+ return this.errorResult(err.message);
1267
+ }
1268
+ return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
1269
+ 'This is an internal codegraph error — retry the call once; if it persists, ' +
1270
+ 'continue without codegraph for this task.');
1271
+ }
1272
+ }
1273
+ /**
1274
+ * Run a single read tool to completion and return its raw {@link ToolResult},
1275
+ * classifying expected failures the same way {@link execute}'s catch does so
1276
+ * the SHAPE is identical whether dispatch runs in-process or on a worker:
1277
+ * NotIndexed → success-shaped guidance, PathRefusal → clean error, anything
1278
+ * else → internal-error-with-retry. Never throws.
1279
+ *
1280
+ * This is the worker thread's entry point (see {@link ./query-worker}) and the
1281
+ * in-process fallback for {@link execute}. It deliberately does NOT run the
1282
+ * catch-up gate or the staleness/worktree notices — those need the daemon's
1283
+ * watched main instance and stay on the main thread. Cross-cutting allowlist +
1284
+ * path validation already ran in {@link execute} before routing here.
1285
+ */
1286
+ async executeReadTool(toolName, args) {
1287
+ try {
1288
+ return await this.dispatchTool(toolName, args);
1289
+ }
1290
+ catch (err) {
1291
+ if (err instanceof NotIndexedError) {
1292
+ return this.textResult(err.message);
1293
+ }
1294
+ if (err instanceof PathRefusalError) {
1295
+ return this.errorResult(err.message);
1296
+ }
1297
+ return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
1298
+ 'This is an internal codegraph error — retry the call once; if it persists, ' +
1299
+ 'continue without codegraph for this task.');
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Pure dispatch over the read tools — the switch, with no gate, no notices, no
1304
+ * allowlist/validation (the caller owns those). `codegraph_status` is handled
1305
+ * on the main thread in {@link execute} and never reaches here. May throw
1306
+ * NotIndexed/PathRefusal, which {@link executeReadTool} classifies.
1307
+ */
1308
+ async dispatchTool(toolName, args) {
1309
+ switch (toolName) {
1310
+ case 'codegraph_search': return await this.handleSearch(args);
1311
+ case 'codegraph_callers': return await this.handleCallers(args);
1312
+ case 'codegraph_callees': return await this.handleCallees(args);
1313
+ case 'codegraph_impact': return await this.handleImpact(args);
1314
+ case 'codegraph_explore': return await this.handleExplore(args);
1315
+ case 'codegraph_node': return await this.handleNode(args);
1316
+ case 'codegraph_files': return await this.handleFiles(args);
1317
+ default: return this.errorResult(`Unknown tool: ${toolName}`);
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Handle codegraph_search
1322
+ */
1323
+ async handleSearch(args) {
1324
+ const query = this.validateString(args.query, 'query');
1325
+ if (typeof query !== 'string')
1326
+ return query;
1327
+ const cg = this.getCodeGraph(args.projectPath);
1328
+ const rawKind = args.kind;
1329
+ // The schema enum says 'type' (what agents naturally reach for); the
1330
+ // NodeKind is 'type_alias'. Without the mapping, kind: "type" silently
1331
+ // matched nothing — a filter value we advertise must work.
1332
+ const kind = rawKind === 'type' ? 'type_alias' : rawKind;
1333
+ const rawLimit = Number(args.limit) || 10;
1334
+ const limit = (0, utils_1.clamp)(rawLimit, 1, 100);
1335
+ const results = cg.searchNodes(query, {
1336
+ limit,
1337
+ kinds: kind ? [kind] : undefined,
1338
+ });
1339
+ if (results.length === 0) {
1340
+ return this.textResult(`No results found for "${query}"`);
1341
+ }
1342
+ // Down-rank generated files within the FTS-returned set so a search
1343
+ // for "Send" surfaces the hand-written keeper before .pb.go stubs
1344
+ // that share the name. Stable: only reorders generated vs. not.
1345
+ const ranked = [...results].sort((a, b) => {
1346
+ const aGen = (0, generated_detection_1.isGeneratedFile)(a.node.filePath) ? 1 : 0;
1347
+ const bGen = (0, generated_detection_1.isGeneratedFile)(b.node.filePath) ? 1 : 0;
1348
+ return aGen - bGen;
1349
+ });
1350
+ const formatted = this.formatSearchResults(ranked);
1351
+ return this.textResult(this.truncateOutput(formatted));
1352
+ }
1353
+ /**
1354
+ * Group symbol matches into DISTINCT DEFINITIONS — one group per
1355
+ * (filePath, qualifiedName), so same-file overloads stay together while
1356
+ * unrelated same-named classes across a monorepo's apps (#764: one
1357
+ * `UserService` per NestJS app) are kept apart. Optionally narrowed by a
1358
+ * `file` path/suffix first.
1359
+ */
1360
+ groupDefinitions(nodes, fileFilter) {
1361
+ let pool = nodes;
1362
+ let filteredOut = false;
1363
+ if (fileFilter) {
1364
+ const wanted = fileFilter.replace(/^\.\//, '');
1365
+ const narrowed = pool.filter((n) => n.filePath === wanted || n.filePath.endsWith(wanted) || n.filePath.endsWith(`/${wanted}`));
1366
+ if (narrowed.length > 0) {
1367
+ pool = narrowed;
1368
+ }
1369
+ else {
1370
+ filteredOut = true;
1371
+ }
1372
+ }
1373
+ const byDef = new Map();
1374
+ for (const n of pool) {
1375
+ const key = `${n.filePath}|${n.qualifiedName}`;
1376
+ const group = byDef.get(key);
1377
+ if (group)
1378
+ group.push(n);
1379
+ else
1380
+ byDef.set(key, [n]);
1381
+ }
1382
+ return { groups: [...byDef.values()], filteredOut };
1383
+ }
1384
+ /** Section heading for one distinct definition in grouped output. */
1385
+ definitionHeading(group) {
1386
+ const head = group[0];
1387
+ const line = head.startLine ? `:${head.startLine}` : '';
1388
+ return `**${head.qualifiedName}** (${head.kind}) — ${head.filePath}${line}`;
1389
+ }
1390
+ /**
1391
+ * Handle codegraph_callers
1392
+ */
1393
+ async handleCallers(args) {
1394
+ const symbol = this.validateString(args.symbol, 'symbol');
1395
+ if (typeof symbol !== 'string')
1396
+ return symbol;
1397
+ const cg = this.getCodeGraph(args.projectPath);
1398
+ const limit = (0, utils_1.clamp)(args.limit || 20, 1, 100);
1399
+ const fileFilter = typeof args.file === 'string' ? args.file : undefined;
1400
+ const allMatches = this.findAllSymbols(cg, symbol);
1401
+ if (allMatches.nodes.length === 0) {
1402
+ return this.textResult(`Symbol "${symbol}" not found in the codebase`);
1403
+ }
1404
+ const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
1405
+ const filterNote = filteredOut
1406
+ ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
1407
+ : '';
1408
+ const collect = (defNodes) => {
1409
+ const seen = new Set();
1410
+ const callers = [];
1411
+ const labels = new Map();
1412
+ for (const node of defNodes) {
1413
+ for (const c of cg.getCallers(node.id)) {
1414
+ if (!seen.has(c.node.id)) {
1415
+ seen.add(c.node.id);
1416
+ callers.push(c.node);
1417
+ const label = this.edgeLabel(c.edge);
1418
+ if (label)
1419
+ labels.set(c.node.id, label);
1420
+ }
1421
+ }
1422
+ }
1423
+ return { callers, labels };
1424
+ };
1425
+ // Single definition (or same-file overloads): the familiar flat list.
1426
+ if (groups.length === 1) {
1427
+ const { callers, labels } = collect(groups[0]);
1428
+ if (callers.length === 0) {
1429
+ return this.textResult(`No callers found for "${symbol}"${allMatches.note}${filterNote}`);
1430
+ }
1431
+ // A successful `file` narrowing makes the multi-symbol aggregation note
1432
+ // stale — suppress it.
1433
+ const note = fileFilter && !filteredOut ? '' : allMatches.note;
1434
+ const formatted = this.formatNodeList(callers.slice(0, limit), `Callers of ${symbol}`, labels) + note + filterNote;
1435
+ return this.textResult(this.truncateOutput(formatted));
1436
+ }
1437
+ // Multiple DISTINCT definitions (#764): one section per definition so an
1438
+ // agent never mistakes one app's callers for another's. Narrow with
1439
+ // `file` to focus a single definition.
1440
+ const lines = [
1441
+ `**Callers of ${symbol} — ${groups.length} distinct definitions (narrow with \`file\`)**`,
1442
+ ];
1443
+ for (const group of groups) {
1444
+ const { callers, labels } = collect(group);
1445
+ lines.push('', this.definitionHeading(group));
1446
+ if (callers.length === 0) {
1447
+ lines.push('- (no callers)');
1448
+ continue;
1449
+ }
1450
+ for (const node of callers.slice(0, limit)) {
1451
+ const location = node.startLine ? `:${node.startLine}` : '';
1452
+ const label = labels.get(node.id);
1453
+ lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
1454
+ }
1455
+ }
1456
+ return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
1457
+ }
1458
+ /**
1459
+ * Handle codegraph_callees
1460
+ */
1461
+ async handleCallees(args) {
1462
+ const symbol = this.validateString(args.symbol, 'symbol');
1463
+ if (typeof symbol !== 'string')
1464
+ return symbol;
1465
+ const cg = this.getCodeGraph(args.projectPath);
1466
+ const limit = (0, utils_1.clamp)(args.limit || 20, 1, 100);
1467
+ const fileFilter = typeof args.file === 'string' ? args.file : undefined;
1468
+ const allMatches = this.findAllSymbols(cg, symbol);
1469
+ if (allMatches.nodes.length === 0) {
1470
+ return this.textResult(`Symbol "${symbol}" not found in the codebase`);
1471
+ }
1472
+ const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
1473
+ const filterNote = filteredOut
1474
+ ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
1475
+ : '';
1476
+ const collect = (defNodes) => {
1477
+ const seen = new Set();
1478
+ const callees = [];
1479
+ const labels = new Map();
1480
+ for (const node of defNodes) {
1481
+ for (const c of cg.getCallees(node.id)) {
1482
+ if (!seen.has(c.node.id)) {
1483
+ seen.add(c.node.id);
1484
+ callees.push(c.node);
1485
+ const label = this.edgeLabel(c.edge);
1486
+ if (label)
1487
+ labels.set(c.node.id, label);
1488
+ }
1489
+ }
1490
+ }
1491
+ return { callees, labels };
1492
+ };
1493
+ if (groups.length === 1) {
1494
+ const { callees, labels } = collect(groups[0]);
1495
+ if (callees.length === 0) {
1496
+ return this.textResult(`No callees found for "${symbol}"${allMatches.note}${filterNote}`);
1497
+ }
1498
+ // A successful `file` narrowing makes the multi-symbol aggregation note
1499
+ // stale — suppress it.
1500
+ const note = fileFilter && !filteredOut ? '' : allMatches.note;
1501
+ const formatted = this.formatNodeList(callees.slice(0, limit), `Callees of ${symbol}`, labels) + note + filterNote;
1502
+ return this.textResult(this.truncateOutput(formatted));
1503
+ }
1504
+ // Multiple DISTINCT definitions (#764): per-definition sections.
1505
+ const lines = [
1506
+ `**Callees of ${symbol} — ${groups.length} distinct definitions (narrow with \`file\`)**`,
1507
+ ];
1508
+ for (const group of groups) {
1509
+ const { callees, labels } = collect(group);
1510
+ lines.push('', this.definitionHeading(group));
1511
+ if (callees.length === 0) {
1512
+ lines.push('- (no callees)');
1513
+ continue;
1514
+ }
1515
+ for (const node of callees.slice(0, limit)) {
1516
+ const location = node.startLine ? `:${node.startLine}` : '';
1517
+ const label = labels.get(node.id);
1518
+ lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
1519
+ }
1520
+ }
1521
+ return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
1522
+ }
1523
+ /**
1524
+ * Handle codegraph_impact
1525
+ */
1526
+ async handleImpact(args) {
1527
+ const symbol = this.validateString(args.symbol, 'symbol');
1528
+ if (typeof symbol !== 'string')
1529
+ return symbol;
1530
+ const cg = this.getCodeGraph(args.projectPath);
1531
+ const depth = (0, utils_1.clamp)(args.depth || 2, 1, 10);
1532
+ const fileFilter = typeof args.file === 'string' ? args.file : undefined;
1533
+ const allMatches = this.findAllSymbols(cg, symbol);
1534
+ if (allMatches.nodes.length === 0) {
1535
+ return this.textResult(`Symbol "${symbol}" not found in the codebase`);
1536
+ }
1537
+ const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
1538
+ const filterNote = filteredOut
1539
+ ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
1540
+ : '';
1541
+ const impactOf = (defNodes) => {
1542
+ const mergedNodes = new Map();
1543
+ const mergedEdges = [];
1544
+ const seenEdges = new Set();
1545
+ for (const node of defNodes) {
1546
+ const impact = cg.getImpactRadius(node.id, depth);
1547
+ for (const [id, n] of impact.nodes) {
1548
+ mergedNodes.set(id, n);
1549
+ }
1550
+ for (const e of impact.edges) {
1551
+ const key = `${e.source}->${e.target}:${e.kind}`;
1552
+ if (!seenEdges.has(key)) {
1553
+ seenEdges.add(key);
1554
+ mergedEdges.push(e);
1555
+ }
1556
+ }
1557
+ }
1558
+ return { nodes: mergedNodes, edges: mergedEdges, roots: defNodes.map((n) => n.id) };
1559
+ };
1560
+ // Single definition (or same-file overloads): the familiar merged report.
1561
+ if (groups.length === 1) {
1562
+ const formatted = this.formatImpact(symbol, impactOf(groups[0])) + (fileFilter && !filteredOut ? "" : allMatches.note) + filterNote;
1563
+ return this.textResult(this.truncateOutput(formatted));
1564
+ }
1565
+ // Multiple DISTINCT definitions (#764): a blast radius PER definition —
1566
+ // merging unrelated same-named classes (one UserService per monorepo app)
1567
+ // overstated impact and confused agents. Narrow with `file`.
1568
+ const sections = [
1569
+ `**Impact of ${symbol} — ${groups.length} distinct definitions (each with its own blast radius; narrow with \`file\`)**`,
1570
+ ];
1571
+ for (const group of groups) {
1572
+ const head = group[0];
1573
+ const line = head.startLine ? `:${head.startLine}` : '';
1574
+ sections.push('', this.formatImpact(`${head.qualifiedName} (${head.filePath}${line})`, impactOf(group)));
1575
+ }
1576
+ return this.textResult(this.truncateOutput(sections.join('\n') + filterNote));
1577
+ }
1578
+ /**
1579
+ * Describe a synthesized (dynamic-dispatch) edge for human output: how the
1580
+ * callback was wired up — the bridge static parsing can't see. Returns null
1581
+ * for ordinary static edges. Used by trace + the node trail so a synthesized
1582
+ * hop reads as "registered via onUpdate at App.tsx:3148", not a bare arrow.
1583
+ */
1584
+ synthEdgeNote(edge) {
1585
+ if (!edge || edge.provenance !== 'heuristic')
1586
+ return null;
1587
+ const m = edge.metadata;
1588
+ const registeredAt = typeof m?.registeredAt === 'string' ? m.registeredAt : undefined;
1589
+ const at = registeredAt ? ` @${registeredAt}` : '';
1590
+ if (m?.synthesizedBy === 'callback') {
1591
+ const via = m.via ? `\`${String(m.via)}\`` : 'a registrar';
1592
+ const field = m.field ? ` on .${String(m.field)}` : '';
1593
+ return {
1594
+ label: `callback — registered via ${via}${field} (dynamic dispatch)`,
1595
+ compact: `dynamic: callback via ${via}${at}`,
1596
+ registeredAt,
1597
+ };
1598
+ }
1599
+ if (m?.synthesizedBy === 'event-emitter') {
1600
+ const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
1601
+ return {
1602
+ label: `event ${ev} — emit → handler (dynamic dispatch)`,
1603
+ compact: `dynamic: event ${ev}${at}`,
1604
+ registeredAt,
1605
+ };
1606
+ }
1607
+ if (m?.synthesizedBy === 'react-render') {
1608
+ return {
1609
+ label: `React re-render — \`setState\` re-runs render() (dynamic dispatch)`,
1610
+ compact: `dynamic: React re-render via setState${at}`,
1611
+ registeredAt,
1612
+ };
1613
+ }
1614
+ if (m?.synthesizedBy === 'jsx-render') {
1615
+ const child = m.via ? `<${String(m.via)}>` : 'a child component';
1616
+ return {
1617
+ label: `renders ${child} (JSX child — dynamic dispatch)`,
1618
+ compact: `dynamic: renders ${child}`,
1619
+ registeredAt,
1620
+ };
1621
+ }
1622
+ if (m?.synthesizedBy === 'vue-handler') {
1623
+ const ev = m.event ? `@${String(m.event)}` : 'a template event';
1624
+ return {
1625
+ label: `Vue template handler — bound to ${ev} (dynamic dispatch)`,
1626
+ compact: `dynamic: Vue ${ev} handler`,
1627
+ registeredAt,
1628
+ };
1629
+ }
1630
+ if (m?.synthesizedBy === 'interface-impl') {
1631
+ return {
1632
+ label: `interface/abstract dispatch — runs the implementation override (dynamic dispatch)`,
1633
+ compact: `dynamic: interface → impl${at}`,
1634
+ registeredAt,
1635
+ };
1636
+ }
1637
+ if (m?.synthesizedBy === 'closure-collection') {
1638
+ const field = m.field ? `\`${String(m.field)}\`` : 'a collection';
1639
+ return {
1640
+ label: `closure collection — runs handlers appended to ${field} (dynamic dispatch)`,
1641
+ compact: `dynamic: runs ${field} handlers${at}`,
1642
+ registeredAt,
1643
+ };
1644
+ }
1645
+ if (m?.synthesizedBy === 'fn-pointer-dispatch') {
1646
+ const via = m.via ? `\`${String(m.via)}\`` : 'a function pointer';
1647
+ return {
1648
+ label: `function-pointer dispatch via ${via} (dynamic dispatch)`,
1649
+ compact: `dynamic: fn-pointer ${m.via ? String(m.via) : ''}${at}`,
1650
+ registeredAt,
1651
+ };
1652
+ }
1653
+ if (m?.synthesizedBy === 'goframe-route') {
1654
+ const route = m.route ? `\`${String(m.route)}\`` : 'a route';
1655
+ return {
1656
+ label: `GoFrame route ${route} — reflective Bind → controller method (dynamic dispatch)`,
1657
+ compact: `dynamic: GoFrame route ${m.route ? String(m.route) : ''}${at}`,
1658
+ registeredAt,
1659
+ };
1660
+ }
1661
+ // Generic fallback for any other synthesizer (redux-thunk, gin-middleware-chain,
1662
+ // flutter-build, …): a synthesized hop must never read as a bare static `calls`.
1663
+ // It's a dynamic-dispatch bridge — label it as one and keep its wiring site.
1664
+ if (typeof m?.synthesizedBy === 'string') {
1665
+ const kind = m.synthesizedBy.replace(/-/g, ' ');
1666
+ return { label: `${kind} (dynamic dispatch)`, compact: `dynamic: ${kind}${at}`, registeredAt };
1667
+ }
1668
+ return null;
1669
+ }
1670
+ /**
1671
+ * Flow-from-named-symbols: an agent's codegraph_explore query is a bag of
1672
+ * symbol names that usually spans the flow it's investigating (e.g.
1673
+ * "PmsProductController getList PmsProductService list PmsProductServiceImpl").
1674
+ * Surface the longest call chain AMONG those named symbols — scoped to what the
1675
+ * agent explicitly named, so (unlike a fuzzy relevance set) there's no
1676
+ * wrong-feature wandering. Rides synthesized edges, so controller→service-
1677
+ * interface→impl shows up. Returns '' if no chain of >=3 nodes exists.
1678
+ *
1679
+ * Ambiguous tokens (Java `list` → dozens of nodes) are disambiguated by
1680
+ * CO-NAMING: the agent names the class too, so we keep only `list` candidates
1681
+ * whose qualifiedName contains another named token (`PmsProductServiceImpl::list`),
1682
+ * dropping unrelated `OmsOrderService::list`.
1683
+ */
1684
+ buildFlowFromNamedSymbols(cg, query) {
1685
+ // spineCallSites: for each spine node, the line where it CALLS the next hop —
1686
+ // lets the source assembler window an oversize spine method (e.g. n8n's 962-line
1687
+ // processRunExecutionData) to the call site instead of dumping the whole body.
1688
+ const EMPTY = { text: '', pathNodeIds: new Set(), namedNodeIds: new Set(), uniqueNamedNodeIds: new Set(), spineCallSites: new Map() };
1689
+ try {
1690
+ const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
1691
+ // Strip only a REAL file extension (Create.cs → Create); KEEP qualified
1692
+ // names (Class.method / Class::method) — the agent's most precise input,
1693
+ // resolved exactly by findAllSymbols. (The old strip mangled Class.method
1694
+ // into Class, throwing the method away.)
1695
+ const FILE_EXT = /\.(?:java|kt|kts|ts|tsx|js|jsx|mjs|cjs|cs|py|go|rb|php|swift|rs|cpp|cc|cxx|c|h|hpp|scala|lua|dart|vue|svelte|astro|erl|hrl)$/i;
1696
+ const tokens = [...new Set(query.split(/[\s,()[\]]+/)
1697
+ .map((t) => t.replace(FILE_EXT, '').trim())
1698
+ .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t)))].slice(0, 16);
1699
+ if (tokens.length < 2)
1700
+ return EMPTY;
1701
+ // Pool of name SEGMENTS (Class + method from every token) used to
1702
+ // disambiguate an ambiguous SIMPLE name: keep a candidate only if its
1703
+ // CONTAINER class is itself named in the query.
1704
+ const segPool = new Set();
1705
+ for (const t of tokens)
1706
+ for (const s of t.toLowerCase().split(/::|\./))
1707
+ if (s)
1708
+ segPool.add(s);
1709
+ const named = new Map();
1710
+ // Nodes whose token is SPECIFIC — a (near-)unique callable name (<=3 defs in
1711
+ // the whole graph). These are safe to SPARE a file on: the agent named THIS
1712
+ // method (`getResponseWithInterceptorChain`, 1 def). A hyper-polymorphic name
1713
+ // (`as_sql`, 110 defs across every Expression/Compiler subclass) is NOT here,
1714
+ // so naming it doesn't keep every backend variant full and flood the budget.
1715
+ const uniqueNamedNodeIds = new Set();
1716
+ // token → resolved node ids: drives the token-coverage check that gates
1717
+ // the dynamic-boundary scan (a token is covered when ANY of its nodes
1718
+ // lands on the main chain — overloads off the chain don't count against).
1719
+ const tokenNodes = new Map();
1720
+ // token → its full same-name callable family (before the container filter).
1721
+ // A LARGE family that fails to connect on the chain is a polymorphic
1722
+ // interface/registry dispatch — surfaced by buildPolymorphicBoundaries below.
1723
+ const tokenFamily = new Map();
1724
+ // Non-callable endpoints (CONSTANT/VARIABLE/FIELD) connected by a SYNTHESIZED
1725
+ // edge. RTK thunks are `const X = createAsyncThunk(...)`, so a thunk→thunk hop
1726
+ // is constant→constant — the CALLABLE-only `named` set can't hold it, and
1727
+ // without this the hop is invisible to the Flow path at every tier (the
1728
+ // Relationships section catches it only on repos ≥500 files). Kept SEPARATE
1729
+ // from `named` (which drives the call-chain + source sizing, callable-only);
1730
+ // fed only to the dynamic-dispatch-links scan below.
1731
+ const dynNamed = new Map();
1732
+ const DYN_KINDS = new Set(['constant', 'variable', 'field', 'property']);
1733
+ const hasHeuristicEdge = (id) => [...cg.getCallers(id), ...cg.getCallees(id)].some(({ edge }) => edge.provenance === 'heuristic');
1734
+ for (const t of tokens) {
1735
+ const hits = this.findAllSymbols(cg, t).nodes;
1736
+ const cands = hits.filter((n) => CALLABLE.has(n.kind));
1737
+ tokenFamily.set(t, cands);
1738
+ // A qualified or otherwise-specific name (<=3 hits) keeps all; an
1739
+ // ambiguous simple name keeps only candidates whose container is named.
1740
+ const specific = cands.length <= 3;
1741
+ const pick = specific
1742
+ ? cands
1743
+ : cands.filter((n) => {
1744
+ const segs = (n.qualifiedName || '').toLowerCase().split(/::|\./).filter(Boolean);
1745
+ const container = segs.length >= 2 ? segs[segs.length - 2] : '';
1746
+ return !!container && segPool.has(container);
1747
+ });
1748
+ const kept = pick.slice(0, 6);
1749
+ tokenNodes.set(t, kept.map((n) => n.id));
1750
+ for (const n of kept) {
1751
+ named.set(n.id, n);
1752
+ if (specific)
1753
+ uniqueNamedNodeIds.add(n.id);
1754
+ }
1755
+ // Same token, non-callable synth endpoints (capped, precision-gated on an
1756
+ // actual heuristic edge so plain config constants never qualify).
1757
+ // Per-token sub-cap so one token's many endpoints (10 nix option writes
1758
+ // of `programs.git.enable` across test configs) can't fill the pool
1759
+ // before later tokens (`home.file`) get a slot.
1760
+ if (dynNamed.size < 12) {
1761
+ let tokenDyn = 0;
1762
+ for (const n of hits) {
1763
+ if (CALLABLE.has(n.kind) || !DYN_KINDS.has(n.kind) || dynNamed.has(n.id))
1764
+ continue;
1765
+ if (hasHeuristicEdge(n.id)) {
1766
+ dynNamed.set(n.id, n);
1767
+ tokenDyn++;
1768
+ }
1769
+ if (dynNamed.size >= 12 || tokenDyn >= 4)
1770
+ break;
1771
+ }
1772
+ }
1773
+ if (named.size > 40)
1774
+ break;
1775
+ }
1776
+ // Surface synthesized (heuristic) edges incident to a named symbol — INCLUDING
1777
+ // the non-callable CONSTANT endpoints in `dynNamed`. `skipInChain` drops a hop
1778
+ // already shown in the rendered main chain (a 2-node chain renders nothing, so a
1779
+ // direct named→named synth hop still surfaces — #687).
1780
+ const collectSynthLinks = (skipInChain) => {
1781
+ const synthLines = [];
1782
+ const synthSeen = new Set();
1783
+ for (const n of [...named.values(), ...dynNamed.values()]) {
1784
+ if (synthLines.length >= 6)
1785
+ break;
1786
+ for (const { node: other, edge } of [...cg.getCallers(n.id), ...cg.getCallees(n.id)]) {
1787
+ if (synthLines.length >= 6)
1788
+ break;
1789
+ if (edge.provenance !== 'heuristic' || other.id === n.id)
1790
+ continue;
1791
+ if (skipInChain && skipInChain(edge))
1792
+ continue;
1793
+ const src = edge.source === n.id ? n : other;
1794
+ const tgt = edge.source === n.id ? other : n;
1795
+ const key = `${src.name}>${tgt.name}`;
1796
+ if (synthSeen.has(key))
1797
+ continue;
1798
+ synthSeen.add(key);
1799
+ const note = this.synthEdgeNote(edge);
1800
+ synthLines.push(`- ${src.name} → ${tgt.name} [${note ? note.compact : edge.kind}]`);
1801
+ }
1802
+ }
1803
+ return synthLines;
1804
+ };
1805
+ if (named.size < 2) {
1806
+ // <2 CALLABLES resolved. Two recoveries before giving up: (1) synthesized
1807
+ // edges among named CONSTANT/VARIABLE endpoints — RTK thunk→thunk is
1808
+ // constant→constant, so `named` can be empty while `dynNamed` holds the
1809
+ // whole chain; (2) the one resolved callable's body may hold the
1810
+ // dynamic-dispatch site that EXPLAINS a half-connected flow.
1811
+ const synthLines = collectSynthLinks(null);
1812
+ const boundaries = named.size === 0 ? '' : (this.buildDynamicBoundaries(cg, [...named.values()], named) || '');
1813
+ if (synthLines.length === 0 && !boundaries)
1814
+ return EMPTY;
1815
+ const out = [];
1816
+ if (synthLines.length)
1817
+ out.push('**Dynamic-dispatch links among your symbols**', '(synthesized — the indirect hops grep/Read would reconstruct; the `@file:line` is the wiring site)', '', ...synthLines, '');
1818
+ if (boundaries)
1819
+ out.push(boundaries);
1820
+ out.push('> Full source for these symbols is below.\n');
1821
+ return { text: out.join('\n'), pathNodeIds: new Set(), namedNodeIds: new Set([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites: new Map() };
1822
+ }
1823
+ const MAX_HOPS = 7;
1824
+ let best = null;
1825
+ // BFS the full call graph (incl. synth edges) from each named seed, but
1826
+ // only ACCEPT a sink that is also named — both ends anchored to symbols the
1827
+ // agent named, so the chain stays on-topic while bridging intermediates
1828
+ // (e.g. the exact interface overload) that the token resolution missed.
1829
+ for (const seed of [...named.values()].slice(0, 8)) {
1830
+ const parent = new Map();
1831
+ parent.set(seed.id, { prev: null, edge: null, node: seed });
1832
+ const q = [{ id: seed.id, depth: 0, streak: 0 }];
1833
+ let deep = null, deepDepth = 0;
1834
+ const MAX_BRIDGE = 1; // ≤1 consecutive UNNAMED hop: bridge one missing intermediate, never wander a god-function's fan-out
1835
+ for (let h = 0; h < q.length && parent.size < 1500; h++) {
1836
+ const { id, depth, streak } = q[h];
1837
+ if (id !== seed.id && named.has(id) && depth > deepDepth) {
1838
+ deep = id;
1839
+ deepDepth = depth;
1840
+ }
1841
+ if (depth >= MAX_HOPS - 1)
1842
+ continue;
1843
+ for (const c of cg.getCallees(id)) {
1844
+ if (c.edge.kind !== 'calls' || parent.has(c.node.id))
1845
+ continue;
1846
+ const newStreak = named.has(c.node.id) ? 0 : streak + 1;
1847
+ if (newStreak > MAX_BRIDGE)
1848
+ continue;
1849
+ parent.set(c.node.id, { prev: id, edge: c.edge, node: c.node });
1850
+ q.push({ id: c.node.id, depth: depth + 1, streak: newStreak });
1851
+ }
1852
+ }
1853
+ if (!deep)
1854
+ continue;
1855
+ const chain = [];
1856
+ let cur = deep;
1857
+ while (cur) {
1858
+ const p = parent.get(cur);
1859
+ if (!p)
1860
+ break;
1861
+ chain.push({ node: p.node, edge: p.edge });
1862
+ cur = p.prev;
1863
+ }
1864
+ chain.reverse();
1865
+ if (!best || chain.length > best.length)
1866
+ best = chain;
1867
+ }
1868
+ const hasMain = !!best && best.length >= 3;
1869
+ const pathIds = new Set((best ?? []).map((s) => s.node.id));
1870
+ // Where each spine node calls the NEXT hop (best[i+1].edge is the edge from
1871
+ // best[i] → best[i+1]; its line is the call site inside best[i]'s body). Lets
1872
+ // the assembler window an oversize spine method to the call instead of dumping it.
1873
+ const spineCallSites = new Map();
1874
+ if (best)
1875
+ for (let i = 0; i < best.length - 1; i++) {
1876
+ const ln = best[i + 1]?.edge?.line;
1877
+ if (ln && ln > 0 && !spineCallSites.has(best[i].node.id))
1878
+ spineCallSites.set(best[i].node.id, ln);
1879
+ }
1880
+ // Dynamic-boundary scan (#687) — fires ONLY when the flow the agent
1881
+ // asked about did not fully connect: some token resolved to nodes but
1882
+ // none of them sit on the main chain (or there is no chain at all). A
1883
+ // healthy flow skips this entirely. Scan order: the chain's dead end
1884
+ // first (where the partial flow stops), then the disconnected symbols,
1885
+ // agent-specific (unique-named) ones first.
1886
+ let boundaryText = '';
1887
+ {
1888
+ const uncovered = [];
1889
+ if (!hasMain) {
1890
+ // No rendered chain — but a 2-node chain still CONNECTS its two
1891
+ // endpoints (e.g. via one synthesized hop, surfaced below as a
1892
+ // dynamic-dispatch link). Only nodes off that short chain are
1893
+ // unexplained breaks worth scanning.
1894
+ for (const n of named.values())
1895
+ if (!pathIds.has(n.id))
1896
+ uncovered.push(n);
1897
+ }
1898
+ else {
1899
+ for (const ids of tokenNodes.values()) {
1900
+ if (ids.length === 0 || ids.some((id) => pathIds.has(id)))
1901
+ continue;
1902
+ for (const id of ids) {
1903
+ const n = named.get(id);
1904
+ if (n)
1905
+ uncovered.push(n);
1906
+ }
1907
+ }
1908
+ }
1909
+ if (uncovered.length > 0) {
1910
+ const scanList = [];
1911
+ if (hasMain)
1912
+ scanList.push(best[best.length - 1].node);
1913
+ scanList.push(...uncovered.sort((a, b) => (uniqueNamedNodeIds.has(b.id) ? 1 : 0) - (uniqueNamedNodeIds.has(a.id) ? 1 : 0)));
1914
+ boundaryText = this.buildDynamicBoundaries(cg, scanList, named);
1915
+ }
1916
+ }
1917
+ // Interface/registry-dispatch announcement (extends #687 to GRAPH-visible
1918
+ // polymorphism). A method the agent NAMED that resolves to a large same-name
1919
+ // family AND did not land on the main chain is almost always a runtime
1920
+ // dispatch (plugin/strategy/handler interface): the concrete target is chosen
1921
+ // at runtime from N implementations, so no single static edge is the answer.
1922
+ // The body-scan above can't see this — `nodeType.execute()` is textually an
1923
+ // ordinary call; the polymorphism lives in the graph (implements edges), so
1924
+ // detect it there. Fires ONLY for an uncovered named token; a connected flow
1925
+ // stays silent.
1926
+ let polyText = '';
1927
+ {
1928
+ const POLY_MIN_FAMILY = 8; // smaller families are overload sets, not dispatch
1929
+ const polyCands = [];
1930
+ for (const [t, fam] of tokenFamily) {
1931
+ if (fam.length < POLY_MIN_FAMILY)
1932
+ continue;
1933
+ const ids = tokenNodes.get(t) || [];
1934
+ if (ids.some((id) => pathIds.has(id)))
1935
+ continue; // covered by the flow — silent
1936
+ polyCands.push({ token: t, family: fam });
1937
+ }
1938
+ if (polyCands.length)
1939
+ polyText = this.buildPolymorphicBoundaries(cg, polyCands, named);
1940
+ }
1941
+ // Supplementary: dynamic-dispatch (synthesized) edges incident to a named
1942
+ // symbol (incl. the non-callable CONSTANT endpoints in `dynNamed`) — the
1943
+ // indirect hops an agent would otherwise grep/Read to reconstruct ("where do
1944
+ // the appended `validators` actually run?"). Surfaced even when the OTHER end
1945
+ // wasn't named. The skip drops a hop already in the rendered main chain; a
1946
+ // 2-node chain renders nothing (hasMain false) so a direct named→named synth
1947
+ // hop still surfaces — too short for Flow, but #687-visible here.
1948
+ const synthLines = collectSynthLinks(hasMain ? (e) => pathIds.has(e.source) && pathIds.has(e.target) : null);
1949
+ if (!hasMain && synthLines.length === 0 && !boundaryText && !polyText)
1950
+ return EMPTY;
1951
+ const out = [];
1952
+ if (hasMain) {
1953
+ out.push('**Flow (call path among the symbols you queried)**', '');
1954
+ for (let i = 0; i < best.length; i++) {
1955
+ const step = best[i];
1956
+ if (step.edge) {
1957
+ const sy = this.synthEdgeNote(step.edge);
1958
+ out.push(` ↓ ${sy ? sy.compact : step.edge.kind}`);
1959
+ }
1960
+ out.push(`${i + 1}. ${step.node.name} (${step.node.filePath}:${step.node.startLine})`);
1961
+ }
1962
+ out.push('');
1963
+ }
1964
+ if (synthLines.length) {
1965
+ out.push('**Dynamic-dispatch links among your symbols**', '(synthesized — the indirect hops grep/Read would reconstruct; the `@file:line` is the wiring site)', '', ...synthLines, '');
1966
+ }
1967
+ if (boundaryText)
1968
+ out.push(boundaryText);
1969
+ if (polyText)
1970
+ out.push(polyText);
1971
+ out.push('> Full source for these symbols is below — the call flow among them, followed by their bodies.', '');
1972
+ // namedNodeIds = every callable the agent explicitly named (a superset of
1973
+ // the spine). A file holding one is something the agent asked to SEE, so it
1974
+ // must keep full source even if it's an off-spine polymorphic sibling — the
1975
+ // agent named `getResponseWithInterceptorChain` / `SQLCompiler.execute_sql`
1976
+ // as the mechanism, not as an interchangeable leaf. See the skeleton gate.
1977
+ return { text: out.join('\n'), pathNodeIds: pathIds, namedNodeIds: new Set([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites };
1978
+ }
1979
+ catch {
1980
+ return EMPTY;
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Dynamic-boundary surfacing (#687): when the flow among the agent's named
1985
+ * symbols does not fully connect, scan the disconnected symbols' bodies for
1986
+ * dynamic-dispatch sites (computed member calls, getattr, reflection, typed
1987
+ * message buses, runtime-keyed emits) and ANNOUNCE the boundary — the exact
1988
+ * site, the form, and (when a key is statically visible) candidate targets —
1989
+ * instead of guessing edges. The answer to "how does A reach B" when no
1990
+ * static path exists IS the dispatch site: that's where the flow continues
1991
+ * at runtime. Query-time, deterministic, zero graph mutation; a fully
1992
+ * connected flow never reaches this method.
1993
+ */
1994
+ buildDynamicBoundaries(cg, scanList, named) {
1995
+ const MAX_NOTES = 4; // boundary bullets per explore
1996
+ const MAX_SCAN = 8; // bodies scanned
1997
+ const MAX_TOTAL_CHARS = 200_000;
1998
+ let projectRoot;
1999
+ try {
2000
+ projectRoot = cg.getProjectRoot();
2001
+ }
2002
+ catch {
2003
+ return '';
2004
+ }
2005
+ const notes = [];
2006
+ const seenNode = new Set();
2007
+ const seenSite = new Set();
2008
+ let scanned = 0, charsScanned = 0;
2009
+ for (const node of scanList) {
2010
+ if (notes.length >= MAX_NOTES || scanned >= MAX_SCAN || charsScanned > MAX_TOTAL_CHARS)
2011
+ break;
2012
+ if (seenNode.has(node.id) || !node.startLine || !node.endLine)
2013
+ continue;
2014
+ seenNode.add(node.id);
2015
+ const absPath = (0, utils_1.validatePathWithinRoot)(projectRoot, node.filePath);
2016
+ if (!absPath || !(0, fs_1.existsSync)(absPath))
2017
+ continue;
2018
+ let content;
2019
+ try {
2020
+ content = (0, fs_1.readFileSync)(absPath, 'utf-8');
2021
+ }
2022
+ catch {
2023
+ continue;
2024
+ }
2025
+ const body = content.split('\n').slice(node.startLine - 1, node.endLine).join('\n');
2026
+ scanned++;
2027
+ charsScanned += body.length;
2028
+ for (const m of (0, dynamic_boundaries_1.scanDynamicDispatch)(body, node.language || '', node.startLine)) {
2029
+ if (notes.length >= MAX_NOTES)
2030
+ break;
2031
+ const siteKey = `${node.filePath}:${m.line}:${m.form}`;
2032
+ if (seenSite.has(siteKey))
2033
+ continue;
2034
+ seenSite.add(siteKey);
2035
+ const more = m.moreSites ? ` (+${m.moreSites} more such site${m.moreSites > 1 ? 's' : ''} in this body)` : '';
2036
+ notes.push(`- \`${node.name}\` (${node.filePath}:${m.line}) — ${m.label}: \`${m.snippet}\`${more}`);
2037
+ if (m.key) {
2038
+ const cand = this.boundaryCandidates(cg, m.key, !!m.keyIsType, named, node.id);
2039
+ if (cand)
2040
+ notes.push(` ${cand}`);
2041
+ }
2042
+ }
2043
+ }
2044
+ if (notes.length === 0)
2045
+ return '';
2046
+ return [
2047
+ '**Dynamic boundaries (the static path ends at runtime dispatch)**',
2048
+ '',
2049
+ ...notes,
2050
+ '',
2051
+ '> These sites choose their call target at runtime (registry / bus / reflection) — the site shown IS where the flow continues. To follow it, run codegraph_explore or codegraph_node on a candidate; source for the sites above is included below.',
2052
+ '',
2053
+ ].join('\n');
2054
+ }
2055
+ /**
2056
+ * Interface/registry-dispatch announcement — #687 extended to GRAPH-visible
2057
+ * polymorphism (the body-scan can't see it: `nodeType.execute()` is textually
2058
+ * an ordinary call; the polymorphism lives in the `implements`/`extends` edges).
2059
+ *
2060
+ * A method the agent named that resolves to a large same-name family whose
2061
+ * definers overwhelmingly implement/extend ONE supertype is a runtime dispatch:
2062
+ * the concrete target is chosen at runtime from N implementations, so no single
2063
+ * static edge is "the answer" — the implementations ARE the continuations. We
2064
+ * announce the supertype, its TRUE implementer count, and a few concrete targets,
2065
+ * then steer to codegraph_explore. Graph-only, query-time, zero mutation; the
2066
+ * caller fires it ONLY for an UNCOVERED named token, so a connected flow is silent.
2067
+ *
2068
+ * Robust to FTS sampling bias: the same-name family is a capped FTS sample that
2069
+ * over-represents whatever FTS ranks first (n8n: DB `TableOperation.execute`
2070
+ * outnumbered `INodeType.execute` in the sample 7:6 even though INodeType has
2071
+ * 611 implementers vs a handful). So candidate supertypes are ranked by their
2072
+ * TRUE graph-wide implementer count, NOT their frequency in the sample.
2073
+ */
2074
+ buildPolymorphicBoundaries(cg, candidates, named) {
2075
+ const CLASSY = new Set(['class', 'struct', 'interface', 'trait', 'protocol', 'abstract']);
2076
+ const MIN_IMPL = 8; // a supertype needs >= this many implementers to count as "polymorphic"
2077
+ const MIN_SUPPORT = 2; // >= this many sampled definers must share the supertype (ties it to the token)
2078
+ const SAMPLE = 40; // family members inspected per token
2079
+ const MAX_NOTES = 3;
2080
+ const rel = (p) => p.replace(/\\/g, '/');
2081
+ const containerOf = (m) => {
2082
+ try {
2083
+ const ce = cg.getIncomingEdges(m.id).find((e) => e.kind === 'contains');
2084
+ return ce ? cg.getNode(ce.source) : null;
2085
+ }
2086
+ catch {
2087
+ return null;
2088
+ }
2089
+ };
2090
+ const notes = [];
2091
+ const seenSuper = new Set();
2092
+ for (const { token, family } of candidates) {
2093
+ if (notes.length >= MAX_NOTES)
2094
+ break;
2095
+ // supertype id → how many sampled definers share it + a few example definers
2096
+ const supers = new Map();
2097
+ for (const m of family.slice(0, SAMPLE)) {
2098
+ const container = containerOf(m);
2099
+ if (!container || !CLASSY.has(container.kind))
2100
+ continue;
2101
+ let sups = [];
2102
+ try {
2103
+ sups = cg.getOutgoingEdges(container.id)
2104
+ .filter((e) => e.kind === 'implements' || e.kind === 'extends')
2105
+ .map((e) => { try {
2106
+ return cg.getNode(e.target);
2107
+ }
2108
+ catch {
2109
+ return null;
2110
+ } })
2111
+ .filter((n) => !!n && CLASSY.has(n.kind) && (n.name?.length || 0) >= 3);
2112
+ }
2113
+ catch { /* no supertypes — free function or unresolved */ }
2114
+ for (const s of sups) {
2115
+ const e = supers.get(s.id) || { node: s, count: 0, targets: [] };
2116
+ e.count++;
2117
+ if (e.targets.length < 6)
2118
+ e.targets.push(m);
2119
+ supers.set(s.id, e);
2120
+ }
2121
+ }
2122
+ // Pick the supertype with the most TRUE implementers (graph-wide), among
2123
+ // those genuinely shared by the token's definers.
2124
+ let best = null;
2125
+ for (const { node, count, targets } of supers.values()) {
2126
+ if (count < MIN_SUPPORT)
2127
+ continue;
2128
+ let impl = 0;
2129
+ try {
2130
+ impl = cg.getIncomingEdges(node.id).filter((e) => e.kind === 'implements' || e.kind === 'extends').length;
2131
+ }
2132
+ catch { /* leave 0 — gated out below */ }
2133
+ if (impl < MIN_IMPL)
2134
+ continue;
2135
+ if (!best || impl > best.impl)
2136
+ best = { node, impl, targets };
2137
+ }
2138
+ if (!best || seenSuper.has(best.node.id))
2139
+ continue;
2140
+ seenSuper.add(best.node.id);
2141
+ const namedNames = new Set([...named.values()].map((n) => n.name));
2142
+ const eg = best.targets.slice(0, 4).map((m) => {
2143
+ const cont = containerOf(m);
2144
+ const disp = cont ? `${cont.name}.${m.name}` : (m.qualifiedName || m.name);
2145
+ const mark = cont && namedNames.has(cont.name) ? ' ← you named this' : '';
2146
+ return `\`${disp}\` (${rel(m.filePath)}:${m.startLine})${mark}`;
2147
+ });
2148
+ const more = best.impl > eg.length ? ` +${best.impl - eg.length} more` : '';
2149
+ notes.push(`- \`${token}\` → runtime dispatch to **${best.impl}** types implementing \`${best.node.name}\` — the static path ends here, the target is chosen at runtime. e.g. ${eg.join(', ')}${more}`);
2150
+ }
2151
+ if (notes.length === 0)
2152
+ return '';
2153
+ return [
2154
+ '**Interface dispatch (a named method has many implementations)**',
2155
+ '',
2156
+ ...notes,
2157
+ '',
2158
+ '> The method above is dispatched at runtime to one of the listed implementations (a registry / plugin / strategy interface) — there is no single static caller→callee edge; the implementations ARE the continuations. To follow one, run codegraph_explore on a listed target.',
2159
+ '',
2160
+ ].join('\n');
2161
+ }
2162
+ /**
2163
+ * Shortlist candidate runtime targets for a dispatch key surfaced by
2164
+ * {@link buildDynamicBoundaries}. Exact conventional names first (`save` →
2165
+ * `onSave`/`handleSave`; `CreateCmd` → `CreateCmdHandler`), then FTS, with a
2166
+ * normalized-containment post-filter (FTS camel-splitting is fuzzier than a
2167
+ * candidate list should be). Symbols the agent already named sort first and
2168
+ * are marked — that's the "you were right, here's the wiring" case.
2169
+ */
2170
+ boundaryCandidates(cg, key, keyIsType, named, selfId) {
2171
+ const CALLABLE = new Set(['method', 'function', 'component', 'constructor', 'class']);
2172
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
2173
+ const keyNorm = norm(key);
2174
+ if (keyNorm.length < 3)
2175
+ return '';
2176
+ const cands = new Map();
2177
+ const consider = (n) => {
2178
+ if (!n || n.id === selfId || !CALLABLE.has(n.kind) || cands.has(n.id))
2179
+ return;
2180
+ const nameNorm = norm(n.name || '');
2181
+ if (nameNorm.length < 3)
2182
+ return;
2183
+ if (!nameNorm.includes(keyNorm) && !keyNorm.includes(nameNorm))
2184
+ return;
2185
+ cands.set(n.id, n);
2186
+ };
2187
+ const cap = key.charAt(0).toUpperCase() + key.slice(1);
2188
+ const probes = keyIsType
2189
+ ? [`${key}Handler`, key]
2190
+ : [key, `on${cap}`, `handle${cap}`, `${key}Handler`, `handle_${key}`];
2191
+ for (const p of probes) {
2192
+ try {
2193
+ for (const n of cg.getNodesByName(p))
2194
+ consider(n);
2195
+ }
2196
+ catch { /* exact probe miss is fine */ }
2197
+ }
2198
+ let raw = 0;
2199
+ try {
2200
+ const results = cg.searchNodes(key, { limit: 12 });
2201
+ raw = results.length;
2202
+ for (const r of results)
2203
+ consider(r.node);
2204
+ }
2205
+ catch { /* FTS syntax edge — exact probes already ran */ }
2206
+ if (cands.size === 0) {
2207
+ return raw >= 12 && key.length < 5 ? `key \`${key}\` is too generic to shortlist (${raw}+ matches)` : '';
2208
+ }
2209
+ // A constructor candidate duplicates its class: extractors emit ctors as
2210
+ // METHOD nodes named like the class (C#/Java `Foo::Foo`) — keep the class.
2211
+ const all = [...cands.values()];
2212
+ const classKey = new Set(all.filter((n) => n.kind === 'class').map((n) => `${n.name}|${n.filePath}`));
2213
+ const namedNames = new Set([...named.values()].map((n) => n.name));
2214
+ const isNamed = (n) => named.has(n.id) || namedNames.has(n.name); // the flow's named set holds callables only — transfer the mark to the class
2215
+ const list = all
2216
+ .filter((n) => !(n.kind !== 'class' && classKey.has(`${n.name}|${n.filePath}`)))
2217
+ .sort((a, b) => (isNamed(b) ? 1 : 0) - (isNamed(a) ? 1 : 0))
2218
+ .slice(0, 4)
2219
+ .map((n) => {
2220
+ // Typed-bus convention: the runtime target is the candidate class's
2221
+ // Handle/Execute/Consume method — name the exact node, not just the class.
2222
+ let display = n.qualifiedName || n.name;
2223
+ let at = `${n.filePath}:${n.startLine}`;
2224
+ if (keyIsType && n.kind === 'class') {
2225
+ try {
2226
+ const HANDLER_METHODS = /^(handle|handleAsync|execute|executeAsync|consume|consumeAsync|run|__invoke)$/i;
2227
+ const method = cg.getOutgoingEdges(n.id)
2228
+ .filter((e) => e.kind === 'contains')
2229
+ .map((e) => { try {
2230
+ return cg.getNode(e.target);
2231
+ }
2232
+ catch {
2233
+ return null;
2234
+ } })
2235
+ .find((c) => !!c && c.kind === 'method' && HANDLER_METHODS.test(c.name));
2236
+ if (method) {
2237
+ display = `${n.name}.${method.name}`;
2238
+ at = `${method.filePath}:${method.startLine}`;
2239
+ }
2240
+ }
2241
+ catch { /* class without resolvable members — show the class itself */ }
2242
+ }
2243
+ return `\`${display}\` (${at})${isNamed(n) ? ' ← you named this' : ''}`;
2244
+ });
2245
+ return `candidates for key \`${key}\`: ${list.join(', ')}`;
2246
+ }
2247
+ /**
2248
+ * Compact "blast radius" for the entry symbols of an explore result: who
2249
+ * depends on each (callers) and which test files cover it — LOCATIONS ONLY,
2250
+ * no source, so the agent knows what to update / re-verify before editing
2251
+ * without reaching for a separate impact call. Always-on, but skips symbols
2252
+ * that have no dependents (nothing to warn about), and returns '' when none
2253
+ * qualify so a leaf-only exploration stays clean.
2254
+ */
2255
+ buildBlastRadiusSection(cg, subgraph) {
2256
+ const ROOT_CAP = 5; // only the symbols the query actually targeted
2257
+ const FILE_CAP = 4; // caller files listed per symbol before "+N more"
2258
+ const MEANINGFUL = new Set([
2259
+ 'function', 'method', 'class', 'interface', 'struct', 'trait', 'protocol',
2260
+ 'enum', 'type_alias', 'component', 'constant', 'variable', 'property', 'field',
2261
+ ]);
2262
+ const rel = (p) => p.replace(/\\/g, '/');
2263
+ const roots = subgraph.roots
2264
+ .map((id) => subgraph.nodes.get(id))
2265
+ .filter((n) => !!n && MEANINGFUL.has(n.kind))
2266
+ .slice(0, ROOT_CAP);
2267
+ if (roots.length === 0)
2268
+ return '';
2269
+ const entries = [];
2270
+ for (const root of roots) {
2271
+ let callers = [];
2272
+ try {
2273
+ callers = cg.getCallers(root.id);
2274
+ }
2275
+ catch { /* skip this root */ }
2276
+ const seen = new Set();
2277
+ const uniq = [];
2278
+ for (const c of callers) {
2279
+ if (c?.node && !seen.has(c.node.id)) {
2280
+ seen.add(c.node.id);
2281
+ uniq.push(c.node);
2282
+ }
2283
+ }
2284
+ if (uniq.length === 0)
2285
+ continue; // no blast radius → nothing to flag
2286
+ const callerFiles = [...new Set(uniq.map((n) => rel(n.filePath)))];
2287
+ const testFiles = callerFiles.filter((f) => (0, query_utils_1.isTestFile)(f));
2288
+ const nonTest = callerFiles.filter((f) => !(0, query_utils_1.isTestFile)(f));
2289
+ const shown = nonTest.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ');
2290
+ const more = nonTest.length > FILE_CAP ? ` +${nonTest.length - FILE_CAP} more` : '';
2291
+ const where = nonTest.length > 0 ? ` in ${shown}${more}` : '';
2292
+ const tests = testFiles.length > 0
2293
+ ? `; tests: ${testFiles.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ')}${testFiles.length > FILE_CAP ? ` +${testFiles.length - FILE_CAP}` : ''}`
2294
+ : '; ⚠️ no covering tests found';
2295
+ entries.push(`- \`${root.name}\` (${rel(root.filePath)}:${root.startLine}) — ${uniq.length} caller${uniq.length === 1 ? '' : 's'}${where}${tests}`);
2296
+ }
2297
+ if (entries.length === 0)
2298
+ return '';
2299
+ return [
2300
+ '**Blast radius — what depends on these (update/verify before editing)**',
2301
+ '',
2302
+ ...entries,
2303
+ '',
2304
+ ].join('\n');
2305
+ }
2306
+ /**
2307
+ * Graph-connectivity relevance via Random-Walk-with-Restart (personalized
2308
+ * PageRank) from the query's matched SEED nodes over the call/reference graph.
2309
+ *
2310
+ * This is the ranking signal text search (FTS/bm25) CANNOT provide, and it's
2311
+ * codegraph's home turf: relevance by STRUCTURE, not words. A file whose
2312
+ * symbols are call-connected to the matched cluster accrues walk mass and
2313
+ * ranks high; a lone TEXT match — e.g. `LensSwitcher.swift` matched the word
2314
+ * "switch" from `switchOrganization`, but calls none of `setUser`/`fetchUser`
2315
+ * — gets only its own restart probability and ranks ~0. Immune to the
2316
+ * tokenization trap that fools term matching, deterministic, no embeddings.
2317
+ *
2318
+ * Undirected adjacency (reachability both ways), restart α=0.25 to the seeds,
2319
+ * power iteration to convergence. Bounded to the already-relevant subgraph, so
2320
+ * it's a few hundred nodes × ~25 iterations — negligible cost.
2321
+ */
2322
+ computeGraphRelevance(nodeIds, edges, seedIds) {
2323
+ const out = new Map();
2324
+ const n = nodeIds.length;
2325
+ if (n === 0)
2326
+ return out;
2327
+ const idx = new Map();
2328
+ for (let i = 0; i < n; i++)
2329
+ idx.set(nodeIds[i], i);
2330
+ const RANK_EDGES = new Set([
2331
+ 'calls', 'references', 'extends', 'implements', 'overrides',
2332
+ 'instantiates', 'returns', 'type_of', 'imports',
2333
+ ]);
2334
+ const adj = Array.from({ length: n }, () => []);
2335
+ for (const e of edges) {
2336
+ if (!RANK_EDGES.has(e.kind))
2337
+ continue;
2338
+ const i = idx.get(e.source);
2339
+ const j = idx.get(e.target);
2340
+ if (i === undefined || j === undefined || i === j)
2341
+ continue;
2342
+ adj[i].push(j);
2343
+ adj[j].push(i); // undirected — reachable either direction
2344
+ }
2345
+ // Restart vector: uniform over seeds present in the candidate set. (Falls
2346
+ // back to uniform-over-all if no seed landed in the set, so we never return
2347
+ // all-zero.)
2348
+ const r = new Array(n).fill(0);
2349
+ let rsum = 0;
2350
+ for (const id of seedIds) {
2351
+ const i = idx.get(id);
2352
+ if (i !== undefined) {
2353
+ r[i] = 1;
2354
+ rsum += 1;
2355
+ }
2356
+ }
2357
+ if (rsum === 0) {
2358
+ for (let i = 0; i < n; i++)
2359
+ r[i] = 1;
2360
+ rsum = n;
2361
+ }
2362
+ for (let i = 0; i < n; i++)
2363
+ r[i] /= rsum;
2364
+ const alpha = 0.25;
2365
+ let s = r.slice();
2366
+ for (let iter = 0; iter < 25; iter++) {
2367
+ const next = new Array(n).fill(0);
2368
+ for (let i = 0; i < n; i++) {
2369
+ const si = s[i];
2370
+ if (si === 0)
2371
+ continue;
2372
+ const d = adj[i].length;
2373
+ if (d === 0) {
2374
+ next[i] += si;
2375
+ continue;
2376
+ } // dangling: keep its mass
2377
+ const share = si / d;
2378
+ for (const j of adj[i])
2379
+ next[j] += share;
2380
+ }
2381
+ for (let i = 0; i < n; i++)
2382
+ s[i] = (1 - alpha) * next[i] + alpha * r[i];
2383
+ }
2384
+ for (let i = 0; i < n; i++)
2385
+ out.set(nodeIds[i], s[i]);
2386
+ return out;
2387
+ }
2388
+ /**
2389
+ * Handle codegraph_explore — deep exploration in a single call
2390
+ *
2391
+ * Strategy: find relevant symbols via graph traversal, group by file,
2392
+ * then read contiguous file sections covering all symbols per file.
2393
+ * This replaces multiple codegraph_node + Read calls.
2394
+ *
2395
+ * Output size is adaptive to project file count via
2396
+ * `getExploreOutputBudget` — see #185 for why a fixed 35k cap was a
2397
+ * tax on small projects while earning its keep on large ones.
2398
+ */
2399
+ async handleExplore(args) {
2400
+ const rawQuery = this.validateString(args.query, 'query');
2401
+ if (typeof rawQuery !== 'string')
2402
+ return rawQuery;
2403
+ // One normalization point so the flow-builder, relevance search, and
2404
+ // ranking all see the same canonical spelling (Erlang `mod:fn/arity`).
2405
+ const query = normalizeQuerySpelling(rawQuery);
2406
+ const cg = this.getCodeGraph(args.projectPath);
2407
+ const projectRoot = cg.getProjectRoot();
2408
+ // Resolve adaptive output budget from project size. Falls back to the
2409
+ // largest-tier defaults if stats aren't available, which preserves
2410
+ // pre-#185 behavior for callers that hit the rare stats failure.
2411
+ let budget;
2412
+ try {
2413
+ budget = getExploreOutputBudget(cg.getStats().fileCount);
2414
+ }
2415
+ catch {
2416
+ budget = getExploreOutputBudget(Infinity);
2417
+ }
2418
+ const maxFiles = (0, utils_1.clamp)(args.maxFiles || budget.defaultMaxFiles, 1, 20);
2419
+ // Step 1: Find relevant context with generous parameters.
2420
+ // Use a large maxNodes budget — explore has its own 35k char output limit
2421
+ // that prevents context bloat, so more nodes just means better coverage
2422
+ // across entry points (especially for large files like Svelte components).
2423
+ const subgraph = await cg.findRelevantContext(query, {
2424
+ searchLimit: 8,
2425
+ traversalDepth: 3,
2426
+ maxNodes: 200,
2427
+ minScore: 0.2,
2428
+ });
2429
+ if (subgraph.nodes.size === 0) {
2430
+ return this.textResult(`No relevant code found for "${query}"`);
2431
+ }
2432
+ // Graph-aware glue: findRelevantContext builds the subgraph from name/text
2433
+ // search, so a method that BRIDGES named symbols — e.g. App.tsx's
2434
+ // triggerRender, which calls the named triggerUpdate — is never a search hit
2435
+ // and gets missed, forcing the agent to Read the file to trace it. Pull in
2436
+ // the callers/callees of the entry (root) nodes, but ONLY those that live in
2437
+ // files the subgraph already surfaces (where the agent reads to fill gaps),
2438
+ // so we add wiring without dragging in unrelated files. These get an
2439
+ // importance boost below so they survive the per-file cluster budget.
2440
+ const glueNodeIds = new Set();
2441
+ const subgraphFiles = new Set();
2442
+ for (const n of subgraph.nodes.values())
2443
+ subgraphFiles.add(n.filePath);
2444
+ const GLUE_NODE_CAP = 60;
2445
+ for (const rootId of subgraph.roots) {
2446
+ if (glueNodeIds.size >= GLUE_NODE_CAP)
2447
+ break;
2448
+ let neighbors = [];
2449
+ try {
2450
+ neighbors = [
2451
+ ...cg.getCallers(rootId).map(c => c.node),
2452
+ ...cg.getCallees(rootId).map(c => c.node),
2453
+ ];
2454
+ }
2455
+ catch {
2456
+ continue;
2457
+ }
2458
+ for (const nb of neighbors) {
2459
+ if (glueNodeIds.size >= GLUE_NODE_CAP)
2460
+ break;
2461
+ if (subgraph.nodes.has(nb.id))
2462
+ continue;
2463
+ if (!subgraphFiles.has(nb.filePath))
2464
+ continue;
2465
+ subgraph.nodes.set(nb.id, nb);
2466
+ glueNodeIds.add(nb.id);
2467
+ }
2468
+ }
2469
+ // Named-symbol seeding: findRelevantContext is an FTS/text rank, so a query
2470
+ // that's a BAG of symbol names skewed toward one phase (Alamofire: 5 build
2471
+ // terms, each a high-frequency name, vs 3 validate terms) lets the
2472
+ // lower-frequency names fall below the search cut — their definitions, and
2473
+ // whole files (Validation.swift), never get gathered, so they can never
2474
+ // render and the agent Reads them. Resolve EACH named token to its
2475
+ // substantive definition (skip empty stubs + test files, same relevance the
2476
+ // trace endpoint picker uses) and inject it as an entry, so every symbol the
2477
+ // agent explicitly named is in the subgraph and its file is scored.
2478
+ const namedSeedIds = new Set();
2479
+ // The subset of named seeds that earns the named-FIRST sort tier. We still
2480
+ // SEED every ≤3-def name (so RWR / flow ranking is unchanged), but only the
2481
+ // most-substantive def is tiered — a bare name's unrelated namesakes (Go's
2482
+ // `NewClient` = real client + test fake + xds pool) must not fill the tier
2483
+ // and crowd out the real answer file (grpc's `dialoptions.go`). Corroborated
2484
+ // overloads (the query also named the type) all earn it. (#1064)
2485
+ const tierSeedIds = new Set();
2486
+ {
2487
+ const FILE_EXT = /\.(?:java|kt|kts|ts|tsx|js|jsx|mjs|cjs|cs|py|go|rb|php|swift|rs|cpp|cc|cxx|c|h|hpp|scala|lua|dart|vue|svelte|astro|erl|hrl)$/i;
2488
+ const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
2489
+ const isTestPath = (p) => /(^|\/)(tests?|specs?|__tests__|testdata|mocks?|fixtures?)\//i.test(p) || /\.(test|spec)\.[a-z]+$/i.test(p);
2490
+ const bodyLines = (n) => Math.max(0, (n.endLine ?? n.startLine) - n.startLine);
2491
+ const callerCount = (n) => { try {
2492
+ return cg.getCallers(n.id).length;
2493
+ }
2494
+ catch {
2495
+ return 0;
2496
+ } };
2497
+ const tokens = [...new Set(query.split(/[\s,()[\]]+/)
2498
+ .map((t) => t.replace(FILE_EXT, '').trim())
2499
+ .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t)))].slice(0, 16);
2500
+ // PascalCase tokens in the query are type/file disambiguators — when the
2501
+ // agent writes "DataRequest task validate", the `task`/`validate` it wants
2502
+ // are DataRequest's, NOT the same-named overloads in Validation.swift /
2503
+ // Concurrency.swift / the abstract base. Used below to bias overloaded
2504
+ // names toward the file/class the query also names. EXCLUDE the project
2505
+ // name (a PascalCase token a user naturally includes) — it names the whole
2506
+ // repo, so biasing toward it just pulls overloads to whichever stack
2507
+ // embeds it, re-burying the rest (#720).
2508
+ const projectNameTokens = cg.getProjectNameTokens();
2509
+ const typeTokens = tokens.filter((o) => /^[A-Z][A-Za-z0-9]{3,}/.test(o) && !projectNameTokens.has((0, query_utils_1.normalizeNameToken)(o)));
2510
+ const inNamedContext = (n) => typeTokens.some((ct) => {
2511
+ const lc = ct.toLowerCase();
2512
+ return n.filePath.toLowerCase().includes(lc) || n.qualifiedName.toLowerCase().includes(lc);
2513
+ });
2514
+ // NL-stopword guard: this seeding treats every token as "a symbol the
2515
+ // agent named", but explore also takes natural-language questions, whose
2516
+ // ordinary English words collide with real callables — "…check the latest
2517
+ // version…" exact-matched a lone `check()` method, which then earned the
2518
+ // named-FIRST sort tier and displaced the corroborated answer files from
2519
+ // the whole render budget (the agent fell back to Read). A shape-precise
2520
+ // token (camelCase, PascalCase, snake_case, qualified) is an unambiguous
2521
+ // symbol reference and seeds unconditionally; a BARE lowercase word seeds
2522
+ // only where the query corroborates the file — another query token is
2523
+ // itself a symbol defined in that same file (the "check drain fire"
2524
+ // sibling-bag case), which an incidental English-word collision never is.
2525
+ const lcTokens = new Set(tokens.map((x) => x.toLowerCase()));
2526
+ const isPreciseToken = (x) => /[._$]|::|\//.test(x) || /[a-z][A-Z]/.test(x) || /^[A-Z]/.test(x);
2527
+ const fileNameSets = new Map();
2528
+ const coNamedInFile = (t, fp) => {
2529
+ let names = fileNameSets.get(fp);
2530
+ if (!names) {
2531
+ names = new Set();
2532
+ try {
2533
+ for (const n of cg.getNodesInFile(fp))
2534
+ names.add(n.name.toLowerCase());
2535
+ }
2536
+ catch { /* unreadable file entry — treat as uncorroborated */ }
2537
+ fileNameSets.set(fp, names);
2538
+ }
2539
+ const self = t.toLowerCase();
2540
+ for (const o of lcTokens) {
2541
+ if (o !== self && names.has(o))
2542
+ return true;
2543
+ }
2544
+ return false;
2545
+ };
2546
+ for (const t of tokens) {
2547
+ // Enumerate ALL defs of a bare token via the direct index, not FTS — a
2548
+ // 50+-overload name (tokio `poll`) ranks the wanted def (`Harness::poll`)
2549
+ // below the FTS cut, so findAllSymbols would never see it and the
2550
+ // type-token bias below couldn't pick the harness.rs one. (Same fix as
2551
+ // codegraph_node's findSymbolMatches.) Qualified tokens keep findAllSymbols.
2552
+ const isQual = /[.\/]|::/.test(t);
2553
+ const raw = isQual ? this.findAllSymbols(cg, t).nodes : cg.getNodesByName(t);
2554
+ let cands = raw
2555
+ .filter((n) => CALLABLE.has(n.kind) && !isTestPath(n.filePath))
2556
+ .sort((a, b) => (bodyLines(b) > 1 ? 1 : 0) - (bodyLines(a) > 1 ? 1 : 0) || bodyLines(b) - bodyLines(a));
2557
+ // Bare lowercase words only seed defs their query-siblings corroborate
2558
+ // (see the NL-stopword guard above). Filtering CANDS (not picks) applies
2559
+ // the guard uniformly to both branches below, including the >3-def
2560
+ // single-pick fallback — an uncorroborated bare `run` must not tier its
2561
+ // most-substantive namesake any more than a 1-def `check` may.
2562
+ if (!isPreciseToken(t)) {
2563
+ cands = cands.filter((n) => coNamedInFile(t, n.filePath));
2564
+ }
2565
+ // A specific name (<=3 defs) injects all its defs. An overloaded name
2566
+ // (`validate` = 10, `request` = 44) would flood the subgraph, so inject
2567
+ // only: the overloads whose file/class the query ALSO names (the agent
2568
+ // told us which one it wants — DataRequest's, not Validation.swift's),
2569
+ // capped; else fall back to the single most-substantive def. This is the
2570
+ // explore-side mirror of codegraph_node's overload disambiguation.
2571
+ let picks;
2572
+ let tierPicks; // subset that earns the named-first tier (#1064)
2573
+ if (cands.length <= 3) {
2574
+ picks = cands;
2575
+ // Centrality de-noise: tier the most-substantive def PLUS any co-named
2576
+ // def of comparable centrality (a real overload/wrapper — excalidraw's
2577
+ // `mutateElement` lives in mutateElement.ts, App.tsx AND Scene.ts, all
2578
+ // within ~2x callers). EXCLUDE a vastly-less-central namesake (Go's
2579
+ // `NewClient`: real client 492 callers vs xds-pool 11, test-fake 3 →
2580
+ // ratio <0.025) so it doesn't fill the tier and crowd out the answer.
2581
+ const counts = new Map(cands.map((c) => [c.id, callerCount(c)]));
2582
+ const maxCallers = Math.max(1, ...counts.values());
2583
+ tierPicks = cands.filter((c, i) => i === 0 || (counts.get(c.id) ?? 0) >= maxCallers * 0.25);
2584
+ }
2585
+ else {
2586
+ const ctx = cands.filter(inNamedContext);
2587
+ picks = ctx.length > 0 ? ctx.slice(0, 4) : cands.slice(0, 1);
2588
+ tierPicks = picks; // corroborated overloads (or the single fallback) all earn it
2589
+ }
2590
+ for (const n of picks) {
2591
+ if (!subgraph.nodes.has(n.id))
2592
+ subgraph.nodes.set(n.id, n);
2593
+ // Mark as a named seed EVEN IF the FTS gather already had it — being
2594
+ // "named by the agent" is independent of whether search happened to
2595
+ // surface it, and it drives the +50 score, the gate, and the
2596
+ // named-file sort below. (Previously only NEW injections were marked,
2597
+ // so a named symbol FTS already gathered never sorted to the top.)
2598
+ namedSeedIds.add(n.id);
2599
+ }
2600
+ for (const n of tierPicks)
2601
+ tierSeedIds.add(n.id);
2602
+ }
2603
+ }
2604
+ // Step 2: Group nodes by file, score by relevance
2605
+ const fileGroups = new Map();
2606
+ const entryNodeIds = new Set([...subgraph.roots, ...namedSeedIds]);
2607
+ // Build a set of nodes directly connected to entry points (depth 1)
2608
+ const connectedToEntry = new Set();
2609
+ for (const edge of subgraph.edges) {
2610
+ if (entryNodeIds.has(edge.source))
2611
+ connectedToEntry.add(edge.target);
2612
+ if (entryNodeIds.has(edge.target))
2613
+ connectedToEntry.add(edge.source);
2614
+ }
2615
+ // CHANGE SURFACE (#1064): a named method's signature types — its parameter
2616
+ // and return types — are part of what you'd edit to "add a parameter to X",
2617
+ // yet they can be lexically dissimilar to the query ("add a parameter to
2618
+ // NewClient" shares no words with `dialoptions.go`, which defines NewClient's
2619
+ // `DialOption`) and sit a hop away. COLLECT them here from each named-seed
2620
+ // callable's outgoing signature edges (full graph — the type is often not in
2621
+ // the subgraph); the decision to surface one is DEFERRED to the buried-rescue
2622
+ // pass below, which fires only when the type's file would otherwise be
2623
+ // dropped — so a well-connected type (excalidraw's element types, Alamofire's
2624
+ // `DataRequest` on a flow query) is left to rank on its own and never
2625
+ // displaces a flow-central file. Bounded: only the few named seeds, only the
2626
+ // types in their signatures.
2627
+ const CALLABLE_KINDS = new Set(['method', 'function', 'component', 'constructor']);
2628
+ const TYPE_KINDS = new Set(['class', 'struct', 'interface', 'trait', 'protocol', 'enum', 'type_alias']);
2629
+ const SIG_EDGE = new Set(['references', 'type_of', 'returns']);
2630
+ const changeSurfaceCandidates = [];
2631
+ const seenChangeSurface = new Set();
2632
+ for (const seedId of tierSeedIds) {
2633
+ const seedNode = subgraph.nodes.get(seedId);
2634
+ if (!seedNode || !CALLABLE_KINDS.has(seedNode.kind))
2635
+ continue;
2636
+ let outs = [];
2637
+ try {
2638
+ outs = cg.getOutgoingEdges(seedId);
2639
+ }
2640
+ catch {
2641
+ continue;
2642
+ }
2643
+ for (const e of outs) {
2644
+ if (!SIG_EDGE.has(e.kind))
2645
+ continue;
2646
+ const tgt = cg.getNode(e.target);
2647
+ if (!tgt || !TYPE_KINDS.has(tgt.kind) || namedSeedIds.has(tgt.id))
2648
+ continue;
2649
+ if (seenChangeSurface.has(tgt.id))
2650
+ continue;
2651
+ seenChangeSurface.add(tgt.id);
2652
+ changeSurfaceCandidates.push(tgt);
2653
+ }
2654
+ }
2655
+ for (const node of subgraph.nodes.values()) {
2656
+ // Skip import/export nodes — they add noise without information
2657
+ if (node.kind === 'import' || node.kind === 'export')
2658
+ continue;
2659
+ // SECURITY (#383): never render the on-disk source of a config-leaf
2660
+ // (Spring application.{yml,properties} key) — its line is `key = <secret>`,
2661
+ // so whole-file/cluster rendering here would push secrets into context
2662
+ // unbidden. The key still appears in the flow/symbol listing above.
2663
+ if ((0, utils_1.isConfigLeafNode)(node))
2664
+ continue;
2665
+ const group = fileGroups.get(node.filePath) || { nodes: [], score: 0 };
2666
+ group.nodes.push(node);
2667
+ // Score: a NAMED-SEED node (a symbol the agent named that FTS missed, now
2668
+ // injected) is worth far more than a mere reference — its file is where the
2669
+ // answer lives. Without this, an incidental file that name-drops the flow
2670
+ // (Combine.swift references request/task → score 23 from connected nodes)
2671
+ // outranks the file that DEFINES a named symbol (Validation.swift's
2672
+ // `validate` → 10) and steals its render slot. Definition ≫ reference.
2673
+ if (namedSeedIds.has(node.id)) {
2674
+ group.score += 50;
2675
+ }
2676
+ else if (entryNodeIds.has(node.id)) {
2677
+ group.score += 10;
2678
+ }
2679
+ else if (connectedToEntry.has(node.id)) {
2680
+ group.score += 3;
2681
+ }
2682
+ else {
2683
+ group.score += 1;
2684
+ }
2685
+ fileGroups.set(node.filePath, group);
2686
+ }
2687
+ // Only include files that have entry points or nodes directly connected to entry points
2688
+ let relevantFiles = [...fileGroups.entries()].filter(([, group]) => group.score >= 3);
2689
+ // Extract query terms for relevance checking
2690
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
2691
+ // Test/spec/icon/i18n file detector — used both for the pre-sort hard
2692
+ // filter (tiny tier) and the comparator deprioritization (all tiers).
2693
+ const isLowValue = (p) => {
2694
+ const lp = p.toLowerCase();
2695
+ return (/\/(tests?|__tests?__|spec)\//.test(lp) ||
2696
+ /_test\.go$/.test(lp) ||
2697
+ /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
2698
+ /_test\.py$/.test(lp) ||
2699
+ /_spec\.rb$/.test(lp) ||
2700
+ /_test\.rb$/.test(lp) ||
2701
+ /\.(test|spec)\.[jt]sx?$/.test(lp) ||
2702
+ /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
2703
+ /(tests?|spec)\.cs$/.test(lp) ||
2704
+ /tests?\.swift$/.test(lp) ||
2705
+ /_test\.dart$/.test(lp) ||
2706
+ /\bicons?\b/.test(lp) ||
2707
+ /\bi18n\b/.test(lp));
2708
+ };
2709
+ // Hard-exclude test/spec files (ALL tiers, not just tiny). One slipped test
2710
+ // file dominates the per-file budget on small repos (cobra's `command_test.go`
2711
+ // displaced `args.go`) AND wastes budget on large ones (Django's
2712
+ // `custom_lookups/tests.py` ate ~2.3 KB of the 28 KB cap, crowding out the
2713
+ // SQLCompiler mechanism the agent then Read). A test file almost never answers
2714
+ // an architecture question. Skip when the query itself is about tests — the
2715
+ // legitimate "explore the tests" case — and only cut if ≥2 non-test candidates
2716
+ // remain (else tests are the only signal for this area).
2717
+ {
2718
+ const queryMentionsTests = /\b(test|tests|testing|spec|verify|verifies)\b/i.test(query);
2719
+ if (!queryMentionsTests) {
2720
+ const nonLow = relevantFiles.filter(([p]) => !isLowValue(p));
2721
+ if (nonLow.length >= 2) {
2722
+ relevantFiles = nonLow;
2723
+ }
2724
+ }
2725
+ }
2726
+ // Secondary signal: how many DISTINCT query terms each file matches (path +
2727
+ // symbol names). Kept only as a tiebreak — the PRIMARY relevance is graph
2728
+ // connectivity below. (Term counting alone tied the real central file with
2729
+ // incidental same-word matches; it's a weak text signal, not the ranker.)
2730
+ const uniqueQueryTerms = [...new Set(queryTerms)].filter(t => t.length >= 3);
2731
+ const fileTermHits = new Map();
2732
+ for (const [fp, group] of relevantFiles) {
2733
+ const hay = fp.toLowerCase() + ' ' + group.nodes.map(n => n.name.toLowerCase()).join(' ');
2734
+ let hits = 0;
2735
+ for (const t of uniqueQueryTerms)
2736
+ if (hay.includes(t))
2737
+ hits++;
2738
+ fileTermHits.set(fp, hits);
2739
+ }
2740
+ // PRIMARY relevance: graph connectivity (Random-Walk-with-Restart from the
2741
+ // matched seeds — see computeGraphRelevance). Aggregate each file's nodes'
2742
+ // walk mass. This is the signal text search lacks: the real cluster
2743
+ // (org-user.storage.ts, call-connected to the matches) accrues mass; a lone
2744
+ // text match (LensSwitcher.swift, matched "switch" but calls nothing in the
2745
+ // flow) gets only its restart probability → ~0, and is dropped by the gate.
2746
+ const nodeRwr = this.computeGraphRelevance([...subgraph.nodes.keys()], subgraph.edges, entryNodeIds);
2747
+ const fileGraphScore = new Map();
2748
+ for (const node of subgraph.nodes.values()) {
2749
+ fileGraphScore.set(node.filePath, (fileGraphScore.get(node.filePath) ?? 0) + (nodeRwr.get(node.id) ?? 0));
2750
+ }
2751
+ const maxGraph = Math.max(0, ...fileGraphScore.values());
2752
+ // Central file(s): the 1-2 most graph-central files that also match the
2753
+ // query textually (so a connected hub-utility with no term match isn't
2754
+ // mistaken for the subject). The heart of the answer — they earn the larger
2755
+ // WHOLE-FILE ceiling below (a god-file central file still exceeds it and
2756
+ // falls to generous full-method sectioning — never a whole dump).
2757
+ const centralFiles = new Set([...fileGraphScore.entries()]
2758
+ .filter(([fp, g]) => g > 0 && (fileTermHits.get(fp) ?? 0) >= 1)
2759
+ .sort((a, b) => b[1] - a[1] || (fileTermHits.get(b[0]) ?? 0) - (fileTermHits.get(a[0]) ?? 0))
2760
+ .slice(0, 2)
2761
+ .map(([f]) => f));
2762
+ // Files that DEFINE a symbol the agent named (or a subgraph root). These are
2763
+ // the highest-relevance files there are — the agent asked for them by name —
2764
+ // so the connectivity gate below must never drop them, even when their RWR
2765
+ // mass is low (a leaf family file like codec.ts is call-connected to little
2766
+ // but is exactly what the agent queried). Without this protection the gate
2767
+ // prunes a named file and the agent Reads it back.
2768
+ const entryFiles = new Set();
2769
+ for (const id of entryNodeIds) {
2770
+ const n = subgraph.nodes.get(id);
2771
+ if (n)
2772
+ entryFiles.add(n.filePath);
2773
+ }
2774
+ // Buried-rescue pass (#1064): surface a named method's signature type ONLY
2775
+ // when its file is genuinely buried — near-zero graph mass AND not lexically
2776
+ // matched. That is the invisible case (grpc's `DialOption` → `dialoptions.go`,
2777
+ // g≈0, 0 term hits): reachable but ranked nowhere, so the agent greps. A
2778
+ // well-connected type file (excalidraw element types, Alamofire `DataRequest`)
2779
+ // is NOT buried and is left alone — rescuing it would displace a flow-central
2780
+ // file (App.tsx, Validation.swift). Buried is judged on the PRE-rescue graph,
2781
+ // so injecting the type below can't make it look connected. A rescued file is
2782
+ // injected (so it renders), force-kept (gate + relevantFiles), and tiered.
2783
+ const changeSurfaceFiles = new Set();
2784
+ for (const t of changeSurfaceCandidates) {
2785
+ const fp = t.filePath;
2786
+ const buried = (fileGraphScore.get(fp) ?? 0) < maxGraph * 0.06
2787
+ && (fileTermHits.get(fp) ?? 0) < 2;
2788
+ if (!buried)
2789
+ continue;
2790
+ changeSurfaceFiles.add(fp);
2791
+ if (!subgraph.nodes.has(t.id))
2792
+ subgraph.nodes.set(t.id, t);
2793
+ let group = fileGroups.get(fp);
2794
+ if (!group) {
2795
+ group = { nodes: [], score: 0 };
2796
+ fileGroups.set(fp, group);
2797
+ }
2798
+ if (!group.nodes.some((n) => n.id === t.id))
2799
+ group.nodes.push(t);
2800
+ group.score = Math.max(group.score, 45);
2801
+ if (!relevantFiles.some(([f]) => f === fp))
2802
+ relevantFiles.push([fp, group]);
2803
+ }
2804
+ // Relevance gate (so the generous budget is a CEILING, not a target): keep a
2805
+ // file only if it is STRUCTURALLY relevant by ANY of:
2806
+ // - graph score within a fraction of the top (it's on/near the flow), OR
2807
+ // - central (a query entry-point lives here), OR
2808
+ // - it DEFINES a symbol the agent named (entryFiles), OR
2809
+ // - it matches >= 2 DISTINCT named query terms — a strong text signal that
2810
+ // the agent is asking about this file even when nothing calls it (codec.ts:
2811
+ // the agent named `encode`/`Codec`/`JsonCodec`, all leaf classes with zero
2812
+ // RWR mass — graph alone wrongly drops it).
2813
+ // A lone text match on one shared word (LensSwitcher: term=1, g~0) is still
2814
+ // dropped, so the budget never fills with incidental files. Guarded so it
2815
+ // never prunes below 2.
2816
+ if (maxGraph > 0) {
2817
+ const gated = relevantFiles.filter(([fp]) => (fileGraphScore.get(fp) ?? 0) >= maxGraph * 0.06
2818
+ || centralFiles.has(fp)
2819
+ || entryFiles.has(fp)
2820
+ || changeSurfaceFiles.has(fp)
2821
+ || (fileTermHits.get(fp) ?? 0) >= 2);
2822
+ if (gated.length >= 2)
2823
+ relevantFiles = gated;
2824
+ }
2825
+ // Sort files: graph-central first, then distinct-term match, then the
2826
+ // existing low-value/generated/score tiebreaks.
2827
+ // Files that DEFINE a symbol the agent NAMED. These sort first — ahead of
2828
+ // graph connectivity — because the agent asked for them by name. Without
2829
+ // this, a named leaf override reached only by dynamic dispatch (Alamofire's
2830
+ // `DataRequest.task`/`validate`, low RWR mass) sorts below the high-
2831
+ // connectivity abstract base (`Request.swift`) and the same-named overloads
2832
+ // in other files (`Validation.swift`), falls outside the budget, and the
2833
+ // agent Reads it. The named file is the answer — rank it at the top.
2834
+ const namedSeedFiles = new Set();
2835
+ for (const id of tierSeedIds) {
2836
+ const n = subgraph.nodes.get(id);
2837
+ if (n)
2838
+ namedSeedFiles.add(n.filePath);
2839
+ }
2840
+ // A rescued change-surface file (only the genuinely-buried ones — see the
2841
+ // buried-rescue pass) is the lexically-dissimilar answer; give it the named
2842
+ // tier so it isn't buried under files that merely share surface words (#1064).
2843
+ for (const fp of changeSurfaceFiles)
2844
+ namedSeedFiles.add(fp);
2845
+ // Multi-term corroboration tier: a file that is BOTH (a) an entry/central file
2846
+ // (a search root, named seed, or graph-central hub — i.e. structurally part of
2847
+ // the answer) AND (b) matched by ≥2 DISTINCT query terms must not be buried by
2848
+ // graph-centrality mass that accrued to a denser-but-off-topic cluster. In a
2849
+ // cross-layer monorepo (an API server alongside a much larger, internally dense
2850
+ // frontend that mirrors the same domain words) the Random-Walk-with-Restart mass
2851
+ // — seeded from text matches that skew to the bigger layer — floats hits=0
2852
+ // frontend files above the hits=2/3 backend service that IS the answer (its many
2853
+ // callers don't help: it's call-isolated from the frontend seed cluster). The
2854
+ // entry/central GUARD keeps this safe: an INCIDENTAL multi-term file that is
2855
+ // neither entry nor central (a type/util file that matches "element"+x but isn't
2856
+ // the flow) is NOT promoted, so it can't displace the graph-central answer file
2857
+ // (hits=1) the way a blunt hits-only tier would. Single-layer repos with one
2858
+ // cluster are unaffected (no competing mass). Set CODEGRAPH_RANK_NO_MULTITERM=1
2859
+ // to disable.
2860
+ const MULTITERM_OFF = process.env.CODEGRAPH_RANK_NO_MULTITERM === '1';
2861
+ const isCorroborated = (fp) => !MULTITERM_OFF &&
2862
+ (fileTermHits.get(fp) ?? 0) >= 2 &&
2863
+ (entryFiles.has(fp) || centralFiles.has(fp));
2864
+ const sortedFiles = relevantFiles.sort((a, b) => {
2865
+ const aPath = a[0].toLowerCase();
2866
+ const bPath = b[0].toLowerCase();
2867
+ // Agent-named files first (it asked for a symbol defined here by name).
2868
+ const aNamed = namedSeedFiles.has(a[0]) ? 1 : 0;
2869
+ const bNamed = namedSeedFiles.has(b[0]) ? 1 : 0;
2870
+ if (aNamed !== bNamed)
2871
+ return bNamed - aNamed;
2872
+ // Corroborated (entry/central + ≥2 terms) tier, above the graph signal.
2873
+ const aCorr = isCorroborated(a[0]) ? 1 : 0;
2874
+ const bCorr = isCorroborated(b[0]) ? 1 : 0;
2875
+ if (aCorr !== bCorr)
2876
+ return bCorr - aCorr;
2877
+ // Graph connectivity is the next key (small epsilon so near-ties fall
2878
+ // through to the text signal rather than coin-flipping on float noise).
2879
+ const aG = fileGraphScore.get(a[0]) ?? 0;
2880
+ const bG = fileGraphScore.get(b[0]) ?? 0;
2881
+ if (Math.abs(aG - bG) > maxGraph * 0.01)
2882
+ return bG - aG;
2883
+ const aHits = fileTermHits.get(a[0]) ?? 0;
2884
+ const bHits = fileTermHits.get(b[0]) ?? 0;
2885
+ if (aHits !== bHits)
2886
+ return bHits - aHits;
2887
+ const aLow = isLowValue(aPath);
2888
+ const bLow = isLowValue(bPath);
2889
+ if (aLow !== bLow)
2890
+ return aLow ? 1 : -1;
2891
+ // Deprioritize generated source (.pb.go / .pulsar.go / _mocks.go / …) —
2892
+ // the agent rarely needs to see the protobuf scaffold or gomock output
2893
+ // when asking about the actual flow, and dumping their bodies inflates
2894
+ // the response (the cosmos Q3 explore otherwise leads with
2895
+ // `expected_keepers_mocks.go`, displacing the real `tally.go` content
2896
+ // and forcing the agent to Read tally.go anyway).
2897
+ const aGen = (0, generated_detection_1.isGeneratedFile)(a[0]);
2898
+ const bGen = (0, generated_detection_1.isGeneratedFile)(b[0]);
2899
+ if (aGen !== bGen)
2900
+ return aGen ? 1 : -1;
2901
+ if (a[1].score !== b[1].score)
2902
+ return b[1].score - a[1].score;
2903
+ return b[1].nodes.length - a[1].nodes.length;
2904
+ });
2905
+ // Step 3: Build relationship map
2906
+ const lines = [
2907
+ `**Exploration: ${query}**`,
2908
+ '',
2909
+ // Curated summary — filled in after the source loop (see below). We do NOT
2910
+ // report `subgraph.nodes.size` / `fileGroups.size` here: that's the raw
2911
+ // candidate gather, which a broad natural-language query inflates wildly
2912
+ // (260 symbols / 124 files on a 636-file repo) even though only a handful
2913
+ // render. Reporting the pool read as "260 results to wade through" when the
2914
+ // real, correctly-ranked answer is the few files below (#1046).
2915
+ '',
2916
+ '',
2917
+ ];
2918
+ const summaryLineIdx = 2;
2919
+ // Blast radius (always-on, compact): for the entry symbols, who depends on
2920
+ // them + which tests cover them — locations only, no source — so the agent
2921
+ // knows what to update/verify before editing without a separate call.
2922
+ const blastRadius = this.buildBlastRadiusSection(cg, subgraph);
2923
+ if (blastRadius)
2924
+ lines.push(blastRadius);
2925
+ // Relationship map — show how symbols connect
2926
+ const significantEdges = subgraph.edges.filter(e => e.kind !== 'contains' // skip contains — it's implied by file grouping
2927
+ );
2928
+ if (budget.includeRelationships && significantEdges.length > 0) {
2929
+ lines.push('**Relationships**');
2930
+ lines.push('');
2931
+ // Group edges by kind for readability
2932
+ const byKind = new Map();
2933
+ for (const edge of significantEdges) {
2934
+ const sourceNode = subgraph.nodes.get(edge.source);
2935
+ const targetNode = subgraph.nodes.get(edge.target);
2936
+ if (!sourceNode || !targetNode)
2937
+ continue;
2938
+ const group = byKind.get(edge.kind) || [];
2939
+ group.push({ source: sourceNode.name, target: targetNode.name });
2940
+ byKind.set(edge.kind, group);
2941
+ }
2942
+ for (const [kind, edges] of byKind) {
2943
+ const cap = budget.maxEdgesPerRelationshipKind;
2944
+ const shown = edges.slice(0, cap);
2945
+ lines.push(`**${kind}:**`);
2946
+ for (const e of shown) {
2947
+ lines.push(`- ${e.source} → ${e.target}`);
2948
+ }
2949
+ if (edges.length > cap) {
2950
+ lines.push(`- ... and ${edges.length - cap} more`);
2951
+ }
2952
+ lines.push('');
2953
+ }
2954
+ }
2955
+ // Step 4: Read contiguous file sections
2956
+ // Compute the flow spine once — used both to prepend the Flow section (below)
2957
+ // and to gate adaptive source sizing: files on the spine get full source,
2958
+ // off-spine peers skeletonize.
2959
+ const flow = this.buildFlowFromNamedSymbols(cg, query);
2960
+ // Polymorphic-sibling detector for adaptive sizing. A class that implements/
2961
+ // extends a supertype shared by >= MIN_SIBLINGS classes is one of many
2962
+ // INTERCHANGEABLE implementations (OkHttp's 14 `: Interceptor` classes —
2963
+ // showing one + the rest as signatures is enough), as opposed to a DISTINCT
2964
+ // pipeline step (Excalidraw's `renderStaticScene`, which shares no supertype and
2965
+ // must stay full or the agent loses real content). Only off-spine sibling files
2966
+ // skeletonize; distinct steps and on-spine files keep full source. Cache
2967
+ // supertype→(has ≥N implementers) so this stays a handful of edge queries.
2968
+ const MIN_SIBLINGS = 3;
2969
+ const siblingSuper = new Map();
2970
+ const isPolymorphicSibling = (nodes) => {
2971
+ for (const n of nodes) {
2972
+ for (const e of cg.getOutgoingEdges(n.id)) {
2973
+ if (e.kind !== 'implements' && e.kind !== 'extends')
2974
+ continue;
2975
+ let many = siblingSuper.get(e.target);
2976
+ if (many === undefined) {
2977
+ many = cg.getIncomingEdges(e.target)
2978
+ .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
2979
+ siblingSuper.set(e.target, many);
2980
+ }
2981
+ if (many)
2982
+ return true;
2983
+ }
2984
+ }
2985
+ return false;
2986
+ };
2987
+ // A file that DEFINES a polymorphic supertype (a class/interface with ≥
2988
+ // MIN_SIBLINGS implementers) AND co-locates its subclasses is a redundant
2989
+ // "family" file — Django's compiler.py holds `SQLCompiler` + its 4 subclasses
2990
+ // (SQLInsert/Update/Delete/AggregateCompiler) in 2,266 lines. Such files are
2991
+ // huge and read-anyway, so they should STILL skeletonize even when the agent
2992
+ // named a method in them: a full one eats ~6.5K of the explore budget (Django
2993
+ // is pinned at the 28K cap, truncating), starving the sibling files the agent
2994
+ // then Reads. This flag OVERRIDES the named-callable spare below — it does NOT
2995
+ // by itself spare a file. (OkHttp's RealCall implements the `Lockable` mixin
2996
+ // but defines no ≥3-impl supertype, so the named spare keeps it full.)
2997
+ const superMany = new Map();
2998
+ const definesPolymorphicSupertype = (nodes) => {
2999
+ for (const n of nodes) {
3000
+ if (n.kind !== 'class' && n.kind !== 'interface' && n.kind !== 'struct'
3001
+ && n.kind !== 'trait' && n.kind !== 'protocol' && n.kind !== 'type_alias')
3002
+ continue;
3003
+ let many = superMany.get(n.id);
3004
+ if (many === undefined) {
3005
+ many = cg.getIncomingEdges(n.id)
3006
+ .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
3007
+ superMany.set(n.id, many);
3008
+ }
3009
+ if (many)
3010
+ return true;
3011
+ }
3012
+ return false;
3013
+ };
3014
+ lines.push('**Source Code**');
3015
+ lines.push('');
3016
+ lines.push('> The code below is the **verbatim, current on-disk source** of these files — re-read from disk on this call and line-numbered, byte-for-byte identical to what the Read tool returns. It is NOT a summary, outline, or stale cache. Treat each block as a Read you have already performed: do not Read a file shown here.');
3017
+ lines.push('');
3018
+ let totalChars = lines.join('\n').length;
3019
+ let filesIncluded = 0;
3020
+ // Paths we actually render source for below. Drives the curated header count
3021
+ // (#1046) — it must reflect what we show, not the raw candidate gather.
3022
+ const renderedFilePaths = [];
3023
+ let anyFileTrimmed = false;
3024
+ for (const [filePath, group] of sortedFiles) {
3025
+ if (filesIncluded >= maxFiles)
3026
+ break;
3027
+ // A file DEFINES a named/spine symbol (the answer) vs merely references the
3028
+ // flow. Past 90% budget, stop pulling INCIDENTAL files — but keep scanning
3029
+ // for necessary ones, which render even past the cap (bounded by maxFiles).
3030
+ // Without this `continue` (was an unconditional `break`), the loop stopped
3031
+ // after the build + validators-exec files and never reached the ranked-in
3032
+ // validate-logic file (Alamofire's Validation.swift).
3033
+ const fileNecessary = group.nodes.some(n => entryNodeIds.has(n.id) || flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id));
3034
+ if (!fileNecessary && totalChars > budget.maxOutputChars * 0.9)
3035
+ continue;
3036
+ const absPath = (0, utils_1.validatePathWithinRoot)(projectRoot, filePath);
3037
+ if (!absPath || !(0, fs_1.existsSync)(absPath))
3038
+ continue;
3039
+ let fileContent;
3040
+ try {
3041
+ fileContent = (0, fs_1.readFileSync)(absPath, 'utf-8');
3042
+ }
3043
+ catch {
3044
+ continue;
3045
+ }
3046
+ const fileLines = fileContent.split('\n');
3047
+ const lang = group.nodes[0]?.language || '';
3048
+ // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
3049
+ // to a per-symbol view when it's a redundant member of a polymorphic family.
3050
+ // Engages iff ALL hold:
3051
+ // 1. a flow spine exists,
3052
+ // 2. no symbol in the file is on that spine (it's not the mechanism path),
3053
+ // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
3054
+ // 4. it is NOT SPARED, where a file is spared iff the agent named a
3055
+ // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
3056
+ // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
3057
+ // base+subclasses "family" file like Django's compiler.py — collapse it).
3058
+ // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
3059
+ // subclass; naming it must NOT keep every backend variant + test file full
3060
+ // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
3061
+ // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
3062
+ // agent NAMED or that's on the spine is shown with its FULL body (so the agent
3063
+ // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
3064
+ // every other symbol is just its signature. So the base mechanism survives while
3065
+ // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
3066
+ const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
3067
+ const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
3068
+ const spared = spareNamed && !fileDefinesSuper;
3069
+ const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
3070
+ const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
3071
+ // On-spine god-file: the flow path runs THROUGH this file, but it also holds
3072
+ // many OTHER named methods, and rendering all of them in full blows the
3073
+ // per-file budget and starves the other flow files (Alamofire: the agent
3074
+ // names ~7 Session.swift methods — the build spine PLUS off-path
3075
+ // task/didCompleteTask — far past the whole response budget). Engage the
3076
+ // per-symbol view to keep the SPINE full and collapse the off-path named
3077
+ // methods to signatures. Only when there IS off-path content to shed —
3078
+ // otherwise the spine is irreducible (a sequential flow has no redundancy),
3079
+ // so leave it to the normal full render.
3080
+ const namedBodyChars = group.nodes
3081
+ .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
3082
+ .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
3083
+ const onSpineGodFile = hasSpineNode
3084
+ && namedBodyChars > budget.maxCharsPerFile
3085
+ && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
3086
+ if (adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
3087
+ && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
3088
+ const syms = group.nodes
3089
+ .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
3090
+ .sort((a, b) => a.startLine - b.startLine);
3091
+ // Pass 1: choose which symbols get a FULL body, by priority, greedily within
3092
+ // a per-file body cap — so one huge family file can't body every named method
3093
+ // and crowd out the other flow files (Django's query.py). A symbol earns a
3094
+ // body if it's on-spine, or UNIQUELY named (`SQLCompiler.execute_sql`), or a
3095
+ // co-named method WHEN this file DEFINES the family supertype (so the base
3096
+ // `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides — and
3097
+ // OkHttp's 5 `intercept`s if the agent names `intercept` — stay signatures).
3098
+ const prio = (n) => !CALLABLE_BODY.has(n.kind) ? 99
3099
+ : flow.pathNodeIds.has(n.id) ? 0
3100
+ : flow.uniqueNamedNodeIds.has(n.id) ? 1
3101
+ : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 2 : 99;
3102
+ // One ~250-line WINDOW per file. syms are taken by priority (spine first,
3103
+ // then uniquely-named, then family-base), and the cap applies to ALL of
3104
+ // them — including the spine — so a big-spine god-file (tokio's worker.rs:
3105
+ // run→run_task→next_task→steal_work) can't eat the whole response and
3106
+ // starve the co-flow file (harness.rs's poll). The native agent windows
3107
+ // such a file too (~190 lines at a time), so this mimics, not truncates.
3108
+ // Always emit ≥1 (never an empty section).
3109
+ const bodyCap = budget.maxCharsPerFile * 1.5;
3110
+ const bodyIds = new Set();
3111
+ let bodyChars = 0;
3112
+ for (const n of syms.filter(n => prio(n) < 99 && n.endLine >= n.startLine).sort((a, b) => prio(a) - prio(b))) {
3113
+ const sz = fileLines.slice(n.startLine - 1, n.endLine).join('\n').length;
3114
+ if (bodyChars + sz > bodyCap && bodyIds.size > 0)
3115
+ continue;
3116
+ bodyIds.add(n.id);
3117
+ bodyChars += sz;
3118
+ }
3119
+ // Pass 2: render in line order — full body for chosen symbols, else the
3120
+ // signature line (capped, with a "+N more" tail so the structure map of a
3121
+ // god-file doesn't itself bloat the budget).
3122
+ const skel = [];
3123
+ let coveredUntil = 0; // skip symbols already inside an emitted body
3124
+ let sigCount = 0, sigDropped = 0;
3125
+ const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
3126
+ for (const n of syms) {
3127
+ if (n.startLine <= coveredUntil)
3128
+ continue;
3129
+ if (bodyIds.has(n.id)) {
3130
+ const end = n.endLine;
3131
+ const body = fileLines.slice(n.startLine - 1, end).join('\n');
3132
+ skel.push(exploreLineNumbersEnabled() ? numberSourceLines(body, n.startLine) : body);
3133
+ coveredUntil = end;
3134
+ }
3135
+ else {
3136
+ // Elide the body, emit the signature. node.startLine can point at a
3137
+ // decorator/annotation, so scan forward for the line that names the symbol.
3138
+ let lineNo = n.startLine;
3139
+ for (let k = 0; k < 4; k++) {
3140
+ if ((fileLines[n.startLine - 1 + k] || '').includes(n.name)) {
3141
+ lineNo = n.startLine + k;
3142
+ break;
3143
+ }
3144
+ }
3145
+ if (lineNo <= coveredUntil)
3146
+ continue;
3147
+ if (sigCount >= SIG_MAX) {
3148
+ sigDropped++;
3149
+ continue;
3150
+ }
3151
+ const sig = (fileLines[lineNo - 1] || '').trim();
3152
+ if (sig) {
3153
+ skel.push(exploreLineNumbersEnabled() ? `${lineNo}\t${sig}` : sig);
3154
+ sigCount++;
3155
+ }
3156
+ }
3157
+ }
3158
+ if (sigDropped > 0)
3159
+ skel.push(`… +${sigDropped} more (signatures elided)`);
3160
+ if (skel.length > 0) {
3161
+ const names = [...new Set(group.nodes.filter(n => n.kind !== 'import' && n.kind !== 'export').map(n => n.name))]
3162
+ .slice(0, budget.maxSymbolsInFileHeader).join(', ');
3163
+ // Steer the agent to codegraph_explore for an elided body — NEVER to
3164
+ // Read. The old "Read for more" / "Read for a full body" tags invited
3165
+ // a Read of the very file just skeletonized; on a central, wanted file
3166
+ // (Session.swift, DataRequest.swift) that fired an over-investigation
3167
+ // spiral (the agent Read the skeletonized file, then kept digging).
3168
+ // CLAUDE.md: explore output must never tell the agent to Read.
3169
+ const tag = bodyIds.size > 0
3170
+ ? 'focused (the methods you named in full, the rest as signatures — codegraph_explore a signature by name for its body; do NOT Read)'
3171
+ : 'skeleton (signatures only — codegraph_explore a name for its full body; do NOT Read)';
3172
+ lines.push(fileSectionHeader(filePath, `${names} · ${tag}`), '', '```' + lang, skel.join('\n'), '```', '');
3173
+ totalChars += skel.join('\n').length + 120;
3174
+ renderedFilePaths.push(filePath);
3175
+ filesIncluded++;
3176
+ continue;
3177
+ }
3178
+ }
3179
+ // Whole-file rule: if a relevant file is small enough to afford, return it
3180
+ // ENTIRELY instead of clustering. Clustering exists to tame god-files
3181
+ // (App.tsx ~13k lines); on a ~134-line component a cluster is a lossy
3182
+ // subset of a file the agent will just Read in full anyway — costing a
3183
+ // round-trip and a re-read every later turn. Reserve clustering for files
3184
+ // too big to ship whole. Still bounded by the total maxOutputChars check.
3185
+ //
3186
+ // CENTRAL files (where the query's entry points live) get a larger — but
3187
+ // bounded — ceiling: they're the heart of the answer, the file(s) the agent
3188
+ // would Read whole, so a genuinely small one comes back whole rather than as
3189
+ // thin clusters. A LARGE central file (the 791-line org-user store) exceeds
3190
+ // the ceiling and falls through to sectioning/clustering below — full method
3191
+ // bodies + signatures — so we never dump (or overflow on) a whole god-file.
3192
+ const isCentralFile = centralFiles.has(filePath);
3193
+ // Central files get a slightly larger whole-file window than peripheral ones,
3194
+ // but a TIGHT one (~1.5× the per-file cap): the native read of a central file
3195
+ // is a ~150–250 line orientation window, NOT the whole file. A flat "whole
3196
+ // central file" both overflowed the inline cap AND starved the co-flow files
3197
+ // (worker.rs ate the budget, dropping harness.rs's poll). A larger central
3198
+ // file falls through to per-method windowing/clustering below.
3199
+ const WHOLE_FILE_MAX_LINES = isCentralFile ? 280 : 220;
3200
+ const WHOLE_FILE_MAX_CHARS = isCentralFile
3201
+ ? Math.min(Math.max(0, budget.maxOutputChars - totalChars - 200), Math.round(budget.maxCharsPerFile * 1.5))
3202
+ : budget.maxCharsPerFile * 3;
3203
+ if (fileLines.length <= WHOLE_FILE_MAX_LINES && fileContent.length <= WHOLE_FILE_MAX_CHARS) {
3204
+ const body = fileContent.replace(/\n+$/, '');
3205
+ let wholeSection = exploreLineNumbersEnabled() ? numberSourceLines(body, 1) : body;
3206
+ const uniqSymbols = [...new Set(group.nodes
3207
+ .filter(n => n.kind !== 'import' && n.kind !== 'export')
3208
+ .map(n => `${n.name}(${n.kind})`))];
3209
+ const headerNames = uniqSymbols.slice(0, budget.maxSymbolsInFileHeader);
3210
+ const omitted = uniqSymbols.length - headerNames.length;
3211
+ const wholeHeader = fileSectionHeader(filePath, omitted > 0 ? `${headerNames.join(', ')}, +${omitted} more` : headerNames.join(', '));
3212
+ if (!fileNecessary && totalChars + wholeSection.length + 200 > budget.maxOutputChars) {
3213
+ // Don't slice a whole file mid-method: an incidental file that doesn't
3214
+ // fit is skipped; a necessary one (below) renders in full. Half a file
3215
+ // forces the Read this is meant to prevent.
3216
+ anyFileTrimmed = true;
3217
+ continue;
3218
+ }
3219
+ lines.push(wholeHeader, '', '```' + lang, wholeSection, '```', '');
3220
+ totalChars += wholeSection.length + 200;
3221
+ renderedFilePaths.push(filePath);
3222
+ filesIncluded++;
3223
+ continue;
3224
+ }
3225
+ // Cluster nearby symbols to avoid reading huge gaps between distant symbols.
3226
+ // Sort by start line, then merge overlapping/adjacent ranges (within the
3227
+ // adaptive gap threshold). Include both node ranges AND edge source
3228
+ // locations so template sections with component usages/calls are
3229
+ // covered (not just script block symbols).
3230
+ //
3231
+ // Each range carries an `importance` score so we can rank clusters
3232
+ // when the per-file budget forces us to drop some: entry-point nodes
3233
+ // are worth 10, directly-connected nodes 3, peripheral nodes 1, and
3234
+ // bare edge-source lines 2 (less than a connected node but more than
3235
+ // a peripheral one — they hint at a reference but aren't a definition).
3236
+ // Container kinds whose body can span most/all of a file. When such a
3237
+ // node covers most of the file we drop it from the ranges: keeping it
3238
+ // would merge every method inside it into one giant cluster spanning
3239
+ // the whole file, which then tail-trims down to just the container's
3240
+ // opening lines (its header/declarations) and buries the methods the
3241
+ // query actually asked about (#185 follow-up — Session.swift in
3242
+ // Alamofire is the canonical case: the `Session` class spans ~1,400
3243
+ // lines). We want the granular symbols inside, not the envelope.
3244
+ const ENVELOPE_KINDS = new Set(['file', 'module', 'class', 'struct', 'interface', 'enum', 'namespace', 'protocol', 'trait', 'component']);
3245
+ // Cluster from this file's gathered nodes PLUS any callable the agent NAMED that
3246
+ // lives here. Explore's relevance gather can miss a named method def in a huge
3247
+ // non-sibling file — Django's query.py is 3,040 lines and `_fetch_all` (L2237)
3248
+ // was gathered only as call-reference edges, never as a def, so it formed no
3249
+ // cluster and the agent Read it back. Inject named defs directly and rank them
3250
+ // ABOVE connected/glue nodes (importance 9) so their cluster wins the per-file
3251
+ // budget — the agent explicitly asked for these symbols.
3252
+ const rangeNodes = new Map();
3253
+ for (const n of group.nodes)
3254
+ if (n.startLine > 0 && n.endLine > 0)
3255
+ rangeNodes.set(n.id, n);
3256
+ for (const id of flow.namedNodeIds) {
3257
+ if (rangeNodes.has(id))
3258
+ continue;
3259
+ const n = cg.getNode(id);
3260
+ if (n && n.filePath === filePath && n.startLine > 0 && n.endLine > 0)
3261
+ rangeNodes.set(id, n);
3262
+ }
3263
+ const ranges = [...rangeNodes.values()]
3264
+ // Drop whole-file envelope nodes (containers covering >50% of the file).
3265
+ .filter(n => !(ENVELOPE_KINDS.has(n.kind) && (n.endLine - n.startLine + 1) > fileLines.length * 0.5))
3266
+ .map(n => {
3267
+ let importance = 1;
3268
+ if (entryNodeIds.has(n.id))
3269
+ importance = 10;
3270
+ else if (flow.namedNodeIds.has(n.id))
3271
+ importance = 9; // agent named it → keep its cluster
3272
+ else if (glueNodeIds.has(n.id))
3273
+ importance = 6; // bridging caller/callee of an entry
3274
+ else if (connectedToEntry.has(n.id))
3275
+ importance = 3;
3276
+ // On the rendered call-path spine? That IS the flow answer — its cluster
3277
+ // must never be dropped by the per-file budget (n8n's huge workflow-execute.ts:
3278
+ // processRunExecutionData, the named flow ENTRY at L1562, is a large
3279
+ // low-density method that lost the budget to denser blocks and got cut, so
3280
+ // the agent Read it back — the very thing explore exists to prevent).
3281
+ return { start: n.startLine, end: n.endLine, name: n.name, kind: n.kind, importance, spine: flow.pathNodeIds.has(n.id), spineCallLine: flow.spineCallSites.get(n.id) };
3282
+ });
3283
+ // Add edge source locations in this file — captures template references
3284
+ // (component usages, event handlers) that aren't nodes themselves.
3285
+ // Query edges directly from the DB (not just the subgraph) because BFS
3286
+ // traversal may have pruned template reference targets due to node budget.
3287
+ const edgeLines = new Set(); // dedup by "line:name"
3288
+ for (const node of group.nodes) {
3289
+ const outgoing = cg.getOutgoingEdges(node.id);
3290
+ for (const edge of outgoing) {
3291
+ if (!edge.line || edge.line <= 0 || edge.kind === 'contains')
3292
+ continue;
3293
+ const key = `${edge.line}:${edge.target}`;
3294
+ if (edgeLines.has(key))
3295
+ continue;
3296
+ edgeLines.add(key);
3297
+ // Look up target name from subgraph first, fall back to edge kind
3298
+ const targetNode = subgraph.nodes.get(edge.target);
3299
+ const targetName = targetNode?.name ?? edge.kind;
3300
+ ranges.push({ start: edge.line, end: edge.line, name: targetName, kind: edge.kind, importance: 2, spine: false });
3301
+ }
3302
+ }
3303
+ ranges.sort((a, b) => a.start - b.start);
3304
+ if (ranges.length === 0)
3305
+ continue;
3306
+ const gapThreshold = budget.gapThreshold;
3307
+ const clusters = [];
3308
+ let current = {
3309
+ start: ranges[0].start,
3310
+ end: ranges[0].end,
3311
+ symbols: [`${ranges[0].name}(${ranges[0].kind})`],
3312
+ score: ranges[0].importance,
3313
+ maxImportance: ranges[0].importance,
3314
+ hasSpine: ranges[0].spine,
3315
+ spineCallLine: ranges[0].spineCallLine,
3316
+ };
3317
+ for (let i = 1; i < ranges.length; i++) {
3318
+ const r = ranges[i];
3319
+ if (r.start <= current.end + gapThreshold) {
3320
+ current.end = Math.max(current.end, r.end);
3321
+ current.symbols.push(`${r.name}(${r.kind})`);
3322
+ current.score += r.importance;
3323
+ current.maxImportance = Math.max(current.maxImportance, r.importance);
3324
+ current.hasSpine = current.hasSpine || r.spine;
3325
+ current.spineCallLine = current.spineCallLine ?? r.spineCallLine;
3326
+ }
3327
+ else {
3328
+ clusters.push(current);
3329
+ current = {
3330
+ start: r.start,
3331
+ end: r.end,
3332
+ symbols: [`${r.name}(${r.kind})`],
3333
+ score: r.importance,
3334
+ maxImportance: r.importance,
3335
+ hasSpine: r.spine,
3336
+ spineCallLine: r.spineCallLine,
3337
+ };
3338
+ }
3339
+ }
3340
+ clusters.push(current);
3341
+ // Build file section output from clusters, capped by per-file budget.
3342
+ // The pathological case (#185): a file like Session.swift where every
3343
+ // method is adjacent collapses into one cluster spanning the whole
3344
+ // file, and dumping that into the agent's context is most of the
3345
+ // token cost on small projects. We pick clusters in priority order
3346
+ // until the per-file char cap is hit. Truly enormous single clusters
3347
+ // get tail-trimmed with a marker.
3348
+ const contextPadding = 3;
3349
+ const withLineNumbers = exploreLineNumbersEnabled();
3350
+ // Language-neutral separator (no `//` — not a comment in Python, Ruby,
3351
+ // etc.). With line numbers on, the line-number jump also signals the gap.
3352
+ const GAP_MARKER = '\n\n... (gap) ...\n\n';
3353
+ // An oversize spine method (the call path runs THROUGH a god-method — n8n's
3354
+ // processRunExecutionData is 962 lines) is windowed to its next-hop CALL site
3355
+ // plus the signature head, NOT dumped whole. Without this the cluster is too big
3356
+ // for any per-file cap and gets dropped, so the agent Reads the method back —
3357
+ // the exact gap this closes. Bounded, so a god-method can't blow the budget yet
3358
+ // the spine's call still appears in context.
3359
+ const OVERSIZE_SPINE_LINES = 200;
3360
+ const SPINE_WINDOW = 28; // lines each side of the next-hop call site
3361
+ const buildSection = (c) => {
3362
+ if (c.hasSpine && c.spineCallLine && (c.end - c.start + 1) > OVERSIZE_SPINE_LINES) {
3363
+ const call = c.spineCallLine;
3364
+ const winStart = Math.max(c.start, call - SPINE_WINDOW);
3365
+ const winEnd = Math.min(c.end, call + SPINE_WINDOW);
3366
+ const parts = [];
3367
+ // Signature head, only when it sits clearly above the window (else the
3368
+ // window already covers the method opening).
3369
+ const headEnd = Math.min(c.start + 4, winStart - 2);
3370
+ if (headEnd >= c.start) {
3371
+ const head = fileLines.slice(c.start - 1, headEnd).join('\n');
3372
+ parts.push(withLineNumbers ? numberSourceLines(head, c.start) : head);
3373
+ }
3374
+ const win = fileLines.slice(winStart - 1, winEnd).join('\n');
3375
+ parts.push(withLineNumbers ? numberSourceLines(win, winStart) : win);
3376
+ return parts.join(GAP_MARKER);
3377
+ }
3378
+ const startIdx = Math.max(0, c.start - 1 - contextPadding);
3379
+ const endIdx = Math.min(fileLines.length, c.end + contextPadding);
3380
+ const slice = fileLines.slice(startIdx, endIdx).join('\n');
3381
+ // startIdx is 0-based, so the slice's first line is line startIdx + 1.
3382
+ return withLineNumbers ? numberSourceLines(slice, startIdx + 1) : slice;
3383
+ };
3384
+ // Rank clusters for inclusion under the per-file cap. Entry-point
3385
+ // clusters come first: a cluster containing a query entry point
3386
+ // (importance 10) must outrank a dense block of mere declarations,
3387
+ // otherwise on a large file like Session.swift the top-of-file class
3388
+ // header + property list (many adjacent low-importance nodes, high
3389
+ // density) wins the budget and buries the actual methods the query
3390
+ // asked about (perform/didCreateURLRequest/task live deep in the
3391
+ // file). Within the same importance tier, prefer density (score per
3392
+ // line) so we still favor focused clusters over sprawling ones, then
3393
+ // smaller span as a cheap-to-include tiebreak.
3394
+ const rankedClusters = clusters
3395
+ .map((c, i) => ({ idx: i, span: c.end - c.start + 1, c }))
3396
+ .sort((a, b) => {
3397
+ // Spine clusters first — the rendered call path IS the flow answer, so it
3398
+ // outranks any denser block of peripheral declarations (a low-density entry
3399
+ // method must not lose the budget to them). Within spine / within non-spine,
3400
+ // the existing importance → density → score → span order holds.
3401
+ if (a.c.hasSpine !== b.c.hasSpine)
3402
+ return (b.c.hasSpine ? 1 : 0) - (a.c.hasSpine ? 1 : 0);
3403
+ if (b.c.maxImportance !== a.c.maxImportance)
3404
+ return b.c.maxImportance - a.c.maxImportance;
3405
+ const densityA = a.c.score / a.span;
3406
+ const densityB = b.c.score / b.span;
3407
+ if (densityB !== densityA)
3408
+ return densityB - densityA;
3409
+ if (b.c.score !== a.c.score)
3410
+ return b.c.score - a.c.score;
3411
+ return a.span - b.span;
3412
+ });
3413
+ // Per-file budget is the SMALLER of the per-file cap and what's left of the
3414
+ // total output cap — so selection (which ranks by importance) keeps the
3415
+ // high-importance clusters and drops peripheral ones, instead of the
3416
+ // downstream source-order trim slicing off whatever comes last in the file.
3417
+ // That source-order slice is what cut Django's `_fetch_all` (L2237, importance
3418
+ // 9 — agent-named) when query.py was the last of four big files to be emitted.
3419
+ const fileBudget = Math.min(budget.maxCharsPerFile, Math.max(0, budget.maxOutputChars - totalChars - 200));
3420
+ // Spine ceiling: a flow-path cluster may exceed the per-file cap (the call
3421
+ // path is the answer), but bounded — at most ~2.5× the per-file cap and never
3422
+ // past what's left of the total output cap — so a pathological long in-file
3423
+ // spine can't run away or starve co-flow files entirely.
3424
+ const SPINE_CEILING = Math.min(budget.maxCharsPerFile * 2.5, Math.max(0, budget.maxOutputChars - totalChars - 200));
3425
+ const chosenIndices = new Set();
3426
+ let projectedChars = 0;
3427
+ for (const rc of rankedClusters) {
3428
+ const sectionLen = buildSection(rc.c).length + (chosenIndices.size > 0 ? GAP_MARKER.length : 0);
3429
+ // Always take the top-ranked cluster, even if oversize, so we don't
3430
+ // return an empty file section (agent would then re-Read the file,
3431
+ // negating the savings).
3432
+ if (chosenIndices.size === 0) {
3433
+ chosenIndices.add(rc.idx);
3434
+ projectedChars += sectionLen;
3435
+ continue;
3436
+ }
3437
+ // A spine cluster (the rendered call path) is the flow answer — include it
3438
+ // past the per-file budget up to the spine ceiling; non-spine clusters obey
3439
+ // the normal per-file budget.
3440
+ const fits = projectedChars + sectionLen <= fileBudget;
3441
+ const spineFits = rc.c.hasSpine && projectedChars + sectionLen <= SPINE_CEILING;
3442
+ if (!fits && !spineFits)
3443
+ continue;
3444
+ chosenIndices.add(rc.idx);
3445
+ projectedChars += sectionLen;
3446
+ }
3447
+ // Emit chosen clusters in source order so the file reads top-to-bottom.
3448
+ let fileSection = '';
3449
+ const allSymbols = [];
3450
+ for (let i = 0; i < clusters.length; i++) {
3451
+ if (!chosenIndices.has(i))
3452
+ continue;
3453
+ const cluster = clusters[i];
3454
+ const section = buildSection(cluster);
3455
+ if (fileSection.length > 0)
3456
+ fileSection += GAP_MARKER;
3457
+ fileSection += section;
3458
+ allSymbols.push(...cluster.symbols);
3459
+ }
3460
+ // A chosen cluster is a COMPLETE method-range — we never cut through a body.
3461
+ // An oversize single cluster (a long monolithic function) renders in FULL:
3462
+ // half a method is useless (the agent just Reads the rest for the other half),
3463
+ // which is the very fallback explore exists to prevent. A pathological file is
3464
+ // bounded by the per-file cluster SELECTION above + the total hard ceiling.
3465
+ if (chosenIndices.size < clusters.length) {
3466
+ anyFileTrimmed = true;
3467
+ }
3468
+ // Dedupe + cap the symbols list shown in the per-file header. Some
3469
+ // files (Session.swift in Alamofire) produced 3.4KB symbol lists
3470
+ // from cluster scoring + edge-source lines, dwarfing the per-file
3471
+ // body cap. Show top names by frequency, with a "+N more" tail.
3472
+ const symbolCounts = new Map();
3473
+ for (const s of allSymbols) {
3474
+ symbolCounts.set(s, (symbolCounts.get(s) ?? 0) + 1);
3475
+ }
3476
+ const sortedSymbols = [...symbolCounts.entries()]
3477
+ .sort((a, b) => b[1] - a[1])
3478
+ .map(([name]) => name);
3479
+ const headerCap = budget.maxSymbolsInFileHeader;
3480
+ const headerSymbols = sortedSymbols.slice(0, headerCap);
3481
+ const omittedCount = sortedSymbols.length - headerSymbols.length;
3482
+ const headerSuffix = omittedCount > 0
3483
+ ? `${headerSymbols.join(', ')}, +${omittedCount} more`
3484
+ : headerSymbols.join(', ');
3485
+ const fileHeader = fileSectionHeader(filePath, headerSuffix);
3486
+ // The total cap bounds INCIDENTAL files only. A file that DEFINES a symbol
3487
+ // the agent named (or that's on the flow spine) renders even when the
3488
+ // nominal total is used up — it's the answer, and the set is bounded by
3489
+ // maxFiles AND by true-spine/named-seeding having already trimmed each file
3490
+ // to its necessary content. A file that merely REFERENCES the flow
3491
+ // (Combine.swift name-drops request/task) is incidental → still capped, so
3492
+ // freed budget never leaks into noise. This is the last god-file layer:
3493
+ // build (Session, true-spined) + validators-exec (Request) + validate
3494
+ // (DataRequest/Validation) all render, instead of the cap dropping whichever
3495
+ // phase the file order happened to put last.
3496
+ if (!fileNecessary && totalChars + fileSection.length + 200 > budget.maxOutputChars) {
3497
+ // Incidental file that doesn't fit: SKIP it whole — never slice mid-method.
3498
+ // Keep scanning for necessary files (which bypass this cap and render in
3499
+ // full, bounded by the hard ceiling).
3500
+ anyFileTrimmed = true;
3501
+ continue;
3502
+ }
3503
+ lines.push(fileHeader);
3504
+ lines.push('');
3505
+ lines.push('```' + lang);
3506
+ lines.push(fileSection);
3507
+ lines.push('```');
3508
+ lines.push('');
3509
+ totalChars += fileSection.length + 200;
3510
+ renderedFilePaths.push(filePath);
3511
+ filesIncluded++;
3512
+ }
3513
+ // The curated header count is computed from the files that SURVIVE the final
3514
+ // truncation (see end of method) — `filesIncluded` can over-count when the
3515
+ // hard ceiling drops trailing sections — so leave a sentinel here and fill it
3516
+ // in once the output is final.
3517
+ lines[summaryLineIdx] = SUMMARY_SENTINEL;
3518
+ // Add remaining files as references (from both relevant and peripheral files).
3519
+ // Small projects (per budget) skip this — the relevant story already fits
3520
+ // in the source section, and a trailing pointer list is pure overhead.
3521
+ if (budget.includeAdditionalFiles) {
3522
+ const remainingRelevant = sortedFiles.slice(filesIncluded);
3523
+ const peripheralFiles = [...fileGroups.entries()]
3524
+ .filter(([, group]) => group.score < 3)
3525
+ .sort((a, b) => b[1].score - a[1].score);
3526
+ const remainingFiles = [...remainingRelevant, ...peripheralFiles];
3527
+ if (remainingFiles.length > 0) {
3528
+ lines.push('**Not shown above — explore these names for their source**');
3529
+ lines.push('');
3530
+ for (const [filePath, group] of remainingFiles.slice(0, 10)) {
3531
+ const symbols = group.nodes.map(n => `${n.name}:${n.startLine}`).join(', ');
3532
+ lines.push(`- ${filePath}: ${symbols}`);
3533
+ }
3534
+ if (remainingFiles.length > 10) {
3535
+ lines.push(`- ... and ${remainingFiles.length - 10} more files`);
3536
+ }
3537
+ }
3538
+ }
3539
+ // Add completeness signal so agents know they don't need to re-read these files.
3540
+ // On small projects the budget gates this off — but if we actually had to
3541
+ // trim or drop clusters, surface a brief note so the agent knows it can
3542
+ // still Read for more detail.
3543
+ if (budget.includeCompletenessSignal) {
3544
+ lines.push('');
3545
+ lines.push('---');
3546
+ lines.push(`> **Complete source for ${filesIncluded} files is included above — do NOT re-read them.** If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER codegraph_explore targeting those names — it returns the same source with line numbers and is cheaper and more complete than reading. Reserve Read for a single specific line range explore can't surface.`);
3547
+ }
3548
+ else if (anyFileTrimmed) {
3549
+ lines.push('');
3550
+ lines.push(`> Some file sections were trimmed for size. For a specific symbol you still need, run another \`codegraph_explore\` (or \`codegraph_node\`) with its exact name — line-numbered source, cheaper and more complete than Read.`);
3551
+ }
3552
+ // Add explore budget note based on project size
3553
+ if (budget.includeBudgetNote) {
3554
+ try {
3555
+ const stats = cg.getStats();
3556
+ const callBudget = getExploreBudget(stats.fileCount);
3557
+ lines.push('');
3558
+ lines.push(`> **Explore budget: ${callBudget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).** Each call covers ~6 files; if your question spans more, spend your remaining calls on the uncovered area BEFORE falling back to Read — another explore is cheaper and more complete than reading those files. Synthesize once you've used ${callBudget}.`);
3559
+ }
3560
+ catch {
3561
+ // Stats unavailable — skip budget note
3562
+ }
3563
+ }
3564
+ // Final ceiling — an ABSOLUTE inline cap, not a multiple of the budget. The
3565
+ // render loop renders necessary (named/spine) files even a bit past
3566
+ // maxOutputChars and caps only incidental ones, so this is the last safety.
3567
+ // It MUST stay under the host's inline tool-result limit (~25K chars): above
3568
+ // that the result is externalized to a file the agent Reads back (a 35K
3569
+ // vscode explore did exactly this in the n=4 A/B). So allow a little
3570
+ // necessary overflow above the 24K budget, but hard-stop at 25K — never into
3571
+ // externalize territory.
3572
+ const output = flow.text + lines.join('\n');
3573
+ const hardCeiling = Math.min(Math.round(budget.maxOutputChars * 1.5), 25000);
3574
+ let finalText;
3575
+ if (output.length > hardCeiling) {
3576
+ // Cut at a FILE-SECTION boundary (the last ``**` `` file header before the
3577
+ // ceiling) so we drop whole trailing file-sections rather than slicing
3578
+ // through a method body — a half-rendered method just forces the Read this
3579
+ // tool exists to prevent. Fall back to a line boundary only if no section
3580
+ // header sits in the back half (degenerate single-giant-section case).
3581
+ const cut = output.slice(0, hardCeiling);
3582
+ const lastSection = cut.lastIndexOf('\n' + FILE_SECTION_PREFIX);
3583
+ const boundary = lastSection > hardCeiling * 0.5 ? lastSection : cut.lastIndexOf('\n');
3584
+ const safe = boundary > 0 ? cut.slice(0, boundary) : cut;
3585
+ finalText = safe + '\n\n... (output truncated to budget; the source above is complete and verbatim — treat it as already Read. For any area not covered, run another codegraph_explore with the specific names — do NOT Read these files.)';
3586
+ }
3587
+ else {
3588
+ finalText = output;
3589
+ }
3590
+ // Curated header (#1046): substitute the sentinel with the count of files
3591
+ // whose source SURVIVES in the final text — not `subgraph`/`fileGroups` (the
3592
+ // raw gather a broad query inflates) and not `filesIncluded` (which can
3593
+ // over-count when the ceiling above drops trailing sections). A file counts
3594
+ // only if its section header is still present; its relevant (non-import)
3595
+ // symbols are summed for N. Files we couldn't fit are still named under "Not
3596
+ // shown above" + the budget note, so nothing is silently dropped.
3597
+ const survivors = renderedFilePaths.filter((fp) => finalText.includes(`${FILE_SECTION_PREFIX}${fp}\``));
3598
+ const shownSymbols = survivors.reduce((sum, fp) => {
3599
+ const g = fileGroups.get(fp);
3600
+ if (!g)
3601
+ return sum;
3602
+ return sum + new Set(g.nodes.filter((n) => n.kind !== 'import' && n.kind !== 'export').map((n) => n.id)).size;
3603
+ }, 0);
3604
+ const summaryLine = survivors.length > 0
3605
+ ? `Found ${shownSymbols} symbol${shownSymbols === 1 ? '' : 's'} across ${survivors.length} file${survivors.length === 1 ? '' : 's'}.`
3606
+ : `Found ${subgraph.nodes.size} symbol${subgraph.nodes.size === 1 ? '' : 's'} across ${fileGroups.size} file${fileGroups.size === 1 ? '' : 's'}.`;
3607
+ finalText = finalText.replace(SUMMARY_SENTINEL, summaryLine);
3608
+ return this.textResult(finalText);
3609
+ }
3610
+ /**
3611
+ * Handle codegraph_node
3612
+ */
3613
+ async handleNode(args) {
3614
+ const cg = this.getCodeGraph(args.projectPath);
3615
+ // Default to false to minimize context usage
3616
+ const includeCode = args.includeCode === true;
3617
+ const fileHint = typeof args.file === 'string' && args.file.trim() ? args.file.trim() : undefined;
3618
+ const lineHint = typeof args.line === 'number' && args.line > 0 ? args.line : undefined;
3619
+ const offset = typeof args.offset === 'number' && args.offset > 0 ? Math.floor(args.offset) : undefined;
3620
+ const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : undefined;
3621
+ const symbolsOnly = args.symbolsOnly === true;
3622
+ const symbolRaw = typeof args.symbol === 'string' ? args.symbol.trim() : '';
3623
+ // FILE READ MODE: a `file` with no `symbol` reads that file like the Read
3624
+ // tool — its current on-disk source with line numbers, narrowable with
3625
+ // `offset`/`limit` exactly as Read does — PLUS a one-line blast-radius
3626
+ // header (which files depend on it). `symbolsOnly` returns just the
3627
+ // structural map instead. Backed by the index: same bytes Read gives you.
3628
+ if (!symbolRaw && fileHint) {
3629
+ return this.handleFileView(cg, fileHint, { offset, limit, symbolsOnly });
3630
+ }
3631
+ const symbol = this.validateString(args.symbol, 'symbol');
3632
+ if (typeof symbol !== 'string')
3633
+ return symbol;
3634
+ let matches = this.findSymbolMatches(cg, symbol);
3635
+ if (matches.length === 0) {
3636
+ return this.textResult(`Symbol "${symbol}" not found in the codebase`);
3637
+ }
3638
+ // Disambiguate a heavily-overloaded name to a specific definition the caller
3639
+ // pinned by file/line (the `file:line` a trail or another tool showed it) —
3640
+ // so it can fetch e.g. `Harness::poll` at harness.rs:153 out of 50+ `poll`s
3641
+ // instead of Reading. file matches by path suffix/substring; line prefers the
3642
+ // def whose body contains it, else the nearest start. Only narrows (never
3643
+ // empties — if a hint matches nothing it's ignored).
3644
+ if (matches.length > 1 && (fileHint || lineHint !== undefined)) {
3645
+ const norm = (p) => p.replace(/\\/g, '/').toLowerCase();
3646
+ let narrowed = matches;
3647
+ if (fileHint) {
3648
+ const fh = norm(fileHint);
3649
+ const byFile = narrowed.filter((n) => norm(n.filePath).endsWith(fh) || norm(n.filePath).includes(fh));
3650
+ if (byFile.length > 0)
3651
+ narrowed = byFile;
3652
+ }
3653
+ if (lineHint !== undefined && narrowed.length > 1) {
3654
+ const containing = narrowed.filter((n) => n.startLine <= lineHint && (n.endLine ?? n.startLine) >= lineHint);
3655
+ narrowed = containing.length > 0
3656
+ ? containing
3657
+ : [...narrowed].sort((a, b) => Math.abs(a.startLine - lineHint) - Math.abs(b.startLine - lineHint)).slice(0, 1);
3658
+ }
3659
+ if (narrowed.length > 0)
3660
+ matches = narrowed;
3661
+ }
3662
+ // Single definition — the common case.
3663
+ if (matches.length === 1) {
3664
+ return this.textResult(this.truncateOutput(await this.renderNodeSection(cg, matches[0], includeCode)));
3665
+ }
3666
+ // Multiple definitions share this name — overloads, or same-named methods on
3667
+ // different types (Alamofire `didCompleteTask`/`task`/`validate`, gin
3668
+ // `reset`). Returning ONE forces the agent to guess, and when it guesses
3669
+ // wrong it READS the file to find the right overload — the dominant
3670
+ // codegraph_node read cause on Swift/Go. So return them ALL: pack as many
3671
+ // FULL bodies as fit a char budget (the agent gets the one it needs in this
3672
+ // one call, no follow-up parameter to learn), and list any remainder by
3673
+ // file:line so a large overload set can't overflow the per-tool cap.
3674
+ const header = `**${matches.length} definitions named "${symbol}"**`;
3675
+ if (!includeCode) {
3676
+ const list = matches.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`);
3677
+ return this.textResult(this.truncateOutput([header, '', 'Re-query with `includeCode: true` to get every body in one call — no need to pick one first.', '', ...list].join('\n')));
3678
+ }
3679
+ const BODY_BUDGET = 12000; // leaves room under MAX_OUTPUT_LENGTH for the header + list
3680
+ // The CHAR budget is the real limiter — keep the count cap high so a set of
3681
+ // SHORT overloads (Alamofire's 10 `validate` variants, each a few lines) all
3682
+ // render in full rather than relegating the one the agent wanted to a
3683
+ // bodiless list. Only a set of many LARGE bodies hits the char budget first.
3684
+ const HARD_CAP = 16;
3685
+ const rendered = [];
3686
+ const listed = [];
3687
+ let used = 0;
3688
+ for (const n of matches) {
3689
+ if (rendered.length >= HARD_CAP) {
3690
+ listed.push(n);
3691
+ continue;
3692
+ }
3693
+ const section = await this.renderNodeSection(cg, n, true);
3694
+ // Always emit the first; emit the rest only while within the char budget.
3695
+ if (rendered.length === 0 || used + section.length <= BODY_BUDGET) {
3696
+ rendered.push(section);
3697
+ used += section.length;
3698
+ }
3699
+ else {
3700
+ listed.push(n);
3701
+ }
3702
+ }
3703
+ const out = [
3704
+ header,
3705
+ `Returning ${rendered.length} in full${listed.length ? `; ${listed.length} more listed below` : ''} — pick the one you need (no Read required).`,
3706
+ '',
3707
+ rendered.join('\n\n---\n\n'),
3708
+ ];
3709
+ if (listed.length) {
3710
+ const LIST_CAP = 20;
3711
+ const shownList = listed.slice(0, LIST_CAP);
3712
+ out.push('', '**Other definitions**', ...shownList.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`));
3713
+ if (listed.length > LIST_CAP)
3714
+ out.push(`- … +${listed.length - LIST_CAP} more`);
3715
+ out.push('', `> Need one of these in full? Call codegraph_node again with \`file\` (e.g. \`"${listed[0].filePath.split('/').pop()}"\`) or \`line\` — do NOT Read it.`);
3716
+ }
3717
+ return this.textResult(this.truncateOutput(out.join('\n')));
3718
+ }
3719
+ /**
3720
+ * FILE READ MODE: resolve `fileArg` (path or basename) to an indexed file and
3721
+ * read it like the Read tool — its current on-disk source with line numbers,
3722
+ * narrowable with `offset`/`limit` exactly as Read's are — preceded by a
3723
+ * one-line blast-radius header (which files depend on it). `symbolsOnly`
3724
+ * returns just the structural map (symbols + dependents) instead of source.
3725
+ *
3726
+ * Parity goal: the numbered source block is byte-for-byte the shape Read
3727
+ * returns (`<n>\t<line>`, no padding), so the agent treats it as a Read — only
3728
+ * faster (served from the index) and with the blast radius attached. Security:
3729
+ * yaml/properties files are summarized by key, never dumped (#383); reads go
3730
+ * through validatePathWithinRoot (#527).
3731
+ */
3732
+ async handleFileView(cg, fileArg, opts = {}) {
3733
+ const normalize = (p) => p.replace(/\\/g, '/').replace(/^(?:\.?\/+)+/, '').replace(/\/+$/, '');
3734
+ const wantLower = normalize(fileArg).toLowerCase();
3735
+ const allFiles = cg.getFiles();
3736
+ if (allFiles.length === 0)
3737
+ return this.textResult('No files indexed. Run `codegraph index` first.');
3738
+ let resolved = allFiles.find((f) => f.path.toLowerCase() === wantLower);
3739
+ let candidates = [];
3740
+ if (!resolved) {
3741
+ candidates = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
3742
+ if (candidates.length === 1)
3743
+ resolved = candidates[0];
3744
+ }
3745
+ if (!resolved && candidates.length === 0) {
3746
+ candidates = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
3747
+ if (candidates.length === 1)
3748
+ resolved = candidates[0];
3749
+ }
3750
+ if (!resolved && candidates.length > 1) {
3751
+ return this.textResult([`"${fileArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
3752
+ ...candidates.slice(0, 25).map((f) => `- ${f.path}`)].join('\n'));
3753
+ }
3754
+ if (!resolved) {
3755
+ return this.textResult(`No indexed file matches "${fileArg}". Codegraph indexes source files; configs/docs it doesn't parse won't appear — Read those directly.`);
3756
+ }
3757
+ const filePath = resolved.path;
3758
+ const nodes = cg.getNodesInFile(filePath)
3759
+ .filter((n) => n.kind !== 'file' && n.kind !== 'import' && n.kind !== 'export')
3760
+ .sort((a, b) => a.startLine - b.startLine);
3761
+ const dependents = cg.getFileDependents(filePath);
3762
+ // Compact, one-line blast radius (codegraph's value-add over a plain Read).
3763
+ const depSummary = dependents.length
3764
+ ? `used by ${dependents.length} file${dependents.length === 1 ? '' : 's'}: ${dependents.slice(0, 8).join(', ')}${dependents.length > 8 ? `, +${dependents.length - 8} more` : ''}`
3765
+ : 'no other indexed file depends on it';
3766
+ // Symbol-map renderer — for symbolsOnly, the config fallback, and read errors.
3767
+ const symbolMap = (heading, limit = 200) => {
3768
+ const lines = [heading];
3769
+ for (const n of nodes.slice(0, limit)) {
3770
+ const sig = n.signature ? ` ${n.signature.replace(/\s+/g, ' ').trim()}` : '';
3771
+ lines.push(`- \`${n.name}\` (${n.kind})${sig} — :${n.startLine}`);
3772
+ }
3773
+ if (nodes.length > limit)
3774
+ lines.push(`- … +${nodes.length - limit} more`);
3775
+ return lines;
3776
+ };
3777
+ // symbolsOnly → the cheap structural overview, no source.
3778
+ if (opts.symbolsOnly) {
3779
+ const out = [`**${filePath}** — ${nodes.length} symbol${nodes.length === 1 ? '' : 's'}, ${depSummary}`, ''];
3780
+ if (nodes.length)
3781
+ out.push(...symbolMap('**Symbols**'));
3782
+ else
3783
+ out.push('_No indexed symbols in this file._');
3784
+ out.push('', '> Drop `symbolsOnly` (or pass `offset`/`limit`) to read the source, like Read.');
3785
+ return this.textResult(this.truncateOutput(out.join('\n')));
3786
+ }
3787
+ // SECURITY (#383): never dump a raw config/data file — a yaml/properties
3788
+ // line is `key: <secret>`. Summarize by key and point to a real Read.
3789
+ if (utils_1.CONFIG_LEAF_LANGUAGES.has(resolved.language)) {
3790
+ const out = [`**${filePath}** — configuration/data file, ${depSummary}`, ''];
3791
+ if (nodes.length)
3792
+ out.push(...symbolMap('**Keys (values withheld for safety)**'));
3793
+ out.push('', '> Values may be secrets, so codegraph indexes keys only. Read the file directly if you need a value.');
3794
+ return this.textResult(this.truncateOutput(out.join('\n')));
3795
+ }
3796
+ // Read the current bytes from disk through the security chokepoint
3797
+ // (validatePathWithinRoot: blocks `../` traversal and symlink escapes, #527).
3798
+ const abs = (0, utils_1.validatePathWithinRoot)(cg.getProjectRoot(), filePath);
3799
+ let content = null;
3800
+ if (abs) {
3801
+ try {
3802
+ content = (0, fs_1.readFileSync)(abs, 'utf-8');
3803
+ }
3804
+ catch {
3805
+ content = null;
3806
+ }
3807
+ }
3808
+ if (content === null) {
3809
+ const out = [`**${filePath}** — could not read from disk (it may have moved since indexing). ${depSummary}`, ''];
3810
+ if (nodes.length)
3811
+ out.push(...symbolMap('**Symbols**'));
3812
+ out.push('', `> Read \`${filePath}\` directly for its current content.`);
3813
+ return this.textResult(this.truncateOutput(out.join('\n')));
3814
+ }
3815
+ // Split exactly as Read does — keep the trailing empty line a final newline
3816
+ // produces (Read numbers it too), so line numbers line up byte-for-byte.
3817
+ const fileLines = content.split('\n');
3818
+ const total = fileLines.length;
3819
+ // Read-parity windowing: `offset`/`limit` mean exactly what they do on Read
3820
+ // (1-based start line; max line count). Default: the whole file, capped like
3821
+ // Read at 2000 lines and bounded by a char budget that tracks explore's
3822
+ // proven-safe ~38k response ceiling. Overflow is stated explicitly (Read
3823
+ // paginates too) — never the silent 15k truncateOutput chop.
3824
+ const CHAR_BUDGET = 38000;
3825
+ const DEFAULT_LIMIT = 2000;
3826
+ const offset = Math.max(1, opts.offset ?? 1);
3827
+ if (offset > total) {
3828
+ return this.textResult(`**${filePath}** has ${total} line${total === 1 ? '' : 's'} — offset ${offset} is past the end. ${depSummary}`);
3829
+ }
3830
+ const maxLines = Math.max(1, opts.limit ?? DEFAULT_LIMIT);
3831
+ const start = offset - 1; // 0-based
3832
+ const header = `**${filePath}** — ${total} lines, ${nodes.length} symbol${nodes.length === 1 ? '' : 's'} · ${depSummary}`;
3833
+ // Numbered lines, byte-for-byte Read's shape: `<n>\t<line>`, no left-pad.
3834
+ const numbered = [];
3835
+ let used = header.length + 8;
3836
+ let i = start;
3837
+ for (; i < total && numbered.length < maxLines; i++) {
3838
+ const ln = `${i + 1}\t${fileLines[i]}`;
3839
+ if (used + ln.length + 1 > CHAR_BUDGET && numbered.length > 0)
3840
+ break;
3841
+ numbered.push(ln);
3842
+ used += ln.length + 1;
3843
+ }
3844
+ const shownEnd = start + numbered.length;
3845
+ const complete = offset === 1 && shownEnd >= total;
3846
+ const out = [header, '', ...numbered];
3847
+ if (!complete) {
3848
+ out.push('', `(lines ${offset}–${shownEnd} of ${total} — pass \`offset\`/\`limit\` for another range, or \`codegraph_node <symbol>\` for one symbol in full)`);
3849
+ }
3850
+ // Self-bounded to CHAR_BUDGET — do NOT route through truncateOutput (15k).
3851
+ return this.textResult(out.join('\n'));
3852
+ }
3853
+ /** Render one symbol: details + (optional) body/outline + its caller/callee trail. */
3854
+ async renderNodeSection(cg, node, includeCode) {
3855
+ let code = null;
3856
+ let outline = null;
3857
+ if (includeCode) {
3858
+ // For container symbols (class/interface/struct/…), the full body is the
3859
+ // sum of every method body — a wall of source. Return a structural outline
3860
+ // (members + signatures + line numbers) instead; leaf symbols return their
3861
+ // full body.
3862
+ if (CONTAINER_NODE_KINDS.has(node.kind)) {
3863
+ outline = this.buildContainerOutline(cg, node);
3864
+ }
3865
+ if (!outline) {
3866
+ code = await cg.getCode(node.id);
3867
+ }
3868
+ }
3869
+ return this.formatNodeDetails(node, code, outline) + this.formatTrail(cg, node);
3870
+ }
3871
+ /**
3872
+ * Build the "trail" for a symbol: its direct callees (what it calls) and
3873
+ * callers (what calls it), each with file:line — so codegraph_node doubles as
3874
+ * the structural Grep→Read→expand primitive: a spot PLUS where to go next.
3875
+ * Capped to stay cheap. Walk the graph by calling codegraph_node on a trail
3876
+ * entry; no Read needed for covered hops. Empty edges on a non-leaf often mean
3877
+ * dynamic dispatch the static graph couldn't resolve — that absence is itself
3878
+ * a signal (read that one hop) rather than a dead end.
3879
+ */
3880
+ formatTrail(cg, node) {
3881
+ const TRAIL_CAP = 12;
3882
+ const fmt = (e) => {
3883
+ const base = `${e.node.name} (${e.node.filePath}:${e.node.startLine})`;
3884
+ const synth = this.synthEdgeNote(e.edge);
3885
+ return synth ? `${base} [${synth.compact}]` : base;
3886
+ };
3887
+ const collect = (edges) => {
3888
+ const seen = new Set([node.id]);
3889
+ const out = [];
3890
+ for (const e of edges) {
3891
+ if (seen.has(e.node.id))
3892
+ continue;
3893
+ seen.add(e.node.id);
3894
+ out.push(e);
3895
+ }
3896
+ return out;
3897
+ };
3898
+ const callees = collect(cg.getCallees(node.id));
3899
+ const callers = collect(cg.getCallers(node.id));
3900
+ if (callees.length === 0 && callers.length === 0)
3901
+ return '';
3902
+ const lines = ['', '**Trail — codegraph_node any of these to follow it (no Read needed)**'];
3903
+ if (callees.length > 0) {
3904
+ lines.push(`**Calls →** ${callees.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callees.length > TRAIL_CAP ? `, +${callees.length - TRAIL_CAP} more` : ''}`);
3905
+ }
3906
+ if (callers.length > 0) {
3907
+ lines.push(`**Called by ←** ${callers.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callers.length > TRAIL_CAP ? `, +${callers.length - TRAIL_CAP} more` : ''}`);
3908
+ }
3909
+ return lines.join('\n');
3910
+ }
3911
+ /**
3912
+ * Handle codegraph_status
3913
+ */
3914
+ async handleStatus(args) {
3915
+ let cg = this.getCodeGraph(args.projectPath);
3916
+ // Same trick as withStalenessNotice — when an explicit projectPath
3917
+ // resolves to the same project as the default session cg, prefer the
3918
+ // default so getPendingFiles() (only populated by the default's watcher)
3919
+ // is non-empty when there are pending edits.
3920
+ if (this.cg && cg !== this.cg) {
3921
+ try {
3922
+ if ((0, path_1.resolve)(this.cg.getProjectRoot()) === (0, path_1.resolve)(cg.getProjectRoot())) {
3923
+ cg = this.cg;
3924
+ }
3925
+ }
3926
+ catch { /* closed instance — leave as is */ }
3927
+ }
3928
+ const stats = cg.getStats();
3929
+ // Warn when this index actually belongs to a different git working tree
3930
+ // (e.g. the server resolved up from a nested worktree to the main checkout).
3931
+ // Queries then reflect that tree's branch, not the worktree being edited.
3932
+ // status shows the verbose, multi-line form; the read tools get the compact
3933
+ // one-liner via withWorktreeNotice. Both share the cached detection.
3934
+ const mismatch = this.worktreeMismatchFor(args.projectPath);
3935
+ const lines = [
3936
+ '**CodeGraph Status**',
3937
+ '',
3938
+ ];
3939
+ if (mismatch) {
3940
+ lines.push(`> ⚠ ${(0, worktree_1.worktreeMismatchWarning)(mismatch).replace(/\n/g, '\n> ')}`, '');
3941
+ }
3942
+ lines.push(`**Files indexed:** ${stats.fileCount}`, `**Total nodes:** ${stats.nodeCount}`, `**Total edges:** ${stats.edgeCount}`, `**Database size:** ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
3943
+ // Surface the active SQLite backend (node:sqlite, Node's built-in real
3944
+ // SQLite — full WAL + FTS5, no native build).
3945
+ lines.push(`**Backend:** node:sqlite (Node built-in) — full WAL + FTS5`);
3946
+ // Effective journal mode. 'wal' ⇒ concurrent reads never block on a writer;
3947
+ // anything else ⇒ they can ("database is locked"). node:sqlite supports WAL
3948
+ // everywhere, so a non-wal mode means the filesystem can't (network/
3949
+ // virtualized mounts, WSL2 /mnt). See issue #238.
3950
+ const journalMode = cg.getJournalMode();
3951
+ if (journalMode === 'wal') {
3952
+ lines.push(`**Journal mode:** wal (concurrent reads safe)`);
3953
+ }
3954
+ else {
3955
+ lines.push(`**Journal mode:** ⚠ ${journalMode || 'unknown'} — WAL not active, so reads ` +
3956
+ `can block on a concurrent write (WAL appears unsupported on this filesystem)`);
3957
+ }
3958
+ // A newer release exists (#1243) — status is where users and agents look
3959
+ // when something seems off, so surface the drift here too. Cheap memoized
3960
+ // cache read; absent entirely when up to date or opted out.
3961
+ const updateNotice = (0, update_check_1.getUpdateNotice)();
3962
+ if (updateNotice) {
3963
+ lines.push(`**Update available:** ${updateNotice}`);
3964
+ }
3965
+ // Non-zero at rest means a resolution pass was interrupted mid-run, so
3966
+ // some files' call/impact edges are missing until the next sync sweeps
3967
+ // the leftovers (#1187). Surface it — an agent trusting an incomplete
3968
+ // blast radius is worse than one that knows to re-sync.
3969
+ const pendingRefs = cg.getPendingReferenceCount();
3970
+ if (pendingRefs > 0) {
3971
+ lines.push(`**Pending resolution:** ⚠ ${pendingRefs} references from an interrupted ` +
3972
+ `index run — some caller/impact edges are missing until the next sync ` +
3973
+ `(any file change triggers it, or run \`codegraph sync\`)`);
3974
+ }
3975
+ lines.push('', '**Nodes by Kind:**');
3976
+ for (const [kind, count] of Object.entries(stats.nodesByKind)) {
3977
+ if (count > 0) {
3978
+ lines.push(`- ${kind}: ${count}`);
3979
+ }
3980
+ }
3981
+ lines.push('', '**Languages:**');
3982
+ for (const [lang, count] of Object.entries(stats.filesByLanguage)) {
3983
+ if (count > 0) {
3984
+ lines.push(`- ${lang}: ${count}`);
3985
+ }
3986
+ }
3987
+ // Whole-index degradation (#876): when live watching has permanently
3988
+ // stopped, getPendingFiles() is empty (so no "Pending sync" section below)
3989
+ // but the index is frozen — call that out explicitly here, the one place an
3990
+ // agent asks "is the index caught up?".
3991
+ if (cg.isWatcherDegraded()) {
3992
+ lines.push('', '**Auto-sync disabled:**', `- ${cg.getWatcherDegradedReason() ?? 'live file watching stopped'}`, '- The index is frozen; Read files directly for current content.');
3993
+ }
3994
+ // Per-file freshness — the inverse of the auto-prepended staleness banner
3995
+ // (issue #403). Surfacing it inside `status` gives the agent a single
3996
+ // place to ask "is the index caught up?" rather than inferring from
3997
+ // banners on other tool calls.
3998
+ const pending = cg.getPendingFiles();
3999
+ if (pending.length > 0) {
4000
+ lines.push('', '**Pending sync:**');
4001
+ const now = Date.now();
4002
+ for (const p of pending) {
4003
+ const ageMs = Math.max(0, now - p.lastSeenMs);
4004
+ const label = p.indexing ? 'indexing in progress' : 'pending sync';
4005
+ lines.push(`- ${p.path} (edited ${ageMs}ms ago, ${label})`);
4006
+ }
4007
+ }
4008
+ return this.textResult(lines.join('\n'));
4009
+ }
4010
+ /**
4011
+ * Handle codegraph_files - get project file structure from the index
4012
+ */
4013
+ async handleFiles(args) {
4014
+ const cg = this.getCodeGraph(args.projectPath);
4015
+ const pathFilter = args.path;
4016
+ const pattern = args.pattern;
4017
+ const format = args.format || 'tree';
4018
+ const includeMetadata = args.includeMetadata !== false;
4019
+ const maxDepth = args.maxDepth != null ? (0, utils_1.clamp)(args.maxDepth, 1, 20) : undefined;
4020
+ // Get all files from the index
4021
+ const allFiles = cg.getFiles();
4022
+ if (allFiles.length === 0) {
4023
+ return this.textResult('No files indexed. Run `codegraph index` first.');
4024
+ }
4025
+ // Filter by path prefix. Stored paths are project-relative POSIX (e.g.
4026
+ // "src/foo.ts"), but agents commonly pass project-root variants like "/",
4027
+ // ".", "./", "" or Windows-style "src\foo" — and prefixes with leading
4028
+ // "/", "./" or "\". Normalize all of those before matching so the agent
4029
+ // gets results instead of falling back to Read/Glob (see #426).
4030
+ const normalizedFilter = pathFilter
4031
+ ? pathFilter
4032
+ .replace(/\\/g, '/')
4033
+ .replace(/^(?:\.?\/+)+/, '')
4034
+ .replace(/^\.$/, '')
4035
+ .replace(/\/+$/, '')
4036
+ : '';
4037
+ let files = normalizedFilter
4038
+ ? allFiles.filter(f => f.path === normalizedFilter || f.path.startsWith(normalizedFilter + '/'))
4039
+ : allFiles;
4040
+ // Filter by glob pattern
4041
+ if (pattern) {
4042
+ const regex = this.globToRegex(pattern);
4043
+ files = files.filter(f => regex.test(f.path));
4044
+ }
4045
+ if (files.length === 0) {
4046
+ return this.textResult(`No files found matching the criteria.`);
4047
+ }
4048
+ // Format output
4049
+ let output;
4050
+ switch (format) {
4051
+ case 'flat':
4052
+ output = this.formatFilesFlat(files, includeMetadata);
4053
+ break;
4054
+ case 'grouped':
4055
+ output = this.formatFilesGrouped(files, includeMetadata);
4056
+ break;
4057
+ case 'tree':
4058
+ default:
4059
+ output = this.formatFilesTree(files, includeMetadata, maxDepth);
4060
+ break;
4061
+ }
4062
+ return this.textResult(this.truncateOutput(output));
4063
+ }
4064
+ /**
4065
+ * Convert glob pattern to regex
4066
+ */
4067
+ globToRegex(pattern) {
4068
+ const escaped = pattern
4069
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special regex chars except * and ?
4070
+ .replace(/\*\*/g, '{{GLOBSTAR}}') // Temp placeholder for **
4071
+ .replace(/\*/g, '[^/]*') // * matches anything except /
4072
+ .replace(/\?/g, '[^/]') // ? matches single char except /
4073
+ .replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** matches anything including /
4074
+ return new RegExp(escaped);
4075
+ }
4076
+ /**
4077
+ * Format files as a flat list
4078
+ */
4079
+ formatFilesFlat(files, includeMetadata) {
4080
+ const lines = [`**Files (${files.length})**`, ''];
4081
+ for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
4082
+ if (includeMetadata) {
4083
+ lines.push(`- ${file.path} (${file.language}, ${file.nodeCount} symbols)`);
4084
+ }
4085
+ else {
4086
+ lines.push(`- ${file.path}`);
4087
+ }
4088
+ }
4089
+ return lines.join('\n');
4090
+ }
4091
+ /**
4092
+ * Format files grouped by language
4093
+ */
4094
+ formatFilesGrouped(files, includeMetadata) {
4095
+ const byLang = new Map();
4096
+ for (const file of files) {
4097
+ const existing = byLang.get(file.language) || [];
4098
+ existing.push(file);
4099
+ byLang.set(file.language, existing);
4100
+ }
4101
+ const lines = [`**Files by Language (${files.length} total)**`, ''];
4102
+ // Sort languages by file count (descending)
4103
+ const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
4104
+ for (const [lang, langFiles] of sortedLangs) {
4105
+ lines.push(`**${lang} (${langFiles.length})**`);
4106
+ for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
4107
+ if (includeMetadata) {
4108
+ lines.push(`- ${file.path} (${file.nodeCount} symbols)`);
4109
+ }
4110
+ else {
4111
+ lines.push(`- ${file.path}`);
4112
+ }
4113
+ }
4114
+ lines.push('');
4115
+ }
4116
+ return lines.join('\n');
4117
+ }
4118
+ /**
4119
+ * Format files as a tree structure
4120
+ */
4121
+ formatFilesTree(files, includeMetadata, maxDepth) {
4122
+ const root = { name: '', children: new Map() };
4123
+ for (const file of files) {
4124
+ const parts = file.path.split('/');
4125
+ let current = root;
4126
+ for (let i = 0; i < parts.length; i++) {
4127
+ const part = parts[i];
4128
+ if (!part)
4129
+ continue;
4130
+ if (!current.children.has(part)) {
4131
+ current.children.set(part, { name: part, children: new Map() });
4132
+ }
4133
+ current = current.children.get(part);
4134
+ // If this is the last part, it's a file
4135
+ if (i === parts.length - 1) {
4136
+ current.file = { language: file.language, nodeCount: file.nodeCount };
4137
+ }
4138
+ }
4139
+ }
4140
+ // Render tree
4141
+ const lines = [`**Project Structure (${files.length} files)**`, ''];
4142
+ const renderNode = (node, prefix, isLast, depth) => {
4143
+ if (maxDepth !== undefined && depth > maxDepth)
4144
+ return;
4145
+ const connector = isLast ? '└── ' : '├── ';
4146
+ const childPrefix = isLast ? ' ' : '│ ';
4147
+ if (node.name) {
4148
+ let line = prefix + connector + node.name;
4149
+ if (node.file && includeMetadata) {
4150
+ line += ` (${node.file.language}, ${node.file.nodeCount} symbols)`;
4151
+ }
4152
+ lines.push(line);
4153
+ }
4154
+ const children = [...node.children.values()];
4155
+ // Sort: directories first, then files, both alphabetically
4156
+ children.sort((a, b) => {
4157
+ const aIsDir = a.children.size > 0 && !a.file;
4158
+ const bIsDir = b.children.size > 0 && !b.file;
4159
+ if (aIsDir !== bIsDir)
4160
+ return aIsDir ? -1 : 1;
4161
+ return a.name.localeCompare(b.name);
4162
+ });
4163
+ for (let i = 0; i < children.length; i++) {
4164
+ const child = children[i];
4165
+ const nextPrefix = node.name ? prefix + childPrefix : prefix;
4166
+ renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
4167
+ }
4168
+ };
4169
+ renderNode(root, '', true, 0);
4170
+ return lines.join('\n');
4171
+ }
4172
+ // =========================================================================
4173
+ // Symbol resolution helpers
4174
+ // =========================================================================
4175
+ /**
4176
+ * Find a symbol by name, handling disambiguation when multiple matches exist.
4177
+ * Returns the best match and a note about alternatives if any.
4178
+ */
4179
+ /**
4180
+ * Check if a node matches a symbol query.
4181
+ *
4182
+ * Accepts simple names (`run`) and three flavors of qualifier:
4183
+ * - dotted `Session.request` (TS/JS/Python)
4184
+ * - colon-pair `stage_apply::run` (Rust, C++, Ruby)
4185
+ * - slash `configurator/stage_apply` (path-ish)
4186
+ *
4187
+ * Multi-level qualifiers compose: `crate::configurator::stage_apply::run`
4188
+ * works. Rust path prefixes (`crate`, `super`, `self`) are stripped so
4189
+ * the canonical `crate::module::symbol` form resolves.
4190
+ *
4191
+ * Resolution order, last part must always equal `node.name`:
4192
+ * 1. Suffix-match against `qualifiedName` (handles class-scoped methods
4193
+ * where the extractor builds the qualified name from the AST stack)
4194
+ * 2. File-path containment (handles file-derived modules in Rust/
4195
+ * Python — `stage_apply::run` matches a `run` in `stage_apply.rs`)
4196
+ */
4197
+ matchesSymbol(node, symbol) {
4198
+ // Simple name match
4199
+ if (node.name === symbol)
4200
+ return true;
4201
+ // File basename match (e.g., "product-card" matches "product-card.liquid")
4202
+ if (node.kind === 'file' && node.name.replace(/\.[^.]+$/, '') === symbol)
4203
+ return true;
4204
+ // Qualified-name lookups: split on any supported separator. `\w` keeps
4205
+ // identifier chars (incl. `_`) intact; everything else is treated as
4206
+ // a separator we tolerate.
4207
+ if (!/[.\/]|::/.test(symbol))
4208
+ return false;
4209
+ const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
4210
+ if (parts.length < 2)
4211
+ return false;
4212
+ const lastPart = parts[parts.length - 1];
4213
+ if (node.name !== lastPart)
4214
+ return false;
4215
+ // Stage 1: qualified-name suffix match. The extractor joins the
4216
+ // semantic hierarchy with `::`, so `Session.request` and
4217
+ // `Session::request` both become `Session::request` here.
4218
+ const colonSuffix = parts.join('::');
4219
+ if (node.qualifiedName.includes(colonSuffix))
4220
+ return true;
4221
+ // Stage 2: file-path containment. Rust modules and Python packages
4222
+ // are not in `qualifiedName` — they're encoded in the file path. So
4223
+ // `stage_apply::run` matches a `run` in any file whose path
4224
+ // contains a `stage_apply` segment (with or without an extension).
4225
+ //
4226
+ // Filter out Rust path prefixes that have no file-system equivalent.
4227
+ const containerHints = parts.slice(0, -1).filter((p) => !RUST_PATH_PREFIXES.has(p));
4228
+ if (containerHints.length === 0)
4229
+ return false;
4230
+ const segments = node.filePath.split('/').filter((s) => s.length > 0);
4231
+ return containerHints.every((hint) => segments.some((seg) => seg === hint || seg.replace(/\.[^.]+$/, '') === hint));
4232
+ }
4233
+ /**
4234
+ * Find ALL definitions matching a name, ranked, so codegraph_node can return
4235
+ * every overload instead of guessing one (the wrong guess → a Read). Keepers
4236
+ * rank before generated stubs (.pb.go etc.); stable within a group preserves
4237
+ * FTS order. Returns [] when nothing matches; a qualified lookup that finds no
4238
+ * exact match returns [] rather than a misleading fuzzy file hit (#173); a
4239
+ * bare name with no exact match falls back to the single top fuzzy result.
4240
+ */
4241
+ findSymbolMatches(cg, symbol) {
4242
+ const isQualified = /[.\/]|::/.test(symbol);
4243
+ // For a bare name, enumerate EVERY exact-name definition via the direct index
4244
+ // (not FTS, which caps + ranks): tokio's `poll` has 50+ defs and the one the
4245
+ // caller wants (`Harness::poll` at harness.rs:153) ranks below any search cut,
4246
+ // so it could be neither rendered nor pinned by the file/line disambiguator —
4247
+ // and the agent Read it. With the full set, the multi-overload render + the
4248
+ // file/line filter can both reach it.
4249
+ if (!isQualified) {
4250
+ const exact = cg.getNodesByName(symbol);
4251
+ if (exact.length > 0) {
4252
+ return [...exact].sort((a, b) => ((0, generated_detection_1.isGeneratedFile)(a.filePath) ? 1 : 0) - ((0, generated_detection_1.isGeneratedFile)(b.filePath) ? 1 : 0));
4253
+ }
4254
+ // No exact match — use the single top fuzzy result (e.g. a file basename).
4255
+ const fuzzy = cg.searchNodes(symbol, { limit: 10 });
4256
+ return fuzzy[0] ? [fuzzy[0].node] : [];
4257
+ }
4258
+ // Qualified lookup (`Session.request`, `stage_apply::run`): FTS + matchesSymbol.
4259
+ const limit = 50;
4260
+ let results = cg.searchNodes(symbol, { limit });
4261
+ // FTS strips colons, so `stage_apply::run` searches the literal
4262
+ // `stage_applyrun` and finds nothing. Re-search by the bare last part and
4263
+ // let `matchesSymbol` filter by qualifier.
4264
+ if (isQualified && results.length === 0) {
4265
+ const tail = lastQualifierPart(symbol);
4266
+ if (tail && tail !== symbol)
4267
+ results = cg.searchNodes(tail, { limit });
4268
+ }
4269
+ if (results.length === 0)
4270
+ return [];
4271
+ const exactMatches = results.filter((r) => this.matchesSymbol(r.node, symbol));
4272
+ if (exactMatches.length === 0) {
4273
+ // No exact match — a qualified lookup must not fall back to a fuzzy file
4274
+ // hit (#173); a bare name may use the single top fuzzy result.
4275
+ return isQualified ? [] : results[0] ? [results[0].node] : [];
4276
+ }
4277
+ // Down-rank generated files (.pb.go, .pulsar.go, _grpc.pb.go, …) so a flow
4278
+ // query prefers the keeper implementation over the protobuf-generated stub.
4279
+ return [...exactMatches]
4280
+ .sort((a, b) => ((0, generated_detection_1.isGeneratedFile)(a.node.filePath) ? 1 : 0) - ((0, generated_detection_1.isGeneratedFile)(b.node.filePath) ? 1 : 0))
4281
+ .map((r) => r.node);
4282
+ }
4283
+ /**
4284
+ * Find ALL symbols matching a name. Used by callers/callees/impact to aggregate
4285
+ * results across all matching symbols (e.g., multiple classes with an `execute` method).
4286
+ */
4287
+ findAllSymbols(cg, symbol) {
4288
+ // Nix option paths: the declaration is stored as `options.<path>` and
4289
+ // config writes carry longer/quoted tails (`<path>."git/config".text`),
4290
+ // so a dotted option token (`xdg.configFile`, `launchd.user.agents`) has
4291
+ // no exact-name node and would degrade to bare-tail FTS soup — burying
4292
+ // the declaration hub the nix-option-path edges hang off. Resolve the
4293
+ // convention directly: declaration first, then the exact write, then a
4294
+ // capped prefix scan of write sites. Three index hits; non-nix graphs
4295
+ // fall straight through.
4296
+ if (/^[a-z][\w'-]*(?:\.[\w'-]+)+$/.test(symbol)) {
4297
+ const optionHits = [
4298
+ ...cg.getNodesByName(`options.${symbol}`),
4299
+ ...cg.getNodesByName(symbol),
4300
+ ...cg.getNodesByNamePrefix(`${symbol}.`, 12),
4301
+ ].filter((n) => n.language === 'nix');
4302
+ if (optionHits.length > 0) {
4303
+ const seen = new Set();
4304
+ const nodes = optionHits.filter((n) => !seen.has(n.id) && !!seen.add(n.id)).slice(0, 10);
4305
+ return { nodes, note: '' };
4306
+ }
4307
+ }
4308
+ let results = cg.searchNodes(symbol, { limit: 50 });
4309
+ // Mirror the fallback in `findSymbol` for qualified queries — FTS
4310
+ // strips colons, so a module-qualified lookup needs a second pass
4311
+ // by the bare last part.
4312
+ if (results.length === 0 && /[.\/]|::/.test(symbol)) {
4313
+ const tail = lastQualifierPart(symbol);
4314
+ if (tail && tail !== symbol)
4315
+ results = cg.searchNodes(tail, { limit: 50 });
4316
+ }
4317
+ if (results.length === 0) {
4318
+ return { nodes: [], note: '' };
4319
+ }
4320
+ const exactMatches = results.filter(r => this.matchesSymbol(r.node, symbol));
4321
+ if (exactMatches.length <= 1) {
4322
+ const node = exactMatches[0]?.node ?? results[0].node;
4323
+ return { nodes: [node], note: '' };
4324
+ }
4325
+ // Same generated-file down-rank as findSymbol — keeps callers/callees
4326
+ // /impact aggregation aligned (a query against "Send" returns the
4327
+ // hand-written implementations before the protobuf scaffold).
4328
+ const ranked = [...exactMatches].sort((a, b) => {
4329
+ const aGen = (0, generated_detection_1.isGeneratedFile)(a.node.filePath) ? 1 : 0;
4330
+ const bGen = (0, generated_detection_1.isGeneratedFile)(b.node.filePath) ? 1 : 0;
4331
+ return aGen - bGen;
4332
+ });
4333
+ const locations = ranked.map(r => `${r.node.kind} at ${r.node.filePath}:${r.node.startLine}`);
4334
+ const note = `\n\n> **Note:** Aggregated results across ${ranked.length} symbols named "${symbol}": ${locations.join(', ')}`;
4335
+ return { nodes: ranked.map(r => r.node), note };
4336
+ }
4337
+ /**
4338
+ * Truncate output if it exceeds the maximum length
4339
+ */
4340
+ truncateOutput(text) {
4341
+ if (text.length <= MAX_OUTPUT_LENGTH)
4342
+ return text;
4343
+ const truncated = text.slice(0, MAX_OUTPUT_LENGTH);
4344
+ const lastNewline = truncated.lastIndexOf('\n');
4345
+ const cutPoint = lastNewline > MAX_OUTPUT_LENGTH * 0.8 ? lastNewline : MAX_OUTPUT_LENGTH;
4346
+ return truncated.slice(0, cutPoint) + '\n\n... (output truncated)';
4347
+ }
4348
+ // =========================================================================
4349
+ // Formatting helpers (compact by default to reduce context usage)
4350
+ // =========================================================================
4351
+ formatSearchResults(results) {
4352
+ const lines = [`**Search Results (${results.length} found)**`, ''];
4353
+ for (const result of results) {
4354
+ const { node } = result;
4355
+ const location = node.startLine ? `:${node.startLine}` : '';
4356
+ // Compact format: one line per result with key info
4357
+ lines.push(`**${node.name}** (${node.kind})`);
4358
+ lines.push(`${node.filePath}${location}`);
4359
+ if (node.signature)
4360
+ lines.push(`\`${node.signature}\``);
4361
+ lines.push('');
4362
+ }
4363
+ return lines.join('\n');
4364
+ }
4365
+ formatNodeList(nodes, title, labels) {
4366
+ const lines = [`**${title} (${nodes.length} found)**`, ''];
4367
+ for (const node of nodes) {
4368
+ const location = node.startLine ? `:${node.startLine}` : '';
4369
+ // Compact: just name, kind, location — plus the relationship when it
4370
+ // isn't a plain call (callback registration, instantiation, …).
4371
+ const label = labels?.get(node.id);
4372
+ lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
4373
+ }
4374
+ return lines.join('\n');
4375
+ }
4376
+ /**
4377
+ * Relationship label for a non-`calls` edge in callers/callees lists. A
4378
+ * function-as-value edge (#756) is the high-signal one: `callers(cb)`
4379
+ * showing "via callback registration" tells the agent this is where the
4380
+ * callback is WIRED, not where it's invoked.
4381
+ */
4382
+ edgeLabel(edge) {
4383
+ if (edge.kind === 'calls')
4384
+ return null;
4385
+ if (edge.metadata?.fnRef === true)
4386
+ return 'callback registration';
4387
+ if (edge.kind === 'instantiates')
4388
+ return 'instantiation';
4389
+ if (edge.kind === 'imports')
4390
+ return 'import';
4391
+ if (edge.kind === 'references')
4392
+ return 'reference';
4393
+ return edge.kind;
4394
+ }
4395
+ formatImpact(symbol, impact) {
4396
+ const nodeCount = impact.nodes.size;
4397
+ // Compact format: just list affected symbols grouped by file
4398
+ const lines = [
4399
+ `**Impact: "${symbol}" affects ${nodeCount} symbols**`,
4400
+ '',
4401
+ ];
4402
+ // Group by file
4403
+ const byFile = new Map();
4404
+ for (const node of impact.nodes.values()) {
4405
+ const existing = byFile.get(node.filePath) || [];
4406
+ existing.push(node);
4407
+ byFile.set(node.filePath, existing);
4408
+ }
4409
+ for (const [file, nodes] of byFile) {
4410
+ lines.push(`**${file}:**`);
4411
+ // Compact: inline list
4412
+ const nodeList = nodes.map(n => `${n.name}:${n.startLine}`).join(', ');
4413
+ lines.push(nodeList);
4414
+ lines.push('');
4415
+ }
4416
+ return lines.join('\n');
4417
+ }
4418
+ /**
4419
+ * Build a compact structural outline of a container symbol from its
4420
+ * indexed children (methods, fields, properties, …) — name, kind,
4421
+ * line number, and signature — so the agent gets the shape of a class
4422
+ * without the full source of every method. Returns '' when the container
4423
+ * has no indexed children, so the caller can fall back to full source.
4424
+ */
4425
+ buildContainerOutline(cg, node) {
4426
+ const children = cg.getChildren(node.id)
4427
+ .filter(c => c.kind !== 'import' && c.kind !== 'export')
4428
+ .sort((a, b) => (a.startLine ?? 0) - (b.startLine ?? 0));
4429
+ if (children.length === 0)
4430
+ return '';
4431
+ const lines = [`**Members (${children.length}):**`, ''];
4432
+ for (const c of children) {
4433
+ const loc = c.startLine ? `:${c.startLine}` : '';
4434
+ const sig = c.signature ? ` — \`${c.signature}\`` : '';
4435
+ lines.push(`- ${c.name} (${c.kind})${loc}${sig}`);
4436
+ }
4437
+ return lines.join('\n');
4438
+ }
4439
+ formatNodeDetails(node, code, outline) {
4440
+ const location = node.startLine ? `:${node.startLine}` : '';
4441
+ const lines = [
4442
+ `**${node.name}** (${node.kind})`,
4443
+ '',
4444
+ `**Location:** ${node.filePath}${location}`,
4445
+ ];
4446
+ if (node.signature) {
4447
+ lines.push(`**Signature:** \`${node.signature}\``);
4448
+ }
4449
+ // Only include docstring if it's short and useful
4450
+ if (node.docstring && node.docstring.length < 200) {
4451
+ lines.push('', node.docstring);
4452
+ }
4453
+ if (outline) {
4454
+ lines.push('', outline, '', `> Structural outline only. Read \`${node.filePath}\` or call codegraph_node on a specific member for its body.`);
4455
+ }
4456
+ else if (code) {
4457
+ // Line-numbered (cat -n style, like codegraph_explore and Read) so the
4458
+ // agent can cite/edit exact lines without re-Reading the file for them.
4459
+ const numbered = node.startLine ? numberSourceLines(code, node.startLine) : code;
4460
+ lines.push('', '```' + node.language, numbered, '```');
4461
+ }
4462
+ return lines.join('\n');
4463
+ }
4464
+ textResult(text) {
4465
+ return {
4466
+ content: [{ type: 'text', text }],
4467
+ };
4468
+ }
4469
+ errorResult(message) {
4470
+ return {
4471
+ content: [{ type: 'text', text: `Error: ${message}` }],
4472
+ isError: true,
4473
+ };
4474
+ }
4475
+ }
4476
+ exports.ToolHandler = ToolHandler;
4477
+ //# sourceMappingURL=tools.js.map