tools.ts 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438
  1. /**
  2. * MCP Tool Definitions
  3. *
  4. * Defines the tools exposed by the CodeGraph MCP server.
  5. */
  6. import type CodeGraph from '../index';
  7. import { findNearestCodeGraphRoot } from '../directory';
  8. // Lazy-load the heavy CodeGraph chain off the MCP startup path — see the same
  9. // helper in engine.ts. ToolHandler must load to answer tools/list (static
  10. // schemas), but it must NOT drag in sqlite/query layers before the daemon binds;
  11. // CodeGraph is pulled in only when a tool actually opens a project. require() is
  12. // sync + cached (CommonJS build).
  13. const loadCodeGraph = (): typeof import('../index').default =>
  14. (require('../index') as typeof import('../index')).default;
  15. import {
  16. detectWorktreeIndexMismatch,
  17. worktreeMismatchWarning,
  18. worktreeMismatchNotice,
  19. type WorktreeIndexMismatch,
  20. } from '../sync/worktree';
  21. import type { PendingFile } from '../sync';
  22. import type { Node, Edge, SearchResult, Subgraph, NodeKind } from '../types';
  23. import { isTestFile } from '../search/query-utils';
  24. import {
  25. existsSync,
  26. readFileSync,
  27. } from 'fs';
  28. import { clamp, validatePathWithinRoot, validateProjectPath, isConfigLeafNode, CONFIG_LEAF_LANGUAGES } from '../utils';
  29. import { isGeneratedFile } from '../extraction/generated-detection';
  30. import { resolve as resolvePath } from 'path';
  31. /** Maximum output length to prevent context bloat (characters) */
  32. const MAX_OUTPUT_LENGTH = 15000;
  33. /**
  34. * Maximum length for free-form string inputs (query, task, symbol).
  35. * Bounds memory and CPU when a buggy or hostile MCP client sends a
  36. * huge payload — without this an attacker could ship a 100MB string
  37. * and force a full FTS5 scan / OOM the server. 10 000 characters is
  38. * far beyond any realistic legitimate query.
  39. */
  40. const MAX_INPUT_LENGTH = 10_000;
  41. /**
  42. * Maximum length for path-like string inputs (projectPath, path
  43. * filter, glob pattern). Paths beyond a few thousand chars are
  44. * never legitimate and signal abuse or a bug upstream.
  45. */
  46. const MAX_PATH_LENGTH = 4_096;
  47. /**
  48. * Rust path roots that have no file-system equivalent — `crate` is the
  49. * current crate, `super` is the parent module, `self` is the current
  50. * module. Used by `matchesSymbol` to strip these before file-path
  51. * matching so `crate::configurator::stage_apply::run` resolves the
  52. * same as `configurator::stage_apply::run`.
  53. */
  54. const RUST_PATH_PREFIXES = new Set(['crate', 'super', 'self']);
  55. /**
  56. * Node kinds that contain other symbols. For these, `codegraph_node` with
  57. * `includeCode=true` returns a structural outline (member names + signatures
  58. * + line numbers) instead of the full body, which for a large class is a
  59. * multi-thousand-character wall of source that bloats the agent's context.
  60. */
  61. const CONTAINER_NODE_KINDS = new Set<NodeKind>([
  62. 'class', 'struct', 'interface', 'trait', 'protocol', 'enum', 'namespace', 'module',
  63. ]);
  64. /** Last `::` / `.` / `/`-separated segment of a qualified symbol. */
  65. function lastQualifierPart(symbol: string): string {
  66. const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
  67. return parts[parts.length - 1] ?? symbol;
  68. }
  69. /**
  70. * Calculate the recommended number of codegraph_explore calls based on project size.
  71. * Larger codebases need more exploration calls to cover their surface area,
  72. * but smaller ones should use fewer to avoid unnecessary overhead.
  73. */
  74. export function getExploreBudget(fileCount: number): number {
  75. if (fileCount < 500) return 1;
  76. if (fileCount < 5000) return 2;
  77. if (fileCount < 15000) return 3;
  78. if (fileCount < 25000) return 4;
  79. return 5;
  80. }
  81. /**
  82. * Adaptive output budget for `codegraph_explore`, scaled to project size.
  83. *
  84. * Smaller codebases get a tighter total cap, fewer default files, smaller
  85. * per-file cap, and tighter clustering — so a focused query on a 100-file
  86. * project doesn't dump a whole file's worth of source into the agent's
  87. * context. Larger codebases keep the generous defaults because the
  88. * agent's native discovery cost (grep + find + many Reads) genuinely
  89. * dwarfs a fat explore call at that scale.
  90. *
  91. * Meta-text (relationships map, "additional relevant files" list,
  92. * completeness signal, budget note) is gated off for tiny projects
  93. * where one rich call is the whole story and the extra prose is just
  94. * overhead.
  95. *
  96. * Tier breakpoints mirror `getExploreBudget` so a project sits in the
  97. * same tier across both knobs.
  98. */
  99. export interface ExploreOutputBudget {
  100. /** Hard cap on total output characters. */
  101. maxOutputChars: number;
  102. /** Default `maxFiles` when the caller didn't specify one. */
  103. defaultMaxFiles: number;
  104. /** Cap on contiguous source returned per file (across all its clusters). */
  105. maxCharsPerFile: number;
  106. /** Cluster gap threshold in lines — tighter clustering on small projects. */
  107. gapThreshold: number;
  108. /** Max symbols listed in the per-file header (`#### path — sym(kind), ...`). */
  109. maxSymbolsInFileHeader: number;
  110. /** Max edges shown per relationship kind in the Relationships section. */
  111. maxEdgesPerRelationshipKind: number;
  112. /** Include the "Relationships" section. */
  113. includeRelationships: boolean;
  114. /** Include the "Additional relevant files (not shown)" trailing list. */
  115. includeAdditionalFiles: boolean;
  116. /** Include the "Complete source code is included above…" reminder. */
  117. includeCompletenessSignal: boolean;
  118. /** Include the explore-budget reminder at the end. */
  119. includeBudgetNote: boolean;
  120. /**
  121. * Hard-drop test/spec/icon/i18n files from the relevant-file set unless
  122. * the query itself mentions tests. Today they're only deprioritized in
  123. * the sort, which on tiny repos still lets one slip into the top N (e.g.
  124. * cobra's `command_test.go` displaced `args.go` and contributed ~10KB of
  125. * pure noise to "How does cobra parse commands?"). Off by default; on
  126. * for the very-tiny tier where one slip dominates the budget.
  127. */
  128. excludeLowValueFiles: boolean;
  129. }
  130. export function getExploreOutputBudget(fileCount: number): ExploreOutputBudget {
  131. // Tiered budget, scaled to project size. The budget is a CEILING (relevance
  132. // still gates WHAT is included), and it MUST stay under the agent's INLINE
  133. // tool-result cap (~25K chars). Above that, the host externalizes the result
  134. // to a file the agent then Reads back — re-introducing a read AND the
  135. // cache-write cost — which is exactly what a 35K vscode explore did in the
  136. // n=4 README A/B. So even large repos cap at ~24K: the answer is the handful
  137. // of ~100-line flow windows the agent would have grep-located and read (it
  138. // natively reads ~6–9 files, median 100-line ranges), NOT a sprawl of 12
  139. // files. Concentration onto the flow emerges from this cap + the named-file-
  140. // first sort dropping peripheral files. Invariant: a larger tier must never
  141. // get a smaller `maxCharsPerFile` than a smaller tier.
  142. if (fileCount < 150) {
  143. return {
  144. // ITER3: revert iter2's aggressive body shrink (forced Read fallback —
  145. // the per-file 2.5K cap pushed the agent to Read instead of node).
  146. // Back to the iter1 shape (13K/4/3.8K) but keep the test-file
  147. // hard-exclude. The cost lever for this tier lives in steering the
  148. // agent to stop after 1-2 calls, not in this budget.
  149. maxOutputChars: 13000,
  150. defaultMaxFiles: 4,
  151. maxCharsPerFile: 3800,
  152. gapThreshold: 7,
  153. maxSymbolsInFileHeader: 5,
  154. maxEdgesPerRelationshipKind: 4,
  155. includeRelationships: false,
  156. includeAdditionalFiles: false,
  157. includeCompletenessSignal: false,
  158. includeBudgetNote: false,
  159. excludeLowValueFiles: true,
  160. };
  161. }
  162. if (fileCount < 500) {
  163. return {
  164. // ITER3: same revert/keep-filter pattern as <150.
  165. maxOutputChars: 18000,
  166. defaultMaxFiles: 5,
  167. maxCharsPerFile: 3800,
  168. gapThreshold: 8,
  169. maxSymbolsInFileHeader: 6,
  170. maxEdgesPerRelationshipKind: 6,
  171. includeRelationships: false,
  172. includeAdditionalFiles: false,
  173. includeCompletenessSignal: false,
  174. includeBudgetNote: false,
  175. excludeLowValueFiles: true,
  176. };
  177. }
  178. if (fileCount < 5000) {
  179. return {
  180. // ~150-line per-file window (the native read unit) × ~6 files, capped at
  181. // the ~24K inline ceiling so the response is never externalized. Per-file
  182. // stays ≥ the <500 tier (3800) — monotonic.
  183. maxOutputChars: 24000,
  184. defaultMaxFiles: 8,
  185. maxCharsPerFile: 6500,
  186. gapThreshold: 12,
  187. maxSymbolsInFileHeader: 10,
  188. maxEdgesPerRelationshipKind: 10,
  189. includeRelationships: true,
  190. includeAdditionalFiles: true,
  191. includeCompletenessSignal: true,
  192. includeBudgetNote: true,
  193. excludeLowValueFiles: false,
  194. };
  195. }
  196. // Large + very-large repos: SAME ~24K inline ceiling (a bigger response just
  197. // externalizes — see vscode). More files indexed → more CALLS via
  198. // getExploreBudget, not a bigger single response. Per-file 7000 (≥ smaller
  199. // tiers) gives the central file a ~180-line orientation window.
  200. if (fileCount < 15000) {
  201. return {
  202. maxOutputChars: 24000,
  203. defaultMaxFiles: 8,
  204. maxCharsPerFile: 7000,
  205. gapThreshold: 15,
  206. maxSymbolsInFileHeader: 15,
  207. maxEdgesPerRelationshipKind: 15,
  208. includeRelationships: true,
  209. includeAdditionalFiles: true,
  210. includeCompletenessSignal: true,
  211. includeBudgetNote: true,
  212. excludeLowValueFiles: false,
  213. };
  214. }
  215. return {
  216. maxOutputChars: 24000,
  217. defaultMaxFiles: 8,
  218. maxCharsPerFile: 7000,
  219. gapThreshold: 15,
  220. maxSymbolsInFileHeader: 15,
  221. maxEdgesPerRelationshipKind: 15,
  222. includeRelationships: true,
  223. includeAdditionalFiles: true,
  224. includeCompletenessSignal: true,
  225. includeBudgetNote: true,
  226. excludeLowValueFiles: false,
  227. };
  228. }
  229. /**
  230. * Whether `codegraph_explore` should prefix source lines with their line
  231. * numbers (cat -n style: `<num>\t<code>`).
  232. *
  233. * Line numbers let the agent cite `file:line` straight from the explore
  234. * payload instead of re-Reading the file just to find a line number — the
  235. * dominant residual cost on precise-tracing questions (#185 follow-up).
  236. *
  237. * Defaults ON. Set `CODEGRAPH_EXPLORE_LINENUMS=0` to disable (used by the
  238. * A/B harness to measure the payload-cost vs. read-savings tradeoff).
  239. */
  240. function exploreLineNumbersEnabled(): boolean {
  241. return process.env.CODEGRAPH_EXPLORE_LINENUMS !== '0';
  242. }
  243. /**
  244. * Adaptive explore sizing (default ON). `codegraph_explore` skeletonizes OFF-SPINE
  245. * polymorphic-sibling files — a file whose class is one of ≥3 interchangeable
  246. * implementations of a shared interface (e.g. OkHttp's `: Interceptor` classes) —
  247. * to class + member signatures (bodies elided), keeping the on-spine exemplar full.
  248. * This sizes the response to the answer instead of the budget cap on sibling-heavy
  249. * flows (OkHttp interceptor-chain explore 28.5k→16.6k, ~28% cheaper than native
  250. * search, reads flat). It is PROVABLY INERT elsewhere: distinct pipeline steps (no
  251. * ≥3-implementer supertype, e.g. Excalidraw's `renderStaticScene`) and on-spine
  252. * files keep full source — output is byte-identical to shipped on excalidraw /
  253. * tokio / django / vscode / gin. Set `CODEGRAPH_ADAPTIVE_EXPLORE=0` to disable.
  254. */
  255. function adaptiveExploreEnabled(): boolean {
  256. return process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== '0' && process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== 'false';
  257. }
  258. /**
  259. * Prefix each line of a source slice with its 1-based line number, matching
  260. * the Read tool's `cat -n` convention (number + tab) so the agent treats it
  261. * the same way it treats Read output.
  262. *
  263. * @param slice contiguous source text (already extracted from the file)
  264. * @param firstLineNumber the 1-based line number of the slice's first line
  265. */
  266. function numberSourceLines(slice: string, firstLineNumber: number): string {
  267. const out: string[] = [];
  268. const split = slice.split('\n');
  269. for (let i = 0; i < split.length; i++) {
  270. out.push(`${firstLineNumber + i}\t${split[i]}`);
  271. }
  272. return out.join('\n');
  273. }
  274. /**
  275. * Per-file staleness banner emitted at the top of a tool response when the
  276. * file watcher has pending events for files referenced by the response.
  277. * The agent uses this to fall back to Read for those specific files
  278. * without waiting for the debounced sync (issue #403).
  279. */
  280. export function formatStaleBanner(stale: PendingFile[]): string {
  281. const now = Date.now();
  282. const lines = stale.map((p) => {
  283. const ageMs = Math.max(0, now - p.lastSeenMs);
  284. const label = p.indexing ? 'indexing in progress' : 'pending sync';
  285. return ` - ${p.path} (edited ${ageMs}ms ago, ${label})`;
  286. });
  287. return (
  288. '⚠️ Some files referenced below were edited since the last index sync — ' +
  289. 'their codegraph entries may be stale:\n' +
  290. lines.join('\n') +
  291. '\nFor accurate content of those specific files, Read them directly. ' +
  292. 'The rest of this response is fresh.'
  293. );
  294. }
  295. /**
  296. * Compact footer listing pending files that are NOT referenced in this
  297. * response. Gives the agent a complete project-wide freshness picture
  298. * without bloating the main banner.
  299. */
  300. export function formatStaleFooter(stale: PendingFile[]): string {
  301. const MAX = 5;
  302. const now = Date.now();
  303. const shown = stale.slice(0, MAX);
  304. const lines = shown.map((p) => {
  305. const ageMs = Math.max(0, now - p.lastSeenMs);
  306. return ` - ${p.path} (edited ${ageMs}ms ago)`;
  307. });
  308. const more = stale.length > MAX ? `\n - …and ${stale.length - MAX} more` : '';
  309. return (
  310. `(Note: ${stale.length} file(s) elsewhere in this project are pending index ` +
  311. `sync but were not referenced above:\n${lines.join('\n')}${more})`
  312. );
  313. }
  314. /**
  315. * MCP Tool definition
  316. */
  317. export interface ToolDefinition {
  318. name: string;
  319. description: string;
  320. inputSchema: {
  321. type: 'object';
  322. properties: Record<string, PropertySchema>;
  323. required?: string[];
  324. };
  325. }
  326. interface PropertySchema {
  327. type: string;
  328. description: string;
  329. enum?: string[];
  330. default?: unknown;
  331. }
  332. /**
  333. * Tool execution result
  334. */
  335. export interface ToolResult {
  336. content: Array<{
  337. type: 'text';
  338. text: string;
  339. }>;
  340. isError?: boolean;
  341. }
  342. /**
  343. * Common projectPath property for cross-project queries
  344. */
  345. const projectPathProperty: PropertySchema = {
  346. type: 'string',
  347. description: 'Path to a different project with .codegraph/ initialized. If omitted, uses current project. Use this to query other codebases.',
  348. };
  349. /**
  350. * All CodeGraph MCP tools
  351. *
  352. * Designed for minimal context usage - use codegraph_explore as the primary tool
  353. * (one call usually answers the whole question), and only use other tools for
  354. * targeted follow-up queries.
  355. *
  356. * All tools support cross-project queries via the optional `projectPath` parameter.
  357. */
  358. export const tools: ToolDefinition[] = [
  359. {
  360. name: 'codegraph_search',
  361. description: 'Quick symbol search by name. Returns locations only (no code). Use codegraph_explore instead to get the actual source / understand an area in one call.',
  362. inputSchema: {
  363. type: 'object',
  364. properties: {
  365. query: {
  366. type: 'string',
  367. description: 'Symbol name or partial name (e.g., "auth", "signIn", "UserService")',
  368. },
  369. kind: {
  370. type: 'string',
  371. description: 'Filter by node kind',
  372. enum: ['function', 'method', 'class', 'interface', 'type', 'variable', 'route', 'component'],
  373. },
  374. limit: {
  375. type: 'number',
  376. description: 'Maximum results (default: 10)',
  377. default: 10,
  378. },
  379. projectPath: projectPathProperty,
  380. },
  381. required: ['query'],
  382. },
  383. },
  384. {
  385. name: 'codegraph_callers',
  386. description: 'List functions that call <symbol>. For the full flow, use codegraph_explore.',
  387. inputSchema: {
  388. type: 'object',
  389. properties: {
  390. symbol: {
  391. type: 'string',
  392. description: 'Name of the function, method, or class to find callers for',
  393. },
  394. limit: {
  395. type: 'number',
  396. description: 'Maximum number of callers to return (default: 20)',
  397. default: 20,
  398. },
  399. projectPath: projectPathProperty,
  400. },
  401. required: ['symbol'],
  402. },
  403. },
  404. {
  405. name: 'codegraph_callees',
  406. description: 'List functions that <symbol> calls. For the full flow, use codegraph_explore.',
  407. inputSchema: {
  408. type: 'object',
  409. properties: {
  410. symbol: {
  411. type: 'string',
  412. description: 'Name of the function, method, or class to find callees for',
  413. },
  414. limit: {
  415. type: 'number',
  416. description: 'Maximum number of callees to return (default: 20)',
  417. default: 20,
  418. },
  419. projectPath: projectPathProperty,
  420. },
  421. required: ['symbol'],
  422. },
  423. },
  424. {
  425. name: 'codegraph_impact',
  426. description: 'List symbols affected by changing <symbol>. Use before a refactor.',
  427. inputSchema: {
  428. type: 'object',
  429. properties: {
  430. symbol: {
  431. type: 'string',
  432. description: 'Name of the symbol to analyze impact for',
  433. },
  434. depth: {
  435. type: 'number',
  436. description: 'How many levels of dependencies to traverse (default: 2)',
  437. default: 2,
  438. },
  439. projectPath: projectPathProperty,
  440. },
  441. required: ['symbol'],
  442. },
  443. },
  444. {
  445. name: 'codegraph_node',
  446. description: 'Two modes. (1) READ A FILE — use INSTEAD of the Read tool: pass `file` (a path or basename) with no `symbol` and it returns that file\'s current on-disk source with line numbers, exactly the shape Read gives you (`<n>\\t<line>`, safe to Edit from), narrowable with `offset`/`limit` just like Read — PLUS a one-line note of which files depend on it. Same bytes as Read, faster (served from the index), with the blast radius attached. Use it whenever you would Read a source file. (2) ONE SYMBOL you can name — its location, signature, verbatim source (includeCode=true) and caller/callee trail in one call, so before changing it you see what calls it and what your edit would break. For an AMBIGUOUS name it returns EVERY matching definition\'s body in one call (so you never Read a file to find the right overload); pass `file`/`line` to pin one. Use codegraph_explore for several related symbols or the full flow.',
  447. inputSchema: {
  448. type: 'object',
  449. properties: {
  450. symbol: {
  451. type: 'string',
  452. description: 'Name of the symbol to read (symbol mode). Omit it and pass `file` alone to read a whole file like Read.',
  453. },
  454. includeCode: {
  455. type: 'boolean',
  456. description: 'Symbol mode: include the symbol\'s full body (default: false). Ignored in file mode, which always returns source unless `symbolsOnly` is set.',
  457. default: false,
  458. },
  459. file: {
  460. type: 'string',
  461. description: 'A file path or basename (e.g. "harness.rs", "src/auth/session.ts"). Pass it ALONE (no symbol) to READ the file like the Read tool — its full source with line numbers + which files depend on it. Or pass it WITH a symbol to disambiguate an overloaded name to the definition in this file.',
  462. },
  463. offset: {
  464. type: 'number',
  465. description: 'File mode: 1-based line to start reading from, exactly like Read\'s offset. Defaults to the start of the file.',
  466. },
  467. limit: {
  468. type: 'number',
  469. description: 'File mode: maximum number of lines to return, exactly like Read\'s limit. Defaults to the whole file (capped at 2000 lines, like Read).',
  470. },
  471. symbolsOnly: {
  472. type: 'boolean',
  473. description: 'File mode: return just the file\'s symbol map + dependents (a cheap structural overview) instead of its source.',
  474. default: false,
  475. },
  476. line: {
  477. type: 'number',
  478. description: 'Symbol mode only: disambiguate to the definition at/around this line (use with the file:line a trail showed you).',
  479. },
  480. projectPath: projectPathProperty,
  481. },
  482. required: [],
  483. },
  484. },
  485. {
  486. name: 'codegraph_explore',
  487. description: 'PRIMARY TOOL — call FIRST for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or the symbols you are about to change. Returns the verbatim source of the relevant symbols grouped by file in ONE capped call (Read-equivalent — treat the shown source as already Read; do NOT re-open those files), plus the call path among them. Query can be a natural-language question OR a bag of symbol/file names. Usually the ONLY call you need — more accurate context, in far fewer tokens and round-trips than a search/Read/Grep loop.',
  488. inputSchema: {
  489. type: 'object',
  490. properties: {
  491. query: {
  492. type: 'string',
  493. description: 'Symbol names, file names, or short code terms to explore (e.g., "AuthService loginUser session-manager", "GraphTraverser BFS impact traversal.ts"). Use codegraph_search first to find relevant names.',
  494. },
  495. maxFiles: {
  496. type: 'number',
  497. description: 'Maximum number of files to include source code from (default: 12)',
  498. default: 12,
  499. },
  500. projectPath: projectPathProperty,
  501. },
  502. required: ['query'],
  503. },
  504. },
  505. {
  506. name: 'codegraph_status',
  507. description: 'Index health check (files / nodes / edges). Skip unless debugging.',
  508. inputSchema: {
  509. type: 'object',
  510. properties: {
  511. projectPath: projectPathProperty,
  512. },
  513. },
  514. },
  515. {
  516. name: 'codegraph_files',
  517. description: 'Indexed file tree with language + symbol counts. Faster than Glob for project layout.',
  518. inputSchema: {
  519. type: 'object',
  520. properties: {
  521. path: {
  522. type: 'string',
  523. description: 'Filter to files under this directory path (e.g., "src/components"). Returns all files if not specified.',
  524. },
  525. pattern: {
  526. type: 'string',
  527. description: 'Filter files matching this glob pattern (e.g., "*.tsx", "**/*.test.ts")',
  528. },
  529. format: {
  530. type: 'string',
  531. description: 'Output format: "tree" (hierarchical, default), "flat" (simple list), "grouped" (by language)',
  532. enum: ['tree', 'flat', 'grouped'],
  533. default: 'tree',
  534. },
  535. includeMetadata: {
  536. type: 'boolean',
  537. description: 'Include file metadata like language and symbol count (default: true)',
  538. default: true,
  539. },
  540. maxDepth: {
  541. type: 'number',
  542. description: 'Maximum directory depth to show (default: unlimited)',
  543. },
  544. projectPath: projectPathProperty,
  545. },
  546. },
  547. },
  548. ];
  549. /**
  550. * Allowlist-filtered tool definitions WITHOUT an engine — the static surface the
  551. * proxy answers `tools/list` with before any project is open. Mirrors
  552. * `ToolHandler.getTools()` in the no-CodeGraph case (the dynamic per-repo budget
  553. * note in a description only adds once `cg` is loaded; the schemas are static).
  554. */
  555. export function getStaticTools(): ToolDefinition[] {
  556. const raw = process.env.CODEGRAPH_MCP_TOOLS;
  557. if (!raw || !raw.trim()) return tools;
  558. const allow = new Set(raw.split(',').map(s => s.trim().replace(/^codegraph_/, '')).filter(Boolean));
  559. return allow.size ? tools.filter(t => allow.has(t.name.replace(/^codegraph_/, ''))) : tools;
  560. }
  561. /**
  562. * Tool handler that executes tools against a CodeGraph instance
  563. *
  564. * Supports cross-project queries via the projectPath parameter.
  565. * Other projects are opened on-demand and cached for performance.
  566. */
  567. export class ToolHandler {
  568. // Cache of opened CodeGraph instances for cross-project queries
  569. private projectCache: Map<string, CodeGraph> = new Map();
  570. // The directory the server last searched for a default project. Surfaced in
  571. // the "not initialized" error so users can see why detection missed.
  572. private defaultProjectHint: string | null = null;
  573. // Per-start-path cache of the git worktree/index mismatch (issue #155). The
  574. // mismatch is a fixed property of (where the request came from → which
  575. // .codegraph/ it resolves to), so the up-to-two `git rev-parse` spawns run
  576. // once and every later tool call reuses the result — never shelling out to
  577. // git on the hot path. `undefined` = not computed yet; `null` = no mismatch.
  578. private worktreeMismatchCache: Map<string, WorktreeIndexMismatch | null> = new Map();
  579. // Gate that the MCP engine pokes after `cg.open()` so the first tool call
  580. // blocks on the post-open filesystem reconcile (catch-up sync). Without
  581. // this, a tool call that races past `catchUpSync()` serves rows for files
  582. // that were deleted (or edited) while no MCP server was running — and the
  583. // per-file staleness banner can't help, because `getPendingFiles()` is
  584. // populated by the watcher, not by catch-up. Cleared on first await so
  585. // subsequent calls don't pay any cost.
  586. private catchUpGate: Promise<void> | null = null;
  587. constructor(private cg: CodeGraph | null) {}
  588. /**
  589. * Update the default CodeGraph instance (e.g. after lazy initialization)
  590. */
  591. setDefaultCodeGraph(cg: CodeGraph): void {
  592. this.cg = cg;
  593. }
  594. /**
  595. * Engine-only: register the catch-up sync promise so the next `execute()`
  596. * call awaits it before serving. The handler swallows rejections (the
  597. * engine logs them) so a sync failure never propagates as a tool error;
  598. * we still want to serve a best-effort result over the same potentially-
  599. * stale data, which is what would have happened without the gate.
  600. */
  601. setCatchUpGate(p: Promise<void> | null): void {
  602. this.catchUpGate = p;
  603. }
  604. /**
  605. * Record the directory the server tried to resolve the default project from.
  606. * Used only to make the "no default project" error actionable.
  607. */
  608. setDefaultProjectHint(searchedPath: string): void {
  609. this.defaultProjectHint = searchedPath;
  610. }
  611. /**
  612. * Whether a default CodeGraph instance is available
  613. */
  614. hasDefaultCodeGraph(): boolean {
  615. return this.cg !== null;
  616. }
  617. /**
  618. * Optional allowlist of exposed tools, parsed from the CODEGRAPH_MCP_TOOLS
  619. * env var (comma-separated short names, e.g. "trace,search,node,context").
  620. * Unset/empty → every tool is exposed. Lets an operator (or an A/B harness)
  621. * trim the tool surface without rebuilding the client config; the ablated
  622. * tool is then truly absent from ListTools rather than merely denied on call.
  623. * Matching is on the short form, so "node" and "codegraph_node" both work.
  624. */
  625. private toolAllowlist(): Set<string> | null {
  626. const raw = process.env.CODEGRAPH_MCP_TOOLS;
  627. if (!raw || !raw.trim()) return null;
  628. const short = (s: string) => s.trim().replace(/^codegraph_/, '');
  629. const set = new Set(raw.split(',').map(short).filter(Boolean));
  630. return set.size ? set : null;
  631. }
  632. /** Whether a tool name passes the CODEGRAPH_MCP_TOOLS allowlist (if any). */
  633. private isToolAllowed(name: string): boolean {
  634. const allow = this.toolAllowlist();
  635. return !allow || allow.has(name.replace(/^codegraph_/, ''));
  636. }
  637. /**
  638. * Get tool definitions with dynamic descriptions based on project size.
  639. * The codegraph_explore tool description includes a budget recommendation
  640. * scaled to the number of indexed files. Honors the CODEGRAPH_MCP_TOOLS
  641. * allowlist so a trimmed surface is reflected in ListTools.
  642. */
  643. getTools(): ToolDefinition[] {
  644. const allow = this.toolAllowlist();
  645. let visible = allow
  646. ? tools.filter(t => allow.has(t.name.replace(/^codegraph_/, '')))
  647. : tools;
  648. if (!this.cg) return visible;
  649. try {
  650. const stats = this.cg.getStats();
  651. const budget = getExploreBudget(stats.fileCount);
  652. // Tiny-repo tool gating: on projects under TINY_REPO_FILE_THRESHOLD
  653. // files, only expose the 5 core tools (search, context, node,
  654. // explore, trace). The 5 omitted tools (callers, callees, impact,
  655. // status, files) reduce to one grep at this scale.
  656. //
  657. // n=2 audits ruled out cutting below 5 tools:
  658. // - 3-tool gate (search + context + trace): cost regressed on
  659. // cobra/ky/sinatra. The agent fell back to raw Reads to cover
  660. // what codegraph_node + codegraph_explore would have answered.
  661. // - 1-tool gate (search only): catastrophic regression — express
  662. // went from -43% WIN to +107% LOSS. With only search, the agent
  663. // can't navigate the call graph structurally and reads everything.
  664. //
  665. // 5 is the empirical lower bound. Tools beyond search/context/
  666. // node/explore/trace pay overhead that the agent doesn't recoup
  667. // on tiny-repo flow questions.
  668. // ITER4: raise threshold 150 → 500 so single-file frameworks
  669. // (sinatra at 159, slim_framework around 200) also get the
  670. // 5-tool surface. The empirical 5-tool floor was set on <150
  671. // probes; iter3 measurement showed sinatra is structurally the
  672. // SAME problem as cobra (single-file WITHOUT-arm Read wins),
  673. // so it deserves the same gating.
  674. const TINY_REPO_FILE_THRESHOLD = 500;
  675. const TINY_REPO_CORE_TOOLS = new Set([
  676. 'codegraph_explore',
  677. 'codegraph_search',
  678. 'codegraph_node',
  679. ]);
  680. if (stats.fileCount < TINY_REPO_FILE_THRESHOLD) {
  681. visible = visible.filter(t => TINY_REPO_CORE_TOOLS.has(t.name));
  682. }
  683. return visible.map(tool => {
  684. if (tool.name === 'codegraph_explore') {
  685. return {
  686. ...tool,
  687. description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
  688. };
  689. }
  690. return tool;
  691. });
  692. } catch {
  693. return visible;
  694. }
  695. }
  696. /**
  697. * Get CodeGraph instance for a project
  698. *
  699. * If projectPath is provided, opens that project's CodeGraph (cached).
  700. * Otherwise returns the default CodeGraph instance.
  701. *
  702. * Walks up parent directories to find the nearest .codegraph/ folder,
  703. * similar to how git finds .git/ directories.
  704. */
  705. private getCodeGraph(projectPath?: string): CodeGraph {
  706. if (!projectPath) {
  707. if (!this.cg) {
  708. const searched = this.defaultProjectHint ?? process.cwd();
  709. throw new Error(
  710. 'No CodeGraph project is loaded for this session.\n' +
  711. `Searched for a .codegraph/ directory starting from: ${searched}\n` +
  712. 'The index is likely fine — this is a working-directory detection issue: ' +
  713. "the MCP client launched the server outside your project and didn't report the " +
  714. 'workspace root. Fix it either way:\n' +
  715. ' • Pass projectPath to the tool call, e.g. projectPath: "/absolute/path/to/your/project"\n' +
  716. ' • Or add --path to the server\'s MCP config args: ["serve", "--mcp", "--path", "/absolute/path/to/your/project"]'
  717. );
  718. }
  719. return this.cg;
  720. }
  721. // Check cache first (using original path as key)
  722. if (this.projectCache.has(projectPath)) {
  723. return this.projectCache.get(projectPath)!;
  724. }
  725. // Reject sensitive system directories before opening. Only validate a
  726. // path that actually exists — a nested or not-yet-created sub-path of a
  727. // real project must still be allowed to resolve UP to its .codegraph/
  728. // root below (issue #238), so we don't run the existence-checking
  729. // validator on paths that are meant to walk up.
  730. if (existsSync(projectPath)) {
  731. const pathError = validateProjectPath(projectPath);
  732. if (pathError) {
  733. throw new Error(pathError);
  734. }
  735. }
  736. // Walk up parent directories to find nearest .codegraph/
  737. const resolvedRoot = findNearestCodeGraphRoot(projectPath);
  738. if (!resolvedRoot) {
  739. throw new Error(`CodeGraph not initialized in ${projectPath}. Run 'codegraph init' in that project first.`);
  740. }
  741. // If the path resolves to the default project, reuse the already-open
  742. // default instance rather than opening a SECOND connection to the same DB.
  743. // A duplicate connection serializes reads against the watcher's auto-sync
  744. // writes; on the wasm backend (no WAL) that surfaces as intermittent
  745. // "database is locked" on concurrent tool calls. See issue #238. Deliberately
  746. // not cached under projectPath — the server owns and closes the default
  747. // instance, so routing it through projectCache.closeAll() would double-close it.
  748. if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
  749. return this.cg;
  750. }
  751. // Check if we already have this resolved root cached (different path, same project)
  752. if (this.projectCache.has(resolvedRoot)) {
  753. const cg = this.projectCache.get(resolvedRoot)!;
  754. // Cache under original path too for faster future lookups
  755. this.projectCache.set(projectPath, cg);
  756. return cg;
  757. }
  758. // Open and cache under both paths
  759. const cg = loadCodeGraph().openSync(resolvedRoot);
  760. this.projectCache.set(resolvedRoot, cg);
  761. if (projectPath !== resolvedRoot) {
  762. this.projectCache.set(projectPath, cg);
  763. }
  764. return cg;
  765. }
  766. /**
  767. * Close all cached project connections
  768. */
  769. closeAll(): void {
  770. for (const cg of this.projectCache.values()) {
  771. cg.close();
  772. }
  773. this.projectCache.clear();
  774. this.worktreeMismatchCache.clear();
  775. }
  776. /**
  777. * Validate that a value is a non-empty string within length bounds.
  778. *
  779. * The `maxLength` cap protects against MCP clients that ship huge
  780. * payloads (10MB+ query strings either by accident or maliciously).
  781. * Without this, a single oversized input can pin the FTS5 index or
  782. * exhaust memory before any real work runs.
  783. */
  784. private validateString(
  785. value: unknown,
  786. name: string,
  787. maxLength: number = MAX_INPUT_LENGTH
  788. ): string | ToolResult {
  789. if (typeof value !== 'string' || value.length === 0) {
  790. return this.errorResult(`${name} must be a non-empty string`);
  791. }
  792. if (value.length > maxLength) {
  793. return this.errorResult(
  794. `${name} exceeds maximum length of ${maxLength} characters (got ${value.length})`
  795. );
  796. }
  797. return value;
  798. }
  799. /**
  800. * Validate an optional path-like string input. Returns the value if
  801. * valid (or undefined), or a ToolResult with the error.
  802. */
  803. private validateOptionalPath(
  804. value: unknown,
  805. name: string
  806. ): string | undefined | ToolResult {
  807. if (value === undefined || value === null) return undefined;
  808. if (typeof value !== 'string') {
  809. return this.errorResult(`${name} must be a string`);
  810. }
  811. if (value.length > MAX_PATH_LENGTH) {
  812. return this.errorResult(
  813. `${name} exceeds maximum length of ${MAX_PATH_LENGTH} characters (got ${value.length})`
  814. );
  815. }
  816. return value;
  817. }
  818. /**
  819. * Cached git worktree/index mismatch for a tool call's effective project.
  820. *
  821. * The "effective project" is what the request targets: an explicit
  822. * `projectPath` arg, else the directory the server resolved its default
  823. * project from (`defaultProjectHint`), else cwd. Memoized per start path —
  824. * see `worktreeMismatchCache`. Best-effort: if the project can't be resolved
  825. * (e.g. nothing initialized yet), it reports "no mismatch" so a tool is never
  826. * broken by this check.
  827. */
  828. private worktreeMismatchFor(projectPath?: string): WorktreeIndexMismatch | null {
  829. const startPath = projectPath ?? this.defaultProjectHint ?? process.cwd();
  830. const cached = this.worktreeMismatchCache.get(startPath);
  831. if (cached !== undefined) return cached;
  832. let mismatch: WorktreeIndexMismatch | null = null;
  833. try {
  834. mismatch = detectWorktreeIndexMismatch(startPath, this.getCodeGraph(projectPath).getProjectRoot());
  835. } catch {
  836. // No resolvable project (or any other resolution error) → nothing to warn.
  837. mismatch = null;
  838. }
  839. this.worktreeMismatchCache.set(startPath, mismatch);
  840. return mismatch;
  841. }
  842. /**
  843. * Prefix a successful read-tool result with a compact worktree-mismatch
  844. * notice when the resolved index belongs to a different git working tree than
  845. * the caller's (issue #155). Without this, an agent in a nested worktree
  846. * silently trusts main-branch results. No-op on error results and when there
  847. * is no mismatch. `codegraph_status` is excluded — it embeds its own verbose
  848. * warning — so it stays out of this path.
  849. */
  850. private withWorktreeNotice(result: ToolResult, projectPath?: string): ToolResult {
  851. if (result.isError) return result;
  852. const mismatch = this.worktreeMismatchFor(projectPath);
  853. if (!mismatch) return result;
  854. const notice = worktreeMismatchNotice(mismatch);
  855. const [first, ...rest] = result.content;
  856. if (first && first.type === 'text') {
  857. return { ...result, content: [{ type: 'text', text: `${notice}\n\n${first.text}` }, ...rest] };
  858. }
  859. return result;
  860. }
  861. /**
  862. * Annotate a successful read-tool result with per-file staleness — the
  863. * non-blocking answer to issue #403. The file watcher tracks every event
  864. * it sees per path; here we intersect "files referenced in this response"
  865. * against that pending set and prepend a compact banner so the agent can
  866. * fall back to Read for those *specific* files without waiting for the
  867. * debounced sync to fire. Other pending files in the project (not
  868. * referenced by this response) get a small footer so the agent has a
  869. * complete picture without bloating the banner.
  870. *
  871. * Cost when nothing is pending — the common case — is one boolean check.
  872. * No I/O, no parsing of markdown beyond a per-pending-file substring scan.
  873. */
  874. private withStalenessNotice(result: ToolResult, projectPath?: string): ToolResult {
  875. if (result.isError) return result;
  876. let cg: CodeGraph;
  877. try {
  878. cg = this.getCodeGraph(projectPath);
  879. } catch {
  880. return result; // no default project — leave as is
  881. }
  882. // Cross-project `projectPath` calls open a cached CodeGraph WITHOUT a
  883. // watcher (watchers are only attached to the default session project).
  884. // When the cross-project path happens to be the same project as the
  885. // default cg, the cached instance is the wrong one — its pendingFiles is
  886. // permanently empty. Detect the equal-path case and prefer the default
  887. // cg so the staleness signal still fires when an agent passes the
  888. // explicit projectPath form of its own project.
  889. if (this.cg && cg !== this.cg) {
  890. try {
  891. const sameProject =
  892. resolvePath(this.cg.getProjectRoot()) === resolvePath(cg.getProjectRoot());
  893. if (sameProject) cg = this.cg;
  894. } catch {
  895. /* getProjectRoot may throw on a closed instance — leave cg as is */
  896. }
  897. }
  898. // Defensive: some test fakes inject a partial CodeGraph stub without the
  899. // newer pending-files API. Treat missing/throwing as "no pending files."
  900. let pending: PendingFile[] = [];
  901. try {
  902. pending = cg.getPendingFiles?.() ?? [];
  903. } catch {
  904. return result;
  905. }
  906. if (pending.length === 0) return result;
  907. const [first, ...rest] = result.content;
  908. if (!first || first.type !== 'text') return result;
  909. const text = first.text;
  910. const inResponse: PendingFile[] = [];
  911. const elsewhere: PendingFile[] = [];
  912. for (const p of pending) {
  913. // Substring match against the project-relative POSIX path — that's
  914. // exactly the format both the watcher and every codegraph response
  915. // emit, so a plain includes() is sufficient and avoids regex pitfalls.
  916. if (text.includes(p.path)) inResponse.push(p);
  917. else elsewhere.push(p);
  918. }
  919. let banner = '';
  920. if (inResponse.length > 0) {
  921. banner = formatStaleBanner(inResponse);
  922. }
  923. let footer = '';
  924. if (elsewhere.length > 0) {
  925. footer = formatStaleFooter(elsewhere);
  926. }
  927. if (!banner && !footer) return result;
  928. const composed = [banner, text, footer].filter(Boolean).join('\n\n');
  929. return { ...result, content: [{ type: 'text', text: composed }, ...rest] };
  930. }
  931. /**
  932. * Execute a tool by name
  933. */
  934. async execute(toolName: string, args: Record<string, unknown>): Promise<ToolResult> {
  935. try {
  936. // Block the first tool call on the engine's post-open reconcile so we
  937. // never serve rows for files deleted/edited while no MCP server was
  938. // running. The gate is cleared after first await — subsequent calls
  939. // pay nothing. Catch-up failures are logged by the engine; we
  940. // proceed regardless so a transient sync error never breaks tools.
  941. if (this.catchUpGate) {
  942. const gate = this.catchUpGate;
  943. this.catchUpGate = null;
  944. try { await gate; } catch { /* engine already logged */ }
  945. }
  946. // Honor the optional tool allowlist (CODEGRAPH_MCP_TOOLS): a trimmed
  947. // surface rejects ablated tools defensively even if a client cached them.
  948. if (!this.isToolAllowed(toolName)) {
  949. return this.errorResult(`Tool ${toolName} is disabled via CODEGRAPH_MCP_TOOLS`);
  950. }
  951. // Cross-cutting input validation. All tools accept an optional
  952. // `projectPath` and most accept either `query`, `task`, or
  953. // `symbol` — bound their lengths centrally so individual handlers
  954. // can stay focused on tool-specific logic.
  955. const pathCheck = this.validateOptionalPath(args.projectPath, 'projectPath');
  956. if (typeof pathCheck === 'object' && pathCheck !== undefined) {
  957. return pathCheck;
  958. }
  959. // The `path` and `pattern` properties used by codegraph_files are
  960. // also path-shaped — apply the same cap.
  961. if (args.path !== undefined) {
  962. const check = this.validateOptionalPath(args.path, 'path');
  963. if (typeof check === 'object' && check !== undefined) return check;
  964. }
  965. if (args.pattern !== undefined) {
  966. const check = this.validateOptionalPath(args.pattern, 'pattern');
  967. if (typeof check === 'object' && check !== undefined) return check;
  968. }
  969. // Read tools resolve through a single result variable so cross-cutting
  970. // notices — worktree-index mismatch (issue #155) and per-file
  971. // staleness (issue #403) — can be applied in one place. status embeds
  972. // its own verbose worktree warning but still flows through the
  973. // staleness wrapper so its pending-files section stays consistent
  974. // with what the read tools surface.
  975. let result: ToolResult;
  976. switch (toolName) {
  977. case 'codegraph_search':
  978. result = await this.handleSearch(args); break;
  979. case 'codegraph_callers':
  980. result = await this.handleCallers(args); break;
  981. case 'codegraph_callees':
  982. result = await this.handleCallees(args); break;
  983. case 'codegraph_impact':
  984. result = await this.handleImpact(args); break;
  985. case 'codegraph_explore':
  986. result = await this.handleExplore(args); break;
  987. case 'codegraph_node':
  988. result = await this.handleNode(args); break;
  989. case 'codegraph_status':
  990. // status embeds the pending-files list as a first-class section
  991. // (see handleStatus), so we skip the auto-banner wrapper here to
  992. // avoid duplicating the same info at the top of the response.
  993. return await this.handleStatus(args);
  994. case 'codegraph_files':
  995. result = await this.handleFiles(args); break;
  996. default:
  997. return this.errorResult(`Unknown tool: ${toolName}`);
  998. }
  999. const withWorktree = this.withWorktreeNotice(result, args.projectPath as string | undefined);
  1000. return this.withStalenessNotice(withWorktree, args.projectPath as string | undefined);
  1001. } catch (err) {
  1002. return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}`);
  1003. }
  1004. }
  1005. /**
  1006. * Handle codegraph_search
  1007. */
  1008. private async handleSearch(args: Record<string, unknown>): Promise<ToolResult> {
  1009. const query = this.validateString(args.query, 'query');
  1010. if (typeof query !== 'string') return query;
  1011. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  1012. const kind = args.kind as string | undefined;
  1013. const rawLimit = Number(args.limit) || 10;
  1014. const limit = clamp(rawLimit, 1, 100);
  1015. const results = cg.searchNodes(query, {
  1016. limit,
  1017. kinds: kind ? [kind as NodeKind] : undefined,
  1018. });
  1019. if (results.length === 0) {
  1020. return this.textResult(`No results found for "${query}"`);
  1021. }
  1022. // Down-rank generated files within the FTS-returned set so a search
  1023. // for "Send" surfaces the hand-written keeper before .pb.go stubs
  1024. // that share the name. Stable: only reorders generated vs. not.
  1025. const ranked = [...results].sort((a, b) => {
  1026. const aGen = isGeneratedFile(a.node.filePath) ? 1 : 0;
  1027. const bGen = isGeneratedFile(b.node.filePath) ? 1 : 0;
  1028. return aGen - bGen;
  1029. });
  1030. const formatted = this.formatSearchResults(ranked);
  1031. return this.textResult(this.truncateOutput(formatted));
  1032. }
  1033. /**
  1034. * Handle codegraph_callers
  1035. */
  1036. private async handleCallers(args: Record<string, unknown>): Promise<ToolResult> {
  1037. const symbol = this.validateString(args.symbol, 'symbol');
  1038. if (typeof symbol !== 'string') return symbol;
  1039. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  1040. const limit = clamp((args.limit as number) || 20, 1, 100);
  1041. const allMatches = this.findAllSymbols(cg, symbol);
  1042. if (allMatches.nodes.length === 0) {
  1043. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  1044. }
  1045. // Aggregate callers across all matching symbols
  1046. const seen = new Set<string>();
  1047. const allCallers: Node[] = [];
  1048. for (const node of allMatches.nodes) {
  1049. for (const c of cg.getCallers(node.id)) {
  1050. if (!seen.has(c.node.id)) {
  1051. seen.add(c.node.id);
  1052. allCallers.push(c.node);
  1053. }
  1054. }
  1055. }
  1056. if (allCallers.length === 0) {
  1057. return this.textResult(`No callers found for "${symbol}"${allMatches.note}`);
  1058. }
  1059. const formatted = this.formatNodeList(allCallers.slice(0, limit), `Callers of ${symbol}`) + allMatches.note;
  1060. return this.textResult(this.truncateOutput(formatted));
  1061. }
  1062. /**
  1063. * Handle codegraph_callees
  1064. */
  1065. private async handleCallees(args: Record<string, unknown>): Promise<ToolResult> {
  1066. const symbol = this.validateString(args.symbol, 'symbol');
  1067. if (typeof symbol !== 'string') return symbol;
  1068. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  1069. const limit = clamp((args.limit as number) || 20, 1, 100);
  1070. const allMatches = this.findAllSymbols(cg, symbol);
  1071. if (allMatches.nodes.length === 0) {
  1072. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  1073. }
  1074. // Aggregate callees across all matching symbols
  1075. const seen = new Set<string>();
  1076. const allCallees: Node[] = [];
  1077. for (const node of allMatches.nodes) {
  1078. for (const c of cg.getCallees(node.id)) {
  1079. if (!seen.has(c.node.id)) {
  1080. seen.add(c.node.id);
  1081. allCallees.push(c.node);
  1082. }
  1083. }
  1084. }
  1085. if (allCallees.length === 0) {
  1086. return this.textResult(`No callees found for "${symbol}"${allMatches.note}`);
  1087. }
  1088. const formatted = this.formatNodeList(allCallees.slice(0, limit), `Callees of ${symbol}`) + allMatches.note;
  1089. return this.textResult(this.truncateOutput(formatted));
  1090. }
  1091. /**
  1092. * Handle codegraph_impact
  1093. */
  1094. private async handleImpact(args: Record<string, unknown>): Promise<ToolResult> {
  1095. const symbol = this.validateString(args.symbol, 'symbol');
  1096. if (typeof symbol !== 'string') return symbol;
  1097. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  1098. const depth = clamp((args.depth as number) || 2, 1, 10);
  1099. const allMatches = this.findAllSymbols(cg, symbol);
  1100. if (allMatches.nodes.length === 0) {
  1101. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  1102. }
  1103. // Aggregate impact across all matching symbols
  1104. const mergedNodes = new Map<string, Node>();
  1105. const mergedEdges: Edge[] = [];
  1106. const seenEdges = new Set<string>();
  1107. for (const node of allMatches.nodes) {
  1108. const impact = cg.getImpactRadius(node.id, depth);
  1109. for (const [id, n] of impact.nodes) {
  1110. mergedNodes.set(id, n);
  1111. }
  1112. for (const e of impact.edges) {
  1113. const key = `${e.source}->${e.target}:${e.kind}`;
  1114. if (!seenEdges.has(key)) {
  1115. seenEdges.add(key);
  1116. mergedEdges.push(e);
  1117. }
  1118. }
  1119. }
  1120. const mergedImpact = {
  1121. nodes: mergedNodes,
  1122. edges: mergedEdges,
  1123. roots: allMatches.nodes.map(n => n.id),
  1124. };
  1125. const formatted = this.formatImpact(symbol, mergedImpact) + allMatches.note;
  1126. return this.textResult(this.truncateOutput(formatted));
  1127. }
  1128. /**
  1129. * Describe a synthesized (dynamic-dispatch) edge for human output: how the
  1130. * callback was wired up — the bridge static parsing can't see. Returns null
  1131. * for ordinary static edges. Used by trace + the node trail so a synthesized
  1132. * hop reads as "registered via onUpdate at App.tsx:3148", not a bare arrow.
  1133. */
  1134. private synthEdgeNote(edge: Edge | null): { label: string; compact: string; registeredAt?: string } | null {
  1135. if (!edge || edge.provenance !== 'heuristic') return null;
  1136. const m = edge.metadata as Record<string, unknown> | undefined;
  1137. const registeredAt = typeof m?.registeredAt === 'string' ? m.registeredAt : undefined;
  1138. const at = registeredAt ? ` @${registeredAt}` : '';
  1139. if (m?.synthesizedBy === 'callback') {
  1140. const via = m.via ? `\`${String(m.via)}\`` : 'a registrar';
  1141. const field = m.field ? ` on .${String(m.field)}` : '';
  1142. return {
  1143. label: `callback — registered via ${via}${field} (dynamic dispatch)`,
  1144. compact: `dynamic: callback via ${via}${at}`,
  1145. registeredAt,
  1146. };
  1147. }
  1148. if (m?.synthesizedBy === 'event-emitter') {
  1149. const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
  1150. return {
  1151. label: `event ${ev} — emit → handler (dynamic dispatch)`,
  1152. compact: `dynamic: event ${ev}${at}`,
  1153. registeredAt,
  1154. };
  1155. }
  1156. if (m?.synthesizedBy === 'react-render') {
  1157. return {
  1158. label: `React re-render — \`setState\` re-runs render() (dynamic dispatch)`,
  1159. compact: `dynamic: React re-render via setState${at}`,
  1160. registeredAt,
  1161. };
  1162. }
  1163. if (m?.synthesizedBy === 'jsx-render') {
  1164. const child = m.via ? `<${String(m.via)}>` : 'a child component';
  1165. return {
  1166. label: `renders ${child} (JSX child — dynamic dispatch)`,
  1167. compact: `dynamic: renders ${child}`,
  1168. registeredAt,
  1169. };
  1170. }
  1171. if (m?.synthesizedBy === 'vue-handler') {
  1172. const ev = m.event ? `@${String(m.event)}` : 'a template event';
  1173. return {
  1174. label: `Vue template handler — bound to ${ev} (dynamic dispatch)`,
  1175. compact: `dynamic: Vue ${ev} handler`,
  1176. registeredAt,
  1177. };
  1178. }
  1179. if (m?.synthesizedBy === 'interface-impl') {
  1180. return {
  1181. label: `interface/abstract dispatch — runs the implementation override (dynamic dispatch)`,
  1182. compact: `dynamic: interface → impl${at}`,
  1183. registeredAt,
  1184. };
  1185. }
  1186. if (m?.synthesizedBy === 'closure-collection') {
  1187. const field = m.field ? `\`${String(m.field)}\`` : 'a collection';
  1188. return {
  1189. label: `closure collection — runs handlers appended to ${field} (dynamic dispatch)`,
  1190. compact: `dynamic: runs ${field} handlers${at}`,
  1191. registeredAt,
  1192. };
  1193. }
  1194. return null;
  1195. }
  1196. /**
  1197. * Flow-from-named-symbols: an agent's codegraph_explore query is a bag of
  1198. * symbol names that usually spans the flow it's investigating (e.g.
  1199. * "PmsProductController getList PmsProductService list PmsProductServiceImpl").
  1200. * Surface the longest call chain AMONG those named symbols — scoped to what the
  1201. * agent explicitly named, so (unlike a fuzzy relevance set) there's no
  1202. * wrong-feature wandering. Rides synthesized edges, so controller→service-
  1203. * interface→impl shows up. Returns '' if no chain of >=3 nodes exists.
  1204. *
  1205. * Ambiguous tokens (Java `list` → dozens of nodes) are disambiguated by
  1206. * CO-NAMING: the agent names the class too, so we keep only `list` candidates
  1207. * whose qualifiedName contains another named token (`PmsProductServiceImpl::list`),
  1208. * dropping unrelated `OmsOrderService::list`.
  1209. */
  1210. private buildFlowFromNamedSymbols(cg: CodeGraph, query: string): { text: string; pathNodeIds: Set<string>; namedNodeIds: Set<string>; uniqueNamedNodeIds: Set<string> } {
  1211. const EMPTY = { text: '', pathNodeIds: new Set<string>(), namedNodeIds: new Set<string>(), uniqueNamedNodeIds: new Set<string>() };
  1212. try {
  1213. const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
  1214. // Strip only a REAL file extension (Create.cs → Create); KEEP qualified
  1215. // names (Class.method / Class::method) — the agent's most precise input,
  1216. // resolved exactly by findAllSymbols. (The old strip mangled Class.method
  1217. // into Class, throwing the method away.)
  1218. 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)$/i;
  1219. const tokens = [...new Set(
  1220. query.split(/[\s,()[\]]+/)
  1221. .map((t) => t.replace(FILE_EXT, '').trim())
  1222. .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t))
  1223. )].slice(0, 16);
  1224. if (tokens.length < 2) return EMPTY;
  1225. // Pool of name SEGMENTS (Class + method from every token) used to
  1226. // disambiguate an ambiguous SIMPLE name: keep a candidate only if its
  1227. // CONTAINER class is itself named in the query.
  1228. const segPool = new Set<string>();
  1229. for (const t of tokens) for (const s of t.toLowerCase().split(/::|\./)) if (s) segPool.add(s);
  1230. const named = new Map<string, Node>();
  1231. // Nodes whose token is SPECIFIC — a (near-)unique callable name (<=3 defs in
  1232. // the whole graph). These are safe to SPARE a file on: the agent named THIS
  1233. // method (`getResponseWithInterceptorChain`, 1 def). A hyper-polymorphic name
  1234. // (`as_sql`, 110 defs across every Expression/Compiler subclass) is NOT here,
  1235. // so naming it doesn't keep every backend variant full and flood the budget.
  1236. const uniqueNamedNodeIds = new Set<string>();
  1237. for (const t of tokens) {
  1238. const cands = this.findAllSymbols(cg, t).nodes.filter((n) => CALLABLE.has(n.kind));
  1239. // A qualified or otherwise-specific name (<=3 hits) keeps all; an
  1240. // ambiguous simple name keeps only candidates whose container is named.
  1241. const specific = cands.length <= 3;
  1242. const pick = specific
  1243. ? cands
  1244. : cands.filter((n) => {
  1245. const segs = (n.qualifiedName || '').toLowerCase().split(/::|\./).filter(Boolean);
  1246. const container = segs.length >= 2 ? segs[segs.length - 2] : '';
  1247. return !!container && segPool.has(container);
  1248. });
  1249. for (const n of pick.slice(0, 6)) {
  1250. named.set(n.id, n);
  1251. if (specific) uniqueNamedNodeIds.add(n.id);
  1252. }
  1253. if (named.size > 40) break;
  1254. }
  1255. if (named.size < 2) return EMPTY;
  1256. const MAX_HOPS = 7;
  1257. let best: Array<{ node: Node; edge: Edge | null }> | null = null;
  1258. // BFS the full call graph (incl. synth edges) from each named seed, but
  1259. // only ACCEPT a sink that is also named — both ends anchored to symbols the
  1260. // agent named, so the chain stays on-topic while bridging intermediates
  1261. // (e.g. the exact interface overload) that the token resolution missed.
  1262. for (const seed of [...named.values()].slice(0, 8)) {
  1263. const parent = new Map<string, { prev: string | null; edge: Edge | null; node: Node }>();
  1264. parent.set(seed.id, { prev: null, edge: null, node: seed });
  1265. const q: Array<{ id: string; depth: number; streak: number }> = [{ id: seed.id, depth: 0, streak: 0 }];
  1266. let deep: string | null = null, deepDepth = 0;
  1267. const MAX_BRIDGE = 1; // ≤1 consecutive UNNAMED hop: bridge one missing intermediate, never wander a god-function's fan-out
  1268. for (let h = 0; h < q.length && parent.size < 1500; h++) {
  1269. const { id, depth, streak } = q[h]!;
  1270. if (id !== seed.id && named.has(id) && depth > deepDepth) { deep = id; deepDepth = depth; }
  1271. if (depth >= MAX_HOPS - 1) continue;
  1272. for (const c of cg.getCallees(id)) {
  1273. if (c.edge.kind !== 'calls' || parent.has(c.node.id)) continue;
  1274. const newStreak = named.has(c.node.id) ? 0 : streak + 1;
  1275. if (newStreak > MAX_BRIDGE) continue;
  1276. parent.set(c.node.id, { prev: id, edge: c.edge, node: c.node });
  1277. q.push({ id: c.node.id, depth: depth + 1, streak: newStreak });
  1278. }
  1279. }
  1280. if (!deep) continue;
  1281. const chain: Array<{ node: Node; edge: Edge | null }> = [];
  1282. let cur: string | null = deep;
  1283. while (cur) { const p = parent.get(cur); if (!p) break; chain.push({ node: p.node, edge: p.edge }); cur = p.prev; }
  1284. chain.reverse();
  1285. if (!best || chain.length > best.length) best = chain;
  1286. }
  1287. const hasMain = !!best && best.length >= 3;
  1288. const pathIds = new Set((best ?? []).map((s) => s.node.id));
  1289. // Supplementary: dynamic-dispatch (synthesized) edges incident to a NAMED
  1290. // symbol — the indirect hops an agent would otherwise grep/Read to
  1291. // reconstruct ("where do the appended `validators` actually run?"). The
  1292. // synth edge IS that answer, so surface it even when the OTHER end wasn't
  1293. // named (e.g. the agent names `validate` but not the `didCompleteTask`
  1294. // that drains the collection). On-topic by construction: only heuristic
  1295. // edges touching a symbol the agent named; skipped when the hop already
  1296. // shows in the main chain.
  1297. const synthLines: string[] = [];
  1298. const synthSeen = new Set<string>();
  1299. for (const n of named.values()) {
  1300. if (synthLines.length >= 6) break;
  1301. for (const { node: other, edge } of [...cg.getCallers(n.id), ...cg.getCallees(n.id)]) {
  1302. if (synthLines.length >= 6) break;
  1303. if (edge.provenance !== 'heuristic' || other.id === n.id) continue;
  1304. if (pathIds.has(edge.source) && pathIds.has(edge.target)) continue; // already in the main chain
  1305. const src = edge.source === n.id ? n : other;
  1306. const tgt = edge.source === n.id ? other : n;
  1307. const key = `${src.name}>${tgt.name}`;
  1308. if (synthSeen.has(key)) continue;
  1309. synthSeen.add(key);
  1310. const note = this.synthEdgeNote(edge);
  1311. synthLines.push(`- ${src.name} → ${tgt.name} [${note ? note.compact : edge.kind}]`);
  1312. }
  1313. }
  1314. if (!hasMain && synthLines.length === 0) return EMPTY;
  1315. const out: string[] = [];
  1316. if (hasMain) {
  1317. out.push('## Flow (call path among the symbols you queried)', '');
  1318. for (let i = 0; i < best!.length; i++) {
  1319. const step = best![i]!;
  1320. if (step.edge) { const sy = this.synthEdgeNote(step.edge); out.push(` ↓ ${sy ? sy.compact : step.edge.kind}`); }
  1321. out.push(`${i + 1}. ${step.node.name} (${step.node.filePath}:${step.node.startLine})`);
  1322. }
  1323. out.push('');
  1324. }
  1325. if (synthLines.length) {
  1326. out.push(
  1327. '## Dynamic-dispatch links among your symbols',
  1328. '(synthesized — the indirect hops grep/Read would reconstruct; the `@file:line` is the wiring site)',
  1329. '',
  1330. ...synthLines,
  1331. ''
  1332. );
  1333. }
  1334. out.push('> Full source for these symbols is below — the call flow among them, followed by their bodies.', '');
  1335. // namedNodeIds = every callable the agent explicitly named (a superset of
  1336. // the spine). A file holding one is something the agent asked to SEE, so it
  1337. // must keep full source even if it's an off-spine polymorphic sibling — the
  1338. // agent named `getResponseWithInterceptorChain` / `SQLCompiler.execute_sql`
  1339. // as the mechanism, not as an interchangeable leaf. See the skeleton gate.
  1340. return { text: out.join('\n'), pathNodeIds: pathIds, namedNodeIds: new Set(named.keys()), uniqueNamedNodeIds };
  1341. } catch {
  1342. return EMPTY;
  1343. }
  1344. }
  1345. /**
  1346. * Compact "blast radius" for the entry symbols of an explore result: who
  1347. * depends on each (callers) and which test files cover it — LOCATIONS ONLY,
  1348. * no source, so the agent knows what to update / re-verify before editing
  1349. * without reaching for a separate impact call. Always-on, but skips symbols
  1350. * that have no dependents (nothing to warn about), and returns '' when none
  1351. * qualify so a leaf-only exploration stays clean.
  1352. */
  1353. private buildBlastRadiusSection(cg: CodeGraph, subgraph: Subgraph): string {
  1354. const ROOT_CAP = 5; // only the symbols the query actually targeted
  1355. const FILE_CAP = 4; // caller files listed per symbol before "+N more"
  1356. const MEANINGFUL = new Set<string>([
  1357. 'function', 'method', 'class', 'interface', 'struct', 'trait', 'protocol',
  1358. 'enum', 'type_alias', 'component', 'constant', 'variable', 'property', 'field',
  1359. ]);
  1360. const rel = (p: string) => p.replace(/\\/g, '/');
  1361. const roots = subgraph.roots
  1362. .map((id) => subgraph.nodes.get(id))
  1363. .filter((n): n is Node => !!n && MEANINGFUL.has(n.kind))
  1364. .slice(0, ROOT_CAP);
  1365. if (roots.length === 0) return '';
  1366. const entries: string[] = [];
  1367. for (const root of roots) {
  1368. let callers: Array<{ node: Node }> = [];
  1369. try { callers = cg.getCallers(root.id) as Array<{ node: Node }>; } catch { /* skip this root */ }
  1370. const seen = new Set<string>();
  1371. const uniq: Node[] = [];
  1372. for (const c of callers) {
  1373. if (c?.node && !seen.has(c.node.id)) { seen.add(c.node.id); uniq.push(c.node); }
  1374. }
  1375. if (uniq.length === 0) continue; // no blast radius → nothing to flag
  1376. const callerFiles = [...new Set(uniq.map((n) => rel(n.filePath)))];
  1377. const testFiles = callerFiles.filter((f) => isTestFile(f));
  1378. const nonTest = callerFiles.filter((f) => !isTestFile(f));
  1379. const shown = nonTest.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ');
  1380. const more = nonTest.length > FILE_CAP ? ` +${nonTest.length - FILE_CAP} more` : '';
  1381. const where = nonTest.length > 0 ? ` in ${shown}${more}` : '';
  1382. const tests = testFiles.length > 0
  1383. ? `; tests: ${testFiles.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ')}${testFiles.length > FILE_CAP ? ` +${testFiles.length - FILE_CAP}` : ''}`
  1384. : '; ⚠️ no covering tests found';
  1385. entries.push(
  1386. `- \`${root.name}\` (${rel(root.filePath)}:${root.startLine}) — ${uniq.length} caller${uniq.length === 1 ? '' : 's'}${where}${tests}`,
  1387. );
  1388. }
  1389. if (entries.length === 0) return '';
  1390. return [
  1391. '### Blast radius — what depends on these (update/verify before editing)',
  1392. '',
  1393. ...entries,
  1394. '',
  1395. ].join('\n');
  1396. }
  1397. /**
  1398. * Graph-connectivity relevance via Random-Walk-with-Restart (personalized
  1399. * PageRank) from the query's matched SEED nodes over the call/reference graph.
  1400. *
  1401. * This is the ranking signal text search (FTS/bm25) CANNOT provide, and it's
  1402. * codegraph's home turf: relevance by STRUCTURE, not words. A file whose
  1403. * symbols are call-connected to the matched cluster accrues walk mass and
  1404. * ranks high; a lone TEXT match — e.g. `LensSwitcher.swift` matched the word
  1405. * "switch" from `switchOrganization`, but calls none of `setUser`/`fetchUser`
  1406. * — gets only its own restart probability and ranks ~0. Immune to the
  1407. * tokenization trap that fools term matching, deterministic, no embeddings.
  1408. *
  1409. * Undirected adjacency (reachability both ways), restart α=0.25 to the seeds,
  1410. * power iteration to convergence. Bounded to the already-relevant subgraph, so
  1411. * it's a few hundred nodes × ~25 iterations — negligible cost.
  1412. */
  1413. private computeGraphRelevance(
  1414. nodeIds: string[],
  1415. edges: Edge[],
  1416. seedIds: Set<string>,
  1417. ): Map<string, number> {
  1418. const out = new Map<string, number>();
  1419. const n = nodeIds.length;
  1420. if (n === 0) return out;
  1421. const idx = new Map<string, number>();
  1422. for (let i = 0; i < n; i++) idx.set(nodeIds[i]!, i);
  1423. const RANK_EDGES = new Set<string>([
  1424. 'calls', 'references', 'extends', 'implements', 'overrides',
  1425. 'instantiates', 'returns', 'type_of', 'imports',
  1426. ]);
  1427. const adj: number[][] = Array.from({ length: n }, () => []);
  1428. for (const e of edges) {
  1429. if (!RANK_EDGES.has(e.kind)) continue;
  1430. const i = idx.get(e.source);
  1431. const j = idx.get(e.target);
  1432. if (i === undefined || j === undefined || i === j) continue;
  1433. adj[i]!.push(j);
  1434. adj[j]!.push(i); // undirected — reachable either direction
  1435. }
  1436. // Restart vector: uniform over seeds present in the candidate set. (Falls
  1437. // back to uniform-over-all if no seed landed in the set, so we never return
  1438. // all-zero.)
  1439. const r = new Array<number>(n).fill(0);
  1440. let rsum = 0;
  1441. for (const id of seedIds) {
  1442. const i = idx.get(id);
  1443. if (i !== undefined) { r[i] = 1; rsum += 1; }
  1444. }
  1445. if (rsum === 0) { for (let i = 0; i < n; i++) r[i] = 1; rsum = n; }
  1446. for (let i = 0; i < n; i++) r[i]! /= rsum;
  1447. const alpha = 0.25;
  1448. let s = r.slice();
  1449. for (let iter = 0; iter < 25; iter++) {
  1450. const next = new Array<number>(n).fill(0);
  1451. for (let i = 0; i < n; i++) {
  1452. const si = s[i]!;
  1453. if (si === 0) continue;
  1454. const d = adj[i]!.length;
  1455. if (d === 0) { next[i]! += si; continue; } // dangling: keep its mass
  1456. const share = si / d;
  1457. for (const j of adj[i]!) next[j]! += share;
  1458. }
  1459. for (let i = 0; i < n; i++) s[i] = (1 - alpha) * next[i]! + alpha * r[i]!;
  1460. }
  1461. for (let i = 0; i < n; i++) out.set(nodeIds[i]!, s[i]!);
  1462. return out;
  1463. }
  1464. /**
  1465. * Handle codegraph_explore — deep exploration in a single call
  1466. *
  1467. * Strategy: find relevant symbols via graph traversal, group by file,
  1468. * then read contiguous file sections covering all symbols per file.
  1469. * This replaces multiple codegraph_node + Read calls.
  1470. *
  1471. * Output size is adaptive to project file count via
  1472. * `getExploreOutputBudget` — see #185 for why a fixed 35k cap was a
  1473. * tax on small projects while earning its keep on large ones.
  1474. */
  1475. private async handleExplore(args: Record<string, unknown>): Promise<ToolResult> {
  1476. const query = this.validateString(args.query, 'query');
  1477. if (typeof query !== 'string') return query;
  1478. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  1479. const projectRoot = cg.getProjectRoot();
  1480. // Resolve adaptive output budget from project size. Falls back to the
  1481. // largest-tier defaults if stats aren't available, which preserves
  1482. // pre-#185 behavior for callers that hit the rare stats failure.
  1483. let budget: ExploreOutputBudget;
  1484. try {
  1485. budget = getExploreOutputBudget(cg.getStats().fileCount);
  1486. } catch {
  1487. budget = getExploreOutputBudget(Infinity);
  1488. }
  1489. const maxFiles = clamp((args.maxFiles as number) || budget.defaultMaxFiles, 1, 20);
  1490. // Step 1: Find relevant context with generous parameters.
  1491. // Use a large maxNodes budget — explore has its own 35k char output limit
  1492. // that prevents context bloat, so more nodes just means better coverage
  1493. // across entry points (especially for large files like Svelte components).
  1494. const subgraph = await cg.findRelevantContext(query, {
  1495. searchLimit: 8,
  1496. traversalDepth: 3,
  1497. maxNodes: 200,
  1498. minScore: 0.2,
  1499. });
  1500. if (subgraph.nodes.size === 0) {
  1501. return this.textResult(`No relevant code found for "${query}"`);
  1502. }
  1503. // Graph-aware glue: findRelevantContext builds the subgraph from name/text
  1504. // search, so a method that BRIDGES named symbols — e.g. App.tsx's
  1505. // triggerRender, which calls the named triggerUpdate — is never a search hit
  1506. // and gets missed, forcing the agent to Read the file to trace it. Pull in
  1507. // the callers/callees of the entry (root) nodes, but ONLY those that live in
  1508. // files the subgraph already surfaces (where the agent reads to fill gaps),
  1509. // so we add wiring without dragging in unrelated files. These get an
  1510. // importance boost below so they survive the per-file cluster budget.
  1511. const glueNodeIds = new Set<string>();
  1512. const subgraphFiles = new Set<string>();
  1513. for (const n of subgraph.nodes.values()) subgraphFiles.add(n.filePath);
  1514. const GLUE_NODE_CAP = 60;
  1515. for (const rootId of subgraph.roots) {
  1516. if (glueNodeIds.size >= GLUE_NODE_CAP) break;
  1517. let neighbors: Node[] = [];
  1518. try {
  1519. neighbors = [
  1520. ...cg.getCallers(rootId).map(c => c.node),
  1521. ...cg.getCallees(rootId).map(c => c.node),
  1522. ];
  1523. } catch {
  1524. continue;
  1525. }
  1526. for (const nb of neighbors) {
  1527. if (glueNodeIds.size >= GLUE_NODE_CAP) break;
  1528. if (subgraph.nodes.has(nb.id)) continue;
  1529. if (!subgraphFiles.has(nb.filePath)) continue;
  1530. subgraph.nodes.set(nb.id, nb);
  1531. glueNodeIds.add(nb.id);
  1532. }
  1533. }
  1534. // Named-symbol seeding: findRelevantContext is an FTS/text rank, so a query
  1535. // that's a BAG of symbol names skewed toward one phase (Alamofire: 5 build
  1536. // terms, each a high-frequency name, vs 3 validate terms) lets the
  1537. // lower-frequency names fall below the search cut — their definitions, and
  1538. // whole files (Validation.swift), never get gathered, so they can never
  1539. // render and the agent Reads them. Resolve EACH named token to its
  1540. // substantive definition (skip empty stubs + test files, same relevance the
  1541. // trace endpoint picker uses) and inject it as an entry, so every symbol the
  1542. // agent explicitly named is in the subgraph and its file is scored.
  1543. const namedSeedIds = new Set<string>();
  1544. {
  1545. 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)$/i;
  1546. const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
  1547. const isTestPath = (p: string) => /(^|\/)(tests?|specs?|__tests__|testdata|mocks?|fixtures?)\//i.test(p) || /\.(test|spec)\.[a-z]+$/i.test(p);
  1548. const bodyLines = (n: Node) => Math.max(0, (n.endLine ?? n.startLine) - n.startLine);
  1549. const tokens = [...new Set(
  1550. query.split(/[\s,()[\]]+/)
  1551. .map((t) => t.replace(FILE_EXT, '').trim())
  1552. .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t))
  1553. )].slice(0, 16);
  1554. // PascalCase tokens in the query are type/file disambiguators — when the
  1555. // agent writes "DataRequest task validate", the `task`/`validate` it wants
  1556. // are DataRequest's, NOT the same-named overloads in Validation.swift /
  1557. // Concurrency.swift / the abstract base. Used below to bias overloaded
  1558. // names toward the file/class the query also names.
  1559. const typeTokens = tokens.filter((o) => /^[A-Z][A-Za-z0-9]{3,}/.test(o));
  1560. const inNamedContext = (n: Node) =>
  1561. typeTokens.some((ct) => {
  1562. const lc = ct.toLowerCase();
  1563. return n.filePath.toLowerCase().includes(lc) || n.qualifiedName.toLowerCase().includes(lc);
  1564. });
  1565. for (const t of tokens) {
  1566. // Enumerate ALL defs of a bare token via the direct index, not FTS — a
  1567. // 50+-overload name (tokio `poll`) ranks the wanted def (`Harness::poll`)
  1568. // below the FTS cut, so findAllSymbols would never see it and the
  1569. // type-token bias below couldn't pick the harness.rs one. (Same fix as
  1570. // codegraph_node's findSymbolMatches.) Qualified tokens keep findAllSymbols.
  1571. const isQual = /[.\/]|::/.test(t);
  1572. const raw = isQual ? this.findAllSymbols(cg, t).nodes : cg.getNodesByName(t);
  1573. const cands = raw
  1574. .filter((n) => CALLABLE.has(n.kind) && !isTestPath(n.filePath))
  1575. .sort((a, b) => (bodyLines(b) > 1 ? 1 : 0) - (bodyLines(a) > 1 ? 1 : 0) || bodyLines(b) - bodyLines(a));
  1576. // A specific name (<=3 defs) injects all its defs. An overloaded name
  1577. // (`validate` = 10, `request` = 44) would flood the subgraph, so inject
  1578. // only: the overloads whose file/class the query ALSO names (the agent
  1579. // told us which one it wants — DataRequest's, not Validation.swift's),
  1580. // capped; else fall back to the single most-substantive def. This is the
  1581. // explore-side mirror of codegraph_node's overload disambiguation.
  1582. let picks: Node[];
  1583. if (cands.length <= 3) {
  1584. picks = cands;
  1585. } else {
  1586. const ctx = cands.filter(inNamedContext);
  1587. picks = ctx.length > 0 ? ctx.slice(0, 4) : cands.slice(0, 1);
  1588. }
  1589. for (const n of picks) {
  1590. if (!subgraph.nodes.has(n.id)) subgraph.nodes.set(n.id, n);
  1591. // Mark as a named seed EVEN IF the FTS gather already had it — being
  1592. // "named by the agent" is independent of whether search happened to
  1593. // surface it, and it drives the +50 score, the gate, and the
  1594. // named-file sort below. (Previously only NEW injections were marked,
  1595. // so a named symbol FTS already gathered never sorted to the top.)
  1596. namedSeedIds.add(n.id);
  1597. }
  1598. }
  1599. }
  1600. // Step 2: Group nodes by file, score by relevance
  1601. const fileGroups = new Map<string, { nodes: Node[]; score: number }>();
  1602. const entryNodeIds = new Set([...subgraph.roots, ...namedSeedIds]);
  1603. // Build a set of nodes directly connected to entry points (depth 1)
  1604. const connectedToEntry = new Set<string>();
  1605. for (const edge of subgraph.edges) {
  1606. if (entryNodeIds.has(edge.source)) connectedToEntry.add(edge.target);
  1607. if (entryNodeIds.has(edge.target)) connectedToEntry.add(edge.source);
  1608. }
  1609. for (const node of subgraph.nodes.values()) {
  1610. // Skip import/export nodes — they add noise without information
  1611. if (node.kind === 'import' || node.kind === 'export') continue;
  1612. // SECURITY (#383): never render the on-disk source of a config-leaf
  1613. // (Spring application.{yml,properties} key) — its line is `key = <secret>`,
  1614. // so whole-file/cluster rendering here would push secrets into context
  1615. // unbidden. The key still appears in the flow/symbol listing above.
  1616. if (isConfigLeafNode(node)) continue;
  1617. const group = fileGroups.get(node.filePath) || { nodes: [], score: 0 };
  1618. group.nodes.push(node);
  1619. // Score: a NAMED-SEED node (a symbol the agent named that FTS missed, now
  1620. // injected) is worth far more than a mere reference — its file is where the
  1621. // answer lives. Without this, an incidental file that name-drops the flow
  1622. // (Combine.swift references request/task → score 23 from connected nodes)
  1623. // outranks the file that DEFINES a named symbol (Validation.swift's
  1624. // `validate` → 10) and steals its render slot. Definition ≫ reference.
  1625. if (namedSeedIds.has(node.id)) {
  1626. group.score += 50;
  1627. } else if (entryNodeIds.has(node.id)) {
  1628. group.score += 10;
  1629. } else if (connectedToEntry.has(node.id)) {
  1630. group.score += 3;
  1631. } else {
  1632. group.score += 1;
  1633. }
  1634. fileGroups.set(node.filePath, group);
  1635. }
  1636. // Only include files that have entry points or nodes directly connected to entry points
  1637. let relevantFiles = [...fileGroups.entries()].filter(([, group]) => group.score >= 3);
  1638. // Extract query terms for relevance checking
  1639. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
  1640. // Test/spec/icon/i18n file detector — used both for the pre-sort hard
  1641. // filter (tiny tier) and the comparator deprioritization (all tiers).
  1642. const isLowValue = (p: string) => {
  1643. const lp = p.toLowerCase();
  1644. return (
  1645. /\/(tests?|__tests?__|spec)\//.test(lp) ||
  1646. /_test\.go$/.test(lp) ||
  1647. /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
  1648. /_test\.py$/.test(lp) ||
  1649. /_spec\.rb$/.test(lp) ||
  1650. /_test\.rb$/.test(lp) ||
  1651. /\.(test|spec)\.[jt]sx?$/.test(lp) ||
  1652. /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
  1653. /(tests?|spec)\.cs$/.test(lp) ||
  1654. /tests?\.swift$/.test(lp) ||
  1655. /_test\.dart$/.test(lp) ||
  1656. /\bicons?\b/.test(lp) ||
  1657. /\bi18n\b/.test(lp)
  1658. );
  1659. };
  1660. // Hard-exclude test/spec files (ALL tiers, not just tiny). One slipped test
  1661. // file dominates the per-file budget on small repos (cobra's `command_test.go`
  1662. // displaced `args.go`) AND wastes budget on large ones (Django's
  1663. // `custom_lookups/tests.py` ate ~2.3 KB of the 28 KB cap, crowding out the
  1664. // SQLCompiler mechanism the agent then Read). A test file almost never answers
  1665. // an architecture question. Skip when the query itself is about tests — the
  1666. // legitimate "explore the tests" case — and only cut if ≥2 non-test candidates
  1667. // remain (else tests are the only signal for this area).
  1668. {
  1669. const queryMentionsTests = /\b(test|tests|testing|spec|verify|verifies)\b/i.test(query);
  1670. if (!queryMentionsTests) {
  1671. const nonLow = relevantFiles.filter(([p]) => !isLowValue(p));
  1672. if (nonLow.length >= 2) {
  1673. relevantFiles = nonLow;
  1674. }
  1675. }
  1676. }
  1677. // Secondary signal: how many DISTINCT query terms each file matches (path +
  1678. // symbol names). Kept only as a tiebreak — the PRIMARY relevance is graph
  1679. // connectivity below. (Term counting alone tied the real central file with
  1680. // incidental same-word matches; it's a weak text signal, not the ranker.)
  1681. const uniqueQueryTerms = [...new Set(queryTerms)].filter(t => t.length >= 3);
  1682. const fileTermHits = new Map<string, number>();
  1683. for (const [fp, group] of relevantFiles) {
  1684. const hay = fp.toLowerCase() + ' ' + group.nodes.map(n => n.name.toLowerCase()).join(' ');
  1685. let hits = 0;
  1686. for (const t of uniqueQueryTerms) if (hay.includes(t)) hits++;
  1687. fileTermHits.set(fp, hits);
  1688. }
  1689. // PRIMARY relevance: graph connectivity (Random-Walk-with-Restart from the
  1690. // matched seeds — see computeGraphRelevance). Aggregate each file's nodes'
  1691. // walk mass. This is the signal text search lacks: the real cluster
  1692. // (org-user.storage.ts, call-connected to the matches) accrues mass; a lone
  1693. // text match (LensSwitcher.swift, matched "switch" but calls nothing in the
  1694. // flow) gets only its restart probability → ~0, and is dropped by the gate.
  1695. const nodeRwr = this.computeGraphRelevance(
  1696. [...subgraph.nodes.keys()], subgraph.edges, entryNodeIds,
  1697. );
  1698. const fileGraphScore = new Map<string, number>();
  1699. for (const node of subgraph.nodes.values()) {
  1700. fileGraphScore.set(
  1701. node.filePath,
  1702. (fileGraphScore.get(node.filePath) ?? 0) + (nodeRwr.get(node.id) ?? 0),
  1703. );
  1704. }
  1705. const maxGraph = Math.max(0, ...fileGraphScore.values());
  1706. // Central file(s): the 1-2 most graph-central files that also match the
  1707. // query textually (so a connected hub-utility with no term match isn't
  1708. // mistaken for the subject). The heart of the answer — they earn the larger
  1709. // WHOLE-FILE ceiling below (a god-file central file still exceeds it and
  1710. // falls to generous full-method sectioning — never a whole dump).
  1711. const centralFiles = new Set(
  1712. [...fileGraphScore.entries()]
  1713. .filter(([fp, g]) => g > 0 && (fileTermHits.get(fp) ?? 0) >= 1)
  1714. .sort((a, b) => b[1] - a[1] || (fileTermHits.get(b[0]) ?? 0) - (fileTermHits.get(a[0]) ?? 0))
  1715. .slice(0, 2)
  1716. .map(([f]) => f),
  1717. );
  1718. // Files that DEFINE a symbol the agent named (or a subgraph root). These are
  1719. // the highest-relevance files there are — the agent asked for them by name —
  1720. // so the connectivity gate below must never drop them, even when their RWR
  1721. // mass is low (a leaf family file like codec.ts is call-connected to little
  1722. // but is exactly what the agent queried). Without this protection the gate
  1723. // prunes a named file and the agent Reads it back.
  1724. const entryFiles = new Set<string>();
  1725. for (const id of entryNodeIds) {
  1726. const n = subgraph.nodes.get(id);
  1727. if (n) entryFiles.add(n.filePath);
  1728. }
  1729. // Relevance gate (so the generous budget is a CEILING, not a target): keep a
  1730. // file only if it is STRUCTURALLY relevant by ANY of:
  1731. // - graph score within a fraction of the top (it's on/near the flow), OR
  1732. // - central (a query entry-point lives here), OR
  1733. // - it DEFINES a symbol the agent named (entryFiles), OR
  1734. // - it matches >= 2 DISTINCT named query terms — a strong text signal that
  1735. // the agent is asking about this file even when nothing calls it (codec.ts:
  1736. // the agent named `encode`/`Codec`/`JsonCodec`, all leaf classes with zero
  1737. // RWR mass — graph alone wrongly drops it).
  1738. // A lone text match on one shared word (LensSwitcher: term=1, g~0) is still
  1739. // dropped, so the budget never fills with incidental files. Guarded so it
  1740. // never prunes below 2.
  1741. if (maxGraph > 0) {
  1742. const gated = relevantFiles.filter(([fp]) =>
  1743. (fileGraphScore.get(fp) ?? 0) >= maxGraph * 0.06
  1744. || centralFiles.has(fp)
  1745. || entryFiles.has(fp)
  1746. || (fileTermHits.get(fp) ?? 0) >= 2,
  1747. );
  1748. if (gated.length >= 2) relevantFiles = gated;
  1749. }
  1750. // Sort files: graph-central first, then distinct-term match, then the
  1751. // existing low-value/generated/score tiebreaks.
  1752. // Files that DEFINE a symbol the agent NAMED. These sort first — ahead of
  1753. // graph connectivity — because the agent asked for them by name. Without
  1754. // this, a named leaf override reached only by dynamic dispatch (Alamofire's
  1755. // `DataRequest.task`/`validate`, low RWR mass) sorts below the high-
  1756. // connectivity abstract base (`Request.swift`) and the same-named overloads
  1757. // in other files (`Validation.swift`), falls outside the budget, and the
  1758. // agent Reads it. The named file is the answer — rank it at the top.
  1759. const namedSeedFiles = new Set<string>();
  1760. for (const id of namedSeedIds) {
  1761. const n = subgraph.nodes.get(id);
  1762. if (n) namedSeedFiles.add(n.filePath);
  1763. }
  1764. const sortedFiles = relevantFiles.sort((a, b) => {
  1765. const aPath = a[0].toLowerCase();
  1766. const bPath = b[0].toLowerCase();
  1767. // Agent-named files first (it asked for a symbol defined here by name).
  1768. const aNamed = namedSeedFiles.has(a[0]) ? 1 : 0;
  1769. const bNamed = namedSeedFiles.has(b[0]) ? 1 : 0;
  1770. if (aNamed !== bNamed) return bNamed - aNamed;
  1771. // Graph connectivity is the next key (small epsilon so near-ties fall
  1772. // through to the text signal rather than coin-flipping on float noise).
  1773. const aG = fileGraphScore.get(a[0]) ?? 0;
  1774. const bG = fileGraphScore.get(b[0]) ?? 0;
  1775. if (Math.abs(aG - bG) > maxGraph * 0.01) return bG - aG;
  1776. const aHits = fileTermHits.get(a[0]) ?? 0;
  1777. const bHits = fileTermHits.get(b[0]) ?? 0;
  1778. if (aHits !== bHits) return bHits - aHits;
  1779. const aLow = isLowValue(aPath);
  1780. const bLow = isLowValue(bPath);
  1781. if (aLow !== bLow) return aLow ? 1 : -1;
  1782. // Deprioritize generated source (.pb.go / .pulsar.go / _mocks.go / …) —
  1783. // the agent rarely needs to see the protobuf scaffold or gomock output
  1784. // when asking about the actual flow, and dumping their bodies inflates
  1785. // the response (the cosmos Q3 explore otherwise leads with
  1786. // `expected_keepers_mocks.go`, displacing the real `tally.go` content
  1787. // and forcing the agent to Read tally.go anyway).
  1788. const aGen = isGeneratedFile(a[0]);
  1789. const bGen = isGeneratedFile(b[0]);
  1790. if (aGen !== bGen) return aGen ? 1 : -1;
  1791. if (a[1].score !== b[1].score) return b[1].score - a[1].score;
  1792. return b[1].nodes.length - a[1].nodes.length;
  1793. });
  1794. // Step 3: Build relationship map
  1795. const lines: string[] = [
  1796. `## Exploration: ${query}`,
  1797. '',
  1798. `Found ${subgraph.nodes.size} symbols across ${fileGroups.size} files.`,
  1799. '',
  1800. ];
  1801. // Blast radius (always-on, compact): for the entry symbols, who depends on
  1802. // them + which tests cover them — locations only, no source — so the agent
  1803. // knows what to update/verify before editing without a separate call.
  1804. const blastRadius = this.buildBlastRadiusSection(cg, subgraph);
  1805. if (blastRadius) lines.push(blastRadius);
  1806. // Relationship map — show how symbols connect
  1807. const significantEdges = subgraph.edges.filter(e =>
  1808. e.kind !== 'contains' // skip contains — it's implied by file grouping
  1809. );
  1810. if (budget.includeRelationships && significantEdges.length > 0) {
  1811. lines.push('### Relationships');
  1812. lines.push('');
  1813. // Group edges by kind for readability
  1814. const byKind = new Map<string, Array<{ source: string; target: string }>>();
  1815. for (const edge of significantEdges) {
  1816. const sourceNode = subgraph.nodes.get(edge.source);
  1817. const targetNode = subgraph.nodes.get(edge.target);
  1818. if (!sourceNode || !targetNode) continue;
  1819. const group = byKind.get(edge.kind) || [];
  1820. group.push({ source: sourceNode.name, target: targetNode.name });
  1821. byKind.set(edge.kind, group);
  1822. }
  1823. for (const [kind, edges] of byKind) {
  1824. const cap = budget.maxEdgesPerRelationshipKind;
  1825. const shown = edges.slice(0, cap);
  1826. lines.push(`**${kind}:**`);
  1827. for (const e of shown) {
  1828. lines.push(`- ${e.source} → ${e.target}`);
  1829. }
  1830. if (edges.length > cap) {
  1831. lines.push(`- ... and ${edges.length - cap} more`);
  1832. }
  1833. lines.push('');
  1834. }
  1835. }
  1836. // Step 4: Read contiguous file sections
  1837. // Compute the flow spine once — used both to prepend the Flow section (below)
  1838. // and to gate adaptive source sizing: files on the spine get full source,
  1839. // off-spine peers skeletonize.
  1840. const flow = this.buildFlowFromNamedSymbols(cg, query);
  1841. // Polymorphic-sibling detector for adaptive sizing. A class that implements/
  1842. // extends a supertype shared by >= MIN_SIBLINGS classes is one of many
  1843. // INTERCHANGEABLE implementations (OkHttp's 14 `: Interceptor` classes —
  1844. // showing one + the rest as signatures is enough), as opposed to a DISTINCT
  1845. // pipeline step (Excalidraw's `renderStaticScene`, which shares no supertype and
  1846. // must stay full or the agent loses real content). Only off-spine sibling files
  1847. // skeletonize; distinct steps and on-spine files keep full source. Cache
  1848. // supertype→(has ≥N implementers) so this stays a handful of edge queries.
  1849. const MIN_SIBLINGS = 3;
  1850. const siblingSuper = new Map<string, boolean>();
  1851. const isPolymorphicSibling = (nodes: Node[]): boolean => {
  1852. for (const n of nodes) {
  1853. for (const e of cg.getOutgoingEdges(n.id)) {
  1854. if (e.kind !== 'implements' && e.kind !== 'extends') continue;
  1855. let many = siblingSuper.get(e.target);
  1856. if (many === undefined) {
  1857. many = cg.getIncomingEdges(e.target)
  1858. .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
  1859. siblingSuper.set(e.target, many);
  1860. }
  1861. if (many) return true;
  1862. }
  1863. }
  1864. return false;
  1865. };
  1866. // A file that DEFINES a polymorphic supertype (a class/interface with ≥
  1867. // MIN_SIBLINGS implementers) AND co-locates its subclasses is a redundant
  1868. // "family" file — Django's compiler.py holds `SQLCompiler` + its 4 subclasses
  1869. // (SQLInsert/Update/Delete/AggregateCompiler) in 2,266 lines. Such files are
  1870. // huge and read-anyway, so they should STILL skeletonize even when the agent
  1871. // named a method in them: a full one eats ~6.5K of the explore budget (Django
  1872. // is pinned at the 28K cap, truncating), starving the sibling files the agent
  1873. // then Reads. This flag OVERRIDES the named-callable spare below — it does NOT
  1874. // by itself spare a file. (OkHttp's RealCall implements the `Lockable` mixin
  1875. // but defines no ≥3-impl supertype, so the named spare keeps it full.)
  1876. const superMany = new Map<string, boolean>();
  1877. const definesPolymorphicSupertype = (nodes: Node[]): boolean => {
  1878. for (const n of nodes) {
  1879. if (n.kind !== 'class' && n.kind !== 'interface' && n.kind !== 'struct'
  1880. && n.kind !== 'trait' && n.kind !== 'protocol' && n.kind !== 'type_alias') continue;
  1881. let many = superMany.get(n.id);
  1882. if (many === undefined) {
  1883. many = cg.getIncomingEdges(n.id)
  1884. .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
  1885. superMany.set(n.id, many);
  1886. }
  1887. if (many) return true;
  1888. }
  1889. return false;
  1890. };
  1891. lines.push('### Source Code');
  1892. lines.push('');
  1893. lines.push('> The code below is the **verbatim, current on-disk source** of these files — re-read from disk on this call and line-numbered, byte-for-byte identical to what the Read tool returns. It is NOT a summary, outline, or stale cache. Treat each block as a Read you have already performed: do not Read a file shown here.');
  1894. lines.push('');
  1895. let totalChars = lines.join('\n').length;
  1896. let filesIncluded = 0;
  1897. let anyFileTrimmed = false;
  1898. for (const [filePath, group] of sortedFiles) {
  1899. if (filesIncluded >= maxFiles) break;
  1900. // A file DEFINES a named/spine symbol (the answer) vs merely references the
  1901. // flow. Past 90% budget, stop pulling INCIDENTAL files — but keep scanning
  1902. // for necessary ones, which render even past the cap (bounded by maxFiles).
  1903. // Without this `continue` (was an unconditional `break`), the loop stopped
  1904. // after the build + validators-exec files and never reached the ranked-in
  1905. // validate-logic file (Alamofire's Validation.swift).
  1906. const fileNecessary = group.nodes.some(n =>
  1907. entryNodeIds.has(n.id) || flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id));
  1908. if (!fileNecessary && totalChars > budget.maxOutputChars * 0.9) continue;
  1909. const absPath = validatePathWithinRoot(projectRoot, filePath);
  1910. if (!absPath || !existsSync(absPath)) continue;
  1911. let fileContent: string;
  1912. try {
  1913. fileContent = readFileSync(absPath, 'utf-8');
  1914. } catch {
  1915. continue;
  1916. }
  1917. const fileLines = fileContent.split('\n');
  1918. const lang = group.nodes[0]?.language || '';
  1919. // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
  1920. // to a per-symbol view when it's a redundant member of a polymorphic family.
  1921. // Engages iff ALL hold:
  1922. // 1. a flow spine exists,
  1923. // 2. no symbol in the file is on that spine (it's not the mechanism path),
  1924. // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
  1925. // 4. it is NOT SPARED, where a file is spared iff the agent named a
  1926. // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
  1927. // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
  1928. // base+subclasses "family" file like Django's compiler.py — collapse it).
  1929. // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
  1930. // subclass; naming it must NOT keep every backend variant + test file full
  1931. // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
  1932. // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
  1933. // agent NAMED or that's on the spine is shown with its FULL body (so the agent
  1934. // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
  1935. // every other symbol is just its signature. So the base mechanism survives while
  1936. // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
  1937. const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
  1938. const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
  1939. const spared = spareNamed && !fileDefinesSuper;
  1940. const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
  1941. const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
  1942. // On-spine god-file: the flow path runs THROUGH this file, but it also holds
  1943. // many OTHER named methods, and rendering all of them in full blows the
  1944. // per-file budget and starves the other flow files (Alamofire: the agent
  1945. // names ~7 Session.swift methods — the build spine PLUS off-path
  1946. // task/didCompleteTask — far past the whole response budget). Engage the
  1947. // per-symbol view to keep the SPINE full and collapse the off-path named
  1948. // methods to signatures. Only when there IS off-path content to shed —
  1949. // otherwise the spine is irreducible (a sequential flow has no redundancy),
  1950. // so leave it to the normal full render.
  1951. const namedBodyChars = group.nodes
  1952. .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
  1953. .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
  1954. const onSpineGodFile = hasSpineNode
  1955. && namedBodyChars > budget.maxCharsPerFile
  1956. && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
  1957. if (adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
  1958. && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
  1959. const syms = group.nodes
  1960. .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
  1961. .sort((a, b) => a.startLine - b.startLine);
  1962. // Pass 1: choose which symbols get a FULL body, by priority, greedily within
  1963. // a per-file body cap — so one huge family file can't body every named method
  1964. // and crowd out the other flow files (Django's query.py). A symbol earns a
  1965. // body if it's on-spine, or UNIQUELY named (`SQLCompiler.execute_sql`), or a
  1966. // co-named method WHEN this file DEFINES the family supertype (so the base
  1967. // `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides — and
  1968. // OkHttp's 5 `intercept`s if the agent names `intercept` — stay signatures).
  1969. const prio = (n: Node) => !CALLABLE_BODY.has(n.kind) ? 99
  1970. : flow.pathNodeIds.has(n.id) ? 0
  1971. : flow.uniqueNamedNodeIds.has(n.id) ? 1
  1972. : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 2 : 99;
  1973. // One ~250-line WINDOW per file. syms are taken by priority (spine first,
  1974. // then uniquely-named, then family-base), and the cap applies to ALL of
  1975. // them — including the spine — so a big-spine god-file (tokio's worker.rs:
  1976. // run→run_task→next_task→steal_work) can't eat the whole response and
  1977. // starve the co-flow file (harness.rs's poll). The native agent windows
  1978. // such a file too (~190 lines at a time), so this mimics, not truncates.
  1979. // Always emit ≥1 (never an empty section).
  1980. const bodyCap = budget.maxCharsPerFile * 1.5;
  1981. const bodyIds = new Set<string>();
  1982. let bodyChars = 0;
  1983. for (const n of syms.filter(n => prio(n) < 99 && n.endLine >= n.startLine).sort((a, b) => prio(a) - prio(b))) {
  1984. const sz = fileLines.slice(n.startLine - 1, n.endLine).join('\n').length;
  1985. if (bodyChars + sz > bodyCap && bodyIds.size > 0) continue;
  1986. bodyIds.add(n.id);
  1987. bodyChars += sz;
  1988. }
  1989. // Pass 2: render in line order — full body for chosen symbols, else the
  1990. // signature line (capped, with a "+N more" tail so the structure map of a
  1991. // god-file doesn't itself bloat the budget).
  1992. const skel: string[] = [];
  1993. let coveredUntil = 0; // skip symbols already inside an emitted body
  1994. let sigCount = 0, sigDropped = 0;
  1995. const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
  1996. for (const n of syms) {
  1997. if (n.startLine <= coveredUntil) continue;
  1998. if (bodyIds.has(n.id)) {
  1999. const end = n.endLine;
  2000. const body = fileLines.slice(n.startLine - 1, end).join('\n');
  2001. skel.push(exploreLineNumbersEnabled() ? numberSourceLines(body, n.startLine) : body);
  2002. coveredUntil = end;
  2003. } else {
  2004. // Elide the body, emit the signature. node.startLine can point at a
  2005. // decorator/annotation, so scan forward for the line that names the symbol.
  2006. let lineNo = n.startLine;
  2007. for (let k = 0; k < 4; k++) {
  2008. if ((fileLines[n.startLine - 1 + k] || '').includes(n.name)) { lineNo = n.startLine + k; break; }
  2009. }
  2010. if (lineNo <= coveredUntil) continue;
  2011. if (sigCount >= SIG_MAX) { sigDropped++; continue; }
  2012. const sig = (fileLines[lineNo - 1] || '').trim();
  2013. if (sig) { skel.push(exploreLineNumbersEnabled() ? `${lineNo}\t${sig}` : sig); sigCount++; }
  2014. }
  2015. }
  2016. if (sigDropped > 0) skel.push(`… +${sigDropped} more (signatures elided)`);
  2017. if (skel.length > 0) {
  2018. const names = [...new Set(group.nodes.filter(n => n.kind !== 'import' && n.kind !== 'export').map(n => n.name))]
  2019. .slice(0, budget.maxSymbolsInFileHeader).join(', ');
  2020. // Steer the agent to codegraph_explore for an elided body — NEVER to
  2021. // Read. The old "Read for more" / "Read for a full body" tags invited
  2022. // a Read of the very file just skeletonized; on a central, wanted file
  2023. // (Session.swift, DataRequest.swift) that fired an over-investigation
  2024. // spiral (the agent Read the skeletonized file, then kept digging).
  2025. // CLAUDE.md: explore output must never tell the agent to Read.
  2026. const tag = bodyIds.size > 0
  2027. ? 'focused (the methods you named in full, the rest as signatures — codegraph_explore a signature by name for its body; do NOT Read)'
  2028. : 'skeleton (signatures only — codegraph_explore a name for its full body; do NOT Read)';
  2029. lines.push(`#### ${filePath} — ${names} · ${tag}`, '', '```' + lang, skel.join('\n'), '```', '');
  2030. totalChars += skel.join('\n').length + 120;
  2031. filesIncluded++;
  2032. continue;
  2033. }
  2034. }
  2035. // Whole-file rule: if a relevant file is small enough to afford, return it
  2036. // ENTIRELY instead of clustering. Clustering exists to tame god-files
  2037. // (App.tsx ~13k lines); on a ~134-line component a cluster is a lossy
  2038. // subset of a file the agent will just Read in full anyway — costing a
  2039. // round-trip and a re-read every later turn. Reserve clustering for files
  2040. // too big to ship whole. Still bounded by the total maxOutputChars check.
  2041. //
  2042. // CENTRAL files (where the query's entry points live) get a larger — but
  2043. // bounded — ceiling: they're the heart of the answer, the file(s) the agent
  2044. // would Read whole, so a genuinely small one comes back whole rather than as
  2045. // thin clusters. A LARGE central file (the 791-line org-user store) exceeds
  2046. // the ceiling and falls through to sectioning/clustering below — full method
  2047. // bodies + signatures — so we never dump (or overflow on) a whole god-file.
  2048. const isCentralFile = centralFiles.has(filePath);
  2049. // Central files get a slightly larger whole-file window than peripheral ones,
  2050. // but a TIGHT one (~1.5× the per-file cap): the native read of a central file
  2051. // is a ~150–250 line orientation window, NOT the whole file. A flat "whole
  2052. // central file" both overflowed the inline cap AND starved the co-flow files
  2053. // (worker.rs ate the budget, dropping harness.rs's poll). A larger central
  2054. // file falls through to per-method windowing/clustering below.
  2055. const WHOLE_FILE_MAX_LINES = isCentralFile ? 280 : 220;
  2056. const WHOLE_FILE_MAX_CHARS = isCentralFile
  2057. ? Math.min(Math.max(0, budget.maxOutputChars - totalChars - 200), Math.round(budget.maxCharsPerFile * 1.5))
  2058. : budget.maxCharsPerFile * 3;
  2059. if (fileLines.length <= WHOLE_FILE_MAX_LINES && fileContent.length <= WHOLE_FILE_MAX_CHARS) {
  2060. const body = fileContent.replace(/\n+$/, '');
  2061. let wholeSection = exploreLineNumbersEnabled() ? numberSourceLines(body, 1) : body;
  2062. const uniqSymbols = [...new Set(
  2063. group.nodes
  2064. .filter(n => n.kind !== 'import' && n.kind !== 'export')
  2065. .map(n => `${n.name}(${n.kind})`)
  2066. )];
  2067. const headerNames = uniqSymbols.slice(0, budget.maxSymbolsInFileHeader);
  2068. const omitted = uniqSymbols.length - headerNames.length;
  2069. const wholeHeader = `#### ${filePath} — ${omitted > 0 ? `${headerNames.join(', ')}, +${omitted} more` : headerNames.join(', ')}`;
  2070. if (!fileNecessary && totalChars + wholeSection.length + 200 > budget.maxOutputChars) {
  2071. // Don't slice a whole file mid-method: an incidental file that doesn't
  2072. // fit is skipped; a necessary one (below) renders in full. Half a file
  2073. // forces the Read this is meant to prevent.
  2074. anyFileTrimmed = true;
  2075. continue;
  2076. }
  2077. lines.push(wholeHeader, '', '```' + lang, wholeSection, '```', '');
  2078. totalChars += wholeSection.length + 200;
  2079. filesIncluded++;
  2080. continue;
  2081. }
  2082. // Cluster nearby symbols to avoid reading huge gaps between distant symbols.
  2083. // Sort by start line, then merge overlapping/adjacent ranges (within the
  2084. // adaptive gap threshold). Include both node ranges AND edge source
  2085. // locations so template sections with component usages/calls are
  2086. // covered (not just script block symbols).
  2087. //
  2088. // Each range carries an `importance` score so we can rank clusters
  2089. // when the per-file budget forces us to drop some: entry-point nodes
  2090. // are worth 10, directly-connected nodes 3, peripheral nodes 1, and
  2091. // bare edge-source lines 2 (less than a connected node but more than
  2092. // a peripheral one — they hint at a reference but aren't a definition).
  2093. // Container kinds whose body can span most/all of a file. When such a
  2094. // node covers most of the file we drop it from the ranges: keeping it
  2095. // would merge every method inside it into one giant cluster spanning
  2096. // the whole file, which then tail-trims down to just the container's
  2097. // opening lines (its header/declarations) and buries the methods the
  2098. // query actually asked about (#185 follow-up — Session.swift in
  2099. // Alamofire is the canonical case: the `Session` class spans ~1,400
  2100. // lines). We want the granular symbols inside, not the envelope.
  2101. const ENVELOPE_KINDS = new Set(['file', 'module', 'class', 'struct', 'interface', 'enum', 'namespace', 'protocol', 'trait', 'component']);
  2102. // Cluster from this file's gathered nodes PLUS any callable the agent NAMED that
  2103. // lives here. Explore's relevance gather can miss a named method def in a huge
  2104. // non-sibling file — Django's query.py is 3,040 lines and `_fetch_all` (L2237)
  2105. // was gathered only as call-reference edges, never as a def, so it formed no
  2106. // cluster and the agent Read it back. Inject named defs directly and rank them
  2107. // ABOVE connected/glue nodes (importance 9) so their cluster wins the per-file
  2108. // budget — the agent explicitly asked for these symbols.
  2109. const rangeNodes = new Map<string, Node>();
  2110. for (const n of group.nodes) if (n.startLine > 0 && n.endLine > 0) rangeNodes.set(n.id, n);
  2111. for (const id of flow.namedNodeIds) {
  2112. if (rangeNodes.has(id)) continue;
  2113. const n = cg.getNode(id);
  2114. if (n && n.filePath === filePath && n.startLine > 0 && n.endLine > 0) rangeNodes.set(id, n);
  2115. }
  2116. const ranges: Array<{ start: number; end: number; name: string; kind: string; importance: number }> = [...rangeNodes.values()]
  2117. // Drop whole-file envelope nodes (containers covering >50% of the file).
  2118. .filter(n => !(ENVELOPE_KINDS.has(n.kind) && (n.endLine - n.startLine + 1) > fileLines.length * 0.5))
  2119. .map(n => {
  2120. let importance = 1;
  2121. if (entryNodeIds.has(n.id)) importance = 10;
  2122. else if (flow.namedNodeIds.has(n.id)) importance = 9; // agent named it → keep its cluster
  2123. else if (glueNodeIds.has(n.id)) importance = 6; // bridging caller/callee of an entry
  2124. else if (connectedToEntry.has(n.id)) importance = 3;
  2125. return { start: n.startLine, end: n.endLine, name: n.name, kind: n.kind, importance };
  2126. });
  2127. // Add edge source locations in this file — captures template references
  2128. // (component usages, event handlers) that aren't nodes themselves.
  2129. // Query edges directly from the DB (not just the subgraph) because BFS
  2130. // traversal may have pruned template reference targets due to node budget.
  2131. const edgeLines = new Set<string>(); // dedup by "line:name"
  2132. for (const node of group.nodes) {
  2133. const outgoing = cg.getOutgoingEdges(node.id);
  2134. for (const edge of outgoing) {
  2135. if (!edge.line || edge.line <= 0 || edge.kind === 'contains') continue;
  2136. const key = `${edge.line}:${edge.target}`;
  2137. if (edgeLines.has(key)) continue;
  2138. edgeLines.add(key);
  2139. // Look up target name from subgraph first, fall back to edge kind
  2140. const targetNode = subgraph.nodes.get(edge.target);
  2141. const targetName = targetNode?.name ?? edge.kind;
  2142. ranges.push({ start: edge.line, end: edge.line, name: targetName, kind: edge.kind, importance: 2 });
  2143. }
  2144. }
  2145. ranges.sort((a, b) => a.start - b.start);
  2146. if (ranges.length === 0) continue;
  2147. const gapThreshold = budget.gapThreshold;
  2148. const clusters: Array<{ start: number; end: number; symbols: string[]; score: number; maxImportance: number }> = [];
  2149. let current = {
  2150. start: ranges[0]!.start,
  2151. end: ranges[0]!.end,
  2152. symbols: [`${ranges[0]!.name}(${ranges[0]!.kind})`],
  2153. score: ranges[0]!.importance,
  2154. maxImportance: ranges[0]!.importance,
  2155. };
  2156. for (let i = 1; i < ranges.length; i++) {
  2157. const r = ranges[i]!;
  2158. if (r.start <= current.end + gapThreshold) {
  2159. current.end = Math.max(current.end, r.end);
  2160. current.symbols.push(`${r.name}(${r.kind})`);
  2161. current.score += r.importance;
  2162. current.maxImportance = Math.max(current.maxImportance, r.importance);
  2163. } else {
  2164. clusters.push(current);
  2165. current = {
  2166. start: r.start,
  2167. end: r.end,
  2168. symbols: [`${r.name}(${r.kind})`],
  2169. score: r.importance,
  2170. maxImportance: r.importance,
  2171. };
  2172. }
  2173. }
  2174. clusters.push(current);
  2175. // Build file section output from clusters, capped by per-file budget.
  2176. // The pathological case (#185): a file like Session.swift where every
  2177. // method is adjacent collapses into one cluster spanning the whole
  2178. // file, and dumping that into the agent's context is most of the
  2179. // token cost on small projects. We pick clusters in priority order
  2180. // until the per-file char cap is hit. Truly enormous single clusters
  2181. // get tail-trimmed with a marker.
  2182. const contextPadding = 3;
  2183. const withLineNumbers = exploreLineNumbersEnabled();
  2184. const buildSection = (c: { start: number; end: number }): string => {
  2185. const startIdx = Math.max(0, c.start - 1 - contextPadding);
  2186. const endIdx = Math.min(fileLines.length, c.end + contextPadding);
  2187. const slice = fileLines.slice(startIdx, endIdx).join('\n');
  2188. // startIdx is 0-based, so the slice's first line is line startIdx + 1.
  2189. return withLineNumbers ? numberSourceLines(slice, startIdx + 1) : slice;
  2190. };
  2191. // Language-neutral separator (no `//` — not a comment in Python, Ruby,
  2192. // etc.). With line numbers on, the line-number jump also signals the gap.
  2193. const GAP_MARKER = '\n\n... (gap) ...\n\n';
  2194. // Rank clusters for inclusion under the per-file cap. Entry-point
  2195. // clusters come first: a cluster containing a query entry point
  2196. // (importance 10) must outrank a dense block of mere declarations,
  2197. // otherwise on a large file like Session.swift the top-of-file class
  2198. // header + property list (many adjacent low-importance nodes, high
  2199. // density) wins the budget and buries the actual methods the query
  2200. // asked about (perform/didCreateURLRequest/task live deep in the
  2201. // file). Within the same importance tier, prefer density (score per
  2202. // line) so we still favor focused clusters over sprawling ones, then
  2203. // smaller span as a cheap-to-include tiebreak.
  2204. const rankedClusters = clusters
  2205. .map((c, i) => ({ idx: i, span: c.end - c.start + 1, c }))
  2206. .sort((a, b) => {
  2207. if (b.c.maxImportance !== a.c.maxImportance) return b.c.maxImportance - a.c.maxImportance;
  2208. const densityA = a.c.score / a.span;
  2209. const densityB = b.c.score / b.span;
  2210. if (densityB !== densityA) return densityB - densityA;
  2211. if (b.c.score !== a.c.score) return b.c.score - a.c.score;
  2212. return a.span - b.span;
  2213. });
  2214. // Per-file budget is the SMALLER of the per-file cap and what's left of the
  2215. // total output cap — so selection (which ranks by importance) keeps the
  2216. // high-importance clusters and drops peripheral ones, instead of the
  2217. // downstream source-order trim slicing off whatever comes last in the file.
  2218. // That source-order slice is what cut Django's `_fetch_all` (L2237, importance
  2219. // 9 — agent-named) when query.py was the last of four big files to be emitted.
  2220. const fileBudget = Math.min(budget.maxCharsPerFile, Math.max(0, budget.maxOutputChars - totalChars - 200));
  2221. const chosenIndices = new Set<number>();
  2222. let projectedChars = 0;
  2223. for (const rc of rankedClusters) {
  2224. const sectionLen = buildSection(rc.c).length + (chosenIndices.size > 0 ? GAP_MARKER.length : 0);
  2225. // Always take the top-ranked cluster, even if oversize, so we don't
  2226. // return an empty file section (agent would then re-Read the file,
  2227. // negating the savings).
  2228. if (chosenIndices.size === 0) {
  2229. chosenIndices.add(rc.idx);
  2230. projectedChars += sectionLen;
  2231. continue;
  2232. }
  2233. if (projectedChars + sectionLen > fileBudget) continue;
  2234. chosenIndices.add(rc.idx);
  2235. projectedChars += sectionLen;
  2236. }
  2237. // Emit chosen clusters in source order so the file reads top-to-bottom.
  2238. let fileSection = '';
  2239. const allSymbols: string[] = [];
  2240. for (let i = 0; i < clusters.length; i++) {
  2241. if (!chosenIndices.has(i)) continue;
  2242. const cluster = clusters[i]!;
  2243. const section = buildSection(cluster);
  2244. if (fileSection.length > 0) fileSection += GAP_MARKER;
  2245. fileSection += section;
  2246. allSymbols.push(...cluster.symbols);
  2247. }
  2248. // A chosen cluster is a COMPLETE method-range — we never cut through a body.
  2249. // An oversize single cluster (a long monolithic function) renders in FULL:
  2250. // half a method is useless (the agent just Reads the rest for the other half),
  2251. // which is the very fallback explore exists to prevent. A pathological file is
  2252. // bounded by the per-file cluster SELECTION above + the total hard ceiling.
  2253. if (chosenIndices.size < clusters.length) {
  2254. anyFileTrimmed = true;
  2255. }
  2256. // Dedupe + cap the symbols list shown in the per-file header. Some
  2257. // files (Session.swift in Alamofire) produced 3.4KB symbol lists
  2258. // from cluster scoring + edge-source lines, dwarfing the per-file
  2259. // body cap. Show top names by frequency, with a "+N more" tail.
  2260. const symbolCounts = new Map<string, number>();
  2261. for (const s of allSymbols) {
  2262. symbolCounts.set(s, (symbolCounts.get(s) ?? 0) + 1);
  2263. }
  2264. const sortedSymbols = [...symbolCounts.entries()]
  2265. .sort((a, b) => b[1] - a[1])
  2266. .map(([name]) => name);
  2267. const headerCap = budget.maxSymbolsInFileHeader;
  2268. const headerSymbols = sortedSymbols.slice(0, headerCap);
  2269. const omittedCount = sortedSymbols.length - headerSymbols.length;
  2270. const headerSuffix = omittedCount > 0
  2271. ? `${headerSymbols.join(', ')}, +${omittedCount} more`
  2272. : headerSymbols.join(', ');
  2273. const fileHeader = `#### ${filePath} — ${headerSuffix}`;
  2274. // The total cap bounds INCIDENTAL files only. A file that DEFINES a symbol
  2275. // the agent named (or that's on the flow spine) renders even when the
  2276. // nominal total is used up — it's the answer, and the set is bounded by
  2277. // maxFiles AND by true-spine/named-seeding having already trimmed each file
  2278. // to its necessary content. A file that merely REFERENCES the flow
  2279. // (Combine.swift name-drops request/task) is incidental → still capped, so
  2280. // freed budget never leaks into noise. This is the last god-file layer:
  2281. // build (Session, true-spined) + validators-exec (Request) + validate
  2282. // (DataRequest/Validation) all render, instead of the cap dropping whichever
  2283. // phase the file order happened to put last.
  2284. if (!fileNecessary && totalChars + fileSection.length + 200 > budget.maxOutputChars) {
  2285. // Incidental file that doesn't fit: SKIP it whole — never slice mid-method.
  2286. // Keep scanning for necessary files (which bypass this cap and render in
  2287. // full, bounded by the hard ceiling).
  2288. anyFileTrimmed = true;
  2289. continue;
  2290. }
  2291. lines.push(fileHeader);
  2292. lines.push('');
  2293. lines.push('```' + lang);
  2294. lines.push(fileSection);
  2295. lines.push('```');
  2296. lines.push('');
  2297. totalChars += fileSection.length + 200;
  2298. filesIncluded++;
  2299. }
  2300. // Add remaining files as references (from both relevant and peripheral files).
  2301. // Small projects (per budget) skip this — the relevant story already fits
  2302. // in the source section, and a trailing pointer list is pure overhead.
  2303. if (budget.includeAdditionalFiles) {
  2304. const remainingRelevant = sortedFiles.slice(filesIncluded);
  2305. const peripheralFiles = [...fileGroups.entries()]
  2306. .filter(([, group]) => group.score < 3)
  2307. .sort((a, b) => b[1].score - a[1].score);
  2308. const remainingFiles = [...remainingRelevant, ...peripheralFiles];
  2309. if (remainingFiles.length > 0) {
  2310. lines.push('### Not shown above — explore these names for their source');
  2311. lines.push('');
  2312. for (const [filePath, group] of remainingFiles.slice(0, 10)) {
  2313. const symbols = group.nodes.map(n => `${n.name}:${n.startLine}`).join(', ');
  2314. lines.push(`- ${filePath}: ${symbols}`);
  2315. }
  2316. if (remainingFiles.length > 10) {
  2317. lines.push(`- ... and ${remainingFiles.length - 10} more files`);
  2318. }
  2319. }
  2320. }
  2321. // Add completeness signal so agents know they don't need to re-read these files.
  2322. // On small projects the budget gates this off — but if we actually had to
  2323. // trim or drop clusters, surface a brief note so the agent knows it can
  2324. // still Read for more detail.
  2325. if (budget.includeCompletenessSignal) {
  2326. lines.push('');
  2327. lines.push('---');
  2328. lines.push(`> **Complete source for ${filesIncluded} files is included above — do NOT re-read them.** If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER codegraph_explore targeting those names — it returns the same source with line numbers and is cheaper and more complete than reading. Reserve Read for a single specific line range explore can't surface.`);
  2329. } else if (anyFileTrimmed) {
  2330. lines.push('');
  2331. lines.push(`> Some file sections were trimmed for size. For a specific symbol you still need, run another \`codegraph_explore\` (or \`codegraph_node\`) with its exact name — line-numbered source, cheaper and more complete than Read.`);
  2332. }
  2333. // Add explore budget note based on project size
  2334. if (budget.includeBudgetNote) {
  2335. try {
  2336. const stats = cg.getStats();
  2337. const callBudget = getExploreBudget(stats.fileCount);
  2338. lines.push('');
  2339. lines.push(`> **Explore budget: ${callBudget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).** Each call covers ~6 files; if your question spans more, spend your remaining calls on the uncovered area BEFORE falling back to Read — another explore is cheaper and more complete than reading those files. Synthesize once you've used ${callBudget}.`);
  2340. } catch {
  2341. // Stats unavailable — skip budget note
  2342. }
  2343. }
  2344. // Final ceiling — an ABSOLUTE inline cap, not a multiple of the budget. The
  2345. // render loop renders necessary (named/spine) files even a bit past
  2346. // maxOutputChars and caps only incidental ones, so this is the last safety.
  2347. // It MUST stay under the host's inline tool-result limit (~25K chars): above
  2348. // that the result is externalized to a file the agent Reads back (a 35K
  2349. // vscode explore did exactly this in the n=4 A/B). So allow a little
  2350. // necessary overflow above the 24K budget, but hard-stop at 25K — never into
  2351. // externalize territory.
  2352. const output = flow.text + lines.join('\n');
  2353. const hardCeiling = Math.min(Math.round(budget.maxOutputChars * 1.5), 25000);
  2354. if (output.length > hardCeiling) {
  2355. // Cut at a FILE-SECTION boundary (the last `#### ` header before the
  2356. // ceiling) so we drop whole trailing file-sections rather than slicing
  2357. // through a method body — a half-rendered method just forces the Read this
  2358. // tool exists to prevent. Fall back to a line boundary only if no section
  2359. // header sits in the back half (degenerate single-giant-section case).
  2360. const cut = output.slice(0, hardCeiling);
  2361. const lastSection = cut.lastIndexOf('\n#### ');
  2362. const boundary = lastSection > hardCeiling * 0.5 ? lastSection : cut.lastIndexOf('\n');
  2363. const safe = boundary > 0 ? cut.slice(0, boundary) : cut;
  2364. return this.textResult(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.)');
  2365. }
  2366. return this.textResult(output);
  2367. }
  2368. /**
  2369. * Handle codegraph_node
  2370. */
  2371. private async handleNode(args: Record<string, unknown>): Promise<ToolResult> {
  2372. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2373. // Default to false to minimize context usage
  2374. const includeCode = args.includeCode === true;
  2375. const fileHint = typeof args.file === 'string' && args.file.trim() ? args.file.trim() : undefined;
  2376. const lineHint = typeof args.line === 'number' && args.line > 0 ? args.line : undefined;
  2377. const offset = typeof args.offset === 'number' && args.offset > 0 ? Math.floor(args.offset) : undefined;
  2378. const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : undefined;
  2379. const symbolsOnly = args.symbolsOnly === true;
  2380. const symbolRaw = typeof args.symbol === 'string' ? args.symbol.trim() : '';
  2381. // FILE READ MODE: a `file` with no `symbol` reads that file like the Read
  2382. // tool — its current on-disk source with line numbers, narrowable with
  2383. // `offset`/`limit` exactly as Read does — PLUS a one-line blast-radius
  2384. // header (which files depend on it). `symbolsOnly` returns just the
  2385. // structural map instead. Backed by the index: same bytes Read gives you.
  2386. if (!symbolRaw && fileHint) {
  2387. return this.handleFileView(cg, fileHint, { offset, limit, symbolsOnly });
  2388. }
  2389. const symbol = this.validateString(args.symbol, 'symbol');
  2390. if (typeof symbol !== 'string') return symbol;
  2391. let matches = this.findSymbolMatches(cg, symbol);
  2392. if (matches.length === 0) {
  2393. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  2394. }
  2395. // Disambiguate a heavily-overloaded name to a specific definition the caller
  2396. // pinned by file/line (the `file:line` a trail or another tool showed it) —
  2397. // so it can fetch e.g. `Harness::poll` at harness.rs:153 out of 50+ `poll`s
  2398. // instead of Reading. file matches by path suffix/substring; line prefers the
  2399. // def whose body contains it, else the nearest start. Only narrows (never
  2400. // empties — if a hint matches nothing it's ignored).
  2401. if (matches.length > 1 && (fileHint || lineHint !== undefined)) {
  2402. const norm = (p: string) => p.replace(/\\/g, '/').toLowerCase();
  2403. let narrowed = matches;
  2404. if (fileHint) {
  2405. const fh = norm(fileHint);
  2406. const byFile = narrowed.filter((n) => norm(n.filePath).endsWith(fh) || norm(n.filePath).includes(fh));
  2407. if (byFile.length > 0) narrowed = byFile;
  2408. }
  2409. if (lineHint !== undefined && narrowed.length > 1) {
  2410. const containing = narrowed.filter((n) => n.startLine <= lineHint && (n.endLine ?? n.startLine) >= lineHint);
  2411. narrowed = containing.length > 0
  2412. ? containing
  2413. : [...narrowed].sort((a, b) => Math.abs(a.startLine - lineHint) - Math.abs(b.startLine - lineHint)).slice(0, 1);
  2414. }
  2415. if (narrowed.length > 0) matches = narrowed;
  2416. }
  2417. // Single definition — the common case.
  2418. if (matches.length === 1) {
  2419. return this.textResult(this.truncateOutput(await this.renderNodeSection(cg, matches[0]!, includeCode)));
  2420. }
  2421. // Multiple definitions share this name — overloads, or same-named methods on
  2422. // different types (Alamofire `didCompleteTask`/`task`/`validate`, gin
  2423. // `reset`). Returning ONE forces the agent to guess, and when it guesses
  2424. // wrong it READS the file to find the right overload — the dominant
  2425. // codegraph_node read cause on Swift/Go. So return them ALL: pack as many
  2426. // FULL bodies as fit a char budget (the agent gets the one it needs in this
  2427. // one call, no follow-up parameter to learn), and list any remainder by
  2428. // file:line so a large overload set can't overflow the per-tool cap.
  2429. const header = `**${matches.length} definitions named "${symbol}"**`;
  2430. if (!includeCode) {
  2431. const list = matches.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`);
  2432. return this.textResult(this.truncateOutput(
  2433. [header, '', 'Re-query with `includeCode: true` to get every body in one call — no need to pick one first.', '', ...list].join('\n'),
  2434. ));
  2435. }
  2436. const BODY_BUDGET = 12000; // leaves room under MAX_OUTPUT_LENGTH for the header + list
  2437. // The CHAR budget is the real limiter — keep the count cap high so a set of
  2438. // SHORT overloads (Alamofire's 10 `validate` variants, each a few lines) all
  2439. // render in full rather than relegating the one the agent wanted to a
  2440. // bodiless list. Only a set of many LARGE bodies hits the char budget first.
  2441. const HARD_CAP = 16;
  2442. const rendered: string[] = [];
  2443. const listed: Node[] = [];
  2444. let used = 0;
  2445. for (const n of matches) {
  2446. if (rendered.length >= HARD_CAP) { listed.push(n); continue; }
  2447. const section = await this.renderNodeSection(cg, n, true);
  2448. // Always emit the first; emit the rest only while within the char budget.
  2449. if (rendered.length === 0 || used + section.length <= BODY_BUDGET) {
  2450. rendered.push(section);
  2451. used += section.length;
  2452. } else {
  2453. listed.push(n);
  2454. }
  2455. }
  2456. const out: string[] = [
  2457. header,
  2458. `Returning ${rendered.length} in full${listed.length ? `; ${listed.length} more listed below` : ''} — pick the one you need (no Read required).`,
  2459. '',
  2460. rendered.join('\n\n---\n\n'),
  2461. ];
  2462. if (listed.length) {
  2463. const LIST_CAP = 20;
  2464. const shownList = listed.slice(0, LIST_CAP);
  2465. out.push(
  2466. '',
  2467. '### Other definitions',
  2468. ...shownList.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`),
  2469. );
  2470. if (listed.length > LIST_CAP) out.push(`- … +${listed.length - LIST_CAP} more`);
  2471. out.push(
  2472. '',
  2473. `> Need one of these in full? Call codegraph_node again with \`file\` (e.g. \`"${listed[0]!.filePath.split('/').pop()}"\`) or \`line\` — do NOT Read it.`,
  2474. );
  2475. }
  2476. return this.textResult(this.truncateOutput(out.join('\n')));
  2477. }
  2478. /**
  2479. * FILE READ MODE: resolve `fileArg` (path or basename) to an indexed file and
  2480. * read it like the Read tool — its current on-disk source with line numbers,
  2481. * narrowable with `offset`/`limit` exactly as Read's are — preceded by a
  2482. * one-line blast-radius header (which files depend on it). `symbolsOnly`
  2483. * returns just the structural map (symbols + dependents) instead of source.
  2484. *
  2485. * Parity goal: the numbered source block is byte-for-byte the shape Read
  2486. * returns (`<n>\t<line>`, no padding), so the agent treats it as a Read — only
  2487. * faster (served from the index) and with the blast radius attached. Security:
  2488. * yaml/properties files are summarized by key, never dumped (#383); reads go
  2489. * through validatePathWithinRoot (#527).
  2490. */
  2491. private async handleFileView(
  2492. cg: CodeGraph,
  2493. fileArg: string,
  2494. opts: { offset?: number; limit?: number; symbolsOnly?: boolean } = {},
  2495. ): Promise<ToolResult> {
  2496. const normalize = (p: string) => p.replace(/\\/g, '/').replace(/^(?:\.?\/+)+/, '').replace(/\/+$/, '');
  2497. const wantLower = normalize(fileArg).toLowerCase();
  2498. const allFiles = cg.getFiles();
  2499. if (allFiles.length === 0) return this.textResult('No files indexed. Run `codegraph index` first.');
  2500. let resolved = allFiles.find((f) => f.path.toLowerCase() === wantLower);
  2501. let candidates: typeof allFiles = [];
  2502. if (!resolved) {
  2503. candidates = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
  2504. if (candidates.length === 1) resolved = candidates[0];
  2505. }
  2506. if (!resolved && candidates.length === 0) {
  2507. candidates = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
  2508. if (candidates.length === 1) resolved = candidates[0];
  2509. }
  2510. if (!resolved && candidates.length > 1) {
  2511. return this.textResult(
  2512. [`"${fileArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
  2513. ...candidates.slice(0, 25).map((f) => `- ${f.path}`)].join('\n'),
  2514. );
  2515. }
  2516. if (!resolved) {
  2517. return this.textResult(
  2518. `No indexed file matches "${fileArg}". Codegraph indexes source files; configs/docs it doesn't parse won't appear — Read those directly.`,
  2519. );
  2520. }
  2521. const filePath = resolved.path;
  2522. const nodes = cg.getNodesInFile(filePath)
  2523. .filter((n) => n.kind !== 'file' && n.kind !== 'import' && n.kind !== 'export')
  2524. .sort((a, b) => a.startLine - b.startLine);
  2525. const dependents = cg.getFileDependents(filePath);
  2526. // Compact, one-line blast radius (codegraph's value-add over a plain Read).
  2527. const depSummary = dependents.length
  2528. ? `used by ${dependents.length} file${dependents.length === 1 ? '' : 's'}: ${dependents.slice(0, 8).join(', ')}${dependents.length > 8 ? `, +${dependents.length - 8} more` : ''}`
  2529. : 'no other indexed file depends on it';
  2530. // Symbol-map renderer — for symbolsOnly, the config fallback, and read errors.
  2531. const symbolMap = (heading: string, limit = 200): string[] => {
  2532. const lines: string[] = [heading];
  2533. for (const n of nodes.slice(0, limit)) {
  2534. const sig = n.signature ? ` ${n.signature.replace(/\s+/g, ' ').trim()}` : '';
  2535. lines.push(`- \`${n.name}\` (${n.kind})${sig} — :${n.startLine}`);
  2536. }
  2537. if (nodes.length > limit) lines.push(`- … +${nodes.length - limit} more`);
  2538. return lines;
  2539. };
  2540. // symbolsOnly → the cheap structural overview, no source.
  2541. if (opts.symbolsOnly) {
  2542. const out = [`**${filePath}** — ${nodes.length} symbol${nodes.length === 1 ? '' : 's'}, ${depSummary}`, ''];
  2543. if (nodes.length) out.push(...symbolMap('### Symbols'));
  2544. else out.push('_No indexed symbols in this file._');
  2545. out.push('', '> Drop `symbolsOnly` (or pass `offset`/`limit`) to read the source, like Read.');
  2546. return this.textResult(this.truncateOutput(out.join('\n')));
  2547. }
  2548. // SECURITY (#383): never dump a raw config/data file — a yaml/properties
  2549. // line is `key: <secret>`. Summarize by key and point to a real Read.
  2550. if (CONFIG_LEAF_LANGUAGES.has(resolved.language)) {
  2551. const out = [`**${filePath}** — configuration/data file, ${depSummary}`, ''];
  2552. if (nodes.length) out.push(...symbolMap('### Keys (values withheld for safety)'));
  2553. out.push('', '> Values may be secrets, so codegraph indexes keys only. Read the file directly if you need a value.');
  2554. return this.textResult(this.truncateOutput(out.join('\n')));
  2555. }
  2556. // Read the current bytes from disk through the security chokepoint
  2557. // (validatePathWithinRoot: blocks `../` traversal and symlink escapes, #527).
  2558. const abs = validatePathWithinRoot(cg.getProjectRoot(), filePath);
  2559. let content: string | null = null;
  2560. if (abs) {
  2561. try { content = readFileSync(abs, 'utf-8'); } catch { content = null; }
  2562. }
  2563. if (content === null) {
  2564. const out = [`**${filePath}** — could not read from disk (it may have moved since indexing). ${depSummary}`, ''];
  2565. if (nodes.length) out.push(...symbolMap('### Symbols'));
  2566. out.push('', `> Read \`${filePath}\` directly for its current content.`);
  2567. return this.textResult(this.truncateOutput(out.join('\n')));
  2568. }
  2569. // Split exactly as Read does — keep the trailing empty line a final newline
  2570. // produces (Read numbers it too), so line numbers line up byte-for-byte.
  2571. const fileLines = content.split('\n');
  2572. const total = fileLines.length;
  2573. // Read-parity windowing: `offset`/`limit` mean exactly what they do on Read
  2574. // (1-based start line; max line count). Default: the whole file, capped like
  2575. // Read at 2000 lines and bounded by a char budget that tracks explore's
  2576. // proven-safe ~38k response ceiling. Overflow is stated explicitly (Read
  2577. // paginates too) — never the silent 15k truncateOutput chop.
  2578. const CHAR_BUDGET = 38000;
  2579. const DEFAULT_LIMIT = 2000;
  2580. const offset = Math.max(1, opts.offset ?? 1);
  2581. if (offset > total) {
  2582. return this.textResult(`**${filePath}** has ${total} line${total === 1 ? '' : 's'} — offset ${offset} is past the end. ${depSummary}`);
  2583. }
  2584. const maxLines = Math.max(1, opts.limit ?? DEFAULT_LIMIT);
  2585. const start = offset - 1; // 0-based
  2586. const header = `**${filePath}** — ${total} lines, ${nodes.length} symbol${nodes.length === 1 ? '' : 's'} · ${depSummary}`;
  2587. // Numbered lines, byte-for-byte Read's shape: `<n>\t<line>`, no left-pad.
  2588. const numbered: string[] = [];
  2589. let used = header.length + 8;
  2590. let i = start;
  2591. for (; i < total && numbered.length < maxLines; i++) {
  2592. const ln = `${i + 1}\t${fileLines[i]}`;
  2593. if (used + ln.length + 1 > CHAR_BUDGET && numbered.length > 0) break;
  2594. numbered.push(ln);
  2595. used += ln.length + 1;
  2596. }
  2597. const shownEnd = start + numbered.length;
  2598. const complete = offset === 1 && shownEnd >= total;
  2599. const out: string[] = [header, '', ...numbered];
  2600. if (!complete) {
  2601. out.push(
  2602. '',
  2603. `(lines ${offset}–${shownEnd} of ${total} — pass \`offset\`/\`limit\` for another range, or \`codegraph_node <symbol>\` for one symbol in full)`,
  2604. );
  2605. }
  2606. // Self-bounded to CHAR_BUDGET — do NOT route through truncateOutput (15k).
  2607. return this.textResult(out.join('\n'));
  2608. }
  2609. /** Render one symbol: details + (optional) body/outline + its caller/callee trail. */
  2610. private async renderNodeSection(cg: CodeGraph, node: Node, includeCode: boolean): Promise<string> {
  2611. let code: string | null = null;
  2612. let outline: string | null = null;
  2613. if (includeCode) {
  2614. // For container symbols (class/interface/struct/…), the full body is the
  2615. // sum of every method body — a wall of source. Return a structural outline
  2616. // (members + signatures + line numbers) instead; leaf symbols return their
  2617. // full body.
  2618. if (CONTAINER_NODE_KINDS.has(node.kind)) {
  2619. outline = this.buildContainerOutline(cg, node);
  2620. }
  2621. if (!outline) {
  2622. code = await cg.getCode(node.id);
  2623. }
  2624. }
  2625. return this.formatNodeDetails(node, code, outline) + this.formatTrail(cg, node);
  2626. }
  2627. /**
  2628. * Build the "trail" for a symbol: its direct callees (what it calls) and
  2629. * callers (what calls it), each with file:line — so codegraph_node doubles as
  2630. * the structural Grep→Read→expand primitive: a spot PLUS where to go next.
  2631. * Capped to stay cheap. Walk the graph by calling codegraph_node on a trail
  2632. * entry; no Read needed for covered hops. Empty edges on a non-leaf often mean
  2633. * dynamic dispatch the static graph couldn't resolve — that absence is itself
  2634. * a signal (read that one hop) rather than a dead end.
  2635. */
  2636. private formatTrail(cg: CodeGraph, node: Node): string {
  2637. const TRAIL_CAP = 12;
  2638. const fmt = (e: { node: Node; edge: Edge }) => {
  2639. const base = `${e.node.name} (${e.node.filePath}:${e.node.startLine})`;
  2640. const synth = this.synthEdgeNote(e.edge);
  2641. return synth ? `${base} [${synth.compact}]` : base;
  2642. };
  2643. const collect = (edges: Array<{ node: Node; edge: Edge }>): Array<{ node: Node; edge: Edge }> => {
  2644. const seen = new Set<string>([node.id]);
  2645. const out: Array<{ node: Node; edge: Edge }> = [];
  2646. for (const e of edges) {
  2647. if (seen.has(e.node.id)) continue;
  2648. seen.add(e.node.id);
  2649. out.push(e);
  2650. }
  2651. return out;
  2652. };
  2653. const callees = collect(cg.getCallees(node.id));
  2654. const callers = collect(cg.getCallers(node.id));
  2655. if (callees.length === 0 && callers.length === 0) return '';
  2656. const lines: string[] = ['', '### Trail — codegraph_node any of these to follow it (no Read needed)'];
  2657. if (callees.length > 0) {
  2658. lines.push(`**Calls →** ${callees.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callees.length > TRAIL_CAP ? `, +${callees.length - TRAIL_CAP} more` : ''}`);
  2659. }
  2660. if (callers.length > 0) {
  2661. lines.push(`**Called by ←** ${callers.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callers.length > TRAIL_CAP ? `, +${callers.length - TRAIL_CAP} more` : ''}`);
  2662. }
  2663. return lines.join('\n');
  2664. }
  2665. /**
  2666. * Handle codegraph_status
  2667. */
  2668. private async handleStatus(args: Record<string, unknown>): Promise<ToolResult> {
  2669. let cg = this.getCodeGraph(args.projectPath as string | undefined);
  2670. // Same trick as withStalenessNotice — when an explicit projectPath
  2671. // resolves to the same project as the default session cg, prefer the
  2672. // default so getPendingFiles() (only populated by the default's watcher)
  2673. // is non-empty when there are pending edits.
  2674. if (this.cg && cg !== this.cg) {
  2675. try {
  2676. if (resolvePath(this.cg.getProjectRoot()) === resolvePath(cg.getProjectRoot())) {
  2677. cg = this.cg;
  2678. }
  2679. } catch { /* closed instance — leave as is */ }
  2680. }
  2681. const stats = cg.getStats();
  2682. // Warn when this index actually belongs to a different git working tree
  2683. // (e.g. the server resolved up from a nested worktree to the main checkout).
  2684. // Queries then reflect that tree's branch, not the worktree being edited.
  2685. // status shows the verbose, multi-line form; the read tools get the compact
  2686. // one-liner via withWorktreeNotice. Both share the cached detection.
  2687. const mismatch = this.worktreeMismatchFor(args.projectPath as string | undefined);
  2688. const lines: string[] = [
  2689. '## CodeGraph Status',
  2690. '',
  2691. ];
  2692. if (mismatch) {
  2693. lines.push(`> ⚠ ${worktreeMismatchWarning(mismatch).replace(/\n/g, '\n> ')}`, '');
  2694. }
  2695. lines.push(
  2696. `**Files indexed:** ${stats.fileCount}`,
  2697. `**Total nodes:** ${stats.nodeCount}`,
  2698. `**Total edges:** ${stats.edgeCount}`,
  2699. `**Database size:** ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`,
  2700. );
  2701. // Surface the active SQLite backend (node:sqlite, Node's built-in real
  2702. // SQLite — full WAL + FTS5, no native build).
  2703. lines.push(`**Backend:** node:sqlite (Node built-in) — full WAL + FTS5`);
  2704. // Effective journal mode. 'wal' ⇒ concurrent reads never block on a writer;
  2705. // anything else ⇒ they can ("database is locked"). node:sqlite supports WAL
  2706. // everywhere, so a non-wal mode means the filesystem can't (network/
  2707. // virtualized mounts, WSL2 /mnt). See issue #238.
  2708. const journalMode = cg.getJournalMode();
  2709. if (journalMode === 'wal') {
  2710. lines.push(`**Journal mode:** wal (concurrent reads safe)`);
  2711. } else {
  2712. lines.push(
  2713. `**Journal mode:** ⚠ ${journalMode || 'unknown'} — WAL not active, so reads ` +
  2714. `can block on a concurrent write (WAL appears unsupported on this filesystem)`
  2715. );
  2716. }
  2717. lines.push('', '### Nodes by Kind:');
  2718. for (const [kind, count] of Object.entries(stats.nodesByKind)) {
  2719. if ((count as number) > 0) {
  2720. lines.push(`- ${kind}: ${count}`);
  2721. }
  2722. }
  2723. lines.push('', '### Languages:');
  2724. for (const [lang, count] of Object.entries(stats.filesByLanguage)) {
  2725. if ((count as number) > 0) {
  2726. lines.push(`- ${lang}: ${count}`);
  2727. }
  2728. }
  2729. // Per-file freshness — the inverse of the auto-prepended staleness banner
  2730. // (issue #403). Surfacing it inside `status` gives the agent a single
  2731. // place to ask "is the index caught up?" rather than inferring from
  2732. // banners on other tool calls.
  2733. const pending = cg.getPendingFiles();
  2734. if (pending.length > 0) {
  2735. lines.push('', '### Pending sync:');
  2736. const now = Date.now();
  2737. for (const p of pending) {
  2738. const ageMs = Math.max(0, now - p.lastSeenMs);
  2739. const label = p.indexing ? 'indexing in progress' : 'pending sync';
  2740. lines.push(`- ${p.path} (edited ${ageMs}ms ago, ${label})`);
  2741. }
  2742. }
  2743. return this.textResult(lines.join('\n'));
  2744. }
  2745. /**
  2746. * Handle codegraph_files - get project file structure from the index
  2747. */
  2748. private async handleFiles(args: Record<string, unknown>): Promise<ToolResult> {
  2749. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2750. const pathFilter = args.path as string | undefined;
  2751. const pattern = args.pattern as string | undefined;
  2752. const format = (args.format as 'tree' | 'flat' | 'grouped') || 'tree';
  2753. const includeMetadata = args.includeMetadata !== false;
  2754. const maxDepth = args.maxDepth != null ? clamp(args.maxDepth as number, 1, 20) : undefined;
  2755. // Get all files from the index
  2756. const allFiles = cg.getFiles();
  2757. if (allFiles.length === 0) {
  2758. return this.textResult('No files indexed. Run `codegraph index` first.');
  2759. }
  2760. // Filter by path prefix. Stored paths are project-relative POSIX (e.g.
  2761. // "src/foo.ts"), but agents commonly pass project-root variants like "/",
  2762. // ".", "./", "" or Windows-style "src\foo" — and prefixes with leading
  2763. // "/", "./" or "\". Normalize all of those before matching so the agent
  2764. // gets results instead of falling back to Read/Glob (see #426).
  2765. const normalizedFilter = pathFilter
  2766. ? pathFilter
  2767. .replace(/\\/g, '/')
  2768. .replace(/^(?:\.?\/+)+/, '')
  2769. .replace(/^\.$/, '')
  2770. .replace(/\/+$/, '')
  2771. : '';
  2772. let files = normalizedFilter
  2773. ? allFiles.filter(f => f.path === normalizedFilter || f.path.startsWith(normalizedFilter + '/'))
  2774. : allFiles;
  2775. // Filter by glob pattern
  2776. if (pattern) {
  2777. const regex = this.globToRegex(pattern);
  2778. files = files.filter(f => regex.test(f.path));
  2779. }
  2780. if (files.length === 0) {
  2781. return this.textResult(`No files found matching the criteria.`);
  2782. }
  2783. // Format output
  2784. let output: string;
  2785. switch (format) {
  2786. case 'flat':
  2787. output = this.formatFilesFlat(files, includeMetadata);
  2788. break;
  2789. case 'grouped':
  2790. output = this.formatFilesGrouped(files, includeMetadata);
  2791. break;
  2792. case 'tree':
  2793. default:
  2794. output = this.formatFilesTree(files, includeMetadata, maxDepth);
  2795. break;
  2796. }
  2797. return this.textResult(this.truncateOutput(output));
  2798. }
  2799. /**
  2800. * Convert glob pattern to regex
  2801. */
  2802. private globToRegex(pattern: string): RegExp {
  2803. const escaped = pattern
  2804. .replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special regex chars except * and ?
  2805. .replace(/\*\*/g, '{{GLOBSTAR}}') // Temp placeholder for **
  2806. .replace(/\*/g, '[^/]*') // * matches anything except /
  2807. .replace(/\?/g, '[^/]') // ? matches single char except /
  2808. .replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** matches anything including /
  2809. return new RegExp(escaped);
  2810. }
  2811. /**
  2812. * Format files as a flat list
  2813. */
  2814. private formatFilesFlat(files: { path: string; language: string; nodeCount: number }[], includeMetadata: boolean): string {
  2815. const lines: string[] = [`## Files (${files.length})`, ''];
  2816. for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
  2817. if (includeMetadata) {
  2818. lines.push(`- ${file.path} (${file.language}, ${file.nodeCount} symbols)`);
  2819. } else {
  2820. lines.push(`- ${file.path}`);
  2821. }
  2822. }
  2823. return lines.join('\n');
  2824. }
  2825. /**
  2826. * Format files grouped by language
  2827. */
  2828. private formatFilesGrouped(files: { path: string; language: string; nodeCount: number }[], includeMetadata: boolean): string {
  2829. const byLang = new Map<string, typeof files>();
  2830. for (const file of files) {
  2831. const existing = byLang.get(file.language) || [];
  2832. existing.push(file);
  2833. byLang.set(file.language, existing);
  2834. }
  2835. const lines: string[] = [`## Files by Language (${files.length} total)`, ''];
  2836. // Sort languages by file count (descending)
  2837. const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
  2838. for (const [lang, langFiles] of sortedLangs) {
  2839. lines.push(`### ${lang} (${langFiles.length})`);
  2840. for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
  2841. if (includeMetadata) {
  2842. lines.push(`- ${file.path} (${file.nodeCount} symbols)`);
  2843. } else {
  2844. lines.push(`- ${file.path}`);
  2845. }
  2846. }
  2847. lines.push('');
  2848. }
  2849. return lines.join('\n');
  2850. }
  2851. /**
  2852. * Format files as a tree structure
  2853. */
  2854. private formatFilesTree(
  2855. files: { path: string; language: string; nodeCount: number }[],
  2856. includeMetadata: boolean,
  2857. maxDepth?: number
  2858. ): string {
  2859. // Build tree structure
  2860. interface TreeNode {
  2861. name: string;
  2862. children: Map<string, TreeNode>;
  2863. file?: { language: string; nodeCount: number };
  2864. }
  2865. const root: TreeNode = { name: '', children: new Map() };
  2866. for (const file of files) {
  2867. const parts = file.path.split('/');
  2868. let current = root;
  2869. for (let i = 0; i < parts.length; i++) {
  2870. const part = parts[i];
  2871. if (!part) continue;
  2872. if (!current.children.has(part)) {
  2873. current.children.set(part, { name: part, children: new Map() });
  2874. }
  2875. current = current.children.get(part)!;
  2876. // If this is the last part, it's a file
  2877. if (i === parts.length - 1) {
  2878. current.file = { language: file.language, nodeCount: file.nodeCount };
  2879. }
  2880. }
  2881. }
  2882. // Render tree
  2883. const lines: string[] = [`## Project Structure (${files.length} files)`, ''];
  2884. const renderNode = (node: TreeNode, prefix: string, isLast: boolean, depth: number): void => {
  2885. if (maxDepth !== undefined && depth > maxDepth) return;
  2886. const connector = isLast ? '└── ' : '├── ';
  2887. const childPrefix = isLast ? ' ' : '│ ';
  2888. if (node.name) {
  2889. let line = prefix + connector + node.name;
  2890. if (node.file && includeMetadata) {
  2891. line += ` (${node.file.language}, ${node.file.nodeCount} symbols)`;
  2892. }
  2893. lines.push(line);
  2894. }
  2895. const children = [...node.children.values()];
  2896. // Sort: directories first, then files, both alphabetically
  2897. children.sort((a, b) => {
  2898. const aIsDir = a.children.size > 0 && !a.file;
  2899. const bIsDir = b.children.size > 0 && !b.file;
  2900. if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
  2901. return a.name.localeCompare(b.name);
  2902. });
  2903. for (let i = 0; i < children.length; i++) {
  2904. const child = children[i]!;
  2905. const nextPrefix = node.name ? prefix + childPrefix : prefix;
  2906. renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
  2907. }
  2908. };
  2909. renderNode(root, '', true, 0);
  2910. return lines.join('\n');
  2911. }
  2912. // =========================================================================
  2913. // Symbol resolution helpers
  2914. // =========================================================================
  2915. /**
  2916. * Find a symbol by name, handling disambiguation when multiple matches exist.
  2917. * Returns the best match and a note about alternatives if any.
  2918. */
  2919. /**
  2920. * Check if a node matches a symbol query.
  2921. *
  2922. * Accepts simple names (`run`) and three flavors of qualifier:
  2923. * - dotted `Session.request` (TS/JS/Python)
  2924. * - colon-pair `stage_apply::run` (Rust, C++, Ruby)
  2925. * - slash `configurator/stage_apply` (path-ish)
  2926. *
  2927. * Multi-level qualifiers compose: `crate::configurator::stage_apply::run`
  2928. * works. Rust path prefixes (`crate`, `super`, `self`) are stripped so
  2929. * the canonical `crate::module::symbol` form resolves.
  2930. *
  2931. * Resolution order, last part must always equal `node.name`:
  2932. * 1. Suffix-match against `qualifiedName` (handles class-scoped methods
  2933. * where the extractor builds the qualified name from the AST stack)
  2934. * 2. File-path containment (handles file-derived modules in Rust/
  2935. * Python — `stage_apply::run` matches a `run` in `stage_apply.rs`)
  2936. */
  2937. private matchesSymbol(node: Node, symbol: string): boolean {
  2938. // Simple name match
  2939. if (node.name === symbol) return true;
  2940. // File basename match (e.g., "product-card" matches "product-card.liquid")
  2941. if (node.kind === 'file' && node.name.replace(/\.[^.]+$/, '') === symbol) return true;
  2942. // Qualified-name lookups: split on any supported separator. `\w` keeps
  2943. // identifier chars (incl. `_`) intact; everything else is treated as
  2944. // a separator we tolerate.
  2945. if (!/[.\/]|::/.test(symbol)) return false;
  2946. const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
  2947. if (parts.length < 2) return false;
  2948. const lastPart = parts[parts.length - 1]!;
  2949. if (node.name !== lastPart) return false;
  2950. // Stage 1: qualified-name suffix match. The extractor joins the
  2951. // semantic hierarchy with `::`, so `Session.request` and
  2952. // `Session::request` both become `Session::request` here.
  2953. const colonSuffix = parts.join('::');
  2954. if (node.qualifiedName.includes(colonSuffix)) return true;
  2955. // Stage 2: file-path containment. Rust modules and Python packages
  2956. // are not in `qualifiedName` — they're encoded in the file path. So
  2957. // `stage_apply::run` matches a `run` in any file whose path
  2958. // contains a `stage_apply` segment (with or without an extension).
  2959. //
  2960. // Filter out Rust path prefixes that have no file-system equivalent.
  2961. const containerHints = parts.slice(0, -1).filter((p) => !RUST_PATH_PREFIXES.has(p));
  2962. if (containerHints.length === 0) return false;
  2963. const segments = node.filePath.split('/').filter((s) => s.length > 0);
  2964. return containerHints.every((hint) =>
  2965. segments.some((seg) => seg === hint || seg.replace(/\.[^.]+$/, '') === hint)
  2966. );
  2967. }
  2968. /**
  2969. * Find ALL definitions matching a name, ranked, so codegraph_node can return
  2970. * every overload instead of guessing one (the wrong guess → a Read). Keepers
  2971. * rank before generated stubs (.pb.go etc.); stable within a group preserves
  2972. * FTS order. Returns [] when nothing matches; a qualified lookup that finds no
  2973. * exact match returns [] rather than a misleading fuzzy file hit (#173); a
  2974. * bare name with no exact match falls back to the single top fuzzy result.
  2975. */
  2976. private findSymbolMatches(cg: CodeGraph, symbol: string): Node[] {
  2977. const isQualified = /[.\/]|::/.test(symbol);
  2978. // For a bare name, enumerate EVERY exact-name definition via the direct index
  2979. // (not FTS, which caps + ranks): tokio's `poll` has 50+ defs and the one the
  2980. // caller wants (`Harness::poll` at harness.rs:153) ranks below any search cut,
  2981. // so it could be neither rendered nor pinned by the file/line disambiguator —
  2982. // and the agent Read it. With the full set, the multi-overload render + the
  2983. // file/line filter can both reach it.
  2984. if (!isQualified) {
  2985. const exact = cg.getNodesByName(symbol);
  2986. if (exact.length > 0) {
  2987. return [...exact].sort((a, b) => (isGeneratedFile(a.filePath) ? 1 : 0) - (isGeneratedFile(b.filePath) ? 1 : 0));
  2988. }
  2989. // No exact match — use the single top fuzzy result (e.g. a file basename).
  2990. const fuzzy = cg.searchNodes(symbol, { limit: 10 });
  2991. return fuzzy[0] ? [fuzzy[0].node] : [];
  2992. }
  2993. // Qualified lookup (`Session.request`, `stage_apply::run`): FTS + matchesSymbol.
  2994. const limit = 50;
  2995. let results = cg.searchNodes(symbol, { limit });
  2996. // FTS strips colons, so `stage_apply::run` searches the literal
  2997. // `stage_applyrun` and finds nothing. Re-search by the bare last part and
  2998. // let `matchesSymbol` filter by qualifier.
  2999. if (isQualified && results.length === 0) {
  3000. const tail = lastQualifierPart(symbol);
  3001. if (tail && tail !== symbol) results = cg.searchNodes(tail, { limit });
  3002. }
  3003. if (results.length === 0) return [];
  3004. const exactMatches = results.filter((r) => this.matchesSymbol(r.node, symbol));
  3005. if (exactMatches.length === 0) {
  3006. // No exact match — a qualified lookup must not fall back to a fuzzy file
  3007. // hit (#173); a bare name may use the single top fuzzy result.
  3008. return isQualified ? [] : results[0] ? [results[0].node] : [];
  3009. }
  3010. // Down-rank generated files (.pb.go, .pulsar.go, _grpc.pb.go, …) so a flow
  3011. // query prefers the keeper implementation over the protobuf-generated stub.
  3012. return [...exactMatches]
  3013. .sort((a, b) => (isGeneratedFile(a.node.filePath) ? 1 : 0) - (isGeneratedFile(b.node.filePath) ? 1 : 0))
  3014. .map((r) => r.node);
  3015. }
  3016. /**
  3017. * Find ALL symbols matching a name. Used by callers/callees/impact to aggregate
  3018. * results across all matching symbols (e.g., multiple classes with an `execute` method).
  3019. */
  3020. private findAllSymbols(cg: CodeGraph, symbol: string): { nodes: Node[]; note: string } {
  3021. let results = cg.searchNodes(symbol, { limit: 50 });
  3022. // Mirror the fallback in `findSymbol` for qualified queries — FTS
  3023. // strips colons, so a module-qualified lookup needs a second pass
  3024. // by the bare last part.
  3025. if (results.length === 0 && /[.\/]|::/.test(symbol)) {
  3026. const tail = lastQualifierPart(symbol);
  3027. if (tail && tail !== symbol) results = cg.searchNodes(tail, { limit: 50 });
  3028. }
  3029. if (results.length === 0) {
  3030. return { nodes: [], note: '' };
  3031. }
  3032. const exactMatches = results.filter(r => this.matchesSymbol(r.node, symbol));
  3033. if (exactMatches.length <= 1) {
  3034. const node = exactMatches[0]?.node ?? results[0]!.node;
  3035. return { nodes: [node], note: '' };
  3036. }
  3037. // Same generated-file down-rank as findSymbol — keeps callers/callees
  3038. // /impact aggregation aligned (a query against "Send" returns the
  3039. // hand-written implementations before the protobuf scaffold).
  3040. const ranked = [...exactMatches].sort((a, b) => {
  3041. const aGen = isGeneratedFile(a.node.filePath) ? 1 : 0;
  3042. const bGen = isGeneratedFile(b.node.filePath) ? 1 : 0;
  3043. return aGen - bGen;
  3044. });
  3045. const locations = ranked.map(r =>
  3046. `${r.node.kind} at ${r.node.filePath}:${r.node.startLine}`
  3047. );
  3048. const note = `\n\n> **Note:** Aggregated results across ${ranked.length} symbols named "${symbol}": ${locations.join(', ')}`;
  3049. return { nodes: ranked.map(r => r.node), note };
  3050. }
  3051. /**
  3052. * Truncate output if it exceeds the maximum length
  3053. */
  3054. private truncateOutput(text: string): string {
  3055. if (text.length <= MAX_OUTPUT_LENGTH) return text;
  3056. const truncated = text.slice(0, MAX_OUTPUT_LENGTH);
  3057. const lastNewline = truncated.lastIndexOf('\n');
  3058. const cutPoint = lastNewline > MAX_OUTPUT_LENGTH * 0.8 ? lastNewline : MAX_OUTPUT_LENGTH;
  3059. return truncated.slice(0, cutPoint) + '\n\n... (output truncated)';
  3060. }
  3061. // =========================================================================
  3062. // Formatting helpers (compact by default to reduce context usage)
  3063. // =========================================================================
  3064. private formatSearchResults(results: SearchResult[]): string {
  3065. const lines: string[] = [`## Search Results (${results.length} found)`, ''];
  3066. for (const result of results) {
  3067. const { node } = result;
  3068. const location = node.startLine ? `:${node.startLine}` : '';
  3069. // Compact format: one line per result with key info
  3070. lines.push(`### ${node.name} (${node.kind})`);
  3071. lines.push(`${node.filePath}${location}`);
  3072. if (node.signature) lines.push(`\`${node.signature}\``);
  3073. lines.push('');
  3074. }
  3075. return lines.join('\n');
  3076. }
  3077. private formatNodeList(nodes: Node[], title: string): string {
  3078. const lines: string[] = [`## ${title} (${nodes.length} found)`, ''];
  3079. for (const node of nodes) {
  3080. const location = node.startLine ? `:${node.startLine}` : '';
  3081. // Compact: just name, kind, location
  3082. lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}`);
  3083. }
  3084. return lines.join('\n');
  3085. }
  3086. private formatImpact(symbol: string, impact: Subgraph): string {
  3087. const nodeCount = impact.nodes.size;
  3088. // Compact format: just list affected symbols grouped by file
  3089. const lines: string[] = [
  3090. `## Impact: "${symbol}" affects ${nodeCount} symbols`,
  3091. '',
  3092. ];
  3093. // Group by file
  3094. const byFile = new Map<string, Node[]>();
  3095. for (const node of impact.nodes.values()) {
  3096. const existing = byFile.get(node.filePath) || [];
  3097. existing.push(node);
  3098. byFile.set(node.filePath, existing);
  3099. }
  3100. for (const [file, nodes] of byFile) {
  3101. lines.push(`**${file}:**`);
  3102. // Compact: inline list
  3103. const nodeList = nodes.map(n => `${n.name}:${n.startLine}`).join(', ');
  3104. lines.push(nodeList);
  3105. lines.push('');
  3106. }
  3107. return lines.join('\n');
  3108. }
  3109. /**
  3110. * Build a compact structural outline of a container symbol from its
  3111. * indexed children (methods, fields, properties, …) — name, kind,
  3112. * line number, and signature — so the agent gets the shape of a class
  3113. * without the full source of every method. Returns '' when the container
  3114. * has no indexed children, so the caller can fall back to full source.
  3115. */
  3116. private buildContainerOutline(cg: CodeGraph, node: Node): string {
  3117. const children = cg.getChildren(node.id)
  3118. .filter(c => c.kind !== 'import' && c.kind !== 'export')
  3119. .sort((a, b) => (a.startLine ?? 0) - (b.startLine ?? 0));
  3120. if (children.length === 0) return '';
  3121. const lines = [`**Members (${children.length}):**`, ''];
  3122. for (const c of children) {
  3123. const loc = c.startLine ? `:${c.startLine}` : '';
  3124. const sig = c.signature ? ` — \`${c.signature}\`` : '';
  3125. lines.push(`- ${c.name} (${c.kind})${loc}${sig}`);
  3126. }
  3127. return lines.join('\n');
  3128. }
  3129. private formatNodeDetails(node: Node, code: string | null, outline?: string | null): string {
  3130. const location = node.startLine ? `:${node.startLine}` : '';
  3131. const lines: string[] = [
  3132. `## ${node.name} (${node.kind})`,
  3133. '',
  3134. `**Location:** ${node.filePath}${location}`,
  3135. ];
  3136. if (node.signature) {
  3137. lines.push(`**Signature:** \`${node.signature}\``);
  3138. }
  3139. // Only include docstring if it's short and useful
  3140. if (node.docstring && node.docstring.length < 200) {
  3141. lines.push('', node.docstring);
  3142. }
  3143. if (outline) {
  3144. lines.push('', outline, '',
  3145. `> Structural outline only. Read \`${node.filePath}\` or call codegraph_node on a specific member for its body.`);
  3146. } else if (code) {
  3147. // Line-numbered (cat -n style, like codegraph_explore and Read) so the
  3148. // agent can cite/edit exact lines without re-Reading the file for them.
  3149. const numbered = node.startLine ? numberSourceLines(code, node.startLine) : code;
  3150. lines.push('', '```' + node.language, numbered, '```');
  3151. }
  3152. return lines.join('\n');
  3153. }
  3154. private textResult(text: string): ToolResult {
  3155. return {
  3156. content: [{ type: 'text', text }],
  3157. };
  3158. }
  3159. private errorResult(message: string): ToolResult {
  3160. return {
  3161. content: [{ type: 'text', text: `Error: ${message}` }],
  3162. isError: true,
  3163. };
  3164. }
  3165. }