tools.ts 164 KB

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