@colbymchenry/codegraph-win32-arm64 1.6.0 → 1.6.1

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 (622) 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 +599 -291
  7. package/lib/dist/bin/codegraph.js.map +1 -1
  8. package/lib/dist/bin/viewer-gate.d.ts +17 -0
  9. package/lib/dist/bin/viewer-gate.d.ts.map +1 -0
  10. package/lib/dist/bin/viewer-gate.js +31 -0
  11. package/lib/dist/bin/viewer-gate.js.map +1 -0
  12. package/lib/dist/context/index.d.ts.map +1 -1
  13. package/lib/dist/context/index.js +43 -2
  14. package/lib/dist/context/index.js.map +1 -1
  15. package/lib/dist/db/index.d.ts +21 -2
  16. package/lib/dist/db/index.d.ts.map +1 -1
  17. package/lib/dist/db/index.js +86 -31
  18. package/lib/dist/db/index.js.map +1 -1
  19. package/lib/dist/db/migrations.d.ts +1 -1
  20. package/lib/dist/db/migrations.d.ts.map +1 -1
  21. package/lib/dist/db/migrations.js +40 -1
  22. package/lib/dist/db/migrations.js.map +1 -1
  23. package/lib/dist/db/queries.d.ts +423 -3
  24. package/lib/dist/db/queries.d.ts.map +1 -1
  25. package/lib/dist/db/queries.js +1026 -33
  26. package/lib/dist/db/queries.js.map +1 -1
  27. package/lib/dist/db/schema.sql +11 -1
  28. package/lib/dist/db/sqlite-adapter.d.ts +2 -0
  29. package/lib/dist/db/sqlite-adapter.d.ts.map +1 -1
  30. package/lib/dist/db/sqlite-adapter.js +56 -7
  31. package/lib/dist/db/sqlite-adapter.js.map +1 -1
  32. package/lib/dist/db/synthesis-stage.d.ts +12 -0
  33. package/lib/dist/db/synthesis-stage.d.ts.map +1 -0
  34. package/lib/dist/db/synthesis-stage.js +89 -0
  35. package/lib/dist/db/synthesis-stage.js.map +1 -0
  36. package/lib/dist/db/wal-valve.d.ts +32 -12
  37. package/lib/dist/db/wal-valve.d.ts.map +1 -1
  38. package/lib/dist/db/wal-valve.js +65 -22
  39. package/lib/dist/db/wal-valve.js.map +1 -1
  40. package/lib/dist/db/wsl-shared-index.d.ts +53 -0
  41. package/lib/dist/db/wsl-shared-index.d.ts.map +1 -0
  42. package/lib/dist/db/wsl-shared-index.js +121 -0
  43. package/lib/dist/db/wsl-shared-index.js.map +1 -0
  44. package/lib/dist/directory.d.ts +101 -2
  45. package/lib/dist/directory.d.ts.map +1 -1
  46. package/lib/dist/directory.js +254 -23
  47. package/lib/dist/directory.js.map +1 -1
  48. package/lib/dist/errors.d.ts +14 -0
  49. package/lib/dist/errors.d.ts.map +1 -1
  50. package/lib/dist/errors.js +16 -1
  51. package/lib/dist/errors.js.map +1 -1
  52. package/lib/dist/extraction/cfml-extractor.d.ts +1 -0
  53. package/lib/dist/extraction/cfml-extractor.d.ts.map +1 -1
  54. package/lib/dist/extraction/cfml-extractor.js +15 -3
  55. package/lib/dist/extraction/cfml-extractor.js.map +1 -1
  56. package/lib/dist/extraction/dfm-extractor.d.ts.map +1 -1
  57. package/lib/dist/extraction/dfm-extractor.js +14 -10
  58. package/lib/dist/extraction/dfm-extractor.js.map +1 -1
  59. package/lib/dist/extraction/extraction-version.d.ts +1 -1
  60. package/lib/dist/extraction/extraction-version.js +1 -1
  61. package/lib/dist/extraction/function-ref.d.ts +6 -4
  62. package/lib/dist/extraction/function-ref.d.ts.map +1 -1
  63. package/lib/dist/extraction/function-ref.js +35 -14
  64. package/lib/dist/extraction/function-ref.js.map +1 -1
  65. package/lib/dist/extraction/grammars.d.ts +38 -0
  66. package/lib/dist/extraction/grammars.d.ts.map +1 -1
  67. package/lib/dist/extraction/grammars.js +77 -1
  68. package/lib/dist/extraction/grammars.js.map +1 -1
  69. package/lib/dist/extraction/index.d.ts +113 -15
  70. package/lib/dist/extraction/index.d.ts.map +1 -1
  71. package/lib/dist/extraction/index.js +599 -132
  72. package/lib/dist/extraction/index.js.map +1 -1
  73. package/lib/dist/extraction/languages/c-cpp.d.ts +58 -0
  74. package/lib/dist/extraction/languages/c-cpp.d.ts.map +1 -1
  75. package/lib/dist/extraction/languages/c-cpp.js +291 -15
  76. package/lib/dist/extraction/languages/c-cpp.js.map +1 -1
  77. package/lib/dist/extraction/languages/dart.d.ts.map +1 -1
  78. package/lib/dist/extraction/languages/dart.js +8 -3
  79. package/lib/dist/extraction/languages/dart.js.map +1 -1
  80. package/lib/dist/extraction/languages/javascript.js +1 -1
  81. package/lib/dist/extraction/languages/javascript.js.map +1 -1
  82. package/lib/dist/extraction/languages/kotlin.d.ts.map +1 -1
  83. package/lib/dist/extraction/languages/kotlin.js +169 -36
  84. package/lib/dist/extraction/languages/kotlin.js.map +1 -1
  85. package/lib/dist/extraction/languages/lua.d.ts.map +1 -1
  86. package/lib/dist/extraction/languages/lua.js +4 -1
  87. package/lib/dist/extraction/languages/lua.js.map +1 -1
  88. package/lib/dist/extraction/languages/python.d.ts.map +1 -1
  89. package/lib/dist/extraction/languages/python.js +71 -0
  90. package/lib/dist/extraction/languages/python.js.map +1 -1
  91. package/lib/dist/extraction/languages/rust.d.ts.map +1 -1
  92. package/lib/dist/extraction/languages/rust.js +3 -0
  93. package/lib/dist/extraction/languages/rust.js.map +1 -1
  94. package/lib/dist/extraction/languages/scala.d.ts.map +1 -1
  95. package/lib/dist/extraction/languages/scala.js +18 -3
  96. package/lib/dist/extraction/languages/scala.js.map +1 -1
  97. package/lib/dist/extraction/languages/typescript.d.ts.map +1 -1
  98. package/lib/dist/extraction/languages/typescript.js +9 -2
  99. package/lib/dist/extraction/languages/typescript.js.map +1 -1
  100. package/lib/dist/extraction/liquid-extractor.d.ts +18 -0
  101. package/lib/dist/extraction/liquid-extractor.d.ts.map +1 -1
  102. package/lib/dist/extraction/liquid-extractor.js +98 -22
  103. package/lib/dist/extraction/liquid-extractor.js.map +1 -1
  104. package/lib/dist/extraction/mybatis-extractor.d.ts.map +1 -1
  105. package/lib/dist/extraction/mybatis-extractor.js +6 -4
  106. package/lib/dist/extraction/mybatis-extractor.js.map +1 -1
  107. package/lib/dist/extraction/syntax-tokens.d.ts +103 -0
  108. package/lib/dist/extraction/syntax-tokens.d.ts.map +1 -0
  109. package/lib/dist/extraction/syntax-tokens.js +381 -0
  110. package/lib/dist/extraction/syntax-tokens.js.map +1 -0
  111. package/lib/dist/extraction/tree-sitter-helpers.d.ts +5 -0
  112. package/lib/dist/extraction/tree-sitter-helpers.d.ts.map +1 -1
  113. package/lib/dist/extraction/tree-sitter-helpers.js +17 -0
  114. package/lib/dist/extraction/tree-sitter-helpers.js.map +1 -1
  115. package/lib/dist/extraction/tree-sitter-types.d.ts +29 -3
  116. package/lib/dist/extraction/tree-sitter-types.d.ts.map +1 -1
  117. package/lib/dist/extraction/tree-sitter.d.ts +96 -17
  118. package/lib/dist/extraction/tree-sitter.d.ts.map +1 -1
  119. package/lib/dist/extraction/tree-sitter.js +820 -82
  120. package/lib/dist/extraction/tree-sitter.js.map +1 -1
  121. package/lib/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  122. package/lib/dist/file-limits.d.ts +40 -0
  123. package/lib/dist/file-limits.d.ts.map +1 -0
  124. package/lib/dist/file-limits.js +147 -0
  125. package/lib/dist/file-limits.js.map +1 -0
  126. package/lib/dist/graph/branch-guards.d.ts +248 -0
  127. package/lib/dist/graph/branch-guards.d.ts.map +1 -0
  128. package/lib/dist/graph/branch-guards.js +2231 -0
  129. package/lib/dist/graph/branch-guards.js.map +1 -0
  130. package/lib/dist/graph/dead-code.d.ts +251 -0
  131. package/lib/dist/graph/dead-code.d.ts.map +1 -0
  132. package/lib/dist/graph/dead-code.js +776 -0
  133. package/lib/dist/graph/dead-code.js.map +1 -0
  134. package/lib/dist/graph/dynamic-boundary-report.d.ts +121 -0
  135. package/lib/dist/graph/dynamic-boundary-report.d.ts.map +1 -0
  136. package/lib/dist/graph/dynamic-boundary-report.js +283 -0
  137. package/lib/dist/graph/dynamic-boundary-report.js.map +1 -0
  138. package/lib/dist/graph/index.d.ts +4 -0
  139. package/lib/dist/graph/index.d.ts.map +1 -1
  140. package/lib/dist/graph/index.js +16 -1
  141. package/lib/dist/graph/index.js.map +1 -1
  142. package/lib/dist/graph/named-symbol-flow.d.ts +125 -0
  143. package/lib/dist/graph/named-symbol-flow.d.ts.map +1 -0
  144. package/lib/dist/graph/named-symbol-flow.js +552 -0
  145. package/lib/dist/graph/named-symbol-flow.js.map +1 -0
  146. package/lib/dist/graph/symbol-lookup.d.ts +83 -0
  147. package/lib/dist/graph/symbol-lookup.d.ts.map +1 -0
  148. package/lib/dist/graph/symbol-lookup.js +181 -0
  149. package/lib/dist/graph/symbol-lookup.js.map +1 -0
  150. package/lib/dist/graph/traversal.d.ts +9 -0
  151. package/lib/dist/graph/traversal.d.ts.map +1 -1
  152. package/lib/dist/graph/traversal.js +61 -35
  153. package/lib/dist/graph/traversal.js.map +1 -1
  154. package/lib/dist/graph/type-hierarchy.d.ts +155 -0
  155. package/lib/dist/graph/type-hierarchy.d.ts.map +1 -0
  156. package/lib/dist/graph/type-hierarchy.js +382 -0
  157. package/lib/dist/graph/type-hierarchy.js.map +1 -0
  158. package/lib/dist/index.d.ts +251 -11
  159. package/lib/dist/index.d.ts.map +1 -1
  160. package/lib/dist/index.js +395 -34
  161. package/lib/dist/index.js.map +1 -1
  162. package/lib/dist/installer/index.d.ts.map +1 -1
  163. package/lib/dist/installer/index.js +3 -2
  164. package/lib/dist/installer/index.js.map +1 -1
  165. package/lib/dist/installer/targets/antigravity.d.ts.map +1 -1
  166. package/lib/dist/installer/targets/antigravity.js +14 -2
  167. package/lib/dist/installer/targets/antigravity.js.map +1 -1
  168. package/lib/dist/installer/targets/claude.d.ts +3 -0
  169. package/lib/dist/installer/targets/claude.d.ts.map +1 -1
  170. package/lib/dist/installer/targets/claude.js +35 -7
  171. package/lib/dist/installer/targets/claude.js.map +1 -1
  172. package/lib/dist/installer/targets/codex.d.ts +2 -1
  173. package/lib/dist/installer/targets/codex.d.ts.map +1 -1
  174. package/lib/dist/installer/targets/codex.js +14 -4
  175. package/lib/dist/installer/targets/codex.js.map +1 -1
  176. package/lib/dist/installer/targets/copilot-cli.d.ts.map +1 -1
  177. package/lib/dist/installer/targets/copilot-cli.js +7 -1
  178. package/lib/dist/installer/targets/copilot-cli.js.map +1 -1
  179. package/lib/dist/installer/targets/opencode.d.ts +16 -5
  180. package/lib/dist/installer/targets/opencode.d.ts.map +1 -1
  181. package/lib/dist/installer/targets/opencode.js +73 -22
  182. package/lib/dist/installer/targets/opencode.js.map +1 -1
  183. package/lib/dist/installer/targets/shared.d.ts +14 -3
  184. package/lib/dist/installer/targets/shared.d.ts.map +1 -1
  185. package/lib/dist/installer/targets/shared.js +39 -11
  186. package/lib/dist/installer/targets/shared.js.map +1 -1
  187. package/lib/dist/installer/targets/types.d.ts +7 -0
  188. package/lib/dist/installer/targets/types.d.ts.map +1 -1
  189. package/lib/dist/mcp/answer-freshness.d.ts +10 -0
  190. package/lib/dist/mcp/answer-freshness.d.ts.map +1 -0
  191. package/lib/dist/mcp/answer-freshness.js +68 -0
  192. package/lib/dist/mcp/answer-freshness.js.map +1 -0
  193. package/lib/dist/mcp/daemon-manager.d.ts.map +1 -1
  194. package/lib/dist/mcp/daemon-manager.js +16 -0
  195. package/lib/dist/mcp/daemon-manager.js.map +1 -1
  196. package/lib/dist/mcp/daemon-paths.d.ts +2 -0
  197. package/lib/dist/mcp/daemon-paths.d.ts.map +1 -1
  198. package/lib/dist/mcp/daemon-paths.js +12 -3
  199. package/lib/dist/mcp/daemon-paths.js.map +1 -1
  200. package/lib/dist/mcp/daemon-registry.d.ts +7 -4
  201. package/lib/dist/mcp/daemon-registry.d.ts.map +1 -1
  202. package/lib/dist/mcp/daemon-registry.js +91 -29
  203. package/lib/dist/mcp/daemon-registry.js.map +1 -1
  204. package/lib/dist/mcp/daemon.d.ts +17 -7
  205. package/lib/dist/mcp/daemon.d.ts.map +1 -1
  206. package/lib/dist/mcp/daemon.js +116 -24
  207. package/lib/dist/mcp/daemon.js.map +1 -1
  208. package/lib/dist/mcp/dynamic-boundaries.d.ts +1 -10
  209. package/lib/dist/mcp/dynamic-boundaries.d.ts.map +1 -1
  210. package/lib/dist/mcp/dynamic-boundaries.js +46 -42
  211. package/lib/dist/mcp/dynamic-boundaries.js.map +1 -1
  212. package/lib/dist/mcp/engine.d.ts +28 -9
  213. package/lib/dist/mcp/engine.d.ts.map +1 -1
  214. package/lib/dist/mcp/engine.js +146 -62
  215. package/lib/dist/mcp/engine.js.map +1 -1
  216. package/lib/dist/mcp/explore-dedup.d.ts +5 -2
  217. package/lib/dist/mcp/explore-dedup.d.ts.map +1 -1
  218. package/lib/dist/mcp/explore-dedup.js +8 -5
  219. package/lib/dist/mcp/explore-dedup.js.map +1 -1
  220. package/lib/dist/mcp/index-freshness-worker.d.ts +2 -0
  221. package/lib/dist/mcp/index-freshness-worker.d.ts.map +1 -0
  222. package/lib/dist/mcp/index-freshness-worker.js +30 -0
  223. package/lib/dist/mcp/index-freshness-worker.js.map +1 -0
  224. package/lib/dist/mcp/index-freshness.d.ts +7 -0
  225. package/lib/dist/mcp/index-freshness.d.ts.map +1 -0
  226. package/lib/dist/mcp/index-freshness.js +94 -0
  227. package/lib/dist/mcp/index-freshness.js.map +1 -0
  228. package/lib/dist/mcp/index.d.ts +3 -1
  229. package/lib/dist/mcp/index.d.ts.map +1 -1
  230. package/lib/dist/mcp/index.js +95 -11
  231. package/lib/dist/mcp/index.js.map +1 -1
  232. package/lib/dist/mcp/liveness-watchdog.d.ts +4 -1
  233. package/lib/dist/mcp/liveness-watchdog.d.ts.map +1 -1
  234. package/lib/dist/mcp/liveness-watchdog.js +11 -2
  235. package/lib/dist/mcp/liveness-watchdog.js.map +1 -1
  236. package/lib/dist/mcp/project-lifecycle.d.ts +9 -0
  237. package/lib/dist/mcp/project-lifecycle.d.ts.map +1 -0
  238. package/lib/dist/mcp/project-lifecycle.js +181 -0
  239. package/lib/dist/mcp/project-lifecycle.js.map +1 -0
  240. package/lib/dist/mcp/proxy.d.ts.map +1 -1
  241. package/lib/dist/mcp/proxy.js +9 -0
  242. package/lib/dist/mcp/proxy.js.map +1 -1
  243. package/lib/dist/mcp/query-pool.d.ts +2 -2
  244. package/lib/dist/mcp/query-pool.d.ts.map +1 -1
  245. package/lib/dist/mcp/query-pool.js +9 -7
  246. package/lib/dist/mcp/query-pool.js.map +1 -1
  247. package/lib/dist/mcp/query-worker.js +2 -2
  248. package/lib/dist/mcp/query-worker.js.map +1 -1
  249. package/lib/dist/mcp/server-instructions.d.ts +1 -1
  250. package/lib/dist/mcp/server-instructions.d.ts.map +1 -1
  251. package/lib/dist/mcp/server-instructions.js +6 -3
  252. package/lib/dist/mcp/server-instructions.js.map +1 -1
  253. package/lib/dist/mcp/startup-handshake.d.ts +3 -1
  254. package/lib/dist/mcp/startup-handshake.d.ts.map +1 -1
  255. package/lib/dist/mcp/startup-handshake.js +10 -2
  256. package/lib/dist/mcp/startup-handshake.js.map +1 -1
  257. package/lib/dist/mcp/tools.d.ts +276 -36
  258. package/lib/dist/mcp/tools.d.ts.map +1 -1
  259. package/lib/dist/mcp/tools.js +2295 -980
  260. package/lib/dist/mcp/tools.js.map +1 -1
  261. package/lib/dist/mcp/writer-lock.d.ts +61 -0
  262. package/lib/dist/mcp/writer-lock.d.ts.map +1 -0
  263. package/lib/dist/mcp/writer-lock.js +260 -0
  264. package/lib/dist/mcp/writer-lock.js.map +1 -0
  265. package/lib/dist/resolution/alias-binding.d.ts +56 -0
  266. package/lib/dist/resolution/alias-binding.d.ts.map +1 -0
  267. package/lib/dist/resolution/alias-binding.js +127 -0
  268. package/lib/dist/resolution/alias-binding.js.map +1 -0
  269. package/lib/dist/resolution/callback-synthesizer.d.ts +23 -1
  270. package/lib/dist/resolution/callback-synthesizer.d.ts.map +1 -1
  271. package/lib/dist/resolution/callback-synthesizer.js +291 -143
  272. package/lib/dist/resolution/callback-synthesizer.js.map +1 -1
  273. package/lib/dist/resolution/cpp-constructor.d.ts +4 -0
  274. package/lib/dist/resolution/cpp-constructor.d.ts.map +1 -0
  275. package/lib/dist/resolution/cpp-constructor.js +123 -0
  276. package/lib/dist/resolution/cpp-constructor.js.map +1 -0
  277. package/lib/dist/resolution/cpp-macro-visibility.d.ts +12 -0
  278. package/lib/dist/resolution/cpp-macro-visibility.d.ts.map +1 -0
  279. package/lib/dist/resolution/cpp-macro-visibility.js +342 -0
  280. package/lib/dist/resolution/cpp-macro-visibility.js.map +1 -0
  281. package/lib/dist/resolution/expo-router-synthesizer.d.ts +32 -0
  282. package/lib/dist/resolution/expo-router-synthesizer.d.ts.map +1 -0
  283. package/lib/dist/resolution/expo-router-synthesizer.js +189 -0
  284. package/lib/dist/resolution/expo-router-synthesizer.js.map +1 -0
  285. package/lib/dist/resolution/frameworks/csharp.d.ts.map +1 -1
  286. package/lib/dist/resolution/frameworks/csharp.js +96 -2
  287. package/lib/dist/resolution/frameworks/csharp.js.map +1 -1
  288. package/lib/dist/resolution/frameworks/expo-router.d.ts +189 -0
  289. package/lib/dist/resolution/frameworks/expo-router.d.ts.map +1 -0
  290. package/lib/dist/resolution/frameworks/expo-router.js +785 -0
  291. package/lib/dist/resolution/frameworks/expo-router.js.map +1 -0
  292. package/lib/dist/resolution/frameworks/express.d.ts.map +1 -1
  293. package/lib/dist/resolution/frameworks/express.js +251 -16
  294. package/lib/dist/resolution/frameworks/express.js.map +1 -1
  295. package/lib/dist/resolution/frameworks/index.d.ts +5 -0
  296. package/lib/dist/resolution/frameworks/index.d.ts.map +1 -1
  297. package/lib/dist/resolution/frameworks/index.js +29 -1
  298. package/lib/dist/resolution/frameworks/index.js.map +1 -1
  299. package/lib/dist/resolution/frameworks/java.d.ts.map +1 -1
  300. package/lib/dist/resolution/frameworks/java.js +79 -47
  301. package/lib/dist/resolution/frameworks/java.js.map +1 -1
  302. package/lib/dist/resolution/frameworks/nestjs.d.ts.map +1 -1
  303. package/lib/dist/resolution/frameworks/nestjs.js +6 -14
  304. package/lib/dist/resolution/frameworks/nestjs.js.map +1 -1
  305. package/lib/dist/resolution/frameworks/nextjs.d.ts +76 -0
  306. package/lib/dist/resolution/frameworks/nextjs.d.ts.map +1 -0
  307. package/lib/dist/resolution/frameworks/nextjs.js +328 -0
  308. package/lib/dist/resolution/frameworks/nextjs.js.map +1 -0
  309. package/lib/dist/resolution/frameworks/object-literal.d.ts +32 -0
  310. package/lib/dist/resolution/frameworks/object-literal.d.ts.map +1 -0
  311. package/lib/dist/resolution/frameworks/object-literal.js +139 -0
  312. package/lib/dist/resolution/frameworks/object-literal.js.map +1 -0
  313. package/lib/dist/resolution/frameworks/package-deps.d.ts +14 -0
  314. package/lib/dist/resolution/frameworks/package-deps.d.ts.map +1 -0
  315. package/lib/dist/resolution/frameworks/package-deps.js +78 -0
  316. package/lib/dist/resolution/frameworks/package-deps.js.map +1 -0
  317. package/lib/dist/resolution/frameworks/python.d.ts.map +1 -1
  318. package/lib/dist/resolution/frameworks/python.js +166 -0
  319. package/lib/dist/resolution/frameworks/python.js.map +1 -1
  320. package/lib/dist/resolution/frameworks/react-native.d.ts +26 -0
  321. package/lib/dist/resolution/frameworks/react-native.d.ts.map +1 -1
  322. package/lib/dist/resolution/frameworks/react-native.js +153 -14
  323. package/lib/dist/resolution/frameworks/react-native.js.map +1 -1
  324. package/lib/dist/resolution/frameworks/react-router.d.ts +46 -0
  325. package/lib/dist/resolution/frameworks/react-router.d.ts.map +1 -0
  326. package/lib/dist/resolution/frameworks/react-router.js +187 -0
  327. package/lib/dist/resolution/frameworks/react-router.js.map +1 -0
  328. package/lib/dist/resolution/frameworks/react.d.ts +2 -1
  329. package/lib/dist/resolution/frameworks/react.d.ts.map +1 -1
  330. package/lib/dist/resolution/frameworks/react.js +188 -139
  331. package/lib/dist/resolution/frameworks/react.js.map +1 -1
  332. package/lib/dist/resolution/frameworks/svelte.d.ts.map +1 -1
  333. package/lib/dist/resolution/frameworks/svelte.js +6 -1
  334. package/lib/dist/resolution/frameworks/svelte.js.map +1 -1
  335. package/lib/dist/resolution/frameworks/sveltekit-router.d.ts +36 -0
  336. package/lib/dist/resolution/frameworks/sveltekit-router.d.ts.map +1 -0
  337. package/lib/dist/resolution/frameworks/sveltekit-router.js +156 -0
  338. package/lib/dist/resolution/frameworks/sveltekit-router.js.map +1 -0
  339. package/lib/dist/resolution/frameworks/tanstack-router.d.ts +84 -0
  340. package/lib/dist/resolution/frameworks/tanstack-router.d.ts.map +1 -0
  341. package/lib/dist/resolution/frameworks/tanstack-router.js +437 -0
  342. package/lib/dist/resolution/frameworks/tanstack-router.js.map +1 -0
  343. package/lib/dist/resolution/frameworks/vue-router.d.ts +82 -0
  344. package/lib/dist/resolution/frameworks/vue-router.d.ts.map +1 -0
  345. package/lib/dist/resolution/frameworks/vue-router.js +377 -0
  346. package/lib/dist/resolution/frameworks/vue-router.js.map +1 -0
  347. package/lib/dist/resolution/import-resolver.d.ts +38 -0
  348. package/lib/dist/resolution/import-resolver.d.ts.map +1 -1
  349. package/lib/dist/resolution/import-resolver.js +376 -26
  350. package/lib/dist/resolution/import-resolver.js.map +1 -1
  351. package/lib/dist/resolution/index.d.ts +89 -25
  352. package/lib/dist/resolution/index.d.ts.map +1 -1
  353. package/lib/dist/resolution/index.js +552 -145
  354. package/lib/dist/resolution/index.js.map +1 -1
  355. package/lib/dist/resolution/js-builtins.d.ts +13 -0
  356. package/lib/dist/resolution/js-builtins.d.ts.map +1 -0
  357. package/lib/dist/resolution/js-builtins.js +46 -0
  358. package/lib/dist/resolution/js-builtins.js.map +1 -0
  359. package/lib/dist/resolution/name-matcher.d.ts +69 -22
  360. package/lib/dist/resolution/name-matcher.d.ts.map +1 -1
  361. package/lib/dist/resolution/name-matcher.js +1902 -87
  362. package/lib/dist/resolution/name-matcher.js.map +1 -1
  363. package/lib/dist/resolution/next-router-synthesizer.d.ts +27 -0
  364. package/lib/dist/resolution/next-router-synthesizer.d.ts.map +1 -0
  365. package/lib/dist/resolution/next-router-synthesizer.js +113 -0
  366. package/lib/dist/resolution/next-router-synthesizer.js.map +1 -0
  367. package/lib/dist/resolution/react-router-synthesizer.d.ts +33 -0
  368. package/lib/dist/resolution/react-router-synthesizer.d.ts.map +1 -0
  369. package/lib/dist/resolution/react-router-synthesizer.js +126 -0
  370. package/lib/dist/resolution/react-router-synthesizer.js.map +1 -0
  371. package/lib/dist/resolution/resolver-pool.d.ts +2 -0
  372. package/lib/dist/resolution/resolver-pool.d.ts.map +1 -1
  373. package/lib/dist/resolution/resolver-pool.js +4 -0
  374. package/lib/dist/resolution/resolver-pool.js.map +1 -1
  375. package/lib/dist/resolution/strip-comments.d.ts +6 -0
  376. package/lib/dist/resolution/strip-comments.d.ts.map +1 -1
  377. package/lib/dist/resolution/strip-comments.js +58 -0
  378. package/lib/dist/resolution/strip-comments.js.map +1 -1
  379. package/lib/dist/resolution/sveltekit-synthesizer.d.ts +58 -0
  380. package/lib/dist/resolution/sveltekit-synthesizer.d.ts.map +1 -0
  381. package/lib/dist/resolution/sveltekit-synthesizer.js +173 -0
  382. package/lib/dist/resolution/sveltekit-synthesizer.js.map +1 -0
  383. package/lib/dist/resolution/synth-utils.d.ts +26 -0
  384. package/lib/dist/resolution/synth-utils.d.ts.map +1 -0
  385. package/lib/dist/resolution/synth-utils.js +75 -0
  386. package/lib/dist/resolution/synth-utils.js.map +1 -0
  387. package/lib/dist/resolution/tanstack-router-synthesizer.d.ts +31 -0
  388. package/lib/dist/resolution/tanstack-router-synthesizer.d.ts.map +1 -0
  389. package/lib/dist/resolution/tanstack-router-synthesizer.js +114 -0
  390. package/lib/dist/resolution/tanstack-router-synthesizer.js.map +1 -0
  391. package/lib/dist/resolution/tier-synthesizer.d.ts +49 -0
  392. package/lib/dist/resolution/tier-synthesizer.d.ts.map +1 -0
  393. package/lib/dist/resolution/tier-synthesizer.js +931 -0
  394. package/lib/dist/resolution/tier-synthesizer.js.map +1 -0
  395. package/lib/dist/resolution/types.d.ts +78 -2
  396. package/lib/dist/resolution/types.d.ts.map +1 -1
  397. package/lib/dist/resolution/types.js +64 -0
  398. package/lib/dist/resolution/types.js.map +1 -1
  399. package/lib/dist/resolution/vue-router-synthesizer.d.ts +30 -0
  400. package/lib/dist/resolution/vue-router-synthesizer.d.ts.map +1 -0
  401. package/lib/dist/resolution/vue-router-synthesizer.js +115 -0
  402. package/lib/dist/resolution/vue-router-synthesizer.js.map +1 -0
  403. package/lib/dist/search/query-paths.d.ts +50 -1
  404. package/lib/dist/search/query-paths.d.ts.map +1 -1
  405. package/lib/dist/search/query-paths.js +227 -12
  406. package/lib/dist/search/query-paths.js.map +1 -1
  407. package/lib/dist/search/query-utils.d.ts +15 -0
  408. package/lib/dist/search/query-utils.d.ts.map +1 -1
  409. package/lib/dist/search/query-utils.js +35 -7
  410. package/lib/dist/search/query-utils.js.map +1 -1
  411. package/lib/dist/sync/watch-policy.d.ts +14 -0
  412. package/lib/dist/sync/watch-policy.d.ts.map +1 -1
  413. package/lib/dist/sync/watch-policy.js +19 -0
  414. package/lib/dist/sync/watch-policy.js.map +1 -1
  415. package/lib/dist/sync/watcher.d.ts +52 -35
  416. package/lib/dist/sync/watcher.d.ts.map +1 -1
  417. package/lib/dist/sync/watcher.js +236 -100
  418. package/lib/dist/sync/watcher.js.map +1 -1
  419. package/lib/dist/telemetry/index.d.ts +4 -2
  420. package/lib/dist/telemetry/index.d.ts.map +1 -1
  421. package/lib/dist/telemetry/index.js +92 -41
  422. package/lib/dist/telemetry/index.js.map +1 -1
  423. package/lib/dist/types.d.ts +1 -1
  424. package/lib/dist/types.d.ts.map +1 -1
  425. package/lib/dist/types.js +1 -0
  426. package/lib/dist/types.js.map +1 -1
  427. package/lib/dist/ui-server/api/deadcode.d.ts +84 -0
  428. package/lib/dist/ui-server/api/deadcode.d.ts.map +1 -0
  429. package/lib/dist/ui-server/api/deadcode.js +136 -0
  430. package/lib/dist/ui-server/api/deadcode.js.map +1 -0
  431. package/lib/dist/ui-server/api/effects.d.ts +87 -0
  432. package/lib/dist/ui-server/api/effects.d.ts.map +1 -0
  433. package/lib/dist/ui-server/api/effects.js +499 -0
  434. package/lib/dist/ui-server/api/effects.js.map +1 -0
  435. package/lib/dist/ui-server/api/entrypoints.d.ts +86 -0
  436. package/lib/dist/ui-server/api/entrypoints.d.ts.map +1 -0
  437. package/lib/dist/ui-server/api/entrypoints.js +279 -0
  438. package/lib/dist/ui-server/api/entrypoints.js.map +1 -0
  439. package/lib/dist/ui-server/api/events.d.ts +183 -0
  440. package/lib/dist/ui-server/api/events.d.ts.map +1 -0
  441. package/lib/dist/ui-server/api/events.js +430 -0
  442. package/lib/dist/ui-server/api/events.js.map +1 -0
  443. package/lib/dist/ui-server/api/file.d.ts +66 -0
  444. package/lib/dist/ui-server/api/file.d.ts.map +1 -0
  445. package/lib/dist/ui-server/api/file.js +235 -0
  446. package/lib/dist/ui-server/api/file.js.map +1 -0
  447. package/lib/dist/ui-server/api/filecode.d.ts +126 -0
  448. package/lib/dist/ui-server/api/filecode.d.ts.map +1 -0
  449. package/lib/dist/ui-server/api/filecode.js +205 -0
  450. package/lib/dist/ui-server/api/filecode.js.map +1 -0
  451. package/lib/dist/ui-server/api/flow.d.ts +226 -0
  452. package/lib/dist/ui-server/api/flow.d.ts.map +1 -0
  453. package/lib/dist/ui-server/api/flow.js +612 -0
  454. package/lib/dist/ui-server/api/flow.js.map +1 -0
  455. package/lib/dist/ui-server/api/hierarchy.d.ts +81 -0
  456. package/lib/dist/ui-server/api/hierarchy.d.ts.map +1 -0
  457. package/lib/dist/ui-server/api/hierarchy.js +92 -0
  458. package/lib/dist/ui-server/api/hierarchy.js.map +1 -0
  459. package/lib/dist/ui-server/api/index.d.ts +90 -0
  460. package/lib/dist/ui-server/api/index.d.ts.map +1 -0
  461. package/lib/dist/ui-server/api/index.js +332 -0
  462. package/lib/dist/ui-server/api/index.js.map +1 -0
  463. package/lib/dist/ui-server/api/map.d.ts +238 -0
  464. package/lib/dist/ui-server/api/map.d.ts.map +1 -0
  465. package/lib/dist/ui-server/api/map.js +681 -0
  466. package/lib/dist/ui-server/api/map.js.map +1 -0
  467. package/lib/dist/ui-server/api/node.d.ts +81 -0
  468. package/lib/dist/ui-server/api/node.d.ts.map +1 -0
  469. package/lib/dist/ui-server/api/node.js +388 -0
  470. package/lib/dist/ui-server/api/node.js.map +1 -0
  471. package/lib/dist/ui-server/api/nodes.d.ts +25 -0
  472. package/lib/dist/ui-server/api/nodes.d.ts.map +1 -0
  473. package/lib/dist/ui-server/api/nodes.js +45 -0
  474. package/lib/dist/ui-server/api/nodes.js.map +1 -0
  475. package/lib/dist/ui-server/api/program.d.ts +139 -0
  476. package/lib/dist/ui-server/api/program.d.ts.map +1 -0
  477. package/lib/dist/ui-server/api/program.js +315 -0
  478. package/lib/dist/ui-server/api/program.js.map +1 -0
  479. package/lib/dist/ui-server/api/respond.d.ts +76 -0
  480. package/lib/dist/ui-server/api/respond.d.ts.map +1 -0
  481. package/lib/dist/ui-server/api/respond.js +186 -0
  482. package/lib/dist/ui-server/api/respond.js.map +1 -0
  483. package/lib/dist/ui-server/api/route-roots.d.ts +39 -0
  484. package/lib/dist/ui-server/api/route-roots.d.ts.map +1 -0
  485. package/lib/dist/ui-server/api/route-roots.js +96 -0
  486. package/lib/dist/ui-server/api/route-roots.js.map +1 -0
  487. package/lib/dist/ui-server/api/routes.d.ts +59 -0
  488. package/lib/dist/ui-server/api/routes.d.ts.map +1 -0
  489. package/lib/dist/ui-server/api/routes.js +108 -0
  490. package/lib/dist/ui-server/api/routes.js.map +1 -0
  491. package/lib/dist/ui-server/api/screens.d.ts +117 -0
  492. package/lib/dist/ui-server/api/screens.d.ts.map +1 -0
  493. package/lib/dist/ui-server/api/screens.js +611 -0
  494. package/lib/dist/ui-server/api/screens.js.map +1 -0
  495. package/lib/dist/ui-server/api/search.d.ts +29 -0
  496. package/lib/dist/ui-server/api/search.d.ts.map +1 -0
  497. package/lib/dist/ui-server/api/search.js +232 -0
  498. package/lib/dist/ui-server/api/search.js.map +1 -0
  499. package/lib/dist/ui-server/api/session.d.ts +52 -0
  500. package/lib/dist/ui-server/api/session.d.ts.map +1 -0
  501. package/lib/dist/ui-server/api/session.js +196 -0
  502. package/lib/dist/ui-server/api/session.js.map +1 -0
  503. package/lib/dist/ui-server/api/source.d.ts +200 -0
  504. package/lib/dist/ui-server/api/source.d.ts.map +1 -0
  505. package/lib/dist/ui-server/api/source.js +422 -0
  506. package/lib/dist/ui-server/api/source.js.map +1 -0
  507. package/lib/dist/ui-server/api/stats.d.ts +27 -0
  508. package/lib/dist/ui-server/api/stats.d.ts.map +1 -0
  509. package/lib/dist/ui-server/api/stats.js +164 -0
  510. package/lib/dist/ui-server/api/stats.js.map +1 -0
  511. package/lib/dist/ui-server/api/steps.d.ts +274 -0
  512. package/lib/dist/ui-server/api/steps.d.ts.map +1 -0
  513. package/lib/dist/ui-server/api/steps.js +1446 -0
  514. package/lib/dist/ui-server/api/steps.js.map +1 -0
  515. package/lib/dist/ui-server/api/trail-store.d.ts +142 -0
  516. package/lib/dist/ui-server/api/trail-store.d.ts.map +1 -0
  517. package/lib/dist/ui-server/api/trail-store.js +323 -0
  518. package/lib/dist/ui-server/api/trail-store.js.map +1 -0
  519. package/lib/dist/ui-server/api/trails.d.ts +163 -0
  520. package/lib/dist/ui-server/api/trails.d.ts.map +1 -0
  521. package/lib/dist/ui-server/api/trails.js +369 -0
  522. package/lib/dist/ui-server/api/trails.js.map +1 -0
  523. package/lib/dist/ui-server/api/when.d.ts +125 -0
  524. package/lib/dist/ui-server/api/when.d.ts.map +1 -0
  525. package/lib/dist/ui-server/api/when.js +251 -0
  526. package/lib/dist/ui-server/api/when.js.map +1 -0
  527. package/lib/dist/ui-server/api/wire.d.ts +179 -0
  528. package/lib/dist/ui-server/api/wire.d.ts.map +1 -0
  529. package/lib/dist/ui-server/api/wire.js +231 -0
  530. package/lib/dist/ui-server/api/wire.js.map +1 -0
  531. package/lib/dist/ui-server/assets.d.ts +40 -0
  532. package/lib/dist/ui-server/assets.d.ts.map +1 -0
  533. package/lib/dist/ui-server/assets.js +110 -0
  534. package/lib/dist/ui-server/assets.js.map +1 -0
  535. package/lib/dist/ui-server/constants.d.ts +32 -0
  536. package/lib/dist/ui-server/constants.d.ts.map +1 -0
  537. package/lib/dist/ui-server/constants.js +35 -0
  538. package/lib/dist/ui-server/constants.js.map +1 -0
  539. package/lib/dist/ui-server/highlight/index.d.ts +113 -0
  540. package/lib/dist/ui-server/highlight/index.d.ts.map +1 -0
  541. package/lib/dist/ui-server/highlight/index.js +307 -0
  542. package/lib/dist/ui-server/highlight/index.js.map +1 -0
  543. package/lib/dist/ui-server/highlight/languages.d.ts +36 -0
  544. package/lib/dist/ui-server/highlight/languages.d.ts.map +1 -0
  545. package/lib/dist/ui-server/highlight/languages.js +50 -0
  546. package/lib/dist/ui-server/highlight/languages.js.map +1 -0
  547. package/lib/dist/ui-server/index.d.ts +92 -0
  548. package/lib/dist/ui-server/index.d.ts.map +1 -0
  549. package/lib/dist/ui-server/index.js +399 -0
  550. package/lib/dist/ui-server/index.js.map +1 -0
  551. package/lib/dist/ui-server/open-browser.d.ts +31 -0
  552. package/lib/dist/ui-server/open-browser.d.ts.map +1 -0
  553. package/lib/dist/ui-server/open-browser.js +79 -0
  554. package/lib/dist/ui-server/open-browser.js.map +1 -0
  555. package/lib/dist/ui-server/security.d.ts +127 -0
  556. package/lib/dist/ui-server/security.d.ts.map +1 -0
  557. package/lib/dist/ui-server/security.js +332 -0
  558. package/lib/dist/ui-server/security.js.map +1 -0
  559. package/lib/dist/ui-server/static.d.ts +45 -0
  560. package/lib/dist/ui-server/static.d.ts.map +1 -0
  561. package/lib/dist/ui-server/static.js +165 -0
  562. package/lib/dist/ui-server/static.js.map +1 -0
  563. package/lib/dist/utils.d.ts +14 -2
  564. package/lib/dist/utils.d.ts.map +1 -1
  565. package/lib/dist/utils.js +25 -10
  566. package/lib/dist/utils.js.map +1 -1
  567. package/lib/dist/viewer/assets/archivo-latin-ext-wght-normal-C4zznr8T.woff2 +0 -0
  568. package/lib/dist/viewer/assets/archivo-latin-wght-normal-E0tuGl4L.woff2 +0 -0
  569. package/lib/dist/viewer/assets/archivo-vietnamese-wght-normal-XAtsl5Q_.woff2 +0 -0
  570. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-2syK4fUT.woff +0 -0
  571. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-CBJ8pzag.woff2 +0 -0
  572. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  573. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  574. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  575. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  576. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  577. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  578. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-B4oTjJdl.woff +0 -0
  579. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-CBjNughH.woff2 +0 -0
  580. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  581. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  582. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  583. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  584. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  585. package/lib/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  586. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-italic-66oory27.woff +0 -0
  587. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-italic-BqAiT5Ww.woff2 +0 -0
  588. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  589. package/lib/dist/viewer/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  590. package/lib/dist/viewer/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  591. package/lib/dist/viewer/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  592. package/lib/dist/viewer/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  593. package/lib/dist/viewer/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  594. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-B7_fu1kp.woff2 +0 -0
  595. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-Bg0ZHwF4.woff +0 -0
  596. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  597. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  598. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  599. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  600. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  601. package/lib/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  602. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-D6eaYXMU.woff +0 -0
  603. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-DRuN92E5.woff2 +0 -0
  604. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  605. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  606. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  607. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  608. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  609. package/lib/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  610. package/lib/dist/viewer/assets/index-CF9yvio6.css +1 -0
  611. package/lib/dist/viewer/assets/index-D4S7YUPf.js +97 -0
  612. package/lib/dist/viewer/index.html +16 -0
  613. package/lib/kernel/codegraph-kernel.node +2 -2
  614. package/lib/node_modules/.package-lock.json +4 -4
  615. package/lib/node_modules/picomatch/README.md +56 -51
  616. package/lib/node_modules/picomatch/lib/constants.js +4 -0
  617. package/lib/node_modules/picomatch/lib/parse.js +341 -1
  618. package/lib/node_modules/picomatch/lib/picomatch.js +25 -5
  619. package/lib/node_modules/picomatch/lib/scan.js +30 -18
  620. package/lib/node_modules/picomatch/package.json +4 -4
  621. package/lib/package.json +9 -2
  622. 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,23 @@ 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;
1108
1592
  /**
1109
1593
  * Tool handler that executes tools against a CodeGraph instance
1110
1594
  *
@@ -1113,8 +1597,19 @@ const DEFAULT_MCP_TOOLS = new Set(['explore']);
1113
1597
  */
1114
1598
  class ToolHandler {
1115
1599
  cg;
1116
- // Cache of opened CodeGraph instances for cross-project queries
1600
+ // Cache of opened CodeGraph instances for cross-project queries, keyed by the
1601
+ // CANONICAL (realpath) index root. Map insertion order doubles as LRU order:
1602
+ // a hit re-inserts, and `MAX_CACHED_PROJECTS` bounds the size (#1835).
1117
1603
  projectCache = new Map();
1604
+ // Engine hook that watches + catches up an explicit project (null for the
1605
+ // CLI and worker-thread handlers, which never own a watcher).
1606
+ projectLifecycle = null;
1607
+ // Every concurrent call shares its project's pending catch-up promise.
1608
+ projectGates = new Map();
1609
+ activeCalls = 0;
1610
+ closing = false;
1611
+ pendingCloses = 0;
1612
+ closeWaiters = [];
1118
1613
  // The directory the server last searched for a default project. Surfaced in
1119
1614
  // the "not initialized" error so users can see why detection missed.
1120
1615
  defaultProjectHint = null;
@@ -1125,6 +1620,10 @@ class ToolHandler {
1125
1620
  // retry) — tool calls themselves never scan.
1126
1621
  knownSubprojects = [];
1127
1622
  knownSubprojectsBase = null;
1623
+ // Why the default project failed to open, when that is worth telling the
1624
+ // agent instead of "no project loaded" — today only the Windows/WSL
1625
+ // shared-index error (#995). Engine-maintained; cleared by a successful open.
1626
+ defaultOpenFailure = null;
1128
1627
  // Per-start-path cache of the git worktree/index mismatch (issue #155). The
1129
1628
  // mismatch is a fixed property of (where the request came from → which
1130
1629
  // .codegraph/ it resolves to), so the up-to-two `git rev-parse` spawns run
@@ -1138,31 +1637,47 @@ class ToolHandler {
1138
1637
  // per-file staleness banner can't help, because `getPendingFiles()` is
1139
1638
  // populated by the watcher, not by catch-up. The wait is time-boxed
1140
1639
  // (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.
1640
+ // huge repo can't hang a call (#905); cleared when the reconcile settles.
1143
1641
  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).
1642
+ // Engine hook fired when `freshen` reopened a replaced database (#1902), so
1643
+ // the engine can reconcile the new file with a catch-up sync.
1644
+ onDatabaseReopened = null;
1645
+ // Optional worker-thread pool for off-loop read-tool dispatch. When ready +
1646
+ // healthy, heavy reads leave the main loop free for the MCP transport.
1148
1647
  queryPool = null;
1149
1648
  constructor(cg) {
1150
1649
  this.cg = cg;
1151
1650
  }
1152
1651
  /**
1153
1652
  * 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
1653
+ * engine sets this after resolving its default project; the workers each
1155
1654
  * hold their own WAL read connection and run {@link executeReadTool}. A
1156
1655
  * worker's own ToolHandler never has a pool, so there is no nested off-loading.
1157
1656
  */
1158
1657
  setQueryPool(pool) {
1159
1658
  this.queryPool = pool;
1160
1659
  }
1660
+ /**
1661
+ * Engine-only: own the lifecycle (watcher, catch-up, writer lock) of every
1662
+ * project this handler opens for an explicit `projectPath` (#1835).
1663
+ */
1664
+ setProjectLifecycle(lifecycle) {
1665
+ this.projectLifecycle = lifecycle;
1666
+ }
1161
1667
  /**
1162
1668
  * Update the default CodeGraph instance (e.g. after lazy initialization)
1163
1669
  */
1164
1670
  setDefaultCodeGraph(cg) {
1165
1671
  this.cg = cg;
1672
+ this.defaultOpenFailure = null;
1673
+ }
1674
+ /**
1675
+ * Engine-only: record why the default project failed to open (#995), so a
1676
+ * call that needs it answers with that fix rather than "no project loaded".
1677
+ * `null` clears it.
1678
+ */
1679
+ setDefaultOpenFailure(err) {
1680
+ this.defaultOpenFailure = err;
1166
1681
  }
1167
1682
  /**
1168
1683
  * Engine-only: register the catch-up sync promise so the next `execute()`
@@ -1173,6 +1688,21 @@ class ToolHandler {
1173
1688
  */
1174
1689
  setCatchUpGate(p) {
1175
1690
  this.catchUpGate = p;
1691
+ void p?.then(() => {
1692
+ if (this.catchUpGate === p)
1693
+ this.catchUpGate = null;
1694
+ }, () => {
1695
+ if (this.catchUpGate === p)
1696
+ this.catchUpGate = null;
1697
+ });
1698
+ }
1699
+ /**
1700
+ * Engine-only: called after a tool call's {@link freshen} reopened a database
1701
+ * that was replaced on disk (#1902). The engine decides whether a catch-up
1702
+ * sync is its to run (only for the instance it watches and writes).
1703
+ */
1704
+ setOnDatabaseReopened(fn) {
1705
+ this.onDatabaseReopened = fn;
1176
1706
  }
1177
1707
  /**
1178
1708
  * Await the catch-up gate, but no longer than the configured timeout (#905).
@@ -1330,7 +1860,7 @@ class ToolHandler {
1330
1860
  if (tool.name === 'codegraph_explore') {
1331
1861
  return {
1332
1862
  ...tool,
1333
- description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
1863
+ 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
1864
  };
1335
1865
  }
1336
1866
  return tool;
@@ -1352,6 +1882,8 @@ class ToolHandler {
1352
1882
  getCodeGraph(projectPath) {
1353
1883
  if (!projectPath) {
1354
1884
  if (!this.cg) {
1885
+ if (this.defaultOpenFailure)
1886
+ throw this.defaultOpenFailure;
1355
1887
  const searched = this.defaultProjectHint ?? process.cwd();
1356
1888
  throw new NotIndexedError('No CodeGraph project is loaded for this session.\n' +
1357
1889
  `Searched for a .codegraph/ directory starting from: ${searched}\n` +
@@ -1377,7 +1909,7 @@ class ToolHandler {
1377
1909
  if ((0, fs_1.existsSync)(projectPath)) {
1378
1910
  const pathError = (0, utils_1.validateProjectPath)(projectPath);
1379
1911
  if (pathError) {
1380
- throw new PathRefusalError(pathError);
1912
+ throw new errors_2.PathRefusalError(pathError);
1381
1913
  }
1382
1914
  }
1383
1915
  // Always RE-RESOLVE the nearest .codegraph/ from the input path. The walk
@@ -1391,7 +1923,10 @@ class ToolHandler {
1391
1923
  // (#926). The DB connection itself is still cached (by resolved root,
1392
1924
  // below), so re-resolving costs only the stat walk, never a reopen.
1393
1925
  const resolvedRoot = (0, directory_1.findNearestCodeGraphRoot)(projectPath);
1394
- if (!resolvedRoot) {
1926
+ // Two spellings of one root (a symlinked checkout, `/tmp` vs
1927
+ // `/private/tmp`) must share one connection and one watcher (#1835).
1928
+ const canonicalRoot = resolvedRoot ? canonicalPath(resolvedRoot) : null;
1929
+ if (!resolvedRoot || !canonicalRoot) {
1395
1930
  throw new NotIndexedError(`The project at ${projectPath} isn't indexed with codegraph (no .codegraph/ directory found ` +
1396
1931
  'walking up from it), so codegraph cannot query it. Use your built-in tools (Read/Grep/Glob) ' +
1397
1932
  "for that codebase instead, and don't call codegraph for it again this session. " +
@@ -1404,19 +1939,76 @@ class ToolHandler {
1404
1939
  // support) that surfaces as intermittent
1405
1940
  // "database is locked" on concurrent tool calls. See issue #238. The
1406
1941
  // default instance is owned/closed by the server, so it's never cached.
1407
- if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
1942
+ // Another spelling of the same root counts too (#1057).
1943
+ if (this.cg && (0, directory_1.isSameIndexRoot)(this.cg.getProjectRoot(), resolvedRoot)) {
1408
1944
  return this.freshen(this.cg);
1409
1945
  }
1410
- // Cache the open DB connection by RESOLVED ROOT only — never by the input
1946
+ // Cache the open DB connection by CANONICAL ROOT only — never by the input
1411
1947
  // path. One key per instance means closeAll() closes each exactly once, and
1412
1948
  // a changed resolution maps to a different entry instead of a stale hit.
1413
- const cached = this.projectCache.get(resolvedRoot);
1414
- if (cached)
1949
+ const cached = this.projectCache.get(canonicalRoot);
1950
+ if (cached) {
1951
+ // Refresh LRU position.
1952
+ this.projectCache.delete(canonicalRoot);
1953
+ this.projectCache.set(canonicalRoot, cached);
1415
1954
  return this.freshen(cached);
1416
- const cg = loadCodeGraph().openSync(resolvedRoot);
1417
- this.projectCache.set(resolvedRoot, cg);
1955
+ }
1956
+ // Compare current identities on every cache miss: a previously seen alias
1957
+ // may have been retargeted or recreated since the last call (#1057).
1958
+ for (const [root, open] of this.projectCache) {
1959
+ if ((0, directory_1.isSameIndexRoot)(root, resolvedRoot)) {
1960
+ this.projectCache.delete(root);
1961
+ this.projectCache.set(root, open);
1962
+ return this.freshen(open);
1963
+ }
1964
+ }
1965
+ const open = () => loadCodeGraph().openSync(canonicalRoot);
1966
+ const cg = this.projectLifecycle?.open(canonicalRoot, open) ?? open();
1967
+ this.projectCache.set(canonicalRoot, cg);
1968
+ this.trimProjects();
1418
1969
  return cg;
1419
1970
  }
1971
+ async awaitProjectGate(projectPath) {
1972
+ const cg = this.getCodeGraph(projectPath);
1973
+ if (!this.projectLifecycle || cg === this.cg)
1974
+ return;
1975
+ let gate = this.projectGates.get(cg);
1976
+ if (!gate) {
1977
+ gate = this.projectLifecycle.activate(cg).catch(() => { });
1978
+ this.projectGates.set(cg, gate);
1979
+ void gate.then(() => {
1980
+ if (this.projectGates.get(cg) === gate)
1981
+ this.projectGates.delete(cg);
1982
+ this.trimProjects();
1983
+ });
1984
+ }
1985
+ await this.awaitCatchUpGate(gate);
1986
+ }
1987
+ /** Never evict a graph while a tool call or its timed-out reconcile uses it. */
1988
+ trimProjects() {
1989
+ if (this.activeCalls > 0)
1990
+ return;
1991
+ for (const [root, cg] of this.projectCache) {
1992
+ if (!this.closing && this.projectCache.size <= exports.MAX_CACHED_PROJECTS)
1993
+ break;
1994
+ if (this.projectGates.has(cg))
1995
+ continue;
1996
+ this.projectCache.delete(root);
1997
+ if (this.projectLifecycle) {
1998
+ this.pendingCloses++;
1999
+ void Promise.resolve(this.projectLifecycle.release(cg)).finally(() => {
2000
+ this.pendingCloses--;
2001
+ this.trimProjects();
2002
+ });
2003
+ }
2004
+ else
2005
+ cg.close();
2006
+ }
2007
+ if (this.closing && this.projectCache.size === 0 && this.pendingCloses === 0) {
2008
+ for (const resolve of this.closeWaiters.splice(0))
2009
+ resolve();
2010
+ }
2011
+ }
1420
2012
  /**
1421
2013
  * Heal a long-lived connection whose `.codegraph/` was removed and recreated
1422
2014
  * at the same path (a worktree recreated, or `rm -rf .codegraph` + re-init)
@@ -1432,6 +2024,7 @@ class ToolHandler {
1432
2024
  if (cg.reopenIfReplaced()) {
1433
2025
  process.stderr.write('[CodeGraph MCP] The index was replaced on disk (e.g. a git worktree ' +
1434
2026
  'recreated at the same path); reopened the live database in place.\n');
2027
+ this.onDatabaseReopened?.(cg);
1435
2028
  }
1436
2029
  }
1437
2030
  catch {
@@ -1444,11 +2037,12 @@ class ToolHandler {
1444
2037
  * Close all cached project connections
1445
2038
  */
1446
2039
  closeAll() {
1447
- for (const cg of this.projectCache.values()) {
1448
- cg.close();
1449
- }
1450
- this.projectCache.clear();
2040
+ this.closing = true;
1451
2041
  this.worktreeMismatchCache.clear();
2042
+ this.trimProjects();
2043
+ if (this.projectCache.size === 0 && this.activeCalls === 0 && this.pendingCloses === 0)
2044
+ return Promise.resolve();
2045
+ return new Promise((resolve) => this.closeWaiters.push(resolve));
1452
2046
  }
1453
2047
  /**
1454
2048
  * Validate that a value is a non-empty string within length bounds.
@@ -1600,7 +2194,9 @@ class ToolHandler {
1600
2194
  // Same freshness test as the sync fast path (extraction/index.ts):
1601
2195
  // equal size + equal floored mtime ⇒ unchanged, no read needed.
1602
2196
  if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt)) {
1603
- const data = content ?? (0, fs_1.readFileSync)(absPath, 'utf-8');
2197
+ // A file over the index's size limit is stored as its size stamp
2198
+ // (#1910), so it is compared as one, without reading it.
2199
+ const data = (0, file_limits_1.indexedHashInput)(st.size, () => content ?? (0, fs_1.readFileSync)(absPath, 'utf-8'));
1604
2200
  // Must stay byte-identical to extraction's `hashContent` (sha256 over
1605
2201
  // the utf-8 string) — the identical-rewrite test in
1606
2202
  // mcp-stale-slice.test.ts pins the parity. Inlined (not imported)
@@ -1615,6 +2211,14 @@ class ToolHandler {
1615
2211
  this.driftCache.set(key, { at: now, stale });
1616
2212
  return stale;
1617
2213
  }
2214
+ answerResult(cg, text, paths) {
2215
+ const result = this.textResult(text);
2216
+ result._cgAnswerFiles = [...new Set(paths)].map(file => ({
2217
+ path: file,
2218
+ contentHash: cg.getFile(file)?.contentHash ?? null,
2219
+ }));
2220
+ return result;
2221
+ }
1618
2222
  withStalenessNotice(result, projectPath) {
1619
2223
  if (result.isError)
1620
2224
  return result;
@@ -1625,13 +2229,11 @@ class ToolHandler {
1625
2229
  catch {
1626
2230
  return result; // no default project — leave as is
1627
2231
  }
1628
- // Cross-project `projectPath` calls open a cached CodeGraph WITHOUT a
1629
- // watcher (watchers are only attached to the default session project).
2232
+ // A cross-project `projectPath` call's cached CodeGraph only has a watcher
2233
+ // when the engine owns its lifecycle (#1835) — the CLI's handler has none.
1630
2234
  // 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.
2235
+ // default cg, prefer the default cg so the staleness signal still fires
2236
+ // when an agent passes the explicit projectPath form of its own project.
1635
2237
  if (this.cg && cg !== this.cg) {
1636
2238
  try {
1637
2239
  const sameProject = (0, path_1.resolve)(this.cg.getProjectRoot()) === (0, path_1.resolve)(cg.getProjectRoot());
@@ -1646,9 +2248,9 @@ class ToolHandler {
1646
2248
  // stopped, getPendingFiles() is empty so the per-file banner below can't
1647
2249
  // fire — but the index is now FROZEN and silently drifting stale. Surface
1648
2250
  // 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.)
2251
+ // than trusting a response off a no-longer-updating index. (A cross-project
2252
+ // instance without an engine-owned watcher reports false here — correct: we
2253
+ // only know degraded state for a project we watch.)
1652
2254
  let degraded = false;
1653
2255
  try {
1654
2256
  degraded = cg.isWatcherDegraded?.() ?? false;
@@ -1660,6 +2262,10 @@ class ToolHandler {
1660
2262
  const [head, ...tail] = result.content;
1661
2263
  if (!head || head.type !== 'text')
1662
2264
  return result;
2265
+ if (cg.isWatcherRecovering?.()) {
2266
+ const composed = `${formatRecoveringBanner()}\n\n${head.text}`;
2267
+ return { ...result, content: [{ type: 'text', text: composed }, ...tail] };
2268
+ }
1663
2269
  let reason = null;
1664
2270
  try {
1665
2271
  reason = cg.getWatcherDegradedReason?.() ?? null;
@@ -1688,10 +2294,10 @@ class ToolHandler {
1688
2294
  const inResponse = [];
1689
2295
  const elsewhere = [];
1690
2296
  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))
2297
+ // Project-relative POSIX path — the format both the watcher and every
2298
+ // codegraph response emit — matched as a whole path, so a pending
2299
+ // `src/app.ts` isn't "referenced" by a response that shows `src/app.tsx`.
2300
+ if (mentionsPath(text, p.path))
1695
2301
  inResponse.push(p);
1696
2302
  else
1697
2303
  elsewhere.push(p);
@@ -1719,18 +2325,20 @@ class ToolHandler {
1719
2325
  * Omit it (the CLI does) and explore behaves exactly as before, untracked.
1720
2326
  */
1721
2327
  async execute(toolName, args, sessionState) {
2328
+ if (this.closing)
2329
+ return this.textResult('This MCP session is closing; retry with a connected session.');
2330
+ this.activeCalls++;
1722
2331
  try {
1723
2332
  // Block the first tool call on the engine's post-open reconcile so we
1724
2333
  // never serve rows for files deleted/edited while no MCP server was
1725
2334
  // running. The wait is time-boxed (#905): a huge-repo reconcile takes
1726
2335
  // minutes, and blocking the first call on all of it reads as a hang, so
1727
2336
  // we wait briefly then serve and let it finish in the background. The
1728
- // gate is cleared after first await — subsequent calls pay nothing.
2337
+ // gate stays installed until reconciliation settles, including on timeout.
1729
2338
  // Catch-up failures are logged by the engine; we proceed regardless so a
1730
2339
  // transient sync error never breaks tools.
1731
2340
  if (this.catchUpGate) {
1732
2341
  const gate = this.catchUpGate;
1733
- this.catchUpGate = null;
1734
2342
  await this.awaitCatchUpGate(gate);
1735
2343
  }
1736
2344
  // Honor the optional tool allowlist (CODEGRAPH_MCP_TOOLS): a trimmed
@@ -1746,6 +2354,13 @@ class ToolHandler {
1746
2354
  if (typeof pathCheck === 'object' && pathCheck !== undefined) {
1747
2355
  return pathCheck;
1748
2356
  }
2357
+ // An explicit project gets the same first-call guarantee as the default
2358
+ // (#1835): its post-open catch-up sync finishes (time-boxed) before we
2359
+ // serve it. Resolved on the main thread so the watcher lives here even
2360
+ // when dispatch is off-loaded to a worker.
2361
+ if (typeof pathCheck === 'string') {
2362
+ await this.awaitProjectGate(pathCheck);
2363
+ }
1749
2364
  // The `path` and `pattern` properties used by codegraph_files are
1750
2365
  // also path-shaped — apply the same cap.
1751
2366
  if (args.path !== undefined) {
@@ -1758,6 +2373,13 @@ class ToolHandler {
1758
2373
  if (typeof check === 'object' && check !== undefined)
1759
2374
  return check;
1760
2375
  }
2376
+ const project = await this.getCodeGraph(args.projectPath);
2377
+ // Recover a watcher disabled by prolonged lock contention on the next call.
2378
+ // The stale banner remains until the watcher finishes its full scan;
2379
+ // frequent calls cannot bypass its cooldown (#1959).
2380
+ if (project.rearmWatcherAfterLockContention?.()) {
2381
+ process.stderr.write('[CodeGraph MCP] Re-armed file watcher; full catch-up pending.\n');
2382
+ }
1761
2383
  // codegraph_status reports watcher state (pending files, degraded mode,
1762
2384
  // worktree warning) and embeds its own sections — it must run on the MAIN
1763
2385
  // thread against the watched default instance, so it is NEVER off-loaded to
@@ -1767,15 +2389,15 @@ class ToolHandler {
1767
2389
  return await this.handleStatus(args);
1768
2390
  }
1769
2391
  // 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
2392
+ // is attached, healthy, AND has finished its first cold start,
2393
+ // so the server's single event loop stays free for the MCP
1772
2394
  // transport under concurrent load — otherwise N concurrent explores
1773
2395
  // serialize AND starve the transport until the whole batch drains
1774
2396
  // (clients then time out). Before the first worker is warm, calls run
1775
2397
  // in-process: a call queued behind a cold start sat invisible until the
1776
2398
  // 45s busy backstop — the daemon's first tool call stalling for however
1777
2399
  // 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
2400
+ // no pool or a degraded one, dispatch runs in-process
1779
2401
  // exactly as before. Either way the result flows through the
1780
2402
  // cross-cutting notices — worktree-index mismatch (#155) and per-file
1781
2403
  // staleness (#403) — which need the watched MAIN instance and so are
@@ -1787,9 +2409,34 @@ class ToolHandler {
1787
2409
  // structured-clone boundary into a worker, where a closure or a handler
1788
2410
  // field could not follow.
1789
2411
  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)
2412
+ // The default may have appeared after the workers started. Pass the
2413
+ // main thread's current root explicitly; with no root or projectPath,
2414
+ // keep the main handler's workspace-specific not-indexed guidance.
2415
+ const pooled = !!(this.queryPool && this.queryPool.healthy && this.queryPool.ready);
2416
+ const projectPath = pooled ? args.projectPath ?? this.cg?.getProjectRoot() : undefined;
2417
+ const wasDegraded = project.isWatcherDegraded?.();
2418
+ const raw = (pooled && projectPath)
2419
+ ? await this.queryPool.run(toolName, { ...dispatchArgs, projectPath })
1792
2420
  : await this.executeReadTool(toolName, dispatchArgs);
2421
+ const answeredFrom = raw._cgAnswerFiles;
2422
+ delete raw._cgAnswerFiles;
2423
+ if (!raw.isError && answeredFrom && (wasDegraded || project.isWatcherDegraded?.())) {
2424
+ const validation = await (0, answer_freshness_1.validateAnswerFiles)(project.getProjectRoot(), answeredFrom);
2425
+ if (validation.stale.length || validation.unchecked.length) {
2426
+ // Rejected source must not enter the session's emission history.
2427
+ const lines = ['⚠️ CodeGraph cannot answer from this index:'];
2428
+ if (validation.stale.length) {
2429
+ lines.push('These files changed or became unavailable after their last sync:', ...validation.stale.map(file => `- ${file}`));
2430
+ }
2431
+ if (validation.unchecked.length) {
2432
+ lines.push(`Freshness could not be verified within the validation budget for ${validation.unchecked.length} files:`, ...validation.unchecked.slice(0, 20).map(file => `- ${file}`));
2433
+ if (validation.unchecked.length > 20)
2434
+ lines.push(`- … ${validation.unchecked.length - 20} more (narrow the query)`);
2435
+ }
2436
+ lines.push('Retry after a successful codegraph sync, or narrow the query.');
2437
+ return { ...this.textResult(lines.join('\n')), structuredContent: { freshness: validation } };
2438
+ }
2439
+ }
1793
2440
  // Record + STRIP before anything else touches the result: the emission is
1794
2441
  // internal bookkeeping and must never reach the client, whether or not a
1795
2442
  // caller passed session state.
@@ -1801,17 +2448,28 @@ class ToolHandler {
1801
2448
  // Expected condition, not a malfunction: answer as a SUCCESS so the
1802
2449
  // agent keeps trusting the toolset for projects that ARE indexed.
1803
2450
  // (An isError here teaches session-long abandonment — see NotIndexedError.)
1804
- if (err instanceof NotIndexedError) {
2451
+ // A running `codegraph index` rebuild is the same kind of expected,
2452
+ // temporary condition (#1325). Matched by name: tools.ts stays free of
2453
+ // the writer-lock module on the MCP startup path.
2454
+ if (err instanceof NotIndexedError || err?.name === 'RebuildInProgressError') {
1805
2455
  return this.textResult(err.message);
1806
2456
  }
2457
+ // Windows and WSL sharing one index (#995): the user's fix, not a malfunction.
2458
+ if (err instanceof wsl_shared_index_1.WslSharedIndexError) {
2459
+ return this.textResult(wslSharedIndexGuidance(err));
2460
+ }
1807
2461
  // Security refusal: a clean error, no retry encouragement.
1808
- if (err instanceof PathRefusalError) {
2462
+ if (err instanceof errors_2.PathRefusalError) {
1809
2463
  return this.errorResult(err.message);
1810
2464
  }
1811
2465
  return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
1812
2466
  'This is an internal codegraph error — retry the call once; if it persists, ' +
1813
2467
  'continue without codegraph for this task.');
1814
2468
  }
2469
+ finally {
2470
+ this.activeCalls--;
2471
+ this.trimProjects();
2472
+ }
1815
2473
  }
1816
2474
  /**
1817
2475
  * Attach the caller's session view to an explore call's args (CG-17), on a
@@ -1878,7 +2536,10 @@ class ToolHandler {
1878
2536
  if (err instanceof NotIndexedError) {
1879
2537
  return this.textResult(err.message);
1880
2538
  }
1881
- if (err instanceof PathRefusalError) {
2539
+ if (err instanceof wsl_shared_index_1.WslSharedIndexError) {
2540
+ return this.textResult(wslSharedIndexGuidance(err));
2541
+ }
2542
+ if (err instanceof errors_2.PathRefusalError) {
1882
2543
  return this.errorResult(err.message);
1883
2544
  }
1884
2545
  return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
@@ -1936,7 +2597,7 @@ class ToolHandler {
1936
2597
  return aGen - bGen;
1937
2598
  });
1938
2599
  const formatted = this.formatSearchResults(ranked);
1939
- return this.textResult(this.truncateOutput(formatted));
2600
+ return this.answerResult(cg, this.truncateOutput(formatted), ranked.map(r => r.node.filePath));
1940
2601
  }
1941
2602
  /**
1942
2603
  * Group symbol matches into DISTINCT DEFINITIONS — one group per
@@ -1946,28 +2607,7 @@ class ToolHandler {
1946
2607
  * `file` path/suffix first.
1947
2608
  */
1948
2609
  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 };
2610
+ return (0, symbol_lookup_1.groupDefinitions)(nodes, fileFilter);
1971
2611
  }
1972
2612
  /** Section heading for one distinct definition in grouped output. */
1973
2613
  definitionHeading(group) {
@@ -1987,9 +2627,10 @@ class ToolHandler {
1987
2627
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
1988
2628
  const allMatches = this.findAllSymbols(cg, symbol);
1989
2629
  if (allMatches.nodes.length === 0) {
1990
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2630
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
1991
2631
  }
1992
2632
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2633
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
1993
2634
  const filterNote = filteredOut
1994
2635
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
1995
2636
  : '';
@@ -2002,6 +2643,7 @@ class ToolHandler {
2002
2643
  if (!seen.has(c.node.id)) {
2003
2644
  seen.add(c.node.id);
2004
2645
  callers.push(c.node);
2646
+ answerPaths.add(c.node.filePath);
2005
2647
  const label = this.edgeLabel(c.edge);
2006
2648
  if (label)
2007
2649
  labels.set(c.node.id, label);
@@ -2014,13 +2656,18 @@ class ToolHandler {
2014
2656
  if (groups.length === 1) {
2015
2657
  const { callers, labels } = collect(groups[0]);
2016
2658
  if (callers.length === 0) {
2017
- return this.textResult(`No callers found for "${symbol}"${allMatches.note}${filterNote}`);
2659
+ return this.answerResult(cg, `No callers found for "${symbol}"${allMatches.note}${filterNote}`, answerPaths);
2018
2660
  }
2019
2661
  // A successful `file` narrowing makes the multi-symbol aggregation note
2020
2662
  // stale — suppress it.
2021
2663
  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));
2664
+ // Say when the cap cut the list (#1639, #1674): a truncated answer with
2665
+ // no marker reads as the complete set, and an agent under-counts from it.
2666
+ const cut = callers.length > limit
2667
+ ? `\n\n> Showing ${limit} of ${callers.length} callers; pass \`limit\` (up to 100) to widen.`
2668
+ : '';
2669
+ const formatted = this.formatNodeList(callers.slice(0, limit), `Callers of ${symbol}`, labels) + cut + note + filterNote;
2670
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2024
2671
  }
2025
2672
  // Multiple DISTINCT definitions (#764): one section per definition so an
2026
2673
  // agent never mistakes one app's callers for another's. Narrow with
@@ -2040,8 +2687,11 @@ class ToolHandler {
2040
2687
  const label = labels.get(node.id);
2041
2688
  lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
2042
2689
  }
2690
+ if (callers.length > limit) {
2691
+ lines.push(`- … +${callers.length - limit} more (pass \`limit\` to widen)`);
2692
+ }
2043
2693
  }
2044
- return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
2694
+ return this.answerResult(cg, this.truncateOutput(lines.join('\n') + filterNote), answerPaths);
2045
2695
  }
2046
2696
  /**
2047
2697
  * Handle codegraph_callees
@@ -2055,9 +2705,10 @@ class ToolHandler {
2055
2705
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
2056
2706
  const allMatches = this.findAllSymbols(cg, symbol);
2057
2707
  if (allMatches.nodes.length === 0) {
2058
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2708
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
2059
2709
  }
2060
2710
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2711
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
2061
2712
  const filterNote = filteredOut
2062
2713
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
2063
2714
  : '';
@@ -2070,6 +2721,7 @@ class ToolHandler {
2070
2721
  if (!seen.has(c.node.id)) {
2071
2722
  seen.add(c.node.id);
2072
2723
  callees.push(c.node);
2724
+ answerPaths.add(c.node.filePath);
2073
2725
  const label = this.edgeLabel(c.edge);
2074
2726
  if (label)
2075
2727
  labels.set(c.node.id, label);
@@ -2081,13 +2733,18 @@ class ToolHandler {
2081
2733
  if (groups.length === 1) {
2082
2734
  const { callees, labels } = collect(groups[0]);
2083
2735
  if (callees.length === 0) {
2084
- return this.textResult(`No callees found for "${symbol}"${allMatches.note}${filterNote}`);
2736
+ return this.answerResult(cg, `No callees found for "${symbol}"${allMatches.note}${filterNote}`, answerPaths);
2085
2737
  }
2086
2738
  // A successful `file` narrowing makes the multi-symbol aggregation note
2087
2739
  // stale — suppress it.
2088
2740
  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));
2741
+ // Say when the cap cut the list (#1639, #1674): a truncated answer with
2742
+ // no marker reads as the complete set, and an agent under-counts from it.
2743
+ const cut = callees.length > limit
2744
+ ? `\n\n> Showing ${limit} of ${callees.length} callees; pass \`limit\` (up to 100) to widen.`
2745
+ : '';
2746
+ const formatted = this.formatNodeList(callees.slice(0, limit), `Callees of ${symbol}`, labels) + cut + note + filterNote;
2747
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2091
2748
  }
2092
2749
  // Multiple DISTINCT definitions (#764): per-definition sections.
2093
2750
  const lines = [
@@ -2105,8 +2762,11 @@ class ToolHandler {
2105
2762
  const label = labels.get(node.id);
2106
2763
  lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
2107
2764
  }
2765
+ if (callees.length > limit) {
2766
+ lines.push(`- … +${callees.length - limit} more (pass \`limit\` to widen)`);
2767
+ }
2108
2768
  }
2109
- return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
2769
+ return this.answerResult(cg, this.truncateOutput(lines.join('\n') + filterNote), answerPaths);
2110
2770
  }
2111
2771
  /**
2112
2772
  * Handle codegraph_impact
@@ -2120,9 +2780,10 @@ class ToolHandler {
2120
2780
  const fileFilter = typeof args.file === 'string' ? args.file : undefined;
2121
2781
  const allMatches = this.findAllSymbols(cg, symbol);
2122
2782
  if (allMatches.nodes.length === 0) {
2123
- return this.textResult(`Symbol "${symbol}" not found in the codebase`);
2783
+ return this.textResult(`Symbol "${symbol}" not found in the codebase${allMatches.note}`);
2124
2784
  }
2125
2785
  const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
2786
+ const answerPaths = new Set(groups.flat().map(node => node.filePath));
2126
2787
  const filterNote = filteredOut
2127
2788
  ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
2128
2789
  : '';
@@ -2134,6 +2795,7 @@ class ToolHandler {
2134
2795
  const impact = cg.getImpactRadius(node.id, depth);
2135
2796
  for (const [id, n] of impact.nodes) {
2136
2797
  mergedNodes.set(id, n);
2798
+ answerPaths.add(n.filePath);
2137
2799
  }
2138
2800
  for (const e of impact.edges) {
2139
2801
  const key = `${e.source}->${e.target}:${e.kind}`;
@@ -2148,7 +2810,7 @@ class ToolHandler {
2148
2810
  // Single definition (or same-file overloads): the familiar merged report.
2149
2811
  if (groups.length === 1) {
2150
2812
  const formatted = this.formatImpact(symbol, impactOf(groups[0])) + (fileFilter && !filteredOut ? "" : allMatches.note) + filterNote;
2151
- return this.textResult(this.truncateOutput(formatted));
2813
+ return this.answerResult(cg, this.truncateOutput(formatted), answerPaths);
2152
2814
  }
2153
2815
  // Multiple DISTINCT definitions (#764): a blast radius PER definition —
2154
2816
  // merging unrelated same-named classes (one UserService per monorepo app)
@@ -2161,7 +2823,7 @@ class ToolHandler {
2161
2823
  const line = head.startLine ? `:${head.startLine}` : '';
2162
2824
  sections.push('', this.formatImpact(`${head.qualifiedName} (${head.filePath}${line})`, impactOf(group)));
2163
2825
  }
2164
- return this.textResult(this.truncateOutput(sections.join('\n') + filterNote));
2826
+ return this.answerResult(cg, this.truncateOutput(sections.join('\n') + filterNote), answerPaths);
2165
2827
  }
2166
2828
  /**
2167
2829
  * Describe a synthesized (dynamic-dispatch) edge for human output: how the
@@ -2169,6 +2831,33 @@ class ToolHandler {
2169
2831
  * for ordinary static edges. Used by trace + the node trail so a synthesized
2170
2832
  * hop reads as "registered via onUpdate at App.tsx:3148", not a bare arrow.
2171
2833
  */
2834
+ /**
2835
+ * The branch conditions a flow hop's call site runs under, read from the
2836
+ * caller's source now (`graph/branch-guards.ts`); '' when unconditional,
2837
+ * unreadable, or the grammar for that language is not loaded.
2838
+ */
2839
+ whenLabel(cg, caller, edge) {
2840
+ if (!edge.line || !(0, branch_guards_1.supportsBranchGuards)(caller.language))
2841
+ return '';
2842
+ try {
2843
+ const rec = cg.getFile(caller.filePath);
2844
+ if (!rec)
2845
+ return '';
2846
+ const abs = (0, utils_1.validatePathWithinRoot)(cg.getProjectRoot(), caller.filePath);
2847
+ if (!abs)
2848
+ return '';
2849
+ const st = (0, fs_1.statSync)(abs);
2850
+ // Drifted since the index: the recorded line may point elsewhere.
2851
+ if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt))
2852
+ return '';
2853
+ const site = { line: edge.line, column: typeof edge.column === 'number' ? edge.column : null };
2854
+ const g = (0, branch_guards_1.guardsForFileSync)(abs, caller.language, [site]).get((0, branch_guards_1.siteKey)(site));
2855
+ return g ? (0, branch_guards_1.guardLabel)(g) : '';
2856
+ }
2857
+ catch {
2858
+ return '';
2859
+ }
2860
+ }
2172
2861
  synthEdgeNote(edge) {
2173
2862
  if (!edge || edge.provenance !== 'heuristic')
2174
2863
  return null;
@@ -2184,6 +2873,33 @@ class ToolHandler {
2184
2873
  registeredAt,
2185
2874
  };
2186
2875
  }
2876
+ if (m?.synthesizedBy === 'http-client') {
2877
+ const req = `${String(m.method ?? 'GET')} ${String(m.href ?? '')}`.trim();
2878
+ return {
2879
+ label: `HTTP request \`${req}\` — the client's call onto its own route (cross-tier)`,
2880
+ compact: `dynamic: HTTP ${req}${at}`,
2881
+ registeredAt,
2882
+ };
2883
+ }
2884
+ if (m?.synthesizedBy === 'queue-job') {
2885
+ const job = m.event ? `\`${String(m.event)}\`` : 'a job';
2886
+ const queue = m.queue ? ` on queue \`${String(m.queue)}\`` : '';
2887
+ return {
2888
+ label: `queue job ${job}${queue} — producer → consumer (cross-tier)`,
2889
+ compact: `dynamic: queue job ${job}${at}`,
2890
+ registeredAt,
2891
+ };
2892
+ }
2893
+ if (m?.synthesizedBy === 'event-bus') {
2894
+ const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
2895
+ const what = m.channel === 'socket' ? 'socket message' : 'bus event';
2896
+ const dir = m.tier === 'client→server' ? ', client → server' : m.tier === 'server→client' ? ', server → client' : '';
2897
+ return {
2898
+ label: `${what} ${ev} — emit → handler${dir} (dynamic dispatch)`,
2899
+ compact: `dynamic: ${what} ${ev}${at}`,
2900
+ registeredAt,
2901
+ };
2902
+ }
2187
2903
  if (m?.synthesizedBy === 'event-emitter') {
2188
2904
  const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
2189
2905
  return {
@@ -2275,104 +2991,13 @@ class ToolHandler {
2275
2991
  // processRunExecutionData) to the call site instead of dumping the whole body.
2276
2992
  const EMPTY = { text: '', pathNodeIds: new Set(), namedNodeIds: new Set(), uniqueNamedNodeIds: new Set(), spineCallSites: new Map() };
2277
2993
  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)
2994
+ // Token resolution — parsing, overload disambiguation, the CONSTANT/
2995
+ // VARIABLE synth endpoints — is shared with `/api/flow`, so a name written
2996
+ // in the viewer's search box resolves to the same nodes it does here.
2997
+ const flow = (0, named_symbol_flow_1.resolveNamedSymbolFlow)(cg, query);
2998
+ const { named, dynNamed, tokenNodes, tokenFamily, uniqueNamedNodeIds, preciseNamedIds } = flow;
2999
+ if (flow.tokens.length < 2)
2288
3000
  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
3001
  // Surface synthesized (heuristic) edges incident to a named symbol — INCLUDING
2377
3002
  // the non-callable CONSTANT endpoints in `dynNamed`. `skipInChain` drops a hop
2378
3003
  // already shown in the rendered main chain (a 2-node chain renders nothing, so a
@@ -2383,10 +3008,19 @@ class ToolHandler {
2383
3008
  for (const n of [...named.values(), ...dynNamed.values()]) {
2384
3009
  if (synthLines.length >= 6)
2385
3010
  break;
2386
- for (const { node: other, edge } of [...cg.getCallers(n.id), ...cg.getCallees(n.id)]) {
3011
+ // RAW edges for the same reason as hasHeuristicEdge above — a static
3012
+ // edge over the same pair hides the synthesized one from getCallers.
3013
+ const incident = [...cg.getIncomingEdges(n.id), ...cg.getOutgoingEdges(n.id)];
3014
+ for (const edge of incident) {
2387
3015
  if (synthLines.length >= 6)
2388
3016
  break;
2389
- if (edge.provenance !== 'heuristic' || other.id === n.id)
3017
+ if (edge.provenance !== 'heuristic')
3018
+ continue;
3019
+ const otherId = edge.source === n.id ? edge.target : edge.source;
3020
+ if (otherId === n.id)
3021
+ continue;
3022
+ const other = cg.getNode(otherId);
3023
+ if (!other)
2390
3024
  continue;
2391
3025
  if (skipInChain && skipInChain(edge))
2392
3026
  continue;
@@ -2449,63 +3083,16 @@ class ToolHandler {
2449
3083
  out.push('> Full source for these symbols is below.\n');
2450
3084
  return { text: out.join('\n'), pathNodeIds: new Set(), namedNodeIds: new Set([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites: new Map() };
2451
3085
  }
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
- }
3086
+ // The search itself lives in `../graph/named-symbol-flow`, so the viewer's
3087
+ // Flow strip rides exactly this path finder rather than a second one that
3088
+ // could disagree with it. What stays here is the PROSE — the narrative,
3089
+ // the dynamic-dispatch links, the boundary announcements.
3090
+ const best = flow.chains[0]?.steps ?? null;
2497
3091
  const hasMain = !!best && best.length >= 3;
2498
3092
  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
- }
3093
+ // Where each spine node calls the NEXT hop — lets the assembler window an
3094
+ // oversize spine method to the call instead of dumping the whole body.
3095
+ const spineCallSites = flow.chains[0]?.callSites ?? new Map();
2509
3096
  // Dynamic-boundary scan (#687) — fires ONLY when the flow the agent
2510
3097
  // asked about did not fully connect: some token resolved to nodes but
2511
3098
  // none of them sit on the main chain (or there is no chain at all). A
@@ -2584,7 +3171,8 @@ class ToolHandler {
2584
3171
  const step = best[i];
2585
3172
  if (step.edge) {
2586
3173
  const sy = this.synthEdgeNote(step.edge);
2587
- out.push(` ↓ ${sy ? sy.compact : step.edge.kind}`);
3174
+ const when = i > 0 ? this.whenLabel(cg, best[i - 1].node, step.edge) : '';
3175
+ out.push(` ↓ ${sy ? sy.compact : step.edge.kind}${when ? ` (when ${when})` : ''}`);
2588
3176
  }
2589
3177
  out.push(`${i + 1}. ${step.node.name} (${step.node.filePath}:${step.node.startLine})`);
2590
3178
  }
@@ -2622,52 +3210,24 @@ class ToolHandler {
2622
3210
  */
2623
3211
  buildDynamicBoundaries(cg, scanList, named) {
2624
3212
  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
- }
3213
+ // The verdict is not derived here — `findDynamicBoundaries` produces it and
3214
+ // the viewer's end cap renders the same object, so the two can never
3215
+ // disagree about where a flow stops. What is left here is the prose.
3216
+ const reports = (0, dynamic_boundary_report_1.findDynamicBoundaries)(cg, scanList, { named, maxSites: MAX_NOTES });
2634
3217
  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)
3218
+ for (const report of reports) {
3219
+ if (notes.length >= MAX_NOTES)
2640
3220
  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)) {
3221
+ for (const site of report.sites) {
2658
3222
  if (notes.length >= MAX_NOTES)
2659
3223
  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
- }
3224
+ const more = site.moreSites
3225
+ ? ` (+${site.moreSites} more such site${site.moreSites > 1 ? 's' : ''} in this body)`
3226
+ : '';
3227
+ notes.push(`- \`${report.node.name}\` (${report.node.filePath}:${site.line}) — ${site.label}: \`${site.snippet}\`${more}`);
3228
+ const cand = this.boundaryCandidates(site);
3229
+ if (cand)
3230
+ notes.push(` ${cand}`);
2671
3231
  }
2672
3232
  }
2673
3233
  if (notes.length === 0)
@@ -2716,24 +3276,104 @@ class ToolHandler {
2716
3276
  return null;
2717
3277
  }
2718
3278
  };
2719
- const notes = [];
2720
- const seenSuper = new Set();
2721
- for (const { token, family } of candidates) {
2722
- if (notes.length >= MAX_NOTES)
2723
- break;
2724
- // supertype id → how many sampled definers share it + a few example definers
2725
- const supers = new Map();
2726
- for (const m of family.slice(0, SAMPLE)) {
2727
- const container = containerOf(m);
2728
- if (!container || !CLASSY.has(container.kind))
2729
- continue;
2730
- let sups = [];
3279
+ // A supertype dispatches only a member it (or an ancestor) declares. Without
3280
+ // this, any name shared by enough subclasses read as dispatch through their
3281
+ // common base: on vscode the query word `extension`, a getter on unrelated
3282
+ // classes that all extend `Disposable`, was announced as "runtime dispatch to
3283
+ // 2706 types implementing Disposable" at the top of 9 of 31 answers.
3284
+ //
3285
+ // A Swift protocol and each of its extensions are separate nodes of one name,
3286
+ // and a conformer's edge may land on any of them (Alamofire's
3287
+ // `RequestInterceptor` conformers point at an extension in OfflineRetrier.swift
3288
+ // that has no `adapt`), so every same-named type is asked. The answer is
3289
+ // `unknown`, and the announcement stays, whenever absence can't be judged:
3290
+ // nothing on the chain has indexed members of the family's sort, or an
3291
+ // interface/protocol on it has none (Swift requirements aren't nodes, so
3292
+ // `URLRequestConvertible` can't be said to lack `asURLRequest`).
3293
+ const memberOfSupertype = (typeId, name, callable) => {
3294
+ const counts = (kind) => !callable || kind === 'method' || kind === 'function';
3295
+ let sawMembers = false;
3296
+ let opaque = false;
3297
+ const seen = new Set();
3298
+ const visit = (id, depth) => {
3299
+ if (seen.has(id))
3300
+ return false;
3301
+ seen.add(id);
3302
+ let node = null;
3303
+ let edges = [];
2731
3304
  try {
2732
- sups = cg.getOutgoingEdges(container.id)
2733
- .filter((e) => e.kind === 'implements' || e.kind === 'extends')
2734
- .map((e) => { try {
2735
- return cg.getNode(e.target);
2736
- }
3305
+ node = cg.getNode(id);
3306
+ edges = cg.getOutgoingEdges(id);
3307
+ }
3308
+ catch {
3309
+ return false;
3310
+ }
3311
+ let own = 0;
3312
+ for (const e of edges) {
3313
+ if (e.kind !== 'contains')
3314
+ continue;
3315
+ let child = null;
3316
+ try {
3317
+ child = cg.getNode(e.target);
3318
+ }
3319
+ catch {
3320
+ child = null;
3321
+ }
3322
+ if (!child)
3323
+ continue;
3324
+ if (child.name === name)
3325
+ return true;
3326
+ if (counts(child.kind))
3327
+ own++;
3328
+ }
3329
+ if (own > 0)
3330
+ sawMembers = true;
3331
+ else if (node && (node.kind === 'interface' || node.kind === 'protocol' || node.kind === 'trait'))
3332
+ opaque = true;
3333
+ if (depth >= 3)
3334
+ return false;
3335
+ return edges.some((e) => (e.kind === 'extends' || e.kind === 'implements') && visit(e.target, depth + 1));
3336
+ };
3337
+ let root = null;
3338
+ try {
3339
+ root = cg.getNode(typeId);
3340
+ }
3341
+ catch {
3342
+ root = null;
3343
+ }
3344
+ let namesakes = [];
3345
+ try {
3346
+ namesakes = root
3347
+ ? cg.getNodesByName(root.name).filter((n) => n.language === root.language && CLASSY.has(n.kind))
3348
+ : [];
3349
+ }
3350
+ catch {
3351
+ namesakes = [];
3352
+ }
3353
+ if (visit(typeId, 0) || namesakes.some((n) => visit(n.id, 0)))
3354
+ return 'declared';
3355
+ return sawMembers && !opaque ? 'absent' : 'unknown';
3356
+ };
3357
+ const notes = [];
3358
+ const seenSuper = new Set();
3359
+ for (const { token, family } of candidates) {
3360
+ if (notes.length >= MAX_NOTES)
3361
+ break;
3362
+ const memberName = family[0]?.name ?? token;
3363
+ const callableFamily = family[0]?.kind === 'method' || family[0]?.kind === 'function';
3364
+ // supertype id → how many sampled definers share it + a few example definers
3365
+ const supers = new Map();
3366
+ for (const m of family.slice(0, SAMPLE)) {
3367
+ const container = containerOf(m);
3368
+ if (!container || !CLASSY.has(container.kind))
3369
+ continue;
3370
+ let sups = [];
3371
+ try {
3372
+ sups = cg.getOutgoingEdges(container.id)
3373
+ .filter((e) => e.kind === 'implements' || e.kind === 'extends')
3374
+ .map((e) => { try {
3375
+ return cg.getNode(e.target);
3376
+ }
2737
3377
  catch {
2738
3378
  return null;
2739
3379
  } })
@@ -2754,15 +3394,19 @@ class ToolHandler {
2754
3394
  for (const { node, count, targets } of supers.values()) {
2755
3395
  if (count < MIN_SUPPORT)
2756
3396
  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 */ }
3397
+ // The implementer count is `countImplementers` — the same function the
3398
+ // viewer's type-hierarchy fan counts with, so "dispatch to N types
3399
+ // implementing X" is the same N on both surfaces (CG-58). Distinct
3400
+ // types, not edges: a class tied to its supertype by both a parsed
3401
+ // `extends` and a synthesized `implements` is one implementation.
3402
+ const impl = (0, type_hierarchy_1.countImplementers)(cg, node.id);
2762
3403
  if (impl < MIN_IMPL)
2763
3404
  continue;
2764
- if (!best || impl > best.impl)
2765
- best = { node, impl, targets };
3405
+ if (best && impl <= best.impl)
3406
+ continue;
3407
+ if (memberOfSupertype(node.id, memberName, callableFamily) === 'absent')
3408
+ continue;
3409
+ best = { node, impl, targets };
2766
3410
  }
2767
3411
  if (!best || seenSuper.has(best.node.id))
2768
3412
  continue;
@@ -2789,89 +3433,19 @@ class ToolHandler {
2789
3433
  ].join('\n');
2790
3434
  }
2791
3435
  /**
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.
3436
+ * Render the candidate shortlist for a dispatch site as one line.
3437
+ *
3438
+ * The shortlist itself is `shortlistBoundaryCandidates` in
3439
+ * `../graph/dynamic-boundary-report` — shared with the viewer's end cap, so
3440
+ * "candidates for key `save`" names the same symbols in both places. Symbols
3441
+ * the agent already named are marked: that is the "you were right, here's the
3442
+ * wiring" case.
2798
3443
  */
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(', ')}`;
3444
+ boundaryCandidates(site) {
3445
+ if (site.candidates.length === 0)
3446
+ return site.candidateNote ?? '';
3447
+ const list = site.candidates.map((c) => `\`${c.display}\` (${c.node.filePath}:${c.node.startLine})${c.named ? ' ← you named this' : ''}`);
3448
+ return `candidates for key \`${site.key}\`: ${list.join(', ')}`;
2875
3449
  }
2876
3450
  /**
2877
3451
  * Compact "blast radius" for the entry symbols of an explore result: who
@@ -2881,7 +3455,14 @@ class ToolHandler {
2881
3455
  * that have no dependents (nothing to warn about), and returns '' when none
2882
3456
  * qualify so a leaf-only exploration stays clean.
2883
3457
  */
2884
- buildBlastRadiusSection(cg, subgraph) {
3458
+ buildBlastRadiusSection(cg, subgraph,
3459
+ /**
3460
+ * Exact targets (a qualified name, a line anchor) lead the list. The search
3461
+ * roots are whatever FTS ranked first for the bare name, so without this a
3462
+ * query for `SQLCompiler.as_sql` headlined `SQLInsertCompiler.as_sql` — and
3463
+ * the agent took that as the tool having found the wrong method.
3464
+ */
3465
+ leadingIds = []) {
2885
3466
  const ROOT_CAP = 5; // only the symbols the query actually targeted
2886
3467
  const FILE_CAP = 4; // caller files listed per symbol before "+N more"
2887
3468
  const MEANINGFUL = new Set([
@@ -2889,7 +3470,7 @@ class ToolHandler {
2889
3470
  'enum', 'type_alias', 'component', 'constant', 'variable', 'property', 'field',
2890
3471
  ]);
2891
3472
  const rel = (p) => p.replace(/\\/g, '/');
2892
- const roots = subgraph.roots
3473
+ const roots = [...new Set([...leadingIds, ...subgraph.roots])]
2893
3474
  .map((id) => subgraph.nodes.get(id))
2894
3475
  .filter((n) => !!n && MEANINGFUL.has(n.kind))
2895
3476
  .slice(0, ROOT_CAP);
@@ -3011,7 +3592,7 @@ class ToolHandler {
3011
3592
  idx.set(nodeIds[i], i);
3012
3593
  const RANK_EDGES = new Set([
3013
3594
  'calls', 'references', 'extends', 'implements', 'overrides',
3014
- 'instantiates', 'returns', 'type_of', 'imports',
3595
+ 'instantiates', 'returns', 'type_of', 'imports', 'navigates',
3015
3596
  ]);
3016
3597
  const adj = Array.from({ length: n }, () => []);
3017
3598
  for (const e of edges) {
@@ -3092,8 +3673,11 @@ class ToolHandler {
3092
3673
  // pre-#185 behavior for callers that hit the rare stats failure.
3093
3674
  let budget;
3094
3675
  let indexedFileCount = -1;
3676
+ let indexedNodeCount = -1;
3095
3677
  try {
3096
- indexedFileCount = cg.getStats().fileCount;
3678
+ const stats = cg.getStats();
3679
+ indexedFileCount = stats.fileCount;
3680
+ indexedNodeCount = stats.nodeCount;
3097
3681
  budget = getExploreOutputBudget(indexedFileCount);
3098
3682
  }
3099
3683
  catch {
@@ -3110,18 +3694,34 @@ class ToolHandler {
3110
3694
  // `+page.svelte`), starving the very files the agent asked for.
3111
3695
  let pinnedFiles = [];
3112
3696
  let unresolvedPathSpans = [];
3697
+ let lineAnchors = [];
3698
+ let setAsideMatches = [];
3113
3699
  let matchQuery = query;
3114
3700
  if ((0, query_paths_1.queryMightContainPaths)(rawQuery)) {
3115
3701
  try {
3116
- const extraction = (0, query_paths_1.extractQueryPaths)(rawQuery, cg.getFiles().map((f) => f.path), { maxPins: maxFiles });
3702
+ const extraction = (0, query_paths_1.extractQueryPaths)(rawQuery, cg.getFiles().map((f) => f.path), {
3703
+ maxPins: maxFiles,
3704
+ existsOnDisk: (rel) => pathIsProjectFile(projectRoot, rel),
3705
+ symbolFiles: (symbol) => filesDefiningSymbol(cg, symbol),
3706
+ });
3117
3707
  if (extraction.pinnedFiles.length > 0 || extraction.unresolvedPathSpans.length > 0) {
3118
3708
  pinnedFiles = extraction.pinnedFiles;
3119
3709
  unresolvedPathSpans = extraction.unresolvedPathSpans;
3710
+ lineAnchors = extraction.lineAnchors;
3711
+ setAsideMatches = extraction.setAsideMatches;
3120
3712
  matchQuery = normalizeQuerySpelling(extraction.strippedQuery);
3121
3713
  }
3122
3714
  }
3123
3715
  catch { /* path pinning must never fail an explore call */ }
3124
3716
  }
3717
+ // A same-named file the span did not pin is named in the summary line, so
3718
+ // an agent that did mean it sees where it went instead of a silent drop.
3719
+ const setAsideNote = setAsideMatches.map((s) => {
3720
+ const which = s.files.length <= 2
3721
+ ? s.files.map((f) => `\`${f}\``).join(', ')
3722
+ : `${s.files.length} other \`${s.span}\` files`;
3723
+ return ` Not pinned: ${which}, which define${s.files.length === 1 ? 's' : ''} none of the named symbols.`;
3724
+ }).join('');
3125
3725
  const pinnedSet = new Set(pinnedFiles);
3126
3726
  const pinnedOrder = new Map(pinnedFiles.map((p, i) => [p, i]));
3127
3727
  // Per-file allocation diagnostic (CG-4). `null` unless CODEGRAPH_EXPLORE_DEBUG
@@ -3196,17 +3796,87 @@ class ToolHandler {
3196
3796
  .forEach((n) => { if (!subgraph.nodes.has(n.id))
3197
3797
  subgraph.nodes.set(n.id, n); });
3198
3798
  }
3799
+ // EXACT targets: callables the agent pointed at with no ambiguity left — a
3800
+ // qualified name that resolves to at most a handful of defs
3801
+ // (`SQLCompiler.as_sql`, filled in by the seeding loop below) or the
3802
+ // callable enclosing a line anchor (`compiler.py:776`). Every render path
3803
+ // puts these first and never reduces one to a signature line: the agent
3804
+ // has already said which of the 110 `as_sql`s it means, and an answer that
3805
+ // spends the file on the named method's neighbours instead is the one it
3806
+ // Reads the file to get past.
3807
+ const exactNodeIds = new Set();
3808
+ // A multi-line anchor (`lines 900-1003`, `foo.ts:12-40`) names a SPAN, not
3809
+ // a symbol — often the tail of a body a previous response windowed — and
3810
+ // is rendered as exactly that span. A single-line anchor with no enclosing
3811
+ // callable (a module-level line) becomes a small span around the line.
3812
+ const anchorSpans = new Map();
3813
+ for (const anchor of lineAnchors) {
3814
+ let fileNodes = [];
3815
+ try {
3816
+ fileNodes = cg.getNodesInFile(anchor.file);
3817
+ }
3818
+ catch {
3819
+ continue;
3820
+ }
3821
+ if (anchor.start === anchor.end) {
3822
+ const enclosing = fileNodes
3823
+ .filter((n) => ANCHOR_CALLABLE_KINDS.has(n.kind)
3824
+ && n.startLine <= anchor.start && n.endLine >= anchor.start)
3825
+ .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0];
3826
+ if (enclosing) {
3827
+ exactNodeIds.add(enclosing.id);
3828
+ if (!subgraph.nodes.has(enclosing.id))
3829
+ subgraph.nodes.set(enclosing.id, enclosing);
3830
+ continue;
3831
+ }
3832
+ }
3833
+ const span = anchor.start === anchor.end
3834
+ ? { start: Math.max(1, anchor.start - ANCHOR_LINE_CONTEXT), end: anchor.start + ANCHOR_LINE_CONTEXT }
3835
+ : { start: anchor.start, end: anchor.end };
3836
+ const spans = anchorSpans.get(anchor.file) ?? [];
3837
+ spans.push(span);
3838
+ anchorSpans.set(anchor.file, spans);
3839
+ }
3199
3840
  if (subgraph.nodes.size === 0) {
3200
3841
  diag?.finishEmpty('no relevant code found — empty subgraph');
3201
3842
  const missNote = unresolvedPathSpans.length > 0
3202
3843
  ? ` (no indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')})`
3203
3844
  : '';
3204
- const empty = `No relevant code found for "${query}"${missNote}`;
3845
+ let explanation = '\n\nExplore matches symbol/file names and indexed code words lexically, not by meaning.';
3846
+ if (indexedNodeCount === 0) {
3847
+ explanation += '\nThis project has nothing indexed.';
3848
+ }
3849
+ else {
3850
+ const miss = cg.getExploreMissDiagnostics(matchQuery);
3851
+ const list = (words) => words.map(w => `\`${w}\``).join(', ');
3852
+ // Separate caps preserve the retry instruction and complete candidate
3853
+ // names even with long queries or generated identifiers.
3854
+ const cappedList = (words, cap) => {
3855
+ const kept = [];
3856
+ for (const word of words) {
3857
+ if (list([...kept, word]).length > cap)
3858
+ break;
3859
+ kept.push(word);
3860
+ }
3861
+ return list(kept) + (kept.length < words.length ? ' …' : '');
3862
+ };
3863
+ explanation += '\nChecked indexed names, signatures, docstrings (FTS prefixes) and live name segments; not all source text.';
3864
+ if (miss.limited)
3865
+ explanation += '\nWord check limited to 16 words of at most 64 characters.';
3866
+ explanation += `\nNo lexical matches for checked words: ${cappedList(miss.unmatched, 250) || '(none)'}.`;
3867
+ if (miss.matched.length > 0) {
3868
+ explanation += `\nMatched indexed words: ${cappedList(miss.matched, 200)}; these did not yield a relevant result after filtering/scoring.`;
3869
+ }
3870
+ explanation += miss.candidates.length > 0
3871
+ ? `\nCandidates to retry with codegraph_explore (shared words, not confirmed answers): ${cappedList(miss.candidates, 350)}`
3872
+ : '\nNo shared-word symbol candidates found; retry codegraph_explore with literal symbol/file names or code terms.';
3873
+ }
3874
+ const empty = `No relevant code found for "${query}"${missNote}${explanation}`;
3205
3875
  // Still an explore call, so it is still recorded: an empty answer spends a
3206
3876
  // 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
- });
3877
+ return { ...this.textResult(empty), [explore_session_state_1.EXPLORE_EMISSION_KEY]: {
3878
+ projectRoot, query, files: [], sourceBytes: 0, responseBytes: empty.length,
3879
+ } };
3210
3880
  }
3211
3881
  // Graph-aware glue: findRelevantContext builds the subgraph from name/text
3212
3882
  // search, so a method that BRIDGES named symbols — e.g. App.tsx's
@@ -3254,6 +3924,35 @@ class ToolHandler {
3254
3924
  // substantive definition (skip empty stubs + test files, same relevance the
3255
3925
  // trace endpoint picker uses) and inject it as an entry, so every symbol the
3256
3926
  // agent explicitly named is in the subgraph and its file is scored.
3927
+ /**
3928
+ * Is this a member an INTERFACE declares — a signature with no body (#1638)?
3929
+ *
3930
+ * It arrives as an ordinary `method` node, so without asking, every ranking
3931
+ * stage reads a `.d.ts` full of `method_signature`s as a file full of
3932
+ * callables. Two stages below ask, for the same reason: a signature is the
3933
+ * declaration of behaviour, never behaviour, and the rank a file earns must
3934
+ * not grow just because its interfaces spell their members out.
3935
+ *
3936
+ * Cached; reached only for `method` nodes on paths that already probe the
3937
+ * graph per node, so it adds a key lookup, not a pass.
3938
+ */
3939
+ const interfaceMemberCache = new Map();
3940
+ const isInterfaceOwnedMethod = (node) => {
3941
+ if (node.kind !== 'method')
3942
+ return false;
3943
+ const cached = interfaceMemberCache.get(node.id);
3944
+ if (cached !== undefined)
3945
+ return cached;
3946
+ let owned = false;
3947
+ try {
3948
+ owned = cg.getIncomingEdges(node.id).some((e) => e.kind === 'contains' && cg.getNode(e.source)?.kind === 'interface');
3949
+ }
3950
+ catch {
3951
+ owned = false; // a probe failure must not manufacture a penalty
3952
+ }
3953
+ interfaceMemberCache.set(node.id, owned);
3954
+ return owned;
3955
+ };
3257
3956
  const namedSeedIds = new Set();
3258
3957
  // The subset of named seeds that earns the named-FIRST sort tier. We still
3259
3958
  // SEED every ≤3-def name (so RWR / flow ranking is unchanged), but only the
@@ -3319,8 +4018,18 @@ class ToolHandler {
3319
4018
  if (!names) {
3320
4019
  names = new Set();
3321
4020
  try {
3322
- for (const n of cg.getNodesInFile(fp))
3323
- names.add(n.name.toLowerCase());
4021
+ // An interface's members (#1638) describe a shape; nobody names
4022
+ // them in a question. Counting them let `readonly host: string` in
4023
+ // an options interface corroborate the English word "main" into
4024
+ // seeding the same file's `main()`, which then took the named-first
4025
+ // tier from the answer files (vscode "extension host … main process").
4026
+ const fileNodes = cg.getNodesInFile(fp);
4027
+ const interfaces = fileNodes.filter((n) => n.kind === 'interface');
4028
+ const declaresShape = (n) => (n.kind === 'property' || n.kind === 'method') &&
4029
+ interfaces.some((i) => n.startLine >= i.startLine && n.endLine <= i.endLine);
4030
+ for (const n of fileNodes)
4031
+ if (!declaresShape(n))
4032
+ names.add(n.name.toLowerCase());
3324
4033
  }
3325
4034
  catch { /* unreadable file entry — treat as uncorroborated */ }
3326
4035
  fileNameSets.set(fp, names);
@@ -3429,9 +4138,29 @@ class ToolHandler {
3429
4138
  // named-file sort below. (Previously only NEW injections were marked,
3430
4139
  // so a named symbol FTS already gathered never sorted to the top.)
3431
4140
  namedSeedIds.add(n.id);
4141
+ // A QUALIFIED name that resolved to a handful of defs is the agent
4142
+ // choosing one overload out of a family — `SQLCompiler.as_sql`, not
4143
+ // the 109 other `as_sql`s. The bare name keeps the family rules; the
4144
+ // qualified one is an exact target (see `exactNodeIds`).
4145
+ if (isQual && cands.length <= 3 && CALLABLE.has(n.kind))
4146
+ exactNodeIds.add(n.id);
4147
+ }
4148
+ // An interface's `method_signature` seeds (so RWR and the flow ranking
4149
+ // still see it, and a query that names it still reaches its file) but
4150
+ // never earns the named-FIRST tier (#1638). That tier means "the agent
4151
+ // asked for the symbol DEFINED here", and this seeding says as much —
4152
+ // it resolves a token to its substantive definition and sorts bodies
4153
+ // first. A declaration is the stub that sort demotes, not the answer.
4154
+ // Without this the tier is reachable by prose: `body`, `stream` and
4155
+ // `metadata` are member names in any platform `.d.ts`, and each one
4156
+ // corroborates the next through `coNamedInFile`, so an ambient shim
4157
+ // walks past the NL-stopword guard and lands above every implementation
4158
+ // file — the exact inversion CG-28 exists to prevent, arriving on a key
4159
+ // that sorts above the CG-28 penalty.
4160
+ for (const n of tierPicks) {
4161
+ if (!isInterfaceOwnedMethod(n))
4162
+ tierSeedIds.add(n.id);
3432
4163
  }
3433
- for (const n of tierPicks)
3434
- tierSeedIds.add(n.id);
3435
4164
  }
3436
4165
  }
3437
4166
  // Step 2: Group nodes by file, score by relevance
@@ -3484,9 +4213,21 @@ class ToolHandler {
3484
4213
  isolationCache.set(node.id, isolated);
3485
4214
  return isolated;
3486
4215
  };
4216
+ /**
4217
+ * A `method_signature` reaches here as a `method`, which the kind table
4218
+ * rates 1.0: "a callable — the unit an architecture question is about". It
4219
+ * is not that. It is the row below on the same scale, "a member of a type",
4220
+ * and rating it as a callable is how a 28-interface `.d.ts` doubled its
4221
+ * score the moment its members became indexable (#1638). Only `method`
4222
+ * needs correcting; `property` already sits in the member tier whoever
4223
+ * declares it.
4224
+ */
3487
4225
  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))
4226
+ const signatureOnly = isInterfaceOwnedMethod(node);
4227
+ const weight = signatureOnly
4228
+ ? TYPE_MEMBER_RELEVANCE_WEIGHT
4229
+ : exports.RELEVANCE_KIND_WEIGHT[node.kind] ?? DEFAULT_RELEVANCE_KIND_WEIGHT;
4230
+ if (!probeIsolation || !(signatureOnly || WEAK_RELEVANCE_KINDS.has(node.kind)))
3490
4231
  return weight;
3491
4232
  return isUsageIsolated(node) ? ISOLATED_WEAK_KIND_WEIGHT : weight;
3492
4233
  };
@@ -3706,7 +4447,33 @@ class ToolHandler {
3706
4447
  // (org-user.storage.ts, call-connected to the matches) accrues mass; a lone
3707
4448
  // text match (LensSwitcher.swift, matched "switch" but calls nothing in the
3708
4449
  // flow) gets only its restart probability → ~0, and is dropped by the gate.
3709
- const nodeRwr = this.computeGraphRelevance([...subgraph.nodes.keys()], subgraph.edges, entryNodeIds);
4450
+ //
4451
+ // A file the ambient-declaration penalty has already damped is a candidate,
4452
+ // but not a place a walk STARTS. The restart vector is uniform over seeds,
4453
+ // so every seed divides the restart mass the implementation files compete
4454
+ // for — and since #1638 a platform `.d.ts` contributes one seed per member,
4455
+ // whose names (`body`, `stream`, `metadata`) are exactly what a prose flow
4456
+ // query matches. That is what halves an implementation file's graph mass
4457
+ // while the shim's holds steady: dilution of the restart vector, not
4458
+ // connectivity. `contains` is not a RANK_EDGE, so these members carry almost
4459
+ // no walk mass of their own; seeding is the whole of their effect on rank.
4460
+ //
4461
+ // `isDampedDeclaration` and not a bare ambient test: it already exempts a
4462
+ // file whose declared type the query NAMED, so a query genuinely about the
4463
+ // declared type keeps its seeds and the shim still ranks first. Damped files
4464
+ // stay in the candidate set, stay reachable, and keep their `score`
4465
+ // contribution — this changes only where the walk starts.
4466
+ const rwrSeedIds = new Set();
4467
+ for (const id of entryNodeIds) {
4468
+ const seed = subgraph.nodes.get(id);
4469
+ if (seed && isDampedDeclaration(seed.filePath))
4470
+ continue;
4471
+ rwrSeedIds.add(id);
4472
+ }
4473
+ const nodeRwr = this.computeGraphRelevance(
4474
+ // Fall back to the unfiltered seeds when EVERY seed is damped: the walk
4475
+ // must not lose its restart vector and return all-uniform.
4476
+ [...subgraph.nodes.keys()], subgraph.edges, rwrSeedIds.size > 0 ? rwrSeedIds : entryNodeIds);
3710
4477
  //
3711
4478
  // Carries `rankPenalty` too, so generated/low-value files are demoted on the
3712
4479
  // sort's PRIMARY key rather than only at the tiebreak. Everything downstream
@@ -3907,7 +4674,7 @@ class ToolHandler {
3907
4674
  // Blast radius (always-on, compact): for the entry symbols, who depends on
3908
4675
  // them + which tests cover them — locations only, no source — so the agent
3909
4676
  // knows what to update/verify before editing without a separate call.
3910
- const blastRadius = this.buildBlastRadiusSection(cg, subgraph);
4677
+ const blastRadius = this.buildBlastRadiusSection(cg, subgraph, exactNodeIds);
3911
4678
  if (blastRadius)
3912
4679
  lines.push(blastRadius);
3913
4680
  // Relationship map — show how symbols connect
@@ -3944,7 +4711,41 @@ class ToolHandler {
3944
4711
  // Compute the flow spine once — used both to prepend the Flow section (below)
3945
4712
  // and to gate adaptive source sizing: files on the spine get full source,
3946
4713
  // off-spine peers skeletonize.
4714
+ // The Flow section labels each hop with its branch conditions; that read
4715
+ // is synchronous, so the grammars it needs are loaded here, once.
4716
+ await (0, branch_guards_1.warmBranchGuardGrammars)();
3947
4717
  const flow = this.buildFlowFromNamedSymbols(cg, matchQuery);
4718
+ // The symbols the question is about: exact targets, the named ones, the spine.
4719
+ const questionIds = new Set([...exactNodeIds, ...flow.pathNodeIds, ...flow.namedNodeIds]);
4720
+ /**
4721
+ * The lines a WINDOW of an oversize body must reach: an anchored line
4722
+ * inside it, the spine's next-hop call, and every call it makes into
4723
+ * another symbol the question is about — "the parts the question is
4724
+ * about", in the graph's own terms rather than by matching words. Most
4725
+ * important first, capped so a window stays a window.
4726
+ */
4727
+ const bodyFocusLines = (n) => {
4728
+ const focus = [];
4729
+ for (const a of lineAnchors) {
4730
+ if (a.file === n.filePath && a.start > n.startLine && a.start <= n.endLine)
4731
+ focus.push(a.start);
4732
+ }
4733
+ const call = flow.spineCallSites.get(n.id);
4734
+ if (call)
4735
+ focus.push(call);
4736
+ const calls = [];
4737
+ try {
4738
+ for (const e of cg.getOutgoingEdges(n.id)) {
4739
+ if (e.target === n.id || !questionIds.has(e.target) || !e.line)
4740
+ continue;
4741
+ if (e.line > n.startLine && e.line <= n.endLine)
4742
+ calls.push(e.line);
4743
+ }
4744
+ }
4745
+ catch { /* focus is a nicety; the head window still renders */ }
4746
+ focus.push(...calls.sort((a, b) => a - b));
4747
+ return [...new Set(focus)].slice(0, MAX_BODY_FOCUS_LINES);
4748
+ };
3948
4749
  // Snapshot every ranked candidate's scoring inputs, in final sort order, so
3949
4750
  // the diagnostic can show what each file's share of the envelope was BOUGHT
3950
4751
  // with (score, graph mass, term hits, flags) — not just what it cost.
@@ -3987,8 +4788,13 @@ class ToolHandler {
3987
4788
  // A pinned file's bytes are worth full price by definition — the agent
3988
4789
  // asked for the file itself, generated/test or not.
3989
4790
  worth: pinnedSet.has(fp) ? 1 : rankPenalty(fp),
3990
- spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id)),
4791
+ // A file holding an EXACT target is funded like a spine file: it is the
4792
+ // answer to the question as asked, and clipping it is what sends the
4793
+ // agent to Read — the exact reason the spine gets this treatment.
4794
+ spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id) || exactNodeIds.has(n.id))
4795
+ || anchorSpans.has(fp),
3991
4796
  pinned: pinnedSet.has(fp),
4797
+ named: namedSeedFiles.has(fp),
3992
4798
  })), budget, maxFiles);
3993
4799
  diag?.setAllocation(allocation.allowances, allocation.cliffed, allocation.cliffAt, allocation.pool);
3994
4800
  // Cliffed files ship as pointers — path, symbols, line numbers — so the agent
@@ -4083,7 +4889,22 @@ class ToolHandler {
4083
4889
  const g = fileGroups.get(fp);
4084
4890
  return g ? n + pointerLineFor(fp, g.nodes).length + 1 : n;
4085
4891
  }, cliffedFiles.size > 0 ? POINTER_HEADER.length + 2 : 0);
4086
- const epilogueFloor = EPILOGUE_LOST_NOTE.length + 2 + cliffPointerFloor;
4892
+ // The summary line ("Found N symbols across M files. …") is written only
4893
+ // after the final cut, and sits in `lines` as an empty placeholder until
4894
+ // then — so the loop never paid for it, and a response filled to the
4895
+ // ceiling ended up past it by the line's length once it was filled in: five
4896
+ // of 47 measured responses over the 25K inline cap (up to 25,032), or the
4897
+ // lost-pointer note above squeezed out.
4898
+ // Reserved at its worst case: the gather's symbol and file counts bound the
4899
+ // shown ones from above.
4900
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
4901
+ const summaryReserve = `Found ${plural(subgraph.nodes.size, 'symbol')} across ${plural(fileGroups.size, 'file')}.`.length
4902
+ + (pinnedFiles.length > 0 ? ` ${plural(pinnedFiles.length, 'file')} pinned from the query.`.length : 0)
4903
+ + (unresolvedPathSpans.length > 0
4904
+ ? ` No indexed file uniquely matches ${unresolvedPathSpans.map((sp) => `\`${sp}\``).join(', ')}.`.length
4905
+ : 0)
4906
+ + setAsideNote.length;
4907
+ const epilogueFloor = Math.max(exports.EXPLORE_FALLBACK_NOTES.lost.complete.length, exports.EXPLORE_FALLBACK_NOTES.lost.trimmed.length) + 2 + cliffPointerFloor + summaryReserve;
4087
4908
  // Absolute stop for the render loop. Reservations already fit the envelope, so
4088
4909
  // this only catches their bounded overshoot (the whole-file grace, an oversize
4089
4910
  // first cluster) — and catches it HERE, where a file can be skipped cleanly and
@@ -4104,6 +4925,11 @@ class ToolHandler {
4104
4925
  // (#1046) — it must reflect what we show, not the raw candidate gather.
4105
4926
  const renderedFilePaths = [];
4106
4927
  let anyFileTrimmed = false;
4928
+ // Rendered files whose section is missing some of what it set out to
4929
+ // deliver, by path — measured at emission from the ranges actually sent
4930
+ // (`elidedWantedSpans`), not from the trim sites. Drives the completeness
4931
+ // note: "complete" is claimed only for sections that are.
4932
+ const trimmedFiles = new Map();
4107
4933
  // Files that changed on disk after their last index sync (#1474). Their
4108
4934
  // indexed line ranges are untrustworthy, so sliced renders (adaptive /
4109
4935
  // skeleton / clusters) are OFF for them: a small drifted file still ships
@@ -4127,16 +4953,40 @@ class ToolHandler {
4127
4953
  // `sourceSpent` outrun `reservedSoFar`, which suppresses slack until a later
4128
4954
  // under-spend covers the debt. So the pool is conserved in both directions,
4129
4955
  // and no file is ever cut BELOW the reservation it was promised.
4956
+ //
4957
+ // Both totals count what a file is GUARANTEED (below), which is its whole
4958
+ // reservation for every file but a named one. A named file's share above
4959
+ // the `MAX_SHARE` valve is spare-room money, not a promise: it is entered
4960
+ // only once the loop has moved past the file, and only as far as the file
4961
+ // actually spent it (`unsettledSoft`). Booked in full up front, whatever the
4962
+ // file could not spend would flow down as slack that exists only in the
4963
+ // ledger, and count against the buy rule's funding line as a debt nobody
4964
+ // owes.
4130
4965
  let reservedSoFar = 0;
4131
4966
  let sourceSpent = 0;
4967
+ let unsettledSoft = 0;
4968
+ const valveCap = Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.MAX_SHARE);
4969
+ const isNamedFile = (path) => isNamedCandidate({ named: namedSeedFiles.has(path), pinned: pinnedSet.has(path) });
4970
+ /**
4971
+ * What the render loop GUARANTEES a file, whatever that costs the files
4972
+ * below it: its reservation, except a named file's share above the
4973
+ * `MAX_SHARE` valve. The allocator lifts the valve for a named file to hand
4974
+ * it budget no other file would spend, not to take room a lower file is
4975
+ * owed — so that part is funded only from spare room, and is never held back
4976
+ * for it either. Guaranteeing the whole reservation dropped two admitted
4977
+ * files from a saturated django response so the named `query.py` could ship
4978
+ * 3K more of itself.
4979
+ */
4980
+ const guaranteedOf = (path, reserved) => (isNamedFile(path) ? Math.min(reserved, valveCap) : reserved);
4132
4981
  // Funding line for the whole-file BUY rule: the response's SOURCE may reach
4133
4982
  // everything the allocator promised plus one bounded overshoot, and no more.
4134
4983
  // Measured against the promise rather than `renderCeiling` on purpose — the
4135
4984
  // ceiling sits 50% above the envelope and says nothing about who is owed
4136
4985
  // 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);
4986
+ // the loop reaches last. See WHOLE_FILE_BUY_OVERSHOOT_FRACTION. The promise
4987
+ // grows as a named file's soft share is settled (see `unsettledSoft`).
4988
+ let reservedTotal = [...allocation.allowances].reduce((sum, [path, n]) => sum + guaranteedOf(path, n), 0);
4989
+ const buyOvershoot = Math.round(budget.maxOutputChars * exports.EXPLORE_ALLOCATION.WHOLE_FILE_BUY_OVERSHOOT_FRACTION);
4140
4990
  /**
4141
4991
  * What a file's section costs BESIDES its source, in render space: the
4142
4992
  * header (path + up to `maxSymbolsInFileHeader` symbol names) plus the code
@@ -4182,13 +5032,31 @@ class ToolHandler {
4182
5032
  * whole reservation, and when they do not, the carry-forward hands the
4183
5033
  * difference to whoever comes next anyway.
4184
5034
  */
5035
+ /**
5036
+ * Everything still owed below `fileIndex`, in render-space chars, whether the
5037
+ * ceiling can pay it or not — the bar a named file's extension has to clear
5038
+ * (see the render loop). What is left above it is room no admitted file will
5039
+ * ever claim.
5040
+ */
5041
+ const owedInFullBelow = (fileIndex) => {
5042
+ let owed = 0;
5043
+ for (let j = fileIndex + 1; j < sortedFiles.length; j++) {
5044
+ const [path, g] = sortedFiles[j];
5045
+ const r = allocation.allowances.get(path);
5046
+ if (r !== undefined)
5047
+ owed += guaranteedOf(path, r) + sectionOverhead(path, g.nodes);
5048
+ }
5049
+ return owed;
5050
+ };
4185
5051
  const owedPayableBelow = (fileIndex, budgetLeft) => {
4186
5052
  let held = 0;
4187
5053
  for (let j = fileIndex + 1; j < sortedFiles.length; j++) {
4188
5054
  const path = sortedFiles[j][0];
4189
- const r = allocation.allowances.get(path);
4190
- if (r === undefined)
5055
+ const reservedBelow = allocation.allowances.get(path);
5056
+ if (reservedBelow === undefined)
4191
5057
  continue;
5058
+ // Only what that file is guaranteed is owed to it (see `guaranteedOf`).
5059
+ const r = guaranteedOf(path, reservedBelow);
4192
5060
  const overhead = sectionOverhead(path, sortedFiles[j][1].nodes);
4193
5061
  const need = r + overhead;
4194
5062
  if (held + need > budgetLeft) {
@@ -4210,6 +5078,16 @@ class ToolHandler {
4210
5078
  return held;
4211
5079
  };
4212
5080
  for (let fileIndex = 0; fileIndex < sortedFiles.length; fileIndex++) {
5081
+ // Settle the soft share of the file the loop just left: what it spent past
5082
+ // its guarantee becomes a promise it kept; the rest was never available.
5083
+ // Here rather than after its render, because every exit path below —
5084
+ // however it `continue`s — comes back through this line.
5085
+ if (unsettledSoft > 0) {
5086
+ const settled = Math.min(unsettledSoft, Math.max(0, sourceSpent - reservedSoFar));
5087
+ reservedSoFar += settled;
5088
+ reservedTotal += settled;
5089
+ unsettledSoft = 0;
5090
+ }
4213
5091
  const [filePath, group] = sortedFiles[fileIndex];
4214
5092
  if (filesIncluded >= maxFiles) {
4215
5093
  if (diag)
@@ -4240,10 +5118,14 @@ class ToolHandler {
4240
5118
  // order because that is the only file a single-pass loop can still pay;
4241
5119
  // `MAX_SHARE` keeps that from turning a weak tail file into the response,
4242
5120
  // 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);
5121
+ // reservation time. (A named file may go past it — but only into spare
5122
+ // room; see below the displacement guard.)
5123
+ const slack = Math.max(0, reservedSoFar - sourceSpent);
5124
+ const guaranteed = guaranteedOf(filePath, reserved);
5125
+ const ruleAllowance = Math.min(guaranteed + slack, Math.max(guaranteed, valveCap));
5126
+ let allowance = ruleAllowance;
5127
+ reservedSoFar += guaranteed;
5128
+ unsettledSoft = reserved - guaranteed;
4247
5129
  // DISPLACEMENT GUARD, in render space (CG-31). `allowance` says what this
4248
5130
  // file MAY spend; it does not say the bytes are still there to spend. The
4249
5131
  // hard ceiling is shared with every file the loop has not reached yet, and
@@ -4260,14 +5142,36 @@ class ToolHandler {
4260
5142
  //
4261
5143
  // Floored at this file's OWN reservation, never below: a kept promise is
4262
5144
  // not a displacement, and cutting a file under what it earned is the
4263
- // failure this whole allocation layer exists to prevent.
5145
+ // failure this whole allocation layer exists to prevent. (For a named
5146
+ // file, the part of the reservation it is `guaranteed` — see above.)
4264
5147
  //
4265
5148
  // Slack still reaches the file: a file above that under-spends leaves
4266
5149
  // `totalChars` lower, which raises `headroom` one-for-one, so the
4267
5150
  // carry-forward the `allowance` line grants is exactly the carry-forward
4268
5151
  // this bound funds.
4269
5152
  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)));
5153
+ const fundedHeadroom = Math.max(Math.min(guaranteed, headroom), headroom - owedPayableBelow(fileIndex, Math.max(0, headroom - guaranteed)));
5154
+ // A file the query NAMED may spend past the rule above — its share over the
5155
+ // `MAX_SHARE` valve, and slack past the valve — but only into SPARE room:
5156
+ // the call's BUDGET left once every file below is paid its full
5157
+ // reservation, payable or not. Two bars that look right and are not:
5158
+ // - `fundedHeadroom` holds back only the payable prefix of what is owed
5159
+ // below (CG-31), so on a saturated response the room it releases still
5160
+ // belongs to a partially-payable file: reaching it cost vscode an
5161
+ // admitted rank-4 file its whole section.
5162
+ // - the render CEILING sits above the budget to absorb the render's own
5163
+ // bounded overshoot (named gap markers, never-empty windows). Spend up
5164
+ // to it and that overshoot lands on the files below: django's named
5165
+ // `query.py` ran 561 chars past its bound and cut a lower file to 53%
5166
+ // of its reservation.
5167
+ // Where nothing is spare the extension is zero and the file renders
5168
+ // exactly as it did before the valve was lifted for it.
5169
+ if (isNamedFile(filePath)) {
5170
+ const spare = budget.maxOutputChars - totalChars - sectionOverhead(filePath, group.nodes)
5171
+ - owedInFullBelow(fileIndex);
5172
+ allowance = Math.max(allowance, Math.min(reserved + slack, spare));
5173
+ }
5174
+ diag?.recordSpendable(filePath, allowance);
4271
5175
  diag?.recordFunded(filePath, fundedHeadroom);
4272
5176
  const absPath = (0, utils_1.validatePathWithinRoot)(projectRoot, filePath);
4273
5177
  if (!absPath || !(0, fs_1.existsSync)(absPath)) {
@@ -4289,6 +5193,10 @@ class ToolHandler {
4289
5193
  // (no `//` — not a comment in Python, Ruby, etc.). With line numbers on,
4290
5194
  // the line-number jump also signals the gap.
4291
5195
  const GAP_MARKER = '\n\n... (gap) ...\n\n';
5196
+ // Full file index — not just the relevance-gathered `group.nodes`. A trim
5197
+ // often drops filler symbols that never scored into the gather set; naming
5198
+ // those holes still needs their defs (#1711).
5199
+ const fileIndexNodes = cg.getNodesInFile(filePath);
4292
5200
  // Cross-call dedup (CG-18). `served` is what THIS session already sent the
4293
5201
  // agent for THIS file, and it is empty unless the file still hashes to the
4294
5202
  // bytes those spans were sliced from — an edit between calls means the
@@ -4348,6 +5256,11 @@ class ToolHandler {
4348
5256
  const folded = opts.covered.length > 0 && opts.body.length < explore_dedup_1.EXPLORE_DEDUP.MIN_DELTA_CHARS;
4349
5257
  const body = folded ? '' : opts.body;
4350
5258
  const ranges = folded ? [] : opts.ranges;
5259
+ // Judged on what this call sends plus what the agent already holds —
5260
+ // AFTER the fold, whose remainder is in neither.
5261
+ const elided = elidedWantedSpans(opts.wanted, [...ranges, ...opts.covered]);
5262
+ if (elided.length > 0)
5263
+ trimmedFiles.set(filePath, elided);
4351
5264
  const at = lines.length;
4352
5265
  lines.push(opts.header, '');
4353
5266
  // Charge what the section ACTUALLY costs, not a flat 200 (CG-26). A
@@ -4404,107 +5317,369 @@ class ToolHandler {
4404
5317
  };
4405
5318
  }
4406
5319
  };
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;
5320
+ // Window helpers — shared by the focused per-symbol view and the cluster
5321
+ // path below, so an oversize body is cut by ONE set of rules wherever it
5322
+ // renders. Parts are SPAN-KEYED: every part carries the exact line range
5323
+ // its text was sliced from (see `buildSection`).
5324
+ const SPINE_WINDOW = 28; // lines each side of a focus line (the next-hop call site)
5325
+ /**
5326
+ * Bounded overshoot for one cluster's render (CG-30).
5327
+ *
5328
+ * `shrinkCluster` keeps the highest-importance member whole even when that
5329
+ * member alone is oversize — an empty file section sends the agent to Read,
5330
+ * which is exactly what explore exists to prevent. But "never empty" is not
5331
+ * "any size": with nothing bounding it, one 22K member rendered against a
5332
+ * 9K reservation (2.4x), which collapses the headroom every file ranked
5333
+ * below it draws from. Past the ceiling the member is WINDOWED rather than
5334
+ * dropped — a leading window (signature + head of the body), plus a window
5335
+ * on the spine's call site when the head misses it, since on a flow cluster
5336
+ * the call path IS the answer.
5337
+ */
5338
+ const MIN_WINDOW_LINES = 12;
5339
+ /** Rendered cost of one source line, line numbering included. */
5340
+ const lineCost = (ln) => (fileLines[ln - 1] ?? '').length + 1 + (withLineNumbers ? String(ln).length + 1 : 0);
5341
+ /** `lineCostPrefix[n]` = rendered chars of lines 1..n, newlines included. */
5342
+ let lineCostPrefix = null;
5343
+ /** Rendered chars of lines `start..end` (line numbers included), in O(1). */
5344
+ const renderedSpanCost = (start, end) => {
5345
+ if (!lineCostPrefix) {
5346
+ lineCostPrefix = [0];
5347
+ for (let ln = 1; ln <= fileLines.length; ln++)
5348
+ lineCostPrefix.push(lineCostPrefix[ln - 1] + lineCost(ln));
4487
5349
  }
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;
5350
+ const s = Math.max(1, start);
5351
+ const e = Math.min(fileLines.length, end);
5352
+ return e < s ? 0 : Math.max(0, lineCostPrefix[e] - lineCostPrefix[s - 1] - 1);
5353
+ };
5354
+ /**
5355
+ * Longest prefix of `r` that fits `room`. `minLines` is the never-empty
5356
+ * floor — it may overrun `room`, so it is only ever asked for when nothing
5357
+ * else has been emitted and the alternative is an empty section.
5358
+ */
5359
+ const headWindowOf = (r, room, minLines = 0) => {
5360
+ let end = r.start - 1;
5361
+ let chars = 0;
5362
+ for (let ln = r.start; ln <= r.end; ln++) {
5363
+ const cost = lineCost(ln);
5364
+ if (chars + cost > room && end - r.start + 1 >= minLines)
5365
+ break;
5366
+ chars += cost;
5367
+ end = ln;
5368
+ }
5369
+ return end >= r.start ? { start: r.start, end } : null;
5370
+ };
5371
+ /** Widest window around `line` inside [lo, hi] that fits `room`. */
5372
+ const centeredWindowOf = (line, lo, hi, room) => {
5373
+ if (line < lo || line > hi)
5374
+ return null;
5375
+ let start = line, end = line, chars = lineCost(line);
5376
+ for (let grown = true; grown;) {
5377
+ grown = false;
5378
+ if (end + 1 <= hi && chars + lineCost(end + 1) <= room) {
5379
+ end += 1;
5380
+ chars += lineCost(end);
5381
+ grown = true;
4506
5382
  }
4507
- else {
5383
+ if (start - 1 >= lo && chars + lineCost(start - 1) <= room) {
5384
+ start -= 1;
5385
+ chars += lineCost(start);
5386
+ grown = true;
5387
+ }
5388
+ }
5389
+ return { start, end };
5390
+ };
5391
+ /**
5392
+ * Reduce rendered parts to fit `ceiling`, never to nothing. Whole parts are
5393
+ * kept while they fit; the first part that overruns is cut to a leading
5394
+ * window on whole lines (a body is never cut mid-line), and everything past
5395
+ * it is dropped. The GAP_MARKER between surviving parts — and the line-number
5396
+ * jump — is what tells the agent the cut happened.
5397
+ *
5398
+ * A partial window shorter than MIN_WINDOW_LINES is not worth emitting, and
5399
+ * emitting one is actively harmful: the session record then claims a 4-line
5400
+ * sliver, and the NEXT call's dedup has to either shred a whole block around
5401
+ * it or re-send it. Below that floor the part is simply dropped — unless
5402
+ * nothing has been emitted at all, where the floor wins over the ceiling
5403
+ * because an empty section is the one outcome worse than an oversize one.
5404
+ *
5405
+ * `focusLines` are the lines this trim must not lose: the spine's next-hop
5406
+ * call site (CG-30) and every definition the agent NAMED inside the cluster
5407
+ * (CG-38). The head fill is source-ordered, so a named def in the TAIL of a
5408
+ * large file is otherwise always the first thing an over-ceiling render
5409
+ * drops — the one span the agent asked for by name, cut in favour of
5410
+ * head-of-file filler it did not ask for. The full-ceiling fill is tried
5411
+ * FIRST and the 60% hold-back applies only when a focus line is actually
5412
+ * left uncovered, so a cluster whose head already reaches its focus keeps
5413
+ * the whole ceiling for source.
5414
+ */
5415
+ const windowToCeiling = (parts, ceiling, focusLines = []) => {
5416
+ const inParts = (line) => parts.some((p) => line >= p.range.start && line <= p.range.end);
5417
+ const focus = [...new Set(focusLines)]
5418
+ .filter((l) => typeof l === 'number' && l > 0 && inParts(l))
5419
+ .sort((a, b) => a - b);
5420
+ /** Source-ordered fill of whole parts, the overrunning one cut to a head window. */
5421
+ const fill = (room) => {
5422
+ const emit = [];
5423
+ let used = 0;
5424
+ for (const p of parts) {
5425
+ const join = emit.length > 0 ? GAP_MARKER.length : 0;
5426
+ if (used + join + p.text.length <= room) {
5427
+ emit.push(p.range);
5428
+ used += join + p.text.length;
5429
+ continue;
5430
+ }
5431
+ const first = emit.length === 0;
5432
+ const win = headWindowOf(p.range, Math.max(0, room - used - join), first ? MIN_WINDOW_LINES : 0);
5433
+ if (win && (first || win.end - win.start + 1 >= MIN_WINDOW_LINES)) {
5434
+ emit.push(win);
5435
+ used += join + renderSpan(win).length;
5436
+ }
5437
+ break;
5438
+ }
5439
+ return { emit, used };
5440
+ };
5441
+ let { emit, used } = fill(ceiling);
5442
+ const reached = () => (emit.length ? emit[emit.length - 1].end : 0);
5443
+ if (focus.some((l) => l > reached())) {
5444
+ // Hold room back for the focus windows so the head can't eat all of it.
5445
+ ({ emit, used } = fill(Math.floor(ceiling * 0.6)));
5446
+ }
5447
+ // What is left is SPLIT between the uncovered focus lines rather than
5448
+ // handed to them in order. Greedy-in-source-order reproduces the very bug
5449
+ // this guards: on a prose query resolving four focus lines, the two
5450
+ // earliest took the whole reserve and `flushQueuedMessages` at L1102 —
5451
+ // named in the question — was dropped again. A skipped or undersized
5452
+ // window returns its share to the pool for the ones after it.
5453
+ let covered = reached();
5454
+ let room = Math.max(0, ceiling - used);
5455
+ const pending = focus.filter((l) => l > covered);
5456
+ for (let i = 0; i < pending.length; i++) {
5457
+ const line = pending[i];
5458
+ if (line <= covered)
5459
+ continue; // an earlier window already reached it
5460
+ const share = Math.floor(room / (pending.length - i)) - GAP_MARKER.length;
5461
+ if (share <= 0)
5462
+ continue;
5463
+ const host = parts.find((p) => line >= p.range.start && line <= p.range.end);
5464
+ const lo = Math.max(host.range.start, line - SPINE_WINDOW, covered + 1);
5465
+ const hi = Math.min(host.range.end, line + SPINE_WINDOW);
5466
+ const win = centeredWindowOf(line, lo, hi, share);
5467
+ // Same sliver floor as the head window — a two-line peek at the call
5468
+ // site teaches the next call's dedup to shred the block around it.
5469
+ if (!win || win.end - win.start + 1 < MIN_WINDOW_LINES)
5470
+ continue;
5471
+ emit.push(win);
5472
+ const cost = GAP_MARKER.length + renderSpan(win).length;
5473
+ used += cost;
5474
+ room -= cost;
5475
+ covered = win.end;
5476
+ }
5477
+ // Never empty: a section with no source sends the agent to Read.
5478
+ if (emit.length === 0 && parts.length > 0) {
5479
+ const first = headWindowOf(parts[0].range, ceiling, MIN_WINDOW_LINES);
5480
+ if (first)
5481
+ emit.push(first);
5482
+ }
5483
+ return emit
5484
+ .sort((a, b) => a.start - b.start)
5485
+ .map((r) => ({ range: r, text: renderSpan(r) }));
5486
+ };
5487
+ // Disk-drift gate (#1474): every render branch below except whole-file
5488
+ // slices fileContent (CURRENT bytes) at INDEXED line ranges. Content is
5489
+ // already in hand, so the check costs one stat (hash only on mismatch).
5490
+ const fileStale = this.isFileStaleOnDisk(cg, filePath, fileContent);
5491
+ // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
5492
+ // to a per-symbol view when it's a redundant member of a polymorphic family.
5493
+ // Engages iff ALL hold:
5494
+ // 1. a flow spine exists,
5495
+ // 2. no symbol in the file is on that spine (it's not the mechanism path),
5496
+ // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
5497
+ // 4. it is NOT SPARED, where a file is spared iff the agent named a
5498
+ // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
5499
+ // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
5500
+ // base+subclasses "family" file like Django's compiler.py — collapse it).
5501
+ // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
5502
+ // subclass; naming it must NOT keep every backend variant + test file full
5503
+ // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
5504
+ // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
5505
+ // agent NAMED or that's on the spine is shown with its FULL body (so the agent
5506
+ // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
5507
+ // every other symbol is just its signature. So the base mechanism survives while
5508
+ // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
5509
+ // The symbols a section of this file sets out to deliver, for the
5510
+ // completeness check (`elidedWantedSpans`), ranked the way the cluster
5511
+ // path ranks its members.
5512
+ // The file node is not one of them: no section delivers "the file" as a
5513
+ // symbol, and it spans trailing lines no render prints.
5514
+ const wantedFrom = (nodes) => nodes
5515
+ .filter((n) => n.kind !== 'import' && n.kind !== 'export' && n.kind !== 'file' && n.startLine > 0)
5516
+ .map((n) => ({
5517
+ name: n.name,
5518
+ kind: n.kind,
5519
+ start: n.startLine,
5520
+ end: n.endLine,
5521
+ importance: entryNodeIds.has(n.id) ? 10 : flow.namedNodeIds.has(n.id) ? 9 : 1,
5522
+ spine: flow.pathNodeIds.has(n.id),
5523
+ qualifiedName: n.qualifiedName,
5524
+ }));
5525
+ const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
5526
+ const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
5527
+ const spared = spareNamed && !fileDefinesSuper;
5528
+ const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
5529
+ const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
5530
+ // On-spine god-file: the flow path runs THROUGH this file, but it also holds
5531
+ // many OTHER named methods, and rendering all of them in full blows the
5532
+ // per-file budget and starves the other flow files (Alamofire: the agent
5533
+ // names ~7 Session.swift methods — the build spine PLUS off-path
5534
+ // task/didCompleteTask — far past the whole response budget). Engage the
5535
+ // per-symbol view to keep the SPINE full and collapse the off-path named
5536
+ // methods to signatures. Only when there IS off-path content to shed —
5537
+ // otherwise the spine is irreducible (a sequential flow has no redundancy),
5538
+ // so leave it to the normal full render.
5539
+ const namedBodyChars = group.nodes
5540
+ .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
5541
+ .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
5542
+ const onSpineGodFile = hasSpineNode
5543
+ && namedBodyChars > allowance
5544
+ && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
5545
+ // A line RANGE the agent asked for (`lines 900-1003`) is not a symbol, so
5546
+ // the per-symbol view has no way to show it — such a file takes the
5547
+ // cluster path, which renders anchor spans first.
5548
+ if (!fileStale && adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
5549
+ && !anchorSpans.has(filePath)
5550
+ && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
5551
+ const syms = group.nodes
5552
+ .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
5553
+ .sort((a, b) => a.startLine - b.startLine);
5554
+ // Pass 1: choose which symbols get a FULL body, by priority, greedily within
5555
+ // a per-file body cap — so one huge family file can't body every named method
5556
+ // and crowd out the other flow files (Django's query.py). A symbol earns a
5557
+ // body if it's EXACT, on-spine, UNIQUELY named (`SQLCompiler.execute_sql`),
5558
+ // or a co-named method WHEN this file DEFINES the family supertype (so the
5559
+ // base `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides —
5560
+ // and OkHttp's 5 `intercept`s if the agent names `intercept` — stay
5561
+ // signatures). Tiers, most-wanted first:
5562
+ // 0 EXACT — a qualified name or a line anchor (see `exactNodeIds`),
5563
+ // 1 a spine step the agent NAMED,
5564
+ // 2 a spine step it did not (the one unnamed bridge between two named),
5565
+ // 3 a UNIQUELY named off-spine method,
5566
+ // 4 a co-named method in the family's base file.
5567
+ // Within a tier the spine keeps its CALL order, then source order. Source
5568
+ // order alone let the smaller steps that happen to sit higher in the file
5569
+ // take the cap: Django's `SQLCompiler.as_sql` — named, qualified, step 1 of
5570
+ // the flow, 226 lines — lost to the unnamed bridge `get_qualify_sql` and to
5571
+ // `get_select` and came back as its signature line, every time.
5572
+ const chainPos = new Map([...flow.pathNodeIds].map((id, i) => [id, i]));
5573
+ const prio = (n) => !CALLABLE_BODY.has(n.kind) ? 99
5574
+ : exactNodeIds.has(n.id) ? 0
5575
+ : flow.pathNodeIds.has(n.id) ? (flow.namedNodeIds.has(n.id) ? 1 : 2)
5576
+ : flow.uniqueNamedNodeIds.has(n.id) ? 3
5577
+ : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 4 : 99;
5578
+ // Tiers 0-1 are never reduced to a signature: a body too big for what is
5579
+ // left is WINDOWED instead — its head plus the lines where it calls the
5580
+ // other symbols the question named. A signature is the one render of a
5581
+ // method the agent explicitly asked for that is guaranteed to send it to
5582
+ // Read.
5583
+ const WINDOWED_TIER = 1;
5584
+ // One WINDOW per file, sized by this file's RESERVATION. syms are taken by
5585
+ // priority, and the cap applies to ALL of them — including the spine — so a
5586
+ // big-spine god-file (tokio's worker.rs: run→run_task→next_task→steal_work)
5587
+ // can't eat the whole response and starve the co-flow file (harness.rs's
5588
+ // poll). The native agent windows such a file too (~190 lines at a time),
5589
+ // so this mimics, not truncates. Always emit ≥1 (never an empty section).
5590
+ //
5591
+ // Held to `fundedHeadroom` as well (CG-31) so this path cannot spend a
5592
+ // reservation still owed below it either. It never exceeds `allowance`
5593
+ // today, so the bound only bites once the ceiling is genuinely tight —
5594
+ // but "every render path" has to mean every one, or the guard is just a
5595
+ // detour the next god-file takes.
5596
+ //
5597
+ // Priced in RENDERED chars — line numbers included — and net of the
5598
+ // signature lines the view also prints. Raw source length undercounts
5599
+ // both, and once an oversize body is windowed to the room that is left
5600
+ // the undercount stops being slack: the section ran 19% past what it
5601
+ // was funded (excalidraw's App.tsx) and the four files below it
5602
+ // rendered nothing.
5603
+ const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
5604
+ const sigReserve = syms.slice(0, SIG_MAX).reduce((sum, n) => sum + lineCost(n.startLine), 0);
5605
+ const bodyCap = Math.max(0, Math.min(allowance, fundedHeadroom) - sigReserve);
5606
+ const bodyIds = new Set();
5607
+ /** Tier 0-1 bodies too big to fit whole, as the windows they render as. */
5608
+ const bodyWindows = new Map();
5609
+ let bodyChars = 0;
5610
+ const ranked = syms
5611
+ .filter(n => prio(n) < 99 && n.endLine >= n.startLine)
5612
+ .sort((a, b) => prio(a) - prio(b)
5613
+ || (chainPos.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (chainPos.get(b.id) ?? Number.MAX_SAFE_INTEGER)
5614
+ || a.startLine - b.startLine);
5615
+ const deferred = [];
5616
+ for (const n of ranked) {
5617
+ if (prio(n) > WINDOWED_TIER)
5618
+ continue;
5619
+ const sz = renderedSpanCost(n.startLine, n.endLine);
5620
+ if (bodyChars + sz <= bodyCap) {
5621
+ bodyIds.add(n.id);
5622
+ bodyChars += sz;
5623
+ }
5624
+ else {
5625
+ deferred.push(n);
5626
+ }
5627
+ }
5628
+ for (const n of deferred) {
5629
+ const room = bodyCap - bodyChars;
5630
+ // Below MIN_CHARS a window cannot hold a readable block; with nothing
5631
+ // emitted yet the never-empty floor inside `windowToCeiling` wins.
5632
+ if (room < exports.EXPLORE_ALLOCATION.MIN_CHARS && bodyIds.size + bodyWindows.size > 0)
5633
+ continue;
5634
+ const range = { start: n.startLine, end: n.endLine };
5635
+ const windows = windowToCeiling([{ range, text: renderSpan(range) }], Math.max(0, room), bodyFocusLines(n)).map((p) => p.range);
5636
+ if (windows.length === 0)
5637
+ continue;
5638
+ bodyWindows.set(n.id, windows);
5639
+ bodyChars += windows.reduce((sum, w) => sum + renderedSpanCost(w.start, w.end), 0);
5640
+ }
5641
+ for (const n of ranked) {
5642
+ if (prio(n) <= WINDOWED_TIER)
5643
+ continue;
5644
+ const sz = renderedSpanCost(n.startLine, n.endLine);
5645
+ if (bodyChars + sz > bodyCap && bodyIds.size + bodyWindows.size > 0)
5646
+ continue;
5647
+ bodyIds.add(n.id);
5648
+ bodyChars += sz;
5649
+ }
5650
+ // Pass 2: render in line order — full body for chosen symbols, else the
5651
+ // signature line (capped, with a "+N more" tail so the structure map of a
5652
+ // god-file doesn't itself bloat the budget).
5653
+ const skel = [];
5654
+ let coveredUntil = 0; // skip symbols already inside an emitted body
5655
+ let sigCount = 0, sigDropped = 0;
5656
+ for (const n of syms) {
5657
+ if (n.startLine <= coveredUntil)
5658
+ continue;
5659
+ if (bodyIds.has(n.id)) {
5660
+ const end = n.endLine;
5661
+ const body = fileLines.slice(n.startLine - 1, end).join('\n');
5662
+ skel.push({
5663
+ range: { start: n.startLine, end },
5664
+ text: withLineNumbers ? numberSourceLines(body, n.startLine) : body,
5665
+ });
5666
+ coveredUntil = end;
5667
+ }
5668
+ else if (bodyWindows.has(n.id)) {
5669
+ // Each hole in a windowed body is named with the explore query that
5670
+ // returns it — a line range, which explore now honours — so the
5671
+ // follow-up is one call, not a Read of the file.
5672
+ const windows = bodyWindows.get(n.id);
5673
+ windows.forEach((w, k) => {
5674
+ const holeEnd = (windows[k + 1]?.start ?? n.endLine + 1) - 1;
5675
+ const hole = holeEnd > w.end
5676
+ ? `\n… lines ${w.end + 1}-${holeEnd} of \`${n.name}\` elided — codegraph_explore \`${filePath}:${w.end + 1}-${holeEnd}\` returns them`
5677
+ : '';
5678
+ skel.push({ range: w, text: renderSpan(w) + hole });
5679
+ });
5680
+ coveredUntil = n.endLine;
5681
+ }
5682
+ else {
4508
5683
  // Elide the body, emit the signature. node.startLine can point at a
4509
5684
  // decorator/annotation, so scan forward for the line that names the symbol.
4510
5685
  let lineNo = n.startLine;
@@ -4530,7 +5705,6 @@ class ToolHandler {
4530
5705
  }
4531
5706
  }
4532
5707
  }
4533
- const sigTail = sigDropped > 0 ? `… +${sigDropped} more (signatures elided)` : '';
4534
5708
  if (skel.length > 0) {
4535
5709
  const names = [...new Set(group.nodes.filter(n => n.kind !== 'import' && n.kind !== 'export').map(n => n.name))]
4536
5710
  .slice(0, budget.maxSymbolsInFileHeader).join(', ');
@@ -4540,7 +5714,7 @@ class ToolHandler {
4540
5714
  // (Session.swift, DataRequest.swift) that fired an over-investigation
4541
5715
  // spiral (the agent Read the skeletonized file, then kept digging).
4542
5716
  // CLAUDE.md: explore output must never tell the agent to Read.
4543
- const tag = bodyIds.size > 0
5717
+ const tag = bodyIds.size + bodyWindows.size > 0
4544
5718
  ? 'focused (the methods you named in full, the rest as signatures — codegraph_explore a signature by name for its body; do NOT Read)'
4545
5719
  : 'skeleton (signatures only — codegraph_explore a name for its full body; do NOT Read)';
4546
5720
  // Dedup runs on the per-symbol parts, so a body the agent already has
@@ -4548,16 +5722,50 @@ class ToolHandler {
4548
5722
  // (a one-line signature is far under MIN_COVERED_LINES and is never
4549
5723
  // withheld — the structure map is what makes this render legible).
4550
5724
  const dd = dedupeSpans(skel);
4551
- const withTail = (parts) => [...parts.map((p) => p.text), ...(sigTail ? [sigTail] : [])].join('\n');
5725
+ const withTail = (parts, extraDropped = 0) => {
5726
+ const dropped = sigDropped + extraDropped;
5727
+ const tail = dropped > 0 ? `… +${dropped} more (signatures elided)` : '';
5728
+ return [...parts.map((p) => p.text), ...(tail ? [tail] : [])].join('\n');
5729
+ };
5730
+ const header = fileSectionHeader(filePath, `${names} · ${tag}`);
5731
+ // The ceiling fit test every other render path has (CG-26), which this
5732
+ // one lacked: it emitted whatever it built, so a skeleton at the tail
5733
+ // of a full response ran past the ceiling and the final cut threw away
5734
+ // it, the section before it, and the pointer list behind them. Trim
5735
+ // from the end instead — trailing signatures first, then trailing
5736
+ // bodies — and skip the file only if not one part fits.
5737
+ let parts = dd.parts;
5738
+ let trimmedSigs = 0;
5739
+ const sectionCost = (ps) => header.length + 2 + (ps.length > 0 ? withTail(ps, trimmedSigs).length + lang.length + 11 : 0);
5740
+ while (parts.length > 1 && totalChars + sectionCost(parts) > renderCeiling) {
5741
+ let drop = -1;
5742
+ for (let k = parts.length - 1; k >= 0; k--) {
5743
+ if (parts[k].range.start === parts[k].range.end) {
5744
+ drop = k;
5745
+ break;
5746
+ }
5747
+ }
5748
+ if (drop < 0)
5749
+ drop = parts.length - 1;
5750
+ else
5751
+ trimmedSigs++;
5752
+ parts = parts.filter((_, k) => k !== drop);
5753
+ }
5754
+ if (dd.parts.length > 0 && totalChars + sectionCost(parts) > renderCeiling) {
5755
+ diag?.recordSkip(filePath, 'budget-clusters');
5756
+ continue;
5757
+ }
4552
5758
  emitFileSection({
4553
- header: fileSectionHeader(filePath, `${names} · ${tag}`),
4554
- body: dd.parts.length > 0 ? withTail(dd.parts) : '',
4555
- ranges: dd.parts.map((p) => p.range),
5759
+ header,
5760
+ body: parts.length > 0 ? withTail(parts, trimmedSigs) : '',
5761
+ ranges: parts.map((p) => p.range),
4556
5762
  covered: dd.covered,
4557
5763
  overhead: 120,
4558
- mode: bodyIds.size > 0 ? 'focused' : 'skeleton',
5764
+ mode: bodyIds.size + bodyWindows.size > 0 ? 'focused' : 'skeleton',
4559
5765
  // Always "clipped": the per-symbol view elides bodies by construction.
4560
5766
  clipped: true,
5767
+ // Every symbol whose body this view could have shown.
5768
+ wanted: wantedFrom(syms),
4561
5769
  fullBody: withTail(skel),
4562
5770
  fullRanges: skel.map((p) => p.range),
4563
5771
  });
@@ -4637,7 +5845,7 @@ class ToolHandler {
4637
5845
  // the emission site below, so it cannot displace either.
4638
5846
  const buysWhole = fileContent.length <= graceBound
4639
5847
  || (reserved >= fileContent.length * exports.EXPLORE_ALLOCATION.WHOLE_FILE_BUY_FRACTION
4640
- && sourceSpent + fileContent.length + owedBelow <= sourceCeiling
5848
+ && sourceSpent + fileContent.length + owedBelow <= reservedTotal + buyOvershoot
4641
5849
  && fileContent.length <= fundedHeadroom);
4642
5850
  // Set by the whole-file arm when it actually emits. A whole render that
4643
5851
  // does not FIT no longer ends the file's turn (CG-26) — it falls through
@@ -4688,6 +5896,11 @@ class ToolHandler {
4688
5896
  overhead: 200,
4689
5897
  mode: 'whole',
4690
5898
  clipped: false,
5899
+ // Sent whole, so nothing is elided — unless dedup folds a remainder
5900
+ // the agent does not hold (`emitFileSection`). Clamped to the lines
5901
+ // the render carries, which stop before trailing blank lines.
5902
+ wanted: wantedFrom(group.nodes)
5903
+ .map((w) => ({ ...w, end: Math.min(w.end, wholeRange.end) })),
4691
5904
  fullBody: fullSection,
4692
5905
  fullRanges: [wholeRange],
4693
5906
  });
@@ -4747,19 +5960,27 @@ class ToolHandler {
4747
5960
  for (const n of group.nodes)
4748
5961
  if (n.startLine > 0 && n.endLine > 0)
4749
5962
  rangeNodes.set(n.id, n);
4750
- for (const id of flow.namedNodeIds) {
5963
+ for (const id of [...flow.namedNodeIds, ...exactNodeIds]) {
4751
5964
  if (rangeNodes.has(id))
4752
5965
  continue;
4753
5966
  const n = cg.getNode(id);
4754
5967
  if (n && n.filePath === filePath && n.startLine > 0 && n.endLine > 0)
4755
5968
  rangeNodes.set(id, n);
4756
5969
  }
5970
+ // EXACT targets outrank even the query's entry points: an entry is what the
5971
+ // search matched, an exact target is the def the agent singled out. Their
5972
+ // clusters rank first and get the spine's bounded overshoot (below), so a
5973
+ // qualified `SQLCompiler.as_sql` is no longer outranked by a denser cluster
5974
+ // around `SQLInsertCompiler.as_sql` that merely matched the bare name.
5975
+ const EXACT_IMPORTANCE = 11;
4757
5976
  const ranges = [...rangeNodes.values()]
4758
5977
  // Drop whole-file envelope nodes (containers covering >50% of the file).
4759
5978
  .filter(n => !(ENVELOPE_KINDS.has(n.kind) && (n.endLine - n.startLine + 1) > fileLines.length * 0.5))
4760
5979
  .map(n => {
4761
5980
  let importance = 1;
4762
- if (entryNodeIds.has(n.id))
5981
+ if (exactNodeIds.has(n.id))
5982
+ importance = EXACT_IMPORTANCE;
5983
+ else if (entryNodeIds.has(n.id))
4763
5984
  importance = 10;
4764
5985
  else if (flow.namedNodeIds.has(n.id))
4765
5986
  importance = 9; // agent named it → keep its cluster
@@ -4772,7 +5993,7 @@ class ToolHandler {
4772
5993
  // processRunExecutionData, the named flow ENTRY at L1562, is a large
4773
5994
  // low-density method that lost the budget to denser blocks and got cut, so
4774
5995
  // 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) };
5996
+ 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
5997
  });
4777
5998
  // Add edge source locations in this file — captures template references
4778
5999
  // (component usages, event handlers) that aren't nodes themselves.
@@ -4794,6 +6015,15 @@ class ToolHandler {
4794
6015
  ranges.push({ start: edge.line, end: edge.line, name: targetName, kind: edge.kind, importance: 2, spine: false });
4795
6016
  }
4796
6017
  }
6018
+ // Line spans the agent anchored in this file (`lines 900-1003`) are exact
6019
+ // targets too — rendered as exactly the span asked for, not as the
6020
+ // symbols around it.
6021
+ for (const span of anchorSpans.get(filePath) ?? []) {
6022
+ if (span.start > fileLines.length)
6023
+ continue;
6024
+ const end = Math.min(span.end, fileLines.length);
6025
+ ranges.push({ start: span.start, end, name: `lines ${span.start}-${end}`, kind: 'range', importance: EXACT_IMPORTANCE, spine: false });
6026
+ }
4797
6027
  ranges.sort((a, b) => a.start - b.start);
4798
6028
  if (ranges.length === 0) {
4799
6029
  diag?.recordSkip(filePath, 'no-ranges');
@@ -4847,44 +6077,154 @@ class ToolHandler {
4847
6077
  const contextPadding = 3;
4848
6078
  // An oversize spine method (the call path runs THROUGH a god-method — n8n's
4849
6079
  // 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
6080
+ // plus the signature head, NOT dumped whole. Without this the method is too big
4851
6081
  // for any per-file cap and gets dropped, so the agent Reads the method back —
4852
6082
  // the exact gap this closes. Bounded, so a god-method can't blow the budget yet
4853
6083
  // the spine's call still appears in context.
6084
+ //
6085
+ // The size test is on the spine METHOD, never on the cluster holding it. A
6086
+ // cluster merges every symbol within `gapThreshold` lines of the next, so on a
6087
+ // dense file — and on every PINNED file, whose whole symbol list enters the
6088
+ // gather — it spans hundreds of lines around a short spine method. Windowing
6089
+ // that merge threw away every other symbol in it: vscode's pinned
6090
+ // `rpcProtocol.ts` merged into one cluster over lines 20–968 around a 77-line
6091
+ // `_receiveOneMessage`, and the five `MessageIO.serialize*` bodies and the
6092
+ // `MessageType` enum the query named were cut to a 5-line file head plus ±28
6093
+ // lines of one call site — 2,910 chars spent of a 16,800 reservation, and
6094
+ // reported unclipped. A cluster that is long only because it merged goes
6095
+ // through the shrink-by-member path like any other oversize cluster.
4854
6096
  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;
6097
+ /**
6098
+ * Spine methods too long to render whole, in source order. Not one that is,
6099
+ * or holds, an EXACT target (a qualified name, an anchored line span): its
6100
+ * body is what was asked for, so it is kept whole up to the ceiling and only
6101
+ * then windowed — by `windowToCeiling`, which keeps the call site AND the
6102
+ * named defs. Windowed here, an anchored `lines 900-1003` inside it would go
6103
+ * with the rest of the body.
6104
+ */
6105
+ const exactRanges = ranges.filter((r) => r.importance >= EXACT_IMPORTANCE);
6106
+ const oversizeSpine = ranges
6107
+ .filter((r) => r.spine && r.spineCallLine !== undefined
6108
+ && r.end - r.start + 1 > OVERSIZE_SPINE_LINES
6109
+ && r.spineCallLine >= r.start && r.spineCallLine <= r.end
6110
+ && !exactRanges.some((x) => x.start <= r.end && x.end >= r.start))
6111
+ .sort((a, b) => a.start - b.start);
6112
+ const oversizeSpineSet = new Set(oversizeSpine);
6113
+ /** What an oversize spine method renders as: its signature head plus its call site. */
6114
+ const spineWindowOf = (g) => {
6115
+ const call = g.spineCallLine;
6116
+ const winStart = Math.max(g.start, call - SPINE_WINDOW);
6117
+ const winEnd = Math.min(g.end, call + SPINE_WINDOW);
6118
+ // Signature head, only when it sits clearly above the window (else the
6119
+ // window already covers the method opening).
6120
+ const headEnd = Math.min(g.start + 4, winStart - 2);
6121
+ return headEnd >= g.start
6122
+ ? [{ start: g.start, end: headEnd }, { start: winStart, end: winEnd }]
6123
+ : [{ start: winStart, end: winEnd }];
6124
+ };
6125
+ /** Whether rendering [start, end] windows an oversize spine method inside it. */
6126
+ const windowsSpineIn = (start, end) => oversizeSpine.some((g) => g.start >= start && g.end <= end);
6127
+ // Returns the rendered text as SPAN-KEYED PARTS. Every part carries the
6128
+ // exact line range its text was sliced from, which two things depend on:
6129
+ // the session record (CG-17) — a record claiming lines it never sent would
6130
+ // withhold them from a later call, costing a Read — and cross-call dedup
6131
+ // (CG-18), which rebuilds a part's text from a narrower span when the
6132
+ // agent already holds the rest. Both read the spans from the function that
6133
+ // does the slicing; a second function mirroring these window/padding rules
6134
+ // would drift.
6135
+ // Every fit decision below measures parts joined by BARE gap markers.
6136
+ // Naming what a gap skipped (#1711) is added once, at assembly, from what
6137
+ // the file's budget has left: measured with the names, a shrunk cluster
6138
+ // could overrun its room by the names alone and be dropped whole — the
6139
+ // RPCProtocol class in vscode's rpcProtocol.ts went out that way, leaving a
6140
+ // 3-line stub where ~5,200 chars of its body had fit.
6141
+ const sectionText = (parts) => joinPartsWithNamedGaps(filePath, parts, fileIndexNodes, 0);
6142
+ /**
6143
+ * The line spans `buildSection` renders for [start, end] — split out so the
6144
+ * exact pricing below (`renderedSizeOfKept`) prices a member window as the
6145
+ * window it renders, not as the body it elides.
6146
+ */
6147
+ const sectionRangesOf = (c) => {
6148
+ // Plain source for [start, end], except each oversize spine method inside
6149
+ // it, which renders as its window. Context padding goes on the outer edges
6150
+ // of PLAIN source only: padding past a windowed method would add lines
6151
+ // after a tail that was elided.
6152
+ const spans = [];
6153
+ let cursor = c.start;
6154
+ for (const g of oversizeSpine) {
6155
+ if (g.start < cursor || g.start < c.start || g.end > c.end)
6156
+ continue;
6157
+ if (g.start > cursor)
6158
+ spans.push({ range: { start: cursor, end: g.start - 1 }, plain: true });
6159
+ for (const w of spineWindowOf(g))
6160
+ spans.push({ range: w, plain: false });
6161
+ cursor = g.end + 1;
6162
+ }
6163
+ if (cursor <= c.end)
6164
+ spans.push({ range: { start: cursor, end: c.end }, plain: true });
6165
+ const first = spans[0];
6166
+ const last = spans[spans.length - 1];
6167
+ if (first?.plain)
6168
+ first.range.start = Math.max(1, first.range.start - contextPadding);
6169
+ if (last?.plain)
6170
+ last.range.end = Math.min(fileLines.length, last.range.end + contextPadding);
6171
+ // Spans that touch in the file are one block, not two parts with a gap
6172
+ // marker between adjacent lines.
6173
+ const merged = [];
6174
+ for (const { range } of spans) {
6175
+ const prev = merged[merged.length - 1];
6176
+ if (prev && range.start <= prev.end + 1)
6177
+ prev.end = Math.max(prev.end, range.end);
6178
+ else
6179
+ merged.push({ ...range });
6180
+ }
6181
+ return merged;
6182
+ };
6183
+ const buildSection = (c) => sectionRangesOf(c).map((r) => ({ range: r, text: renderSpan(r) }));
6184
+ /** Rendered cost of one member on its own, context padding included. */
6185
+ const paddedCost = (r) => {
6186
+ let chars = 0;
6187
+ const hi = Math.min(fileLines.length, r.end + contextPadding);
6188
+ for (let ln = Math.max(1, r.start - contextPadding); ln <= hi; ln++)
6189
+ chars += lineCost(ln);
6190
+ return chars;
6191
+ };
6192
+ /**
6193
+ * A member the query asked for: one it named or that is an entry point
6194
+ * (importance >= 9), or one on the rendered call path. The rest of a
6195
+ * cluster — glue, connected nodes, edge lines, peripheral declarations —
6196
+ * is incidental context that happens to sit within `gapThreshold` of it.
6197
+ */
6198
+ const isProtectedMember = (r) => r.importance >= 9 || r.spine;
6199
+ /**
6200
+ * Kept ranges re-merged in source order, the way a cluster merges — so
6201
+ * adjacent survivors read as one block rather than a stutter of
6202
+ * one-symbol fragments.
6203
+ */
6204
+ const mergeKept = (keep) => {
6205
+ const merged = [];
6206
+ for (const r of [...keep].sort((a, b) => a.start - b.start)) {
6207
+ const last = merged[merged.length - 1];
6208
+ if (last && r.start <= last.end + gapThreshold)
6209
+ last.end = Math.max(last.end, r.end);
6210
+ else
6211
+ merged.push({ start: r.start, end: r.end });
4879
6212
  }
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
- }];
6213
+ return merged;
6214
+ };
6215
+ /** Whole member ranges, re-merged in source order and rendered. */
6216
+ const partsOfMembers = (members) => mergeKept(members).flatMap((m) => buildSection(m));
6217
+ /**
6218
+ * What this cluster's protected members cost to render on their own, after
6219
+ * the session history — the room a cluster ranked ABOVE it must leave for
6220
+ * them. 0 for a cluster with nothing the query asked for.
6221
+ */
6222
+ const protectedCoreCost = (c) => {
6223
+ const core = c.members.filter(isProtectedMember);
6224
+ if (core.length === 0)
6225
+ return 0;
6226
+ const parts = core.length === c.members.length ? buildSection(c) : partsOfMembers(core);
6227
+ return sectionText(dedupeSpans(parts).parts).length + GAP_MARKER.length;
4888
6228
  };
4889
6229
  /**
4890
6230
  * Shrink an oversize cluster to the highest-importance symbols inside it
@@ -4914,188 +6254,90 @@ class ToolHandler {
4914
6254
  * decide WHICH members survive: that is the ceiling trim's job, and CG-38 is
4915
6255
  * why that trim now protects the named spans instead of cutting in source
4916
6256
  * 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
6257
  *
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.
6258
+ * `incidentalCap` is set for a cluster holding a member the query asked for
6259
+ * (see `renderCluster` and `protectedCoreCost`). Protected members are then
6260
+ * chosen first, exactly as above; every other member must also fit
6261
+ * `incidentalCap`, which is measured on the rendered text (padding, line
6262
+ * numbers) because it is a bound — the ceiling past which the render is
6263
+ * windowed, or bytes owed to a cluster below — not an estimate.
4963
6264
  */
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
6265
  /**
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.
6266
+ * Exact rendered size of `keep` once merged, padded and joined — what
6267
+ * `sectionText` will measure — via a prefix sum, so pricing a candidate
6268
+ * member costs O(members), not a re-render. Priced on the spans
6269
+ * `buildSection` renders, so an oversize spine member costs its window.
4971
6270
  */
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)
6271
+ 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);
6272
+ const shrinkCluster = (c, cap, incidentalCap) => {
6273
+ if (c.members.length < 2)
4987
6274
  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;
6275
+ const guarded = incidentalCap !== undefined;
6276
+ // Protected members first when a hold-back applies (see `renderCluster`);
6277
+ // then an EXACT target, then the spine, as `rankedClusters` ranks spine
6278
+ // clusters first: the call path IS the answer. An unnamed bridge on it
6279
+ // (vscode's `_receiveRequest`, the Flow section's own step 2) otherwise
6280
+ // ranks with incidental helpers and is the member the cap drops. Exact
6281
+ // ahead of spine because the exact branch below keeps members in this
6282
+ // order until the cap: a long spine method first would price out the
6283
+ // body the agent singled out.
6284
+ const byImportance = [...c.members].sort((a, b) => (guarded ? Number(isProtectedMember(b)) - Number(isProtectedMember(a)) : 0)
6285
+ || Number(b.importance >= EXACT_IMPORTANCE) - Number(a.importance >= EXACT_IMPORTANCE)
6286
+ || (b.spine ? 1 : 0) - (a.spine ? 1 : 0)
6287
+ || b.importance - a.importance || (a.end - a.start) - (b.end - b.start) || a.start - b.start);
6288
+ const keep = [];
6289
+ if (c.maxImportance >= EXACT_IMPORTANCE) {
6290
+ // An EXACT target prices EVERY member in rendered chars, protected
6291
+ // ones included. The raw estimate below over-keeps on purpose and
6292
+ // leaves the ceiling trim to cut — but that trim fills in SOURCE
6293
+ // order, so any member above the exact body in the file (an entry
6294
+ // point, a named neighbour) was paid for first and the body the agent
6295
+ // asked for lost its tail (Django's `SQLCompiler.as_sql` stopped at
6296
+ // L944 of 1001 behind a 15-line neighbour). Priced exactly, the kept
6297
+ // set fits and the trim has nothing left to cut unless the exact body
6298
+ // ALONE overruns the ceiling — where it is windowed on its focus
6299
+ // lines. Incidental members also fit `incidentalCap`, as below.
6300
+ for (const r of byImportance) {
6301
+ const limit = guarded && !isProtectedMember(r) ? Math.min(cap, incidentalCap) : cap;
6302
+ if (keep.length > 0 && renderedSizeOfKept([...keep, r]) > limit)
6303
+ continue;
6304
+ keep.push(r);
5000
6305
  }
5001
6306
  }
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;
6307
+ else {
6308
+ // An oversize spine method costs its window, not its body — `buildSection`
6309
+ // windows it wherever it lands. Charging the full body kept it as the
6310
+ // most important member and then had no room left for anything beside it.
6311
+ const sizeOf = (r) => (oversizeSpineSet.has(r) ? spineWindowOf(r) : [r])
6312
+ .reduce((n, w) => n + fileLines.slice(w.start - 1, w.end).join('\n').length, 0);
6313
+ let kept = 0;
6314
+ // Rendered size of what is kept so far, once the first incidental member
6315
+ // is weighed. Every protected member sorts ahead of it, so this is the
6316
+ // exact cost of the protected set; each incidental member then adds its
6317
+ // own padded span, an over-estimate that errs toward the cluster below.
6318
+ let rendered;
6319
+ for (const r of byImportance) {
6320
+ const sz = sizeOf(r) + GAP_MARKER.length;
6321
+ // Always keep the most important range, even if it alone is oversize —
6322
+ // an empty section sends the agent to Read, which costs far more. How
6323
+ // far it may overshoot is bounded by the caller's ceiling (CG-30), which
6324
+ // windows a runaway member instead of dropping it.
6325
+ if (keep.length > 0 && kept + sz > cap)
5042
6326
  continue;
6327
+ if (guarded && keep.length > 0 && !isProtectedMember(r)) {
6328
+ rendered ??= sectionText(dedupeSpans(partsOfMembers(keep)).parts).length;
6329
+ const cost = paddedCost(r) + GAP_MARKER.length;
6330
+ if (rendered + cost > incidentalCap)
6331
+ continue;
6332
+ rendered += cost;
5043
6333
  }
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;
6334
+ keep.push(r);
6335
+ kept += sz;
5051
6336
  }
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
6337
  }
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
- }
5096
- return emit
5097
- .sort((a, b) => a.start - b.start)
5098
- .map((r) => ({ range: r, text: renderSpan(r) }));
6338
+ if (keep.length === c.members.length)
6339
+ return null;
6340
+ return partsOfMembers(keep);
5099
6341
  };
5100
6342
  /**
5101
6343
  * The lines a ceiling trim of this cluster must not lose: the spine's
@@ -5112,7 +6354,14 @@ class ToolHandler {
5112
6354
  .sort((a, b) => b.importance - a.importance || a.start - b.start)
5113
6355
  .slice(0, MAX_FOCUS_LINES)
5114
6356
  .map((m) => m.start);
5115
- return c.spineCallLine ? [c.spineCallLine, ...named] : named;
6357
+ // An exact body cut by the ceiling keeps its calls into the question's
6358
+ // other symbols too, not only its def line — the same focus the
6359
+ // per-symbol view windows by.
6360
+ const exactFocus = c.maxImportance < EXACT_IMPORTANCE ? [] : [...exactNodeIds]
6361
+ .map((id) => subgraph.nodes.get(id))
6362
+ .filter((n) => !!n && n.filePath === filePath && n.startLine >= c.start && n.endLine <= c.end)
6363
+ .flatMap((n) => bodyFocusLines(n));
6364
+ return [...exactFocus, ...(c.spineCallLine ? [c.spineCallLine] : []), ...named];
5116
6365
  };
5117
6366
  /**
5118
6367
  * One cluster's final parts: built, shrunk if it overruns `cap`, then
@@ -5130,8 +6379,29 @@ class ToolHandler {
5130
6379
  * before being windowed. Always >= `cap`, so a cluster that already fits is
5131
6380
  * never touched.
5132
6381
  */
5133
- ceiling = Infinity) => {
6382
+ ceiling = Infinity,
6383
+ /**
6384
+ * What this cluster's INCIDENTAL members may render into, when a cluster
6385
+ * ranked below it holds a member the query asked for — see the selection
6386
+ * loop.
6387
+ */
6388
+ incidentalCap) => {
5134
6389
  const base = dedupeSpans(buildSection(c));
6390
+ // In a cluster holding a member the query asked for, incidental members
6391
+ // are never kept past `ceiling` either. The member shrink estimates on raw
6392
+ // source, which runs well under the rendered size, so it kept helpers the
6393
+ // render then had no room for, and the window back to the ceiling cut in
6394
+ // source order — through the tail of a named body (gin's
6395
+ // `handleHTTPRequest` lost 10 of 71 lines to the helpers above it), or,
6396
+ // when its minimum windows overran a later cluster's room, costing that
6397
+ // cluster its place. Every re-render into an exact room is the same case.
6398
+ const guard = Number.isFinite(ceiling) && c.members.some(isProtectedMember)
6399
+ ? Math.min(incidentalCap ?? Infinity, ceiling)
6400
+ : incidentalCap;
6401
+ // A windowed spine method elides source even when nothing else is cut, so
6402
+ // it counts as shrunk: reported unclipped, the one-file-head-plus-a-call-
6403
+ // site render hid in the diagnostic as a complete section.
6404
+ const windowed = windowsSpineIn(c.start, c.end);
5135
6405
  const bound = (r) => {
5136
6406
  if (!Number.isFinite(ceiling) || sectionText(r.parts).length <= ceiling)
5137
6407
  return r;
@@ -5140,12 +6410,12 @@ class ToolHandler {
5140
6410
  const parts = windowToCeiling(r.parts, ceiling, focusLinesOf(c));
5141
6411
  return { parts, covered: r.covered, shrunk: true };
5142
6412
  };
5143
- if (sectionText(base.parts).length <= cap) {
5144
- return { parts: base.parts, covered: base.covered, shrunk: false };
6413
+ if (sectionText(base.parts).length <= Math.min(cap, guard ?? Infinity)) {
6414
+ return { parts: base.parts, covered: base.covered, shrunk: windowed };
5145
6415
  }
5146
- const shrunk = shrinkCluster(c, cap);
6416
+ const shrunk = shrinkCluster(c, cap, guard);
5147
6417
  if (shrunk === null) {
5148
- return bound({ parts: base.parts, covered: base.covered, shrunk: false });
6418
+ return bound({ parts: base.parts, covered: base.covered, shrunk: windowed });
5149
6419
  }
5150
6420
  const dd = dedupeSpans(shrunk);
5151
6421
  return bound({ parts: dd.parts, covered: dd.covered, shrunk: true });
@@ -5163,10 +6433,15 @@ class ToolHandler {
5163
6433
  const rankedClusters = clusters
5164
6434
  .map((c, i) => ({ idx: i, span: c.end - c.start + 1, c }))
5165
6435
  .sort((a, b) => {
5166
- // Spine clusters first — the rendered call path IS the flow answer, so it
6436
+ // Exact-target clusters first — the def (or span) the agent singled out.
6437
+ // Then spine clusters — the rendered call path IS the flow answer, so it
5167
6438
  // outranks any denser block of peripheral declarations (a low-density entry
5168
6439
  // method must not lose the budget to them). Within spine / within non-spine,
5169
6440
  // the existing importance → density → score → span order holds.
6441
+ const aExact = a.c.maxImportance >= EXACT_IMPORTANCE;
6442
+ const bExact = b.c.maxImportance >= EXACT_IMPORTANCE;
6443
+ if (aExact !== bExact)
6444
+ return (bExact ? 1 : 0) - (aExact ? 1 : 0);
5170
6445
  if (a.c.hasSpine !== b.c.hasSpine)
5171
6446
  return (b.c.hasSpine ? 1 : 0) - (a.c.hasSpine ? 1 : 0);
5172
6447
  if (b.c.maxImportance !== a.c.maxImportance)
@@ -5201,15 +6476,46 @@ class ToolHandler {
5201
6476
  // spine can't run away or starve co-flow files entirely. The 1.5x is drawn
5202
6477
  // from the shared envelope, so it is exactly the overshoot the displacement
5203
6478
  // 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);
6479
+ // another file's, not spare room. The half is of `ruleAllowance`: a named
6480
+ // file's spare-room extension is already the budget's last spare byte, and
6481
+ // half again of it ran a 13K-budget response to 19.3K of its 19.5K ceiling.
6482
+ //
6483
+ const SPINE_CEILING = Math.min(Math.max(Math.round(ruleAllowance * 1.5), allowance), fundedHeadroom);
5206
6484
  const chosenIndices = new Set();
5207
6485
  // Final renders (deduped, shrunk where oversize) by cluster index. Computed
5208
6486
  // during selection and reused at emission so the two never disagree.
5209
6487
  const renderedClusters = new Map();
5210
6488
  let anyClusterShrunk = false;
5211
6489
  let projectedChars = 0;
5212
- for (const rc of rankedClusters) {
6490
+ // What the protected members of every cluster ranked BELOW position p cost
6491
+ // to render. Rank orders clusters, not members: among clusters of equal
6492
+ // max importance it prefers density, and density counts every member, so
6493
+ // a named function with unrelated helpers merged around it outranks a
6494
+ // cluster holding that same kind of function alone — the helpers' edge
6495
+ // lines raise its density. Taken whole, the first cluster then spent the
6496
+ // file's budget on the helpers and the isolated named function rendered
6497
+ // nothing. So a cluster's incidental members may only use what is left
6498
+ // once the named members below it are paid for. Its own protected members
6499
+ // are never held back, so the trade-off between two named symbols is the
6500
+ // one rank already made.
6501
+ const owedFrom = new Array(rankedClusters.length + 1).fill(0);
6502
+ for (let p = rankedClusters.length - 1; p >= 0; p--) {
6503
+ owedFrom[p] = owedFrom[p + 1] + protectedCoreCost(rankedClusters[p].c);
6504
+ }
6505
+ // Measured against `fileBudget` even for a spine cluster: the clusters
6506
+ // below it that are not on the spine are held to `fileBudget`, so room a
6507
+ // spine cluster's incidental members take past it is room they never get.
6508
+ const incidentalCapFor = (p, room) => {
6509
+ const owedBelow = owedFrom[p + 1];
6510
+ if (owedBelow === 0)
6511
+ return undefined;
6512
+ const spent = projectedChars + (chosenIndices.size > 0 ? GAP_MARKER.length : 0);
6513
+ return Math.min(room, fileBudget - spent) - owedBelow;
6514
+ };
6515
+ /** Rendered cost of a cluster's EXACT members on their own. */
6516
+ const exactCostOf = (c) => renderedSizeOfKept(c.members.filter((m) => m.importance >= EXACT_IMPORTANCE));
6517
+ for (let p = 0; p < rankedClusters.length; p++) {
6518
+ const rc = rankedClusters[p];
5213
6519
  // The top-ranked cluster is always taken — an empty file section sends the
5214
6520
  // agent to Read, negating the savings. But "always taken" is not "taken at
5215
6521
  // any size": when it overruns the reservation it is SHRUNK to the
@@ -5219,15 +6525,29 @@ class ToolHandler {
5219
6525
  // A spine cluster (the rendered call path) is the flow answer — it may run
5220
6526
  // past the per-file budget up to the spine ceiling; non-spine clusters obey
5221
6527
  // the normal per-file budget.
5222
- const cap = rc.c.hasSpine ? SPINE_CEILING : fileBudget;
6528
+ const cap = rc.c.hasSpine || rc.c.maxImportance >= EXACT_IMPORTANCE ? SPINE_CEILING : fileBudget;
5223
6529
  // CG-30: shrinking keeps the top member whole however big it is, so bound
5224
6530
  // how far that member may overshoot — the same 1.5x-of-reservation bound
5225
6531
  // SPINE_CEILING already draws, never below `cap` (a cluster that fits its
5226
6532
  // cap is never windowed). A spine cluster's cap already IS that bound, so
5227
6533
  // this holds it to it rather than letting the member rule walk past it.
5228
6534
  const ceiling = Math.max(cap, SPINE_CEILING);
6535
+ // Several exact targets can land in different clusters of one big file —
6536
+ // a pinned 13K-line App.tsx merges into a handful of giant clusters, and
6537
+ // `App.triggerRender` and `App.handleCanvasPointerDown` sat in two. The
6538
+ // one ranked first spent the whole cap on its own neighbours and the
6539
+ // other target rendered nothing. So an exact cluster holds back what the
6540
+ // exact clusters ranked BELOW it still owe — never cutting into its own
6541
+ // targets — and each target renders, windowed if it must.
6542
+ const owedExact = rc.c.maxImportance < EXACT_IMPORTANCE ? 0
6543
+ : rankedClusters.slice(p + 1).reduce((n, other) => (other.c.maxImportance < EXACT_IMPORTANCE
6544
+ ? n : n + exactCostOf(other.c) + GAP_MARKER.length), 0);
6545
+ const holdBack = (room) => (owedExact > 0
6546
+ ? Math.min(room, Math.max(exactCostOf(rc.c), room - owedExact))
6547
+ : room);
5229
6548
  if (first) {
5230
- const section = renderCluster(rc.c, cap, ceiling);
6549
+ const firstCap = holdBack(cap);
6550
+ const section = renderCluster(rc.c, firstCap, owedExact > 0 ? firstCap : ceiling, incidentalCapFor(p, firstCap));
5231
6551
  renderedClusters.set(rc.idx, section);
5232
6552
  anyClusterShrunk = anyClusterShrunk || section.shrunk;
5233
6553
  chosenIndices.add(rc.idx);
@@ -5250,10 +6570,10 @@ class ToolHandler {
5250
6570
  // nothing") applied between CLUSTERS. Below `MIN_CHARS` the remainder can't
5251
6571
  // hold one readable block, so it stays a drop rather than a stutter of
5252
6572
  // fragments the next call's dedup then has to shred around.
5253
- const room = cap - projectedChars - GAP_MARKER.length;
6573
+ const room = holdBack(cap - projectedChars - GAP_MARKER.length);
5254
6574
  if (room < exports.EXPLORE_ALLOCATION.MIN_CHARS)
5255
6575
  continue;
5256
- const section = renderCluster(rc.c, room, room);
6576
+ const section = renderCluster(rc.c, room, room, incidentalCapFor(p, room));
5257
6577
  const text = sectionText(section.parts);
5258
6578
  if (text.length === 0)
5259
6579
  continue;
@@ -5269,31 +6589,46 @@ class ToolHandler {
5269
6589
  chosenIndices.add(rc.idx);
5270
6590
  projectedChars += text.length + GAP_MARKER.length;
5271
6591
  }
6592
+ // Gap names (#1711) are paid from what selection left of this file's
6593
+ // budget, never from source: selection measured every gap as bare.
6594
+ const namedGapBudget = Math.max(fileBudget, projectedChars);
5272
6595
  // Emit chosen clusters in source order so the file reads top-to-bottom.
5273
6596
  // Assembled through a function because it may have to run more than once:
5274
6597
  // the fit test below trims the weakest cluster and re-assembles rather
5275
6598
  // than skipping the file (CG-26).
5276
6599
  const assembleSection = (chosen) => {
5277
- let text = '';
6600
+ const parts = [];
5278
6601
  const symbols = [];
5279
- const ranges = [];
5280
6602
  const covered = [];
5281
6603
  for (let i = 0; i < clusters.length; i++) {
5282
6604
  if (!chosen.has(i))
5283
6605
  continue;
5284
6606
  const cluster = clusters[i];
5285
6607
  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));
6608
+ parts.push(...section.parts);
5293
6609
  covered.push(...section.covered);
5294
6610
  symbols.push(...cluster.symbols);
5295
6611
  }
5296
- return { text, symbols, ranges, covered };
6612
+ // Every member across ALL clusters (chosen or not) is a candidate for
6613
+ // the header bias — a dropped cluster's symbols used to vanish from
6614
+ // the header entirely (#1711).
6615
+ const memberRefs = [];
6616
+ const seenMember = new Set();
6617
+ for (const c of clusters) {
6618
+ for (const m of c.members) {
6619
+ if (seenMember.has(m.name))
6620
+ continue;
6621
+ seenMember.add(m.name);
6622
+ memberRefs.push({ name: m.name, kind: m.kind, startLine: m.start });
6623
+ }
6624
+ }
6625
+ const ranges = parts.map((p) => p.range);
6626
+ const text = joinPartsWithNamedGaps(filePath, parts, fileIndexNodes, Math.max(0, namedGapBudget - sectionText(parts).length));
6627
+ // Header bias prefers RELEVANT elisions (cluster members the trim cut)
6628
+ // over incidental index filler — otherwise locale-sorted `calls0`…
6629
+ // crowds out the answer methods (#1711).
6630
+ const elided = symbolsNotInRanges(memberRefs, ranges);
6631
+ return { text, symbols, ranges, covered, elided };
5297
6632
  };
5298
6633
  let assembled = assembleSection(chosenIndices);
5299
6634
  // A chosen cluster is a COMPLETE method-range — we never cut through a body,
@@ -5309,19 +6644,19 @@ class ToolHandler {
5309
6644
  // Dedupe + cap the symbols list shown in the per-file header. Some
5310
6645
  // files (Session.swift in Alamofire) produced 3.4KB symbol lists
5311
6646
  // 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(', '));
6647
+ // body cap. Prefer symbols the trim elided (#1711), then frequency,
6648
+ // with a "+N more" tail.
6649
+ const headerFor = (symbols, elided = [],
6650
+ /** Longest the header may run; fewer names are listed to meet it (never under one). */
6651
+ maxLength = Infinity) => {
6652
+ for (let cap = budget.maxSymbolsInFileHeader;; cap--) {
6653
+ const { shown, omitted } = biasHeaderSymbols(symbols, elided, cap);
6654
+ const header = fileSectionHeader(filePath, omitted > 0
6655
+ ? `${shown.join(', ')}, +${omitted} more`
6656
+ : shown.join(', '));
6657
+ if (header.length <= maxLength || cap <= 1)
6658
+ return header;
6659
+ }
5325
6660
  };
5326
6661
  // Last stop before the hard ceiling. The reservation already bounded cluster
5327
6662
  // selection above, so reaching this means the bounded overshoot (an oversize
@@ -5339,9 +6674,23 @@ class ToolHandler {
5339
6674
  // admitted, reserved and rendered, and would have delivered nothing.
5340
6675
  // Only when the top-ranked cluster alone cannot fit is the file skipped —
5341
6676
  // that one is never sliced mid-method.
5342
- let fileHeader = headerFor(assembled.symbols);
6677
+ let fileHeader = headerFor(assembled.symbols, assembled.elided);
5343
6678
  let chosenNow = chosenIndices;
5344
6679
  const costOfSection = (header, body) => header.length + 2 + (body.length > 0 ? body.length + lang.length + 11 : 0);
6680
+ // Every file was funded for SOURCE against an ESTIMATED header
6681
+ // (`sectionOverhead`: the file's symbol names), and the real one also lists
6682
+ // the edge lines' targets (`filter(calls)`, `QuerySet(imports)`), so it can
6683
+ // run past the estimate. Where the section no longer fits, the header pays
6684
+ // that back first by listing fewer names — a name it drops is still in the
6685
+ // gap markers and the pointer list; a source line the trim drops is not.
6686
+ // Without this, a file above spending exactly its funded line (an exact
6687
+ // target's overshoot, #2063) left the one below its estimate, and the trim
6688
+ // took the difference out of source: 922 of the 1,031 it was owed.
6689
+ let headerLimit = Infinity;
6690
+ if (totalChars + costOfSection(fileHeader, assembled.text) > renderCeiling) {
6691
+ headerLimit = sectionOverhead(filePath, group.nodes) - 2 - lang.length - 11;
6692
+ fileHeader = headerFor(assembled.symbols, assembled.elided, headerLimit);
6693
+ }
5345
6694
  // The weakest cluster is SHRUNK into the room that is left before it is
5346
6695
  // dropped (CG-36). Dropping it whole makes this loop as all-or-nothing as
5347
6696
  // the selection above it was, and at the same cost: on excalidraw's
@@ -5388,7 +6737,7 @@ class ToolHandler {
5388
6737
  chosenNow = trimmed;
5389
6738
  }
5390
6739
  assembled = assembleSection(chosenNow);
5391
- fileHeader = headerFor(assembled.symbols);
6740
+ fileHeader = headerFor(assembled.symbols, assembled.elided, headerLimit);
5392
6741
  anyFileTrimmed = true;
5393
6742
  }
5394
6743
  // One cluster left and still over — by the header estimate's error, at
@@ -5404,6 +6753,26 @@ class ToolHandler {
5404
6753
  - (fileHeader.length + 2 + lang.length + 11);
5405
6754
  if (room > 0) {
5406
6755
  const reshrunk = renderCluster(clusters[idx], room, room);
6756
+ // Every budget upstream charges a gap as a bare GAP_MARKER, but the
6757
+ // joined text NAMES what each gap elides (#1711). A cluster shrunk to
6758
+ // scattered members has dozens of gaps, and their names can outweigh
6759
+ // the source: re-rendered into the room, it still overran, and a
6760
+ // pinned 1,300-line file with every named body inside its render was
6761
+ // skipped whole. Drop whole parts until the REAL text fits instead —
6762
+ // the last one that holds no focus line first, never the final part.
6763
+ const focus = focusLinesOf(clusters[idx]);
6764
+ while (reshrunk.parts.length > 1 && sectionText(reshrunk.parts).length > room) {
6765
+ const holdsFocus = (p) => focus.some((l) => l >= p.range.start && l <= p.range.end);
6766
+ let drop = reshrunk.parts.length - 1;
6767
+ for (let k = reshrunk.parts.length - 1; k >= 0; k--) {
6768
+ if (!holdsFocus(reshrunk.parts[k])) {
6769
+ drop = k;
6770
+ break;
6771
+ }
6772
+ }
6773
+ reshrunk.parts.splice(drop, 1);
6774
+ reshrunk.shrunk = true;
6775
+ }
5407
6776
  renderedClusters.set(idx, reshrunk);
5408
6777
  anyClusterShrunk = anyClusterShrunk || reshrunk.shrunk;
5409
6778
  assembled = assembleSection(chosenNow);
@@ -5435,6 +6804,9 @@ class ToolHandler {
5435
6804
  // Windowing an oversize member elides source too — reporting it as
5436
6805
  // unclipped would hide exactly the cut the diagnostic exists to show.
5437
6806
  clipped: chosenNow.size < clusters.length || anyClusterShrunk,
6807
+ // Every member of every cluster, chosen or not: a dropped cluster, a
6808
+ // shrunk one and a windowed spine all leave a member short.
6809
+ wanted: ranges,
5438
6810
  fullBody: sectionText(fullClusterParts),
5439
6811
  fullRanges: fullClusterParts.map((p) => p.range),
5440
6812
  });
@@ -5539,22 +6911,33 @@ class ToolHandler {
5539
6911
  }
5540
6912
  pointerOmitted = Math.max(0, remainingFiles.length - pointerEntries.length);
5541
6913
  }
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.`]
6914
+ // Completeness signal so agents know they don't need to re-read these files
6915
+ // — claimed only for sections that ARE complete. A trimmed section is
6916
+ // measured from what was sent (`trimmedFiles`), in render order. On small
6917
+ // projects the budget gates the signal off, but a trim still gets a brief
6918
+ // note pointing at the names the gap markers carry.
6919
+ const trimmedShown = renderedFilePaths
6920
+ .filter((fp) => trimmedFiles.has(fp))
6921
+ .map((fp) => ({ filePath: fp, elided: trimmedFiles.get(fp) }));
6922
+ const completenessCandidates = budget.includeCompletenessSignal
6923
+ ? exploreCompletenessNotes(filesIncluded, trimmedShown, [...renderedFilePaths, ...fileGroups.keys()])
6924
+ .map((note) => ['', '---', note])
6925
+ : anyFileTrimmed || trimmedShown.length > 0
6926
+ ? [['', `> 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
6927
  : [];
5551
- // Explore budget note based on project size.
6928
+ /** Whether a trimmed section survives in `text` — picks a fallback note's wording after a cut. */
6929
+ const trimmedIn = (text) => trimmedShown.some((t) => text.includes(`${FILE_SECTION_PREFIX}${t.filePath}\``));
6930
+ // Advisory exploration-guidance note based on project size. Deliberately
6931
+ // phrased as guidance, NOT a quota: agents read "budget / remaining calls /
6932
+ // Synthesize once" as a hard cap and stop exploring early, falling back to
6933
+ // grep + Read (which costs more tokens). The server never rejects or
6934
+ // rate-limits extra explore calls, and the note says so explicitly.
5552
6935
  let budgetBlock = [];
5553
6936
  if (budget.includeBudgetNote) {
5554
6937
  try {
5555
6938
  const stats = cg.getStats();
5556
6939
  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}.`];
6940
+ 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
6941
  }
5559
6942
  catch {
5560
6943
  // Stats unavailable — skip budget note
@@ -5568,40 +6951,24 @@ class ToolHandler {
5568
6951
  // one thing: a fixed floor the loop reserves for (the cut note, plus a
5569
6952
  // pointer for every file whose bytes were deliberately WITHHELD — CG-12
5570
6953
  // 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
- }
6954
+ // left. Assembled in priority order — the completeness note and the
6955
+ // pointers by `fitExploreEpilogue`'s rules, then the budget note — and
6956
+ // emitted in document order.
6957
+ const roomFor = roomForLines;
6958
+ // Less what the summary line will grow by when its sentinel is filled in.
6959
+ let room = hardCeiling - (flow.text.length + lines.join('\n').length)
6960
+ - Math.max(0, summaryReserve - SUMMARY_SENTINEL.length);
6961
+ const fitted = fitExploreEpilogue({
6962
+ room,
6963
+ noteCandidates: completenessCandidates,
6964
+ noteYields: trimmedShown.length > 0,
6965
+ pointerEntries,
6966
+ pointerOmitted,
6967
+ });
6968
+ const completenessBlock = fitted.note;
6969
+ const pointerBlock = fitted.pointers;
6970
+ room = fitted.room;
6971
+ const keepCompleteness = completenessBlock.length > 0;
5605
6972
  // Nothing of the pointer list survived, but there WAS one — say so, in the
5606
6973
  // one line that carries its instruction forward.
5607
6974
  const pointersLost = pointerEntries.length > 0 && pointerBlock.length === 0;
@@ -5613,8 +6980,10 @@ class ToolHandler {
5613
6980
  lines.push(...completenessBlock);
5614
6981
  if (keepBudgetNote)
5615
6982
  lines.push(...budgetBlock);
5616
- if (pointersLost && roomFor([EPILOGUE_LOST_NOTE, '']) <= room) {
5617
- lines.push('', EPILOGUE_LOST_NOTE);
6983
+ // Nothing has been cut yet, so every trimmed section is still in the response.
6984
+ const lostNote = exports.EXPLORE_FALLBACK_NOTES.lost[trimmedShown.length > 0 ? 'trimmed' : 'complete'];
6985
+ if (pointersLost && roomFor([lostNote, '']) <= room) {
6986
+ lines.push('', lostNote);
5618
6987
  }
5619
6988
  const output = flow.text + lines.join('\n');
5620
6989
  let finalText;
@@ -5627,7 +6996,7 @@ class ToolHandler {
5627
6996
  const epilogueOnlyCut = epilogueStart < lines.length
5628
6997
  ? flow.text + lines.slice(0, epilogueStart).join('\n')
5629
6998
  : 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.)';
6999
+ const EPILOGUE_CUT_NOTE = exports.EXPLORE_FALLBACK_NOTES.cut[epilogueOnlyCut !== null && trimmedIn(epilogueOnlyCut) ? 'trimmed' : 'complete'];
5631
7000
  if (output.length > hardCeiling
5632
7001
  && epilogueOnlyCut !== null
5633
7002
  && epilogueOnlyCut.length + EPILOGUE_CUT_NOTE.length <= hardCeiling) {
@@ -5644,7 +7013,7 @@ class ToolHandler {
5644
7013
  const lastSection = cut.lastIndexOf('\n' + FILE_SECTION_PREFIX);
5645
7014
  const boundary = lastSection > hardCeiling * 0.5 ? lastSection : cut.lastIndexOf('\n');
5646
7015
  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.)';
7016
+ finalText = safe + exports.EXPLORE_FALLBACK_NOTES.truncated[trimmedIn(safe) ? 'trimmed' : 'complete'];
5648
7017
  }
5649
7018
  else {
5650
7019
  finalText = output;
@@ -5676,6 +7045,7 @@ class ToolHandler {
5676
7045
  if (unresolvedPathSpans.length > 0) {
5677
7046
  summaryLine += ` No indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')}.`;
5678
7047
  }
7048
+ summaryLine += setAsideNote;
5679
7049
  finalText = finalText.replace(SUMMARY_SENTINEL, summaryLine);
5680
7050
  // Emit the allocation diagnostic from the FINAL text, so per-file bytes and
5681
7051
  // shares account for the hard-ceiling truncation above (CG-4).
@@ -5702,22 +7072,21 @@ class ToolHandler {
5702
7072
  });
5703
7073
  sourceBytes += emitted.bytes;
5704
7074
  }
5705
- return this.exploreResult(finalText, {
7075
+ // Include graph-only and omitted/deleted files, not just emitted source.
7076
+ const answerPaths = new Set(fileGroups.keys());
7077
+ for (const id of [...flow.pathNodeIds, ...flow.namedNodeIds]) {
7078
+ const node = cg.getNode(id);
7079
+ if (node)
7080
+ answerPaths.add(node.filePath);
7081
+ }
7082
+ const result = this.answerResult(cg, finalText, answerPaths);
7083
+ result[explore_session_state_1.EXPLORE_EMISSION_KEY] = {
5706
7084
  projectRoot,
5707
7085
  query,
5708
7086
  files: emittedFiles,
5709
7087
  sourceBytes,
5710
7088
  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;
7089
+ };
5721
7090
  return result;
5722
7091
  }
5723
7092
  /**
@@ -5844,24 +7213,63 @@ class ToolHandler {
5844
7213
  */
5845
7214
  async handleFileView(cg, fileArg, opts = {}) {
5846
7215
  const normalize = (p) => p.replace(/\\/g, '/').replace(/^(?:\.?\/+)+/, '').replace(/\/+$/, '');
5847
- const wantLower = normalize(fileArg).toLowerCase();
5848
7216
  const allFiles = cg.getFiles();
5849
7217
  if (allFiles.length === 0)
5850
7218
  return this.textResult('No files indexed. Run `codegraph index` first.');
5851
- let resolved = allFiles.find((f) => f.path.toLowerCase() === wantLower);
5852
- let candidates = [];
7219
+ // Resolve ONE spelling of the path against the index: exact, then
7220
+ // suffix-of-path, then substring — narrowing to a single file or handing
7221
+ // back the ambiguous set.
7222
+ const resolveOne = (want) => {
7223
+ const wantLower = normalize(want).toLowerCase();
7224
+ let file = allFiles.find((f) => f.path.toLowerCase() === wantLower);
7225
+ let found = [];
7226
+ if (!file) {
7227
+ found = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
7228
+ if (found.length === 1)
7229
+ file = found[0];
7230
+ }
7231
+ if (!file && found.length === 0) {
7232
+ found = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
7233
+ if (found.length === 1)
7234
+ file = found[0];
7235
+ }
7236
+ return { file, candidates: found };
7237
+ };
7238
+ // Agents and humans paste file references WITH a line suffix — `a.ts:12`,
7239
+ // `a.ts:12-40`, `a.ts#L88`, `a.ts#L12-L40`. explore already strips exactly
7240
+ // these shapes (src/search/query-paths.ts); file-view used to treat them as
7241
+ // part of the filename and report an indexed file as missing (#1831).
7242
+ // The literal spelling is tried FIRST, so a file genuinely named `foo:12`
7243
+ // still resolves to itself; only when that finds nothing is the suffix
7244
+ // stripped, and then the range becomes the read window.
7245
+ const LINE_SUFFIX = /(?::(\d+)(?:-(\d+))?|#L(\d+)(?:-L?(\d+))?)$/;
7246
+ let { file: resolved, candidates } = resolveOne(fileArg);
7247
+ let shownArg = fileArg;
5853
7248
  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];
7249
+ const m = LINE_SUFFIX.exec(normalize(fileArg));
7250
+ const stripped = m ? fileArg.slice(0, fileArg.length - m[0].length) : '';
7251
+ const retry = stripped ? resolveOne(stripped) : undefined;
7252
+ if (m && retry && (retry.file || retry.candidates.length > 0)) {
7253
+ resolved = retry.file;
7254
+ candidates = retry.candidates;
7255
+ shownArg = stripped;
7256
+ const startLine = Number(m[1] ?? m[3]);
7257
+ const endRaw = m[2] ?? m[4];
7258
+ const endLine = endRaw === undefined ? undefined : Number(endRaw);
7259
+ if (Number.isFinite(startLine) && startLine > 0) {
7260
+ // An explicit offset/limit from the caller always wins over the
7261
+ // suffix. `:12` alone is a "start here" pointer (Read given only an
7262
+ // offset); `:12-40` pins both ends.
7263
+ opts = {
7264
+ ...opts,
7265
+ offset: opts.offset ?? startLine,
7266
+ limit: opts.limit ?? (endLine !== undefined && endLine >= startLine ? endLine - startLine + 1 : undefined),
7267
+ };
7268
+ }
7269
+ }
5862
7270
  }
5863
7271
  if (!resolved && candidates.length > 1) {
5864
- return this.textResult([`"${fileArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
7272
+ return this.textResult([`"${shownArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
5865
7273
  ...candidates.slice(0, 25).map((f) => `- ${f.path}`)].join('\n'));
5866
7274
  }
5867
7275
  if (!resolved) {
@@ -6110,6 +7518,14 @@ class ToolHandler {
6110
7518
  lines.push(`> ⚠ ${(0, worktree_1.worktreeMismatchWarning)(mismatch).replace(/\n/g, '\n> ')}`, '');
6111
7519
  }
6112
7520
  lines.push(`**Files indexed:** ${stats.fileCount}`, `**Total nodes:** ${stats.nodeCount}`, `**Total edges:** ${stats.edgeCount}`, `**Database size:** ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
7521
+ // Exact CLI-parity change counts are measured on a worker: Git or the
7522
+ // filesystem fallback can stall on a large/busy checkout, but status must
7523
+ // not block the shared daemon's transport (#1959). Unknown is never zero.
7524
+ const lastIndexedAt = cg.getLastIndexedAt();
7525
+ const changes = await (0, index_freshness_1.measurePendingChanges)(cg.getProjectRoot());
7526
+ lines.push(`**Latest file indexed:** ${lastIndexedAt == null ? 'never' : new Date(lastIndexedAt).toISOString()}`, changes
7527
+ ? `**Changes since index:** ${changes.added} added, ${changes.modified} modified, ${changes.removed} removed`
7528
+ : '**Changes since index:** unknown (measurement timed out or failed; do not assume the index is current)');
6113
7529
  // Surface the active SQLite backend (node:sqlite, Node's built-in real
6114
7530
  // SQLite — full WAL + FTS5, no native build).
6115
7531
  lines.push(`**Backend:** node:sqlite (Node built-in) — full WAL + FTS5`);
@@ -6159,7 +7575,10 @@ class ToolHandler {
6159
7575
  // but the index is frozen — call that out explicitly here, the one place an
6160
7576
  // agent asks "is the index caught up?".
6161
7577
  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.');
7578
+ const recovering = cg.isWatcherRecovering();
7579
+ lines.push('', recovering ? '**Auto-sync recovering:**' : '**Auto-sync disabled:**', recovering
7580
+ ? '- File watching restarted; full index catch-up has not completed.'
7581
+ : `- ${cg.getWatcherDegradedReason() ?? 'live file watching stopped'}`, '- The index may be stale; Read files directly for current content.');
6163
7582
  }
6164
7583
  // Per-file freshness — the inverse of the auto-prepended staleness banner
6165
7584
  // (issue #403). Surfacing it inside `status` gives the agent a single
@@ -6175,7 +7594,9 @@ class ToolHandler {
6175
7594
  lines.push(`- ${p.path} (edited ${ageMs}ms ago, ${label})`);
6176
7595
  }
6177
7596
  }
6178
- return this.textResult(lines.join('\n'));
7597
+ return { ...this.textResult(lines.join('\n')), structuredContent: {
7598
+ freshness: { lastIndexedAt, changes, complete: changes !== null },
7599
+ } };
6179
7600
  }
6180
7601
  /**
6181
7602
  * Handle codegraph_files - get project file structure from the index
@@ -6347,72 +7768,11 @@ class ToolHandler {
6347
7768
  * Returns the best match and a note about alternatives if any.
6348
7769
  */
6349
7770
  /**
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`)
7771
+ * Check if a node matches a symbol query — see `matchesSymbol` in
7772
+ * `../graph/symbol-lookup`, which owns the rules.
6366
7773
  */
6367
7774
  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));
7775
+ return (0, symbol_lookup_1.matchesSymbol)(node, symbol);
6416
7776
  }
6417
7777
  /**
6418
7778
  * Find ALL definitions matching a name, ranked, so codegraph_node can return
@@ -6447,7 +7807,7 @@ class ToolHandler {
6447
7807
  // `stage_applyrun` and finds nothing. Re-search by the bare last part and
6448
7808
  // let `matchesSymbol` filter by qualifier.
6449
7809
  if (isQualified && results.length === 0) {
6450
- const tail = lastQualifierPart(symbol);
7810
+ const tail = (0, symbol_lookup_1.lastQualifierPart)(symbol);
6451
7811
  if (tail && tail !== symbol)
6452
7812
  results = cg.searchNodes(tail, { limit });
6453
7813
  }
@@ -6470,57 +7830,12 @@ class ToolHandler {
6470
7830
  /**
6471
7831
  * Find ALL symbols matching a name. Used by callers/callees/impact to aggregate
6472
7832
  * results across all matching symbols (e.g., multiple classes with an `execute` method).
7833
+ *
7834
+ * The resolution itself lives in `../graph/named-symbol-flow`, so the Flow
7835
+ * strip and `codegraph_explore` resolve a written name to the same nodes.
6473
7836
  */
6474
7837
  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 };
7838
+ return (0, named_symbol_flow_1.findAllSymbols)(cg, symbol);
6524
7839
  }
6525
7840
  /**
6526
7841
  * Truncate output if it exceeds the maximum length