tools.ts 180 KB

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