@colbymchenry/codegraph-win32-arm64 1.6.0 → 1.6.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 (761) hide show
  1. package/bin/codegraph +5 -0
  2. package/lib/dist/.test-build-engine.json +1 -0
  3. package/lib/dist/.test-build-viewer.json +1 -0
  4. package/lib/dist/bin/codegraph.d.ts +1 -0
  5. package/lib/dist/bin/codegraph.d.ts.map +1 -1
  6. package/lib/dist/bin/codegraph.js +605 -291
  7. package/lib/dist/bin/codegraph.js.map +1 -1
  8. package/lib/dist/bin/command-supervision.d.ts +7 -0
  9. package/lib/dist/bin/command-supervision.d.ts.map +1 -1
  10. package/lib/dist/bin/command-supervision.js +39 -27
  11. package/lib/dist/bin/command-supervision.js.map +1 -1
  12. package/lib/dist/bin/viewer-gate.d.ts +17 -0
  13. package/lib/dist/bin/viewer-gate.d.ts.map +1 -0
  14. package/lib/dist/bin/viewer-gate.js +31 -0
  15. package/lib/dist/bin/viewer-gate.js.map +1 -0
  16. package/lib/dist/context/index.d.ts.map +1 -1
  17. package/lib/dist/context/index.js +43 -2
  18. package/lib/dist/context/index.js.map +1 -1
  19. package/lib/dist/db/index.d.ts +21 -2
  20. package/lib/dist/db/index.d.ts.map +1 -1
  21. package/lib/dist/db/index.js +86 -31
  22. package/lib/dist/db/index.js.map +1 -1
  23. package/lib/dist/db/migrations.d.ts +1 -1
  24. package/lib/dist/db/migrations.d.ts.map +1 -1
  25. package/lib/dist/db/migrations.js +40 -1
  26. package/lib/dist/db/migrations.js.map +1 -1
  27. package/lib/dist/db/queries.d.ts +454 -10
  28. package/lib/dist/db/queries.d.ts.map +1 -1
  29. package/lib/dist/db/queries.js +1080 -41
  30. package/lib/dist/db/queries.js.map +1 -1
  31. package/lib/dist/db/schema.sql +11 -1
  32. package/lib/dist/db/sqlite-adapter.d.ts +2 -0
  33. package/lib/dist/db/sqlite-adapter.d.ts.map +1 -1
  34. package/lib/dist/db/sqlite-adapter.js +56 -7
  35. package/lib/dist/db/sqlite-adapter.js.map +1 -1
  36. package/lib/dist/db/synthesis-stage.d.ts +12 -0
  37. package/lib/dist/db/synthesis-stage.d.ts.map +1 -0
  38. package/lib/dist/db/synthesis-stage.js +89 -0
  39. package/lib/dist/db/synthesis-stage.js.map +1 -0
  40. package/lib/dist/db/wal-valve.d.ts +32 -12
  41. package/lib/dist/db/wal-valve.d.ts.map +1 -1
  42. package/lib/dist/db/wal-valve.js +65 -22
  43. package/lib/dist/db/wal-valve.js.map +1 -1
  44. package/lib/dist/db/wsl-shared-index.d.ts +53 -0
  45. package/lib/dist/db/wsl-shared-index.d.ts.map +1 -0
  46. package/lib/dist/db/wsl-shared-index.js +121 -0
  47. package/lib/dist/db/wsl-shared-index.js.map +1 -0
  48. package/lib/dist/directory.d.ts +131 -2
  49. package/lib/dist/directory.d.ts.map +1 -1
  50. package/lib/dist/directory.js +299 -23
  51. package/lib/dist/directory.js.map +1 -1
  52. package/lib/dist/errors.d.ts +14 -0
  53. package/lib/dist/errors.d.ts.map +1 -1
  54. package/lib/dist/errors.js +16 -1
  55. package/lib/dist/errors.js.map +1 -1
  56. package/lib/dist/extraction/astro-extractor.d.ts.map +1 -1
  57. package/lib/dist/extraction/astro-extractor.js +7 -35
  58. package/lib/dist/extraction/astro-extractor.js.map +1 -1
  59. package/lib/dist/extraction/cfml-extractor.d.ts +77 -10
  60. package/lib/dist/extraction/cfml-extractor.d.ts.map +1 -1
  61. package/lib/dist/extraction/cfml-extractor.js +302 -71
  62. package/lib/dist/extraction/cfml-extractor.js.map +1 -1
  63. package/lib/dist/extraction/commonjs-requires.d.ts +23 -0
  64. package/lib/dist/extraction/commonjs-requires.d.ts.map +1 -0
  65. package/lib/dist/extraction/commonjs-requires.js +68 -0
  66. package/lib/dist/extraction/commonjs-requires.js.map +1 -0
  67. package/lib/dist/extraction/dfm-extractor.d.ts.map +1 -1
  68. package/lib/dist/extraction/dfm-extractor.js +14 -10
  69. package/lib/dist/extraction/dfm-extractor.js.map +1 -1
  70. package/lib/dist/extraction/extraction-version.d.ts +1 -1
  71. package/lib/dist/extraction/extraction-version.js +1 -1
  72. package/lib/dist/extraction/function-ref.d.ts +6 -4
  73. package/lib/dist/extraction/function-ref.d.ts.map +1 -1
  74. package/lib/dist/extraction/function-ref.js +35 -14
  75. package/lib/dist/extraction/function-ref.js.map +1 -1
  76. package/lib/dist/extraction/generated-detection.d.ts +9 -0
  77. package/lib/dist/extraction/generated-detection.d.ts.map +1 -1
  78. package/lib/dist/extraction/generated-detection.js +42 -2
  79. package/lib/dist/extraction/generated-detection.js.map +1 -1
  80. package/lib/dist/extraction/grammars.d.ts +40 -0
  81. package/lib/dist/extraction/grammars.d.ts.map +1 -1
  82. package/lib/dist/extraction/grammars.js +171 -1
  83. package/lib/dist/extraction/grammars.js.map +1 -1
  84. package/lib/dist/extraction/index.d.ts +132 -19
  85. package/lib/dist/extraction/index.d.ts.map +1 -1
  86. package/lib/dist/extraction/index.js +825 -195
  87. package/lib/dist/extraction/index.js.map +1 -1
  88. package/lib/dist/extraction/kernel/index.d.ts.map +1 -1
  89. package/lib/dist/extraction/kernel/index.js +6 -0
  90. package/lib/dist/extraction/kernel/index.js.map +1 -1
  91. package/lib/dist/extraction/languages/c-cpp.d.ts +73 -0
  92. package/lib/dist/extraction/languages/c-cpp.d.ts.map +1 -1
  93. package/lib/dist/extraction/languages/c-cpp.js +412 -16
  94. package/lib/dist/extraction/languages/c-cpp.js.map +1 -1
  95. package/lib/dist/extraction/languages/csharp.d.ts.map +1 -1
  96. package/lib/dist/extraction/languages/csharp.js +14 -5
  97. package/lib/dist/extraction/languages/csharp.js.map +1 -1
  98. package/lib/dist/extraction/languages/dart.d.ts.map +1 -1
  99. package/lib/dist/extraction/languages/dart.js +16 -3
  100. package/lib/dist/extraction/languages/dart.js.map +1 -1
  101. package/lib/dist/extraction/languages/javascript.js +1 -1
  102. package/lib/dist/extraction/languages/javascript.js.map +1 -1
  103. package/lib/dist/extraction/languages/kotlin.d.ts +4 -0
  104. package/lib/dist/extraction/languages/kotlin.d.ts.map +1 -1
  105. package/lib/dist/extraction/languages/kotlin.js +237 -36
  106. package/lib/dist/extraction/languages/kotlin.js.map +1 -1
  107. package/lib/dist/extraction/languages/lua.d.ts.map +1 -1
  108. package/lib/dist/extraction/languages/lua.js +4 -1
  109. package/lib/dist/extraction/languages/lua.js.map +1 -1
  110. package/lib/dist/extraction/languages/python.d.ts.map +1 -1
  111. package/lib/dist/extraction/languages/python.js +71 -0
  112. package/lib/dist/extraction/languages/python.js.map +1 -1
  113. package/lib/dist/extraction/languages/rust.d.ts.map +1 -1
  114. package/lib/dist/extraction/languages/rust.js +3 -0
  115. package/lib/dist/extraction/languages/rust.js.map +1 -1
  116. package/lib/dist/extraction/languages/scala.d.ts.map +1 -1
  117. package/lib/dist/extraction/languages/scala.js +18 -3
  118. package/lib/dist/extraction/languages/scala.js.map +1 -1
  119. package/lib/dist/extraction/languages/swift.d.ts +15 -0
  120. package/lib/dist/extraction/languages/swift.d.ts.map +1 -1
  121. package/lib/dist/extraction/languages/swift.js +50 -0
  122. package/lib/dist/extraction/languages/swift.js.map +1 -1
  123. package/lib/dist/extraction/languages/typescript.d.ts +7 -0
  124. package/lib/dist/extraction/languages/typescript.d.ts.map +1 -1
  125. package/lib/dist/extraction/languages/typescript.js +30 -2
  126. package/lib/dist/extraction/languages/typescript.js.map +1 -1
  127. package/lib/dist/extraction/liquid-extractor.d.ts +18 -0
  128. package/lib/dist/extraction/liquid-extractor.d.ts.map +1 -1
  129. package/lib/dist/extraction/liquid-extractor.js +98 -22
  130. package/lib/dist/extraction/liquid-extractor.js.map +1 -1
  131. package/lib/dist/extraction/mybatis-extractor.d.ts.map +1 -1
  132. package/lib/dist/extraction/mybatis-extractor.js +6 -4
  133. package/lib/dist/extraction/mybatis-extractor.js.map +1 -1
  134. package/lib/dist/extraction/parse-budget.d.ts +16 -0
  135. package/lib/dist/extraction/parse-budget.d.ts.map +1 -0
  136. package/lib/dist/extraction/parse-budget.js +24 -0
  137. package/lib/dist/extraction/parse-budget.js.map +1 -0
  138. package/lib/dist/extraction/parse-pool.d.ts +12 -0
  139. package/lib/dist/extraction/parse-pool.d.ts.map +1 -1
  140. package/lib/dist/extraction/parse-pool.js +51 -3
  141. package/lib/dist/extraction/parse-pool.js.map +1 -1
  142. package/lib/dist/extraction/parse-worker.js +3 -1
  143. package/lib/dist/extraction/parse-worker.js.map +1 -1
  144. package/lib/dist/extraction/sfc-script.d.ts +43 -0
  145. package/lib/dist/extraction/sfc-script.d.ts.map +1 -0
  146. package/lib/dist/extraction/sfc-script.js +135 -0
  147. package/lib/dist/extraction/sfc-script.js.map +1 -0
  148. package/lib/dist/extraction/store-worker.js +5 -0
  149. package/lib/dist/extraction/store-worker.js.map +1 -1
  150. package/lib/dist/extraction/store-writer.d.ts +10 -2
  151. package/lib/dist/extraction/store-writer.d.ts.map +1 -1
  152. package/lib/dist/extraction/store-writer.js +12 -4
  153. package/lib/dist/extraction/store-writer.js.map +1 -1
  154. package/lib/dist/extraction/svelte-extractor.d.ts.map +1 -1
  155. package/lib/dist/extraction/svelte-extractor.js +7 -37
  156. package/lib/dist/extraction/svelte-extractor.js.map +1 -1
  157. package/lib/dist/extraction/syntax-tokens.d.ts +103 -0
  158. package/lib/dist/extraction/syntax-tokens.d.ts.map +1 -0
  159. package/lib/dist/extraction/syntax-tokens.js +382 -0
  160. package/lib/dist/extraction/syntax-tokens.js.map +1 -0
  161. package/lib/dist/extraction/tree-sitter-helpers.d.ts +5 -0
  162. package/lib/dist/extraction/tree-sitter-helpers.d.ts.map +1 -1
  163. package/lib/dist/extraction/tree-sitter-helpers.js +17 -0
  164. package/lib/dist/extraction/tree-sitter-helpers.js.map +1 -1
  165. package/lib/dist/extraction/tree-sitter-types.d.ts +29 -3
  166. package/lib/dist/extraction/tree-sitter-types.d.ts.map +1 -1
  167. package/lib/dist/extraction/tree-sitter.d.ts +104 -17
  168. package/lib/dist/extraction/tree-sitter.d.ts.map +1 -1
  169. package/lib/dist/extraction/tree-sitter.js +943 -88
  170. package/lib/dist/extraction/tree-sitter.js.map +1 -1
  171. package/lib/dist/extraction/vue-extractor.d.ts +7 -0
  172. package/lib/dist/extraction/vue-extractor.d.ts.map +1 -1
  173. package/lib/dist/extraction/vue-extractor.js +73 -35
  174. package/lib/dist/extraction/vue-extractor.js.map +1 -1
  175. package/lib/dist/extraction/vue-options-api.d.ts +28 -0
  176. package/lib/dist/extraction/vue-options-api.d.ts.map +1 -0
  177. package/lib/dist/extraction/vue-options-api.js +196 -0
  178. package/lib/dist/extraction/vue-options-api.js.map +1 -0
  179. package/lib/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  180. package/lib/dist/extraction/wasm/tree-sitter-kotlin.wasm +0 -0
  181. package/lib/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  182. package/lib/dist/file-limits.d.ts +40 -0
  183. package/lib/dist/file-limits.d.ts.map +1 -0
  184. package/lib/dist/file-limits.js +147 -0
  185. package/lib/dist/file-limits.js.map +1 -0
  186. package/lib/dist/graph/branch-guards.d.ts +265 -0
  187. package/lib/dist/graph/branch-guards.d.ts.map +1 -0
  188. package/lib/dist/graph/branch-guards.js +2326 -0
  189. package/lib/dist/graph/branch-guards.js.map +1 -0
  190. package/lib/dist/graph/dead-code.d.ts +251 -0
  191. package/lib/dist/graph/dead-code.d.ts.map +1 -0
  192. package/lib/dist/graph/dead-code.js +776 -0
  193. package/lib/dist/graph/dead-code.js.map +1 -0
  194. package/lib/dist/graph/dynamic-boundary-report.d.ts +121 -0
  195. package/lib/dist/graph/dynamic-boundary-report.d.ts.map +1 -0
  196. package/lib/dist/graph/dynamic-boundary-report.js +283 -0
  197. package/lib/dist/graph/dynamic-boundary-report.js.map +1 -0
  198. package/lib/dist/graph/index.d.ts +4 -0
  199. package/lib/dist/graph/index.d.ts.map +1 -1
  200. package/lib/dist/graph/index.js +16 -1
  201. package/lib/dist/graph/index.js.map +1 -1
  202. package/lib/dist/graph/named-symbol-flow.d.ts +125 -0
  203. package/lib/dist/graph/named-symbol-flow.d.ts.map +1 -0
  204. package/lib/dist/graph/named-symbol-flow.js +559 -0
  205. package/lib/dist/graph/named-symbol-flow.js.map +1 -0
  206. package/lib/dist/graph/symbol-lookup.d.ts +83 -0
  207. package/lib/dist/graph/symbol-lookup.d.ts.map +1 -0
  208. package/lib/dist/graph/symbol-lookup.js +181 -0
  209. package/lib/dist/graph/symbol-lookup.js.map +1 -0
  210. package/lib/dist/graph/traversal.d.ts +9 -0
  211. package/lib/dist/graph/traversal.d.ts.map +1 -1
  212. package/lib/dist/graph/traversal.js +61 -35
  213. package/lib/dist/graph/traversal.js.map +1 -1
  214. package/lib/dist/graph/type-hierarchy.d.ts +155 -0
  215. package/lib/dist/graph/type-hierarchy.d.ts.map +1 -0
  216. package/lib/dist/graph/type-hierarchy.js +382 -0
  217. package/lib/dist/graph/type-hierarchy.js.map +1 -0
  218. package/lib/dist/index.d.ts +256 -11
  219. package/lib/dist/index.d.ts.map +1 -1
  220. package/lib/dist/index.js +402 -34
  221. package/lib/dist/index.js.map +1 -1
  222. package/lib/dist/installer/index.d.ts.map +1 -1
  223. package/lib/dist/installer/index.js +3 -2
  224. package/lib/dist/installer/index.js.map +1 -1
  225. package/lib/dist/installer/targets/antigravity.d.ts.map +1 -1
  226. package/lib/dist/installer/targets/antigravity.js +14 -2
  227. package/lib/dist/installer/targets/antigravity.js.map +1 -1
  228. package/lib/dist/installer/targets/claude.d.ts +3 -0
  229. package/lib/dist/installer/targets/claude.d.ts.map +1 -1
  230. package/lib/dist/installer/targets/claude.js +35 -7
  231. package/lib/dist/installer/targets/claude.js.map +1 -1
  232. package/lib/dist/installer/targets/codex.d.ts +2 -1
  233. package/lib/dist/installer/targets/codex.d.ts.map +1 -1
  234. package/lib/dist/installer/targets/codex.js +14 -4
  235. package/lib/dist/installer/targets/codex.js.map +1 -1
  236. package/lib/dist/installer/targets/copilot-cli.d.ts.map +1 -1
  237. package/lib/dist/installer/targets/copilot-cli.js +7 -1
  238. package/lib/dist/installer/targets/copilot-cli.js.map +1 -1
  239. package/lib/dist/installer/targets/opencode.d.ts +16 -5
  240. package/lib/dist/installer/targets/opencode.d.ts.map +1 -1
  241. package/lib/dist/installer/targets/opencode.js +73 -22
  242. package/lib/dist/installer/targets/opencode.js.map +1 -1
  243. package/lib/dist/installer/targets/shared.d.ts +14 -3
  244. package/lib/dist/installer/targets/shared.d.ts.map +1 -1
  245. package/lib/dist/installer/targets/shared.js +39 -11
  246. package/lib/dist/installer/targets/shared.js.map +1 -1
  247. package/lib/dist/installer/targets/types.d.ts +7 -0
  248. package/lib/dist/installer/targets/types.d.ts.map +1 -1
  249. package/lib/dist/mcp/answer-freshness.d.ts +10 -0
  250. package/lib/dist/mcp/answer-freshness.d.ts.map +1 -0
  251. package/lib/dist/mcp/answer-freshness.js +68 -0
  252. package/lib/dist/mcp/answer-freshness.js.map +1 -0
  253. package/lib/dist/mcp/daemon-manager.d.ts.map +1 -1
  254. package/lib/dist/mcp/daemon-manager.js +16 -0
  255. package/lib/dist/mcp/daemon-manager.js.map +1 -1
  256. package/lib/dist/mcp/daemon-paths.d.ts +2 -0
  257. package/lib/dist/mcp/daemon-paths.d.ts.map +1 -1
  258. package/lib/dist/mcp/daemon-paths.js +20 -5
  259. package/lib/dist/mcp/daemon-paths.js.map +1 -1
  260. package/lib/dist/mcp/daemon-registry.d.ts +11 -4
  261. package/lib/dist/mcp/daemon-registry.d.ts.map +1 -1
  262. package/lib/dist/mcp/daemon-registry.js +132 -36
  263. package/lib/dist/mcp/daemon-registry.js.map +1 -1
  264. package/lib/dist/mcp/daemon.d.ts +17 -7
  265. package/lib/dist/mcp/daemon.d.ts.map +1 -1
  266. package/lib/dist/mcp/daemon.js +116 -24
  267. package/lib/dist/mcp/daemon.js.map +1 -1
  268. package/lib/dist/mcp/dynamic-boundaries.d.ts +1 -10
  269. package/lib/dist/mcp/dynamic-boundaries.d.ts.map +1 -1
  270. package/lib/dist/mcp/dynamic-boundaries.js +46 -42
  271. package/lib/dist/mcp/dynamic-boundaries.js.map +1 -1
  272. package/lib/dist/mcp/engine.d.ts +30 -9
  273. package/lib/dist/mcp/engine.d.ts.map +1 -1
  274. package/lib/dist/mcp/engine.js +158 -66
  275. package/lib/dist/mcp/engine.js.map +1 -1
  276. package/lib/dist/mcp/explore-dedup.d.ts +5 -2
  277. package/lib/dist/mcp/explore-dedup.d.ts.map +1 -1
  278. package/lib/dist/mcp/explore-dedup.js +8 -5
  279. package/lib/dist/mcp/explore-dedup.js.map +1 -1
  280. package/lib/dist/mcp/index-freshness-worker.d.ts +2 -0
  281. package/lib/dist/mcp/index-freshness-worker.d.ts.map +1 -0
  282. package/lib/dist/mcp/index-freshness-worker.js +36 -0
  283. package/lib/dist/mcp/index-freshness-worker.js.map +1 -0
  284. package/lib/dist/mcp/index-freshness.d.ts +13 -0
  285. package/lib/dist/mcp/index-freshness.d.ts.map +1 -0
  286. package/lib/dist/mcp/index-freshness.js +117 -0
  287. package/lib/dist/mcp/index-freshness.js.map +1 -0
  288. package/lib/dist/mcp/index.d.ts +3 -1
  289. package/lib/dist/mcp/index.d.ts.map +1 -1
  290. package/lib/dist/mcp/index.js +95 -11
  291. package/lib/dist/mcp/index.js.map +1 -1
  292. package/lib/dist/mcp/liveness-watchdog.d.ts +4 -1
  293. package/lib/dist/mcp/liveness-watchdog.d.ts.map +1 -1
  294. package/lib/dist/mcp/liveness-watchdog.js +11 -2
  295. package/lib/dist/mcp/liveness-watchdog.js.map +1 -1
  296. package/lib/dist/mcp/project-lifecycle.d.ts +9 -0
  297. package/lib/dist/mcp/project-lifecycle.d.ts.map +1 -0
  298. package/lib/dist/mcp/project-lifecycle.js +182 -0
  299. package/lib/dist/mcp/project-lifecycle.js.map +1 -0
  300. package/lib/dist/mcp/proxy.d.ts +9 -2
  301. package/lib/dist/mcp/proxy.d.ts.map +1 -1
  302. package/lib/dist/mcp/proxy.js +201 -32
  303. package/lib/dist/mcp/proxy.js.map +1 -1
  304. package/lib/dist/mcp/query-pool.d.ts +18 -3
  305. package/lib/dist/mcp/query-pool.d.ts.map +1 -1
  306. package/lib/dist/mcp/query-pool.js +67 -11
  307. package/lib/dist/mcp/query-pool.js.map +1 -1
  308. package/lib/dist/mcp/query-worker.js +2 -2
  309. package/lib/dist/mcp/query-worker.js.map +1 -1
  310. package/lib/dist/mcp/server-instructions.d.ts +1 -1
  311. package/lib/dist/mcp/server-instructions.d.ts.map +1 -1
  312. package/lib/dist/mcp/server-instructions.js +6 -3
  313. package/lib/dist/mcp/server-instructions.js.map +1 -1
  314. package/lib/dist/mcp/startup-handshake.d.ts +3 -1
  315. package/lib/dist/mcp/startup-handshake.d.ts.map +1 -1
  316. package/lib/dist/mcp/startup-handshake.js +10 -2
  317. package/lib/dist/mcp/startup-handshake.js.map +1 -1
  318. package/lib/dist/mcp/tools.d.ts +306 -36
  319. package/lib/dist/mcp/tools.d.ts.map +1 -1
  320. package/lib/dist/mcp/tools.js +2395 -966
  321. package/lib/dist/mcp/tools.js.map +1 -1
  322. package/lib/dist/mcp/writer-lock.d.ts +61 -0
  323. package/lib/dist/mcp/writer-lock.d.ts.map +1 -0
  324. package/lib/dist/mcp/writer-lock.js +260 -0
  325. package/lib/dist/mcp/writer-lock.js.map +1 -0
  326. package/lib/dist/resolution/alias-binding.d.ts +56 -0
  327. package/lib/dist/resolution/alias-binding.d.ts.map +1 -0
  328. package/lib/dist/resolution/alias-binding.js +143 -0
  329. package/lib/dist/resolution/alias-binding.js.map +1 -0
  330. package/lib/dist/resolution/angular-template-synthesizer.d.ts +49 -0
  331. package/lib/dist/resolution/angular-template-synthesizer.d.ts.map +1 -0
  332. package/lib/dist/resolution/angular-template-synthesizer.js +359 -0
  333. package/lib/dist/resolution/angular-template-synthesizer.js.map +1 -0
  334. package/lib/dist/resolution/callback-synthesizer.d.ts +23 -1
  335. package/lib/dist/resolution/callback-synthesizer.d.ts.map +1 -1
  336. package/lib/dist/resolution/callback-synthesizer.js +460 -144
  337. package/lib/dist/resolution/callback-synthesizer.js.map +1 -1
  338. package/lib/dist/resolution/cpp-constructor.d.ts +4 -0
  339. package/lib/dist/resolution/cpp-constructor.d.ts.map +1 -0
  340. package/lib/dist/resolution/cpp-constructor.js +123 -0
  341. package/lib/dist/resolution/cpp-constructor.js.map +1 -0
  342. package/lib/dist/resolution/cpp-macro-visibility.d.ts +12 -0
  343. package/lib/dist/resolution/cpp-macro-visibility.d.ts.map +1 -0
  344. package/lib/dist/resolution/cpp-macro-visibility.js +392 -0
  345. package/lib/dist/resolution/cpp-macro-visibility.js.map +1 -0
  346. package/lib/dist/resolution/expo-router-synthesizer.d.ts +32 -0
  347. package/lib/dist/resolution/expo-router-synthesizer.d.ts.map +1 -0
  348. package/lib/dist/resolution/expo-router-synthesizer.js +189 -0
  349. package/lib/dist/resolution/expo-router-synthesizer.js.map +1 -0
  350. package/lib/dist/resolution/frameworks/angular-router.d.ts +142 -0
  351. package/lib/dist/resolution/frameworks/angular-router.d.ts.map +1 -0
  352. package/lib/dist/resolution/frameworks/angular-router.js +1126 -0
  353. package/lib/dist/resolution/frameworks/angular-router.js.map +1 -0
  354. package/lib/dist/resolution/frameworks/astro.d.ts.map +1 -1
  355. package/lib/dist/resolution/frameworks/astro.js +32 -6
  356. package/lib/dist/resolution/frameworks/astro.js.map +1 -1
  357. package/lib/dist/resolution/frameworks/csharp.d.ts.map +1 -1
  358. package/lib/dist/resolution/frameworks/csharp.js +186 -24
  359. package/lib/dist/resolution/frameworks/csharp.js.map +1 -1
  360. package/lib/dist/resolution/frameworks/expo-modules.d.ts +10 -0
  361. package/lib/dist/resolution/frameworks/expo-modules.d.ts.map +1 -1
  362. package/lib/dist/resolution/frameworks/expo-modules.js +95 -1
  363. package/lib/dist/resolution/frameworks/expo-modules.js.map +1 -1
  364. package/lib/dist/resolution/frameworks/expo-router.d.ts +195 -0
  365. package/lib/dist/resolution/frameworks/expo-router.d.ts.map +1 -0
  366. package/lib/dist/resolution/frameworks/expo-router.js +847 -0
  367. package/lib/dist/resolution/frameworks/expo-router.js.map +1 -0
  368. package/lib/dist/resolution/frameworks/express.d.ts.map +1 -1
  369. package/lib/dist/resolution/frameworks/express.js +339 -45
  370. package/lib/dist/resolution/frameworks/express.js.map +1 -1
  371. package/lib/dist/resolution/frameworks/fabric.d.ts.map +1 -1
  372. package/lib/dist/resolution/frameworks/fabric.js +13 -11
  373. package/lib/dist/resolution/frameworks/fabric.js.map +1 -1
  374. package/lib/dist/resolution/frameworks/go.d.ts.map +1 -1
  375. package/lib/dist/resolution/frameworks/go.js +11 -28
  376. package/lib/dist/resolution/frameworks/go.js.map +1 -1
  377. package/lib/dist/resolution/frameworks/index.d.ts +8 -2
  378. package/lib/dist/resolution/frameworks/index.d.ts.map +1 -1
  379. package/lib/dist/resolution/frameworks/index.js +39 -1
  380. package/lib/dist/resolution/frameworks/index.js.map +1 -1
  381. package/lib/dist/resolution/frameworks/java.d.ts.map +1 -1
  382. package/lib/dist/resolution/frameworks/java.js +88 -68
  383. package/lib/dist/resolution/frameworks/java.js.map +1 -1
  384. package/lib/dist/resolution/frameworks/laravel.d.ts.map +1 -1
  385. package/lib/dist/resolution/frameworks/laravel.js +369 -26
  386. package/lib/dist/resolution/frameworks/laravel.js.map +1 -1
  387. package/lib/dist/resolution/frameworks/name-heuristic.d.ts +35 -0
  388. package/lib/dist/resolution/frameworks/name-heuristic.d.ts.map +1 -0
  389. package/lib/dist/resolution/frameworks/name-heuristic.js +45 -0
  390. package/lib/dist/resolution/frameworks/name-heuristic.js.map +1 -0
  391. package/lib/dist/resolution/frameworks/nestjs.d.ts.map +1 -1
  392. package/lib/dist/resolution/frameworks/nestjs.js +288 -55
  393. package/lib/dist/resolution/frameworks/nestjs.js.map +1 -1
  394. package/lib/dist/resolution/frameworks/nextjs.d.ts +76 -0
  395. package/lib/dist/resolution/frameworks/nextjs.d.ts.map +1 -0
  396. package/lib/dist/resolution/frameworks/nextjs.js +329 -0
  397. package/lib/dist/resolution/frameworks/nextjs.js.map +1 -0
  398. package/lib/dist/resolution/frameworks/object-literal.d.ts +32 -0
  399. package/lib/dist/resolution/frameworks/object-literal.d.ts.map +1 -0
  400. package/lib/dist/resolution/frameworks/object-literal.js +139 -0
  401. package/lib/dist/resolution/frameworks/object-literal.js.map +1 -0
  402. package/lib/dist/resolution/frameworks/package-deps.d.ts +14 -0
  403. package/lib/dist/resolution/frameworks/package-deps.d.ts.map +1 -0
  404. package/lib/dist/resolution/frameworks/package-deps.js +78 -0
  405. package/lib/dist/resolution/frameworks/package-deps.js.map +1 -0
  406. package/lib/dist/resolution/frameworks/page-component.d.ts +20 -0
  407. package/lib/dist/resolution/frameworks/page-component.d.ts.map +1 -0
  408. package/lib/dist/resolution/frameworks/page-component.js +45 -0
  409. package/lib/dist/resolution/frameworks/page-component.js.map +1 -0
  410. package/lib/dist/resolution/frameworks/play.d.ts.map +1 -1
  411. package/lib/dist/resolution/frameworks/play.js +3 -1
  412. package/lib/dist/resolution/frameworks/play.js.map +1 -1
  413. package/lib/dist/resolution/frameworks/python.d.ts.map +1 -1
  414. package/lib/dist/resolution/frameworks/python.js +279 -26
  415. package/lib/dist/resolution/frameworks/python.js.map +1 -1
  416. package/lib/dist/resolution/frameworks/react-native.d.ts +26 -0
  417. package/lib/dist/resolution/frameworks/react-native.d.ts.map +1 -1
  418. package/lib/dist/resolution/frameworks/react-native.js +153 -14
  419. package/lib/dist/resolution/frameworks/react-native.js.map +1 -1
  420. package/lib/dist/resolution/frameworks/react-router.d.ts +47 -0
  421. package/lib/dist/resolution/frameworks/react-router.d.ts.map +1 -0
  422. package/lib/dist/resolution/frameworks/react-router.js +201 -0
  423. package/lib/dist/resolution/frameworks/react-router.js.map +1 -0
  424. package/lib/dist/resolution/frameworks/react.d.ts +13 -2
  425. package/lib/dist/resolution/frameworks/react.d.ts.map +1 -1
  426. package/lib/dist/resolution/frameworks/react.js +542 -144
  427. package/lib/dist/resolution/frameworks/react.js.map +1 -1
  428. package/lib/dist/resolution/frameworks/ruby.d.ts.map +1 -1
  429. package/lib/dist/resolution/frameworks/ruby.js +177 -17
  430. package/lib/dist/resolution/frameworks/ruby.js.map +1 -1
  431. package/lib/dist/resolution/frameworks/rust.d.ts.map +1 -1
  432. package/lib/dist/resolution/frameworks/rust.js +24 -22
  433. package/lib/dist/resolution/frameworks/rust.js.map +1 -1
  434. package/lib/dist/resolution/frameworks/svelte.d.ts.map +1 -1
  435. package/lib/dist/resolution/frameworks/svelte.js +14 -6
  436. package/lib/dist/resolution/frameworks/svelte.js.map +1 -1
  437. package/lib/dist/resolution/frameworks/sveltekit-router.d.ts +36 -0
  438. package/lib/dist/resolution/frameworks/sveltekit-router.d.ts.map +1 -0
  439. package/lib/dist/resolution/frameworks/sveltekit-router.js +156 -0
  440. package/lib/dist/resolution/frameworks/sveltekit-router.js.map +1 -0
  441. package/lib/dist/resolution/frameworks/swift.d.ts.map +1 -1
  442. package/lib/dist/resolution/frameworks/swift.js +253 -124
  443. package/lib/dist/resolution/frameworks/swift.js.map +1 -1
  444. package/lib/dist/resolution/frameworks/tanstack-router.d.ts +84 -0
  445. package/lib/dist/resolution/frameworks/tanstack-router.d.ts.map +1 -0
  446. package/lib/dist/resolution/frameworks/tanstack-router.js +437 -0
  447. package/lib/dist/resolution/frameworks/tanstack-router.js.map +1 -0
  448. package/lib/dist/resolution/frameworks/vue-router.d.ts +98 -0
  449. package/lib/dist/resolution/frameworks/vue-router.d.ts.map +1 -0
  450. package/lib/dist/resolution/frameworks/vue-router.js +500 -0
  451. package/lib/dist/resolution/frameworks/vue-router.js.map +1 -0
  452. package/lib/dist/resolution/frameworks/vue.d.ts +9 -2
  453. package/lib/dist/resolution/frameworks/vue.d.ts.map +1 -1
  454. package/lib/dist/resolution/frameworks/vue.js +45 -11
  455. package/lib/dist/resolution/frameworks/vue.js.map +1 -1
  456. package/lib/dist/resolution/import-resolver.d.ts +66 -0
  457. package/lib/dist/resolution/import-resolver.d.ts.map +1 -1
  458. package/lib/dist/resolution/import-resolver.js +643 -61
  459. package/lib/dist/resolution/import-resolver.js.map +1 -1
  460. package/lib/dist/resolution/index.d.ts +124 -25
  461. package/lib/dist/resolution/index.d.ts.map +1 -1
  462. package/lib/dist/resolution/index.js +769 -152
  463. package/lib/dist/resolution/index.js.map +1 -1
  464. package/lib/dist/resolution/js-builtins.d.ts +13 -0
  465. package/lib/dist/resolution/js-builtins.d.ts.map +1 -0
  466. package/lib/dist/resolution/js-builtins.js +48 -0
  467. package/lib/dist/resolution/js-builtins.js.map +1 -0
  468. package/lib/dist/resolution/name-matcher.d.ts +101 -22
  469. package/lib/dist/resolution/name-matcher.d.ts.map +1 -1
  470. package/lib/dist/resolution/name-matcher.js +8267 -287
  471. package/lib/dist/resolution/name-matcher.js.map +1 -1
  472. package/lib/dist/resolution/next-router-synthesizer.d.ts +27 -0
  473. package/lib/dist/resolution/next-router-synthesizer.d.ts.map +1 -0
  474. package/lib/dist/resolution/next-router-synthesizer.js +113 -0
  475. package/lib/dist/resolution/next-router-synthesizer.js.map +1 -0
  476. package/lib/dist/resolution/react-router-synthesizer.d.ts +35 -0
  477. package/lib/dist/resolution/react-router-synthesizer.d.ts.map +1 -0
  478. package/lib/dist/resolution/react-router-synthesizer.js +197 -0
  479. package/lib/dist/resolution/react-router-synthesizer.js.map +1 -0
  480. package/lib/dist/resolution/resolver-pool.d.ts +22 -1
  481. package/lib/dist/resolution/resolver-pool.d.ts.map +1 -1
  482. package/lib/dist/resolution/resolver-pool.js +35 -5
  483. package/lib/dist/resolution/resolver-pool.js.map +1 -1
  484. package/lib/dist/resolution/resolver-worker.js +3 -0
  485. package/lib/dist/resolution/resolver-worker.js.map +1 -1
  486. package/lib/dist/resolution/strip-comments.d.ts +6 -0
  487. package/lib/dist/resolution/strip-comments.d.ts.map +1 -1
  488. package/lib/dist/resolution/strip-comments.js +58 -0
  489. package/lib/dist/resolution/strip-comments.js.map +1 -1
  490. package/lib/dist/resolution/sveltekit-synthesizer.d.ts +58 -0
  491. package/lib/dist/resolution/sveltekit-synthesizer.d.ts.map +1 -0
  492. package/lib/dist/resolution/sveltekit-synthesizer.js +173 -0
  493. package/lib/dist/resolution/sveltekit-synthesizer.js.map +1 -0
  494. package/lib/dist/resolution/swift-type-visibility.d.ts +68 -0
  495. package/lib/dist/resolution/swift-type-visibility.d.ts.map +1 -0
  496. package/lib/dist/resolution/swift-type-visibility.js +454 -0
  497. package/lib/dist/resolution/swift-type-visibility.js.map +1 -0
  498. package/lib/dist/resolution/synth-utils.d.ts +26 -0
  499. package/lib/dist/resolution/synth-utils.d.ts.map +1 -0
  500. package/lib/dist/resolution/synth-utils.js +75 -0
  501. package/lib/dist/resolution/synth-utils.js.map +1 -0
  502. package/lib/dist/resolution/tanstack-router-synthesizer.d.ts +31 -0
  503. package/lib/dist/resolution/tanstack-router-synthesizer.d.ts.map +1 -0
  504. package/lib/dist/resolution/tanstack-router-synthesizer.js +114 -0
  505. package/lib/dist/resolution/tanstack-router-synthesizer.js.map +1 -0
  506. package/lib/dist/resolution/tier-synthesizer.d.ts +54 -0
  507. package/lib/dist/resolution/tier-synthesizer.d.ts.map +1 -0
  508. package/lib/dist/resolution/tier-synthesizer.js +1294 -0
  509. package/lib/dist/resolution/tier-synthesizer.js.map +1 -0
  510. package/lib/dist/resolution/type-parameters.d.ts +11 -0
  511. package/lib/dist/resolution/type-parameters.d.ts.map +1 -0
  512. package/lib/dist/resolution/type-parameters.js +287 -0
  513. package/lib/dist/resolution/type-parameters.js.map +1 -0
  514. package/lib/dist/resolution/types.d.ts +105 -2
  515. package/lib/dist/resolution/types.d.ts.map +1 -1
  516. package/lib/dist/resolution/types.js +64 -0
  517. package/lib/dist/resolution/types.js.map +1 -1
  518. package/lib/dist/resolution/vue-router-synthesizer.d.ts +30 -0
  519. package/lib/dist/resolution/vue-router-synthesizer.d.ts.map +1 -0
  520. package/lib/dist/resolution/vue-router-synthesizer.js +115 -0
  521. package/lib/dist/resolution/vue-router-synthesizer.js.map +1 -0
  522. package/lib/dist/search/query-paths.d.ts +50 -1
  523. package/lib/dist/search/query-paths.d.ts.map +1 -1
  524. package/lib/dist/search/query-paths.js +227 -12
  525. package/lib/dist/search/query-paths.js.map +1 -1
  526. package/lib/dist/search/query-utils.d.ts +15 -0
  527. package/lib/dist/search/query-utils.d.ts.map +1 -1
  528. package/lib/dist/search/query-utils.js +35 -7
  529. package/lib/dist/search/query-utils.js.map +1 -1
  530. package/lib/dist/sync/watch-policy.d.ts +14 -0
  531. package/lib/dist/sync/watch-policy.d.ts.map +1 -1
  532. package/lib/dist/sync/watch-policy.js +19 -0
  533. package/lib/dist/sync/watch-policy.js.map +1 -1
  534. package/lib/dist/sync/watcher.d.ts +52 -35
  535. package/lib/dist/sync/watcher.d.ts.map +1 -1
  536. package/lib/dist/sync/watcher.js +236 -100
  537. package/lib/dist/sync/watcher.js.map +1 -1
  538. package/lib/dist/sync/worktree.d.ts +22 -0
  539. package/lib/dist/sync/worktree.d.ts.map +1 -1
  540. package/lib/dist/sync/worktree.js +54 -0
  541. package/lib/dist/sync/worktree.js.map +1 -1
  542. package/lib/dist/telemetry/index.d.ts +4 -2
  543. package/lib/dist/telemetry/index.d.ts.map +1 -1
  544. package/lib/dist/telemetry/index.js +159 -66
  545. package/lib/dist/telemetry/index.js.map +1 -1
  546. package/lib/dist/types.d.ts +1 -1
  547. package/lib/dist/types.d.ts.map +1 -1
  548. package/lib/dist/types.js +1 -0
  549. package/lib/dist/types.js.map +1 -1
  550. package/lib/dist/ui-server/api/deadcode.d.ts +84 -0
  551. package/lib/dist/ui-server/api/deadcode.d.ts.map +1 -0
  552. package/lib/dist/ui-server/api/deadcode.js +136 -0
  553. package/lib/dist/ui-server/api/deadcode.js.map +1 -0
  554. package/lib/dist/ui-server/api/effects.d.ts +94 -0
  555. package/lib/dist/ui-server/api/effects.d.ts.map +1 -0
  556. package/lib/dist/ui-server/api/effects.js +527 -0
  557. package/lib/dist/ui-server/api/effects.js.map +1 -0
  558. package/lib/dist/ui-server/api/entrypoints.d.ts +92 -0
  559. package/lib/dist/ui-server/api/entrypoints.d.ts.map +1 -0
  560. package/lib/dist/ui-server/api/entrypoints.js +364 -0
  561. package/lib/dist/ui-server/api/entrypoints.js.map +1 -0
  562. package/lib/dist/ui-server/api/events.d.ts +183 -0
  563. package/lib/dist/ui-server/api/events.d.ts.map +1 -0
  564. package/lib/dist/ui-server/api/events.js +430 -0
  565. package/lib/dist/ui-server/api/events.js.map +1 -0
  566. package/lib/dist/ui-server/api/file.d.ts +66 -0
  567. package/lib/dist/ui-server/api/file.d.ts.map +1 -0
  568. package/lib/dist/ui-server/api/file.js +235 -0
  569. package/lib/dist/ui-server/api/file.js.map +1 -0
  570. package/lib/dist/ui-server/api/filecode.d.ts +126 -0
  571. package/lib/dist/ui-server/api/filecode.d.ts.map +1 -0
  572. package/lib/dist/ui-server/api/filecode.js +205 -0
  573. package/lib/dist/ui-server/api/filecode.js.map +1 -0
  574. package/lib/dist/ui-server/api/flow.d.ts +226 -0
  575. package/lib/dist/ui-server/api/flow.d.ts.map +1 -0
  576. package/lib/dist/ui-server/api/flow.js +612 -0
  577. package/lib/dist/ui-server/api/flow.js.map +1 -0
  578. package/lib/dist/ui-server/api/hierarchy.d.ts +81 -0
  579. package/lib/dist/ui-server/api/hierarchy.d.ts.map +1 -0
  580. package/lib/dist/ui-server/api/hierarchy.js +92 -0
  581. package/lib/dist/ui-server/api/hierarchy.js.map +1 -0
  582. package/lib/dist/ui-server/api/index.d.ts +90 -0
  583. package/lib/dist/ui-server/api/index.d.ts.map +1 -0
  584. package/lib/dist/ui-server/api/index.js +332 -0
  585. package/lib/dist/ui-server/api/index.js.map +1 -0
  586. package/lib/dist/ui-server/api/map.d.ts +273 -0
  587. package/lib/dist/ui-server/api/map.d.ts.map +1 -0
  588. package/lib/dist/ui-server/api/map.js +781 -0
  589. package/lib/dist/ui-server/api/map.js.map +1 -0
  590. package/lib/dist/ui-server/api/node.d.ts +81 -0
  591. package/lib/dist/ui-server/api/node.d.ts.map +1 -0
  592. package/lib/dist/ui-server/api/node.js +394 -0
  593. package/lib/dist/ui-server/api/node.js.map +1 -0
  594. package/lib/dist/ui-server/api/nodes.d.ts +25 -0
  595. package/lib/dist/ui-server/api/nodes.d.ts.map +1 -0
  596. package/lib/dist/ui-server/api/nodes.js +45 -0
  597. package/lib/dist/ui-server/api/nodes.js.map +1 -0
  598. package/lib/dist/ui-server/api/program.d.ts +139 -0
  599. package/lib/dist/ui-server/api/program.d.ts.map +1 -0
  600. package/lib/dist/ui-server/api/program.js +315 -0
  601. package/lib/dist/ui-server/api/program.js.map +1 -0
  602. package/lib/dist/ui-server/api/respond.d.ts +76 -0
  603. package/lib/dist/ui-server/api/respond.d.ts.map +1 -0
  604. package/lib/dist/ui-server/api/respond.js +186 -0
  605. package/lib/dist/ui-server/api/respond.js.map +1 -0
  606. package/lib/dist/ui-server/api/route-roots.d.ts +45 -0
  607. package/lib/dist/ui-server/api/route-roots.d.ts.map +1 -0
  608. package/lib/dist/ui-server/api/route-roots.js +117 -0
  609. package/lib/dist/ui-server/api/route-roots.js.map +1 -0
  610. package/lib/dist/ui-server/api/routes.d.ts +61 -0
  611. package/lib/dist/ui-server/api/routes.d.ts.map +1 -0
  612. package/lib/dist/ui-server/api/routes.js +164 -0
  613. package/lib/dist/ui-server/api/routes.js.map +1 -0
  614. package/lib/dist/ui-server/api/screens.d.ts +117 -0
  615. package/lib/dist/ui-server/api/screens.d.ts.map +1 -0
  616. package/lib/dist/ui-server/api/screens.js +626 -0
  617. package/lib/dist/ui-server/api/screens.js.map +1 -0
  618. package/lib/dist/ui-server/api/search.d.ts +29 -0
  619. package/lib/dist/ui-server/api/search.d.ts.map +1 -0
  620. package/lib/dist/ui-server/api/search.js +232 -0
  621. package/lib/dist/ui-server/api/search.js.map +1 -0
  622. package/lib/dist/ui-server/api/session.d.ts +52 -0
  623. package/lib/dist/ui-server/api/session.d.ts.map +1 -0
  624. package/lib/dist/ui-server/api/session.js +196 -0
  625. package/lib/dist/ui-server/api/session.js.map +1 -0
  626. package/lib/dist/ui-server/api/source.d.ts +200 -0
  627. package/lib/dist/ui-server/api/source.d.ts.map +1 -0
  628. package/lib/dist/ui-server/api/source.js +422 -0
  629. package/lib/dist/ui-server/api/source.js.map +1 -0
  630. package/lib/dist/ui-server/api/stats.d.ts +27 -0
  631. package/lib/dist/ui-server/api/stats.d.ts.map +1 -0
  632. package/lib/dist/ui-server/api/stats.js +164 -0
  633. package/lib/dist/ui-server/api/stats.js.map +1 -0
  634. package/lib/dist/ui-server/api/steps.d.ts +274 -0
  635. package/lib/dist/ui-server/api/steps.d.ts.map +1 -0
  636. package/lib/dist/ui-server/api/steps.js +1554 -0
  637. package/lib/dist/ui-server/api/steps.js.map +1 -0
  638. package/lib/dist/ui-server/api/trail-store.d.ts +142 -0
  639. package/lib/dist/ui-server/api/trail-store.d.ts.map +1 -0
  640. package/lib/dist/ui-server/api/trail-store.js +323 -0
  641. package/lib/dist/ui-server/api/trail-store.js.map +1 -0
  642. package/lib/dist/ui-server/api/trails.d.ts +163 -0
  643. package/lib/dist/ui-server/api/trails.d.ts.map +1 -0
  644. package/lib/dist/ui-server/api/trails.js +370 -0
  645. package/lib/dist/ui-server/api/trails.js.map +1 -0
  646. package/lib/dist/ui-server/api/when.d.ts +133 -0
  647. package/lib/dist/ui-server/api/when.d.ts.map +1 -0
  648. package/lib/dist/ui-server/api/when.js +275 -0
  649. package/lib/dist/ui-server/api/when.js.map +1 -0
  650. package/lib/dist/ui-server/api/wire.d.ts +179 -0
  651. package/lib/dist/ui-server/api/wire.d.ts.map +1 -0
  652. package/lib/dist/ui-server/api/wire.js +231 -0
  653. package/lib/dist/ui-server/api/wire.js.map +1 -0
  654. package/lib/dist/ui-server/assets.d.ts +40 -0
  655. package/lib/dist/ui-server/assets.d.ts.map +1 -0
  656. package/lib/dist/ui-server/assets.js +110 -0
  657. package/lib/dist/ui-server/assets.js.map +1 -0
  658. package/lib/dist/ui-server/constants.d.ts +32 -0
  659. package/lib/dist/ui-server/constants.d.ts.map +1 -0
  660. package/lib/dist/ui-server/constants.js +35 -0
  661. package/lib/dist/ui-server/constants.js.map +1 -0
  662. package/lib/dist/ui-server/highlight/bounded-tokenize.d.ts +28 -0
  663. package/lib/dist/ui-server/highlight/bounded-tokenize.d.ts.map +1 -0
  664. package/lib/dist/ui-server/highlight/bounded-tokenize.js +139 -0
  665. package/lib/dist/ui-server/highlight/bounded-tokenize.js.map +1 -0
  666. package/lib/dist/ui-server/highlight/index.d.ts +113 -0
  667. package/lib/dist/ui-server/highlight/index.d.ts.map +1 -0
  668. package/lib/dist/ui-server/highlight/index.js +312 -0
  669. package/lib/dist/ui-server/highlight/index.js.map +1 -0
  670. package/lib/dist/ui-server/highlight/languages.d.ts +36 -0
  671. package/lib/dist/ui-server/highlight/languages.d.ts.map +1 -0
  672. package/lib/dist/ui-server/highlight/languages.js +50 -0
  673. package/lib/dist/ui-server/highlight/languages.js.map +1 -0
  674. package/lib/dist/ui-server/highlight/tokenize-worker.d.ts +7 -0
  675. package/lib/dist/ui-server/highlight/tokenize-worker.d.ts.map +1 -0
  676. package/lib/dist/ui-server/highlight/tokenize-worker.js +20 -0
  677. package/lib/dist/ui-server/highlight/tokenize-worker.js.map +1 -0
  678. package/lib/dist/ui-server/index.d.ts +92 -0
  679. package/lib/dist/ui-server/index.d.ts.map +1 -0
  680. package/lib/dist/ui-server/index.js +399 -0
  681. package/lib/dist/ui-server/index.js.map +1 -0
  682. package/lib/dist/ui-server/open-browser.d.ts +31 -0
  683. package/lib/dist/ui-server/open-browser.d.ts.map +1 -0
  684. package/lib/dist/ui-server/open-browser.js +79 -0
  685. package/lib/dist/ui-server/open-browser.js.map +1 -0
  686. package/lib/dist/ui-server/security.d.ts +127 -0
  687. package/lib/dist/ui-server/security.d.ts.map +1 -0
  688. package/lib/dist/ui-server/security.js +332 -0
  689. package/lib/dist/ui-server/security.js.map +1 -0
  690. package/lib/dist/ui-server/static.d.ts +45 -0
  691. package/lib/dist/ui-server/static.d.ts.map +1 -0
  692. package/lib/dist/ui-server/static.js +165 -0
  693. package/lib/dist/ui-server/static.js.map +1 -0
  694. package/lib/dist/upgrade/index.d.ts +43 -5
  695. package/lib/dist/upgrade/index.d.ts.map +1 -1
  696. package/lib/dist/upgrade/index.js +157 -35
  697. package/lib/dist/upgrade/index.js.map +1 -1
  698. package/lib/dist/utils.d.ts +14 -2
  699. package/lib/dist/utils.d.ts.map +1 -1
  700. package/lib/dist/utils.js +25 -10
  701. package/lib/dist/utils.js.map +1 -1
  702. package/lib/dist/viewer/assets/archivo-latin-ext-wght-normal-C4zznr8T.woff2 +0 -0
  703. package/lib/dist/viewer/assets/archivo-latin-wght-normal-E0tuGl4L.woff2 +0 -0
  704. package/lib/dist/viewer/assets/archivo-vietnamese-wght-normal-XAtsl5Q_.woff2 +0 -0
  705. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-2syK4fUT.woff +0 -0
  706. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-CBJ8pzag.woff2 +0 -0
  707. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  708. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  709. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  710. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  711. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  712. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  713. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-B4oTjJdl.woff +0 -0
  714. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-CBjNughH.woff2 +0 -0
  715. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  716. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  717. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  718. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  719. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  720. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  721. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-italic-66oory27.woff +0 -0
  722. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-italic-BqAiT5Ww.woff2 +0 -0
  723. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  724. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  725. package/lib/dist/viewer/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  726. package/lib/dist/viewer/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  727. package/lib/dist/viewer/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  728. package/lib/dist/viewer/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  729. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-B7_fu1kp.woff2 +0 -0
  730. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-Bg0ZHwF4.woff +0 -0
  731. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  732. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  733. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  734. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  735. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  736. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  737. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-D6eaYXMU.woff +0 -0
  738. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-DRuN92E5.woff2 +0 -0
  739. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  740. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  741. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  742. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  743. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  744. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  745. package/lib/dist/viewer/assets/index-BSGpxBr9.js +99 -0
  746. package/lib/dist/viewer/assets/index-CF9yvio6.css +1 -0
  747. package/lib/dist/viewer/index.html +16 -0
  748. package/lib/dist/worker-teardown.d.ts +48 -0
  749. package/lib/dist/worker-teardown.d.ts.map +1 -0
  750. package/lib/dist/worker-teardown.js +100 -0
  751. package/lib/dist/worker-teardown.js.map +1 -0
  752. package/lib/kernel/codegraph-kernel.node +2 -2
  753. package/lib/node_modules/.package-lock.json +4 -4
  754. package/lib/node_modules/picomatch/README.md +56 -51
  755. package/lib/node_modules/picomatch/lib/constants.js +4 -0
  756. package/lib/node_modules/picomatch/lib/parse.js +341 -1
  757. package/lib/node_modules/picomatch/lib/picomatch.js +25 -5
  758. package/lib/node_modules/picomatch/lib/scan.js +30 -18
  759. package/lib/node_modules/picomatch/package.json +4 -4
  760. package/lib/package.json +9 -2
  761. package/package.json +1 -1
@@ -5,17 +5,28 @@
5
5
  * Defines the tools exposed by the CodeGraph MCP server.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.ToolHandler = exports.tools = exports.EXPLORE_ALLOCATION = exports.RELEVANCE_KIND_WEIGHT = exports.PathRefusalError = exports.NotIndexedError = void 0;
8
+ exports.ToolHandler = exports.MAX_CACHED_PROJECTS = exports.tools = exports.EXPLORE_FALLBACK_NOTES = exports.EXPLORE_ALLOCATION = exports.RELEVANCE_KIND_WEIGHT = exports.PathRefusalError = exports.NotIndexedError = void 0;
9
9
  exports.__setLoadCodeGraphForTests = __setLoadCodeGraphForTests;
10
10
  exports.normalizeQuerySpelling = normalizeQuerySpelling;
11
11
  exports.getExploreBudget = getExploreBudget;
12
12
  exports.getExploreOutputBudget = getExploreOutputBudget;
13
13
  exports.allocateExploreBudget = allocateExploreBudget;
14
+ exports.symbolsBetweenRanges = symbolsBetweenRanges;
15
+ exports.symbolsNotInRanges = symbolsNotInRanges;
16
+ exports.formatGapMarker = formatGapMarker;
17
+ exports.joinPartsWithNamedGaps = joinPartsWithNamedGaps;
18
+ exports.biasHeaderSymbols = biasHeaderSymbols;
19
+ exports.elidedWantedSpans = elidedWantedSpans;
20
+ exports.shortestUniqueSuffixes = shortestUniqueSuffixes;
21
+ exports.exploreCompletenessNotes = exploreCompletenessNotes;
22
+ exports.fitExploreEpilogue = fitExploreEpilogue;
14
23
  exports.formatStaleBanner = formatStaleBanner;
15
24
  exports.formatStaleFooter = formatStaleFooter;
16
25
  exports.formatDegradedBanner = formatDegradedBanner;
26
+ exports.formatRecoveringBanner = formatRecoveringBanner;
17
27
  exports.getStaticTools = getStaticTools;
18
28
  const directory_1 = require("../directory");
29
+ const wsl_shared_index_1 = require("../db/wsl-shared-index");
19
30
  // Lazy-load the heavy CodeGraph chain off the MCP startup path — see the same
20
31
  // helper in engine.ts. ToolHandler must load to answer tools/list (static
21
32
  // schemas), but it must NOT drag in sqlite/query layers before the daemon binds;
@@ -33,12 +44,18 @@ function __setLoadCodeGraphForTests(cls) {
33
44
  }
34
45
  const worktree_1 = require("../sync/worktree");
35
46
  const query_utils_1 = require("../search/query-utils");
47
+ const symbol_lookup_1 = require("../graph/symbol-lookup");
36
48
  const query_paths_1 = require("../search/query-paths");
37
49
  const fs_1 = require("fs");
38
50
  const crypto_1 = require("crypto");
39
51
  const utils_1 = require("../utils");
40
- const dynamic_boundaries_1 = require("./dynamic-boundaries");
52
+ const branch_guards_1 = require("../graph/branch-guards");
53
+ const dynamic_boundary_report_1 = require("../graph/dynamic-boundary-report");
54
+ const type_hierarchy_1 = require("../graph/type-hierarchy");
55
+ const named_symbol_flow_1 = require("../graph/named-symbol-flow");
41
56
  const update_check_1 = require("../upgrade/update-check");
57
+ const index_freshness_1 = require("./index-freshness");
58
+ const answer_freshness_1 = require("./answer-freshness");
42
59
  const explore_diagnostics_1 = require("./explore-diagnostics");
43
60
  const explore_session_state_1 = require("./explore-session-state");
44
61
  const explore_dedup_1 = require("./explore-dedup");
@@ -56,13 +73,31 @@ const explore_dedup_1 = require("./explore-dedup");
56
73
  class NotIndexedError extends Error {
57
74
  }
58
75
  exports.NotIndexedError = NotIndexedError;
76
+ /**
77
+ * The Windows/WSL shared-index failure (#995) phrased for the agent. It is an
78
+ * expected condition the USER fixes in their environment, so like
79
+ * {@link NotIndexedError} it answers SUCCESS-shaped — never `isError`, which
80
+ * would teach the agent to abandon codegraph for projects that work fine.
81
+ */
82
+ function wslSharedIndexGuidance(err) {
83
+ return (`${err.message}\n\n` +
84
+ "If you are an AI agent: codegraph can't read this project's index from WSL until the user " +
85
+ 'makes that change. Use your built-in tools (Read/Grep/Glob) for this task and pass the message ' +
86
+ "above on to the user — setting CODEGRAPH_DIR and building the index are the user's decisions, " +
87
+ "so don't do either yourself.");
88
+ }
59
89
  /**
60
90
  * A security refusal (sensitive system path). Stays `isError: true` WITHOUT
61
91
  * retry guidance — abandoning this path is the desired agent reaction.
92
+ *
93
+ * Defined in `../errors` so non-MCP read sinks (the `codegraph ui` server) can
94
+ * enforce the same refusal without importing this module; re-exported here
95
+ * because this is where every existing caller imports it from.
62
96
  */
63
- class PathRefusalError extends Error {
64
- }
65
- exports.PathRefusalError = PathRefusalError;
97
+ var errors_1 = require("../errors");
98
+ Object.defineProperty(exports, "PathRefusalError", { enumerable: true, get: function () { return errors_1.PathRefusalError; } });
99
+ const errors_2 = require("../errors");
100
+ const file_limits_1 = require("../file-limits");
66
101
  const path_1 = require("path");
67
102
  /** Maximum output length to prevent context bloat (characters) */
68
103
  const MAX_OUTPUT_LENGTH = 15000;
@@ -80,14 +115,6 @@ const MAX_INPUT_LENGTH = 10_000;
80
115
  * never legitimate and signal abuse or a bug upstream.
81
116
  */
82
117
  const MAX_PATH_LENGTH = 4_096;
83
- /**
84
- * Rust path roots that have no file-system equivalent — `crate` is the
85
- * current crate, `super` is the parent module, `self` is the current
86
- * module. Used by `matchesSymbol` to strip these before file-path
87
- * matching so `crate::configurator::stage_apply::run` resolves the
88
- * same as `configurator::stage_apply::run`.
89
- */
90
- const RUST_PATH_PREFIXES = new Set(['crate', 'super', 'self']);
91
118
  /**
92
119
  * Node kinds that contain other symbols. For these, `codegraph_node` with
93
120
  * `includeCode=true` returns a structural outline (member names + signatures
@@ -97,16 +124,6 @@ const RUST_PATH_PREFIXES = new Set(['crate', 'super', 'self']);
97
124
  const CONTAINER_NODE_KINDS = new Set([
98
125
  'class', 'struct', 'union', 'interface', 'trait', 'protocol', 'enum', 'namespace', 'module',
99
126
  ]);
100
- /**
101
- * Last `::` / `.` / `/`-separated segment of a qualified symbol. An Erlang
102
- * arity tail (`mod::fn/3`, `fn/3`) is stripped first — the useful last segment
103
- * is the function name, never the digits (#1610).
104
- */
105
- function lastQualifierPart(symbol) {
106
- const noArity = symbol.replace(/\/\d{1,3}$/, '') || symbol;
107
- const parts = noArity.split(/::|[./]/).filter((p) => p.length > 0);
108
- return parts[parts.length - 1] ?? symbol;
109
- }
110
127
  /**
111
128
  * Normalize Erlang-native symbol spellings in an explore query into the shapes
112
129
  * the rest of the pipeline already understands. Agents working Erlang code
@@ -133,6 +150,47 @@ function normalizeQuerySpelling(query) {
133
150
  .replace(/\b([A-Za-z_][\w@]*)\/(\d{1,3})(?=$|[\s,()[\]/])/g, '$1')
134
151
  .replace(/(^|[\s,()[\]])(?!(?:kind|lang|language|path|name):)([a-z_][\w@]*):([A-Za-z_][\w@]*)(?=$|[\s,()[\]])/g, '$1$2.$3');
135
152
  }
153
+ /**
154
+ * Does this query-named span point at a real FILE inside the project?
155
+ *
156
+ * The `existsOnDisk` predicate `extractQueryPaths` takes (that module is pure —
157
+ * no DB, no fs — so the fs access lives here, where the project root is known).
158
+ * Only a REGULAR FILE counts: a directory span (`src/search`) is not a file
159
+ * reference and must keep flowing to the normal matching pipeline. Containment
160
+ * is enforced by `validatePathWithinRoot`, so a `../` span in a query cannot
161
+ * probe outside the project, and every fs error answers `false`.
162
+ */
163
+ function pathIsProjectFile(projectRoot, relPath) {
164
+ try {
165
+ const abs = (0, utils_1.validatePathWithinRoot)(projectRoot, relPath);
166
+ return abs !== null && (0, fs_1.statSync)(abs).isFile();
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ }
172
+ /** Kinds that name a thing without defining it in the file that holds them. */
173
+ const NOT_A_DEFINITION = new Set(['file', 'import', 'export', 'parameter']);
174
+ /**
175
+ * Which indexed files define a symbol spelled like this query token?
176
+ *
177
+ * The `symbolFiles` lookup `extractQueryPaths` takes, split out for the same
178
+ * reason as `pathIsProjectFile`: that module stays DB-free. Exact names only —
179
+ * and the shared matcher for a qualified token (`SQLCompiler.as_sql`) — so it
180
+ * agrees with what explore's named-symbol seeding resolves. Lookup errors
181
+ * answer "none", which leaves the span's pins as they were.
182
+ */
183
+ function filesDefiningSymbol(cg, symbol) {
184
+ try {
185
+ const nodes = (0, symbol_lookup_1.isQualifiedSymbol)(symbol)
186
+ ? cg.getNodesByName((0, symbol_lookup_1.lastQualifierPart)(symbol)).filter((n) => (0, symbol_lookup_1.matchesSymbol)(n, symbol))
187
+ : cg.getNodesByName(symbol);
188
+ return nodes.filter((n) => !NOT_A_DEFINITION.has(n.kind)).map((n) => n.filePath);
189
+ }
190
+ catch {
191
+ return [];
192
+ }
193
+ }
136
194
  /**
137
195
  * Calculate the recommended number of codegraph_explore calls based on project size.
138
196
  * Larger codebases need more exploration calls to cover their surface area,
@@ -292,6 +350,13 @@ exports.RELEVANCE_KIND_WEIGHT = {
292
350
  constant: 0.35, variable: 0.3, parameter: 0.15,
293
351
  };
294
352
  const DEFAULT_RELEVANCE_KIND_WEIGHT = 0.5;
353
+ /**
354
+ * The "member of a type" tier of the table above, named so the one kind that
355
+ * cannot be read off `node.kind` can be placed on it: an interface's
356
+ * `method_signature` (#1638). Same value as `property`/`field`, deliberately —
357
+ * it is the same tier, not a new one.
358
+ */
359
+ const TYPE_MEMBER_RELEVANCE_WEIGHT = 0.5;
295
360
  /**
296
361
  * Kinds whose evidentiary value depends on whether anything USES them. An
297
362
  * exported `const DEFAULTS` that half the codebase references is a real
@@ -310,7 +375,7 @@ const ISOLATED_WEAK_KIND_WEIGHT = 0.08;
310
375
  */
311
376
  const RELEVANCE_USAGE_EDGES = new Set([
312
377
  'calls', 'references', 'extends', 'implements', 'overrides',
313
- 'instantiates', 'returns', 'type_of', 'decorates',
378
+ 'instantiates', 'returns', 'type_of', 'decorates', 'navigates',
314
379
  ]);
315
380
  /**
316
381
  * Cap on what PERIPHERAL nodes (in the subgraph, but neither a query match nor
@@ -473,6 +538,15 @@ exports.EXPLORE_ALLOCATION = {
473
538
  * Safety valve, as a fraction of the envelope. Not the primary guard any more —
474
539
  * the proportional split is — so this only has to stop a pathological
475
540
  * single-file response.
541
+ *
542
+ * It does not apply to a file the query NAMED — one that defines a symbol the
543
+ * query spelled, or that the query named by path. The valve hedges against a
544
+ * mis-ranked dominant file, and a file the agent asked for by name is not
545
+ * one. It also never redistributed: a clamped file's excess was simply left
546
+ * unreserved, and the carry-forward only moves reservations, so nobody could
547
+ * spend it. On express, "response.js res.send res.json res.render …" admits
548
+ * one file, clamps it at 9,100 with 3,700 of the pool unreserved, and cuts
549
+ * the named `send` body at 55 of 97 lines in a 10.9K response to a 13K budget.
476
550
  */
477
551
  MAX_SHARE: 0.7,
478
552
  /**
@@ -540,6 +614,10 @@ exports.EXPLORE_ALLOCATION = {
540
614
  */
541
615
  WHOLE_FILE_BUY_OVERSHOOT_FRACTION: 0.15,
542
616
  };
617
+ /** A file the query asked for by name — a symbol it defines, or its path. */
618
+ function isNamedCandidate(c) {
619
+ return c.named === true || c.pinned === true;
620
+ }
543
621
  /**
544
622
  * Split `budget.maxOutputChars` across ranked candidates in proportion to
545
623
  * relevance, with a hard relative cliff.
@@ -632,10 +710,12 @@ function allocateExploreBudget(candidates, budget, maxFiles) {
632
710
  // exactly — the render loop spends them, so an over-allocation is an over-long
633
711
  // response the hard ceiling then has to truncate. Flooring costs at most one
634
712
  // char per file.
713
+ // The valve spares a file the query named (see MAX_SHARE): its share is already
714
+ // a slice of `pool`, so the reservations still fit the pool exactly.
635
715
  for (const c of admitted) {
636
716
  const share = Math.floor(floors / admitted.length)
637
717
  + Math.floor((remainder * (weights.get(c.path) ?? 0)) / total);
638
- allowances.set(c.path, Math.min(share, ceiling));
718
+ allowances.set(c.path, isNamedCandidate(c) ? share : Math.min(share, ceiling));
639
719
  }
640
720
  return { allowances, cliffed, cliffAt, pool };
641
721
  }
@@ -731,6 +811,162 @@ function fileSectionHeader(filePath, suffix) {
731
811
  const POINTER_HEADER = '**Not shown above — explore these names for their source**';
732
812
  /** Most files the pointer list ever names one-per-line; the rest are a count. */
733
813
  const POINTER_MAX_FILES = 10;
814
+ /**
815
+ * How many elided-in-file symbols a gap marker or biased header names (#1711).
816
+ * Kept small: the names exist so a follow-up explore has a target, not so the
817
+ * meta-text rivals the source it is pointing at.
818
+ */
819
+ const ELIDED_SYMBOL_CAP = 6;
820
+ /**
821
+ * Kinds a single-line anchor (`compiler.py:776`) resolves to: the innermost
822
+ * one containing the line is the symbol the agent is pointing at. A class
823
+ * enclosing the line is deliberately NOT a target — it spans most of its file,
824
+ * and "the whole class" is not what a line number asks for.
825
+ */
826
+ const ANCHOR_CALLABLE_KINDS = new Set(['method', 'function', 'constructor', 'component']);
827
+ /** Lines either side of a single-line anchor that no callable encloses. */
828
+ const ANCHOR_LINE_CONTEXT = 15;
829
+ /**
830
+ * Most windows one oversize exact / named-spine body is cut into in the
831
+ * focused view: the head plus the call sites into the other symbols the
832
+ * question named. More turns a method into confetti.
833
+ */
834
+ const MAX_BODY_FOCUS_LINES = 6;
835
+ /**
836
+ * Indexed symbols whose definition starts strictly between two rendered
837
+ * spans. The hole is what a trim dropped; naming them is what lets the agent
838
+ * follow up by name instead of guessing (#1711).
839
+ */
840
+ function symbolsBetweenRanges(nodes, fromEnd, toStart) {
841
+ if (toStart <= fromEnd + 1)
842
+ return [];
843
+ const out = [];
844
+ const seen = new Set();
845
+ for (const n of nodes) {
846
+ if (n.kind === 'import' || n.kind === 'export')
847
+ continue;
848
+ if (n.startLine <= fromEnd || n.startLine >= toStart)
849
+ continue;
850
+ if (seen.has(n.name))
851
+ continue;
852
+ seen.add(n.name);
853
+ out.push({ name: n.name, kind: n.kind, startLine: n.startLine });
854
+ }
855
+ out.sort((a, b) => a.startLine - b.startLine);
856
+ return out;
857
+ }
858
+ /**
859
+ * Symbols in `candidates` whose start line is not covered by any emitted range.
860
+ * Used to bias the per-file header toward what the trim dropped (#1711).
861
+ */
862
+ function symbolsNotInRanges(candidates, ranges) {
863
+ if (ranges.length === 0)
864
+ return [...candidates].sort((a, b) => a.startLine - b.startLine);
865
+ const out = [];
866
+ const seen = new Set();
867
+ for (const n of candidates) {
868
+ if (seen.has(n.name))
869
+ continue;
870
+ if (ranges.some((r) => n.startLine >= r.start && n.startLine <= r.end))
871
+ continue;
872
+ seen.add(n.name);
873
+ out.push(n);
874
+ }
875
+ out.sort((a, b) => a.startLine - b.startLine);
876
+ return out;
877
+ }
878
+ const BARE_GAP_MARKER = '\n\n... (gap) ...\n\n';
879
+ /**
880
+ * Gap marker between two non-contiguous slices of one file.
881
+ *
882
+ * Bare `... (gap) ...` told the agent something was missing but not WHAT —
883
+ * and the footer then asked it to re-explore "with its exact name", which is
884
+ * circular when the missing names *are* the question (#1711). When the hole
885
+ * holds indexed symbols, list them as `name (file:line)` (same shape the
886
+ * flow / blast-radius lines already use).
887
+ */
888
+ function formatGapMarker(filePath, elided) {
889
+ if (elided.length === 0)
890
+ return BARE_GAP_MARKER;
891
+ const shown = elided.slice(0, ELIDED_SYMBOL_CAP);
892
+ const more = elided.length - shown.length;
893
+ const names = shown.map((s) => `${s.name} (${filePath}:${s.startLine})`).join(', ')
894
+ + (more > 0 ? `, +${more} more` : '');
895
+ return `\n\n... (gap: ${names}) ...\n\n`;
896
+ }
897
+ /**
898
+ * Join rendered parts with gap markers that name whatever the trim skipped.
899
+ *
900
+ * `spareChars` is what naming may cost beyond bare markers. Cluster selection
901
+ * prices every join between clusters as a bare marker, and on a long path each
902
+ * named gap runs to several hundred chars, so unbounded naming overran the
903
+ * file's reservation and the ceiling trim then dropped SOURCE to pay for the
904
+ * names: vscode's `rpcProtocol.ts` went from ~5,200 chars of the RPCProtocol
905
+ * body to a 222-char stub. A gap the spare can't cover stays bare; the file
906
+ * header still lists the symbols the trim dropped.
907
+ */
908
+ function joinPartsWithNamedGaps(filePath, parts, nodes, spareChars = Infinity) {
909
+ if (parts.length === 0)
910
+ return '';
911
+ let out = parts[0].text;
912
+ let spare = spareChars;
913
+ for (let i = 1; i < parts.length; i++) {
914
+ const prev = parts[i - 1];
915
+ const next = parts[i];
916
+ const named = formatGapMarker(filePath, symbolsBetweenRanges(nodes, prev.range.end, next.range.start));
917
+ const extra = named.length - BARE_GAP_MARKER.length;
918
+ if (extra <= spare) {
919
+ out += named;
920
+ spare -= extra;
921
+ }
922
+ else {
923
+ out += BARE_GAP_MARKER;
924
+ }
925
+ out += next.text;
926
+ }
927
+ return out;
928
+ }
929
+ /**
930
+ * Prefer symbols the trim dropped when filling the per-file header's named
931
+ * slots, so `+N more` is less likely to hide the answer (#1711). Frequency
932
+ * still breaks ties among the preferred / remaining groups.
933
+ */
934
+ function biasHeaderSymbols(symbols, elided, cap) {
935
+ const elidedLabels = elided.map((s) => `${s.name}(${s.kind})`);
936
+ const elidedSet = new Set(elidedLabels);
937
+ const elidedNames = new Set(elided.map((s) => s.name));
938
+ const counts = new Map();
939
+ for (const s of symbols)
940
+ counts.set(s, (counts.get(s) ?? 0) + 1);
941
+ // Also surface elided symbols that never made it into `symbols` (a dropped
942
+ // cluster's members are absent from assembleSection's list today).
943
+ for (const label of elidedLabels) {
944
+ if (!counts.has(label))
945
+ counts.set(label, 1);
946
+ }
947
+ // Earlier elided defs first (elided is startLine-sorted) so the header's
948
+ // named slots track source order through the hole rather than alphabetical
949
+ // filler (`calls0` beating `syncStateNow`).
950
+ const elidedRank = new Map();
951
+ elided.forEach((s, i) => {
952
+ elidedRank.set(`${s.name}(${s.kind})`, i);
953
+ if (!elidedRank.has(s.name))
954
+ elidedRank.set(s.name, i);
955
+ });
956
+ const score = (label) => {
957
+ const name = label.replace(/\(.*\)$/, '');
958
+ const preferred = elidedSet.has(label) || elidedNames.has(name) ? 1 : 0;
959
+ const rank = elidedRank.get(label) ?? elidedRank.get(name) ?? 9999;
960
+ return [preferred, counts.get(label) ?? 0, -rank];
961
+ };
962
+ const sorted = [...counts.keys()].sort((a, b) => {
963
+ const [pa, ca, ra] = score(a);
964
+ const [pb, cb, rb] = score(b);
965
+ return pb - pa || cb - ca || rb - ra || a.localeCompare(b);
966
+ });
967
+ const shown = sorted.slice(0, cap);
968
+ return { shown, omitted: Math.max(0, sorted.length - shown.length) };
969
+ }
734
970
  /**
735
971
  * One pointer line: the file plus enough symbol names to make it NAMEABLE in a
736
972
  * follow-up explore. Capped — an un-capped list ran to ~1.9K on the #1500
@@ -754,6 +990,228 @@ function pointerLineFor(filePath, nodes) {
754
990
  * and that another explore — not a Read — is how to reach it.
755
991
  */
756
992
  const EPILOGUE_LOST_NOTE = '> (Trailing pointer list omitted for size. The source above is complete and verbatim — treat it as already Read. For anything this call did not cover, run another codegraph_explore with the specific names rather than reading those files.)';
993
+ /**
994
+ * The notes that stand in for the epilogue, or close a truncated response, in
995
+ * two wordings each. `complete` says the source above is complete; `trimmed` is
996
+ * used when a section it vouches for was trimmed (see `elidedWantedSpans`) and
997
+ * drops that claim, keeping the guarantee that is still true. Each trimmed
998
+ * wording is no longer than its complete one: the epilogue floor (`lost`) and
999
+ * the cut note's fit test (`cut`) are sized before the render knows which of the
1000
+ * two it will need.
1001
+ */
1002
+ exports.EXPLORE_FALLBACK_NOTES = {
1003
+ lost: {
1004
+ complete: EPILOGUE_LOST_NOTE,
1005
+ trimmed: '> (Trailing pointer list omitted for size. The source above is verbatim — treat it as already Read. For symbols its gap markers name, and anything else not covered, run another codegraph_explore with those names rather than reading.)',
1006
+ },
1007
+ cut: {
1008
+ complete: '\n\n> (Trailing notes omitted for size. The source above is complete and verbatim — treat it as already Read. For anything this call did not cover, run another codegraph_explore with the specific names rather than reading those files.)',
1009
+ trimmed: '\n\n> (Trailing notes omitted for size. The source above is verbatim — treat it as already Read. For symbols its gap markers name, and anything else not covered, run another codegraph_explore with those names rather than reading.)',
1010
+ },
1011
+ truncated: {
1012
+ complete: '\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.)',
1013
+ trimmed: '\n\n... (output truncated to budget; the source above is verbatim — treat it as already Read. For names its gap markers list, or any area not covered, run another codegraph_explore — do NOT Read these files.)',
1014
+ },
1015
+ };
1016
+ /**
1017
+ * The wanted spans a section did NOT deliver in full: some line of the span is
1018
+ * in neither what this call sent nor what an earlier call already sent (a
1019
+ * back-referenced span counts — the agent holds that copy).
1020
+ *
1021
+ * Derived from the emitted ranges rather than from a flag each trim site has to
1022
+ * remember to set. The oversize-spine window set none until #2068, which is how
1023
+ * a 62-line slice of vscode's 968-line `rpcProtocol.ts` went out under "Complete
1024
+ * source … do NOT re-read them". Whatever elides source — a member shrink, a
1025
+ * ceiling window, a dropped cluster, the per-symbol view, a path added later —
1026
+ * shows up here.
1027
+ *
1028
+ * Most relevant first (spine, then importance), then source order.
1029
+ */
1030
+ function elidedWantedSpans(wanted, delivered) {
1031
+ const merged = (0, explore_dedup_1.mergeRanges)(delivered);
1032
+ const out = wanted.filter((w) => w.start > 0 && w.end >= w.start
1033
+ && !merged.some((r) => r.start <= w.start && w.end <= r.end));
1034
+ return out.sort((a, b) => Number(b.spine) - Number(a.spine) || b.importance - a.importance || a.start - b.start);
1035
+ }
1036
+ /** Trimmed files the completeness note names one by one; the rest are a count. */
1037
+ const TRIMMED_FILES_NAMED = 3;
1038
+ /** Elided symbols the completeness note names, from the spine or named by the agent. */
1039
+ const TRIMMED_SYMBOLS_NAMED = 4;
1040
+ /**
1041
+ * Kinds the note never offers as a follow-up target. A container elided by a
1042
+ * trim is too big for one section by construction, so exploring it by name
1043
+ * comes back trimmed too; its members are the useful names.
1044
+ */
1045
+ const TRIMMED_NAME_SKIP_KINDS = new Set([
1046
+ 'file', 'module', 'namespace', 'class', 'struct', 'union', 'interface', 'protocol', 'trait',
1047
+ ]);
1048
+ /**
1049
+ * The name the completeness note offers for an elided symbol: `Owner.member`
1050
+ * for a method, so an overloaded name resolves to the definition that was cut
1051
+ * (django has 110 `as_sql`s; the note used to offer the bare one and agents
1052
+ * then added a path and line to disambiguate it). The bare name otherwise.
1053
+ */
1054
+ function followUpName(e) {
1055
+ if (e.kind !== 'method' || !e.qualifiedName)
1056
+ return e.name;
1057
+ const segs = e.qualifiedName.split('::');
1058
+ const owner = segs.length >= 2 ? segs[segs.length - 2] : '';
1059
+ return /^[A-Za-z_$][\w$]*$/.test(owner) ? `${owner}.${e.name}` : e.name;
1060
+ }
1061
+ /**
1062
+ * The shortest trailing slice of each path that no other path in `paths`
1063
+ * ends with: `extHostExtensionService.ts` alone when it is the only one,
1064
+ * `node/extHostExtensionService.ts` beside `common/extHostExtensionService.ts`.
1065
+ */
1066
+ function shortestUniqueSuffixes(paths) {
1067
+ const all = [...new Set(paths)];
1068
+ const out = new Map();
1069
+ for (const p of all) {
1070
+ const segs = p.split('/');
1071
+ let n = 1;
1072
+ for (; n < segs.length; n++) {
1073
+ const suffix = segs.slice(-n).join('/');
1074
+ if (!all.some((o) => o !== p && (o === suffix || o.endsWith(`/${suffix}`))))
1075
+ break;
1076
+ }
1077
+ out.set(p, segs.slice(-n).join('/'));
1078
+ }
1079
+ return out;
1080
+ }
1081
+ /**
1082
+ * The large tiers' completeness note (`includeCompletenessSignal`), as
1083
+ * candidates from most to least specific. The epilogue fit keeps the first
1084
+ * one that fits the room left (CG-26).
1085
+ *
1086
+ * "Complete" is claimed only when no section elided anything it set out to
1087
+ * deliver. Otherwise the note keeps the guarantee that is still true (every
1088
+ * block shown is verbatim; treat it as already Read), names the trimmed files
1089
+ * and the most relevant elided symbols as room allows, and sends the agent to
1090
+ * another codegraph_explore for them. It never offers Read: explore output must
1091
+ * not tell the agent to Read (AGENTS.md).
1092
+ */
1093
+ function exploreCompletenessNotes(filesIncluded, trimmed,
1094
+ /** Every path the response can name (sections and pointer list); labels are unique among them. */
1095
+ knownPaths) {
1096
+ // No count when every section is held from an earlier call: "0 files" reads
1097
+ // as nothing shown, beside a note about what was shown.
1098
+ const files = filesIncluded === 0 ? 'these files'
1099
+ : filesIncluded === 1 ? '1 file' : `${filesIncluded} files`;
1100
+ if (trimmed.length === 0) {
1101
+ return [`> **Complete source for ${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.`];
1102
+ }
1103
+ const label = shortestUniqueSuffixes([...knownPaths, ...trimmed.map((t) => t.filePath)]);
1104
+ const shownFiles = trimmed.slice(0, TRIMMED_FILES_NAMED).map((t) => `\`${label.get(t.filePath)}\``);
1105
+ const moreFiles = trimmed.length - shownFiles.length;
1106
+ const trimmedList = shownFiles.join(', ') + (moreFiles > 0 ? ` +${moreFiles} more` : '');
1107
+ const names = [];
1108
+ for (const t of trimmed) {
1109
+ for (const e of t.elided) {
1110
+ if (names.length >= TRIMMED_SYMBOLS_NAMED)
1111
+ break;
1112
+ if (!(e.spine || e.importance >= 9) || TRIMMED_NAME_SKIP_KINDS.has(e.kind))
1113
+ continue;
1114
+ const name = followUpName(e);
1115
+ if (!names.includes(name))
1116
+ names.push(name);
1117
+ }
1118
+ }
1119
+ const head = `> **Verbatim source for ${files} is included above — treat it as already Read.**`;
1120
+ const what = 'gap markers and file headers name what was elided';
1121
+ const tail = 'For those, or anything under "Not shown above", make ANOTHER codegraph_explore with those exact names instead of reading the files — it returns their source with line numbers.';
1122
+ const withFiles = `${head} Trimmed for size: ${trimmedList}; ${what}`;
1123
+ const candidates = names.length > 0
1124
+ ? [`${withFiles} (e.g. ${names.map((n) => `\`${n}\``).join(', ')}). ${tail}`]
1125
+ : [];
1126
+ candidates.push(`${withFiles}. ${tail}`, `${head} Some sections were trimmed for size; ${what}. ${tail}`);
1127
+ return candidates;
1128
+ }
1129
+ /** Chars a block of lines costs once joined into the response. */
1130
+ const roomForLines = (block) => block.reduce((n, s) => n + s.length + 1, 0);
1131
+ /**
1132
+ * Fit the completeness note and the pointer list into the room the response has
1133
+ * left (CG-26). Returns the note (a candidate block, or none), the pointer
1134
+ * block, and the room that remains.
1135
+ *
1136
+ * The note is one of `noteCandidates`, most specific first. A complete-source
1137
+ * note keeps the precedence it always had and goes first. A note that YIELDS (a
1138
+ * trimmed one) gives way to the pointer list, which names files the response
1139
+ * does not show at all, while what a trimmed section elided is already named in
1140
+ * its own gap markers and header. It leaves the list's header and first entry
1141
+ * when that much could fit, and its optional detail never costs an entry the
1142
+ * least specific candidate would have left.
1143
+ */
1144
+ function fitExploreEpilogue(opts) {
1145
+ const { noteCandidates, noteYields, pointerEntries, pointerOmitted } = opts;
1146
+ let room = opts.room;
1147
+ // The pointer list as it fits `space`: entries in rank order, and a tail
1148
+ // line confessing every entry left out.
1149
+ const fitPointers = (space) => {
1150
+ if (pointerEntries.length === 0)
1151
+ return { block: [], taken: 0 };
1152
+ const head = [POINTER_HEADER, ''];
1153
+ let left = space - roomForLines(head);
1154
+ if (left < 0)
1155
+ return { block: [], taken: 0 };
1156
+ let taken = 0;
1157
+ for (const entry of pointerEntries) {
1158
+ // Every entry we do NOT take has to be confessed by the tail line, so
1159
+ // the tail's cost is part of taking one less than all of them.
1160
+ const dropped = pointerEntries.length - taken - 1 + pointerOmitted;
1161
+ const tail = dropped > 0 ? roomForLines([`- ... and ${dropped} more files`]) : 0;
1162
+ if (entry.length + 1 + tail > left)
1163
+ break;
1164
+ left -= entry.length + 1;
1165
+ taken++;
1166
+ }
1167
+ if (taken === 0)
1168
+ return { block: [], taken: 0 };
1169
+ const block = [...head, ...pointerEntries.slice(0, taken)];
1170
+ const dropped = pointerEntries.length - taken + pointerOmitted;
1171
+ if (dropped > 0)
1172
+ block.push(`- ... and ${dropped} more files`);
1173
+ return { block, taken };
1174
+ };
1175
+ const pointerNeed = pointerEntries.length > 0
1176
+ ? roomForLines([POINTER_HEADER, '', pointerEntries[0],
1177
+ `- ... and ${pointerEntries.length - 1 + pointerOmitted} more files`])
1178
+ : 0;
1179
+ const pointerMin = noteYields && pointerNeed <= room ? pointerNeed : 0;
1180
+ const leastSpecific = noteCandidates[noteCandidates.length - 1];
1181
+ const entriesBeside = (b) => fitPointers(room - roomForLines(b)).taken;
1182
+ const entriesFloor = noteYields && leastSpecific ? entriesBeside(leastSpecific) : 0;
1183
+ const note = [...(noteCandidates.find((b) => roomForLines(b) + pointerMin <= room
1184
+ && (!noteYields || entriesBeside(b) >= entriesFloor)) ?? [])];
1185
+ room -= roomForLines(note);
1186
+ const pointers = fitPointers(room).block;
1187
+ room -= roomForLines(pointers);
1188
+ return { note, pointers, room };
1189
+ }
1190
+ /**
1191
+ * Match response delimiters rather than ASCII "path characters": filenames
1192
+ * can contain Unicode, @, +, and other punctuation. Keep line references and
1193
+ * a sentence-ending period, but reject prefixes/suffixes of longer paths.
1194
+ */
1195
+ function mentionsPath(text, relPath) {
1196
+ const delimiter = /[\s`"'()[\]{}*]/;
1197
+ for (let at = text.indexOf(relPath); at !== -1; at = text.indexOf(relPath, at + 1)) {
1198
+ if (at > 0 && !delimiter.test(text[at - 1] ?? ''))
1199
+ continue;
1200
+ const end = at + relPath.length;
1201
+ if (end === text.length || delimiter.test(text[end] ?? ''))
1202
+ return true;
1203
+ const suffix = text.slice(end);
1204
+ if (/^:\d+(?::\d+|[-–]\d+)?(?=$|[\s`"'()[\]{}*])/.test(suffix))
1205
+ return true;
1206
+ if (/^:(?=$|\s)/.test(suffix))
1207
+ return true; // file-list label
1208
+ if (/^\.(?=$|\s)/.test(suffix))
1209
+ return true; // prose punctuation
1210
+ if (/^[,;](?=$|\s)/.test(suffix))
1211
+ return true; // list separator
1212
+ }
1213
+ return false;
1214
+ }
757
1215
  /**
758
1216
  * Per-file staleness banner emitted at the top of a tool response when the
759
1217
  * file watcher has pending events for files referenced by the response.
@@ -804,6 +1262,12 @@ function formatDegradedBanner(reason) {
804
1262
  'current content before relying on it.' +
805
1263
  (reason ? `\n Reason: ${reason}` : ''));
806
1264
  }
1265
+ /** Re-armed watches are not proof of freshness until their full scan commits. */
1266
+ function formatRecoveringBanner() {
1267
+ return ('⚠️ CodeGraph auto-sync is RECOVERING — file watching restarted after lock contention, ' +
1268
+ 'but the full index catch-up has not completed. Read files directly to confirm ' +
1269
+ 'current content before relying on these results.');
1270
+ }
807
1271
  /**
808
1272
  * Common projectPath property for cross-project queries
809
1273
  */
@@ -1001,10 +1465,13 @@ exports.tools = [
1001
1465
  required: ['query'],
1002
1466
  },
1003
1467
  annotations: READ_ONLY_ANNOTATIONS,
1468
+ // Loaded from the first prompt in Claude Code, which otherwise defers every
1469
+ // MCP tool behind a ToolSearch step (#1696).
1470
+ _meta: { 'anthropic/alwaysLoad': true },
1004
1471
  },
1005
1472
  {
1006
1473
  name: 'codegraph_status',
1007
- description: 'Index health check (files / nodes / edges). Skip unless debugging.',
1474
+ description: 'Index health check: files, nodes, edges, last indexed time, and added/modified/removed counts. Skip unless debugging.',
1008
1475
  inputSchema: {
1009
1476
  type: 'object',
1010
1477
  properties: {
@@ -1105,6 +1572,41 @@ function getStaticTools() {
1105
1572
  * untouched, and `CODEGRAPH_MCP_TOOLS=explore,node,...` re-enables any of them.
1106
1573
  */
1107
1574
  const DEFAULT_MCP_TOOLS = new Set(['explore']);
1575
+ /** realpath when the path exists, the path itself otherwise — never throws. */
1576
+ function canonicalPath(p) {
1577
+ try {
1578
+ return (0, fs_1.realpathSync)(p);
1579
+ }
1580
+ catch {
1581
+ return p;
1582
+ }
1583
+ }
1584
+ /**
1585
+ * How many explicit-`projectPath` projects a handler keeps open at once
1586
+ * (#1835). Each cached project may hold a file watcher, a writer lock and a
1587
+ * SQLite connection, so the cache is bounded LRU: opening one more than this
1588
+ * closes the least recently used. Small on purpose — a session that queries
1589
+ * many repositories still leaks nothing; it only pays a reopen + catch-up.
1590
+ */
1591
+ exports.MAX_CACHED_PROJECTS = 8;
1592
+ /**
1593
+ * How long an explicit-`projectPath` project may go unused before the handler
1594
+ * releases it (#2087). Releasing frees its SQLite handle, its watcher and the
1595
+ * writer lock the engine may hold on that project — which otherwise stays held
1596
+ * for the whole life of this daemon, locking the project's own daemon and
1597
+ * `codegraph index` out. The next call reopens it and catches up.
1598
+ * `CODEGRAPH_PROJECT_IDLE_TIMEOUT_MS` overrides it; `0` never releases.
1599
+ */
1600
+ const DEFAULT_PROJECT_IDLE_TIMEOUT_MS = 600_000;
1601
+ function resolveProjectIdleTimeoutMs() {
1602
+ const raw = process.env.CODEGRAPH_PROJECT_IDLE_TIMEOUT_MS;
1603
+ if (raw === undefined || raw === '')
1604
+ return DEFAULT_PROJECT_IDLE_TIMEOUT_MS;
1605
+ const n = Number(raw);
1606
+ if (!Number.isFinite(n) || n < 0)
1607
+ return DEFAULT_PROJECT_IDLE_TIMEOUT_MS;
1608
+ return Math.floor(n);
1609
+ }
1108
1610
  /**
1109
1611
  * Tool handler that executes tools against a CodeGraph instance
1110
1612
  *
@@ -1113,8 +1615,23 @@ const DEFAULT_MCP_TOOLS = new Set(['explore']);
1113
1615
  */
1114
1616
  class ToolHandler {
1115
1617
  cg;
1116
- // Cache of opened CodeGraph instances for cross-project queries
1618
+ // Cache of opened CodeGraph instances for cross-project queries, keyed by the
1619
+ // CANONICAL (realpath) index root. Map insertion order doubles as LRU order:
1620
+ // a hit re-inserts, and `MAX_CACHED_PROJECTS` bounds the size (#1835).
1117
1621
  projectCache = new Map();
1622
+ // When each cached root was last handed to a call, and the one timer that
1623
+ // releases the oldest once it has been idle long enough (#2087).
1624
+ projectUsedAt = new Map();
1625
+ idleReleaseTimer = null;
1626
+ // Engine hook that watches + catches up an explicit project (null for the
1627
+ // CLI and worker-thread handlers, which never own a watcher).
1628
+ projectLifecycle = null;
1629
+ // Every concurrent call shares its project's pending catch-up promise.
1630
+ projectGates = new Map();
1631
+ activeCalls = 0;
1632
+ closing = false;
1633
+ pendingCloses = 0;
1634
+ closeWaiters = [];
1118
1635
  // The directory the server last searched for a default project. Surfaced in
1119
1636
  // the "not initialized" error so users can see why detection missed.
1120
1637
  defaultProjectHint = null;
@@ -1125,12 +1642,20 @@ class ToolHandler {
1125
1642
  // retry) — tool calls themselves never scan.
1126
1643
  knownSubprojects = [];
1127
1644
  knownSubprojectsBase = null;
1645
+ // Why the default project failed to open, when that is worth telling the
1646
+ // agent instead of "no project loaded" — today only the Windows/WSL
1647
+ // shared-index error (#995). Engine-maintained; cleared by a successful open.
1648
+ defaultOpenFailure = null;
1128
1649
  // Per-start-path cache of the git worktree/index mismatch (issue #155). The
1129
1650
  // mismatch is a fixed property of (where the request came from → which
1130
1651
  // .codegraph/ it resolves to), so the up-to-two `git rev-parse` spawns run
1131
1652
  // once and every later tool call reuses the result — never shelling out to
1132
1653
  // git on the hot path. `undefined` = not computed yet; `null` = no mismatch.
1133
1654
  worktreeMismatchCache = new Map();
1655
+ // Per-(projectPath, index root) cache of the different git repository the
1656
+ // path sits in below that root, if any (#2110) — the git half of
1657
+ // `uncoveredNestedRepo`, memoized like the mismatch above.
1658
+ nestedRepoCache = new Map();
1134
1659
  // Gate that the MCP engine pokes after `cg.open()` so the first tool call
1135
1660
  // blocks on the post-open filesystem reconcile (catch-up sync). Without
1136
1661
  // this, a tool call that races past `catchUpSync()` serves rows for files
@@ -1138,31 +1663,47 @@ class ToolHandler {
1138
1663
  // per-file staleness banner can't help, because `getPendingFiles()` is
1139
1664
  // populated by the watcher, not by catch-up. The wait is time-boxed
1140
1665
  // (see {@link resolveCatchUpGateTimeoutMs}) so a minutes-long reconcile on a
1141
- // huge repo can't hang the first call (#905); cleared on first await so
1142
- // subsequent calls don't pay any cost.
1666
+ // huge repo can't hang a call (#905); cleared when the reconcile settles.
1143
1667
  catchUpGate = null;
1144
- // Optional worker-thread pool for off-loop read-tool dispatch (daemon mode).
1145
- // When set + healthy, the heavy read tools run on a worker so the daemon's
1146
- // main loop stays free for the MCP transport under concurrent load. Null in
1147
- // direct/in-process mode (one client, no concurrency to parallelize).
1668
+ // Engine hook fired when `freshen` reopened a replaced database (#1902), so
1669
+ // the engine can reconcile the new file with a catch-up sync.
1670
+ onDatabaseReopened = null;
1671
+ // Optional worker-thread pool for off-loop read-tool dispatch. When ready +
1672
+ // healthy, heavy reads leave the main loop free for the MCP transport.
1148
1673
  queryPool = null;
1149
1674
  constructor(cg) {
1150
1675
  this.cg = cg;
1151
1676
  }
1152
1677
  /**
1153
1678
  * Engine-only: attach (or detach with null) the worker-thread query pool. The
1154
- * shared daemon sets this once its default project is open; the workers each
1679
+ * engine sets this after resolving its default project; the workers each
1155
1680
  * hold their own WAL read connection and run {@link executeReadTool}. A
1156
1681
  * worker's own ToolHandler never has a pool, so there is no nested off-loading.
1157
1682
  */
1158
1683
  setQueryPool(pool) {
1159
1684
  this.queryPool = pool;
1160
1685
  }
1686
+ /**
1687
+ * Engine-only: own the lifecycle (watcher, catch-up, writer lock) of every
1688
+ * project this handler opens for an explicit `projectPath` (#1835).
1689
+ */
1690
+ setProjectLifecycle(lifecycle) {
1691
+ this.projectLifecycle = lifecycle;
1692
+ }
1161
1693
  /**
1162
1694
  * Update the default CodeGraph instance (e.g. after lazy initialization)
1163
1695
  */
1164
1696
  setDefaultCodeGraph(cg) {
1165
1697
  this.cg = cg;
1698
+ this.defaultOpenFailure = null;
1699
+ }
1700
+ /**
1701
+ * Engine-only: record why the default project failed to open (#995), so a
1702
+ * call that needs it answers with that fix rather than "no project loaded".
1703
+ * `null` clears it.
1704
+ */
1705
+ setDefaultOpenFailure(err) {
1706
+ this.defaultOpenFailure = err;
1166
1707
  }
1167
1708
  /**
1168
1709
  * Engine-only: register the catch-up sync promise so the next `execute()`
@@ -1173,6 +1714,21 @@ class ToolHandler {
1173
1714
  */
1174
1715
  setCatchUpGate(p) {
1175
1716
  this.catchUpGate = p;
1717
+ void p?.then(() => {
1718
+ if (this.catchUpGate === p)
1719
+ this.catchUpGate = null;
1720
+ }, () => {
1721
+ if (this.catchUpGate === p)
1722
+ this.catchUpGate = null;
1723
+ });
1724
+ }
1725
+ /**
1726
+ * Engine-only: called after a tool call's {@link freshen} reopened a database
1727
+ * that was replaced on disk (#1902). The engine decides whether a catch-up
1728
+ * sync is its to run (only for the instance it watches and writes).
1729
+ */
1730
+ setOnDatabaseReopened(fn) {
1731
+ this.onDatabaseReopened = fn;
1176
1732
  }
1177
1733
  /**
1178
1734
  * Await the catch-up gate, but no longer than the configured timeout (#905).
@@ -1330,7 +1886,7 @@ class ToolHandler {
1330
1886
  if (tool.name === 'codegraph_explore') {
1331
1887
  return {
1332
1888
  ...tool,
1333
- description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
1889
+ description: `${tool.description} Exploration guidance — advisory only, NOT a quota: ~${budget} focused calls usually cover this project (${stats.fileCount.toLocaleString()} files indexed), and extra calls are never rejected or rate-limited.`,
1334
1890
  };
1335
1891
  }
1336
1892
  return tool;
@@ -1352,6 +1908,8 @@ class ToolHandler {
1352
1908
  getCodeGraph(projectPath) {
1353
1909
  if (!projectPath) {
1354
1910
  if (!this.cg) {
1911
+ if (this.defaultOpenFailure)
1912
+ throw this.defaultOpenFailure;
1355
1913
  const searched = this.defaultProjectHint ?? process.cwd();
1356
1914
  throw new NotIndexedError('No CodeGraph project is loaded for this session.\n' +
1357
1915
  `Searched for a .codegraph/ directory starting from: ${searched}\n` +
@@ -1377,7 +1935,7 @@ class ToolHandler {
1377
1935
  if ((0, fs_1.existsSync)(projectPath)) {
1378
1936
  const pathError = (0, utils_1.validateProjectPath)(projectPath);
1379
1937
  if (pathError) {
1380
- throw new PathRefusalError(pathError);
1938
+ throw new errors_2.PathRefusalError(pathError);
1381
1939
  }
1382
1940
  }
1383
1941
  // Always RE-RESOLVE the nearest .codegraph/ from the input path. The walk
@@ -1391,12 +1949,36 @@ class ToolHandler {
1391
1949
  // (#926). The DB connection itself is still cached (by resolved root,
1392
1950
  // below), so re-resolving costs only the stat walk, never a reopen.
1393
1951
  const resolvedRoot = (0, directory_1.findNearestCodeGraphRoot)(projectPath);
1394
- if (!resolvedRoot) {
1952
+ // Two spellings of one root (a symlinked checkout, `/tmp` vs
1953
+ // `/private/tmp`) must share one connection and one watcher (#1835).
1954
+ const canonicalRoot = resolvedRoot ? canonicalPath(resolvedRoot) : null;
1955
+ if (!resolvedRoot || !canonicalRoot) {
1395
1956
  throw new NotIndexedError(`The project at ${projectPath} isn't indexed with codegraph (no .codegraph/ directory found ` +
1396
1957
  'walking up from it), so codegraph cannot query it. Use your built-in tools (Read/Grep/Glob) ' +
1397
1958
  "for that codebase instead, and don't call codegraph for it again this session. " +
1398
1959
  "Indexing is the user's decision — they can run 'codegraph init' in that project to enable it.");
1399
1960
  }
1961
+ const cg = this.openProjectRoot(resolvedRoot, canonicalRoot);
1962
+ // The walk above crosses git boundaries. A nested repository the ancestor
1963
+ // index leaves out (typically gitignored) would otherwise be answered from
1964
+ // the ancestor's code, looking like an answer about the requested project
1965
+ // (#2110) — so it gets the same guidance as a project with no index at all.
1966
+ const nested = this.uncoveredNestedRepo(projectPath, canonicalRoot, cg);
1967
+ if (nested) {
1968
+ throw new NotIndexedError(`The project at ${projectPath} isn't indexed with codegraph: it is its own git repository ` +
1969
+ `(${nested.root}), and the nearest index, at ${canonicalRoot}, holds none of its files ` +
1970
+ '(that repository is excluded from it, e.g. by a .gitignore), so codegraph cannot query it. ' +
1971
+ "Use your built-in tools (Read/Grep/Glob) for that codebase instead, and don't call codegraph " +
1972
+ "for it again this session. Indexing is the user's decision — they can run 'codegraph init' " +
1973
+ `in ${nested.root} to enable it.`);
1974
+ }
1975
+ return cg;
1976
+ }
1977
+ /**
1978
+ * The open CodeGraph for an index root the up-walk resolved: the default
1979
+ * instance, a cached one, or a newly opened (and cached) one.
1980
+ */
1981
+ openProjectRoot(resolvedRoot, canonicalRoot) {
1400
1982
  // If the path resolves to the default project, reuse the already-open
1401
1983
  // default instance rather than opening a SECOND connection to the same DB.
1402
1984
  // A duplicate connection serializes reads against the watcher's auto-sync
@@ -1404,19 +1986,137 @@ class ToolHandler {
1404
1986
  // support) that surfaces as intermittent
1405
1987
  // "database is locked" on concurrent tool calls. See issue #238. The
1406
1988
  // default instance is owned/closed by the server, so it's never cached.
1407
- if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
1989
+ // Another spelling of the same root counts too (#1057).
1990
+ if (this.cg && (0, directory_1.isSameIndexRoot)(this.cg.getProjectRoot(), resolvedRoot)) {
1408
1991
  return this.freshen(this.cg);
1409
1992
  }
1410
- // Cache the open DB connection by RESOLVED ROOT only — never by the input
1993
+ // Cache the open DB connection by CANONICAL ROOT only — never by the input
1411
1994
  // path. One key per instance means closeAll() closes each exactly once, and
1412
1995
  // a changed resolution maps to a different entry instead of a stale hit.
1413
- const cached = this.projectCache.get(resolvedRoot);
1414
- if (cached)
1996
+ const cached = this.projectCache.get(canonicalRoot);
1997
+ if (cached) {
1998
+ // Refresh LRU position.
1999
+ this.projectCache.delete(canonicalRoot);
2000
+ this.projectCache.set(canonicalRoot, cached);
2001
+ this.projectUsedAt.set(canonicalRoot, Date.now());
1415
2002
  return this.freshen(cached);
1416
- const cg = loadCodeGraph().openSync(resolvedRoot);
1417
- this.projectCache.set(resolvedRoot, cg);
2003
+ }
2004
+ // Compare current identities on every cache miss: a previously seen alias
2005
+ // may have been retargeted or recreated since the last call (#1057).
2006
+ for (const [root, open] of this.projectCache) {
2007
+ if ((0, directory_1.isSameIndexRoot)(root, resolvedRoot)) {
2008
+ this.projectCache.delete(root);
2009
+ this.projectCache.set(root, open);
2010
+ this.projectUsedAt.set(root, Date.now());
2011
+ return this.freshen(open);
2012
+ }
2013
+ }
2014
+ const open = () => loadCodeGraph().openSync(canonicalRoot);
2015
+ const cg = this.projectLifecycle?.open(canonicalRoot, open) ?? open();
2016
+ this.projectCache.set(canonicalRoot, cg);
2017
+ this.projectUsedAt.set(canonicalRoot, Date.now());
2018
+ this.trimProjects();
1418
2019
  return cg;
1419
2020
  }
2021
+ /**
2022
+ * The nested git repository `projectPath` lives in when the index the
2023
+ * up-walk reached (`indexRoot`'s, open as `cg`) holds none of its files; null
2024
+ * when that index covers it — an ordinary subdirectory, a submodule or
2025
+ * embedded clone the ancestor indexes, a linked worktree (#155) — or when git
2026
+ * can't tell (#2110).
2027
+ *
2028
+ * The git half is memoized per (projectPath, index root), keyed on both for
2029
+ * the reason `worktreeMismatchCache` is (#926). The index half is one
2030
+ * primary-key probe per call, so a sync that brings the repository into the
2031
+ * index is honored without a restart.
2032
+ */
2033
+ uncoveredNestedRepo(projectPath, indexRoot, cg) {
2034
+ const cacheKey = `${projectPath}\u0000${indexRoot}`;
2035
+ let nested = this.nestedRepoCache.get(cacheKey);
2036
+ if (nested === undefined) {
2037
+ nested = (0, worktree_1.nestedRepositoryBelow)(projectPath, indexRoot);
2038
+ this.nestedRepoCache.set(cacheKey, nested);
2039
+ }
2040
+ if (!nested)
2041
+ return null;
2042
+ try {
2043
+ return cg.hasFilesUnder(nested.relPath) ? null : nested;
2044
+ }
2045
+ catch {
2046
+ // An index we can't read is no evidence the repository is excluded.
2047
+ return null;
2048
+ }
2049
+ }
2050
+ async awaitProjectGate(projectPath) {
2051
+ const cg = this.getCodeGraph(projectPath);
2052
+ if (!this.projectLifecycle || cg === this.cg)
2053
+ return;
2054
+ let gate = this.projectGates.get(cg);
2055
+ if (!gate) {
2056
+ gate = this.projectLifecycle.activate(cg).catch(() => { });
2057
+ this.projectGates.set(cg, gate);
2058
+ void gate.then(() => {
2059
+ if (this.projectGates.get(cg) === gate)
2060
+ this.projectGates.delete(cg);
2061
+ this.trimProjects();
2062
+ });
2063
+ }
2064
+ await this.awaitCatchUpGate(gate);
2065
+ }
2066
+ /**
2067
+ * Never evict a graph while a tool call or its timed-out reconcile uses it.
2068
+ * Evicts over the LRU bound, on close, and once idle past the timeout
2069
+ * (#2087). The cache is in last-use order, so idle entries lead it.
2070
+ */
2071
+ trimProjects() {
2072
+ if (this.activeCalls > 0)
2073
+ return;
2074
+ const idleMs = resolveProjectIdleTimeoutMs();
2075
+ const now = Date.now();
2076
+ for (const [root, cg] of this.projectCache) {
2077
+ const idle = idleMs > 0 && now - (this.projectUsedAt.get(root) ?? now) >= idleMs;
2078
+ if (!this.closing && this.projectCache.size <= exports.MAX_CACHED_PROJECTS && !idle)
2079
+ break;
2080
+ if (this.projectGates.has(cg))
2081
+ continue;
2082
+ this.projectCache.delete(root);
2083
+ this.projectUsedAt.delete(root);
2084
+ if (this.projectLifecycle) {
2085
+ this.pendingCloses++;
2086
+ void Promise.resolve(this.projectLifecycle.release(cg)).finally(() => {
2087
+ this.pendingCloses--;
2088
+ this.trimProjects();
2089
+ });
2090
+ }
2091
+ else
2092
+ cg.close();
2093
+ }
2094
+ if (this.closing && this.projectCache.size === 0 && this.pendingCloses === 0) {
2095
+ for (const resolve of this.closeWaiters.splice(0))
2096
+ resolve();
2097
+ }
2098
+ this.scheduleIdleRelease(idleMs);
2099
+ }
2100
+ /**
2101
+ * Arm one unref'd timer for the oldest project a trim could release. A
2102
+ * project whose catch-up is still running is trimmed when that settles; the
2103
+ * 1s floor keeps a project a trim must skip from re-arming in a tight loop.
2104
+ */
2105
+ scheduleIdleRelease(idleMs) {
2106
+ if (this.idleReleaseTimer || this.closing || idleMs <= 0)
2107
+ return;
2108
+ for (const [root, cg] of this.projectCache) {
2109
+ if (this.projectGates.has(cg))
2110
+ continue;
2111
+ const due = (this.projectUsedAt.get(root) ?? Date.now()) + idleMs - Date.now();
2112
+ this.idleReleaseTimer = setTimeout(() => {
2113
+ this.idleReleaseTimer = null;
2114
+ this.trimProjects();
2115
+ }, Math.min(Math.max(due, 1000), 0x7fffffff)); // setTimeout's 32-bit cap
2116
+ this.idleReleaseTimer.unref();
2117
+ return;
2118
+ }
2119
+ }
1420
2120
  /**
1421
2121
  * Heal a long-lived connection whose `.codegraph/` was removed and recreated
1422
2122
  * at the same path (a worktree recreated, or `rm -rf .codegraph` + re-init)
@@ -1432,6 +2132,7 @@ class ToolHandler {
1432
2132
  if (cg.reopenIfReplaced()) {
1433
2133
  process.stderr.write('[CodeGraph MCP] The index was replaced on disk (e.g. a git worktree ' +
1434
2134
  'recreated at the same path); reopened the live database in place.\n');
2135
+ this.onDatabaseReopened?.(cg);
1435
2136
  }
1436
2137
  }
1437
2138
  catch {
@@ -1444,11 +2145,16 @@ class ToolHandler {
1444
2145
  * Close all cached project connections
1445
2146
  */
1446
2147
  closeAll() {
1447
- for (const cg of this.projectCache.values()) {
1448
- cg.close();
1449
- }
1450
- this.projectCache.clear();
2148
+ this.closing = true;
1451
2149
  this.worktreeMismatchCache.clear();
2150
+ if (this.idleReleaseTimer)
2151
+ clearTimeout(this.idleReleaseTimer);
2152
+ this.idleReleaseTimer = null;
2153
+ this.nestedRepoCache.clear();
2154
+ this.trimProjects();
2155
+ if (this.projectCache.size === 0 && this.activeCalls === 0 && this.pendingCloses === 0)
2156
+ return Promise.resolve();
2157
+ return new Promise((resolve) => this.closeWaiters.push(resolve));
1452
2158
  }
1453
2159
  /**
1454
2160
  * Validate that a value is a non-empty string within length bounds.
@@ -1600,7 +2306,9 @@ class ToolHandler {
1600
2306
  // Same freshness test as the sync fast path (extraction/index.ts):
1601
2307
  // equal size + equal floored mtime ⇒ unchanged, no read needed.
1602
2308
  if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt)) {
1603
- const data = content ?? (0, fs_1.readFileSync)(absPath, 'utf-8');
2309
+ // A file over the index's size limit is stored as its size stamp
2310
+ // (#1910), so it is compared as one, without reading it.
2311
+ const data = (0, file_limits_1.indexedHashInput)(st.size, () => content ?? (0, fs_1.readFileSync)(absPath, 'utf-8'));
1604
2312
  // Must stay byte-identical to extraction's `hashContent` (sha256 over
1605
2313
  // the utf-8 string) — the identical-rewrite test in
1606
2314
  // mcp-stale-slice.test.ts pins the parity. Inlined (not imported)
@@ -1615,6 +2323,14 @@ class ToolHandler {
1615
2323
  this.driftCache.set(key, { at: now, stale });
1616
2324
  return stale;
1617
2325
  }
2326
+ answerResult(cg, text, paths) {
2327
+ const result = this.textResult(text);
2328
+ result._cgAnswerFiles = [...new Set(paths)].map(file => ({
2329
+ path: file,
2330
+ contentHash: cg.getFile(file)?.contentHash ?? null,
2331
+ }));
2332
+ return result;
2333
+ }
1618
2334
  withStalenessNotice(result, projectPath) {
1619
2335
  if (result.isError)
1620
2336
  return result;
@@ -1625,13 +2341,11 @@ class ToolHandler {
1625
2341
  catch {
1626
2342
  return result; // no default project — leave as is
1627
2343
  }
1628
- // Cross-project `projectPath` calls open a cached CodeGraph WITHOUT a
1629
- // watcher (watchers are only attached to the default session project).
2344
+ // A cross-project `projectPath` call's cached CodeGraph only has a watcher
2345
+ // when the engine owns its lifecycle (#1835) — the CLI's handler has none.
1630
2346
  // When the cross-project path happens to be the same project as the
1631
- // default cg, the cached instance is the wrong one — its pendingFiles is
1632
- // permanently empty. Detect the equal-path case and prefer the default
1633
- // cg so the staleness signal still fires when an agent passes the
1634
- // explicit projectPath form of its own project.
2347
+ // default cg, prefer the default cg so the staleness signal still fires
2348
+ // when an agent passes the explicit projectPath form of its own project.
1635
2349
  if (this.cg && cg !== this.cg) {
1636
2350
  try {
1637
2351
  const sameProject = (0, path_1.resolve)(this.cg.getProjectRoot()) === (0, path_1.resolve)(cg.getProjectRoot());
@@ -1646,9 +2360,9 @@ class ToolHandler {
1646
2360
  // stopped, getPendingFiles() is empty so the per-file banner below can't
1647
2361
  // fire — but the index is now FROZEN and silently drifting stale. Surface
1648
2362
  // one global notice instead, so the agent Reads for current content rather
1649
- // than trusting a response off a no-longer-updating index. (Cross-project
1650
- // calls open a watcher-less CodeGraph, so this is false there — correct: we
1651
- // only know degraded state for the default session project.)
2363
+ // than trusting a response off a no-longer-updating index. (A cross-project
2364
+ // instance without an engine-owned watcher reports false here — correct: we
2365
+ // only know degraded state for a project we watch.)
1652
2366
  let degraded = false;
1653
2367
  try {
1654
2368
  degraded = cg.isWatcherDegraded?.() ?? false;
@@ -1660,6 +2374,10 @@ class ToolHandler {
1660
2374
  const [head, ...tail] = result.content;
1661
2375
  if (!head || head.type !== 'text')
1662
2376
  return result;
2377
+ if (cg.isWatcherRecovering?.()) {
2378
+ const composed = `${formatRecoveringBanner()}\n\n${head.text}`;
2379
+ return { ...result, content: [{ type: 'text', text: composed }, ...tail] };
2380
+ }
1663
2381
  let reason = null;
1664
2382
  try {
1665
2383
  reason = cg.getWatcherDegradedReason?.() ?? null;
@@ -1688,10 +2406,10 @@ class ToolHandler {
1688
2406
  const inResponse = [];
1689
2407
  const elsewhere = [];
1690
2408
  for (const p of pending) {
1691
- // Substring match against the project-relative POSIX path — that's
1692
- // exactly the format both the watcher and every codegraph response
1693
- // emit, so a plain includes() is sufficient and avoids regex pitfalls.
1694
- if (text.includes(p.path))
2409
+ // Project-relative POSIX path — the format both the watcher and every
2410
+ // codegraph response emit — matched as a whole path, so a pending
2411
+ // `src/app.ts` isn't "referenced" by a response that shows `src/app.tsx`.
2412
+ if (mentionsPath(text, p.path))
1695
2413
  inResponse.push(p);
1696
2414
  else
1697
2415
  elsewhere.push(p);
@@ -1719,18 +2437,20 @@ class ToolHandler {
1719
2437
  * Omit it (the CLI does) and explore behaves exactly as before, untracked.
1720
2438
  */
1721
2439
  async execute(toolName, args, sessionState) {
2440
+ if (this.closing)
2441
+ return this.textResult('This MCP session is closing; retry with a connected session.');
2442
+ this.activeCalls++;
1722
2443
  try {
1723
2444
  // Block the first tool call on the engine's post-open reconcile so we
1724
2445
  // never serve rows for files deleted/edited while no MCP server was
1725
2446
  // running. The wait is time-boxed (#905): a huge-repo reconcile takes
1726
2447
  // minutes, and blocking the first call on all of it reads as a hang, so
1727
2448
  // we wait briefly then serve and let it finish in the background. The
1728
- // gate is cleared after first await — subsequent calls pay nothing.
2449
+ // gate stays installed until reconciliation settles, including on timeout.
1729
2450
  // Catch-up failures are logged by the engine; we proceed regardless so a
1730
2451
  // transient sync error never breaks tools.
1731
2452
  if (this.catchUpGate) {
1732
2453
  const gate = this.catchUpGate;
1733
- this.catchUpGate = null;
1734
2454
  await this.awaitCatchUpGate(gate);
1735
2455
  }
1736
2456
  // Honor the optional tool allowlist (CODEGRAPH_MCP_TOOLS): a trimmed
@@ -1746,6 +2466,13 @@ class ToolHandler {
1746
2466
  if (typeof pathCheck === 'object' && pathCheck !== undefined) {
1747
2467
  return pathCheck;
1748
2468
  }
2469
+ // An explicit project gets the same first-call guarantee as the default
2470
+ // (#1835): its post-open catch-up sync finishes (time-boxed) before we
2471
+ // serve it. Resolved on the main thread so the watcher lives here even
2472
+ // when dispatch is off-loaded to a worker.
2473
+ if (typeof pathCheck === 'string') {
2474
+ await this.awaitProjectGate(pathCheck);
2475
+ }
1749
2476
  // The `path` and `pattern` properties used by codegraph_files are
1750
2477
  // also path-shaped — apply the same cap.
1751
2478
  if (args.path !== undefined) {
@@ -1758,6 +2485,13 @@ class ToolHandler {
1758
2485
  if (typeof check === 'object' && check !== undefined)
1759
2486
  return check;
1760
2487
  }
2488
+ const project = await this.getCodeGraph(args.projectPath);
2489
+ // Recover a watcher disabled by prolonged lock contention on the next call.
2490
+ // The stale banner remains until the watcher finishes its full scan;
2491
+ // frequent calls cannot bypass its cooldown (#1959).
2492
+ if (project.rearmWatcherAfterLockContention?.()) {
2493
+ process.stderr.write('[CodeGraph MCP] Re-armed file watcher; full catch-up pending.\n');
2494
+ }
1761
2495
  // codegraph_status reports watcher state (pending files, degraded mode,
1762
2496
  // worktree warning) and embeds its own sections — it must run on the MAIN
1763
2497
  // thread against the watched default instance, so it is NEVER off-loaded to
@@ -1767,15 +2501,15 @@ class ToolHandler {
1767
2501
  return await this.handleStatus(args);
1768
2502
  }
1769
2503
  // Read tools: off-load the CPU-heavy dispatch to the worker pool when one
1770
- // is attached, healthy, AND has finished its first cold start (daemon
1771
- // mode), so the daemon's single event loop stays free for the MCP
2504
+ // is attached, healthy, AND has finished its first cold start,
2505
+ // so the server's single event loop stays free for the MCP
1772
2506
  // transport under concurrent load — otherwise N concurrent explores
1773
2507
  // serialize AND starve the transport until the whole batch drains
1774
2508
  // (clients then time out). Before the first worker is warm, calls run
1775
2509
  // in-process: a call queued behind a cold start sat invisible until the
1776
2510
  // 45s busy backstop — the daemon's first tool call stalling for however
1777
2511
  // long a worker spawn takes on a loaded machine (the #662 flake). With
1778
- // no pool (direct mode) or a degraded one, dispatch runs in-process
2512
+ // no pool or a degraded one, dispatch runs in-process
1779
2513
  // exactly as before. Either way the result flows through the
1780
2514
  // cross-cutting notices — worktree-index mismatch (#155) and per-file
1781
2515
  // staleness (#403) — which need the watched MAIN instance and so are
@@ -1787,9 +2521,37 @@ class ToolHandler {
1787
2521
  // structured-clone boundary into a worker, where a closure or a handler
1788
2522
  // field could not follow.
1789
2523
  const dispatchArgs = this.withSessionView(toolName, args, sessionState);
1790
- const raw = (this.queryPool && this.queryPool.healthy && this.queryPool.ready)
1791
- ? await this.queryPool.run(toolName, dispatchArgs)
2524
+ // The default may have appeared after the workers started. Pass the
2525
+ // main thread's current root explicitly; with no root or projectPath,
2526
+ // keep the main handler's workspace-specific not-indexed guidance.
2527
+ const pooled = !!(this.queryPool && this.queryPool.healthy && this.queryPool.ready);
2528
+ const projectPath = pooled ? args.projectPath ?? this.cg?.getProjectRoot() : undefined;
2529
+ const wasDegraded = project.isWatcherDegraded?.();
2530
+ const raw = (pooled && projectPath)
2531
+ ? await this.queryPool.run(toolName, { ...dispatchArgs, projectPath })
1792
2532
  : await this.executeReadTool(toolName, dispatchArgs);
2533
+ const answeredFrom = raw._cgAnswerFiles;
2534
+ delete raw._cgAnswerFiles;
2535
+ if (!raw.isError && answeredFrom && (wasDegraded || project.isWatcherDegraded?.())) {
2536
+ const validation = await (0, answer_freshness_1.validateAnswerFiles)(project.getProjectRoot(), answeredFrom);
2537
+ if (validation.stale.length || validation.unchecked.length) {
2538
+ // Rejected source must not enter the session's emission history.
2539
+ const lines = ['⚠️ CodeGraph cannot answer from this index:'];
2540
+ if (validation.stale.length) {
2541
+ lines.push('These files changed or became unavailable after their last sync:', ...validation.stale.map(file => `- ${file}`));
2542
+ }
2543
+ if (validation.unchecked.length) {
2544
+ lines.push(`Freshness could not be verified within the validation budget for ${validation.unchecked.length} files:`, ...validation.unchecked.slice(0, 20).map(file => `- ${file}`));
2545
+ if (validation.unchecked.length > 20)
2546
+ lines.push(`- … ${validation.unchecked.length - 20} more (narrow the query)`);
2547
+ }
2548
+ lines.push('Retry after a successful codegraph sync, or narrow the query.');
2549
+ // Text only: Claude Code shows the model a result's structuredContent
2550
+ // in place of its text (#2088). The text names every stale file and
2551
+ // the first unchecked ones; the rest only need a narrower query.
2552
+ return this.textResult(lines.join('\n'));
2553
+ }
2554
+ }
1793
2555
  // Record + STRIP before anything else touches the result: the emission is
1794
2556
  // internal bookkeeping and must never reach the client, whether or not a
1795
2557
  // caller passed session state.
@@ -1801,17 +2563,28 @@ class ToolHandler {
1801
2563
  // Expected condition, not a malfunction: answer as a SUCCESS so the
1802
2564
  // agent keeps trusting the toolset for projects that ARE indexed.
1803
2565
  // (An isError here teaches session-long abandonment — see NotIndexedError.)
1804
- if (err instanceof NotIndexedError) {
2566
+ // A running `codegraph index` rebuild is the same kind of expected,
2567
+ // temporary condition (#1325). Matched by name: tools.ts stays free of
2568
+ // the writer-lock module on the MCP startup path.
2569
+ if (err instanceof NotIndexedError || err?.name === 'RebuildInProgressError') {
1805
2570
  return this.textResult(err.message);
1806
2571
  }
2572
+ // Windows and WSL sharing one index (#995): the user's fix, not a malfunction.
2573
+ if (err instanceof wsl_shared_index_1.WslSharedIndexError) {
2574
+ return this.textResult(wslSharedIndexGuidance(err));
2575
+ }
1807
2576
  // Security refusal: a clean error, no retry encouragement.
1808
- if (err instanceof PathRefusalError) {
2577
+ if (err instanceof errors_2.PathRefusalError) {
1809
2578
  return this.errorResult(err.message);
1810
2579
  }
1811
2580
  return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
1812
2581
  'This is an internal codegraph error — retry the call once; if it persists, ' +
1813
2582
  'continue without codegraph for this task.');
1814
2583
  }
2584
+ finally {
2585
+ this.activeCalls--;
2586
+ this.trimProjects();
2587
+ }
1815
2588
  }
1816
2589
  /**
1817
2590
  * Attach the caller's session view to an explore call's args (CG-17), on a
@@ -1878,7 +2651,10 @@ class ToolHandler {
1878
2651
  if (err instanceof NotIndexedError) {
1879
2652
  return this.textResult(err.message);
1880
2653
  }
1881
- if (err instanceof PathRefusalError) {
2654
+ if (err instanceof wsl_shared_index_1.WslSharedIndexError) {
2655
+ return this.textResult(wslSharedIndexGuidance(err));
2656
+ }
2657
+ if (err instanceof errors_2.PathRefusalError) {
1882
2658
  return this.errorResult(err.message);
1883
2659
  }
1884
2660
  return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
@@ -1936,7 +2712,7 @@ class ToolHandler {
1936
2712
  return aGen - bGen;
1937
2713
  });
1938
2714
  const formatted = this.formatSearchResults(ranked);
1939
- return this.textResult(this.truncateOutput(formatted));
2715
+ return this.answerResult(cg, this.truncateOutput(formatted), ranked.map(r => r.node.filePath));
1940
2716
  }
1941
2717
  /**
1942
2718
  * Group symbol matches into DISTINCT DEFINITIONS — one group per
@@ -1946,28 +2722,7 @@ class ToolHandler {
1946
2722
  * `file` path/suffix first.
1947
2723
  */
1948
2724
  groupDefinitions(nodes, fileFilter) {
1949
- let pool = nodes;
1950
- let filteredOut = false;
1951
- if (fileFilter) {
1952
- const wanted = fileFilter.replace(/^\.\//, '');
1953
- const narrowed = pool.filter((n) => n.filePath === wanted || n.filePath.endsWith(wanted) || n.filePath.endsWith(`/${wanted}`));
1954
- if (narrowed.length > 0) {
1955
- pool = narrowed;
1956
- }
1957
- else {
1958
- filteredOut = true;
1959
- }
1960
- }
1961
- const byDef = new Map();
1962
- for (const n of pool) {
1963
- const key = `${n.filePath}|${n.qualifiedName}`;
1964
- const group = byDef.get(key);
1965
- if (group)
1966
- group.push(n);
1967
- else
1968
- byDef.set(key, [n]);
1969
- }
1970
- return { groups: [...byDef.values()], filteredOut };
2725
+ return (0, symbol_lookup_1.groupDefinitions)(nodes, fileFilter);
1971
2726
  }
1972
2727
  /** Section heading for one distinct definition in grouped output. */
1973
2728
  definitionHeading(group) {
@@ -1987,9 +2742,10 @@ class ToolHandler {
1987
2742
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
1988
2743
  const allMatches = this.findAllSymbols(cg, symbol);
1989
2744
  if (allMatches.nodes.length === 0) {
1990
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2745
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
1991
2746
  }
1992
2747
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2748
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
1993
2749
  const filterNote = filteredOut
1994
2750
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
1995
2751
  : '';
@@ -2002,6 +2758,7 @@ class ToolHandler {
2002
2758
  if (!seen.has(c.node.id)) {
2003
2759
  seen.add(c.node.id);
2004
2760
  callers.push(c.node);
2761
+ answerPaths.add(c.node.filePath);
2005
2762
  const label = this.edgeLabel(c.edge);
2006
2763
  if (label)
2007
2764
  labels.set(c.node.id, label);
@@ -2014,13 +2771,18 @@ class ToolHandler {
2014
2771
  if (groups.length === 1) {
2015
2772
  const { callers, labels } = collect(groups[0]);
2016
2773
  if (callers.length === 0) {
2017
- return this.textResult(`No callers found for "${symbol}"${allMatches.note}${filterNote}`);
2774
+ return this.answerResult(cg, `No callers found for "${symbol}"${allMatches.note}${filterNote}`, answerPaths);
2018
2775
  }
2019
2776
  // A successful `file` narrowing makes the multi-symbol aggregation note
2020
2777
  // stale — suppress it.
2021
2778
  const note = fileFilter && !filteredOut ? '' : allMatches.note;
2022
- const formatted = this.formatNodeList(callers.slice(0, limit), `Callers of ${symbol}`, labels) + note + filterNote;
2023
- return this.textResult(this.truncateOutput(formatted));
2779
+ // Say when the cap cut the list (#1639, #1674): a truncated answer with
2780
+ // no marker reads as the complete set, and an agent under-counts from it.
2781
+ const cut = callers.length > limit
2782
+ ? `\n\n> Showing ${limit} of ${callers.length} callers; pass \`limit\` (up to 100) to widen.`
2783
+ : '';
2784
+ const formatted = this.formatNodeList(callers.slice(0, limit), `Callers of ${symbol}`, labels) + cut + note + filterNote;
2785
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2024
2786
  }
2025
2787
  // Multiple DISTINCT definitions (#764): one section per definition so an
2026
2788
  // agent never mistakes one app's callers for another's. Narrow with
@@ -2040,8 +2802,11 @@ class ToolHandler {
2040
2802
  const label = labels.get(node.id);
2041
2803
  lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
2042
2804
  }
2805
+ if (callers.length > limit) {
2806
+ lines.push(`- … +${callers.length - limit} more (pass \`limit\` to widen)`);
2807
+ }
2043
2808
  }
2044
- return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
2809
+ return this.answerResult(cg, this.truncateOutput(lines.join('\n') + filterNote), answerPaths);
2045
2810
  }
2046
2811
  /**
2047
2812
  * Handle codegraph_callees
@@ -2055,9 +2820,10 @@ class ToolHandler {
2055
2820
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
2056
2821
  const allMatches = this.findAllSymbols(cg, symbol);
2057
2822
  if (allMatches.nodes.length === 0) {
2058
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2823
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
2059
2824
  }
2060
2825
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2826
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
2061
2827
  const filterNote = filteredOut
2062
2828
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
2063
2829
  : '';
@@ -2070,6 +2836,7 @@ class ToolHandler {
2070
2836
  if (!seen.has(c.node.id)) {
2071
2837
  seen.add(c.node.id);
2072
2838
  callees.push(c.node);
2839
+ answerPaths.add(c.node.filePath);
2073
2840
  const label = this.edgeLabel(c.edge);
2074
2841
  if (label)
2075
2842
  labels.set(c.node.id, label);
@@ -2081,13 +2848,18 @@ class ToolHandler {
2081
2848
  if (groups.length === 1) {
2082
2849
  const { callees, labels } = collect(groups[0]);
2083
2850
  if (callees.length === 0) {
2084
- return this.textResult(`No callees found for "${symbol}"${allMatches.note}${filterNote}`);
2851
+ return this.answerResult(cg, `No callees found for "${symbol}"${allMatches.note}${filterNote}`, answerPaths);
2085
2852
  }
2086
2853
  // A successful `file` narrowing makes the multi-symbol aggregation note
2087
2854
  // stale — suppress it.
2088
2855
  const note = fileFilter && !filteredOut ? '' : allMatches.note;
2089
- const formatted = this.formatNodeList(callees.slice(0, limit), `Callees of ${symbol}`, labels) + note + filterNote;
2090
- return this.textResult(this.truncateOutput(formatted));
2856
+ // Say when the cap cut the list (#1639, #1674): a truncated answer with
2857
+ // no marker reads as the complete set, and an agent under-counts from it.
2858
+ const cut = callees.length > limit
2859
+ ? `\n\n> Showing ${limit} of ${callees.length} callees; pass \`limit\` (up to 100) to widen.`
2860
+ : '';
2861
+ const formatted = this.formatNodeList(callees.slice(0, limit), `Callees of ${symbol}`, labels) + cut + note + filterNote;
2862
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2091
2863
  }
2092
2864
  // Multiple DISTINCT definitions (#764): per-definition sections.
2093
2865
  const lines = [
@@ -2105,8 +2877,11 @@ class ToolHandler {
2105
2877
  const label = labels.get(node.id);
2106
2878
  lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
2107
2879
  }
2880
+ if (callees.length > limit) {
2881
+ lines.push(`- … +${callees.length - limit} more (pass \`limit\` to widen)`);
2882
+ }
2108
2883
  }
2109
- return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
2884
+ return this.answerResult(cg, this.truncateOutput(lines.join('\n') + filterNote), answerPaths);
2110
2885
  }
2111
2886
  /**
2112
2887
  * Handle codegraph_impact
@@ -2120,9 +2895,10 @@ class ToolHandler {
2120
2895
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
2121
2896
  const allMatches = this.findAllSymbols(cg, symbol);
2122
2897
  if (allMatches.nodes.length === 0) {
2123
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2898
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
2124
2899
  }
2125
2900
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2901
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
2126
2902
  const filterNote = filteredOut
2127
2903
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
2128
2904
  : '';
@@ -2134,6 +2910,7 @@ class ToolHandler {
2134
2910
  const impact = cg.getImpactRadius(node.id, depth);
2135
2911
  for (const [id, n] of impact.nodes) {
2136
2912
  mergedNodes.set(id, n);
2913
+ answerPaths.add(n.filePath);
2137
2914
  }
2138
2915
  for (const e of impact.edges) {
2139
2916
  const key = `${e.source}->${e.target}:${e.kind}`;
@@ -2148,7 +2925,7 @@ class ToolHandler {
2148
2925
  // Single definition (or same-file overloads): the familiar merged report.
2149
2926
  if (groups.length === 1) {
2150
2927
  const formatted = this.formatImpact(symbol, impactOf(groups[0])) + (fileFilter && !filteredOut ? "" : allMatches.note) + filterNote;
2151
- return this.textResult(this.truncateOutput(formatted));
2928
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2152
2929
  }
2153
2930
  // Multiple DISTINCT definitions (#764): a blast radius PER definition —
2154
2931
  // merging unrelated same-named classes (one UserService per monorepo app)
@@ -2161,7 +2938,7 @@ class ToolHandler {
2161
2938
  const line = head.startLine ? `:${head.startLine}` : '';
2162
2939
  sections.push('', this.formatImpact(`${head.qualifiedName} (${head.filePath}${line})`, impactOf(group)));
2163
2940
  }
2164
- return this.textResult(this.truncateOutput(sections.join('\n') + filterNote));
2941
+ return this.answerResult(cg, this.truncateOutput(sections.join('\n') + filterNote), answerPaths);
2165
2942
  }
2166
2943
  /**
2167
2944
  * Describe a synthesized (dynamic-dispatch) edge for human output: how the
@@ -2169,6 +2946,33 @@ class ToolHandler {
2169
2946
  * for ordinary static edges. Used by trace + the node trail so a synthesized
2170
2947
  * hop reads as "registered via onUpdate at App.tsx:3148", not a bare arrow.
2171
2948
  */
2949
+ /**
2950
+ * The branch conditions a flow hop's call site runs under, read from the
2951
+ * caller's source now (`graph/branch-guards.ts`); '' when unconditional,
2952
+ * unreadable, or the grammar for that language is not loaded.
2953
+ */
2954
+ whenLabel(cg, caller, edge) {
2955
+ if (!edge.line || !(0, branch_guards_1.supportsBranchGuards)(caller.language))
2956
+ return '';
2957
+ try {
2958
+ const rec = cg.getFile(caller.filePath);
2959
+ if (!rec)
2960
+ return '';
2961
+ const abs = (0, utils_1.validatePathWithinRoot)(cg.getProjectRoot(), caller.filePath);
2962
+ if (!abs)
2963
+ return '';
2964
+ const st = (0, fs_1.statSync)(abs);
2965
+ // Drifted since the index: the recorded line may point elsewhere.
2966
+ if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt))
2967
+ return '';
2968
+ const site = { line: edge.line, column: typeof edge.column === 'number' ? edge.column : null };
2969
+ const g = (0, branch_guards_1.guardsForFileSync)(abs, caller.language, [site]).get((0, branch_guards_1.siteKey)(site));
2970
+ return g ? (0, branch_guards_1.guardLabel)(g) : '';
2971
+ }
2972
+ catch {
2973
+ return '';
2974
+ }
2975
+ }
2172
2976
  synthEdgeNote(edge) {
2173
2977
  if (!edge || edge.provenance !== 'heuristic')
2174
2978
  return null;
@@ -2184,6 +2988,33 @@ class ToolHandler {
2184
2988
  registeredAt,
2185
2989
  };
2186
2990
  }
2991
+ if (m?.synthesizedBy === 'http-client') {
2992
+ const req = `${String(m.method ?? 'GET')} ${String(m.href ?? '')}`.trim();
2993
+ return {
2994
+ label: `HTTP request \`${req}\` — the client's call onto its own route (cross-tier)`,
2995
+ compact: `dynamic: HTTP ${req}${at}`,
2996
+ registeredAt,
2997
+ };
2998
+ }
2999
+ if (m?.synthesizedBy === 'queue-job') {
3000
+ const job = m.event ? `\`${String(m.event)}\`` : 'a job';
3001
+ const queue = m.queue ? ` on queue \`${String(m.queue)}\`` : '';
3002
+ return {
3003
+ label: `queue job ${job}${queue} — producer → consumer (cross-tier)`,
3004
+ compact: `dynamic: queue job ${job}${at}`,
3005
+ registeredAt,
3006
+ };
3007
+ }
3008
+ if (m?.synthesizedBy === 'event-bus') {
3009
+ const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
3010
+ const what = m.channel === 'socket' ? 'socket message' : 'bus event';
3011
+ const dir = m.tier === 'client→server' ? ', client → server' : m.tier === 'server→client' ? ', server → client' : '';
3012
+ return {
3013
+ label: `${what} ${ev} — emit → handler${dir} (dynamic dispatch)`,
3014
+ compact: `dynamic: ${what} ${ev}${at}`,
3015
+ registeredAt,
3016
+ };
3017
+ }
2187
3018
  if (m?.synthesizedBy === 'event-emitter') {
2188
3019
  const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
2189
3020
  return {
@@ -2275,104 +3106,13 @@ class ToolHandler {
2275
3106
  // processRunExecutionData) to the call site instead of dumping the whole body.
2276
3107
  const EMPTY = { text: '', pathNodeIds: new Set(), namedNodeIds: new Set(), uniqueNamedNodeIds: new Set(), spineCallSites: new Map() };
2277
3108
  try {
2278
- const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
2279
- // Strip only a REAL file extension (Create.cs → Create); KEEP qualified
2280
- // names (Class.method / Class::method) — the agent's most precise input,
2281
- // resolved exactly by findAllSymbols. (The old strip mangled Class.method
2282
- // into Class, throwing the method away.)
2283
- 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;
2284
- const tokens = [...new Set(query.split(/[\s,()[\]]+/)
2285
- .map((t) => t.replace(FILE_EXT, '').trim())
2286
- .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t)))].slice(0, 16);
2287
- if (tokens.length < 2)
3109
+ // Token resolution — parsing, overload disambiguation, the CONSTANT/
3110
+ // VARIABLE synth endpoints — is shared with `/api/flow`, so a name written
3111
+ // in the viewer's search box resolves to the same nodes it does here.
3112
+ const flow = (0, named_symbol_flow_1.resolveNamedSymbolFlow)(cg, query);
3113
+ const { named, dynNamed, tokenNodes, tokenFamily, uniqueNamedNodeIds, preciseNamedIds } = flow;
3114
+ if (flow.tokens.length < 2)
2288
3115
  return EMPTY;
2289
- // Pool of name SEGMENTS (Class + method from every token) used to
2290
- // disambiguate an ambiguous SIMPLE name: keep a candidate only if its
2291
- // CONTAINER class is itself named in the query.
2292
- const segPool = new Set();
2293
- for (const t of tokens)
2294
- for (const s of t.toLowerCase().split(/::|\./))
2295
- if (s)
2296
- segPool.add(s);
2297
- const named = new Map();
2298
- // Nodes whose token is SPECIFIC — a (near-)unique callable name (<=3 defs in
2299
- // the whole graph). These are safe to SPARE a file on: the agent named THIS
2300
- // method (`getResponseWithInterceptorChain`, 1 def). A hyper-polymorphic name
2301
- // (`as_sql`, 110 defs across every Expression/Compiler subclass) is NOT here,
2302
- // so naming it doesn't keep every backend variant full and flood the budget.
2303
- const uniqueNamedNodeIds = new Set();
2304
- // token → resolved node ids: drives the token-coverage check that gates
2305
- // the dynamic-boundary scan (a token is covered when ANY of its nodes
2306
- // lands on the main chain — overloads off the chain don't count against).
2307
- const tokenNodes = new Map();
2308
- // token → its full same-name callable family (before the container filter).
2309
- // A LARGE family that fails to connect on the chain is a polymorphic
2310
- // interface/registry dispatch — surfaced by buildPolymorphicBoundaries below.
2311
- const tokenFamily = new Map();
2312
- // Non-callable endpoints (CONSTANT/VARIABLE/FIELD) connected by a SYNTHESIZED
2313
- // edge. RTK thunks are `const X = createAsyncThunk(...)`, so a thunk→thunk hop
2314
- // is constant→constant — the CALLABLE-only `named` set can't hold it, and
2315
- // without this the hop is invisible to the Flow path at every tier (the
2316
- // Relationships section catches it only on repos ≥500 files). Kept SEPARATE
2317
- // from `named` (which drives the call-chain + source sizing, callable-only);
2318
- // fed only to the dynamic-dispatch-links scan below.
2319
- const dynNamed = new Map();
2320
- const DYN_KINDS = new Set(['constant', 'variable', 'field', 'property']);
2321
- // Nodes resolved from a SHAPE-PRECISE token (camelCase / PascalCase /
2322
- // snake_case / qualified) — the same test the gather path uses. It is the
2323
- // difference between "the agent named this symbol" and "an ordinary English
2324
- // word in a prose question collided with a callable", and it is what makes
2325
- // the narrative-less return below safe (see `identityOnly`).
2326
- const isPreciseToken = (x) => /[._$]|::|\//.test(x) || /[a-z][A-Z]/.test(x) || /^[A-Z]/.test(x);
2327
- const preciseNamedIds = new Set();
2328
- const hasHeuristicEdge = (id) => [...cg.getCallers(id), ...cg.getCallees(id)].some(({ edge }) => edge.provenance === 'heuristic');
2329
- for (const t of tokens) {
2330
- const hits = this.findAllSymbols(cg, t).nodes;
2331
- const cands = hits.filter((n) => CALLABLE.has(n.kind));
2332
- tokenFamily.set(t, cands);
2333
- // A qualified or otherwise-specific name (<=3 hits) keeps all; an
2334
- // ambiguous simple name keeps only candidates whose container is named.
2335
- const specific = cands.length <= 3;
2336
- const pick = specific
2337
- ? cands
2338
- : cands.filter((n) => {
2339
- const segs = (n.qualifiedName || '').toLowerCase().split(/::|\./).filter(Boolean);
2340
- const container = segs.length >= 2 ? segs[segs.length - 2] : '';
2341
- return !!container && segPool.has(container);
2342
- });
2343
- const kept = pick.slice(0, 6);
2344
- tokenNodes.set(t, kept.map((n) => n.id));
2345
- const precise = isPreciseToken(t);
2346
- for (const n of kept) {
2347
- named.set(n.id, n);
2348
- if (specific)
2349
- uniqueNamedNodeIds.add(n.id);
2350
- if (precise)
2351
- preciseNamedIds.add(n.id);
2352
- }
2353
- // Same token, non-callable synth endpoints (capped, precision-gated on an
2354
- // actual heuristic edge so plain config constants never qualify).
2355
- // Per-token sub-cap so one token's many endpoints (10 nix option writes
2356
- // of `programs.git.enable` across test configs) can't fill the pool
2357
- // before later tokens (`home.file`) get a slot.
2358
- if (dynNamed.size < 12) {
2359
- let tokenDyn = 0;
2360
- for (const n of hits) {
2361
- if (CALLABLE.has(n.kind) || !DYN_KINDS.has(n.kind) || dynNamed.has(n.id))
2362
- continue;
2363
- if (hasHeuristicEdge(n.id)) {
2364
- dynNamed.set(n.id, n);
2365
- if (precise)
2366
- preciseNamedIds.add(n.id);
2367
- tokenDyn++;
2368
- }
2369
- if (dynNamed.size >= 12 || tokenDyn >= 4)
2370
- break;
2371
- }
2372
- }
2373
- if (named.size > 40)
2374
- break;
2375
- }
2376
3116
  // Surface synthesized (heuristic) edges incident to a named symbol — INCLUDING
2377
3117
  // the non-callable CONSTANT endpoints in `dynNamed`. `skipInChain` drops a hop
2378
3118
  // already shown in the rendered main chain (a 2-node chain renders nothing, so a
@@ -2383,10 +3123,19 @@ class ToolHandler {
2383
3123
  for (const n of [...named.values(), ...dynNamed.values()]) {
2384
3124
  if (synthLines.length >= 6)
2385
3125
  break;
2386
- for (const { node: other, edge } of [...cg.getCallers(n.id), ...cg.getCallees(n.id)]) {
3126
+ // RAW edges for the same reason as hasHeuristicEdge above — a static
3127
+ // edge over the same pair hides the synthesized one from getCallers.
3128
+ const incident = [...cg.getIncomingEdges(n.id), ...cg.getOutgoingEdges(n.id)];
3129
+ for (const edge of incident) {
2387
3130
  if (synthLines.length >= 6)
2388
3131
  break;
2389
- if (edge.provenance !== 'heuristic' || other.id === n.id)
3132
+ if (edge.provenance !== 'heuristic')
3133
+ continue;
3134
+ const otherId = edge.source === n.id ? edge.target : edge.source;
3135
+ if (otherId === n.id)
3136
+ continue;
3137
+ const other = cg.getNode(otherId);
3138
+ if (!other)
2390
3139
  continue;
2391
3140
  if (skipInChain && skipInChain(edge))
2392
3141
  continue;
@@ -2449,63 +3198,16 @@ class ToolHandler {
2449
3198
  out.push('> Full source for these symbols is below.\n');
2450
3199
  return { text: out.join('\n'), pathNodeIds: new Set(), namedNodeIds: new Set([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites: new Map() };
2451
3200
  }
2452
- const MAX_HOPS = 7;
2453
- let best = null;
2454
- // BFS the full call graph (incl. synth edges) from each named seed, but
2455
- // only ACCEPT a sink that is also named — both ends anchored to symbols the
2456
- // agent named, so the chain stays on-topic while bridging intermediates
2457
- // (e.g. the exact interface overload) that the token resolution missed.
2458
- for (const seed of [...named.values()].slice(0, 8)) {
2459
- const parent = new Map();
2460
- parent.set(seed.id, { prev: null, edge: null, node: seed });
2461
- const q = [{ id: seed.id, depth: 0, streak: 0 }];
2462
- let deep = null, deepDepth = 0;
2463
- const MAX_BRIDGE = 1; // ≤1 consecutive UNNAMED hop: bridge one missing intermediate, never wander a god-function's fan-out
2464
- for (let h = 0; h < q.length && parent.size < 1500; h++) {
2465
- const { id, depth, streak } = q[h];
2466
- if (id !== seed.id && named.has(id) && depth > deepDepth) {
2467
- deep = id;
2468
- deepDepth = depth;
2469
- }
2470
- if (depth >= MAX_HOPS - 1)
2471
- continue;
2472
- for (const c of cg.getCallees(id)) {
2473
- if (c.edge.kind !== 'calls' || parent.has(c.node.id))
2474
- continue;
2475
- const newStreak = named.has(c.node.id) ? 0 : streak + 1;
2476
- if (newStreak > MAX_BRIDGE)
2477
- continue;
2478
- parent.set(c.node.id, { prev: id, edge: c.edge, node: c.node });
2479
- q.push({ id: c.node.id, depth: depth + 1, streak: newStreak });
2480
- }
2481
- }
2482
- if (!deep)
2483
- continue;
2484
- const chain = [];
2485
- let cur = deep;
2486
- while (cur) {
2487
- const p = parent.get(cur);
2488
- if (!p)
2489
- break;
2490
- chain.push({ node: p.node, edge: p.edge });
2491
- cur = p.prev;
2492
- }
2493
- chain.reverse();
2494
- if (!best || chain.length > best.length)
2495
- best = chain;
2496
- }
3201
+ // The search itself lives in `../graph/named-symbol-flow`, so the viewer's
3202
+ // Flow strip rides exactly this path finder rather than a second one that
3203
+ // could disagree with it. What stays here is the PROSE — the narrative,
3204
+ // the dynamic-dispatch links, the boundary announcements.
3205
+ const best = flow.chains[0]?.steps ?? null;
2497
3206
  const hasMain = !!best && best.length >= 3;
2498
3207
  const pathIds = new Set((best ?? []).map((s) => s.node.id));
2499
- // Where each spine node calls the NEXT hop (best[i+1].edge is the edge from
2500
- // best[i] → best[i+1]; its line is the call site inside best[i]'s body). Lets
2501
- // the assembler window an oversize spine method to the call instead of dumping it.
2502
- const spineCallSites = new Map();
2503
- if (best)
2504
- for (let i = 0; i < best.length - 1; i++) {
2505
- const ln = best[i + 1]?.edge?.line;
2506
- if (ln && ln > 0 && !spineCallSites.has(best[i].node.id))
2507
- spineCallSites.set(best[i].node.id, ln);
2508
- }
3208
+ // Where each spine node calls the NEXT hop — lets the assembler window an
3209
+ // oversize spine method to the call instead of dumping the whole body.
3210
+ const spineCallSites = flow.chains[0]?.callSites ?? new Map();
2509
3211
  // Dynamic-boundary scan (#687) — fires ONLY when the flow the agent
2510
3212
  // asked about did not fully connect: some token resolved to nodes but
2511
3213
  // none of them sit on the main chain (or there is no chain at all). A
@@ -2584,7 +3286,8 @@ class ToolHandler {
2584
3286
  const step = best[i];
2585
3287
  if (step.edge) {
2586
3288
  const sy = this.synthEdgeNote(step.edge);
2587
- out.push(` ↓ ${sy ? sy.compact : step.edge.kind}`);
3289
+ const when = i > 0 ? this.whenLabel(cg, best[i - 1].node, step.edge) : '';
3290
+ out.push(` ↓ ${sy ? sy.compact : step.edge.kind}${when ? ` (when ${when})` : ''}`);
2588
3291
  }
2589
3292
  out.push(`${i + 1}. ${step.node.name} (${step.node.filePath}:${step.node.startLine})`);
2590
3293
  }
@@ -2622,52 +3325,24 @@ class ToolHandler {
2622
3325
  */
2623
3326
  buildDynamicBoundaries(cg, scanList, named) {
2624
3327
  const MAX_NOTES = 4; // boundary bullets per explore
2625
- const MAX_SCAN = 8; // bodies scanned
2626
- const MAX_TOTAL_CHARS = 200_000;
2627
- let projectRoot;
2628
- try {
2629
- projectRoot = cg.getProjectRoot();
2630
- }
2631
- catch {
2632
- return '';
2633
- }
3328
+ // The verdict is not derived here — `findDynamicBoundaries` produces it and
3329
+ // the viewer's end cap renders the same object, so the two can never
3330
+ // disagree about where a flow stops. What is left here is the prose.
3331
+ const reports = (0, dynamic_boundary_report_1.findDynamicBoundaries)(cg, scanList, { named, maxSites: MAX_NOTES });
2634
3332
  const notes = [];
2635
- const seenNode = new Set();
2636
- const seenSite = new Set();
2637
- let scanned = 0, charsScanned = 0;
2638
- for (const node of scanList) {
2639
- if (notes.length >= MAX_NOTES || scanned >= MAX_SCAN || charsScanned > MAX_TOTAL_CHARS)
3333
+ for (const report of reports) {
3334
+ if (notes.length >= MAX_NOTES)
2640
3335
  break;
2641
- if (seenNode.has(node.id) || !node.startLine || !node.endLine)
2642
- continue;
2643
- seenNode.add(node.id);
2644
- const absPath = (0, utils_1.validatePathWithinRoot)(projectRoot, node.filePath);
2645
- if (!absPath || !(0, fs_1.existsSync)(absPath))
2646
- continue;
2647
- let content;
2648
- try {
2649
- content = (0, fs_1.readFileSync)(absPath, 'utf-8');
2650
- }
2651
- catch {
2652
- continue;
2653
- }
2654
- const body = content.split('\n').slice(node.startLine - 1, node.endLine).join('\n');
2655
- scanned++;
2656
- charsScanned += body.length;
2657
- for (const m of (0, dynamic_boundaries_1.scanDynamicDispatch)(body, node.language || '', node.startLine)) {
3336
+ for (const site of report.sites) {
2658
3337
  if (notes.length >= MAX_NOTES)
2659
3338
  break;
2660
- const siteKey = `${node.filePath}:${m.line}:${m.form}`;
2661
- if (seenSite.has(siteKey))
2662
- continue;
2663
- seenSite.add(siteKey);
2664
- const more = m.moreSites ? ` (+${m.moreSites} more such site${m.moreSites > 1 ? 's' : ''} in this body)` : '';
2665
- notes.push(`- \`${node.name}\` (${node.filePath}:${m.line}) — ${m.label}: \`${m.snippet}\`${more}`);
2666
- if (m.key) {
2667
- const cand = this.boundaryCandidates(cg, m.key, !!m.keyIsType, named, node.id);
2668
- if (cand)
2669
- notes.push(` ${cand}`);
2670
- }
3339
+ const more = site.moreSites
3340
+ ? ` (+${site.moreSites} more such site${site.moreSites > 1 ? 's' : ''} in this body)`
3341
+ : '';
3342
+ notes.push(`- \`${report.node.name}\` (${report.node.filePath}:${site.line}) — ${site.label}: \`${site.snippet}\`${more}`);
3343
+ const cand = this.boundaryCandidates(site);
3344
+ if (cand)
3345
+ notes.push(` ${cand}`);
2671
3346
  }
2672
3347
  }
2673
3348
  if (notes.length === 0)
@@ -2716,11 +3391,91 @@ class ToolHandler {
2716
3391
  return null;
2717
3392
  }
2718
3393
  };
3394
+ // A supertype dispatches only a member it (or an ancestor) declares. Without
3395
+ // this, any name shared by enough subclasses read as dispatch through their
3396
+ // common base: on vscode the query word `extension`, a getter on unrelated
3397
+ // classes that all extend `Disposable`, was announced as "runtime dispatch to
3398
+ // 2706 types implementing Disposable" at the top of 9 of 31 answers.
3399
+ //
3400
+ // A Swift protocol and each of its extensions are separate nodes of one name,
3401
+ // and a conformer's edge may land on any of them (Alamofire's
3402
+ // `RequestInterceptor` conformers point at an extension in OfflineRetrier.swift
3403
+ // that has no `adapt`), so every same-named type is asked. The answer is
3404
+ // `unknown`, and the announcement stays, whenever absence can't be judged:
3405
+ // nothing on the chain has indexed members of the family's sort, or an
3406
+ // interface/protocol on it has none (Swift requirements aren't nodes, so
3407
+ // `URLRequestConvertible` can't be said to lack `asURLRequest`).
3408
+ const memberOfSupertype = (typeId, name, callable) => {
3409
+ const counts = (kind) => !callable || kind === 'method' || kind === 'function';
3410
+ let sawMembers = false;
3411
+ let opaque = false;
3412
+ const seen = new Set();
3413
+ const visit = (id, depth) => {
3414
+ if (seen.has(id))
3415
+ return false;
3416
+ seen.add(id);
3417
+ let node = null;
3418
+ let edges = [];
3419
+ try {
3420
+ node = cg.getNode(id);
3421
+ edges = cg.getOutgoingEdges(id);
3422
+ }
3423
+ catch {
3424
+ return false;
3425
+ }
3426
+ let own = 0;
3427
+ for (const e of edges) {
3428
+ if (e.kind !== 'contains')
3429
+ continue;
3430
+ let child = null;
3431
+ try {
3432
+ child = cg.getNode(e.target);
3433
+ }
3434
+ catch {
3435
+ child = null;
3436
+ }
3437
+ if (!child)
3438
+ continue;
3439
+ if (child.name === name)
3440
+ return true;
3441
+ if (counts(child.kind))
3442
+ own++;
3443
+ }
3444
+ if (own > 0)
3445
+ sawMembers = true;
3446
+ else if (node && (node.kind === 'interface' || node.kind === 'protocol' || node.kind === 'trait'))
3447
+ opaque = true;
3448
+ if (depth >= 3)
3449
+ return false;
3450
+ return edges.some((e) => (e.kind === 'extends' || e.kind === 'implements') && visit(e.target, depth + 1));
3451
+ };
3452
+ let root = null;
3453
+ try {
3454
+ root = cg.getNode(typeId);
3455
+ }
3456
+ catch {
3457
+ root = null;
3458
+ }
3459
+ let namesakes = [];
3460
+ try {
3461
+ namesakes = root
3462
+ ? cg.getNodesByName(root.name).filter((n) => n.language === root.language && CLASSY.has(n.kind))
3463
+ : [];
3464
+ }
3465
+ catch {
3466
+ namesakes = [];
3467
+ }
3468
+ if (visit(typeId, 0) || namesakes.some((n) => visit(n.id, 0)))
3469
+ return 'declared';
3470
+ return sawMembers && !opaque ? 'absent' : 'unknown';
3471
+ };
2719
3472
  const notes = [];
2720
3473
  const seenSuper = new Set();
2721
3474
  for (const { token, family } of candidates) {
2722
3475
  if (notes.length >= MAX_NOTES)
2723
3476
  break;
3477
+ const memberName = family[0]?.name ?? token;
3478
+ const callableFamily = family[0]?.kind === 'method' || family[0]?.kind === 'function';
2724
3479
  // supertype id → how many sampled definers share it + a few example definers
2725
3480
  const supers = new Map();
2726
3481
  for (const m of family.slice(0, SAMPLE)) {
@@ -2754,15 +3509,19 @@ class ToolHandler {
2754
3509
  for (const { node, count, targets } of supers.values()) {
2755
3510
  if (count < MIN_SUPPORT)
2756
3511
  continue;
2757
- let impl = 0;
2758
- try {
2759
- impl = cg.getIncomingEdges(node.id).filter((e) => e.kind === 'implements' || e.kind === 'extends').length;
2760
- }
2761
- catch { /* leave 0 — gated out below */ }
3512
+ // The implementer count is `countImplementers` — the same function the
3513
+ // viewer's type-hierarchy fan counts with, so "dispatch to N types
3514
+ // implementing X" is the same N on both surfaces (CG-58). Distinct
3515
+ // types, not edges: a class tied to its supertype by both a parsed
3516
+ // `extends` and a synthesized `implements` is one implementation.
3517
+ const impl = (0, type_hierarchy_1.countImplementers)(cg, node.id);
2762
3518
  if (impl < MIN_IMPL)
2763
3519
  continue;
2764
- if (!best || impl > best.impl)
2765
- best = { node, impl, targets };
3520
+ if (best && impl <= best.impl)
3521
+ continue;
3522
+ if (memberOfSupertype(node.id, memberName, callableFamily) === 'absent')
3523
+ continue;
3524
+ best = { node, impl, targets };
2766
3525
  }
2767
3526
  if (!best || seenSuper.has(best.node.id))
2768
3527
  continue;
@@ -2789,89 +3548,19 @@ class ToolHandler {
2789
3548
  ].join('\n');
2790
3549
  }
2791
3550
  /**
2792
- * Shortlist candidate runtime targets for a dispatch key surfaced by
2793
- * {@link buildDynamicBoundaries}. Exact conventional names first (`save` →
2794
- * `onSave`/`handleSave`; `CreateCmd` → `CreateCmdHandler`), then FTS, with a
2795
- * normalized-containment post-filter (FTS camel-splitting is fuzzier than a
2796
- * candidate list should be). Symbols the agent already named sort first and
2797
- * are marked — that's the "you were right, here's the wiring" case.
3551
+ * Render the candidate shortlist for a dispatch site as one line.
3552
+ *
3553
+ * The shortlist itself is `shortlistBoundaryCandidates` in
3554
+ * `../graph/dynamic-boundary-report` — shared with the viewer's end cap, so
3555
+ * "candidates for key `save`" names the same symbols in both places. Symbols
3556
+ * the agent already named are marked: that is the "you were right, here's the
3557
+ * wiring" case.
2798
3558
  */
2799
- boundaryCandidates(cg, key, keyIsType, named, selfId) {
2800
- const CALLABLE = new Set(['method', 'function', 'component', 'constructor', 'class']);
2801
- const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
2802
- const keyNorm = norm(key);
2803
- if (keyNorm.length < 3)
2804
- return '';
2805
- const cands = new Map();
2806
- const consider = (n) => {
2807
- if (!n || n.id === selfId || !CALLABLE.has(n.kind) || cands.has(n.id))
2808
- return;
2809
- const nameNorm = norm(n.name || '');
2810
- if (nameNorm.length < 3)
2811
- return;
2812
- if (!nameNorm.includes(keyNorm) && !keyNorm.includes(nameNorm))
2813
- return;
2814
- cands.set(n.id, n);
2815
- };
2816
- const cap = key.charAt(0).toUpperCase() + key.slice(1);
2817
- const probes = keyIsType
2818
- ? [`${key}Handler`, key]
2819
- : [key, `on${cap}`, `handle${cap}`, `${key}Handler`, `handle_${key}`];
2820
- for (const p of probes) {
2821
- try {
2822
- for (const n of cg.getNodesByName(p))
2823
- consider(n);
2824
- }
2825
- catch { /* exact probe miss is fine */ }
2826
- }
2827
- let raw = 0;
2828
- try {
2829
- const results = cg.searchNodes(key, { limit: 12 });
2830
- raw = results.length;
2831
- for (const r of results)
2832
- consider(r.node);
2833
- }
2834
- catch { /* FTS syntax edge — exact probes already ran */ }
2835
- if (cands.size === 0) {
2836
- return raw >= 12 && key.length < 5 ? `key \`${key}\` is too generic to shortlist (${raw}+ matches)` : '';
2837
- }
2838
- // A constructor candidate duplicates its class: extractors emit ctors as
2839
- // METHOD nodes named like the class (C#/Java `Foo::Foo`) — keep the class.
2840
- const all = [...cands.values()];
2841
- const classKey = new Set(all.filter((n) => n.kind === 'class').map((n) => `${n.name}|${n.filePath}`));
2842
- const namedNames = new Set([...named.values()].map((n) => n.name));
2843
- 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
2844
- const list = all
2845
- .filter((n) => !(n.kind !== 'class' && classKey.has(`${n.name}|${n.filePath}`)))
2846
- .sort((a, b) => (isNamed(b) ? 1 : 0) - (isNamed(a) ? 1 : 0))
2847
- .slice(0, 4)
2848
- .map((n) => {
2849
- // Typed-bus convention: the runtime target is the candidate class's
2850
- // Handle/Execute/Consume method — name the exact node, not just the class.
2851
- let display = n.qualifiedName || n.name;
2852
- let at = `${n.filePath}:${n.startLine}`;
2853
- if (keyIsType && n.kind === 'class') {
2854
- try {
2855
- const HANDLER_METHODS = /^(handle|handleAsync|execute|executeAsync|consume|consumeAsync|run|__invoke)$/i;
2856
- const method = cg.getOutgoingEdges(n.id)
2857
- .filter((e) => e.kind === 'contains')
2858
- .map((e) => { try {
2859
- return cg.getNode(e.target);
2860
- }
2861
- catch {
2862
- return null;
2863
- } })
2864
- .find((c) => !!c && c.kind === 'method' && HANDLER_METHODS.test(c.name));
2865
- if (method) {
2866
- display = `${n.name}.${method.name}`;
2867
- at = `${method.filePath}:${method.startLine}`;
2868
- }
2869
- }
2870
- catch { /* class without resolvable members — show the class itself */ }
2871
- }
2872
- return `\`${display}\` (${at})${isNamed(n) ? ' ← you named this' : ''}`;
2873
- });
2874
- return `candidates for key \`${key}\`: ${list.join(', ')}`;
3559
+ boundaryCandidates(site) {
3560
+ if (site.candidates.length === 0)
3561
+ return site.candidateNote ?? '';
3562
+ const list = site.candidates.map((c) => `\`${c.display}\` (${c.node.filePath}:${c.node.startLine})${c.named ? ' ← you named this' : ''}`);
3563
+ return `candidates for key \`${site.key}\`: ${list.join(', ')}`;
2875
3564
  }
2876
3565
  /**
2877
3566
  * Compact "blast radius" for the entry symbols of an explore result: who
@@ -2881,7 +3570,14 @@ class ToolHandler {
2881
3570
  * that have no dependents (nothing to warn about), and returns '' when none
2882
3571
  * qualify so a leaf-only exploration stays clean.
2883
3572
  */
2884
- buildBlastRadiusSection(cg, subgraph) {
3573
+ buildBlastRadiusSection(cg, subgraph,
3574
+ /**
3575
+ * Exact targets (a qualified name, a line anchor) lead the list. The search
3576
+ * roots are whatever FTS ranked first for the bare name, so without this a
3577
+ * query for `SQLCompiler.as_sql` headlined `SQLInsertCompiler.as_sql` — and
3578
+ * the agent took that as the tool having found the wrong method.
3579
+ */
3580
+ leadingIds = []) {
2885
3581
  const ROOT_CAP = 5; // only the symbols the query actually targeted
2886
3582
  const FILE_CAP = 4; // caller files listed per symbol before "+N more"
2887
3583
  const MEANINGFUL = new Set([
@@ -2889,7 +3585,7 @@ class ToolHandler {
2889
3585
  'enum', 'type_alias', 'component', 'constant', 'variable', 'property', 'field',
2890
3586
  ]);
2891
3587
  const rel = (p) => p.replace(/\\/g, '/');
2892
- const roots = subgraph.roots
3588
+ const roots = [...new Set([...leadingIds, ...subgraph.roots])]
2893
3589
  .map((id) => subgraph.nodes.get(id))
2894
3590
  .filter((n) => !!n && MEANINGFUL.has(n.kind))
2895
3591
  .slice(0, ROOT_CAP);
@@ -3011,7 +3707,7 @@ class ToolHandler {
3011
3707
  idx.set(nodeIds[i], i);
3012
3708
  const RANK_EDGES = new Set([
3013
3709
  'calls', 'references', 'extends', 'implements', 'overrides',
3014
- 'instantiates', 'returns', 'type_of', 'imports',
3710
+ 'instantiates', 'returns', 'type_of', 'imports', 'navigates',
3015
3711
  ]);
3016
3712
  const adj = Array.from({ length: n }, () => []);
3017
3713
  for (const e of edges) {
@@ -3092,8 +3788,11 @@ class ToolHandler {
3092
3788
  // pre-#185 behavior for callers that hit the rare stats failure.
3093
3789
  let budget;
3094
3790
  let indexedFileCount = -1;
3791
+ let indexedNodeCount = -1;
3095
3792
  try {
3096
- indexedFileCount = cg.getStats().fileCount;
3793
+ const stats = cg.getStats();
3794
+ indexedFileCount = stats.fileCount;
3795
+ indexedNodeCount = stats.nodeCount;
3097
3796
  budget = getExploreOutputBudget(indexedFileCount);
3098
3797
  }
3099
3798
  catch {
@@ -3110,18 +3809,34 @@ class ToolHandler {
3110
3809
  // `+page.svelte`), starving the very files the agent asked for.
3111
3810
  let pinnedFiles = [];
3112
3811
  let unresolvedPathSpans = [];
3812
+ let lineAnchors = [];
3813
+ let setAsideMatches = [];
3113
3814
  let matchQuery = query;
3114
3815
  if ((0, query_paths_1.queryMightContainPaths)(rawQuery)) {
3115
3816
  try {
3116
- const extraction = (0, query_paths_1.extractQueryPaths)(rawQuery, cg.getFiles().map((f) => f.path), { maxPins: maxFiles });
3817
+ const extraction = (0, query_paths_1.extractQueryPaths)(rawQuery, cg.getFiles().map((f) => f.path), {
3818
+ maxPins: maxFiles,
3819
+ existsOnDisk: (rel) => pathIsProjectFile(projectRoot, rel),
3820
+ symbolFiles: (symbol) => filesDefiningSymbol(cg, symbol),
3821
+ });
3117
3822
  if (extraction.pinnedFiles.length > 0 || extraction.unresolvedPathSpans.length > 0) {
3118
3823
  pinnedFiles = extraction.pinnedFiles;
3119
3824
  unresolvedPathSpans = extraction.unresolvedPathSpans;
3825
+ lineAnchors = extraction.lineAnchors;
3826
+ setAsideMatches = extraction.setAsideMatches;
3120
3827
  matchQuery = normalizeQuerySpelling(extraction.strippedQuery);
3121
3828
  }
3122
3829
  }
3123
3830
  catch { /* path pinning must never fail an explore call */ }
3124
3831
  }
3832
+ // A same-named file the span did not pin is named in the summary line, so
3833
+ // an agent that did mean it sees where it went instead of a silent drop.
3834
+ const setAsideNote = setAsideMatches.map((s) => {
3835
+ const which = s.files.length <= 2
3836
+ ? s.files.map((f) => `\`${f}\``).join(', ')
3837
+ : `${s.files.length} other \`${s.span}\` files`;
3838
+ return ` Not pinned: ${which}, which define${s.files.length === 1 ? 's' : ''} none of the named symbols.`;
3839
+ }).join('');
3125
3840
  const pinnedSet = new Set(pinnedFiles);
3126
3841
  const pinnedOrder = new Map(pinnedFiles.map((p, i) => [p, i]));
3127
3842
  // Per-file allocation diagnostic (CG-4). `null` unless CODEGRAPH_EXPLORE_DEBUG
@@ -3196,17 +3911,87 @@ class ToolHandler {
3196
3911
  .forEach((n) => { if (!subgraph.nodes.has(n.id))
3197
3912
  subgraph.nodes.set(n.id, n); });
3198
3913
  }
3914
+ // EXACT targets: callables the agent pointed at with no ambiguity left — a
3915
+ // qualified name that resolves to at most a handful of defs
3916
+ // (`SQLCompiler.as_sql`, filled in by the seeding loop below) or the
3917
+ // callable enclosing a line anchor (`compiler.py:776`). Every render path
3918
+ // puts these first and never reduces one to a signature line: the agent
3919
+ // has already said which of the 110 `as_sql`s it means, and an answer that
3920
+ // spends the file on the named method's neighbours instead is the one it
3921
+ // Reads the file to get past.
3922
+ const exactNodeIds = new Set();
3923
+ // A multi-line anchor (`lines 900-1003`, `foo.ts:12-40`) names a SPAN, not
3924
+ // a symbol — often the tail of a body a previous response windowed — and
3925
+ // is rendered as exactly that span. A single-line anchor with no enclosing
3926
+ // callable (a module-level line) becomes a small span around the line.
3927
+ const anchorSpans = new Map();
3928
+ for (const anchor of lineAnchors) {
3929
+ let fileNodes = [];
3930
+ try {
3931
+ fileNodes = cg.getNodesInFile(anchor.file);
3932
+ }
3933
+ catch {
3934
+ continue;
3935
+ }
3936
+ if (anchor.start === anchor.end) {
3937
+ const enclosing = fileNodes
3938
+ .filter((n) => ANCHOR_CALLABLE_KINDS.has(n.kind)
3939
+ && n.startLine <= anchor.start && n.endLine >= anchor.start)
3940
+ .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0];
3941
+ if (enclosing) {
3942
+ exactNodeIds.add(enclosing.id);
3943
+ if (!subgraph.nodes.has(enclosing.id))
3944
+ subgraph.nodes.set(enclosing.id, enclosing);
3945
+ continue;
3946
+ }
3947
+ }
3948
+ const span = anchor.start === anchor.end
3949
+ ? { start: Math.max(1, anchor.start - ANCHOR_LINE_CONTEXT), end: anchor.start + ANCHOR_LINE_CONTEXT }
3950
+ : { start: anchor.start, end: anchor.end };
3951
+ const spans = anchorSpans.get(anchor.file) ?? [];
3952
+ spans.push(span);
3953
+ anchorSpans.set(anchor.file, spans);
3954
+ }
3199
3955
  if (subgraph.nodes.size === 0) {
3200
3956
  diag?.finishEmpty('no relevant code found — empty subgraph');
3201
3957
  const missNote = unresolvedPathSpans.length > 0
3202
3958
  ? ` (no indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')})`
3203
3959
  : '';
3204
- const empty = `No relevant code found for "${query}"${missNote}`;
3960
+ let explanation = '\n\nExplore matches symbol/file names and indexed code words lexically, not by meaning.';
3961
+ if (indexedNodeCount === 0) {
3962
+ explanation += '\nThis project has nothing indexed.';
3963
+ }
3964
+ else {
3965
+ const miss = cg.getExploreMissDiagnostics(matchQuery);
3966
+ const list = (words) => words.map(w => `\`${w}\``).join(', ');
3967
+ // Separate caps preserve the retry instruction and complete candidate
3968
+ // names even with long queries or generated identifiers.
3969
+ const cappedList = (words, cap) => {
3970
+ const kept = [];
3971
+ for (const word of words) {
3972
+ if (list([...kept, word]).length > cap)
3973
+ break;
3974
+ kept.push(word);
3975
+ }
3976
+ return list(kept) + (kept.length < words.length ? ' …' : '');
3977
+ };
3978
+ explanation += '\nChecked indexed names, signatures, docstrings (FTS prefixes) and live name segments; not all source text.';
3979
+ if (miss.limited)
3980
+ explanation += '\nWord check limited to 16 words of at most 64 characters.';
3981
+ explanation += `\nNo lexical matches for checked words: ${cappedList(miss.unmatched, 250) || '(none)'}.`;
3982
+ if (miss.matched.length > 0) {
3983
+ explanation += `\nMatched indexed words: ${cappedList(miss.matched, 200)}; these did not yield a relevant result after filtering/scoring.`;
3984
+ }
3985
+ explanation += miss.candidates.length > 0
3986
+ ? `\nCandidates to retry with codegraph_explore (shared words, not confirmed answers): ${cappedList(miss.candidates, 350)}`
3987
+ : '\nNo shared-word symbol candidates found; retry codegraph_explore with literal symbol/file names or code terms.';
3988
+ }
3989
+ const empty = `No relevant code found for "${query}"${missNote}${explanation}`;
3205
3990
  // Still an explore call, so it is still recorded: an empty answer spends a
3206
3991
  // call against the tier budget even though it emits no source.
3207
- return this.exploreResult(empty, {
3208
- projectRoot, query, files: [], sourceBytes: 0, responseBytes: empty.length,
3209
- });
3992
+ return { ...this.textResult(empty), [explore_session_state_1.EXPLORE_EMISSION_KEY]: {
3993
+ projectRoot, query, files: [], sourceBytes: 0, responseBytes: empty.length,
3994
+ } };
3210
3995
  }
3211
3996
  // Graph-aware glue: findRelevantContext builds the subgraph from name/text
3212
3997
  // search, so a method that BRIDGES named symbols — e.g. App.tsx's
@@ -3254,6 +4039,35 @@ class ToolHandler {
3254
4039
  // substantive definition (skip empty stubs + test files, same relevance the
3255
4040
  // trace endpoint picker uses) and inject it as an entry, so every symbol the
3256
4041
  // agent explicitly named is in the subgraph and its file is scored.
4042
+ /**
4043
+ * Is this a member an INTERFACE declares — a signature with no body (#1638)?
4044
+ *
4045
+ * It arrives as an ordinary `method` node, so without asking, every ranking
4046
+ * stage reads a `.d.ts` full of `method_signature`s as a file full of
4047
+ * callables. Two stages below ask, for the same reason: a signature is the
4048
+ * declaration of behaviour, never behaviour, and the rank a file earns must
4049
+ * not grow just because its interfaces spell their members out.
4050
+ *
4051
+ * Cached; reached only for `method` nodes on paths that already probe the
4052
+ * graph per node, so it adds a key lookup, not a pass.
4053
+ */
4054
+ const interfaceMemberCache = new Map();
4055
+ const isInterfaceOwnedMethod = (node) => {
4056
+ if (node.kind !== 'method')
4057
+ return false;
4058
+ const cached = interfaceMemberCache.get(node.id);
4059
+ if (cached !== undefined)
4060
+ return cached;
4061
+ let owned = false;
4062
+ try {
4063
+ owned = cg.getIncomingEdges(node.id).some((e) => e.kind === 'contains' && cg.getNode(e.source)?.kind === 'interface');
4064
+ }
4065
+ catch {
4066
+ owned = false; // a probe failure must not manufacture a penalty
4067
+ }
4068
+ interfaceMemberCache.set(node.id, owned);
4069
+ return owned;
4070
+ };
3257
4071
  const namedSeedIds = new Set();
3258
4072
  // The subset of named seeds that earns the named-FIRST sort tier. We still
3259
4073
  // SEED every ≤3-def name (so RWR / flow ranking is unchanged), but only the
@@ -3319,8 +4133,18 @@ class ToolHandler {
3319
4133
  if (!names) {
3320
4134
  names = new Set();
3321
4135
  try {
3322
- for (const n of cg.getNodesInFile(fp))
3323
- names.add(n.name.toLowerCase());
4136
+ // An interface's members (#1638) describe a shape; nobody names
4137
+ // them in a question. Counting them let `readonly host: string` in
4138
+ // an options interface corroborate the English word "main" into
4139
+ // seeding the same file's `main()`, which then took the named-first
4140
+ // tier from the answer files (vscode "extension host … main process").
4141
+ const fileNodes = cg.getNodesInFile(fp);
4142
+ const interfaces = fileNodes.filter((n) => n.kind === 'interface');
4143
+ const declaresShape = (n) => (n.kind === 'property' || n.kind === 'method') &&
4144
+ interfaces.some((i) => n.startLine >= i.startLine && n.endLine <= i.endLine);
4145
+ for (const n of fileNodes)
4146
+ if (!declaresShape(n))
4147
+ names.add(n.name.toLowerCase());
3324
4148
  }
3325
4149
  catch { /* unreadable file entry — treat as uncorroborated */ }
3326
4150
  fileNameSets.set(fp, names);
@@ -3429,9 +4253,29 @@ class ToolHandler {
3429
4253
  // named-file sort below. (Previously only NEW injections were marked,
3430
4254
  // so a named symbol FTS already gathered never sorted to the top.)
3431
4255
  namedSeedIds.add(n.id);
4256
+ // A QUALIFIED name that resolved to a handful of defs is the agent
4257
+ // choosing one overload out of a family — `SQLCompiler.as_sql`, not
4258
+ // the 109 other `as_sql`s. The bare name keeps the family rules; the
4259
+ // qualified one is an exact target (see `exactNodeIds`).
4260
+ if (isQual && cands.length <= 3 && CALLABLE.has(n.kind))
4261
+ exactNodeIds.add(n.id);
4262
+ }
4263
+ // An interface's `method_signature` seeds (so RWR and the flow ranking
4264
+ // still see it, and a query that names it still reaches its file) but
4265
+ // never earns the named-FIRST tier (#1638). That tier means "the agent
4266
+ // asked for the symbol DEFINED here", and this seeding says as much —
4267
+ // it resolves a token to its substantive definition and sorts bodies
4268
+ // first. A declaration is the stub that sort demotes, not the answer.
4269
+ // Without this the tier is reachable by prose: `body`, `stream` and
4270
+ // `metadata` are member names in any platform `.d.ts`, and each one
4271
+ // corroborates the next through `coNamedInFile`, so an ambient shim
4272
+ // walks past the NL-stopword guard and lands above every implementation
4273
+ // file — the exact inversion CG-28 exists to prevent, arriving on a key
4274
+ // that sorts above the CG-28 penalty.
4275
+ for (const n of tierPicks) {
4276
+ if (!isInterfaceOwnedMethod(n))
4277
+ tierSeedIds.add(n.id);
3432
4278
  }
3433
- for (const n of tierPicks)
3434
- tierSeedIds.add(n.id);
3435
4279
  }
3436
4280
  }
3437
4281
  // Step 2: Group nodes by file, score by relevance
@@ -3484,9 +4328,21 @@ class ToolHandler {
3484
4328
  isolationCache.set(node.id, isolated);
3485
4329
  return isolated;
3486
4330
  };
4331
+ /**
4332
+ * A `method_signature` reaches here as a `method`, which the kind table
4333
+ * rates 1.0: "a callable — the unit an architecture question is about". It
4334
+ * is not that. It is the row below on the same scale, "a member of a type",
4335
+ * and rating it as a callable is how a 28-interface `.d.ts` doubled its
4336
+ * score the moment its members became indexable (#1638). Only `method`
4337
+ * needs correcting; `property` already sits in the member tier whoever
4338
+ * declares it.
4339
+ */
3487
4340
  const relevanceWeight = (node, probeIsolation) => {
3488
- const weight = exports.RELEVANCE_KIND_WEIGHT[node.kind] ?? DEFAULT_RELEVANCE_KIND_WEIGHT;
3489
- if (!probeIsolation || !WEAK_RELEVANCE_KINDS.has(node.kind))
4341
+ const signatureOnly = isInterfaceOwnedMethod(node);
4342
+ const weight = signatureOnly
4343
+ ? TYPE_MEMBER_RELEVANCE_WEIGHT
4344
+ : exports.RELEVANCE_KIND_WEIGHT[node.kind] ?? DEFAULT_RELEVANCE_KIND_WEIGHT;
4345
+ if (!probeIsolation || !(signatureOnly || WEAK_RELEVANCE_KINDS.has(node.kind)))
3490
4346
  return weight;
3491
4347
  return isUsageIsolated(node) ? ISOLATED_WEAK_KIND_WEIGHT : weight;
3492
4348
  };
@@ -3706,7 +4562,33 @@ class ToolHandler {
3706
4562
  // (org-user.storage.ts, call-connected to the matches) accrues mass; a lone
3707
4563
  // text match (LensSwitcher.swift, matched "switch" but calls nothing in the
3708
4564
  // flow) gets only its restart probability → ~0, and is dropped by the gate.
3709
- const nodeRwr = this.computeGraphRelevance([...subgraph.nodes.keys()], subgraph.edges, entryNodeIds);
4565
+ //
4566
+ // A file the ambient-declaration penalty has already damped is a candidate,
4567
+ // but not a place a walk STARTS. The restart vector is uniform over seeds,
4568
+ // so every seed divides the restart mass the implementation files compete
4569
+ // for — and since #1638 a platform `.d.ts` contributes one seed per member,
4570
+ // whose names (`body`, `stream`, `metadata`) are exactly what a prose flow
4571
+ // query matches. That is what halves an implementation file's graph mass
4572
+ // while the shim's holds steady: dilution of the restart vector, not
4573
+ // connectivity. `contains` is not a RANK_EDGE, so these members carry almost
4574
+ // no walk mass of their own; seeding is the whole of their effect on rank.
4575
+ //
4576
+ // `isDampedDeclaration` and not a bare ambient test: it already exempts a
4577
+ // file whose declared type the query NAMED, so a query genuinely about the
4578
+ // declared type keeps its seeds and the shim still ranks first. Damped files
4579
+ // stay in the candidate set, stay reachable, and keep their `score`
4580
+ // contribution — this changes only where the walk starts.
4581
+ const rwrSeedIds = new Set();
4582
+ for (const id of entryNodeIds) {
4583
+ const seed = subgraph.nodes.get(id);
4584
+ if (seed && isDampedDeclaration(seed.filePath))
4585
+ continue;
4586
+ rwrSeedIds.add(id);
4587
+ }
4588
+ const nodeRwr = this.computeGraphRelevance(
4589
+ // Fall back to the unfiltered seeds when EVERY seed is damped: the walk
4590
+ // must not lose its restart vector and return all-uniform.
4591
+ [...subgraph.nodes.keys()], subgraph.edges, rwrSeedIds.size > 0 ? rwrSeedIds : entryNodeIds);
3710
4592
  //
3711
4593
  // Carries `rankPenalty` too, so generated/low-value files are demoted on the
3712
4594
  // sort's PRIMARY key rather than only at the tiebreak. Everything downstream
@@ -3907,7 +4789,7 @@ class ToolHandler {
3907
4789
  // Blast radius (always-on, compact): for the entry symbols, who depends on
3908
4790
  // them + which tests cover them — locations only, no source — so the agent
3909
4791
  // knows what to update/verify before editing without a separate call.
3910
- const blastRadius = this.buildBlastRadiusSection(cg, subgraph);
4792
+ const blastRadius = this.buildBlastRadiusSection(cg, subgraph, exactNodeIds);
3911
4793
  if (blastRadius)
3912
4794
  lines.push(blastRadius);
3913
4795
  // Relationship map — show how symbols connect
@@ -3944,7 +4826,41 @@ class ToolHandler {
3944
4826
  // Compute the flow spine once — used both to prepend the Flow section (below)
3945
4827
  // and to gate adaptive source sizing: files on the spine get full source,
3946
4828
  // off-spine peers skeletonize.
4829
+ // The Flow section labels each hop with its branch conditions; that read
4830
+ // is synchronous, so the grammars it needs are loaded here, once.
4831
+ await (0, branch_guards_1.warmBranchGuardGrammars)();
3947
4832
  const flow = this.buildFlowFromNamedSymbols(cg, matchQuery);
4833
+ // The symbols the question is about: exact targets, the named ones, the spine.
4834
+ const questionIds = new Set([...exactNodeIds, ...flow.pathNodeIds, ...flow.namedNodeIds]);
4835
+ /**
4836
+ * The lines a WINDOW of an oversize body must reach: an anchored line
4837
+ * inside it, the spine's next-hop call, and every call it makes into
4838
+ * another symbol the question is about — "the parts the question is
4839
+ * about", in the graph's own terms rather than by matching words. Most
4840
+ * important first, capped so a window stays a window.
4841
+ */
4842
+ const bodyFocusLines = (n) => {
4843
+ const focus = [];
4844
+ for (const a of lineAnchors) {
4845
+ if (a.file === n.filePath && a.start > n.startLine && a.start <= n.endLine)
4846
+ focus.push(a.start);
4847
+ }
4848
+ const call = flow.spineCallSites.get(n.id);
4849
+ if (call)
4850
+ focus.push(call);
4851
+ const calls = [];
4852
+ try {
4853
+ for (const e of cg.getOutgoingEdges(n.id)) {
4854
+ if (e.target === n.id || !questionIds.has(e.target) || !e.line)
4855
+ continue;
4856
+ if (e.line > n.startLine && e.line <= n.endLine)
4857
+ calls.push(e.line);
4858
+ }
4859
+ }
4860
+ catch { /* focus is a nicety; the head window still renders */ }
4861
+ focus.push(...calls.sort((a, b) => a - b));
4862
+ return [...new Set(focus)].slice(0, MAX_BODY_FOCUS_LINES);
4863
+ };
3948
4864
  // Snapshot every ranked candidate's scoring inputs, in final sort order, so
3949
4865
  // the diagnostic can show what each file's share of the envelope was BOUGHT
3950
4866
  // with (score, graph mass, term hits, flags) — not just what it cost.
@@ -3987,8 +4903,13 @@ class ToolHandler {
3987
4903
  // A pinned file's bytes are worth full price by definition — the agent
3988
4904
  // asked for the file itself, generated/test or not.
3989
4905
  worth: pinnedSet.has(fp) ? 1 : rankPenalty(fp),
3990
- spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id)),
4906
+ // A file holding an EXACT target is funded like a spine file: it is the
4907
+ // answer to the question as asked, and clipping it is what sends the
4908
+ // agent to Read — the exact reason the spine gets this treatment.
4909
+ spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id) || exactNodeIds.has(n.id))
4910
+ || anchorSpans.has(fp),
3991
4911
  pinned: pinnedSet.has(fp),
4912
+ named: namedSeedFiles.has(fp),
3992
4913
  })), budget, maxFiles);
3993
4914
  diag?.setAllocation(allocation.allowances, allocation.cliffed, allocation.cliffAt, allocation.pool);
3994
4915
  // Cliffed files ship as pointers — path, symbols, line numbers — so the agent
@@ -4083,7 +5004,22 @@ class ToolHandler {
4083
5004
  const g = fileGroups.get(fp);
4084
5005
  return g ? n + pointerLineFor(fp, g.nodes).length + 1 : n;
4085
5006
  }, cliffedFiles.size > 0 ? POINTER_HEADER.length + 2 : 0);
4086
- const epilogueFloor = EPILOGUE_LOST_NOTE.length + 2 + cliffPointerFloor;
5007
+ // The summary line ("Found N symbols across M files. …") is written only
5008
+ // after the final cut, and sits in `lines` as an empty placeholder until
5009
+ // then — so the loop never paid for it, and a response filled to the
5010
+ // ceiling ended up past it by the line's length once it was filled in: five
5011
+ // of 47 measured responses over the 25K inline cap (up to 25,032), or the
5012
+ // lost-pointer note above squeezed out.
5013
+ // Reserved at its worst case: the gather's symbol and file counts bound the
5014
+ // shown ones from above.
5015
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
5016
+ const summaryReserve = `Found ${plural(subgraph.nodes.size, 'symbol')} across ${plural(fileGroups.size, 'file')}.`.length
5017
+ + (pinnedFiles.length > 0 ? ` ${plural(pinnedFiles.length, 'file')} pinned from the query.`.length : 0)
5018
+ + (unresolvedPathSpans.length > 0
5019
+ ? ` No indexed file uniquely matches ${unresolvedPathSpans.map((sp) => `\`${sp}\``).join(', ')}.`.length
5020
+ : 0)
5021
+ + setAsideNote.length;
5022
+ const epilogueFloor = Math.max(exports.EXPLORE_FALLBACK_NOTES.lost.complete.length, exports.EXPLORE_FALLBACK_NOTES.lost.trimmed.length) + 2 + cliffPointerFloor + summaryReserve;
4087
5023
  // Absolute stop for the render loop. Reservations already fit the envelope, so
4088
5024
  // this only catches their bounded overshoot (the whole-file grace, an oversize
4089
5025
  // first cluster) — and catches it HERE, where a file can be skipped cleanly and
@@ -4104,6 +5040,11 @@ class ToolHandler {
4104
5040
  // (#1046) — it must reflect what we show, not the raw candidate gather.
4105
5041
  const renderedFilePaths = [];
4106
5042
  let anyFileTrimmed = false;
5043
+ // Rendered files whose section is missing some of what it set out to
5044
+ // deliver, by path — measured at emission from the ranges actually sent
5045
+ // (`elidedWantedSpans`), not from the trim sites. Drives the completeness
5046
+ // note: "complete" is claimed only for sections that are.
5047
+ const trimmedFiles = new Map();
4107
5048
  // Files that changed on disk after their last index sync (#1474). Their
4108
5049
  // indexed line ranges are untrustworthy, so sliced renders (adaptive /
4109
5050
  // skeleton / clusters) are OFF for them: a small drifted file still ships
@@ -4127,16 +5068,40 @@ class ToolHandler {
4127
5068
  // `sourceSpent` outrun `reservedSoFar`, which suppresses slack until a later
4128
5069
  // under-spend covers the debt. So the pool is conserved in both directions,
4129
5070
  // and no file is ever cut BELOW the reservation it was promised.
5071
+ //
5072
+ // Both totals count what a file is GUARANTEED (below), which is its whole
5073
+ // reservation for every file but a named one. A named file's share above
5074
+ // the `MAX_SHARE` valve is spare-room money, not a promise: it is entered
5075
+ // only once the loop has moved past the file, and only as far as the file
5076
+ // actually spent it (`unsettledSoft`). Booked in full up front, whatever the
5077
+ // file could not spend would flow down as slack that exists only in the
5078
+ // ledger, and count against the buy rule's funding line as a debt nobody
5079
+ // owes.
4130
5080
  let reservedSoFar = 0;
4131
5081
  let sourceSpent = 0;
5082
+ let unsettledSoft = 0;
5083
+ const valveCap = Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.MAX_SHARE);
5084
+ const isNamedFile = (path) => isNamedCandidate({ named: namedSeedFiles.has(path), pinned: pinnedSet.has(path) });
5085
+ /**
5086
+ * What the render loop GUARANTEES a file, whatever that costs the files
5087
+ * below it: its reservation, except a named file's share above the
5088
+ * `MAX_SHARE` valve. The allocator lifts the valve for a named file to hand
5089
+ * it budget no other file would spend, not to take room a lower file is
5090
+ * owed — so that part is funded only from spare room, and is never held back
5091
+ * for it either. Guaranteeing the whole reservation dropped two admitted
5092
+ * files from a saturated django response so the named `query.py` could ship
5093
+ * 3K more of itself.
5094
+ */
5095
+ const guaranteedOf = (path, reserved) => (isNamedFile(path) ? Math.min(reserved, valveCap) : reserved);
4132
5096
  // Funding line for the whole-file BUY rule: the response's SOURCE may reach
4133
5097
  // everything the allocator promised plus one bounded overshoot, and no more.
4134
5098
  // Measured against the promise rather than `renderCeiling` on purpose — the
4135
5099
  // ceiling sits 50% above the envelope and says nothing about who is owed
4136
5100
  // what, so funding a buy from it just moves the shortfall to whichever file
4137
- // the loop reaches last. See WHOLE_FILE_BUY_OVERSHOOT_FRACTION.
4138
- const reservedTotal = [...allocation.allowances.values()].reduce((sum, n) => sum + n, 0);
4139
- const sourceCeiling = reservedTotal + Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.WHOLE_FILE_BUY_OVERSHOOT_FRACTION);
5101
+ // the loop reaches last. See WHOLE_FILE_BUY_OVERSHOOT_FRACTION. The promise
5102
+ // grows as a named file's soft share is settled (see `unsettledSoft`).
5103
+ let reservedTotal = [...allocation.allowances].reduce((sum, [path, n]) => sum + guaranteedOf(path, n), 0);
5104
+ const buyOvershoot = Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.WHOLE_FILE_BUY_OVERSHOOT_FRACTION);
4140
5105
  /**
4141
5106
  * What a file's section costs BESIDES its source, in render space: the
4142
5107
  * header (path + up to `maxSymbolsInFileHeader` symbol names) plus the code
@@ -4182,13 +5147,31 @@ class ToolHandler {
4182
5147
  * whole reservation, and when they do not, the carry-forward hands the
4183
5148
  * difference to whoever comes next anyway.
4184
5149
  */
5150
+ /**
5151
+ * Everything still owed below `fileIndex`, in render-space chars, whether the
5152
+ * ceiling can pay it or not — the bar a named file's extension has to clear
5153
+ * (see the render loop). What is left above it is room no admitted file will
5154
+ * ever claim.
5155
+ */
5156
+ const owedInFullBelow = (fileIndex) => {
5157
+ let owed = 0;
5158
+ for (let j = fileIndex + 1; j < sortedFiles.length; j++) {
5159
+ const [path, g] = sortedFiles[j];
5160
+ const r = allocation.allowances.get(path);
5161
+ if (r !== undefined)
5162
+ owed += guaranteedOf(path, r) + sectionOverhead(path, g.nodes);
5163
+ }
5164
+ return owed;
5165
+ };
4185
5166
  const owedPayableBelow = (fileIndex, budgetLeft) => {
4186
5167
  let held = 0;
4187
5168
  for (let j = fileIndex + 1; j < sortedFiles.length; j++) {
4188
5169
  const path = sortedFiles[j][0];
4189
- const r = allocation.allowances.get(path);
4190
- if (r === undefined)
5170
+ const reservedBelow = allocation.allowances.get(path);
5171
+ if (reservedBelow === undefined)
4191
5172
  continue;
5173
+ // Only what that file is guaranteed is owed to it (see `guaranteedOf`).
5174
+ const r = guaranteedOf(path, reservedBelow);
4192
5175
  const overhead = sectionOverhead(path, sortedFiles[j][1].nodes);
4193
5176
  const need = r + overhead;
4194
5177
  if (held + need > budgetLeft) {
@@ -4210,6 +5193,16 @@ class ToolHandler {
4210
5193
  return held;
4211
5194
  };
4212
5195
  for (let fileIndex = 0; fileIndex < sortedFiles.length; fileIndex++) {
5196
+ // Settle the soft share of the file the loop just left: what it spent past
5197
+ // its guarantee becomes a promise it kept; the rest was never available.
5198
+ // Here rather than after its render, because every exit path below —
5199
+ // however it `continue`s — comes back through this line.
5200
+ if (unsettledSoft > 0) {
5201
+ const settled = Math.min(unsettledSoft, Math.max(0, sourceSpent - reservedSoFar));
5202
+ reservedSoFar += settled;
5203
+ reservedTotal += settled;
5204
+ unsettledSoft = 0;
5205
+ }
4213
5206
  const [filePath, group] = sortedFiles[fileIndex];
4214
5207
  if (filesIncluded >= maxFiles) {
4215
5208
  if (diag)
@@ -4240,10 +5233,14 @@ class ToolHandler {
4240
5233
  // order because that is the only file a single-pass loop can still pay;
4241
5234
  // `MAX_SHARE` keeps that from turning a weak tail file into the response,
4242
5235
  // so the allocator's share ceiling holds end-to-end and not just at
4243
- // reservation time.
4244
- const allowance = Math.min(reserved + Math.max(0, reservedSoFar - sourceSpent), Math.max(reserved, Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.MAX_SHARE)));
4245
- reservedSoFar += reserved;
4246
- diag?.recordSpendable(filePath, allowance);
5236
+ // reservation time. (A named file may go past it — but only into spare
5237
+ // room; see below the displacement guard.)
5238
+ const slack = Math.max(0, reservedSoFar - sourceSpent);
5239
+ const guaranteed = guaranteedOf(filePath, reserved);
5240
+ const ruleAllowance = Math.min(guaranteed + slack, Math.max(guaranteed, valveCap));
5241
+ let allowance = ruleAllowance;
5242
+ reservedSoFar += guaranteed;
5243
+ unsettledSoft = reserved - guaranteed;
4247
5244
  // DISPLACEMENT GUARD, in render space (CG-31). `allowance` says what this
4248
5245
  // file MAY spend; it does not say the bytes are still there to spend. The
4249
5246
  // hard ceiling is shared with every file the loop has not reached yet, and
@@ -4260,14 +5257,36 @@ class ToolHandler {
4260
5257
  //
4261
5258
  // Floored at this file's OWN reservation, never below: a kept promise is
4262
5259
  // not a displacement, and cutting a file under what it earned is the
4263
- // failure this whole allocation layer exists to prevent.
5260
+ // failure this whole allocation layer exists to prevent. (For a named
5261
+ // file, the part of the reservation it is `guaranteed` — see above.)
4264
5262
  //
4265
5263
  // Slack still reaches the file: a file above that under-spends leaves
4266
5264
  // `totalChars` lower, which raises `headroom` one-for-one, so the
4267
5265
  // carry-forward the `allowance` line grants is exactly the carry-forward
4268
5266
  // this bound funds.
4269
5267
  const headroom = Math.max(0, renderCeiling - totalChars - sectionOverhead(filePath, group.nodes));
4270
- const fundedHeadroom = Math.max(Math.min(reserved, headroom), headroom - owedPayableBelow(fileIndex, Math.max(0, headroom - reserved)));
5268
+ const fundedHeadroom = Math.max(Math.min(guaranteed, headroom), headroom - owedPayableBelow(fileIndex, Math.max(0, headroom - guaranteed)));
5269
+ // A file the query NAMED may spend past the rule above — its share over the
5270
+ // `MAX_SHARE` valve, and slack past the valve — but only into SPARE room:
5271
+ // the call's BUDGET left once every file below is paid its full
5272
+ // reservation, payable or not. Two bars that look right and are not:
5273
+ // - `fundedHeadroom` holds back only the payable prefix of what is owed
5274
+ // below (CG-31), so on a saturated response the room it releases still
5275
+ // belongs to a partially-payable file: reaching it cost vscode an
5276
+ // admitted rank-4 file its whole section.
5277
+ // - the render CEILING sits above the budget to absorb the render's own
5278
+ // bounded overshoot (named gap markers, never-empty windows). Spend up
5279
+ // to it and that overshoot lands on the files below: django's named
5280
+ // `query.py` ran 561 chars past its bound and cut a lower file to 53%
5281
+ // of its reservation.
5282
+ // Where nothing is spare the extension is zero and the file renders
5283
+ // exactly as it did before the valve was lifted for it.
5284
+ if (isNamedFile(filePath)) {
5285
+ const spare = budget.maxOutputChars - totalChars - sectionOverhead(filePath, group.nodes)
5286
+ - owedInFullBelow(fileIndex);
5287
+ allowance = Math.max(allowance, Math.min(reserved + slack, spare));
5288
+ }
5289
+ diag?.recordSpendable(filePath, allowance);
4271
5290
  diag?.recordFunded(filePath, fundedHeadroom);
4272
5291
  const absPath = (0, utils_1.validatePathWithinRoot)(projectRoot, filePath);
4273
5292
  if (!absPath || !(0, fs_1.existsSync)(absPath)) {
@@ -4289,6 +5308,10 @@ class ToolHandler {
4289
5308
  // (no `//` — not a comment in Python, Ruby, etc.). With line numbers on,
4290
5309
  // the line-number jump also signals the gap.
4291
5310
  const GAP_MARKER = '\n\n... (gap) ...\n\n';
5311
+ // Full file index — not just the relevance-gathered `group.nodes`. A trim
5312
+ // often drops filler symbols that never scored into the gather set; naming
5313
+ // those holes still needs their defs (#1711).
5314
+ const fileIndexNodes = cg.getNodesInFile(filePath);
4292
5315
  // Cross-call dedup (CG-18). `served` is what THIS session already sent the
4293
5316
  // agent for THIS file, and it is empty unless the file still hashes to the
4294
5317
  // bytes those spans were sliced from — an edit between calls means the
@@ -4348,6 +5371,11 @@ class ToolHandler {
4348
5371
  const folded = opts.covered.length > 0 && opts.body.length < explore_dedup_1.EXPLORE_DEDUP.MIN_DELTA_CHARS;
4349
5372
  const body = folded ? '' : opts.body;
4350
5373
  const ranges = folded ? [] : opts.ranges;
5374
+ // Judged on what this call sends plus what the agent already holds —
5375
+ // AFTER the fold, whose remainder is in neither.
5376
+ const elided = elidedWantedSpans(opts.wanted, [...ranges, ...opts.covered]);
5377
+ if (elided.length > 0)
5378
+ trimmedFiles.set(filePath, elided);
4351
5379
  const at = lines.length;
4352
5380
  lines.push(opts.header, '');
4353
5381
  // Charge what the section ACTUALLY costs, not a flat 200 (CG-26). A
@@ -4404,111 +5432,373 @@ class ToolHandler {
4404
5432
  };
4405
5433
  }
4406
5434
  };
4407
- // Disk-drift gate (#1474): every render branch below except whole-file
4408
- // slices fileContent (CURRENT bytes) at INDEXED line ranges. Content is
4409
- // already in hand, so the check costs one stat (hash only on mismatch).
4410
- const fileStale = this.isFileStaleOnDisk(cg, filePath, fileContent);
4411
- // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
4412
- // to a per-symbol view when it's a redundant member of a polymorphic family.
4413
- // Engages iff ALL hold:
4414
- // 1. a flow spine exists,
4415
- // 2. no symbol in the file is on that spine (it's not the mechanism path),
4416
- // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
4417
- // 4. it is NOT SPARED, where a file is spared iff the agent named a
4418
- // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
4419
- // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
4420
- // base+subclasses "family" file like Django's compiler.py — collapse it).
4421
- // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
4422
- // subclass; naming it must NOT keep every backend variant + test file full
4423
- // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
4424
- // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
4425
- // agent NAMED or that's on the spine is shown with its FULL body (so the agent
4426
- // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
4427
- // every other symbol is just its signature. So the base mechanism survives while
4428
- // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
4429
- const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
4430
- const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
4431
- const spared = spareNamed && !fileDefinesSuper;
4432
- const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
4433
- const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
4434
- // On-spine god-file: the flow path runs THROUGH this file, but it also holds
4435
- // many OTHER named methods, and rendering all of them in full blows the
4436
- // per-file budget and starves the other flow files (Alamofire: the agent
4437
- // names ~7 Session.swift methods — the build spine PLUS off-path
4438
- // task/didCompleteTask — far past the whole response budget). Engage the
4439
- // per-symbol view to keep the SPINE full and collapse the off-path named
4440
- // methods to signatures. Only when there IS off-path content to shed —
4441
- // otherwise the spine is irreducible (a sequential flow has no redundancy),
4442
- // so leave it to the normal full render.
4443
- const namedBodyChars = group.nodes
4444
- .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
4445
- .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
4446
- const onSpineGodFile = hasSpineNode
4447
- && namedBodyChars > allowance
4448
- && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
4449
- if (!fileStale && adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
4450
- && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
4451
- const syms = group.nodes
4452
- .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
4453
- .sort((a, b) => a.startLine - b.startLine);
4454
- // Pass 1: choose which symbols get a FULL body, by priority, greedily within
4455
- // a per-file body cap — so one huge family file can't body every named method
4456
- // and crowd out the other flow files (Django's query.py). A symbol earns a
4457
- // body if it's on-spine, or UNIQUELY named (`SQLCompiler.execute_sql`), or a
4458
- // co-named method WHEN this file DEFINES the family supertype (so the base
4459
- // `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides — and
4460
- // OkHttp's 5 `intercept`s if the agent names `intercept` — stay signatures).
4461
- const prio = (n) => !CALLABLE_BODY.has(n.kind) ? 99
4462
- : flow.pathNodeIds.has(n.id) ? 0
4463
- : flow.uniqueNamedNodeIds.has(n.id) ? 1
4464
- : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 2 : 99;
4465
- // One WINDOW per file, sized by this file's RESERVATION. syms are taken by
4466
- // priority (spine first, then uniquely-named, then family-base), and the cap
4467
- // applies to ALL of them — including the spine — so a big-spine god-file
4468
- // (tokio's worker.rs: run→run_task→next_task→steal_work) can't eat the whole
4469
- // response and starve the co-flow file (harness.rs's poll). The native agent
4470
- // windows such a file too (~190 lines at a time), so this mimics, not
4471
- // truncates. Always emit ≥1 (never an empty section).
4472
- //
4473
- // Held to `fundedHeadroom` as well (CG-31) so this path cannot spend a
4474
- // reservation still owed below it either. It never exceeds `allowance`
4475
- // today, so the bound only bites once the ceiling is genuinely tight —
4476
- // but "every render path" has to mean every one, or the guard is just a
4477
- // detour the next god-file takes.
4478
- const bodyCap = Math.min(allowance, fundedHeadroom);
4479
- const bodyIds = new Set();
4480
- let bodyChars = 0;
4481
- for (const n of syms.filter(n => prio(n) < 99 && n.endLine >= n.startLine).sort((a, b) => prio(a) - prio(b))) {
4482
- const sz = fileLines.slice(n.startLine - 1, n.endLine).join('\n').length;
4483
- if (bodyChars + sz > bodyCap && bodyIds.size > 0)
4484
- continue;
4485
- bodyIds.add(n.id);
4486
- bodyChars += sz;
5435
+ // Window helpers — shared by the focused per-symbol view and the cluster
5436
+ // path below, so an oversize body is cut by ONE set of rules wherever it
5437
+ // renders. Parts are SPAN-KEYED: every part carries the exact line range
5438
+ // its text was sliced from (see `buildSection`).
5439
+ const SPINE_WINDOW = 28; // lines each side of a focus line (the next-hop call site)
5440
+ /**
5441
+ * Bounded overshoot for one cluster's render (CG-30).
5442
+ *
5443
+ * `shrinkCluster` keeps the highest-importance member whole even when that
5444
+ * member alone is oversize — an empty file section sends the agent to Read,
5445
+ * which is exactly what explore exists to prevent. But "never empty" is not
5446
+ * "any size": with nothing bounding it, one 22K member rendered against a
5447
+ * 9K reservation (2.4x), which collapses the headroom every file ranked
5448
+ * below it draws from. Past the ceiling the member is WINDOWED rather than
5449
+ * dropped — a leading window (signature + head of the body), plus a window
5450
+ * on the spine's call site when the head misses it, since on a flow cluster
5451
+ * the call path IS the answer.
5452
+ */
5453
+ const MIN_WINDOW_LINES = 12;
5454
+ /** Rendered cost of one source line, line numbering included. */
5455
+ const lineCost = (ln) => (fileLines[ln - 1] ?? '').length + 1 + (withLineNumbers ? String(ln).length + 1 : 0);
5456
+ /** `lineCostPrefix[n]` = rendered chars of lines 1..n, newlines included. */
5457
+ let lineCostPrefix = null;
5458
+ /** Rendered chars of lines `start..end` (line numbers included), in O(1). */
5459
+ const renderedSpanCost = (start, end) => {
5460
+ if (!lineCostPrefix) {
5461
+ lineCostPrefix = [0];
5462
+ for (let ln = 1; ln <= fileLines.length; ln++)
5463
+ lineCostPrefix.push(lineCostPrefix[ln - 1] + lineCost(ln));
4487
5464
  }
4488
- // Pass 2: render in line order — full body for chosen symbols, else the
4489
- // signature line (capped, with a "+N more" tail so the structure map of a
4490
- // god-file doesn't itself bloat the budget).
4491
- const skel = [];
4492
- let coveredUntil = 0; // skip symbols already inside an emitted body
4493
- let sigCount = 0, sigDropped = 0;
4494
- const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
4495
- for (const n of syms) {
4496
- if (n.startLine <= coveredUntil)
4497
- continue;
4498
- if (bodyIds.has(n.id)) {
4499
- const end = n.endLine;
4500
- const body = fileLines.slice(n.startLine - 1, end).join('\n');
4501
- skel.push({
4502
- range: { start: n.startLine, end },
4503
- text: withLineNumbers ? numberSourceLines(body, n.startLine) : body,
4504
- });
4505
- coveredUntil = end;
5465
+ const s = Math.max(1, start);
5466
+ const e = Math.min(fileLines.length, end);
5467
+ return e < s ? 0 : Math.max(0, lineCostPrefix[e] - lineCostPrefix[s - 1] - 1);
5468
+ };
5469
+ /**
5470
+ * Longest prefix of `r` that fits `room`. `minLines` is the never-empty
5471
+ * floor — it may overrun `room`, so it is only ever asked for when nothing
5472
+ * else has been emitted and the alternative is an empty section.
5473
+ */
5474
+ const headWindowOf = (r, room, minLines = 0) => {
5475
+ let end = r.start - 1;
5476
+ let chars = 0;
5477
+ for (let ln = r.start; ln <= r.end; ln++) {
5478
+ const cost = lineCost(ln);
5479
+ if (chars + cost > room && end - r.start + 1 >= minLines)
5480
+ break;
5481
+ chars += cost;
5482
+ end = ln;
5483
+ }
5484
+ return end >= r.start ? { start: r.start, end } : null;
5485
+ };
5486
+ /** Widest window around `line` inside [lo, hi] that fits `room`. */
5487
+ const centeredWindowOf = (line, lo, hi, room) => {
5488
+ if (line < lo || line > hi)
5489
+ return null;
5490
+ let start = line, end = line, chars = lineCost(line);
5491
+ for (let grown = true; grown;) {
5492
+ grown = false;
5493
+ if (end + 1 <= hi && chars + lineCost(end + 1) <= room) {
5494
+ end += 1;
5495
+ chars += lineCost(end);
5496
+ grown = true;
4506
5497
  }
4507
- else {
4508
- // Elide the body, emit the signature. node.startLine can point at a
4509
- // decorator/annotation, so scan forward for the line that names the symbol.
4510
- let lineNo = n.startLine;
4511
- for (let k = 0; k < 4; k++) {
5498
+ if (start - 1 >= lo && chars + lineCost(start - 1) <= room) {
5499
+ start -= 1;
5500
+ chars += lineCost(start);
5501
+ grown = true;
5502
+ }
5503
+ }
5504
+ return { start, end };
5505
+ };
5506
+ /**
5507
+ * Reduce rendered parts to fit `ceiling`, never to nothing. Whole parts are
5508
+ * kept while they fit; the first part that overruns is cut to a leading
5509
+ * window on whole lines (a body is never cut mid-line), and everything past
5510
+ * it is dropped. The GAP_MARKER between surviving parts — and the line-number
5511
+ * jump — is what tells the agent the cut happened.
5512
+ *
5513
+ * A partial window shorter than MIN_WINDOW_LINES is not worth emitting, and
5514
+ * emitting one is actively harmful: the session record then claims a 4-line
5515
+ * sliver, and the NEXT call's dedup has to either shred a whole block around
5516
+ * it or re-send it. Below that floor the part is simply dropped — unless
5517
+ * nothing has been emitted at all, where the floor wins over the ceiling
5518
+ * because an empty section is the one outcome worse than an oversize one.
5519
+ *
5520
+ * `focusLines` are the lines this trim must not lose: the spine's next-hop
5521
+ * call site (CG-30) and every definition the agent NAMED inside the cluster
5522
+ * (CG-38). The head fill is source-ordered, so a named def in the TAIL of a
5523
+ * large file is otherwise always the first thing an over-ceiling render
5524
+ * drops — the one span the agent asked for by name, cut in favour of
5525
+ * head-of-file filler it did not ask for. The full-ceiling fill is tried
5526
+ * FIRST and the 60% hold-back applies only when a focus line is actually
5527
+ * left uncovered, so a cluster whose head already reaches its focus keeps
5528
+ * the whole ceiling for source.
5529
+ */
5530
+ const windowToCeiling = (parts, ceiling, focusLines = []) => {
5531
+ const inParts = (line) => parts.some((p) => line >= p.range.start && line <= p.range.end);
5532
+ const focus = [...new Set(focusLines)]
5533
+ .filter((l) => typeof l === 'number' && l > 0 && inParts(l))
5534
+ .sort((a, b) => a - b);
5535
+ /** Source-ordered fill of whole parts, the overrunning one cut to a head window. */
5536
+ const fill = (room) => {
5537
+ const emit = [];
5538
+ let used = 0;
5539
+ for (const p of parts) {
5540
+ const join = emit.length > 0 ? GAP_MARKER.length : 0;
5541
+ if (used + join + p.text.length <= room) {
5542
+ emit.push(p.range);
5543
+ used += join + p.text.length;
5544
+ continue;
5545
+ }
5546
+ const first = emit.length === 0;
5547
+ const win = headWindowOf(p.range, Math.max(0, room - used - join), first ? MIN_WINDOW_LINES : 0);
5548
+ if (win && (first || win.end - win.start + 1 >= MIN_WINDOW_LINES)) {
5549
+ emit.push(win);
5550
+ used += join + renderSpan(win).length;
5551
+ }
5552
+ break;
5553
+ }
5554
+ return { emit, used };
5555
+ };
5556
+ let { emit, used } = fill(ceiling);
5557
+ const reached = () => (emit.length ? emit[emit.length - 1].end : 0);
5558
+ if (focus.some((l) => l > reached())) {
5559
+ // Hold room back for the focus windows so the head can't eat all of it.
5560
+ ({ emit, used } = fill(Math.floor(ceiling * 0.6)));
5561
+ }
5562
+ // What is left is SPLIT between the uncovered focus lines rather than
5563
+ // handed to them in order. Greedy-in-source-order reproduces the very bug
5564
+ // this guards: on a prose query resolving four focus lines, the two
5565
+ // earliest took the whole reserve and `flushQueuedMessages` at L1102 —
5566
+ // named in the question — was dropped again. A skipped or undersized
5567
+ // window returns its share to the pool for the ones after it.
5568
+ let covered = reached();
5569
+ let room = Math.max(0, ceiling - used);
5570
+ const pending = focus.filter((l) => l > covered);
5571
+ for (let i = 0; i < pending.length; i++) {
5572
+ const line = pending[i];
5573
+ if (line <= covered)
5574
+ continue; // an earlier window already reached it
5575
+ const share = Math.floor(room / (pending.length - i)) - GAP_MARKER.length;
5576
+ if (share <= 0)
5577
+ continue;
5578
+ const host = parts.find((p) => line >= p.range.start && line <= p.range.end);
5579
+ const lo = Math.max(host.range.start, line - SPINE_WINDOW, covered + 1);
5580
+ const hi = Math.min(host.range.end, line + SPINE_WINDOW);
5581
+ const win = centeredWindowOf(line, lo, hi, share);
5582
+ // Same sliver floor as the head window — a two-line peek at the call
5583
+ // site teaches the next call's dedup to shred the block around it.
5584
+ if (!win || win.end - win.start + 1 < MIN_WINDOW_LINES)
5585
+ continue;
5586
+ emit.push(win);
5587
+ const cost = GAP_MARKER.length + renderSpan(win).length;
5588
+ used += cost;
5589
+ room -= cost;
5590
+ covered = win.end;
5591
+ }
5592
+ // Never empty: a section with no source sends the agent to Read.
5593
+ if (emit.length === 0 && parts.length > 0) {
5594
+ const first = headWindowOf(parts[0].range, ceiling, MIN_WINDOW_LINES);
5595
+ if (first)
5596
+ emit.push(first);
5597
+ }
5598
+ return emit
5599
+ .sort((a, b) => a.start - b.start)
5600
+ .map((r) => ({ range: r, text: renderSpan(r) }));
5601
+ };
5602
+ // Disk-drift gate (#1474): every render branch below except whole-file
5603
+ // slices fileContent (CURRENT bytes) at INDEXED line ranges. Content is
5604
+ // already in hand, so the check costs one stat (hash only on mismatch).
5605
+ const fileStale = this.isFileStaleOnDisk(cg, filePath, fileContent);
5606
+ // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
5607
+ // to a per-symbol view when it's a redundant member of a polymorphic family.
5608
+ // Engages iff ALL hold:
5609
+ // 1. a flow spine exists,
5610
+ // 2. no symbol in the file is on that spine (it's not the mechanism path),
5611
+ // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
5612
+ // 4. it is NOT SPARED, where a file is spared iff the agent named a
5613
+ // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
5614
+ // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
5615
+ // base+subclasses "family" file like Django's compiler.py — collapse it).
5616
+ // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
5617
+ // subclass; naming it must NOT keep every backend variant + test file full
5618
+ // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
5619
+ // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
5620
+ // agent NAMED or that's on the spine is shown with its FULL body (so the agent
5621
+ // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
5622
+ // every other symbol is just its signature. So the base mechanism survives while
5623
+ // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
5624
+ // The symbols a section of this file sets out to deliver, for the
5625
+ // completeness check (`elidedWantedSpans`), ranked the way the cluster
5626
+ // path ranks its members.
5627
+ // The file node is not one of them: no section delivers "the file" as a
5628
+ // symbol, and it spans trailing lines no render prints.
5629
+ const wantedFrom = (nodes) => nodes
5630
+ .filter((n) => n.kind !== 'import' && n.kind !== 'export' && n.kind !== 'file' && n.startLine > 0)
5631
+ .map((n) => ({
5632
+ name: n.name,
5633
+ kind: n.kind,
5634
+ start: n.startLine,
5635
+ end: n.endLine,
5636
+ importance: entryNodeIds.has(n.id) ? 10 : flow.namedNodeIds.has(n.id) ? 9 : 1,
5637
+ spine: flow.pathNodeIds.has(n.id),
5638
+ qualifiedName: n.qualifiedName,
5639
+ }));
5640
+ const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
5641
+ const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
5642
+ const spared = spareNamed && !fileDefinesSuper;
5643
+ const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
5644
+ const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
5645
+ // On-spine god-file: the flow path runs THROUGH this file, but it also holds
5646
+ // many OTHER named methods, and rendering all of them in full blows the
5647
+ // per-file budget and starves the other flow files (Alamofire: the agent
5648
+ // names ~7 Session.swift methods — the build spine PLUS off-path
5649
+ // task/didCompleteTask — far past the whole response budget). Engage the
5650
+ // per-symbol view to keep the SPINE full and collapse the off-path named
5651
+ // methods to signatures. Only when there IS off-path content to shed —
5652
+ // otherwise the spine is irreducible (a sequential flow has no redundancy),
5653
+ // so leave it to the normal full render.
5654
+ const namedBodyChars = group.nodes
5655
+ .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
5656
+ .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
5657
+ const onSpineGodFile = hasSpineNode
5658
+ && namedBodyChars > allowance
5659
+ && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
5660
+ // A line RANGE the agent asked for (`lines 900-1003`) is not a symbol, so
5661
+ // the per-symbol view has no way to show it — such a file takes the
5662
+ // cluster path, which renders anchor spans first.
5663
+ if (!fileStale && adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
5664
+ && !anchorSpans.has(filePath)
5665
+ && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
5666
+ const syms = group.nodes
5667
+ .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
5668
+ .sort((a, b) => a.startLine - b.startLine);
5669
+ // Pass 1: choose which symbols get a FULL body, by priority, greedily within
5670
+ // a per-file body cap — so one huge family file can't body every named method
5671
+ // and crowd out the other flow files (Django's query.py). A symbol earns a
5672
+ // body if it's EXACT, on-spine, UNIQUELY named (`SQLCompiler.execute_sql`),
5673
+ // or a co-named method WHEN this file DEFINES the family supertype (so the
5674
+ // base `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides —
5675
+ // and OkHttp's 5 `intercept`s if the agent names `intercept` — stay
5676
+ // signatures). Tiers, most-wanted first:
5677
+ // 0 EXACT — a qualified name or a line anchor (see `exactNodeIds`),
5678
+ // 1 a spine step the agent NAMED,
5679
+ // 2 a spine step it did not (the one unnamed bridge between two named),
5680
+ // 3 a UNIQUELY named off-spine method,
5681
+ // 4 a co-named method in the family's base file.
5682
+ // Within a tier the spine keeps its CALL order, then source order. Source
5683
+ // order alone let the smaller steps that happen to sit higher in the file
5684
+ // take the cap: Django's `SQLCompiler.as_sql` — named, qualified, step 1 of
5685
+ // the flow, 226 lines — lost to the unnamed bridge `get_qualify_sql` and to
5686
+ // `get_select` and came back as its signature line, every time.
5687
+ const chainPos = new Map([...flow.pathNodeIds].map((id, i) => [id, i]));
5688
+ const prio = (n) => !CALLABLE_BODY.has(n.kind) ? 99
5689
+ : exactNodeIds.has(n.id) ? 0
5690
+ : flow.pathNodeIds.has(n.id) ? (flow.namedNodeIds.has(n.id) ? 1 : 2)
5691
+ : flow.uniqueNamedNodeIds.has(n.id) ? 3
5692
+ : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 4 : 99;
5693
+ // Tiers 0-1 are never reduced to a signature: a body too big for what is
5694
+ // left is WINDOWED instead — its head plus the lines where it calls the
5695
+ // other symbols the question named. A signature is the one render of a
5696
+ // method the agent explicitly asked for that is guaranteed to send it to
5697
+ // Read.
5698
+ const WINDOWED_TIER = 1;
5699
+ // One WINDOW per file, sized by this file's RESERVATION. syms are taken by
5700
+ // priority, and the cap applies to ALL of them — including the spine — so a
5701
+ // big-spine god-file (tokio's worker.rs: run→run_task→next_task→steal_work)
5702
+ // can't eat the whole response and starve the co-flow file (harness.rs's
5703
+ // poll). The native agent windows such a file too (~190 lines at a time),
5704
+ // so this mimics, not truncates. Always emit ≥1 (never an empty section).
5705
+ //
5706
+ // Held to `fundedHeadroom` as well (CG-31) so this path cannot spend a
5707
+ // reservation still owed below it either. It never exceeds `allowance`
5708
+ // today, so the bound only bites once the ceiling is genuinely tight —
5709
+ // but "every render path" has to mean every one, or the guard is just a
5710
+ // detour the next god-file takes.
5711
+ //
5712
+ // Priced in RENDERED chars — line numbers included — and net of the
5713
+ // signature lines the view also prints. Raw source length undercounts
5714
+ // both, and once an oversize body is windowed to the room that is left
5715
+ // the undercount stops being slack: the section ran 19% past what it
5716
+ // was funded (excalidraw's App.tsx) and the four files below it
5717
+ // rendered nothing.
5718
+ const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
5719
+ const sigReserve = syms.slice(0, SIG_MAX).reduce((sum, n) => sum + lineCost(n.startLine), 0);
5720
+ const bodyCap = Math.max(0, Math.min(allowance, fundedHeadroom) - sigReserve);
5721
+ const bodyIds = new Set();
5722
+ /** Tier 0-1 bodies too big to fit whole, as the windows they render as. */
5723
+ const bodyWindows = new Map();
5724
+ let bodyChars = 0;
5725
+ const ranked = syms
5726
+ .filter(n => prio(n) < 99 && n.endLine >= n.startLine)
5727
+ .sort((a, b) => prio(a) - prio(b)
5728
+ || (chainPos.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (chainPos.get(b.id) ?? Number.MAX_SAFE_INTEGER)
5729
+ || a.startLine - b.startLine);
5730
+ const deferred = [];
5731
+ for (const n of ranked) {
5732
+ if (prio(n) > WINDOWED_TIER)
5733
+ continue;
5734
+ const sz = renderedSpanCost(n.startLine, n.endLine);
5735
+ if (bodyChars + sz <= bodyCap) {
5736
+ bodyIds.add(n.id);
5737
+ bodyChars += sz;
5738
+ }
5739
+ else {
5740
+ deferred.push(n);
5741
+ }
5742
+ }
5743
+ for (const n of deferred) {
5744
+ const room = bodyCap - bodyChars;
5745
+ // Below MIN_CHARS a window cannot hold a readable block; with nothing
5746
+ // emitted yet the never-empty floor inside `windowToCeiling` wins.
5747
+ if (room < exports.EXPLORE_ALLOCATION.MIN_CHARS && bodyIds.size + bodyWindows.size > 0)
5748
+ continue;
5749
+ const range = { start: n.startLine, end: n.endLine };
5750
+ const windows = windowToCeiling([{ range, text: renderSpan(range) }], Math.max(0, room), bodyFocusLines(n)).map((p) => p.range);
5751
+ if (windows.length === 0)
5752
+ continue;
5753
+ bodyWindows.set(n.id, windows);
5754
+ bodyChars += windows.reduce((sum, w) => sum + renderedSpanCost(w.start, w.end), 0);
5755
+ }
5756
+ for (const n of ranked) {
5757
+ if (prio(n) <= WINDOWED_TIER)
5758
+ continue;
5759
+ const sz = renderedSpanCost(n.startLine, n.endLine);
5760
+ if (bodyChars + sz > bodyCap && bodyIds.size + bodyWindows.size > 0)
5761
+ continue;
5762
+ bodyIds.add(n.id);
5763
+ bodyChars += sz;
5764
+ }
5765
+ // Pass 2: render in line order — full body for chosen symbols, else the
5766
+ // signature line (capped, with a "+N more" tail so the structure map of a
5767
+ // god-file doesn't itself bloat the budget).
5768
+ const skel = [];
5769
+ let coveredUntil = 0; // skip symbols already inside an emitted body
5770
+ let sigCount = 0, sigDropped = 0;
5771
+ for (const n of syms) {
5772
+ if (n.startLine <= coveredUntil)
5773
+ continue;
5774
+ if (bodyIds.has(n.id)) {
5775
+ const end = n.endLine;
5776
+ const body = fileLines.slice(n.startLine - 1, end).join('\n');
5777
+ skel.push({
5778
+ range: { start: n.startLine, end },
5779
+ text: withLineNumbers ? numberSourceLines(body, n.startLine) : body,
5780
+ });
5781
+ coveredUntil = end;
5782
+ }
5783
+ else if (bodyWindows.has(n.id)) {
5784
+ // Each hole in a windowed body is named with the explore query that
5785
+ // returns it — a line range, which explore now honours — so the
5786
+ // follow-up is one call, not a Read of the file.
5787
+ const windows = bodyWindows.get(n.id);
5788
+ windows.forEach((w, k) => {
5789
+ const holeEnd = (windows[k + 1]?.start ?? n.endLine + 1) - 1;
5790
+ const hole = holeEnd > w.end
5791
+ ? `\n… lines ${w.end + 1}-${holeEnd} of \`${n.name}\` elided — codegraph_explore \`${filePath}:${w.end + 1}-${holeEnd}\` returns them`
5792
+ : '';
5793
+ skel.push({ range: w, text: renderSpan(w) + hole });
5794
+ });
5795
+ coveredUntil = n.endLine;
5796
+ }
5797
+ else {
5798
+ // Elide the body, emit the signature. node.startLine can point at a
5799
+ // decorator/annotation, so scan forward for the line that names the symbol.
5800
+ let lineNo = n.startLine;
5801
+ for (let k = 0; k < 4; k++) {
4512
5802
  if ((fileLines[n.startLine - 1 + k] || '').includes(n.name)) {
4513
5803
  lineNo = n.startLine + k;
4514
5804
  break;
@@ -4530,7 +5820,6 @@ class ToolHandler {
4530
5820
  }
4531
5821
  }
4532
5822
  }
4533
- const sigTail = sigDropped > 0 ? `… +${sigDropped} more (signatures elided)` : '';
4534
5823
  if (skel.length > 0) {
4535
5824
  const names = [...new Set(group.nodes.filter(n => n.kind !== 'import' && n.kind !== 'export').map(n => n.name))]
4536
5825
  .slice(0, budget.maxSymbolsInFileHeader).join(', ');
@@ -4540,7 +5829,7 @@ class ToolHandler {
4540
5829
  // (Session.swift, DataRequest.swift) that fired an over-investigation
4541
5830
  // spiral (the agent Read the skeletonized file, then kept digging).
4542
5831
  // CLAUDE.md: explore output must never tell the agent to Read.
4543
- const tag = bodyIds.size > 0
5832
+ const tag = bodyIds.size + bodyWindows.size > 0
4544
5833
  ? 'focused (the methods you named in full, the rest as signatures — codegraph_explore a signature by name for its body; do NOT Read)'
4545
5834
  : 'skeleton (signatures only — codegraph_explore a name for its full body; do NOT Read)';
4546
5835
  // Dedup runs on the per-symbol parts, so a body the agent already has
@@ -4548,16 +5837,50 @@ class ToolHandler {
4548
5837
  // (a one-line signature is far under MIN_COVERED_LINES and is never
4549
5838
  // withheld — the structure map is what makes this render legible).
4550
5839
  const dd = dedupeSpans(skel);
4551
- const withTail = (parts) => [...parts.map((p) => p.text), ...(sigTail ? [sigTail] : [])].join('\n');
5840
+ const withTail = (parts, extraDropped = 0) => {
5841
+ const dropped = sigDropped + extraDropped;
5842
+ const tail = dropped > 0 ? `… +${dropped} more (signatures elided)` : '';
5843
+ return [...parts.map((p) => p.text), ...(tail ? [tail] : [])].join('\n');
5844
+ };
5845
+ const header = fileSectionHeader(filePath, `${names} · ${tag}`);
5846
+ // The ceiling fit test every other render path has (CG-26), which this
5847
+ // one lacked: it emitted whatever it built, so a skeleton at the tail
5848
+ // of a full response ran past the ceiling and the final cut threw away
5849
+ // it, the section before it, and the pointer list behind them. Trim
5850
+ // from the end instead — trailing signatures first, then trailing
5851
+ // bodies — and skip the file only if not one part fits.
5852
+ let parts = dd.parts;
5853
+ let trimmedSigs = 0;
5854
+ const sectionCost = (ps) => header.length + 2 + (ps.length > 0 ? withTail(ps, trimmedSigs).length + lang.length + 11 : 0);
5855
+ while (parts.length > 1 && totalChars + sectionCost(parts) > renderCeiling) {
5856
+ let drop = -1;
5857
+ for (let k = parts.length - 1; k >= 0; k--) {
5858
+ if (parts[k].range.start === parts[k].range.end) {
5859
+ drop = k;
5860
+ break;
5861
+ }
5862
+ }
5863
+ if (drop < 0)
5864
+ drop = parts.length - 1;
5865
+ else
5866
+ trimmedSigs++;
5867
+ parts = parts.filter((_, k) => k !== drop);
5868
+ }
5869
+ if (dd.parts.length > 0 && totalChars + sectionCost(parts) > renderCeiling) {
5870
+ diag?.recordSkip(filePath, 'budget-clusters');
5871
+ continue;
5872
+ }
4552
5873
  emitFileSection({
4553
- header: fileSectionHeader(filePath, `${names} · ${tag}`),
4554
- body: dd.parts.length > 0 ? withTail(dd.parts) : '',
4555
- ranges: dd.parts.map((p) => p.range),
5874
+ header,
5875
+ body: parts.length > 0 ? withTail(parts, trimmedSigs) : '',
5876
+ ranges: parts.map((p) => p.range),
4556
5877
  covered: dd.covered,
4557
5878
  overhead: 120,
4558
- mode: bodyIds.size > 0 ? 'focused' : 'skeleton',
5879
+ mode: bodyIds.size + bodyWindows.size > 0 ? 'focused' : 'skeleton',
4559
5880
  // Always "clipped": the per-symbol view elides bodies by construction.
4560
5881
  clipped: true,
5882
+ // Every symbol whose body this view could have shown.
5883
+ wanted: wantedFrom(syms),
4561
5884
  fullBody: withTail(skel),
4562
5885
  fullRanges: skel.map((p) => p.range),
4563
5886
  });
@@ -4637,7 +5960,7 @@ class ToolHandler {
4637
5960
  // the emission site below, so it cannot displace either.
4638
5961
  const buysWhole = fileContent.length <= graceBound
4639
5962
  || (reserved >= fileContent.length * exports.EXPLORE_ALLOCATION.WHOLE_FILE_BUY_FRACTION
4640
- && sourceSpent + fileContent.length + owedBelow <= sourceCeiling
5963
+ && sourceSpent + fileContent.length + owedBelow <= reservedTotal + buyOvershoot
4641
5964
  && fileContent.length <= fundedHeadroom);
4642
5965
  // Set by the whole-file arm when it actually emits. A whole render that
4643
5966
  // does not FIT no longer ends the file's turn (CG-26) — it falls through
@@ -4688,6 +6011,11 @@ class ToolHandler {
4688
6011
  overhead: 200,
4689
6012
  mode: 'whole',
4690
6013
  clipped: false,
6014
+ // Sent whole, so nothing is elided — unless dedup folds a remainder
6015
+ // the agent does not hold (`emitFileSection`). Clamped to the lines
6016
+ // the render carries, which stop before trailing blank lines.
6017
+ wanted: wantedFrom(group.nodes)
6018
+ .map((w) => ({ ...w, end: Math.min(w.end, wholeRange.end) })),
4691
6019
  fullBody: fullSection,
4692
6020
  fullRanges: [wholeRange],
4693
6021
  });
@@ -4747,19 +6075,27 @@ class ToolHandler {
4747
6075
  for (const n of group.nodes)
4748
6076
  if (n.startLine > 0 && n.endLine > 0)
4749
6077
  rangeNodes.set(n.id, n);
4750
- for (const id of flow.namedNodeIds) {
6078
+ for (const id of [...flow.namedNodeIds, ...exactNodeIds]) {
4751
6079
  if (rangeNodes.has(id))
4752
6080
  continue;
4753
6081
  const n = cg.getNode(id);
4754
6082
  if (n && n.filePath === filePath && n.startLine > 0 && n.endLine > 0)
4755
6083
  rangeNodes.set(id, n);
4756
6084
  }
6085
+ // EXACT targets outrank even the query's entry points: an entry is what the
6086
+ // search matched, an exact target is the def the agent singled out. Their
6087
+ // clusters rank first and get the spine's bounded overshoot (below), so a
6088
+ // qualified `SQLCompiler.as_sql` is no longer outranked by a denser cluster
6089
+ // around `SQLInsertCompiler.as_sql` that merely matched the bare name.
6090
+ const EXACT_IMPORTANCE = 11;
4757
6091
  const ranges = [...rangeNodes.values()]
4758
6092
  // Drop whole-file envelope nodes (containers covering >50% of the file).
4759
6093
  .filter(n => !(ENVELOPE_KINDS.has(n.kind) && (n.endLine - n.startLine + 1) > fileLines.length * 0.5))
4760
6094
  .map(n => {
4761
6095
  let importance = 1;
4762
- if (entryNodeIds.has(n.id))
6096
+ if (exactNodeIds.has(n.id))
6097
+ importance = EXACT_IMPORTANCE;
6098
+ else if (entryNodeIds.has(n.id))
4763
6099
  importance = 10;
4764
6100
  else if (flow.namedNodeIds.has(n.id))
4765
6101
  importance = 9; // agent named it → keep its cluster
@@ -4772,7 +6108,7 @@ class ToolHandler {
4772
6108
  // processRunExecutionData, the named flow ENTRY at L1562, is a large
4773
6109
  // low-density method that lost the budget to denser blocks and got cut, so
4774
6110
  // the agent Read it back — the very thing explore exists to prevent).
4775
- 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) };
6111
+ 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), qualifiedName: n.qualifiedName };
4776
6112
  });
4777
6113
  // Add edge source locations in this file — captures template references
4778
6114
  // (component usages, event handlers) that aren't nodes themselves.
@@ -4794,6 +6130,15 @@ class ToolHandler {
4794
6130
  ranges.push({ start: edge.line, end: edge.line, name: targetName, kind: edge.kind, importance: 2, spine: false });
4795
6131
  }
4796
6132
  }
6133
+ // Line spans the agent anchored in this file (`lines 900-1003`) are exact
6134
+ // targets too — rendered as exactly the span asked for, not as the
6135
+ // symbols around it.
6136
+ for (const span of anchorSpans.get(filePath) ?? []) {
6137
+ if (span.start > fileLines.length)
6138
+ continue;
6139
+ const end = Math.min(span.end, fileLines.length);
6140
+ ranges.push({ start: span.start, end, name: `lines ${span.start}-${end}`, kind: 'range', importance: EXACT_IMPORTANCE, spine: false });
6141
+ }
4797
6142
  ranges.sort((a, b) => a.start - b.start);
4798
6143
  if (ranges.length === 0) {
4799
6144
  diag?.recordSkip(filePath, 'no-ranges');
@@ -4847,44 +6192,154 @@ class ToolHandler {
4847
6192
  const contextPadding = 3;
4848
6193
  // An oversize spine method (the call path runs THROUGH a god-method — n8n's
4849
6194
  // processRunExecutionData is 962 lines) is windowed to its next-hop CALL site
4850
- // plus the signature head, NOT dumped whole. Without this the cluster is too big
6195
+ // plus the signature head, NOT dumped whole. Without this the method is too big
4851
6196
  // for any per-file cap and gets dropped, so the agent Reads the method back —
4852
6197
  // the exact gap this closes. Bounded, so a god-method can't blow the budget yet
4853
6198
  // the spine's call still appears in context.
6199
+ //
6200
+ // The size test is on the spine METHOD, never on the cluster holding it. A
6201
+ // cluster merges every symbol within `gapThreshold` lines of the next, so on a
6202
+ // dense file — and on every PINNED file, whose whole symbol list enters the
6203
+ // gather — it spans hundreds of lines around a short spine method. Windowing
6204
+ // that merge threw away every other symbol in it: vscode's pinned
6205
+ // `rpcProtocol.ts` merged into one cluster over lines 20–968 around a 77-line
6206
+ // `_receiveOneMessage`, and the five `MessageIO.serialize*` bodies and the
6207
+ // `MessageType` enum the query named were cut to a 5-line file head plus ±28
6208
+ // lines of one call site — 2,910 chars spent of a 16,800 reservation, and
6209
+ // reported unclipped. A cluster that is long only because it merged goes
6210
+ // through the shrink-by-member path like any other oversize cluster.
4854
6211
  const OVERSIZE_SPINE_LINES = 200;
4855
- const SPINE_WINDOW = 28; // lines each side of the next-hop call site
4856
- const sectionText = (parts) => parts.map((p) => p.text).join(GAP_MARKER);
4857
- const buildSection = (c) => {
4858
- if (c.hasSpine && c.spineCallLine && (c.end - c.start + 1) > OVERSIZE_SPINE_LINES) {
4859
- const call = c.spineCallLine;
4860
- const winStart = Math.max(c.start, call - SPINE_WINDOW);
4861
- const winEnd = Math.min(c.end, call + SPINE_WINDOW);
4862
- const parts = [];
4863
- // Signature head, only when it sits clearly above the window (else the
4864
- // window already covers the method opening).
4865
- const headEnd = Math.min(c.start + 4, winStart - 2);
4866
- if (headEnd >= c.start) {
4867
- const head = fileLines.slice(c.start - 1, headEnd).join('\n');
4868
- parts.push({
4869
- range: { start: c.start, end: headEnd },
4870
- text: withLineNumbers ? numberSourceLines(head, c.start) : head,
4871
- });
4872
- }
4873
- const win = fileLines.slice(winStart - 1, winEnd).join('\n');
4874
- parts.push({
4875
- range: { start: winStart, end: winEnd },
4876
- text: withLineNumbers ? numberSourceLines(win, winStart) : win,
4877
- });
4878
- return parts;
6212
+ /**
6213
+ * Spine methods too long to render whole, in source order. Not one that is,
6214
+ * or holds, an EXACT target (a qualified name, an anchored line span): its
6215
+ * body is what was asked for, so it is kept whole up to the ceiling and only
6216
+ * then windowed — by `windowToCeiling`, which keeps the call site AND the
6217
+ * named defs. Windowed here, an anchored `lines 900-1003` inside it would go
6218
+ * with the rest of the body.
6219
+ */
6220
+ const exactRanges = ranges.filter((r) => r.importance >= EXACT_IMPORTANCE);
6221
+ const oversizeSpine = ranges
6222
+ .filter((r) => r.spine && r.spineCallLine !== undefined
6223
+ && r.end - r.start + 1 > OVERSIZE_SPINE_LINES
6224
+ && r.spineCallLine >= r.start && r.spineCallLine <= r.end
6225
+ && !exactRanges.some((x) => x.start <= r.end && x.end >= r.start))
6226
+ .sort((a, b) => a.start - b.start);
6227
+ const oversizeSpineSet = new Set(oversizeSpine);
6228
+ /** What an oversize spine method renders as: its signature head plus its call site. */
6229
+ const spineWindowOf = (g) => {
6230
+ const call = g.spineCallLine;
6231
+ const winStart = Math.max(g.start, call - SPINE_WINDOW);
6232
+ const winEnd = Math.min(g.end, call + SPINE_WINDOW);
6233
+ // Signature head, only when it sits clearly above the window (else the
6234
+ // window already covers the method opening).
6235
+ const headEnd = Math.min(g.start + 4, winStart - 2);
6236
+ return headEnd >= g.start
6237
+ ? [{ start: g.start, end: headEnd }, { start: winStart, end: winEnd }]
6238
+ : [{ start: winStart, end: winEnd }];
6239
+ };
6240
+ /** Whether rendering [start, end] windows an oversize spine method inside it. */
6241
+ const windowsSpineIn = (start, end) => oversizeSpine.some((g) => g.start >= start && g.end <= end);
6242
+ // Returns the rendered text as SPAN-KEYED PARTS. Every part carries the
6243
+ // exact line range its text was sliced from, which two things depend on:
6244
+ // the session record (CG-17) — a record claiming lines it never sent would
6245
+ // withhold them from a later call, costing a Read — and cross-call dedup
6246
+ // (CG-18), which rebuilds a part's text from a narrower span when the
6247
+ // agent already holds the rest. Both read the spans from the function that
6248
+ // does the slicing; a second function mirroring these window/padding rules
6249
+ // would drift.
6250
+ // Every fit decision below measures parts joined by BARE gap markers.
6251
+ // Naming what a gap skipped (#1711) is added once, at assembly, from what
6252
+ // the file's budget has left: measured with the names, a shrunk cluster
6253
+ // could overrun its room by the names alone and be dropped whole — the
6254
+ // RPCProtocol class in vscode's rpcProtocol.ts went out that way, leaving a
6255
+ // 3-line stub where ~5,200 chars of its body had fit.
6256
+ const sectionText = (parts) => joinPartsWithNamedGaps(filePath, parts, fileIndexNodes, 0);
6257
+ /**
6258
+ * The line spans `buildSection` renders for [start, end] — split out so the
6259
+ * exact pricing below (`renderedSizeOfKept`) prices a member window as the
6260
+ * window it renders, not as the body it elides.
6261
+ */
6262
+ const sectionRangesOf = (c) => {
6263
+ // Plain source for [start, end], except each oversize spine method inside
6264
+ // it, which renders as its window. Context padding goes on the outer edges
6265
+ // of PLAIN source only: padding past a windowed method would add lines
6266
+ // after a tail that was elided.
6267
+ const spans = [];
6268
+ let cursor = c.start;
6269
+ for (const g of oversizeSpine) {
6270
+ if (g.start < cursor || g.start < c.start || g.end > c.end)
6271
+ continue;
6272
+ if (g.start > cursor)
6273
+ spans.push({ range: { start: cursor, end: g.start - 1 }, plain: true });
6274
+ for (const w of spineWindowOf(g))
6275
+ spans.push({ range: w, plain: false });
6276
+ cursor = g.end + 1;
6277
+ }
6278
+ if (cursor <= c.end)
6279
+ spans.push({ range: { start: cursor, end: c.end }, plain: true });
6280
+ const first = spans[0];
6281
+ const last = spans[spans.length - 1];
6282
+ if (first?.plain)
6283
+ first.range.start = Math.max(1, first.range.start - contextPadding);
6284
+ if (last?.plain)
6285
+ last.range.end = Math.min(fileLines.length, last.range.end + contextPadding);
6286
+ // Spans that touch in the file are one block, not two parts with a gap
6287
+ // marker between adjacent lines.
6288
+ const merged = [];
6289
+ for (const { range } of spans) {
6290
+ const prev = merged[merged.length - 1];
6291
+ if (prev && range.start <= prev.end + 1)
6292
+ prev.end = Math.max(prev.end, range.end);
6293
+ else
6294
+ merged.push({ ...range });
4879
6295
  }
4880
- const startIdx = Math.max(0, c.start - 1 - contextPadding);
4881
- const endIdx = Math.min(fileLines.length, c.end + contextPadding);
4882
- const slice = fileLines.slice(startIdx, endIdx).join('\n');
4883
- // startIdx is 0-based, so the slice's first line is line startIdx + 1.
4884
- return [{
4885
- range: { start: startIdx + 1, end: endIdx },
4886
- text: withLineNumbers ? numberSourceLines(slice, startIdx + 1) : slice,
4887
- }];
6296
+ return merged;
6297
+ };
6298
+ const buildSection = (c) => sectionRangesOf(c).map((r) => ({ range: r, text: renderSpan(r) }));
6299
+ /** Rendered cost of one member on its own, context padding included. */
6300
+ const paddedCost = (r) => {
6301
+ let chars = 0;
6302
+ const hi = Math.min(fileLines.length, r.end + contextPadding);
6303
+ for (let ln = Math.max(1, r.start - contextPadding); ln <= hi; ln++)
6304
+ chars += lineCost(ln);
6305
+ return chars;
6306
+ };
6307
+ /**
6308
+ * A member the query asked for: one it named or that is an entry point
6309
+ * (importance >= 9), or one on the rendered call path. The rest of a
6310
+ * cluster — glue, connected nodes, edge lines, peripheral declarations —
6311
+ * is incidental context that happens to sit within `gapThreshold` of it.
6312
+ */
6313
+ const isProtectedMember = (r) => r.importance >= 9 || r.spine;
6314
+ /**
6315
+ * Kept ranges re-merged in source order, the way a cluster merges — so
6316
+ * adjacent survivors read as one block rather than a stutter of
6317
+ * one-symbol fragments.
6318
+ */
6319
+ const mergeKept = (keep) => {
6320
+ const merged = [];
6321
+ for (const r of [...keep].sort((a, b) => a.start - b.start)) {
6322
+ const last = merged[merged.length - 1];
6323
+ if (last && r.start <= last.end + gapThreshold)
6324
+ last.end = Math.max(last.end, r.end);
6325
+ else
6326
+ merged.push({ start: r.start, end: r.end });
6327
+ }
6328
+ return merged;
6329
+ };
6330
+ /** Whole member ranges, re-merged in source order and rendered. */
6331
+ const partsOfMembers = (members) => mergeKept(members).flatMap((m) => buildSection(m));
6332
+ /**
6333
+ * What this cluster's protected members cost to render on their own, after
6334
+ * the session history — the room a cluster ranked ABOVE it must leave for
6335
+ * them. 0 for a cluster with nothing the query asked for.
6336
+ */
6337
+ const protectedCoreCost = (c) => {
6338
+ const core = c.members.filter(isProtectedMember);
6339
+ if (core.length === 0)
6340
+ return 0;
6341
+ const parts = core.length === c.members.length ? buildSection(c) : partsOfMembers(core);
6342
+ return sectionText(dedupeSpans(parts).parts).length + GAP_MARKER.length;
4888
6343
  };
4889
6344
  /**
4890
6345
  * Shrink an oversize cluster to the highest-importance symbols inside it
@@ -4914,188 +6369,90 @@ class ToolHandler {
4914
6369
  * decide WHICH members survive: that is the ceiling trim's job, and CG-38 is
4915
6370
  * why that trim now protects the named spans instead of cutting in source
4916
6371
  * order. See `docs/benchmarks/explore-tail-render-cg38.md`.
4917
- */
4918
- const shrinkCluster = (c, cap) => {
4919
- if (c.members.length < 2)
4920
- return null;
4921
- const byImportance = [...c.members].sort((a, b) => b.importance - a.importance || (a.end - a.start) - (b.end - b.start) || a.start - b.start);
4922
- const sizeOf = (r) => fileLines.slice(r.start - 1, r.end).join('\n').length;
4923
- const keep = [];
4924
- let kept = 0;
4925
- for (const r of byImportance) {
4926
- const sz = sizeOf(r) + GAP_MARKER.length;
4927
- // Always keep the most important range, even if it alone is oversize —
4928
- // an empty section sends the agent to Read, which costs far more. How
4929
- // far it may overshoot is bounded by the caller's ceiling (CG-30), which
4930
- // windows a runaway member instead of dropping it.
4931
- if (keep.length > 0 && kept + sz > cap)
4932
- continue;
4933
- keep.push(r);
4934
- kept += sz;
4935
- }
4936
- if (keep.length === c.members.length)
4937
- return null;
4938
- // Re-merge the kept ranges in source order so adjacent survivors read as
4939
- // one block rather than a stutter of one-symbol fragments.
4940
- keep.sort((a, b) => a.start - b.start);
4941
- const merged = [];
4942
- for (const r of keep) {
4943
- const last = merged[merged.length - 1];
4944
- if (last && r.start <= last.end + gapThreshold)
4945
- last.end = Math.max(last.end, r.end);
4946
- else
4947
- merged.push({ start: r.start, end: r.end });
4948
- }
4949
- return merged.flatMap((m) => buildSection(m));
4950
- };
4951
- /**
4952
- * Bounded overshoot for one cluster's render (CG-30).
4953
6372
  *
4954
- * `shrinkCluster` keeps the highest-importance member whole even when that
4955
- * member alone is oversize — an empty file section sends the agent to Read,
4956
- * which is exactly what explore exists to prevent. But "never empty" is not
4957
- * "any size": with nothing bounding it, one 22K member rendered against a
4958
- * 9K reservation (2.4x), which collapses the headroom every file ranked
4959
- * below it draws from. Past the ceiling the member is WINDOWED rather than
4960
- * dropped — a leading window (signature + head of the body), plus a window
4961
- * on the spine's call site when the head misses it, since on a flow cluster
4962
- * the call path IS the answer.
6373
+ * `incidentalCap` is set for a cluster holding a member the query asked for
6374
+ * (see `renderCluster` and `protectedCoreCost`). Protected members are then
6375
+ * chosen first, exactly as above; every other member must also fit
6376
+ * `incidentalCap`, which is measured on the rendered text (padding, line
6377
+ * numbers) because it is a bound — the ceiling past which the render is
6378
+ * windowed, or bytes owed to a cluster below — not an estimate.
4963
6379
  */
4964
- const MIN_WINDOW_LINES = 12;
4965
- /** Rendered cost of one source line, line numbering included. */
4966
- const lineCost = (ln) => (fileLines[ln - 1] ?? '').length + 1 + (withLineNumbers ? String(ln).length + 1 : 0);
4967
6380
  /**
4968
- * Longest prefix of `r` that fits `room`. `minLines` is the never-empty
4969
- * floor — it may overrun `room`, so it is only ever asked for when nothing
4970
- * else has been emitted and the alternative is an empty section.
6381
+ * Exact rendered size of `keep` once merged, padded and joined — what
6382
+ * `sectionText` will measure — via a prefix sum, so pricing a candidate
6383
+ * member costs O(members), not a re-render. Priced on the spans
6384
+ * `buildSection` renders, so an oversize spine member costs its window.
4971
6385
  */
4972
- const headWindowOf = (r, room, minLines = 0) => {
4973
- let end = r.start - 1;
4974
- let chars = 0;
4975
- for (let ln = r.start; ln <= r.end; ln++) {
4976
- const cost = lineCost(ln);
4977
- if (chars + cost > room && end - r.start + 1 >= minLines)
4978
- break;
4979
- chars += cost;
4980
- end = ln;
4981
- }
4982
- return end >= r.start ? { start: r.start, end } : null;
4983
- };
4984
- /** Widest window around `line` inside [lo, hi] that fits `room`. */
4985
- const centeredWindowOf = (line, lo, hi, room) => {
4986
- if (line < lo || line > hi)
6386
+ const renderedSizeOfKept = (keep) => mergeKept(keep).flatMap((m) => sectionRangesOf(m)).reduce((sum, r, i) => sum + renderedSpanCost(r.start, r.end) + (i > 0 ? GAP_MARKER.length : 0), 0);
6387
+ const shrinkCluster = (c, cap, incidentalCap) => {
6388
+ if (c.members.length < 2)
4987
6389
  return null;
4988
- let start = line, end = line, chars = lineCost(line);
4989
- for (let grown = true; grown;) {
4990
- grown = false;
4991
- if (end + 1 <= hi && chars + lineCost(end + 1) <= room) {
4992
- end += 1;
4993
- chars += lineCost(end);
4994
- grown = true;
4995
- }
4996
- if (start - 1 >= lo && chars + lineCost(start - 1) <= room) {
4997
- start -= 1;
4998
- chars += lineCost(start);
4999
- grown = true;
6390
+ const guarded = incidentalCap !== undefined;
6391
+ // Protected members first when a hold-back applies (see `renderCluster`);
6392
+ // then an EXACT target, then the spine, as `rankedClusters` ranks spine
6393
+ // clusters first: the call path IS the answer. An unnamed bridge on it
6394
+ // (vscode's `_receiveRequest`, the Flow section's own step 2) otherwise
6395
+ // ranks with incidental helpers and is the member the cap drops. Exact
6396
+ // ahead of spine because the exact branch below keeps members in this
6397
+ // order until the cap: a long spine method first would price out the
6398
+ // body the agent singled out.
6399
+ const byImportance = [...c.members].sort((a, b) => (guarded ? Number(isProtectedMember(b)) - Number(isProtectedMember(a)) : 0)
6400
+ || Number(b.importance >= EXACT_IMPORTANCE) - Number(a.importance >= EXACT_IMPORTANCE)
6401
+ || (b.spine ? 1 : 0) - (a.spine ? 1 : 0)
6402
+ || b.importance - a.importance || (a.end - a.start) - (b.end - b.start) || a.start - b.start);
6403
+ const keep = [];
6404
+ if (c.maxImportance >= EXACT_IMPORTANCE) {
6405
+ // An EXACT target prices EVERY member in rendered chars, protected
6406
+ // ones included. The raw estimate below over-keeps on purpose and
6407
+ // leaves the ceiling trim to cut — but that trim fills in SOURCE
6408
+ // order, so any member above the exact body in the file (an entry
6409
+ // point, a named neighbour) was paid for first and the body the agent
6410
+ // asked for lost its tail (Django's `SQLCompiler.as_sql` stopped at
6411
+ // L944 of 1001 behind a 15-line neighbour). Priced exactly, the kept
6412
+ // set fits and the trim has nothing left to cut unless the exact body
6413
+ // ALONE overruns the ceiling — where it is windowed on its focus
6414
+ // lines. Incidental members also fit `incidentalCap`, as below.
6415
+ for (const r of byImportance) {
6416
+ const limit = guarded && !isProtectedMember(r) ? Math.min(cap, incidentalCap) : cap;
6417
+ if (keep.length > 0 && renderedSizeOfKept([...keep, r]) > limit)
6418
+ continue;
6419
+ keep.push(r);
5000
6420
  }
5001
6421
  }
5002
- return { start, end };
5003
- };
5004
- /**
5005
- * Reduce rendered parts to fit `ceiling`, never to nothing. Whole parts are
5006
- * kept while they fit; the first part that overruns is cut to a leading
5007
- * window on whole lines (a body is never cut mid-line), and everything past
5008
- * it is dropped. The GAP_MARKER between surviving parts — and the line-number
5009
- * jump — is what tells the agent the cut happened.
5010
- *
5011
- * A partial window shorter than MIN_WINDOW_LINES is not worth emitting, and
5012
- * emitting one is actively harmful: the session record then claims a 4-line
5013
- * sliver, and the NEXT call's dedup has to either shred a whole block around
5014
- * it or re-send it. Below that floor the part is simply dropped — unless
5015
- * nothing has been emitted at all, where the floor wins over the ceiling
5016
- * because an empty section is the one outcome worse than an oversize one.
5017
- *
5018
- * `focusLines` are the lines this trim must not lose: the spine's next-hop
5019
- * call site (CG-30) and every definition the agent NAMED inside the cluster
5020
- * (CG-38). The head fill is source-ordered, so a named def in the TAIL of a
5021
- * large file is otherwise always the first thing an over-ceiling render
5022
- * drops — the one span the agent asked for by name, cut in favour of
5023
- * head-of-file filler it did not ask for. The full-ceiling fill is tried
5024
- * FIRST and the 60% hold-back applies only when a focus line is actually
5025
- * left uncovered, so a cluster whose head already reaches its focus keeps
5026
- * the whole ceiling for source.
5027
- */
5028
- const windowToCeiling = (parts, ceiling, focusLines = []) => {
5029
- const inParts = (line) => parts.some((p) => line >= p.range.start && line <= p.range.end);
5030
- const focus = [...new Set(focusLines)]
5031
- .filter((l) => typeof l === 'number' && l > 0 && inParts(l))
5032
- .sort((a, b) => a - b);
5033
- /** Source-ordered fill of whole parts, the overrunning one cut to a head window. */
5034
- const fill = (room) => {
5035
- const emit = [];
5036
- let used = 0;
5037
- for (const p of parts) {
5038
- const join = emit.length > 0 ? GAP_MARKER.length : 0;
5039
- if (used + join + p.text.length <= room) {
5040
- emit.push(p.range);
5041
- used += join + p.text.length;
6422
+ else {
6423
+ // An oversize spine method costs its window, not its body — `buildSection`
6424
+ // windows it wherever it lands. Charging the full body kept it as the
6425
+ // most important member and then had no room left for anything beside it.
6426
+ const sizeOf = (r) => (oversizeSpineSet.has(r) ? spineWindowOf(r) : [r])
6427
+ .reduce((n, w) => n + fileLines.slice(w.start - 1, w.end).join('\n').length, 0);
6428
+ let kept = 0;
6429
+ // Rendered size of what is kept so far, once the first incidental member
6430
+ // is weighed. Every protected member sorts ahead of it, so this is the
6431
+ // exact cost of the protected set; each incidental member then adds its
6432
+ // own padded span, an over-estimate that errs toward the cluster below.
6433
+ let rendered;
6434
+ for (const r of byImportance) {
6435
+ const sz = sizeOf(r) + GAP_MARKER.length;
6436
+ // Always keep the most important range, even if it alone is oversize —
6437
+ // an empty section sends the agent to Read, which costs far more. How
6438
+ // far it may overshoot is bounded by the caller's ceiling (CG-30), which
6439
+ // windows a runaway member instead of dropping it.
6440
+ if (keep.length > 0 && kept + sz > cap)
5042
6441
  continue;
6442
+ if (guarded && keep.length > 0 && !isProtectedMember(r)) {
6443
+ rendered ??= sectionText(dedupeSpans(partsOfMembers(keep)).parts).length;
6444
+ const cost = paddedCost(r) + GAP_MARKER.length;
6445
+ if (rendered + cost > incidentalCap)
6446
+ continue;
6447
+ rendered += cost;
5043
6448
  }
5044
- const first = emit.length === 0;
5045
- const win = headWindowOf(p.range, Math.max(0, room - used - join), first ? MIN_WINDOW_LINES : 0);
5046
- if (win && (first || win.end - win.start + 1 >= MIN_WINDOW_LINES)) {
5047
- emit.push(win);
5048
- used += join + renderSpan(win).length;
5049
- }
5050
- break;
6449
+ keep.push(r);
6450
+ kept += sz;
5051
6451
  }
5052
- return { emit, used };
5053
- };
5054
- let { emit, used } = fill(ceiling);
5055
- const reached = () => (emit.length ? emit[emit.length - 1].end : 0);
5056
- if (focus.some((l) => l > reached())) {
5057
- // Hold room back for the focus windows so the head can't eat all of it.
5058
- ({ emit, used } = fill(Math.floor(ceiling * 0.6)));
5059
- }
5060
- // What is left is SPLIT between the uncovered focus lines rather than
5061
- // handed to them in order. Greedy-in-source-order reproduces the very bug
5062
- // this guards: on a prose query resolving four focus lines, the two
5063
- // earliest took the whole reserve and `flushQueuedMessages` at L1102 —
5064
- // named in the question — was dropped again. A skipped or undersized
5065
- // window returns its share to the pool for the ones after it.
5066
- let covered = reached();
5067
- let room = Math.max(0, ceiling - used);
5068
- const pending = focus.filter((l) => l > covered);
5069
- for (let i = 0; i < pending.length; i++) {
5070
- const line = pending[i];
5071
- if (line <= covered)
5072
- continue; // an earlier window already reached it
5073
- const share = Math.floor(room / (pending.length - i)) - GAP_MARKER.length;
5074
- if (share <= 0)
5075
- continue;
5076
- const host = parts.find((p) => line >= p.range.start && line <= p.range.end);
5077
- const lo = Math.max(host.range.start, line - SPINE_WINDOW, covered + 1);
5078
- const hi = Math.min(host.range.end, line + SPINE_WINDOW);
5079
- const win = centeredWindowOf(line, lo, hi, share);
5080
- // Same sliver floor as the head window — a two-line peek at the call
5081
- // site teaches the next call's dedup to shred the block around it.
5082
- if (!win || win.end - win.start + 1 < MIN_WINDOW_LINES)
5083
- continue;
5084
- emit.push(win);
5085
- const cost = GAP_MARKER.length + renderSpan(win).length;
5086
- used += cost;
5087
- room -= cost;
5088
- covered = win.end;
5089
- }
5090
- // Never empty: a section with no source sends the agent to Read.
5091
- if (emit.length === 0 && parts.length > 0) {
5092
- const first = headWindowOf(parts[0].range, ceiling, MIN_WINDOW_LINES);
5093
- if (first)
5094
- emit.push(first);
5095
6452
  }
5096
- return emit
5097
- .sort((a, b) => a.start - b.start)
5098
- .map((r) => ({ range: r, text: renderSpan(r) }));
6453
+ if (keep.length === c.members.length)
6454
+ return null;
6455
+ return partsOfMembers(keep);
5099
6456
  };
5100
6457
  /**
5101
6458
  * The lines a ceiling trim of this cluster must not lose: the spine's
@@ -5112,7 +6469,14 @@ class ToolHandler {
5112
6469
  .sort((a, b) => b.importance - a.importance || a.start - b.start)
5113
6470
  .slice(0, MAX_FOCUS_LINES)
5114
6471
  .map((m) => m.start);
5115
- return c.spineCallLine ? [c.spineCallLine, ...named] : named;
6472
+ // An exact body cut by the ceiling keeps its calls into the question's
6473
+ // other symbols too, not only its def line — the same focus the
6474
+ // per-symbol view windows by.
6475
+ const exactFocus = c.maxImportance < EXACT_IMPORTANCE ? [] : [...exactNodeIds]
6476
+ .map((id) => subgraph.nodes.get(id))
6477
+ .filter((n) => !!n && n.filePath === filePath && n.startLine >= c.start && n.endLine <= c.end)
6478
+ .flatMap((n) => bodyFocusLines(n));
6479
+ return [...exactFocus, ...(c.spineCallLine ? [c.spineCallLine] : []), ...named];
5116
6480
  };
5117
6481
  /**
5118
6482
  * One cluster's final parts: built, shrunk if it overruns `cap`, then
@@ -5130,8 +6494,29 @@ class ToolHandler {
5130
6494
  * before being windowed. Always >= `cap`, so a cluster that already fits is
5131
6495
  * never touched.
5132
6496
  */
5133
- ceiling = Infinity) => {
6497
+ ceiling = Infinity,
6498
+ /**
6499
+ * What this cluster's INCIDENTAL members may render into, when a cluster
6500
+ * ranked below it holds a member the query asked for — see the selection
6501
+ * loop.
6502
+ */
6503
+ incidentalCap) => {
5134
6504
  const base = dedupeSpans(buildSection(c));
6505
+ // In a cluster holding a member the query asked for, incidental members
6506
+ // are never kept past `ceiling` either. The member shrink estimates on raw
6507
+ // source, which runs well under the rendered size, so it kept helpers the
6508
+ // render then had no room for, and the window back to the ceiling cut in
6509
+ // source order — through the tail of a named body (gin's
6510
+ // `handleHTTPRequest` lost 10 of 71 lines to the helpers above it), or,
6511
+ // when its minimum windows overran a later cluster's room, costing that
6512
+ // cluster its place. Every re-render into an exact room is the same case.
6513
+ const guard = Number.isFinite(ceiling) && c.members.some(isProtectedMember)
6514
+ ? Math.min(incidentalCap ?? Infinity, ceiling)
6515
+ : incidentalCap;
6516
+ // A windowed spine method elides source even when nothing else is cut, so
6517
+ // it counts as shrunk: reported unclipped, the one-file-head-plus-a-call-
6518
+ // site render hid in the diagnostic as a complete section.
6519
+ const windowed = windowsSpineIn(c.start, c.end);
5135
6520
  const bound = (r) => {
5136
6521
  if (!Number.isFinite(ceiling) || sectionText(r.parts).length <= ceiling)
5137
6522
  return r;
@@ -5140,12 +6525,12 @@ class ToolHandler {
5140
6525
  const parts = windowToCeiling(r.parts, ceiling, focusLinesOf(c));
5141
6526
  return { parts, covered: r.covered, shrunk: true };
5142
6527
  };
5143
- if (sectionText(base.parts).length <= cap) {
5144
- return { parts: base.parts, covered: base.covered, shrunk: false };
6528
+ if (sectionText(base.parts).length <= Math.min(cap, guard ?? Infinity)) {
6529
+ return { parts: base.parts, covered: base.covered, shrunk: windowed };
5145
6530
  }
5146
- const shrunk = shrinkCluster(c, cap);
6531
+ const shrunk = shrinkCluster(c, cap, guard);
5147
6532
  if (shrunk === null) {
5148
- return bound({ parts: base.parts, covered: base.covered, shrunk: false });
6533
+ return bound({ parts: base.parts, covered: base.covered, shrunk: windowed });
5149
6534
  }
5150
6535
  const dd = dedupeSpans(shrunk);
5151
6536
  return bound({ parts: dd.parts, covered: dd.covered, shrunk: true });
@@ -5163,10 +6548,15 @@ class ToolHandler {
5163
6548
  const rankedClusters = clusters
5164
6549
  .map((c, i) => ({ idx: i, span: c.end - c.start + 1, c }))
5165
6550
  .sort((a, b) => {
5166
- // Spine clusters first — the rendered call path IS the flow answer, so it
6551
+ // Exact-target clusters first — the def (or span) the agent singled out.
6552
+ // Then spine clusters — the rendered call path IS the flow answer, so it
5167
6553
  // outranks any denser block of peripheral declarations (a low-density entry
5168
6554
  // method must not lose the budget to them). Within spine / within non-spine,
5169
6555
  // the existing importance → density → score → span order holds.
6556
+ const aExact = a.c.maxImportance >= EXACT_IMPORTANCE;
6557
+ const bExact = b.c.maxImportance >= EXACT_IMPORTANCE;
6558
+ if (aExact !== bExact)
6559
+ return (bExact ? 1 : 0) - (aExact ? 1 : 0);
5170
6560
  if (a.c.hasSpine !== b.c.hasSpine)
5171
6561
  return (b.c.hasSpine ? 1 : 0) - (a.c.hasSpine ? 1 : 0);
5172
6562
  if (b.c.maxImportance !== a.c.maxImportance)
@@ -5201,15 +6591,46 @@ class ToolHandler {
5201
6591
  // spine can't run away or starve co-flow files entirely. The 1.5x is drawn
5202
6592
  // from the shared envelope, so it is exactly the overshoot the displacement
5203
6593
  // guard has to fund: past `fundedHeadroom` the extra half-reservation is
5204
- // another file's, not spare room.
5205
- const SPINE_CEILING = Math.min(Math.round(allowance * 1.5), fundedHeadroom);
6594
+ // another file's, not spare room. The half is of `ruleAllowance`: a named
6595
+ // file's spare-room extension is already the budget's last spare byte, and
6596
+ // half again of it ran a 13K-budget response to 19.3K of its 19.5K ceiling.
6597
+ //
6598
+ const SPINE_CEILING = Math.min(Math.max(Math.round(ruleAllowance * 1.5), allowance), fundedHeadroom);
5206
6599
  const chosenIndices = new Set();
5207
6600
  // Final renders (deduped, shrunk where oversize) by cluster index. Computed
5208
6601
  // during selection and reused at emission so the two never disagree.
5209
6602
  const renderedClusters = new Map();
5210
6603
  let anyClusterShrunk = false;
5211
6604
  let projectedChars = 0;
5212
- for (const rc of rankedClusters) {
6605
+ // What the protected members of every cluster ranked BELOW position p cost
6606
+ // to render. Rank orders clusters, not members: among clusters of equal
6607
+ // max importance it prefers density, and density counts every member, so
6608
+ // a named function with unrelated helpers merged around it outranks a
6609
+ // cluster holding that same kind of function alone — the helpers' edge
6610
+ // lines raise its density. Taken whole, the first cluster then spent the
6611
+ // file's budget on the helpers and the isolated named function rendered
6612
+ // nothing. So a cluster's incidental members may only use what is left
6613
+ // once the named members below it are paid for. Its own protected members
6614
+ // are never held back, so the trade-off between two named symbols is the
6615
+ // one rank already made.
6616
+ const owedFrom = new Array(rankedClusters.length + 1).fill(0);
6617
+ for (let p = rankedClusters.length - 1; p >= 0; p--) {
6618
+ owedFrom[p] = owedFrom[p + 1] + protectedCoreCost(rankedClusters[p].c);
6619
+ }
6620
+ // Measured against `fileBudget` even for a spine cluster: the clusters
6621
+ // below it that are not on the spine are held to `fileBudget`, so room a
6622
+ // spine cluster's incidental members take past it is room they never get.
6623
+ const incidentalCapFor = (p, room) => {
6624
+ const owedBelow = owedFrom[p + 1];
6625
+ if (owedBelow === 0)
6626
+ return undefined;
6627
+ const spent = projectedChars + (chosenIndices.size > 0 ? GAP_MARKER.length : 0);
6628
+ return Math.min(room, fileBudget - spent) - owedBelow;
6629
+ };
6630
+ /** Rendered cost of a cluster's EXACT members on their own. */
6631
+ const exactCostOf = (c) => renderedSizeOfKept(c.members.filter((m) => m.importance >= EXACT_IMPORTANCE));
6632
+ for (let p = 0; p < rankedClusters.length; p++) {
6633
+ const rc = rankedClusters[p];
5213
6634
  // The top-ranked cluster is always taken — an empty file section sends the
5214
6635
  // agent to Read, negating the savings. But "always taken" is not "taken at
5215
6636
  // any size": when it overruns the reservation it is SHRUNK to the
@@ -5219,15 +6640,29 @@ class ToolHandler {
5219
6640
  // A spine cluster (the rendered call path) is the flow answer — it may run
5220
6641
  // past the per-file budget up to the spine ceiling; non-spine clusters obey
5221
6642
  // the normal per-file budget.
5222
- const cap = rc.c.hasSpine ? SPINE_CEILING : fileBudget;
6643
+ const cap = rc.c.hasSpine || rc.c.maxImportance >= EXACT_IMPORTANCE ? SPINE_CEILING : fileBudget;
5223
6644
  // CG-30: shrinking keeps the top member whole however big it is, so bound
5224
6645
  // how far that member may overshoot — the same 1.5x-of-reservation bound
5225
6646
  // SPINE_CEILING already draws, never below `cap` (a cluster that fits its
5226
6647
  // cap is never windowed). A spine cluster's cap already IS that bound, so
5227
6648
  // this holds it to it rather than letting the member rule walk past it.
5228
6649
  const ceiling = Math.max(cap, SPINE_CEILING);
6650
+ // Several exact targets can land in different clusters of one big file —
6651
+ // a pinned 13K-line App.tsx merges into a handful of giant clusters, and
6652
+ // `App.triggerRender` and `App.handleCanvasPointerDown` sat in two. The
6653
+ // one ranked first spent the whole cap on its own neighbours and the
6654
+ // other target rendered nothing. So an exact cluster holds back what the
6655
+ // exact clusters ranked BELOW it still owe — never cutting into its own
6656
+ // targets — and each target renders, windowed if it must.
6657
+ const owedExact = rc.c.maxImportance < EXACT_IMPORTANCE ? 0
6658
+ : rankedClusters.slice(p + 1).reduce((n, other) => (other.c.maxImportance < EXACT_IMPORTANCE
6659
+ ? n : n + exactCostOf(other.c) + GAP_MARKER.length), 0);
6660
+ const holdBack = (room) => (owedExact > 0
6661
+ ? Math.min(room, Math.max(exactCostOf(rc.c), room - owedExact))
6662
+ : room);
5229
6663
  if (first) {
5230
- const section = renderCluster(rc.c, cap, ceiling);
6664
+ const firstCap = holdBack(cap);
6665
+ const section = renderCluster(rc.c, firstCap, owedExact > 0 ? firstCap : ceiling, incidentalCapFor(p, firstCap));
5231
6666
  renderedClusters.set(rc.idx, section);
5232
6667
  anyClusterShrunk = anyClusterShrunk || section.shrunk;
5233
6668
  chosenIndices.add(rc.idx);
@@ -5250,10 +6685,10 @@ class ToolHandler {
5250
6685
  // nothing") applied between CLUSTERS. Below `MIN_CHARS` the remainder can't
5251
6686
  // hold one readable block, so it stays a drop rather than a stutter of
5252
6687
  // fragments the next call's dedup then has to shred around.
5253
- const room = cap - projectedChars - GAP_MARKER.length;
6688
+ const room = holdBack(cap - projectedChars - GAP_MARKER.length);
5254
6689
  if (room < exports.EXPLORE_ALLOCATION.MIN_CHARS)
5255
6690
  continue;
5256
- const section = renderCluster(rc.c, room, room);
6691
+ const section = renderCluster(rc.c, room, room, incidentalCapFor(p, room));
5257
6692
  const text = sectionText(section.parts);
5258
6693
  if (text.length === 0)
5259
6694
  continue;
@@ -5269,31 +6704,46 @@ class ToolHandler {
5269
6704
  chosenIndices.add(rc.idx);
5270
6705
  projectedChars += text.length + GAP_MARKER.length;
5271
6706
  }
6707
+ // Gap names (#1711) are paid from what selection left of this file's
6708
+ // budget, never from source: selection measured every gap as bare.
6709
+ const namedGapBudget = Math.max(fileBudget, projectedChars);
5272
6710
  // Emit chosen clusters in source order so the file reads top-to-bottom.
5273
6711
  // Assembled through a function because it may have to run more than once:
5274
6712
  // the fit test below trims the weakest cluster and re-assembles rather
5275
6713
  // than skipping the file (CG-26).
5276
6714
  const assembleSection = (chosen) => {
5277
- let text = '';
6715
+ const parts = [];
5278
6716
  const symbols = [];
5279
- const ranges = [];
5280
6717
  const covered = [];
5281
6718
  for (let i = 0; i < clusters.length; i++) {
5282
6719
  if (!chosen.has(i))
5283
6720
  continue;
5284
6721
  const cluster = clusters[i];
5285
6722
  const section = renderedClusters.get(i);
5286
- const part = sectionText(section.parts);
5287
- if (part.length > 0) {
5288
- if (text.length > 0)
5289
- text += GAP_MARKER;
5290
- text += part;
5291
- }
5292
- ranges.push(...section.parts.map((p) => p.range));
6723
+ parts.push(...section.parts);
5293
6724
  covered.push(...section.covered);
5294
6725
  symbols.push(...cluster.symbols);
5295
6726
  }
5296
- return { text, symbols, ranges, covered };
6727
+ // Every member across ALL clusters (chosen or not) is a candidate for
6728
+ // the header bias — a dropped cluster's symbols used to vanish from
6729
+ // the header entirely (#1711).
6730
+ const memberRefs = [];
6731
+ const seenMember = new Set();
6732
+ for (const c of clusters) {
6733
+ for (const m of c.members) {
6734
+ if (seenMember.has(m.name))
6735
+ continue;
6736
+ seenMember.add(m.name);
6737
+ memberRefs.push({ name: m.name, kind: m.kind, startLine: m.start });
6738
+ }
6739
+ }
6740
+ const ranges = parts.map((p) => p.range);
6741
+ const text = joinPartsWithNamedGaps(filePath, parts, fileIndexNodes, Math.max(0, namedGapBudget - sectionText(parts).length));
6742
+ // Header bias prefers RELEVANT elisions (cluster members the trim cut)
6743
+ // over incidental index filler — otherwise locale-sorted `calls0`…
6744
+ // crowds out the answer methods (#1711).
6745
+ const elided = symbolsNotInRanges(memberRefs, ranges);
6746
+ return { text, symbols, ranges, covered, elided };
5297
6747
  };
5298
6748
  let assembled = assembleSection(chosenIndices);
5299
6749
  // A chosen cluster is a COMPLETE method-range — we never cut through a body,
@@ -5309,19 +6759,19 @@ class ToolHandler {
5309
6759
  // Dedupe + cap the symbols list shown in the per-file header. Some
5310
6760
  // files (Session.swift in Alamofire) produced 3.4KB symbol lists
5311
6761
  // from cluster scoring + edge-source lines, dwarfing the per-file
5312
- // body cap. Show top names by frequency, with a "+N more" tail.
5313
- const headerFor = (symbols) => {
5314
- const symbolCounts = new Map();
5315
- for (const s of symbols)
5316
- symbolCounts.set(s, (symbolCounts.get(s) ?? 0) + 1);
5317
- const sortedSymbols = [...symbolCounts.entries()]
5318
- .sort((a, b) => b[1] - a[1])
5319
- .map(([name]) => name);
5320
- const headerSymbols = sortedSymbols.slice(0, budget.maxSymbolsInFileHeader);
5321
- const omittedCount = sortedSymbols.length - headerSymbols.length;
5322
- return fileSectionHeader(filePath, omittedCount > 0
5323
- ? `${headerSymbols.join(', ')}, +${omittedCount} more`
5324
- : headerSymbols.join(', '));
6762
+ // body cap. Prefer symbols the trim elided (#1711), then frequency,
6763
+ // with a "+N more" tail.
6764
+ const headerFor = (symbols, elided = [],
6765
+ /** Longest the header may run; fewer names are listed to meet it (never under one). */
6766
+ maxLength = Infinity) => {
6767
+ for (let cap = budget.maxSymbolsInFileHeader;; cap--) {
6768
+ const { shown, omitted } = biasHeaderSymbols(symbols, elided, cap);
6769
+ const header = fileSectionHeader(filePath, omitted > 0
6770
+ ? `${shown.join(', ')}, +${omitted} more`
6771
+ : shown.join(', '));
6772
+ if (header.length <= maxLength || cap <= 1)
6773
+ return header;
6774
+ }
5325
6775
  };
5326
6776
  // Last stop before the hard ceiling. The reservation already bounded cluster
5327
6777
  // selection above, so reaching this means the bounded overshoot (an oversize
@@ -5339,9 +6789,23 @@ class ToolHandler {
5339
6789
  // admitted, reserved and rendered, and would have delivered nothing.
5340
6790
  // Only when the top-ranked cluster alone cannot fit is the file skipped —
5341
6791
  // that one is never sliced mid-method.
5342
- let fileHeader = headerFor(assembled.symbols);
6792
+ let fileHeader = headerFor(assembled.symbols, assembled.elided);
5343
6793
  let chosenNow = chosenIndices;
5344
6794
  const costOfSection = (header, body) => header.length + 2 + (body.length > 0 ? body.length + lang.length + 11 : 0);
6795
+ // Every file was funded for SOURCE against an ESTIMATED header
6796
+ // (`sectionOverhead`: the file's symbol names), and the real one also lists
6797
+ // the edge lines' targets (`filter(calls)`, `QuerySet(imports)`), so it can
6798
+ // run past the estimate. Where the section no longer fits, the header pays
6799
+ // that back first by listing fewer names — a name it drops is still in the
6800
+ // gap markers and the pointer list; a source line the trim drops is not.
6801
+ // Without this, a file above spending exactly its funded line (an exact
6802
+ // target's overshoot, #2063) left the one below its estimate, and the trim
6803
+ // took the difference out of source: 922 of the 1,031 it was owed.
6804
+ let headerLimit = Infinity;
6805
+ if (totalChars + costOfSection(fileHeader, assembled.text) > renderCeiling) {
6806
+ headerLimit = sectionOverhead(filePath, group.nodes) - 2 - lang.length - 11;
6807
+ fileHeader = headerFor(assembled.symbols, assembled.elided, headerLimit);
6808
+ }
5345
6809
  // The weakest cluster is SHRUNK into the room that is left before it is
5346
6810
  // dropped (CG-36). Dropping it whole makes this loop as all-or-nothing as
5347
6811
  // the selection above it was, and at the same cost: on excalidraw's
@@ -5388,7 +6852,7 @@ class ToolHandler {
5388
6852
  chosenNow = trimmed;
5389
6853
  }
5390
6854
  assembled = assembleSection(chosenNow);
5391
- fileHeader = headerFor(assembled.symbols);
6855
+ fileHeader = headerFor(assembled.symbols, assembled.elided, headerLimit);
5392
6856
  anyFileTrimmed = true;
5393
6857
  }
5394
6858
  // One cluster left and still over — by the header estimate's error, at
@@ -5404,6 +6868,26 @@ class ToolHandler {
5404
6868
  - (fileHeader.length + 2 + lang.length + 11);
5405
6869
  if (room > 0) {
5406
6870
  const reshrunk = renderCluster(clusters[idx], room, room);
6871
+ // Every budget upstream charges a gap as a bare GAP_MARKER, but the
6872
+ // joined text NAMES what each gap elides (#1711). A cluster shrunk to
6873
+ // scattered members has dozens of gaps, and their names can outweigh
6874
+ // the source: re-rendered into the room, it still overran, and a
6875
+ // pinned 1,300-line file with every named body inside its render was
6876
+ // skipped whole. Drop whole parts until the REAL text fits instead —
6877
+ // the last one that holds no focus line first, never the final part.
6878
+ const focus = focusLinesOf(clusters[idx]);
6879
+ while (reshrunk.parts.length > 1 && sectionText(reshrunk.parts).length > room) {
6880
+ const holdsFocus = (p) => focus.some((l) => l >= p.range.start && l <= p.range.end);
6881
+ let drop = reshrunk.parts.length - 1;
6882
+ for (let k = reshrunk.parts.length - 1; k >= 0; k--) {
6883
+ if (!holdsFocus(reshrunk.parts[k])) {
6884
+ drop = k;
6885
+ break;
6886
+ }
6887
+ }
6888
+ reshrunk.parts.splice(drop, 1);
6889
+ reshrunk.shrunk = true;
6890
+ }
5407
6891
  renderedClusters.set(idx, reshrunk);
5408
6892
  anyClusterShrunk = anyClusterShrunk || reshrunk.shrunk;
5409
6893
  assembled = assembleSection(chosenNow);
@@ -5435,6 +6919,9 @@ class ToolHandler {
5435
6919
  // Windowing an oversize member elides source too — reporting it as
5436
6920
  // unclipped would hide exactly the cut the diagnostic exists to show.
5437
6921
  clipped: chosenNow.size < clusters.length || anyClusterShrunk,
6922
+ // Every member of every cluster, chosen or not: a dropped cluster, a
6923
+ // shrunk one and a windowed spine all leave a member short.
6924
+ wanted: ranges,
5438
6925
  fullBody: sectionText(fullClusterParts),
5439
6926
  fullRanges: fullClusterParts.map((p) => p.range),
5440
6927
  });
@@ -5539,22 +7026,33 @@ class ToolHandler {
5539
7026
  }
5540
7027
  pointerOmitted = Math.max(0, remainingFiles.length - pointerEntries.length);
5541
7028
  }
5542
- // Completeness signal so agents know they don't need to re-read these files.
5543
- // On small projects the budget gates this off — but if we actually had to
5544
- // trim or drop clusters, surface a brief note so the agent knows it can
5545
- // still Read for more detail.
5546
- const completenessBlock = budget.includeCompletenessSignal
5547
- ? ['', '---', `> **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.`]
5548
- : anyFileTrimmed
5549
- ? ['', `> 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.`]
7029
+ // Completeness signal so agents know they don't need to re-read these files
7030
+ // — claimed only for sections that ARE complete. A trimmed section is
7031
+ // measured from what was sent (`trimmedFiles`), in render order. On small
7032
+ // projects the budget gates the signal off, but a trim still gets a brief
7033
+ // note pointing at the names the gap markers carry.
7034
+ const trimmedShown = renderedFilePaths
7035
+ .filter((fp) => trimmedFiles.has(fp))
7036
+ .map((fp) => ({ filePath: fp, elided: trimmedFiles.get(fp) }));
7037
+ const completenessCandidates = budget.includeCompletenessSignal
7038
+ ? exploreCompletenessNotes(filesIncluded, trimmedShown, [...renderedFilePaths, ...fileGroups.keys()])
7039
+ .map((note) => ['', '---', note])
7040
+ : anyFileTrimmed || trimmedShown.length > 0
7041
+ ? [['', `> Some file sections were trimmed for size. Elided symbols are named inside gap markers as \`name (file:line)\` and preferred in the file header — run another \`codegraph_explore\` (or \`codegraph_node\`) with those exact names for their source.`]]
5550
7042
  : [];
5551
- // Explore budget note based on project size.
7043
+ /** Whether a trimmed section survives in `text` — picks a fallback note's wording after a cut. */
7044
+ const trimmedIn = (text) => trimmedShown.some((t) => text.includes(`${FILE_SECTION_PREFIX}${t.filePath}\``));
7045
+ // Advisory exploration-guidance note based on project size. Deliberately
7046
+ // phrased as guidance, NOT a quota: agents read "budget / remaining calls /
7047
+ // Synthesize once" as a hard cap and stop exploring early, falling back to
7048
+ // grep + Read (which costs more tokens). The server never rejects or
7049
+ // rate-limits extra explore calls, and the note says so explicitly.
5552
7050
  let budgetBlock = [];
5553
7051
  if (budget.includeBudgetNote) {
5554
7052
  try {
5555
7053
  const stats = cg.getStats();
5556
7054
  const callBudget = getExploreBudget(stats.fileCount);
5557
- budgetBlock = ['', `> **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}.`];
7055
+ budgetBlock = ['', `> **Exploration guidance — advisory only, NOT a quota: this project (~${stats.fileCount.toLocaleString()} files indexed) is usually covered in ≈${callBudget} focused explore calls, and extra calls are never rejected or rate-limited.** If the response above does not fully cover your question, run another codegraph_explore on the uncovered symbols — it is cheaper and more complete than Read. Only stop exploring when the response actually covers the flow you asked about.`];
5558
7056
  }
5559
7057
  catch {
5560
7058
  // Stats unavailable — skip budget note
@@ -5568,40 +7066,24 @@ class ToolHandler {
5568
7066
  // one thing: a fixed floor the loop reserves for (the cut note, plus a
5569
7067
  // pointer for every file whose bytes were deliberately WITHHELD — CG-12
5570
7068
  // makes those names load-bearing) and an elastic tail that takes what is
5571
- // left. Assembled in priority order — the do-not-re-read reminder first,
5572
- // then pointers in rank order, then the budget note — and emitted in
5573
- // document order.
5574
- const roomFor = (block) => block.reduce((n, s) => n + s.length + 1, 0);
5575
- let room = hardCeiling - (flow.text.length + lines.join('\n').length);
5576
- const keepCompleteness = completenessBlock.length > 0
5577
- && roomFor(completenessBlock) <= room;
5578
- if (keepCompleteness)
5579
- room -= roomFor(completenessBlock);
5580
- const pointerBlock = [];
5581
- if (pointerEntries.length > 0) {
5582
- const head = [POINTER_HEADER, ''];
5583
- let left = room - roomFor(head);
5584
- if (left >= 0) {
5585
- let taken = 0;
5586
- for (const entry of pointerEntries) {
5587
- // Every entry we do NOT take has to be confessed by the tail line, so
5588
- // the tail's cost is part of taking one less than all of them.
5589
- const dropped = pointerEntries.length - taken - 1 + pointerOmitted;
5590
- const tail = dropped > 0 ? roomFor([`- ... and ${dropped} more files`]) : 0;
5591
- if (entry.length + 1 + tail > left)
5592
- break;
5593
- left -= entry.length + 1;
5594
- taken++;
5595
- }
5596
- if (taken > 0) {
5597
- pointerBlock.push(...head, ...pointerEntries.slice(0, taken));
5598
- const dropped = pointerEntries.length - taken + pointerOmitted;
5599
- if (dropped > 0)
5600
- pointerBlock.push(`- ... and ${dropped} more files`);
5601
- room -= roomFor(pointerBlock);
5602
- }
5603
- }
5604
- }
7069
+ // left. Assembled in priority order — the completeness note and the
7070
+ // pointers by `fitExploreEpilogue`'s rules, then the budget note — and
7071
+ // emitted in document order.
7072
+ const roomFor = roomForLines;
7073
+ // Less what the summary line will grow by when its sentinel is filled in.
7074
+ let room = hardCeiling - (flow.text.length + lines.join('\n').length)
7075
+ - Math.max(0, summaryReserve - SUMMARY_SENTINEL.length);
7076
+ const fitted = fitExploreEpilogue({
7077
+ room,
7078
+ noteCandidates: completenessCandidates,
7079
+ noteYields: trimmedShown.length > 0,
7080
+ pointerEntries,
7081
+ pointerOmitted,
7082
+ });
7083
+ const completenessBlock = fitted.note;
7084
+ const pointerBlock = fitted.pointers;
7085
+ room = fitted.room;
7086
+ const keepCompleteness = completenessBlock.length > 0;
5605
7087
  // Nothing of the pointer list survived, but there WAS one — say so, in the
5606
7088
  // one line that carries its instruction forward.
5607
7089
  const pointersLost = pointerEntries.length > 0 && pointerBlock.length === 0;
@@ -5613,8 +7095,10 @@ class ToolHandler {
5613
7095
  lines.push(...completenessBlock);
5614
7096
  if (keepBudgetNote)
5615
7097
  lines.push(...budgetBlock);
5616
- if (pointersLost && roomFor([EPILOGUE_LOST_NOTE, '']) <= room) {
5617
- lines.push('', EPILOGUE_LOST_NOTE);
7098
+ // Nothing has been cut yet, so every trimmed section is still in the response.
7099
+ const lostNote = exports.EXPLORE_FALLBACK_NOTES.lost[trimmedShown.length > 0 ? 'trimmed' : 'complete'];
7100
+ if (pointersLost && roomFor([lostNote, '']) <= room) {
7101
+ lines.push('', lostNote);
5618
7102
  }
5619
7103
  const output = flow.text + lines.join('\n');
5620
7104
  let finalText;
@@ -5627,7 +7111,7 @@ class ToolHandler {
5627
7111
  const epilogueOnlyCut = epilogueStart < lines.length
5628
7112
  ? flow.text + lines.slice(0, epilogueStart).join('\n')
5629
7113
  : null;
5630
- const EPILOGUE_CUT_NOTE = '\n\n> (Trailing notes omitted for size. The source above is complete and verbatim — treat it as already Read. For anything this call did not cover, run another codegraph_explore with the specific names rather than reading those files.)';
7114
+ const EPILOGUE_CUT_NOTE = exports.EXPLORE_FALLBACK_NOTES.cut[epilogueOnlyCut !== null && trimmedIn(epilogueOnlyCut) ? 'trimmed' : 'complete'];
5631
7115
  if (output.length > hardCeiling
5632
7116
  && epilogueOnlyCut !== null
5633
7117
  && epilogueOnlyCut.length + EPILOGUE_CUT_NOTE.length <= hardCeiling) {
@@ -5644,7 +7128,7 @@ class ToolHandler {
5644
7128
  const lastSection = cut.lastIndexOf('\n' + FILE_SECTION_PREFIX);
5645
7129
  const boundary = lastSection > hardCeiling * 0.5 ? lastSection : cut.lastIndexOf('\n');
5646
7130
  const safe = boundary > 0 ? cut.slice(0, boundary) : cut;
5647
- 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.)';
7131
+ finalText = safe + exports.EXPLORE_FALLBACK_NOTES.truncated[trimmedIn(safe) ? 'trimmed' : 'complete'];
5648
7132
  }
5649
7133
  else {
5650
7134
  finalText = output;
@@ -5676,6 +7160,7 @@ class ToolHandler {
5676
7160
  if (unresolvedPathSpans.length > 0) {
5677
7161
  summaryLine += ` No indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')}.`;
5678
7162
  }
7163
+ summaryLine += setAsideNote;
5679
7164
  finalText = finalText.replace(SUMMARY_SENTINEL, summaryLine);
5680
7165
  // Emit the allocation diagnostic from the FINAL text, so per-file bytes and
5681
7166
  // shares account for the hard-ceiling truncation above (CG-4).
@@ -5702,22 +7187,21 @@ class ToolHandler {
5702
7187
  });
5703
7188
  sourceBytes += emitted.bytes;
5704
7189
  }
5705
- return this.exploreResult(finalText, {
7190
+ // Include graph-only and omitted/deleted files, not just emitted source.
7191
+ const answerPaths = new Set(fileGroups.keys());
7192
+ for (const id of [...flow.pathNodeIds, ...flow.namedNodeIds]) {
7193
+ const node = cg.getNode(id);
7194
+ if (node)
7195
+ answerPaths.add(node.filePath);
7196
+ }
7197
+ const result = this.answerResult(cg, finalText, answerPaths);
7198
+ result[explore_session_state_1.EXPLORE_EMISSION_KEY] = {
5706
7199
  projectRoot,
5707
7200
  query,
5708
7201
  files: emittedFiles,
5709
7202
  sourceBytes,
5710
7203
  responseBytes: finalText.length,
5711
- });
5712
- }
5713
- /**
5714
- * An explore response plus the record of what it emitted (CG-17). The record
5715
- * rides the result only as far as {@link execute}, which files it into the
5716
- * calling session's state and deletes it — see {@link EXPLORE_EMISSION_KEY}.
5717
- */
5718
- exploreResult(text, emission) {
5719
- const result = this.textResult(text);
5720
- result[explore_session_state_1.EXPLORE_EMISSION_KEY] = emission;
7204
+ };
5721
7205
  return result;
5722
7206
  }
5723
7207
  /**
@@ -5844,24 +7328,63 @@ class ToolHandler {
5844
7328
  */
5845
7329
  async handleFileView(cg, fileArg, opts = {}) {
5846
7330
  const normalize = (p) => p.replace(/\\/g, '/').replace(/^(?:\.?\/+)+/, '').replace(/\/+$/, '');
5847
- const wantLower = normalize(fileArg).toLowerCase();
5848
7331
  const allFiles = cg.getFiles();
5849
7332
  if (allFiles.length === 0)
5850
7333
  return this.textResult('No files indexed. Run `codegraph index` first.');
5851
- let resolved = allFiles.find((f) => f.path.toLowerCase() === wantLower);
5852
- let candidates = [];
7334
+ // Resolve ONE spelling of the path against the index: exact, then
7335
+ // suffix-of-path, then substring — narrowing to a single file or handing
7336
+ // back the ambiguous set.
7337
+ const resolveOne = (want) => {
7338
+ const wantLower = normalize(want).toLowerCase();
7339
+ let file = allFiles.find((f) => f.path.toLowerCase() === wantLower);
7340
+ let found = [];
7341
+ if (!file) {
7342
+ found = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
7343
+ if (found.length === 1)
7344
+ file = found[0];
7345
+ }
7346
+ if (!file && found.length === 0) {
7347
+ found = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
7348
+ if (found.length === 1)
7349
+ file = found[0];
7350
+ }
7351
+ return { file, candidates: found };
7352
+ };
7353
+ // Agents and humans paste file references WITH a line suffix — `a.ts:12`,
7354
+ // `a.ts:12-40`, `a.ts#L88`, `a.ts#L12-L40`. explore already strips exactly
7355
+ // these shapes (src/search/query-paths.ts); file-view used to treat them as
7356
+ // part of the filename and report an indexed file as missing (#1831).
7357
+ // The literal spelling is tried FIRST, so a file genuinely named `foo:12`
7358
+ // still resolves to itself; only when that finds nothing is the suffix
7359
+ // stripped, and then the range becomes the read window.
7360
+ const LINE_SUFFIX = /(?::(\d+)(?:-(\d+))?|#L(\d+)(?:-L?(\d+))?)$/;
7361
+ let { file: resolved, candidates } = resolveOne(fileArg);
7362
+ let shownArg = fileArg;
5853
7363
  if (!resolved) {
5854
- candidates = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
5855
- if (candidates.length === 1)
5856
- resolved = candidates[0];
5857
- }
5858
- if (!resolved && candidates.length === 0) {
5859
- candidates = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
5860
- if (candidates.length === 1)
5861
- resolved = candidates[0];
7364
+ const m = LINE_SUFFIX.exec(normalize(fileArg));
7365
+ const stripped = m ? fileArg.slice(0, fileArg.length - m[0].length) : '';
7366
+ const retry = stripped ? resolveOne(stripped) : undefined;
7367
+ if (m && retry && (retry.file || retry.candidates.length > 0)) {
7368
+ resolved = retry.file;
7369
+ candidates = retry.candidates;
7370
+ shownArg = stripped;
7371
+ const startLine = Number(m[1] ?? m[3]);
7372
+ const endRaw = m[2] ?? m[4];
7373
+ const endLine = endRaw === undefined ? undefined : Number(endRaw);
7374
+ if (Number.isFinite(startLine) && startLine > 0) {
7375
+ // An explicit offset/limit from the caller always wins over the
7376
+ // suffix. `:12` alone is a "start here" pointer (Read given only an
7377
+ // offset); `:12-40` pins both ends.
7378
+ opts = {
7379
+ ...opts,
7380
+ offset: opts.offset ?? startLine,
7381
+ limit: opts.limit ?? (endLine !== undefined && endLine >= startLine ? endLine - startLine + 1 : undefined),
7382
+ };
7383
+ }
7384
+ }
5862
7385
  }
5863
7386
  if (!resolved && candidates.length > 1) {
5864
- return this.textResult([`"${fileArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
7387
+ return this.textResult([`"${shownArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
5865
7388
  ...candidates.slice(0, 25).map((f) => `- ${f.path}`)].join('\n'));
5866
7389
  }
5867
7390
  if (!resolved) {
@@ -6110,6 +7633,14 @@ class ToolHandler {
6110
7633
  lines.push(`> ⚠ ${(0, worktree_1.worktreeMismatchWarning)(mismatch).replace(/\n/g, '\n> ')}`, '');
6111
7634
  }
6112
7635
  lines.push(`**Files indexed:** ${stats.fileCount}`, `**Total nodes:** ${stats.nodeCount}`, `**Total edges:** ${stats.edgeCount}`, `**Database size:** ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
7636
+ // Exact CLI-parity change counts are measured on a worker: Git or the
7637
+ // filesystem fallback can stall on a large/busy checkout, but status must
7638
+ // not block the shared daemon's transport (#1959). Unknown is never zero.
7639
+ const lastIndexedAt = cg.getLastIndexedAt();
7640
+ const changes = await (0, index_freshness_1.measurePendingChanges)(cg.getProjectRoot());
7641
+ lines.push(`**Latest file indexed:** ${lastIndexedAt == null ? 'never' : new Date(lastIndexedAt).toISOString()}`, changes
7642
+ ? `**Changes since index:** ${changes.added} added, ${changes.modified} modified, ${changes.removed} removed`
7643
+ : '**Changes since index:** unknown (measurement timed out or failed; do not assume the index is current)');
6113
7644
  // Surface the active SQLite backend (node:sqlite, Node's built-in real
6114
7645
  // SQLite — full WAL + FTS5, no native build).
6115
7646
  lines.push(`**Backend:** node:sqlite (Node built-in) — full WAL + FTS5`);
@@ -6159,7 +7690,10 @@ class ToolHandler {
6159
7690
  // but the index is frozen — call that out explicitly here, the one place an
6160
7691
  // agent asks "is the index caught up?".
6161
7692
  if (cg.isWatcherDegraded()) {
6162
- lines.push('', '**Auto-sync disabled:**', `- ${cg.getWatcherDegradedReason() ?? 'live file watching stopped'}`, '- The index is frozen; Read files directly for current content.');
7693
+ const recovering = cg.isWatcherRecovering();
7694
+ lines.push('', recovering ? '**Auto-sync recovering:**' : '**Auto-sync disabled:**', recovering
7695
+ ? '- File watching restarted; full index catch-up has not completed.'
7696
+ : `- ${cg.getWatcherDegradedReason() ?? 'live file watching stopped'}`, '- The index may be stale; Read files directly for current content.');
6163
7697
  }
6164
7698
  // Per-file freshness — the inverse of the auto-prepended staleness banner
6165
7699
  // (issue #403). Surfacing it inside `status` gives the agent a single
@@ -6175,6 +7709,7 @@ class ToolHandler {
6175
7709
  lines.push(`- ${p.path} (edited ${ageMs}ms ago, ${label})`);
6176
7710
  }
6177
7711
  }
7712
+ // Text only, for the same reason as the stale-answer path (#2088).
6178
7713
  return this.textResult(lines.join('\n'));
6179
7714
  }
6180
7715
  /**
@@ -6347,72 +7882,11 @@ class ToolHandler {
6347
7882
  * Returns the best match and a note about alternatives if any.
6348
7883
  */
6349
7884
  /**
6350
- * Check if a node matches a symbol query.
6351
- *
6352
- * Accepts simple names (`run`) and three flavors of qualifier:
6353
- * - dotted `Session.request` (TS/JS/Python)
6354
- * - colon-pair `stage_apply::run` (Rust, C++, Ruby)
6355
- * - slash `configurator/stage_apply` (path-ish)
6356
- *
6357
- * Multi-level qualifiers compose: `crate::configurator::stage_apply::run`
6358
- * works. Rust path prefixes (`crate`, `super`, `self`) are stripped so
6359
- * the canonical `crate::module::symbol` form resolves.
6360
- *
6361
- * Resolution order, last part must always equal `node.name`:
6362
- * 1. Suffix-match against `qualifiedName` (handles class-scoped methods
6363
- * where the extractor builds the qualified name from the AST stack)
6364
- * 2. File-path containment (handles file-derived modules in Rust/
6365
- * Python — `stage_apply::run` matches a `run` in `stage_apply.rs`)
7885
+ * Check if a node matches a symbol query — see `matchesSymbol` in
7886
+ * `../graph/symbol-lookup`, which owns the rules.
6366
7887
  */
6367
7888
  matchesSymbol(node, symbol) {
6368
- // Erlang arity spelling (`fn/3`, `mod:fn/3` → normalized `mod.fn/3`): when
6369
- // the node's qualifiedName carries an arity (`mod::fn/3`, #1610), the
6370
- // written arity must match it exactly; the remaining comparison then runs
6371
- // on the arity-less spelling. A node with no arity in its qualifiedName
6372
- // keeps the original symbol (a `/` there means a path-ish name instead).
6373
- const aritySpelling = /^(.+)\/(\d{1,3})$/.exec(symbol);
6374
- if (aritySpelling) {
6375
- const nodeArity = /\/(\d{1,3})$/.exec(node.qualifiedName ?? '')?.[1];
6376
- if (nodeArity !== undefined) {
6377
- if (nodeArity !== aritySpelling[2])
6378
- return false;
6379
- symbol = aritySpelling[1];
6380
- }
6381
- }
6382
- // Simple name match
6383
- if (node.name === symbol)
6384
- return true;
6385
- // File basename match (e.g., "product-card" matches "product-card.liquid")
6386
- if (node.kind === 'file' && node.name.replace(/\.[^.]+$/, '') === symbol)
6387
- return true;
6388
- // Qualified-name lookups: split on any supported separator. `\w` keeps
6389
- // identifier chars (incl. `_`) intact; everything else is treated as
6390
- // a separator we tolerate.
6391
- if (!/[.\/]|::/.test(symbol))
6392
- return false;
6393
- const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
6394
- if (parts.length < 2)
6395
- return false;
6396
- const lastPart = parts[parts.length - 1];
6397
- if (node.name !== lastPart)
6398
- return false;
6399
- // Stage 1: qualified-name suffix match. The extractor joins the
6400
- // semantic hierarchy with `::`, so `Session.request` and
6401
- // `Session::request` both become `Session::request` here.
6402
- const colonSuffix = parts.join('::');
6403
- if (node.qualifiedName.includes(colonSuffix))
6404
- return true;
6405
- // Stage 2: file-path containment. Rust modules and Python packages
6406
- // are not in `qualifiedName` — they're encoded in the file path. So
6407
- // `stage_apply::run` matches a `run` in any file whose path
6408
- // contains a `stage_apply` segment (with or without an extension).
6409
- //
6410
- // Filter out Rust path prefixes that have no file-system equivalent.
6411
- const containerHints = parts.slice(0, -1).filter((p) => !RUST_PATH_PREFIXES.has(p));
6412
- if (containerHints.length === 0)
6413
- return false;
6414
- const segments = node.filePath.split('/').filter((s) => s.length > 0);
6415
- return containerHints.every((hint) => segments.some((seg) => seg === hint || seg.replace(/\.[^.]+$/, '') === hint));
7889
+ return (0, symbol_lookup_1.matchesSymbol)(node, symbol);
6416
7890
  }
6417
7891
  /**
6418
7892
  * Find ALL definitions matching a name, ranked, so codegraph_node can return
@@ -6447,7 +7921,7 @@ class ToolHandler {
6447
7921
  // `stage_applyrun` and finds nothing. Re-search by the bare last part and
6448
7922
  // let `matchesSymbol` filter by qualifier.
6449
7923
  if (isQualified && results.length === 0) {
6450
- const tail = lastQualifierPart(symbol);
7924
+ const tail = (0, symbol_lookup_1.lastQualifierPart)(symbol);
6451
7925
  if (tail && tail !== symbol)
6452
7926
  results = cg.searchNodes(tail, { limit });
6453
7927
  }
@@ -6470,57 +7944,12 @@ class ToolHandler {
6470
7944
  /**
6471
7945
  * Find ALL symbols matching a name. Used by callers/callees/impact to aggregate
6472
7946
  * results across all matching symbols (e.g., multiple classes with an `execute` method).
7947
+ *
7948
+ * The resolution itself lives in `../graph/named-symbol-flow`, so the Flow
7949
+ * strip and `codegraph_explore` resolve a written name to the same nodes.
6473
7950
  */
6474
7951
  findAllSymbols(cg, symbol) {
6475
- // Nix option paths: the declaration is stored as `options.<path>` and
6476
- // config writes carry longer/quoted tails (`<path>."git/config".text`),
6477
- // so a dotted option token (`xdg.configFile`, `launchd.user.agents`) has
6478
- // no exact-name node and would degrade to bare-tail FTS soup — burying
6479
- // the declaration hub the nix-option-path edges hang off. Resolve the
6480
- // convention directly: declaration first, then the exact write, then a
6481
- // capped prefix scan of write sites. Three index hits; non-nix graphs
6482
- // fall straight through.
6483
- if (/^[a-z][\w'-]*(?:\.[\w'-]+)+$/.test(symbol)) {
6484
- const optionHits = [
6485
- ...cg.getNodesByName(`options.${symbol}`),
6486
- ...cg.getNodesByName(symbol),
6487
- ...cg.getNodesByNamePrefix(`${symbol}.`, 12),
6488
- ].filter((n) => n.language === 'nix');
6489
- if (optionHits.length > 0) {
6490
- const seen = new Set();
6491
- const nodes = optionHits.filter((n) => !seen.has(n.id) && !!seen.add(n.id)).slice(0, 10);
6492
- return { nodes, note: '' };
6493
- }
6494
- }
6495
- let results = cg.searchNodes(symbol, { limit: 50 });
6496
- // Mirror the fallback in `findSymbol` for qualified queries — FTS
6497
- // strips colons, so a module-qualified lookup needs a second pass
6498
- // by the bare last part.
6499
- if (results.length === 0 && /[.\/]|::/.test(symbol)) {
6500
- const tail = lastQualifierPart(symbol);
6501
- if (tail && tail !== symbol)
6502
- results = cg.searchNodes(tail, { limit: 50 });
6503
- }
6504
- if (results.length === 0) {
6505
- return { nodes: [], note: '' };
6506
- }
6507
- const exactMatches = results.filter(r => this.matchesSymbol(r.node, symbol));
6508
- if (exactMatches.length <= 1) {
6509
- const node = exactMatches[0]?.node ?? results[0].node;
6510
- return { nodes: [node], note: '' };
6511
- }
6512
- // Same generated-file down-rank as findSymbol — keeps callers/callees
6513
- // /impact aggregation aligned (a query against "Send" returns the
6514
- // hand-written implementations before the protobuf scaffold).
6515
- const isGen = cg.generatedFilePredicate(exactMatches.map((r) => r.node.filePath));
6516
- const ranked = [...exactMatches].sort((a, b) => {
6517
- const aGen = isGen(a.node.filePath) ? 1 : 0;
6518
- const bGen = isGen(b.node.filePath) ? 1 : 0;
6519
- return aGen - bGen;
6520
- });
6521
- const locations = ranked.map(r => `${r.node.kind} at ${r.node.filePath}:${r.node.startLine}`);
6522
- const note = `\n\n> **Note:** Aggregated results across ${ranked.length} symbols named "${symbol}": ${locations.join(', ')}`;
6523
- return { nodes: ranked.map(r => r.node), note };
7952
+ return (0, named_symbol_flow_1.findAllSymbols)(cg, symbol);
6524
7953
  }
6525
7954
  /**
6526
7955
  * Truncate output if it exceeds the maximum length