tools.ts 342 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981
  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 type { QueryPool } from './query-pool';
  8. import { findNearestCodeGraphRoot } from '../directory';
  9. // Lazy-load the heavy CodeGraph chain off the MCP startup path — see the same
  10. // helper in engine.ts. ToolHandler must load to answer tools/list (static
  11. // schemas), but it must NOT drag in sqlite/query layers before the daemon binds;
  12. // CodeGraph is pulled in only when a tool actually opens a project. require() is
  13. // sync + cached (CommonJS build).
  14. const loadCodeGraph = (): typeof import('../index').default =>
  15. loadCodeGraphForTests ?? (require('../index') as typeof import('../index')).default;
  16. // Test seam (same pattern as the watcher's `__setFsWatchForTests`): vitest's
  17. // module transform can't service the lazy `require('../index')` above, so
  18. // in-process tests that exercise a genuine cross-project open (an explicit
  19. // `projectPath` to a different project — issue #1474's repro shape) inject the
  20. // already-imported class here. Never set outside tests.
  21. let loadCodeGraphForTests: typeof import('../index').default | null = null;
  22. export function __setLoadCodeGraphForTests(cls: typeof import('../index').default | null): void {
  23. loadCodeGraphForTests = cls;
  24. }
  25. import {
  26. detectWorktreeIndexMismatch,
  27. worktreeMismatchWarning,
  28. worktreeMismatchNotice,
  29. type WorktreeIndexMismatch,
  30. } from '../sync/worktree';
  31. import type { PendingFile } from '../sync';
  32. import type { Node, Edge, SearchResult, Subgraph, NodeKind } from '../types';
  33. import { isTestFile, normalizeNameToken } from '../search/query-utils';
  34. import { extractQueryPaths, queryMightContainPaths } from '../search/query-paths';
  35. import {
  36. existsSync,
  37. readFileSync,
  38. statSync,
  39. } from 'fs';
  40. import { createHash } from 'crypto';
  41. import { clamp, validatePathWithinRoot, validateProjectPath, isConfigLeafNode, CONFIG_LEAF_LANGUAGES } from '../utils';
  42. import { guardLabel, guardsForFileSync, siteKey, supportsBranchGuards, warmBranchGuardGrammars } from '../graph/branch-guards';
  43. import { findDynamicBoundaries, type BoundarySite } from '../graph/dynamic-boundary-report';
  44. import { countImplementers } from '../graph/type-hierarchy';
  45. import {
  46. lastQualifierPart,
  47. matchesSymbol,
  48. findAllSymbols,
  49. resolveNamedSymbolFlow,
  50. } from '../graph/named-symbol-flow';
  51. import { getUpdateNotice } from '../upgrade/update-check';
  52. import { ExploreDiagnostics } from './explore-diagnostics';
  53. import {
  54. EXPLORE_EMISSION_KEY,
  55. EXPLORE_SESSION_VIEW_ARG,
  56. ExploreSessionState,
  57. readExploreSessionView,
  58. viewForProject,
  59. type ExploreEmission,
  60. type ExploreFileEmission,
  61. type ExploreLineRange,
  62. } from './explore-session-state';
  63. import {
  64. EXPLORE_DEDUP,
  65. dedupeRange,
  66. exploreDedupEnabled,
  67. fileFingerprint,
  68. formatBackReference,
  69. mergeRanges,
  70. servedRangesForFile,
  71. symbolsInSpans,
  72. } from './explore-dedup';
  73. /**
  74. * An expected, recoverable "codegraph can't serve this" condition — most
  75. * importantly a project with no index. The dispatch catch converts these to
  76. * SUCCESS-shaped responses (guidance text, NO isError): an `isError: true`
  77. * early in a session teaches the agent the toolset is broken and it stops
  78. * calling codegraph entirely (observed repeatedly), which is exactly wrong
  79. * for conditions the agent can simply work around (use built-in tools for
  80. * that codebase / pass projectPath). isError is reserved for "stop trying"
  81. * cases: security refusals ({@link PathRefusalError}) and genuine
  82. * malfunctions.
  83. */
  84. export class NotIndexedError extends Error {}
  85. /**
  86. * A security refusal (sensitive system path). Stays `isError: true` WITHOUT
  87. * retry guidance — abandoning this path is the desired agent reaction.
  88. *
  89. * Defined in `../errors` so non-MCP read sinks (the `codegraph ui` server) can
  90. * enforce the same refusal without importing this module; re-exported here
  91. * because this is where every existing caller imports it from.
  92. */
  93. export { PathRefusalError } from '../errors';
  94. import { PathRefusalError } from '../errors';
  95. import { resolve as resolvePath, relative as relativePath } from 'path';
  96. /** Maximum output length to prevent context bloat (characters) */
  97. const MAX_OUTPUT_LENGTH = 15000;
  98. /**
  99. * Maximum length for free-form string inputs (query, task, symbol).
  100. * Bounds memory and CPU when a buggy or hostile MCP client sends a
  101. * huge payload — without this an attacker could ship a 100MB string
  102. * and force a full FTS5 scan / OOM the server. 10 000 characters is
  103. * far beyond any realistic legitimate query.
  104. */
  105. const MAX_INPUT_LENGTH = 10_000;
  106. /**
  107. * Maximum length for path-like string inputs (projectPath, path
  108. * filter, glob pattern). Paths beyond a few thousand chars are
  109. * never legitimate and signal abuse or a bug upstream.
  110. */
  111. const MAX_PATH_LENGTH = 4_096;
  112. /**
  113. * Node kinds that contain other symbols. For these, `codegraph_node` with
  114. * `includeCode=true` returns a structural outline (member names + signatures
  115. * + line numbers) instead of the full body, which for a large class is a
  116. * multi-thousand-character wall of source that bloats the agent's context.
  117. */
  118. const CONTAINER_NODE_KINDS = new Set<NodeKind>([
  119. 'class', 'struct', 'union', 'interface', 'trait', 'protocol', 'enum', 'namespace', 'module',
  120. ]);
  121. /**
  122. * Normalize Erlang-native symbol spellings in an explore query into the shapes
  123. * the rest of the pipeline already understands. Agents working Erlang code
  124. * name symbols the way the language spells them — `mod:fn/3`, `init/2` — and
  125. * those tokens previously died in both consumers: the flow-builder's token
  126. * filter rejects `:` and `/arity` outright, and the search-side field parser
  127. * eats `mod:fn` as an unknown `field:value`. Measured on cowboy: the agent
  128. * named `cowboy_stream_h:request_process/3` in two queries, got no body back
  129. * either time, and fell back to Read.
  130. *
  131. * - `fn/3` → `fn` (arity tail after an identifier; a path segment like
  132. * `src/2fa` doesn't match because the tail must be all digits)
  133. * - `mod:fn` → `mod.fn` (exactly one colon between identifiers, so it rides
  134. * the existing Class.method qualified handling; `::`, URLs, drive letters,
  135. * and times don't match, and the query language's own field prefixes —
  136. * kind:/lang:/language:/path:/name: — are left alone)
  137. *
  138. * Safe cross-language: Lua's `t:m` spelling maps to the same `t.m` its
  139. * qualified names use, and no other supported spelling contains a bare
  140. * single-colon identifier pair.
  141. */
  142. export function normalizeQuerySpelling(query: string): string {
  143. return query
  144. .replace(/\b([A-Za-z_][\w@]*)\/(\d{1,3})(?=$|[\s,()[\]/])/g, '$1')
  145. .replace(
  146. /(^|[\s,()[\]])(?!(?:kind|lang|language|path|name):)([a-z_][\w@]*):([A-Za-z_][\w@]*)(?=$|[\s,()[\]])/g,
  147. '$1$2.$3'
  148. );
  149. }
  150. /**
  151. * Calculate the recommended number of codegraph_explore calls based on project size.
  152. * Larger codebases need more exploration calls to cover their surface area,
  153. * but smaller ones should use fewer to avoid unnecessary overhead.
  154. */
  155. export function getExploreBudget(fileCount: number): number {
  156. if (fileCount < 500) return 1;
  157. if (fileCount < 5000) return 2;
  158. if (fileCount < 15000) return 3;
  159. if (fileCount < 25000) return 4;
  160. return 5;
  161. }
  162. /**
  163. * Adaptive output budget for `codegraph_explore`, scaled to project size.
  164. *
  165. * Smaller codebases get a tighter total cap, fewer default files, smaller
  166. * per-file cap, and tighter clustering — so a focused query on a 100-file
  167. * project doesn't dump a whole file's worth of source into the agent's
  168. * context. Larger codebases keep the generous defaults because the
  169. * agent's native discovery cost (grep + find + many Reads) genuinely
  170. * dwarfs a fat explore call at that scale.
  171. *
  172. * Meta-text (relationships map, "additional relevant files" list,
  173. * completeness signal, budget note) is gated off for tiny projects
  174. * where one rich call is the whole story and the extra prose is just
  175. * overhead.
  176. *
  177. * Tier breakpoints mirror `getExploreBudget` so a project sits in the
  178. * same tier across both knobs.
  179. */
  180. export interface ExploreOutputBudget {
  181. /** Hard cap on total output characters. */
  182. maxOutputChars: number;
  183. /** Default `maxFiles` when the caller didn't specify one. */
  184. defaultMaxFiles: number;
  185. /** Cap on contiguous source returned per file (across all its clusters). */
  186. maxCharsPerFile: number;
  187. /** Cluster gap threshold in lines — tighter clustering on small projects. */
  188. gapThreshold: number;
  189. /** Max symbols listed in the per-file header (``**`path`** — sym(kind), ...``). */
  190. maxSymbolsInFileHeader: number;
  191. /** Max edges shown per relationship kind in the Relationships section. */
  192. maxEdgesPerRelationshipKind: number;
  193. /** Include the "Relationships" section. */
  194. includeRelationships: boolean;
  195. /** Include the "Additional relevant files (not shown)" trailing list. */
  196. includeAdditionalFiles: boolean;
  197. /** Include the "Complete source code is included above…" reminder. */
  198. includeCompletenessSignal: boolean;
  199. /** Include the explore-budget reminder at the end. */
  200. includeBudgetNote: boolean;
  201. }
  202. export function getExploreOutputBudget(fileCount: number): ExploreOutputBudget {
  203. // Tiered budget, scaled to project size. The budget is a CEILING (relevance
  204. // still gates WHAT is included), and it MUST stay under the agent's INLINE
  205. // tool-result cap (~25K chars). Above that, the host externalizes the result
  206. // to a file the agent then Reads back — re-introducing a read AND the
  207. // cache-write cost — which is exactly what a 35K vscode explore did in the
  208. // n=4 README A/B. So even large repos cap at ~24K: the answer is the handful
  209. // of ~100-line flow windows the agent would have grep-located and read (it
  210. // natively reads ~6–9 files, median 100-line ranges), NOT a sprawl of 12
  211. // files. Concentration onto the flow emerges from this cap + the named-file-
  212. // first sort dropping peripheral files. Invariant: a larger tier must never
  213. // get a smaller `maxCharsPerFile` than a smaller tier.
  214. if (fileCount < 150) {
  215. return {
  216. // ITER3: revert iter2's aggressive body shrink (forced Read fallback —
  217. // the per-file 2.5K cap pushed the agent to Read instead of node).
  218. // Back to the iter1 shape (13K/4/3.8K) but keep the test-file
  219. // hard-exclude. The cost lever for this tier lives in steering the
  220. // agent to stop after 1-2 calls, not in this budget.
  221. maxOutputChars: 13000,
  222. defaultMaxFiles: 4,
  223. maxCharsPerFile: 3800,
  224. gapThreshold: 7,
  225. maxSymbolsInFileHeader: 5,
  226. maxEdgesPerRelationshipKind: 4,
  227. includeRelationships: false,
  228. includeAdditionalFiles: false,
  229. includeCompletenessSignal: false,
  230. includeBudgetNote: false,
  231. };
  232. }
  233. if (fileCount < 500) {
  234. return {
  235. // ITER3: same revert/keep-filter pattern as <150.
  236. maxOutputChars: 18000,
  237. defaultMaxFiles: 5,
  238. maxCharsPerFile: 3800,
  239. gapThreshold: 8,
  240. maxSymbolsInFileHeader: 6,
  241. maxEdgesPerRelationshipKind: 6,
  242. includeRelationships: false,
  243. includeAdditionalFiles: false,
  244. includeCompletenessSignal: false,
  245. includeBudgetNote: false,
  246. };
  247. }
  248. if (fileCount < 5000) {
  249. return {
  250. // ~150-line per-file window (the native read unit) × ~6 files, capped at
  251. // the ~24K inline ceiling so the response is never externalized. Per-file
  252. // stays ≥ the <500 tier (3800) — monotonic.
  253. maxOutputChars: 24000,
  254. defaultMaxFiles: 8,
  255. maxCharsPerFile: 6500,
  256. gapThreshold: 12,
  257. maxSymbolsInFileHeader: 10,
  258. maxEdgesPerRelationshipKind: 10,
  259. includeRelationships: true,
  260. includeAdditionalFiles: true,
  261. includeCompletenessSignal: true,
  262. includeBudgetNote: true,
  263. };
  264. }
  265. // Large + very-large repos: SAME ~24K inline ceiling (a bigger response just
  266. // externalizes — see vscode). More files indexed → more CALLS via
  267. // getExploreBudget, not a bigger single response. Per-file 7000 (≥ smaller
  268. // tiers) gives the central file a ~180-line orientation window.
  269. if (fileCount < 15000) {
  270. return {
  271. maxOutputChars: 24000,
  272. defaultMaxFiles: 8,
  273. maxCharsPerFile: 7000,
  274. gapThreshold: 15,
  275. maxSymbolsInFileHeader: 15,
  276. maxEdgesPerRelationshipKind: 15,
  277. includeRelationships: true,
  278. includeAdditionalFiles: true,
  279. includeCompletenessSignal: true,
  280. includeBudgetNote: true,
  281. };
  282. }
  283. return {
  284. maxOutputChars: 24000,
  285. defaultMaxFiles: 8,
  286. maxCharsPerFile: 7000,
  287. gapThreshold: 15,
  288. maxSymbolsInFileHeader: 15,
  289. maxEdgesPerRelationshipKind: 15,
  290. includeRelationships: true,
  291. includeAdditionalFiles: true,
  292. includeCompletenessSignal: true,
  293. includeBudgetNote: true,
  294. };
  295. }
  296. // ── Explore relevance scoring (CG-10 / #1500) ──────────────────────────────
  297. //
  298. // A file earns its slice of the explore envelope from the symbols in it that the
  299. // query matched. Before this weighting every match counted the same per tier, so
  300. // a file that merely declares a local `const explore` scored what a file that
  301. // DEFINES the explore pipeline scored — which is how three
  302. // `scripts/agent-eval/*.mjs` harnesses took 63% of this repo's own "how does
  303. // explore allocate its output budget across files" response on nothing but a
  304. // local `explore` and a `BUDGET` constant. Four levers — the first three are
  305. // multiplicative, so they compose without ordering surprises; the fourth decides
  306. // admission from the result:
  307. //
  308. // 1. KIND — what a match on this NodeKind actually tells you (below).
  309. // 2. ISOLATION — a weak-kind symbol nothing calls or references is a pure name
  310. // collision; participation in the graph is the corroboration.
  311. // 3. PENALTY — generated / test / i18n files are weaker answers to an
  312. // architecture question at EVERY signal, not just as the
  313. // tiebreak-at-equal-score they used to be.
  314. // 4. FLOOR — admission scales with the best file's score, replacing an
  315. // absolute bar that admitted noise wherever the top score was
  316. // high.
  317. /**
  318. * How strongly a match on a symbol of this kind corroborates that its FILE is
  319. * what the query is about.
  320. *
  321. * 1.0 a callable or a type — the unit an architecture question is about
  322. * ~0.5 a member of a type, or the file node itself (a path match, not a
  323. * symbol match)
  324. * ~0.3 a variable / constant — as often a name collision as a definition
  325. * 0.15 a parameter — essentially never the subject of a question
  326. *
  327. * Unlisted kinds fall back to `DEFAULT_RELEVANCE_KIND_WEIGHT`, so a NodeKind
  328. * added later is neither free nor fatal.
  329. */
  330. export const RELEVANCE_KIND_WEIGHT: Readonly<Record<string, number>> = {
  331. // Callables and types: the answer lives in one of these.
  332. function: 1, method: 1, class: 1, struct: 1, union: 1, interface: 1, trait: 1,
  333. protocol: 1, component: 1, route: 1, enum: 1, type_alias: 1, constructor: 1,
  334. // Containers: real structure, but a whole namespace/module matching a term is
  335. // a coarser signal than a callable matching it.
  336. namespace: 0.8, module: 0.8,
  337. // Members of a type: real, weaker on their own.
  338. property: 0.5, field: 0.5, enum_member: 0.35,
  339. // The file node itself — the path matched, no symbol did.
  340. file: 0.5,
  341. // Incidental until the graph corroborates them (see ISOLATED_ below).
  342. constant: 0.35, variable: 0.3, parameter: 0.15,
  343. };
  344. const DEFAULT_RELEVANCE_KIND_WEIGHT = 0.5;
  345. /**
  346. * Kinds whose evidentiary value depends on whether anything USES them. An
  347. * exported `const DEFAULTS` that half the codebase references is a real
  348. * definition; a `const explore` living inside one function of an eval script is
  349. * a name collision. Only these kinds pay for the isolation probe.
  350. */
  351. const WEAK_RELEVANCE_KINDS: ReadonlySet<string> = new Set([
  352. 'constant', 'variable', 'parameter', 'field', 'property', 'enum_member',
  353. ]);
  354. /** Weight for a weak-kind symbol with no incoming/outgoing usage edge at all. */
  355. const ISOLATED_WEAK_KIND_WEIGHT = 0.08;
  356. /**
  357. * Edges that mean "this symbol is used". `contains` is lexical nesting, not
  358. * usage — counting it would make every file-scope constant look corroborated,
  359. * which is exactly the case this guards against.
  360. */
  361. const RELEVANCE_USAGE_EDGES: ReadonlySet<string> = new Set([
  362. 'calls', 'references', 'extends', 'implements', 'overrides',
  363. 'instantiates', 'returns', 'type_of', 'decorates', 'navigates',
  364. ]);
  365. /**
  366. * Cap on what PERIPHERAL nodes (in the subgraph, but neither a query match nor
  367. * adjacent to one) can contribute to a file's score. Uncapped, each such node
  368. * added a flat +1, so a file grew more "relevant" simply by being bigger —
  369. * `parse-session.mjs` reached score 22 off ONE incidental constant plus twelve
  370. * unrelated symbols. Size is not evidence; cap its contribution.
  371. */
  372. const PERIPHERAL_SCORE_CAP = 5;
  373. /**
  374. * Rank penalties, applied to BOTH the relevance score and the graph mass.
  375. *
  376. * Generated source used to be a tiebreak at equal score only, so a generated
  377. * file that outscored the hand-written one still won — the #1500 report exactly:
  378. * the FKIT CRUD layer carries every query term AND more graph mass than the
  379. * use-case that implements the business rule. A multiplier demotes it on the
  380. * PRIMARY sort key instead, without ever hard-excluding it (ask about the
  381. * generated API by name and the named-seed tier still puts it first). It is
  382. * self-normalizing: in an all-generated repo everything scales together and
  383. * relative ranking is untouched.
  384. */
  385. const GENERATED_RANK_PENALTY = 0.3;
  386. /**
  387. * Test/spec/icon/i18n files. These are normally hard-excluded outright, but that
  388. * filter stands down when fewer than 2 non-low-value candidates remain (else
  389. * tests would be the only signal for the area). This is the softened form for
  390. * that case: down-weighted rather than removed.
  391. */
  392. const LOW_VALUE_RANK_PENALTY = 0.5;
  393. /**
  394. * Ambient declaration files — a hand-written `.d.ts` of global shims, vendored
  395. * typings, module augmentation (CG-28). Declares nothing but types, and nothing
  396. * in the index depends on it.
  397. *
  398. * Such a file cannot answer a FLOW question no matter how much its identifiers
  399. * overlap the query: no bodies, no call edges, no behaviour, and nothing typed
  400. * by it. Its ceiling of usefulness is a type signature, and one follow-up
  401. * explore fetches that. But the identifiers it declares are exactly the generic
  402. * ones a prose question uses (`Body`, `Message`, `ImageMetadata`,
  403. * `ReadableStream`), so on term overlap it out-scores the implementation and
  404. * takes the envelope — measured at rank #1 and 51% of delivered source, with
  405. * the flow's own entry file getting none.
  406. *
  407. * Softer than {@link GENERATED_RANK_PENALTY} on purpose: "generated" is a claim
  408. * about provenance the file itself makes, while this is an inference about what
  409. * a file can be USEFUL for. A demoted declaration file that is still the best
  410. * candidate should keep its place; the penalty only has to stop it beating real
  411. * implementation. It does NOT stack with the generated penalty (see rankPenalty)
  412. * — penalising twice for the same property is how a file gets cliffed out of
  413. * answers where it is genuinely relevant.
  414. */
  415. const AMBIENT_DECLARATION_RANK_PENALTY = 0.5;
  416. /**
  417. * The type-level NodeKinds. Must stay in step with the kind list in
  418. * `QueryBuilder.getAmbientDeclarationPathsAmong` — that query decides which
  419. * files are ambient declarations, this set decides which symbols in them the
  420. * agent can name to lift the penalty back off.
  421. */
  422. const DECLARATION_KINDS = new Set(['interface', 'type_alias', 'enum', 'enum_member', 'namespace']);
  423. /**
  424. * Score floor: `clamp(topScore * FRACTION, ABSOLUTE, MAX)`.
  425. *
  426. * An absolute floor alone (`>= 3`) admits noise on any repo where the top file
  427. * scores 50+, so the bar is now a FRACTION of the best file's score and scales
  428. * with how strong the best match is. On a diffuse survey question no file
  429. * dominates, every candidate sits near the top score, and the whole spread gets
  430. * through; on a precise question it cuts the long tail of incidental matches.
  431. *
  432. * ABSOLUTE is recalibrated for kind-weighted scores: the old `>= 3` assumed an
  433. * unweighted tier sum where any query match was worth 10. A file whose sole
  434. * match is an unused local constant now scores 0.8, so 3 had quietly become a
  435. * much harsher admission bar than it was written to be — and the relative floor
  436. * is what this change means to prune with anyway.
  437. */
  438. const SCORE_FLOOR_ABSOLUTE = 1;
  439. const SCORE_FLOOR_FRACTION_OF_TOP = 0.2;
  440. /**
  441. * Ceiling on the relative floor, in units of one direct query match on a
  442. * callable (the `entryNodeIds` tier, weight 1.0). A single full-strength match
  443. * is never incidental, so no amount of concentration elsewhere may exclude it:
  444. * one named-seed-heavy file (`+50` per seed) otherwise pushed the floor to 21
  445. * and dropped `BridgeInterceptor`'s file, which the agent had named — a class,
  446. * so it entered at the +10 tier rather than +50. The #1500 noise this change
  447. * targets scores 0.8–6, well under this ceiling.
  448. */
  449. const SCORE_FLOOR_MAX = 10;
  450. /**
  451. * The relative floor must never starve a question of candidates: if it would
  452. * leave fewer than this, backfill with the best-scoring ones it cut. The cost of
  453. * under-serving is the agent calling explore again — a whole round-trip. See the
  454. * backfill itself for the two strengths it runs at (thin vs. empty).
  455. */
  456. const SCORE_FLOOR_KEEP_MIN = 3;
  457. // ── Score-proportional byte allocation (CG-12 / #1500) ─────────────────────
  458. //
  459. // The score floor above decides WHICH files reach the response. This decides how
  460. // the byte envelope is SPLIT among them — and until this existed, it wasn't
  461. // really decided at all: every admitted file was capped at the same
  462. // `maxCharsPerFile`, and the whole-file rule handed anything under
  463. // `maxCharsPerFile * 3` its entire contents. So allocation followed FILE SIZE,
  464. // not relevance. On this repo's own "how does explore allocate its output budget
  465. // across files", `src/mcp/tools.ts` (score 41, 4x the graph mass, 3x the distinct
  466. // term hits — it literally holds the allocator) was clipped at 3,800 while a
  467. // score-18 file shipped whole at 5,672 and took 51% of the envelope, purely for
  468. // being small. On the #1500 Go fixture, two generated CRUD files shipped whole at
  469. // ~4.5K each and consumed the tier's 4 file slots, so `BuildPayslip` — the
  470. // hand-written half of "create and calculate payslips" — never appeared at all.
  471. //
  472. // The replacement: reserve each file a share of the envelope proportional to what
  473. // it is worth, up front, before anything renders. Three consequences:
  474. //
  475. // 1. A reservation is a GUARANTEE, not a race. The old loop spent the envelope
  476. // first-come-first-served in rank order, so the top two files could exhaust
  477. // it and every later file hit a `budget-90pct` skip regardless of merit.
  478. // 2. A file below the cliff gets ZERO source — its path, symbols and line
  479. // numbers only. It costs ~100 chars instead of ~4,500, and (crucially) it
  480. // does not consume a `maxFiles` slot, so the slot goes to a file that earns
  481. // its bytes. This is the concentration lever.
  482. // 3. The per-file cap stops being the primary guard. It survives only as
  483. // `ALLOC_MAX_SHARE`, a safety valve against a single god-file — which the
  484. // proportional split already bounds, since a file's share can't exceed its
  485. // weight share.
  486. export const EXPLORE_ALLOCATION = {
  487. /**
  488. * A file whose weight is under this fraction of the top file's gets no source.
  489. *
  490. * Calibrated between the two shapes the fixtures pin: the #1500 generated CRUD
  491. * lands at 10–11% of the top weight (penalised twice — once into the score by
  492. * `rankPenalty`, once again here) and must cliff; a genuinely peripheral but
  493. * hand-written flow file — `payslip_builder.go`, the direct callee of the
  494. * workflow entry — lands at 25% and must NOT. Everything in between is a
  495. * judgement call the agent can undo for ~0 cost, because a cliffed file is
  496. * still NAMED in the response and one follow-up explore fetches it.
  497. */
  498. CLIFF_FRACTION: 0.15,
  499. /**
  500. * Ceiling on the cliff, in the same units as `SCORE_FLOOR_MAX` — and for the
  501. * same reason. A file whose weight clears a full-strength direct match is never
  502. * incidental, so no amount of concentration elsewhere may zero it: one
  503. * overwhelming top file (a 99-scoring god-file among score-10 peers) otherwise
  504. * puts the cliff at 14.9 and silences every peer the score floor had just
  505. * deliberately admitted. The cliff is a RELATIVE prune of weak evidence, not a
  506. * second admission gate — the score floor already owns admission.
  507. */
  508. CLIFF_MAX: SCORE_FLOOR_MAX,
  509. /**
  510. * Floor on a useful reservation — every admitted file gets this much before
  511. * the proportional split divides the rest. Under it a slice can't hold one
  512. * complete method, and a fragment is strictly worse than a pointer: it forces
  513. * the Read this tool exists to prevent.
  514. *
  515. * It is a FLOOR, not a second cliff. Cliffing the starved file instead
  516. * cascades: removing the smallest raises everyone else's share by so little
  517. * that the next-smallest starves too, and a query with two dominant files ate
  518. * six legitimately-ranked peers one at a time. Concentration is the relative
  519. * cliff's job; this only keeps a served file's slice usable.
  520. */
  521. MIN_CHARS: 700,
  522. /**
  523. * Safety valve, as a fraction of the envelope. Not the primary guard any more —
  524. * the proportional split is — so this only has to stop a pathological
  525. * single-file response.
  526. */
  527. MAX_SHARE: 0.7,
  528. /**
  529. * Markdown overhead charged per rendered file (header + fences + blank lines),
  530. * matching the render loop's own `+ 200` accounting. Held out of the pool
  531. * before the split so the reservations plus their overhead fit the envelope —
  532. * without this the last file's reservation is always the one that doesn't fit.
  533. */
  534. FILE_OVERHEAD: 200,
  535. /**
  536. * Flow-spine files are weighted up and are exempt from the cliff. Clipping the
  537. * spine causes the Read fallback (it IS the answer to a flow question);
  538. * clipping a peripheral file does not. This makes the existing advisory spine
  539. * handling — `hasSpine`, `SPINE_CEILING` — strict at the allocation layer.
  540. */
  541. SPINE_WEIGHT_BOOST: 2,
  542. /**
  543. * Slack allowed on the whole-file rule: a file a little over its reservation
  544. * still ships WHOLE rather than as clusters, because slicing off that last
  545. * sliver saves ~1% of the envelope and costs a Read — the trade the whole-file
  546. * rule exists to refuse. Proportional (with an absolute ceiling) because a
  547. * "sliver" is relative: a flat 800 is 15% of a 5K reservation but 31% of a 2.5K
  548. * one, and at the small end that overshoot is exactly what the file below then
  549. * loses.
  550. */
  551. WHOLE_FILE_GRACE_FRACTION: 0.15,
  552. WHOLE_FILE_GRACE_MAX: 800,
  553. /**
  554. * A reservation that already covers this fraction of a file BUYS THE WHOLE
  555. * FILE (CG-21), even though the file is bigger than the reservation.
  556. *
  557. * The grace above is calibrated as a *sliver* — it only rescues a file that
  558. * essentially fits. Below it there is a hole the render loop cannot fill:
  559. * express's `lib/utils.js` (5,293 B) was the TOP-ranked file, reserved 3,870,
  560. * declined the whole-file render at a 4,450 grace bound, and then spent 583 on
  561. * a three-symbol cluster render. The other 3,287 chars of its reservation were
  562. * neither redistributed nor delivered — the envelope shrank by a third against
  563. * an unchanged budget and the agent Read the file back four times.
  564. *
  565. * So the rule is not "does the file fit the reservation" but "has the
  566. * reservation already bought most of the file": at 0.6 the loop pays at most
  567. * two-thirds of a reservation extra to avoid losing the whole thing, and it
  568. * spends bytes it was going to spend anyway on a file that already earned
  569. * them. Below the fraction the shortfall is real — the file is several times
  570. * its reservation, clustering is the right answer, and the carry-forward
  571. * (`reservedSoFar`/`sourceSpent` in the render loop) hands whatever it cannot
  572. * spend to the next file down.
  573. */
  574. WHOLE_FILE_BUY_FRACTION: 0.6,
  575. /**
  576. * The buy rule's overshoot is funded from ONE pool for the whole response,
  577. * sized as this fraction of the envelope — deliberately the same 15% as
  578. * `WHOLE_FILE_GRACE_FRACTION`, one level up: the grace is a sliver of a
  579. * FILE's reservation, this is a sliver of the RESPONSE's envelope.
  580. *
  581. * Per-file funding is the version that fails, and it fails the same way the
  582. * bug being fixed does. The merit test is a RATIO, so wherever several files
  583. * sit near it they all qualify, and N independent overshoots inflate the
  584. * response until the render ceiling drops whatever is last. Measured on the
  585. * #1500 payroll fixture: three files bought whole and `payslip_builder.go` —
  586. * the file that computes the payslip the question asks about, rank #6 — was
  587. * dropped entirely so three higher-ranked files could each ship their final
  588. * sliver. A dropped section is strictly worse than a clustered one, so one
  589. * shared pool, spent in rank order, is the bound that matters.
  590. */
  591. WHOLE_FILE_BUY_OVERSHOOT_FRACTION: 0.15,
  592. } as const;
  593. /** One candidate file's allocation inputs, in final rank order. */
  594. export interface ExploreAllocationCandidate {
  595. path: string;
  596. /** Post-`rankPenalty` relevance score from the ranking pass. */
  597. score: number;
  598. /**
  599. * How much this file's BYTES are worth, independent of how well it matched.
  600. * Ranking answers "is this file about the query"; allocation answers "will
  601. * these bytes teach the agent anything". Generated CRUD can legitimately rank
  602. * (it name-collides on every domain word) while its bytes stay mechanical
  603. * boilerplate the agent gains nothing from reading — so `rankPenalty` is
  604. * applied a SECOND time here. That is what finally sinks the #1500 generated
  605. * layer below the cliff: it survived CG-10's single penalty because the sort's
  606. * leading keys (entry-point, graph mass) are structural, and a big densely
  607. * self-referential generated file scores well on both.
  608. */
  609. worth: number;
  610. /** Carries a symbol on the rendered flow spine. */
  611. spine: boolean;
  612. /**
  613. * The query named this file by PATH (see query-paths.ts). Pinned files are
  614. * never cliffed or trimmed, and weigh at least as much as the strongest
  615. * candidate — the agent asked for the file itself, so starving it on text/
  616. * graph scores (which a pure-path query doesn't produce) defeats the ask.
  617. */
  618. pinned?: boolean;
  619. }
  620. export interface ExploreAllocation {
  621. /** path → chars of source it may render. Only holds admitted files. */
  622. allowances: Map<string, number>;
  623. /** Files the cliff zeroed, in rank order — pointers, not bytes. */
  624. cliffed: string[];
  625. /** The weight threshold the cliff fired at (0 when nothing was cliffed). */
  626. cliffAt: number;
  627. /** Chars actually split among the admitted files. */
  628. pool: number;
  629. }
  630. /**
  631. * Split `budget.maxOutputChars` across ranked candidates in proportion to
  632. * relevance, with a hard relative cliff.
  633. *
  634. * `candidates` must arrive in FINAL RANK ORDER — `maxFiles` is applied to the
  635. * survivors of the cliff, in that order, so cliffing genuinely hands a slot to
  636. * the next file down rather than leaving it unused.
  637. *
  638. * Tier invariant (`getExploreOutputBudget`): a larger tier must never allow less
  639. * per file than a smaller one. It holds here by construction — every bound is a
  640. * fraction of `maxOutputChars` or of `maxCharsPerFile`, both monotonic across
  641. * tiers — except `MIN_CHARS`, which is an absolute floor and so identical at
  642. * every tier.
  643. */
  644. export function allocateExploreBudget(
  645. candidates: readonly ExploreAllocationCandidate[],
  646. budget: ExploreOutputBudget,
  647. maxFiles: number,
  648. ): ExploreAllocation {
  649. const A = EXPLORE_ALLOCATION;
  650. const empty: ExploreAllocation = { allowances: new Map(), cliffed: [], cliffAt: 0, pool: 0 };
  651. if (candidates.length === 0) return empty;
  652. // A non-finite weight is treated as no evidence rather than propagated: an
  653. // Infinity score would otherwise make every share `Infinity/Infinity` = NaN and
  654. // hand the render loop a NaN allowance. Scores are finite sums in the real
  655. // pipeline, so this only has to fail safe.
  656. const weightOf = (c: ExploreAllocationCandidate) => {
  657. const w = Math.max(0, c.score) * Math.max(0, Math.min(1, c.worth)) * (c.spine ? A.SPINE_WEIGHT_BOOST : 1);
  658. return Number.isFinite(w) ? w : 0;
  659. };
  660. // Pinned files weigh at least as much as the strongest raw candidate: their
  661. // score is whatever the stripped query happened to match (for a pure-path
  662. // query, nearly nothing), and a proportional split on that would fund the
  663. // named file worst of all. Floor of 1 covers the all-pinned/zero-score case.
  664. const rawWeights = new Map(candidates.map((c) => [c.path, weightOf(c)]));
  665. const topRaw = Math.max(...rawWeights.values());
  666. const weights = new Map(candidates.map((c) => [
  667. c.path,
  668. c.pinned ? Math.max(rawWeights.get(c.path) ?? 0, topRaw, 1) : (rawWeights.get(c.path) ?? 0),
  669. ]));
  670. const topWeight = Math.max(...weights.values());
  671. if (!(topWeight > 0)) return empty;
  672. // Cliff over the WHOLE candidate list, before `maxFiles` — otherwise the file
  673. // cap fills with cliff-bound files and the slot they free is never handed on.
  674. const cliffAt = Math.min(topWeight * A.CLIFF_FRACTION, A.CLIFF_MAX);
  675. const cliffed: string[] = [];
  676. let admitted: ExploreAllocationCandidate[] = [];
  677. for (const c of candidates) {
  678. if (!c.spine && !c.pinned && (weights.get(c.path) ?? 0) < cliffAt) cliffed.push(c.path);
  679. else admitted.push(c);
  680. }
  681. // Never cliff every candidate: an empty response costs a whole round-trip.
  682. if (admitted.length === 0) {
  683. admitted = [candidates[0]!];
  684. cliffed.splice(cliffed.indexOf(candidates[0]!.path), 1);
  685. }
  686. for (const c of admitted.slice(maxFiles)) cliffed.push(c.path);
  687. admitted = admitted.slice(0, maxFiles);
  688. // Serve fewer files well rather than many badly: the envelope has to afford
  689. // MIN_CHARS for everything admitted. When it can't, cliff the lowest-weight
  690. // files (never a spine file, never the last one) in one deterministic trim —
  691. // not one at a time, which is how the old starvation rule snowballed.
  692. const affordable = Math.max(1, Math.floor(budget.maxOutputChars / (A.MIN_CHARS + A.FILE_OVERHEAD)));
  693. if (admitted.length > affordable) {
  694. const byWeight = [...admitted].sort((a, b) => (weights.get(b.path) ?? 0) - (weights.get(a.path) ?? 0));
  695. const keep = new Set(byWeight.slice(0, affordable).map((c) => c.path));
  696. for (const c of admitted) if (c.spine || c.pinned) keep.add(c.path);
  697. for (const c of admitted) if (!keep.has(c.path)) cliffed.push(c.path);
  698. admitted = admitted.filter((c) => keep.has(c.path));
  699. }
  700. const allowances = new Map<string, number>();
  701. const pool = Math.max(0, budget.maxOutputChars - A.FILE_OVERHEAD * admitted.length);
  702. const total = admitted.reduce((s, c) => s + (weights.get(c.path) ?? 0), 0);
  703. if (total <= 0 || admitted.length === 0) return { allowances, cliffed, cliffAt, pool };
  704. // Everyone gets MIN_CHARS; the REMAINDER is what splits by weight. The floor
  705. // is what keeps a diffuse survey question returning a useful spread, and the
  706. // remainder is what concentrates a precise one — the top file's slice grows
  707. // with its weight share, uncapped by any flat per-file limit.
  708. const ceiling = Math.round(budget.maxOutputChars * A.MAX_SHARE);
  709. const floors = Math.min(pool, A.MIN_CHARS * admitted.length);
  710. const remainder = Math.max(0, pool - floors);
  711. // Both parts FLOOR: a sum of rounded shares can exceed the remainder that fed
  712. // it (by up to half a char per file), and the reservations must fit the pool
  713. // exactly — the render loop spends them, so an over-allocation is an over-long
  714. // response the hard ceiling then has to truncate. Flooring costs at most one
  715. // char per file.
  716. for (const c of admitted) {
  717. const share = Math.floor(floors / admitted.length)
  718. + Math.floor((remainder * (weights.get(c.path) ?? 0)) / total);
  719. allowances.set(c.path, Math.min(share, ceiling));
  720. }
  721. return { allowances, cliffed, cliffAt, pool };
  722. }
  723. /**
  724. * Whether `codegraph_explore` should prefix source lines with their line
  725. * numbers (cat -n style: `<num>\t<code>`).
  726. *
  727. * Line numbers let the agent cite `file:line` straight from the explore
  728. * payload instead of re-Reading the file just to find a line number — the
  729. * dominant residual cost on precise-tracing questions (#185 follow-up).
  730. *
  731. * Defaults ON. Set `CODEGRAPH_EXPLORE_LINENUMS=0` to disable (used by the
  732. * A/B harness to measure the payload-cost vs. read-savings tradeoff).
  733. */
  734. function exploreLineNumbersEnabled(): boolean {
  735. return process.env.CODEGRAPH_EXPLORE_LINENUMS !== '0';
  736. }
  737. /**
  738. * Adaptive explore sizing (default ON). `codegraph_explore` skeletonizes OFF-SPINE
  739. * polymorphic-sibling files — a file whose class is one of ≥3 interchangeable
  740. * implementations of a shared interface (e.g. OkHttp's `: Interceptor` classes) —
  741. * to class + member signatures (bodies elided), keeping the on-spine exemplar full.
  742. * This sizes the response to the answer instead of the budget cap on sibling-heavy
  743. * flows (OkHttp interceptor-chain explore 28.5k→16.6k, ~28% cheaper than native
  744. * search, reads flat). It is PROVABLY INERT elsewhere: distinct pipeline steps (no
  745. * ≥3-implementer supertype, e.g. Excalidraw's `renderStaticScene`) and on-spine
  746. * files keep full source — output is byte-identical to shipped on excalidraw /
  747. * tokio / django / vscode / gin. Set `CODEGRAPH_ADAPTIVE_EXPLORE=0` to disable.
  748. */
  749. function adaptiveExploreEnabled(): boolean {
  750. return process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== '0' && process.env.CODEGRAPH_ADAPTIVE_EXPLORE !== 'false';
  751. }
  752. /**
  753. * How long the FIRST tool call waits on the post-open catch-up reconcile before
  754. * giving up and serving anyway (issue #905). On a normal repo the reconcile
  755. * finishes in well under this, so the gate is fully honored and nothing changes.
  756. * On a very large repo (~100k files) the reconcile takes minutes — blocking the
  757. * first call on all of it presents as a multi-minute hang — so we wait briefly
  758. * for a clean answer, then serve and let the reconcile finish in the background
  759. * (it yields to the event loop, so a concurrent read still runs).
  760. *
  761. * `CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS` overrides the default; `0` restores the
  762. * old unbounded-wait behavior (always block until the reconcile completes).
  763. */
  764. const DEFAULT_CATCHUP_GATE_TIMEOUT_MS = 3000;
  765. function resolveCatchUpGateTimeoutMs(): number {
  766. const raw = process.env.CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS;
  767. if (raw === undefined || raw === '') return DEFAULT_CATCHUP_GATE_TIMEOUT_MS;
  768. const n = Number(raw);
  769. if (!Number.isFinite(n) || n < 0) return DEFAULT_CATCHUP_GATE_TIMEOUT_MS;
  770. return Math.floor(n);
  771. }
  772. /**
  773. * Prefix each line of a source slice with its 1-based line number, matching
  774. * the Read tool's `cat -n` convention (number + tab) so the agent treats it
  775. * the same way it treats Read output.
  776. *
  777. * @param slice contiguous source text (already extracted from the file)
  778. * @param firstLineNumber the 1-based line number of the slice's first line
  779. */
  780. function numberSourceLines(slice: string, firstLineNumber: number): string {
  781. const out: string[] = [];
  782. const split = slice.split('\n');
  783. for (let i = 0; i < split.length; i++) {
  784. out.push(`${firstLineNumber + i}\t${split[i]}`);
  785. }
  786. return out.join('\n');
  787. }
  788. /**
  789. * Unique line-prefix for a per-file source section in codegraph_explore output.
  790. * Issue #778: tool results dropped ATX headings (`####`, `##`, `###`) for bold
  791. * labels so Markdown-rendering MCP clients (e.g. the Claude Code VSCode
  792. * extension) stop blowing every header up to H1–H4. The path is bold + a code
  793. * span so it still reads as a header, and the leading ``**` `` stays a UNIQUE,
  794. * greppable marker — no other explore line begins with it — that the explore
  795. * truncation boundary (`handleExplore`) keys off to cut on whole file sections.
  796. */
  797. const FILE_SECTION_PREFIX = '**`';
  798. // Placeholder for codegraph_explore's "Found N symbols across M files." line.
  799. // The honest N/M can only be known after the final truncation drops trailing
  800. // sections (#1046), so the header is emitted as this sentinel and substituted
  801. // at the very end. This bracketed token never occurs in rendered source or a
  802. // file path, so the final string-replace can't collide.
  803. const SUMMARY_SENTINEL = '[[codegraph-explore-summary]]';
  804. function fileSectionHeader(filePath: string, suffix: string): string {
  805. return suffix
  806. ? `${FILE_SECTION_PREFIX}${filePath}\`** — ${suffix}`
  807. : `${FILE_SECTION_PREFIX}${filePath}\`**`;
  808. }
  809. /** Header of `codegraph_explore`'s trailing pointer list. */
  810. const POINTER_HEADER = '**Not shown above — explore these names for their source**';
  811. /** Most files the pointer list ever names one-per-line; the rest are a count. */
  812. const POINTER_MAX_FILES = 10;
  813. /**
  814. * How many elided-in-file symbols a gap marker or biased header names (#1711).
  815. * Kept small: the names exist so a follow-up explore has a target, not so the
  816. * meta-text rivals the source it is pointing at.
  817. */
  818. const ELIDED_SYMBOL_CAP = 6;
  819. type ElidedSymbolRef = { name: string; kind: string; startLine: number };
  820. /**
  821. * Indexed symbols whose definition starts strictly between two rendered
  822. * spans. The hole is what a trim dropped; naming them is what lets the agent
  823. * follow up by name instead of guessing (#1711).
  824. */
  825. export function symbolsBetweenRanges(
  826. nodes: ReadonlyArray<{ name: string; kind: string; startLine: number; endLine: number }>,
  827. fromEnd: number,
  828. toStart: number,
  829. ): ElidedSymbolRef[] {
  830. if (toStart <= fromEnd + 1) return [];
  831. const out: ElidedSymbolRef[] = [];
  832. const seen = new Set<string>();
  833. for (const n of nodes) {
  834. if (n.kind === 'import' || n.kind === 'export') continue;
  835. if (n.startLine <= fromEnd || n.startLine >= toStart) continue;
  836. if (seen.has(n.name)) continue;
  837. seen.add(n.name);
  838. out.push({ name: n.name, kind: n.kind, startLine: n.startLine });
  839. }
  840. out.sort((a, b) => a.startLine - b.startLine);
  841. return out;
  842. }
  843. /**
  844. * Symbols in `candidates` whose start line is not covered by any emitted range.
  845. * Used to bias the per-file header toward what the trim dropped (#1711).
  846. */
  847. export function symbolsNotInRanges(
  848. candidates: ReadonlyArray<ElidedSymbolRef>,
  849. ranges: ReadonlyArray<ExploreLineRange>,
  850. ): ElidedSymbolRef[] {
  851. if (ranges.length === 0) return [...candidates].sort((a, b) => a.startLine - b.startLine);
  852. const out: ElidedSymbolRef[] = [];
  853. const seen = new Set<string>();
  854. for (const n of candidates) {
  855. if (seen.has(n.name)) continue;
  856. if (ranges.some((r) => n.startLine >= r.start && n.startLine <= r.end)) continue;
  857. seen.add(n.name);
  858. out.push(n);
  859. }
  860. out.sort((a, b) => a.startLine - b.startLine);
  861. return out;
  862. }
  863. /**
  864. * Gap marker between two non-contiguous slices of one file.
  865. *
  866. * Bare `... (gap) ...` told the agent something was missing but not WHAT —
  867. * and the footer then asked it to re-explore "with its exact name", which is
  868. * circular when the missing names *are* the question (#1711). When the hole
  869. * holds indexed symbols, list them as `name (file:line)` (same shape the
  870. * flow / blast-radius lines already use).
  871. */
  872. export function formatGapMarker(
  873. filePath: string,
  874. elided: ReadonlyArray<ElidedSymbolRef>,
  875. ): string {
  876. if (elided.length === 0) return '\n\n... (gap) ...\n\n';
  877. const shown = elided.slice(0, ELIDED_SYMBOL_CAP);
  878. const more = elided.length - shown.length;
  879. const names = shown.map((s) => `${s.name} (${filePath}:${s.startLine})`).join(', ')
  880. + (more > 0 ? `, +${more} more` : '');
  881. return `\n\n... (gap: ${names}) ...\n\n`;
  882. }
  883. /** Join rendered parts with gap markers that name whatever the trim skipped. */
  884. export function joinPartsWithNamedGaps(
  885. filePath: string,
  886. parts: ReadonlyArray<{ range: ExploreLineRange; text: string }>,
  887. nodes: ReadonlyArray<{ name: string; kind: string; startLine: number; endLine: number }>,
  888. ): string {
  889. if (parts.length === 0) return '';
  890. let out = parts[0]!.text;
  891. for (let i = 1; i < parts.length; i++) {
  892. const prev = parts[i - 1]!;
  893. const next = parts[i]!;
  894. out += formatGapMarker(filePath, symbolsBetweenRanges(nodes, prev.range.end, next.range.start));
  895. out += next.text;
  896. }
  897. return out;
  898. }
  899. /**
  900. * Prefer symbols the trim dropped when filling the per-file header's named
  901. * slots, so `+N more` is less likely to hide the answer (#1711). Frequency
  902. * still breaks ties among the preferred / remaining groups.
  903. */
  904. export function biasHeaderSymbols(
  905. symbols: readonly string[],
  906. elided: ReadonlyArray<ElidedSymbolRef>,
  907. cap: number,
  908. ): { shown: string[]; omitted: number } {
  909. const elidedLabels = elided.map((s) => `${s.name}(${s.kind})`);
  910. const elidedSet = new Set(elidedLabels);
  911. const elidedNames = new Set(elided.map((s) => s.name));
  912. const counts = new Map<string, number>();
  913. for (const s of symbols) counts.set(s, (counts.get(s) ?? 0) + 1);
  914. // Also surface elided symbols that never made it into `symbols` (a dropped
  915. // cluster's members are absent from assembleSection's list today).
  916. for (const label of elidedLabels) {
  917. if (!counts.has(label)) counts.set(label, 1);
  918. }
  919. // Earlier elided defs first (elided is startLine-sorted) so the header's
  920. // named slots track source order through the hole rather than alphabetical
  921. // filler (`calls0` beating `syncStateNow`).
  922. const elidedRank = new Map<string, number>();
  923. elided.forEach((s, i) => {
  924. elidedRank.set(`${s.name}(${s.kind})`, i);
  925. if (!elidedRank.has(s.name)) elidedRank.set(s.name, i);
  926. });
  927. const score = (label: string): [number, number, number] => {
  928. const name = label.replace(/\(.*\)$/, '');
  929. const preferred = elidedSet.has(label) || elidedNames.has(name) ? 1 : 0;
  930. const rank = elidedRank.get(label) ?? elidedRank.get(name) ?? 9999;
  931. return [preferred, counts.get(label) ?? 0, -rank];
  932. };
  933. const sorted = [...counts.keys()].sort((a, b) => {
  934. const [pa, ca, ra] = score(a);
  935. const [pb, cb, rb] = score(b);
  936. return pb - pa || cb - ca || rb - ra || a.localeCompare(b);
  937. });
  938. const shown = sorted.slice(0, cap);
  939. return { shown, omitted: Math.max(0, sorted.length - shown.length) };
  940. }
  941. /**
  942. * One pointer line: the file plus enough symbol names to make it NAMEABLE in a
  943. * follow-up explore. Capped — an un-capped list ran to ~1.9K on the #1500
  944. * fixture (12 generated CRUD symbols on one line), meta-text bought at the
  945. * price of the source bytes this section exists to point away from.
  946. */
  947. function pointerLineFor(filePath: string, nodes: readonly Node[]): string {
  948. const POINTER_SYMBOLS = 6;
  949. const named = nodes.filter((n) => n.kind !== 'import' && n.kind !== 'export');
  950. const pool = named.length > 0 ? named : nodes;
  951. const shown = pool.slice(0, POINTER_SYMBOLS);
  952. const more = pool.length - shown.length;
  953. const symbols = shown.map((n) => `${n.name}:${n.startLine}`).join(', ')
  954. + (more > 0 ? `, +${more} more` : '');
  955. return `- ${filePath}: ${symbols}`;
  956. }
  957. /**
  958. * Emitted when the response was too full to carry ANY of its pointer list. It
  959. * is the one line the epilogue floor is reserved for: the list itself can be
  960. * traded away, but the agent must still be told that an uncovered area exists
  961. * and that another explore — not a Read — is how to reach it.
  962. */
  963. const EPILOGUE_LOST_NOTE = '> (Trailing pointer list omitted for size. The source above is complete and verbatim — treat it as already Read. For anything this call did not cover, run another codegraph_explore with the specific names rather than reading those files.)';
  964. /**
  965. * Per-file staleness banner emitted at the top of a tool response when the
  966. * file watcher has pending events for files referenced by the response.
  967. * The agent uses this to fall back to Read for those specific files
  968. * without waiting for the debounced sync (issue #403).
  969. */
  970. export function formatStaleBanner(stale: PendingFile[]): string {
  971. const now = Date.now();
  972. const lines = stale.map((p) => {
  973. const ageMs = Math.max(0, now - p.lastSeenMs);
  974. const label = p.indexing ? 'indexing in progress' : 'pending sync';
  975. return ` - ${p.path} (edited ${ageMs}ms ago, ${label})`;
  976. });
  977. return (
  978. '⚠️ Some files referenced below were edited since the last index sync — ' +
  979. 'their codegraph entries may be stale:\n' +
  980. lines.join('\n') +
  981. '\nFor accurate content of those specific files, Read them directly. ' +
  982. 'The rest of this response is fresh.'
  983. );
  984. }
  985. /**
  986. * Compact footer listing pending files that are NOT referenced in this
  987. * response. Gives the agent a complete project-wide freshness picture
  988. * without bloating the main banner.
  989. */
  990. export function formatStaleFooter(stale: PendingFile[]): string {
  991. const MAX = 5;
  992. const now = Date.now();
  993. const shown = stale.slice(0, MAX);
  994. const lines = shown.map((p) => {
  995. const ageMs = Math.max(0, now - p.lastSeenMs);
  996. return ` - ${p.path} (edited ${ageMs}ms ago)`;
  997. });
  998. const more = stale.length > MAX ? `\n - …and ${stale.length - MAX} more` : '';
  999. return (
  1000. `(Note: ${stale.length} file(s) elsewhere in this project are pending index ` +
  1001. `sync but were not referenced above:\n${lines.join('\n')}${more})`
  1002. );
  1003. }
  1004. /**
  1005. * Whole-index degradation banner (issue #876). Emitted at the top of a read
  1006. * tool response when live watching has permanently stopped — at which point
  1007. * `getPendingFiles()` is empty, so the per-file banner above can't fire even
  1008. * though the index is now FROZEN and silently drifting stale. Leads with the
  1009. * agent-actionable instruction (Read directly) and carries the reason, which
  1010. * already names the operator remedy (`codegraph sync` / git hooks).
  1011. */
  1012. export function formatDegradedBanner(reason: string | null): string {
  1013. return (
  1014. '⚠️ CodeGraph auto-sync is DISABLED — live file watching stopped, so the index is ' +
  1015. 'frozen and any file edited since then is stale here. Read files directly to confirm ' +
  1016. 'current content before relying on it.' +
  1017. (reason ? `\n Reason: ${reason}` : '')
  1018. );
  1019. }
  1020. /**
  1021. * MCP Tool definition
  1022. */
  1023. export interface ToolDefinition {
  1024. name: string;
  1025. description: string;
  1026. inputSchema: {
  1027. type: 'object';
  1028. properties: Record<string, PropertySchema>;
  1029. required?: string[];
  1030. };
  1031. /** Behavioral hints for clients (see {@link ToolAnnotations}). */
  1032. annotations?: ToolAnnotations;
  1033. /**
  1034. * MCP `_meta` on the tool definition. `anthropic/alwaysLoad: true` makes
  1035. * Claude Code load the tool at session start instead of deferring it behind
  1036. * its tool search (https://code.claude.com/docs/en/mcp#exempt-a-server-from-deferral).
  1037. */
  1038. _meta?: Record<string, unknown>;
  1039. }
  1040. /**
  1041. * MCP ToolAnnotations — behavioral hints a client MAY use to decide how, or
  1042. * whether, to run a tool (introduced in the 2025-03-26 spec, carried in
  1043. * 2025-06-18). They are advisory and never to be trusted for security, but
  1044. * clients gate on them: Cursor's Ask mode, for one, refuses any MCP tool that
  1045. * doesn't advertise `readOnlyHint: true` (issue #1018).
  1046. *
  1047. * The field is purely additive — a client that predates annotations ignores it
  1048. * — so codegraph advertises these even though `initialize` still negotiates the
  1049. * 2024-11-05 protocol version.
  1050. *
  1051. * https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations
  1052. */
  1053. export interface ToolAnnotations {
  1054. /** Human-readable title for the tool. */
  1055. title?: string;
  1056. /** If true, the tool does not modify its environment. Default (unset): false. */
  1057. readOnlyHint?: boolean;
  1058. /** Meaningful only when NOT read-only: may the tool perform destructive updates? */
  1059. destructiveHint?: boolean;
  1060. /** If true, repeat calls with the same arguments have no additional effect. */
  1061. idempotentHint?: boolean;
  1062. /** If true, the tool interacts with an open world of external entities. */
  1063. openWorldHint?: boolean;
  1064. }
  1065. interface PropertySchema {
  1066. type: string;
  1067. description: string;
  1068. enum?: string[];
  1069. default?: unknown;
  1070. }
  1071. /**
  1072. * Tool execution result
  1073. */
  1074. export interface ToolResult {
  1075. content: Array<{
  1076. type: 'text';
  1077. text: string;
  1078. }>;
  1079. isError?: boolean;
  1080. /**
  1081. * INTERNAL side-channel (CG-17): what a `codegraph_explore` call actually put
  1082. * on the wire — files, line ranges, bytes. It rides the result because the
  1083. * call may have run on a query-pool worker, while the session state it feeds
  1084. * lives on the main thread. {@link ToolHandler.execute} records it and DELETES
  1085. * it, so nothing here ever reaches the client. Keyed by
  1086. * {@link EXPLORE_EMISSION_KEY}; the two must stay in sync.
  1087. */
  1088. _cgExploreEmission?: ExploreEmission;
  1089. }
  1090. /**
  1091. * Common projectPath property for cross-project queries
  1092. */
  1093. const projectPathProperty: PropertySchema = {
  1094. type: 'string',
  1095. description: 'Absolute path to the project to query (or any directory inside it) — codegraph uses the nearest .codegraph/ index at or above that path. Omit to use this session\'s default project. Pass it to query a second codebase, or when the server root has no index of its own (e.g. a monorepo where only sub-projects are indexed, so there is no default project).',
  1096. };
  1097. /**
  1098. * EVERY codegraph tool is query-only: it reads the pre-built index and never
  1099. * mutates the workspace (indexing is the user's explicit CLI call, never the
  1100. * agent's). Advertising this read-only contract lets clients that gate on it run
  1101. * the tools where a possibly-mutating tool would be blocked — most concretely,
  1102. * Cursor's Ask mode, which rejects any MCP tool lacking `readOnlyHint: true`
  1103. * (issue #1018). `idempotentHint`: a repeated query has no additional effect.
  1104. * `openWorldHint: false`: the domain is the closed local index, not an open
  1105. * external world. Shared so the contract is declared once; a hypothetical
  1106. * mutating tool would simply not reference it.
  1107. */
  1108. const READ_ONLY_ANNOTATIONS: ToolAnnotations = {
  1109. readOnlyHint: true,
  1110. destructiveHint: false,
  1111. idempotentHint: true,
  1112. openWorldHint: false,
  1113. };
  1114. /**
  1115. * All CodeGraph MCP tools
  1116. *
  1117. * Designed for minimal context usage - use codegraph_explore as the primary tool
  1118. * (one call usually answers the whole question), and only use other tools for
  1119. * targeted follow-up queries.
  1120. *
  1121. * All tools support cross-project queries via the optional `projectPath` parameter.
  1122. */
  1123. export const tools: ToolDefinition[] = [
  1124. {
  1125. name: 'codegraph_search',
  1126. 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.',
  1127. inputSchema: {
  1128. type: 'object',
  1129. properties: {
  1130. query: {
  1131. type: 'string',
  1132. description: 'Symbol name or partial name (e.g., "auth", "signIn", "UserService")',
  1133. },
  1134. kind: {
  1135. type: 'string',
  1136. description: 'Filter by node kind',
  1137. enum: ['function', 'method', 'class', 'interface', 'type', 'variable', 'route', 'component'],
  1138. },
  1139. limit: {
  1140. type: 'number',
  1141. description: 'Maximum results (default: 10)',
  1142. default: 10,
  1143. },
  1144. projectPath: projectPathProperty,
  1145. },
  1146. required: ['query'],
  1147. },
  1148. annotations: READ_ONLY_ANNOTATIONS,
  1149. },
  1150. {
  1151. name: 'codegraph_callers',
  1152. description: 'List functions that call <symbol>. For the full flow, use codegraph_explore.',
  1153. inputSchema: {
  1154. type: 'object',
  1155. properties: {
  1156. symbol: {
  1157. type: 'string',
  1158. description: 'Name of the function, method, or class to find callers for',
  1159. },
  1160. file: {
  1161. type: 'string',
  1162. 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)',
  1163. },
  1164. limit: {
  1165. type: 'number',
  1166. description: 'Maximum number of callers to return (default: 20)',
  1167. default: 20,
  1168. },
  1169. projectPath: projectPathProperty,
  1170. },
  1171. required: ['symbol'],
  1172. },
  1173. annotations: READ_ONLY_ANNOTATIONS,
  1174. },
  1175. {
  1176. name: 'codegraph_callees',
  1177. description: 'List functions that <symbol> calls. For the full flow, use codegraph_explore.',
  1178. inputSchema: {
  1179. type: 'object',
  1180. properties: {
  1181. symbol: {
  1182. type: 'string',
  1183. description: 'Name of the function, method, or class to find callees for',
  1184. },
  1185. file: {
  1186. type: 'string',
  1187. description: 'Narrow to the definition in this file (path or suffix) when several same-named symbols exist',
  1188. },
  1189. limit: {
  1190. type: 'number',
  1191. description: 'Maximum number of callees to return (default: 20)',
  1192. default: 20,
  1193. },
  1194. projectPath: projectPathProperty,
  1195. },
  1196. required: ['symbol'],
  1197. },
  1198. annotations: READ_ONLY_ANNOTATIONS,
  1199. },
  1200. {
  1201. name: 'codegraph_impact',
  1202. description: 'List symbols affected by changing <symbol>. Use before a refactor.',
  1203. inputSchema: {
  1204. type: 'object',
  1205. properties: {
  1206. symbol: {
  1207. type: 'string',
  1208. description: 'Name of the symbol to analyze impact for',
  1209. },
  1210. file: {
  1211. type: 'string',
  1212. description: 'Narrow to the definition in this file (path or suffix) when several same-named symbols exist',
  1213. },
  1214. depth: {
  1215. type: 'number',
  1216. description: 'How many levels of dependencies to traverse (default: 2)',
  1217. default: 2,
  1218. },
  1219. projectPath: projectPathProperty,
  1220. },
  1221. required: ['symbol'],
  1222. },
  1223. annotations: READ_ONLY_ANNOTATIONS,
  1224. },
  1225. {
  1226. name: 'codegraph_node',
  1227. 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.',
  1228. inputSchema: {
  1229. type: 'object',
  1230. properties: {
  1231. symbol: {
  1232. type: 'string',
  1233. description: 'Name of the symbol to read (symbol mode). Omit it and pass `file` alone to read a whole file like Read.',
  1234. },
  1235. includeCode: {
  1236. type: 'boolean',
  1237. description: 'Symbol mode: include the symbol\'s full body (default: false). Ignored in file mode, which always returns source unless `symbolsOnly` is set.',
  1238. default: false,
  1239. },
  1240. file: {
  1241. type: 'string',
  1242. 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.',
  1243. },
  1244. offset: {
  1245. type: 'number',
  1246. description: 'File mode: 1-based line to start reading from, exactly like Read\'s offset. Defaults to the start of the file.',
  1247. },
  1248. limit: {
  1249. type: 'number',
  1250. 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).',
  1251. },
  1252. symbolsOnly: {
  1253. type: 'boolean',
  1254. description: 'File mode: return just the file\'s symbol map + dependents (a cheap structural overview) instead of its source.',
  1255. default: false,
  1256. },
  1257. line: {
  1258. type: 'number',
  1259. description: 'Symbol mode only: disambiguate to the definition at/around this line (use with the file:line a trail showed you).',
  1260. },
  1261. projectPath: projectPathProperty,
  1262. },
  1263. required: [],
  1264. },
  1265. annotations: READ_ONLY_ANNOTATIONS,
  1266. },
  1267. {
  1268. name: 'codegraph_explore',
  1269. 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.',
  1270. inputSchema: {
  1271. type: 'object',
  1272. properties: {
  1273. query: {
  1274. type: 'string',
  1275. 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.',
  1276. },
  1277. maxFiles: {
  1278. type: 'number',
  1279. description: 'Maximum number of files to include source code from (default: 12)',
  1280. default: 12,
  1281. },
  1282. projectPath: projectPathProperty,
  1283. },
  1284. required: ['query'],
  1285. },
  1286. annotations: READ_ONLY_ANNOTATIONS,
  1287. // Loaded from the first prompt in Claude Code, which otherwise defers every
  1288. // MCP tool behind a ToolSearch step (#1696).
  1289. _meta: { 'anthropic/alwaysLoad': true },
  1290. },
  1291. {
  1292. name: 'codegraph_status',
  1293. description: 'Index health check (files / nodes / edges). Skip unless debugging.',
  1294. inputSchema: {
  1295. type: 'object',
  1296. properties: {
  1297. projectPath: projectPathProperty,
  1298. },
  1299. },
  1300. annotations: READ_ONLY_ANNOTATIONS,
  1301. },
  1302. {
  1303. name: 'codegraph_files',
  1304. description: 'Indexed file tree with language + symbol counts. Faster than Glob for project layout.',
  1305. inputSchema: {
  1306. type: 'object',
  1307. properties: {
  1308. path: {
  1309. type: 'string',
  1310. description: 'Filter to files under this directory path (e.g., "src/components"). Returns all files if not specified.',
  1311. },
  1312. pattern: {
  1313. type: 'string',
  1314. description: 'Filter files matching this glob pattern (e.g., "*.tsx", "**/*.test.ts")',
  1315. },
  1316. format: {
  1317. type: 'string',
  1318. description: 'Output format: "tree" (hierarchical, default), "flat" (simple list), "grouped" (by language)',
  1319. enum: ['tree', 'flat', 'grouped'],
  1320. default: 'tree',
  1321. },
  1322. includeMetadata: {
  1323. type: 'boolean',
  1324. description: 'Include file metadata like language and symbol count (default: true)',
  1325. default: true,
  1326. },
  1327. maxDepth: {
  1328. type: 'number',
  1329. description: 'Maximum directory depth to show (default: unlimited)',
  1330. },
  1331. projectPath: projectPathProperty,
  1332. },
  1333. },
  1334. annotations: READ_ONLY_ANNOTATIONS,
  1335. },
  1336. ];
  1337. /**
  1338. * Return `defs` with `projectPath` marked `required` in each tool's inputSchema.
  1339. *
  1340. * Used for the NO-DEFAULT-PROJECT tool surface (issue #993): when the MCP server
  1341. * has no default project to fall back to — a gateway server started outside any
  1342. * repo, or a monorepo root whose `.codegraph/` indexes live only in sub-projects
  1343. * — every call MUST carry an explicit `projectPath`, so the schema should say so.
  1344. * A `required` field is a HIGH-salience channel (MCP clients surface and often
  1345. * validate it), unlike the instructions text the reporter found too weak to stop
  1346. * the agent omitting the param. When a default project IS open, callers leave
  1347. * projectPath optional and never call this.
  1348. *
  1349. * Pure: clones each tool's schema rather than mutating the shared module-level
  1350. * `tools` array (reused by every session and the static surface). A tool that
  1351. * doesn't expose projectPath, or already requires it, is returned untouched;
  1352. * explore's `['query']` becomes `['query', 'projectPath']`, and a tool with no
  1353. * `required` list (status/files) gains `['projectPath']`.
  1354. */
  1355. function withRequiredProjectPath(defs: ToolDefinition[]): ToolDefinition[] {
  1356. return defs.map((tool) => {
  1357. if (!tool.inputSchema.properties.projectPath) return tool;
  1358. const required = tool.inputSchema.required ?? [];
  1359. if (required.includes('projectPath')) return tool;
  1360. return {
  1361. ...tool,
  1362. inputSchema: { ...tool.inputSchema, required: [...required, 'projectPath'] },
  1363. };
  1364. });
  1365. }
  1366. /**
  1367. * Allowlist-filtered tool definitions WITHOUT an engine — the static surface the
  1368. * proxy answers `tools/list` with before any project is open. Mirrors
  1369. * `ToolHandler.getTools()` in the no-CodeGraph case (the dynamic per-repo budget
  1370. * note in a description only adds once `cg` is loaded; the schemas are static).
  1371. */
  1372. export function getStaticTools(): ToolDefinition[] {
  1373. const raw = process.env.CODEGRAPH_MCP_TOOLS;
  1374. if (!raw || !raw.trim()) {
  1375. return tools.filter(t => DEFAULT_MCP_TOOLS.has(t.name.replace(/^codegraph_/, '')));
  1376. }
  1377. const allow = new Set(raw.split(',').map(s => s.trim().replace(/^codegraph_/, '')).filter(Boolean));
  1378. return allow.size ? tools.filter(t => allow.has(t.name.replace(/^codegraph_/, ''))) : tools;
  1379. }
  1380. /**
  1381. * The MCP tools served by DEFAULT (short names). Pared to ONLY `codegraph_explore`
  1382. * — the single tool that reliably earns its place: one capped call returns the
  1383. * verbatim source of the relevant symbols grouped by file. Every other tool is a
  1384. * narrower slice of what explore already does, and presence itself steers
  1385. * mis-picks, so they are no longer LISTED to agents.
  1386. *
  1387. * The other defined tools (`node`, `search`, `callers`, plus callees/impact/files/
  1388. * status) remain fully functional — handlers stay, the library API and CLI are
  1389. * untouched, and `CODEGRAPH_MCP_TOOLS=explore,node,...` re-enables any of them.
  1390. */
  1391. const DEFAULT_MCP_TOOLS = new Set(['explore']);
  1392. /**
  1393. * Tool handler that executes tools against a CodeGraph instance
  1394. *
  1395. * Supports cross-project queries via the projectPath parameter.
  1396. * Other projects are opened on-demand and cached for performance.
  1397. */
  1398. export class ToolHandler {
  1399. // Cache of opened CodeGraph instances for cross-project queries
  1400. private projectCache: Map<string, CodeGraph> = new Map();
  1401. // The directory the server last searched for a default project. Surfaced in
  1402. // the "not initialized" error so users can see why detection missed.
  1403. private defaultProjectHint: string | null = null;
  1404. // Indexed sub-projects the engine's bounded down-scan saw below the search
  1405. // base when no default project resolved (#1607). Listed in the "not
  1406. // initialized" error so the fact is reachable through the protocol, not just
  1407. // the host's stderr capture. Engine-maintained (initial resolve + throttled
  1408. // retry) — tool calls themselves never scan.
  1409. private knownSubprojects: string[] = [];
  1410. private knownSubprojectsBase: string | null = null;
  1411. // Per-start-path cache of the git worktree/index mismatch (issue #155). The
  1412. // mismatch is a fixed property of (where the request came from → which
  1413. // .codegraph/ it resolves to), so the up-to-two `git rev-parse` spawns run
  1414. // once and every later tool call reuses the result — never shelling out to
  1415. // git on the hot path. `undefined` = not computed yet; `null` = no mismatch.
  1416. private worktreeMismatchCache: Map<string, WorktreeIndexMismatch | null> = new Map();
  1417. // Gate that the MCP engine pokes after `cg.open()` so the first tool call
  1418. // blocks on the post-open filesystem reconcile (catch-up sync). Without
  1419. // this, a tool call that races past `catchUpSync()` serves rows for files
  1420. // that were deleted (or edited) while no MCP server was running — and the
  1421. // per-file staleness banner can't help, because `getPendingFiles()` is
  1422. // populated by the watcher, not by catch-up. The wait is time-boxed
  1423. // (see {@link resolveCatchUpGateTimeoutMs}) so a minutes-long reconcile on a
  1424. // huge repo can't hang the first call (#905); cleared on first await so
  1425. // subsequent calls don't pay any cost.
  1426. private catchUpGate: Promise<void> | null = null;
  1427. // Optional worker-thread pool for off-loop read-tool dispatch (daemon mode).
  1428. // When set + healthy, the heavy read tools run on a worker so the daemon's
  1429. // main loop stays free for the MCP transport under concurrent load. Null in
  1430. // direct/in-process mode (one client, no concurrency to parallelize).
  1431. private queryPool: QueryPool | null = null;
  1432. constructor(private cg: CodeGraph | null) {}
  1433. /**
  1434. * Engine-only: attach (or detach with null) the worker-thread query pool. The
  1435. * shared daemon sets this once its default project is open; the workers each
  1436. * hold their own WAL read connection and run {@link executeReadTool}. A
  1437. * worker's own ToolHandler never has a pool, so there is no nested off-loading.
  1438. */
  1439. setQueryPool(pool: QueryPool | null): void {
  1440. this.queryPool = pool;
  1441. }
  1442. /**
  1443. * Update the default CodeGraph instance (e.g. after lazy initialization)
  1444. */
  1445. setDefaultCodeGraph(cg: CodeGraph): void {
  1446. this.cg = cg;
  1447. }
  1448. /**
  1449. * Engine-only: register the catch-up sync promise so the next `execute()`
  1450. * call awaits it before serving. The handler swallows rejections (the
  1451. * engine logs them) so a sync failure never propagates as a tool error;
  1452. * we still want to serve a best-effort result over the same potentially-
  1453. * stale data, which is what would have happened without the gate.
  1454. */
  1455. setCatchUpGate(p: Promise<void> | null): void {
  1456. this.catchUpGate = p;
  1457. }
  1458. /**
  1459. * Await the catch-up gate, but no longer than the configured timeout (#905).
  1460. * If the reconcile settles first, we got the fully-reconciled answer. If the
  1461. * timeout wins, we serve the call now and let the reconcile finish in the
  1462. * background — it yields to the event loop (see SYNC_RECONCILE_YIELD_INTERVAL),
  1463. * so a concurrent read still runs against the same connection. Never throws:
  1464. * a failed reconcile is logged by the engine, and we serve best-effort over
  1465. * the same potentially-stale data the un-gated path would have.
  1466. */
  1467. private async awaitCatchUpGate(gate: Promise<void>): Promise<void> {
  1468. const timeoutMs = resolveCatchUpGateTimeoutMs();
  1469. if (timeoutMs <= 0) {
  1470. // 0 = opt back into the original unbounded wait.
  1471. try { await gate; } catch { /* engine already logged */ }
  1472. return;
  1473. }
  1474. let timer: NodeJS.Timeout | undefined;
  1475. const timedOut = new Promise<'timeout'>((resolve) => {
  1476. timer = setTimeout(() => resolve('timeout'), timeoutMs);
  1477. timer.unref?.();
  1478. });
  1479. try {
  1480. const outcome = await Promise.race([
  1481. gate.then(() => 'done' as const, () => 'done' as const),
  1482. timedOut,
  1483. ]);
  1484. if (outcome === 'timeout') {
  1485. process.stderr.write(
  1486. `[CodeGraph MCP] Catch-up reconcile still running after ${timeoutMs}ms; serving this tool call now and finishing the reconcile in the background (#905). ` +
  1487. `Set CODEGRAPH_CATCHUP_GATE_TIMEOUT_MS=0 to always wait for it.\n`
  1488. );
  1489. }
  1490. } finally {
  1491. if (timer) clearTimeout(timer);
  1492. }
  1493. }
  1494. /**
  1495. * Record the directory the server tried to resolve the default project from.
  1496. * Used only to make the "no default project" error actionable.
  1497. */
  1498. setDefaultProjectHint(searchedPath: string): void {
  1499. this.defaultProjectHint = searchedPath;
  1500. }
  1501. /**
  1502. * Engine-only: record the indexed sub-projects the workspace down-scan saw
  1503. * when it could not adopt a default project (#1606/#1607). An empty list
  1504. * clears any previous note.
  1505. */
  1506. setKnownSubprojects(roots: string[], base: string): void {
  1507. this.knownSubprojects = roots;
  1508. this.knownSubprojectsBase = base;
  1509. }
  1510. /** One message line naming the indexed sub-projects, or '' when none known. */
  1511. private formatKnownSubprojects(): string {
  1512. if (this.knownSubprojects.length === 0) return '';
  1513. const base = this.knownSubprojectsBase;
  1514. const rels = this.knownSubprojects.map((r) => (base ? relativePath(base, r) || '.' : r));
  1515. return (
  1516. `Indexed sub-projects were found below it: ${rels.join(', ')} — ` +
  1517. 'pass one of them (absolute, or resolved against that directory) as projectPath.\n'
  1518. );
  1519. }
  1520. /**
  1521. * Whether a default CodeGraph instance is available
  1522. */
  1523. hasDefaultCodeGraph(): boolean {
  1524. return this.cg !== null;
  1525. }
  1526. /**
  1527. * Optional allowlist of exposed tools, parsed from the CODEGRAPH_MCP_TOOLS
  1528. * env var (comma-separated short names, e.g. "trace,search,node,context").
  1529. * Unset/empty → every tool is exposed. Lets an operator (or an A/B harness)
  1530. * trim the tool surface without rebuilding the client config; the ablated
  1531. * tool is then truly absent from ListTools rather than merely denied on call.
  1532. * Matching is on the short form, so "node" and "codegraph_node" both work.
  1533. */
  1534. private toolAllowlist(): Set<string> | null {
  1535. const raw = process.env.CODEGRAPH_MCP_TOOLS;
  1536. if (!raw || !raw.trim()) return null;
  1537. const short = (s: string) => s.trim().replace(/^codegraph_/, '');
  1538. const set = new Set(raw.split(',').map(short).filter(Boolean));
  1539. return set.size ? set : null;
  1540. }
  1541. /** Whether a tool name passes the CODEGRAPH_MCP_TOOLS allowlist (if any). */
  1542. private isToolAllowed(name: string): boolean {
  1543. const allow = this.toolAllowlist();
  1544. return !allow || allow.has(name.replace(/^codegraph_/, ''));
  1545. }
  1546. /**
  1547. * Get tool definitions with dynamic descriptions based on project size.
  1548. * The codegraph_explore tool description includes a budget recommendation
  1549. * scaled to the number of indexed files. Honors the CODEGRAPH_MCP_TOOLS
  1550. * allowlist so a trimmed surface is reflected in ListTools.
  1551. */
  1552. getTools(): ToolDefinition[] {
  1553. const allow = this.toolAllowlist();
  1554. // No explicit allowlist → the default 4-tool surface (see
  1555. // DEFAULT_MCP_TOOLS for the evidence). An allowlist replaces the
  1556. // default entirely, so any defined tool can be re-enabled.
  1557. let visible = allow
  1558. ? tools.filter(t => allow.has(t.name.replace(/^codegraph_/, '')))
  1559. : tools.filter(t => DEFAULT_MCP_TOOLS.has(t.name.replace(/^codegraph_/, '')));
  1560. // No default project loaded → no-root-index case (#993): a gateway server
  1561. // started outside any repo, or a monorepo root whose indexes live in
  1562. // sub-projects. With nothing to fall back to, EVERY call needs an explicit
  1563. // projectPath, so mark it required in the schema — a high-salience nudge the
  1564. // agent acts on, where SERVER_INSTRUCTIONS_NO_ROOT_INDEX's prose alone
  1565. // wasn't enough (the reporter had to add an AGENTS.md note). `this.cg` is
  1566. // settled by `retryInitIfNeeded()` before `handleToolsList` calls us, so a
  1567. // null here means "genuinely no default", not a startup race. When a default
  1568. // IS open we leave projectPath optional (below): a bare call falls back to
  1569. // it, exactly as in the common single-project launch.
  1570. if (!this.cg) return withRequiredProjectPath(visible);
  1571. try {
  1572. const stats = this.cg.getStats();
  1573. const budget = getExploreBudget(stats.fileCount);
  1574. // Tiny-repo tool gating: on projects under TINY_REPO_FILE_THRESHOLD
  1575. // files, only expose the core trio (search, node, explore) — one
  1576. // below even the 4-tool default: at this scale callers, too, reduces
  1577. // to one grep. (Historical note: the audit below ran when context and
  1578. // trace still existed; its "5 core tools" are today's trio.)
  1579. //
  1580. // n=2 audits ruled out cutting below 5 tools:
  1581. // - 3-tool gate (search + context + trace): cost regressed on
  1582. // cobra/ky/sinatra. The agent fell back to raw Reads to cover
  1583. // what codegraph_node + codegraph_explore would have answered.
  1584. // - 1-tool gate (search only): catastrophic regression — express
  1585. // went from -43% WIN to +107% LOSS. With only search, the agent
  1586. // can't navigate the call graph structurally and reads everything.
  1587. //
  1588. // 5 is the empirical lower bound. Tools beyond search/context/
  1589. // node/explore/trace pay overhead that the agent doesn't recoup
  1590. // on tiny-repo flow questions.
  1591. // ITER4: raise threshold 150 → 500 so single-file frameworks
  1592. // (sinatra at 159, slim_framework around 200) also get the
  1593. // 5-tool surface. The empirical 5-tool floor was set on <150
  1594. // probes; iter3 measurement showed sinatra is structurally the
  1595. // SAME problem as cobra (single-file WITHOUT-arm Read wins),
  1596. // so it deserves the same gating.
  1597. const TINY_REPO_FILE_THRESHOLD = 500;
  1598. const TINY_REPO_CORE_TOOLS = new Set([
  1599. 'codegraph_explore',
  1600. 'codegraph_search',
  1601. 'codegraph_node',
  1602. ]);
  1603. if (stats.fileCount < TINY_REPO_FILE_THRESHOLD) {
  1604. visible = visible.filter(t => TINY_REPO_CORE_TOOLS.has(t.name));
  1605. }
  1606. return visible.map(tool => {
  1607. if (tool.name === 'codegraph_explore') {
  1608. return {
  1609. ...tool,
  1610. description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
  1611. };
  1612. }
  1613. return tool;
  1614. });
  1615. } catch {
  1616. return visible;
  1617. }
  1618. }
  1619. /**
  1620. * Get CodeGraph instance for a project
  1621. *
  1622. * If projectPath is provided, opens that project's CodeGraph (cached).
  1623. * Otherwise returns the default CodeGraph instance.
  1624. *
  1625. * Walks up parent directories to find the nearest .codegraph/ folder,
  1626. * similar to how git finds .git/ directories.
  1627. */
  1628. private getCodeGraph(projectPath?: string): CodeGraph {
  1629. if (!projectPath) {
  1630. if (!this.cg) {
  1631. const searched = this.defaultProjectHint ?? process.cwd();
  1632. throw new NotIndexedError(
  1633. 'No CodeGraph project is loaded for this session.\n' +
  1634. `Searched for a .codegraph/ directory starting from: ${searched}\n` +
  1635. this.formatKnownSubprojects() +
  1636. 'Either the server root has no index of its own (e.g. a monorepo where only ' +
  1637. "sub-projects are indexed), or the MCP client launched the server outside your " +
  1638. 'project without reporting the workspace root. Either way, target the project ' +
  1639. 'explicitly:\n' +
  1640. ' • Pass projectPath to the tool call, e.g. projectPath: "/absolute/path/to/your/project" ' +
  1641. '(any project that has a .codegraph/ — including a sub-project of a monorepo)\n' +
  1642. ' • Or add --path to the server\'s MCP config args: ["serve", "--mcp", "--path", "/absolute/path/to/your/project"]\n' +
  1643. 'If a project simply has no index, use your built-in tools (Read/Grep/Glob) for THAT ' +
  1644. "project (the user can run 'codegraph init' there to enable it) — you can still query " +
  1645. 'other indexed projects by projectPath in the same session.'
  1646. );
  1647. }
  1648. return this.freshen(this.cg);
  1649. }
  1650. // Reject sensitive system directories before opening. Only validate a
  1651. // path that actually exists — a nested or not-yet-created sub-path of a
  1652. // real project must still be allowed to resolve UP to its .codegraph/
  1653. // root below (issue #238), so we don't run the existence-checking
  1654. // validator on paths that are meant to walk up.
  1655. if (existsSync(projectPath)) {
  1656. const pathError = validateProjectPath(projectPath);
  1657. if (pathError) {
  1658. throw new PathRefusalError(pathError);
  1659. }
  1660. }
  1661. // Always RE-RESOLVE the nearest .codegraph/ from the input path. The walk
  1662. // is cheap (a few existsSync up the tree) and is the only thing that
  1663. // notices a path whose index root CHANGED since it was first seen — most
  1664. // importantly a git worktree that gained its own .codegraph/ after the
  1665. // (long-lived) server first resolved it up to the parent checkout. We used
  1666. // to short-circuit on a `projectCache[projectPath]` entry before resolving,
  1667. // which pinned that first resolution for the server's whole lifetime, so a
  1668. // worktree kept being served the parent checkout's index until restart
  1669. // (#926). The DB connection itself is still cached (by resolved root,
  1670. // below), so re-resolving costs only the stat walk, never a reopen.
  1671. const resolvedRoot = findNearestCodeGraphRoot(projectPath);
  1672. if (!resolvedRoot) {
  1673. throw new NotIndexedError(
  1674. `The project at ${projectPath} isn't indexed with codegraph (no .codegraph/ directory found ` +
  1675. 'walking up from it), so codegraph cannot query it. Use your built-in tools (Read/Grep/Glob) ' +
  1676. "for that codebase instead, and don't call codegraph for it again this session. " +
  1677. "Indexing is the user's decision — they can run 'codegraph init' in that project to enable it."
  1678. );
  1679. }
  1680. // If the path resolves to the default project, reuse the already-open
  1681. // default instance rather than opening a SECOND connection to the same DB.
  1682. // A duplicate connection serializes reads against the watcher's auto-sync
  1683. // writes; when WAL isn't in effect (e.g. a filesystem without shared-memory
  1684. // support) that surfaces as intermittent
  1685. // "database is locked" on concurrent tool calls. See issue #238. The
  1686. // default instance is owned/closed by the server, so it's never cached.
  1687. if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
  1688. return this.freshen(this.cg);
  1689. }
  1690. // Cache the open DB connection by RESOLVED ROOT only — never by the input
  1691. // path. One key per instance means closeAll() closes each exactly once, and
  1692. // a changed resolution maps to a different entry instead of a stale hit.
  1693. const cached = this.projectCache.get(resolvedRoot);
  1694. if (cached) return this.freshen(cached);
  1695. const cg = loadCodeGraph().openSync(resolvedRoot);
  1696. this.projectCache.set(resolvedRoot, cg);
  1697. return cg;
  1698. }
  1699. /**
  1700. * Heal a long-lived connection whose `.codegraph/` was removed and recreated
  1701. * at the same path (a worktree recreated, or `rm -rf .codegraph` + re-init)
  1702. * before handing it to a tool. Otherwise the daemon keeps serving the
  1703. * pre-removal snapshot from its now-unlinked file handle until restart — and
  1704. * because the daemon registry is keyed by path, a same-path recreate routes
  1705. * new clients straight back to this same stale daemon (#925). The check is one
  1706. * stat() and a no-op unless the inode actually changed; it never throws into a
  1707. * tool call.
  1708. */
  1709. private freshen(cg: CodeGraph): CodeGraph {
  1710. try {
  1711. if (cg.reopenIfReplaced()) {
  1712. process.stderr.write(
  1713. '[CodeGraph MCP] The index was replaced on disk (e.g. a git worktree ' +
  1714. 'recreated at the same path); reopened the live database in place.\n'
  1715. );
  1716. }
  1717. } catch {
  1718. // Best-effort self-heal — a failed reopen must never break the tool call;
  1719. // the (still stale) handle keeps serving and the next call retries.
  1720. }
  1721. return cg;
  1722. }
  1723. /**
  1724. * Close all cached project connections
  1725. */
  1726. closeAll(): void {
  1727. for (const cg of this.projectCache.values()) {
  1728. cg.close();
  1729. }
  1730. this.projectCache.clear();
  1731. this.worktreeMismatchCache.clear();
  1732. }
  1733. /**
  1734. * Validate that a value is a non-empty string within length bounds.
  1735. *
  1736. * The `maxLength` cap protects against MCP clients that ship huge
  1737. * payloads (10MB+ query strings either by accident or maliciously).
  1738. * Without this, a single oversized input can pin the FTS5 index or
  1739. * exhaust memory before any real work runs.
  1740. */
  1741. private validateString(
  1742. value: unknown,
  1743. name: string,
  1744. maxLength: number = MAX_INPUT_LENGTH
  1745. ): string | ToolResult {
  1746. if (typeof value !== 'string' || value.length === 0) {
  1747. return this.errorResult(`${name} must be a non-empty string`);
  1748. }
  1749. if (value.length > maxLength) {
  1750. return this.errorResult(
  1751. `${name} exceeds maximum length of ${maxLength} characters (got ${value.length})`
  1752. );
  1753. }
  1754. return value;
  1755. }
  1756. /**
  1757. * Validate an optional path-like string input. Returns the value if
  1758. * valid (or undefined), or a ToolResult with the error.
  1759. */
  1760. private validateOptionalPath(
  1761. value: unknown,
  1762. name: string
  1763. ): string | undefined | ToolResult {
  1764. if (value === undefined || value === null) return undefined;
  1765. if (typeof value !== 'string') {
  1766. return this.errorResult(`${name} must be a string`);
  1767. }
  1768. if (value.length > MAX_PATH_LENGTH) {
  1769. return this.errorResult(
  1770. `${name} exceeds maximum length of ${MAX_PATH_LENGTH} characters (got ${value.length})`
  1771. );
  1772. }
  1773. return value;
  1774. }
  1775. /**
  1776. * Cached git worktree/index mismatch for a tool call's effective project.
  1777. *
  1778. * The "effective project" is what the request targets: an explicit
  1779. * `projectPath` arg, else the directory the server resolved its default
  1780. * project from (`defaultProjectHint`), else cwd. Memoized per start path —
  1781. * see `worktreeMismatchCache`. Best-effort: if the project can't be resolved
  1782. * (e.g. nothing initialized yet), it reports "no mismatch" so a tool is never
  1783. * broken by this check.
  1784. */
  1785. private worktreeMismatchFor(projectPath?: string): WorktreeIndexMismatch | null {
  1786. const startPath = projectPath ?? this.defaultProjectHint ?? process.cwd();
  1787. // The verdict depends on BOTH the start path AND the index root it resolves
  1788. // to, so the cache must be keyed on the pair. Resolve the index root first
  1789. // (cheap — getCodeGraph re-walks to the nearest .codegraph/, no git), then
  1790. // key on `(startPath, indexRoot)`. The moment that root changes — most
  1791. // importantly when a git worktree gains its own index and the walk-up stops
  1792. // there instead of at the parent checkout — the key changes and the verdict
  1793. // is recomputed, instead of serving the stale "borrowed the parent's index"
  1794. // warning for the server's whole lifetime. Keying on startPath alone pinned
  1795. // that first verdict until restart (#926).
  1796. let indexRoot: string;
  1797. try {
  1798. indexRoot = this.getCodeGraph(projectPath).getProjectRoot();
  1799. } catch {
  1800. // No resolvable project (or any other resolution error) → nothing to warn.
  1801. return null;
  1802. }
  1803. const cacheKey = `${startPath}\u0000${indexRoot}`;
  1804. const cached = this.worktreeMismatchCache.get(cacheKey);
  1805. if (cached !== undefined) return cached;
  1806. const mismatch = detectWorktreeIndexMismatch(startPath, indexRoot);
  1807. this.worktreeMismatchCache.set(cacheKey, mismatch);
  1808. return mismatch;
  1809. }
  1810. /**
  1811. * Prefix a successful read-tool result with a compact worktree-mismatch
  1812. * notice when the resolved index belongs to a different git working tree than
  1813. * the caller's (issue #155). Without this, an agent in a nested worktree
  1814. * silently trusts main-branch results. No-op on error results and when there
  1815. * is no mismatch. `codegraph_status` is excluded — it embeds its own verbose
  1816. * warning — so it stays out of this path.
  1817. */
  1818. private withWorktreeNotice(result: ToolResult, projectPath?: string): ToolResult {
  1819. if (result.isError) return result;
  1820. const mismatch = this.worktreeMismatchFor(projectPath);
  1821. if (!mismatch) return result;
  1822. const notice = worktreeMismatchNotice(mismatch);
  1823. const [first, ...rest] = result.content;
  1824. if (first && first.type === 'text') {
  1825. return { ...result, content: [{ type: 'text', text: `${notice}\n\n${first.text}` }, ...rest] };
  1826. }
  1827. return result;
  1828. }
  1829. /**
  1830. * Annotate a successful read-tool result with per-file staleness — the
  1831. * non-blocking answer to issue #403. The file watcher tracks every event
  1832. * it sees per path; here we intersect "files referenced in this response"
  1833. * against that pending set and prepend a compact banner so the agent can
  1834. * fall back to Read for those *specific* files without waiting for the
  1835. * debounced sync to fire. Other pending files in the project (not
  1836. * referenced by this response) get a small footer so the agent has a
  1837. * complete picture without bloating the banner.
  1838. *
  1839. * Cost when nothing is pending — the common case — is one boolean check.
  1840. * No I/O, no parsing of markdown beyond a per-pending-file substring scan.
  1841. */
  1842. private driftCache = new Map<string, { at: number; stale: boolean }>();
  1843. private static readonly DRIFT_TTL_MS = 2000;
  1844. /**
  1845. * On-disk drift check for a single indexed file (issue #1474). The code
  1846. * renderers slice CURRENT bytes at INDEXED line ranges; when the file
  1847. * changed after its last index sync those ranges can point at a DIFFERENT
  1848. * symbol's code — served under the requested name with `isError: false`.
  1849. * The watcher-based pending/degraded banners can't cover this for a
  1850. * project reached via `projectPath` (cross-project instances have no
  1851. * watcher, by construction), so freshness is verified here, at the point
  1852. * of emission, from data the index already stores.
  1853. *
  1854. * Cheap and precise: one stat() per file (size + mtime, the same
  1855. * comparison the sync fast path uses); only on a stat mismatch is the
  1856. * content hashed (sha256, matching extraction's `hashContent`) so a
  1857. * touch/checkout that rewrote identical bytes never false-positives.
  1858. * Results are memoized briefly so one response rendering the same file in
  1859. * several sections pays for the check once.
  1860. *
  1861. * Returns true when the on-disk file differs from what was indexed —
  1862. * i.e. indexed line ranges for it are NOT trustworthy. Any failure
  1863. * (missing files-table row, stat/read error) reports false: those cases
  1864. * are handled by the existing not-found paths, and a wrong "stale" flag
  1865. * would needlessly push the agent back to Read.
  1866. */
  1867. private isFileStaleOnDisk(cg: CodeGraph, relPath: string, content?: string): boolean {
  1868. let root: string;
  1869. try {
  1870. root = cg.getProjectRoot();
  1871. } catch {
  1872. return false;
  1873. }
  1874. const key = `${root}\0${relPath}`;
  1875. const now = Date.now();
  1876. const hit = this.driftCache.get(key);
  1877. if (hit && now - hit.at < ToolHandler.DRIFT_TTL_MS) return hit.stale;
  1878. let stale = false;
  1879. try {
  1880. const rec = cg.getFile(relPath);
  1881. const absPath = rec ? validatePathWithinRoot(root, relPath) : null;
  1882. if (rec && absPath && existsSync(absPath)) {
  1883. const st = statSync(absPath);
  1884. // Same freshness test as the sync fast path (extraction/index.ts):
  1885. // equal size + equal floored mtime ⇒ unchanged, no read needed.
  1886. if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt)) {
  1887. const data = content ?? readFileSync(absPath, 'utf-8');
  1888. // Must stay byte-identical to extraction's `hashContent` (sha256 over
  1889. // the utf-8 string) — the identical-rewrite test in
  1890. // mcp-stale-slice.test.ts pins the parity. Inlined (not imported)
  1891. // to keep the extraction module off the MCP startup path.
  1892. stale = createHash('sha256').update(data).digest('hex') !== rec.contentHash;
  1893. }
  1894. }
  1895. } catch {
  1896. stale = false;
  1897. }
  1898. this.driftCache.set(key, { at: now, stale });
  1899. return stale;
  1900. }
  1901. private withStalenessNotice(result: ToolResult, projectPath?: string): ToolResult {
  1902. if (result.isError) return result;
  1903. let cg: CodeGraph;
  1904. try {
  1905. cg = this.getCodeGraph(projectPath);
  1906. } catch {
  1907. return result; // no default project — leave as is
  1908. }
  1909. // Cross-project `projectPath` calls open a cached CodeGraph WITHOUT a
  1910. // watcher (watchers are only attached to the default session project).
  1911. // When the cross-project path happens to be the same project as the
  1912. // default cg, the cached instance is the wrong one — its pendingFiles is
  1913. // permanently empty. Detect the equal-path case and prefer the default
  1914. // cg so the staleness signal still fires when an agent passes the
  1915. // explicit projectPath form of its own project.
  1916. if (this.cg && cg !== this.cg) {
  1917. try {
  1918. const sameProject =
  1919. resolvePath(this.cg.getProjectRoot()) === resolvePath(cg.getProjectRoot());
  1920. if (sameProject) cg = this.cg;
  1921. } catch {
  1922. /* getProjectRoot may throw on a closed instance — leave cg as is */
  1923. }
  1924. }
  1925. // Whole-index degradation (#876): once live watching has permanently
  1926. // stopped, getPendingFiles() is empty so the per-file banner below can't
  1927. // fire — but the index is now FROZEN and silently drifting stale. Surface
  1928. // one global notice instead, so the agent Reads for current content rather
  1929. // than trusting a response off a no-longer-updating index. (Cross-project
  1930. // calls open a watcher-less CodeGraph, so this is false there — correct: we
  1931. // only know degraded state for the default session project.)
  1932. let degraded = false;
  1933. try {
  1934. degraded = cg.isWatcherDegraded?.() ?? false;
  1935. } catch {
  1936. degraded = false;
  1937. }
  1938. if (degraded) {
  1939. const [head, ...tail] = result.content;
  1940. if (!head || head.type !== 'text') return result;
  1941. let reason: string | null = null;
  1942. try {
  1943. reason = cg.getWatcherDegradedReason?.() ?? null;
  1944. } catch {
  1945. reason = null;
  1946. }
  1947. const composed = `${formatDegradedBanner(reason)}\n\n${head.text}`;
  1948. return { ...result, content: [{ type: 'text', text: composed }, ...tail] };
  1949. }
  1950. // Defensive: some test fakes inject a partial CodeGraph stub without the
  1951. // newer pending-files API. Treat missing/throwing as "no pending files."
  1952. let pending: PendingFile[] = [];
  1953. try {
  1954. pending = cg.getPendingFiles?.() ?? [];
  1955. } catch {
  1956. return result;
  1957. }
  1958. if (pending.length === 0) return result;
  1959. const [first, ...rest] = result.content;
  1960. if (!first || first.type !== 'text') return result;
  1961. const text = first.text;
  1962. const inResponse: PendingFile[] = [];
  1963. const elsewhere: PendingFile[] = [];
  1964. for (const p of pending) {
  1965. // Substring match against the project-relative POSIX path — that's
  1966. // exactly the format both the watcher and every codegraph response
  1967. // emit, so a plain includes() is sufficient and avoids regex pitfalls.
  1968. if (text.includes(p.path)) inResponse.push(p);
  1969. else elsewhere.push(p);
  1970. }
  1971. let banner = '';
  1972. if (inResponse.length > 0) {
  1973. banner = formatStaleBanner(inResponse);
  1974. }
  1975. let footer = '';
  1976. if (elsewhere.length > 0) {
  1977. footer = formatStaleFooter(elsewhere);
  1978. }
  1979. if (!banner && !footer) return result;
  1980. const composed = [banner, text, footer].filter(Boolean).join('\n\n');
  1981. return { ...result, content: [{ type: 'text', text: composed }, ...rest] };
  1982. }
  1983. /**
  1984. * Execute a tool by name.
  1985. *
  1986. * `sessionState` is the CALLER's per-session explore history (CG-17). The
  1987. * daemon shares one ToolHandler across every connected session, so this state
  1988. * cannot live on the handler — each session owns one and hands it in, which is
  1989. * what keeps two sessions on one daemon from ever seeing each other's calls.
  1990. * Omit it (the CLI does) and explore behaves exactly as before, untracked.
  1991. */
  1992. async execute(
  1993. toolName: string,
  1994. args: Record<string, unknown>,
  1995. sessionState?: ExploreSessionState,
  1996. ): Promise<ToolResult> {
  1997. try {
  1998. // Block the first tool call on the engine's post-open reconcile so we
  1999. // never serve rows for files deleted/edited while no MCP server was
  2000. // running. The wait is time-boxed (#905): a huge-repo reconcile takes
  2001. // minutes, and blocking the first call on all of it reads as a hang, so
  2002. // we wait briefly then serve and let it finish in the background. The
  2003. // gate is cleared after first await — subsequent calls pay nothing.
  2004. // Catch-up failures are logged by the engine; we proceed regardless so a
  2005. // transient sync error never breaks tools.
  2006. if (this.catchUpGate) {
  2007. const gate = this.catchUpGate;
  2008. this.catchUpGate = null;
  2009. await this.awaitCatchUpGate(gate);
  2010. }
  2011. // Honor the optional tool allowlist (CODEGRAPH_MCP_TOOLS): a trimmed
  2012. // surface rejects ablated tools defensively even if a client cached them.
  2013. if (!this.isToolAllowed(toolName)) {
  2014. return this.errorResult(`Tool ${toolName} is disabled via CODEGRAPH_MCP_TOOLS`);
  2015. }
  2016. // Cross-cutting input validation. All tools accept an optional
  2017. // `projectPath` and most accept either `query`, `task`, or
  2018. // `symbol` — bound their lengths centrally so individual handlers
  2019. // can stay focused on tool-specific logic.
  2020. const pathCheck = this.validateOptionalPath(args.projectPath, 'projectPath');
  2021. if (typeof pathCheck === 'object' && pathCheck !== undefined) {
  2022. return pathCheck;
  2023. }
  2024. // The `path` and `pattern` properties used by codegraph_files are
  2025. // also path-shaped — apply the same cap.
  2026. if (args.path !== undefined) {
  2027. const check = this.validateOptionalPath(args.path, 'path');
  2028. if (typeof check === 'object' && check !== undefined) return check;
  2029. }
  2030. if (args.pattern !== undefined) {
  2031. const check = this.validateOptionalPath(args.pattern, 'pattern');
  2032. if (typeof check === 'object' && check !== undefined) return check;
  2033. }
  2034. // codegraph_status reports watcher state (pending files, degraded mode,
  2035. // worktree warning) and embeds its own sections — it must run on the MAIN
  2036. // thread against the watched default instance, so it is NEVER off-loaded to
  2037. // a worker (whose read connection has no watcher). It also skips the
  2038. // auto-banner wrapper to avoid duplicating its own pending-files section.
  2039. if (toolName === 'codegraph_status') {
  2040. return await this.handleStatus(args);
  2041. }
  2042. // Read tools: off-load the CPU-heavy dispatch to the worker pool when one
  2043. // is attached, healthy, AND has finished its first cold start (daemon
  2044. // mode), so the daemon's single event loop stays free for the MCP
  2045. // transport under concurrent load — otherwise N concurrent explores
  2046. // serialize AND starve the transport until the whole batch drains
  2047. // (clients then time out). Before the first worker is warm, calls run
  2048. // in-process: a call queued behind a cold start sat invisible until the
  2049. // 45s busy backstop — the daemon's first tool call stalling for however
  2050. // long a worker spawn takes on a loaded machine (the #662 flake). With
  2051. // no pool (direct mode) or a degraded one, dispatch runs in-process
  2052. // exactly as before. Either way the result flows through the
  2053. // cross-cutting notices — worktree-index mismatch (#155) and per-file
  2054. // staleness (#403) — which need the watched MAIN instance and so are
  2055. // always applied here, never in the worker.
  2056. //
  2057. // Explore also carries the session's own call history down (CG-17) and its
  2058. // emission record back up. Both travel as plain properties — on the args
  2059. // object down, on the ToolResult up — because either leg may cross a
  2060. // structured-clone boundary into a worker, where a closure or a handler
  2061. // field could not follow.
  2062. const dispatchArgs = this.withSessionView(toolName, args, sessionState);
  2063. const raw = (this.queryPool && this.queryPool.healthy && this.queryPool.ready)
  2064. ? await this.queryPool.run(toolName, dispatchArgs)
  2065. : await this.executeReadTool(toolName, dispatchArgs);
  2066. // Record + STRIP before anything else touches the result: the emission is
  2067. // internal bookkeeping and must never reach the client, whether or not a
  2068. // caller passed session state.
  2069. const result = this.takeExploreEmission(raw, sessionState);
  2070. const withWorktree = this.withWorktreeNotice(result, args.projectPath as string | undefined);
  2071. return this.withStalenessNotice(withWorktree, args.projectPath as string | undefined);
  2072. } catch (err) {
  2073. // Expected condition, not a malfunction: answer as a SUCCESS so the
  2074. // agent keeps trusting the toolset for projects that ARE indexed.
  2075. // (An isError here teaches session-long abandonment — see NotIndexedError.)
  2076. if (err instanceof NotIndexedError) {
  2077. return this.textResult(err.message);
  2078. }
  2079. // Security refusal: a clean error, no retry encouragement.
  2080. if (err instanceof PathRefusalError) {
  2081. return this.errorResult(err.message);
  2082. }
  2083. return this.errorResult(
  2084. `Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
  2085. 'This is an internal codegraph error — retry the call once; if it persists, ' +
  2086. 'continue without codegraph for this task.'
  2087. );
  2088. }
  2089. }
  2090. /**
  2091. * Attach the caller's session view to an explore call's args (CG-17), on a
  2092. * COPY so the caller's object is never mutated. Nothing else sees it: a
  2093. * non-explore tool, or a caller with no session state, gets the args
  2094. * unchanged and pays nothing.
  2095. *
  2096. * A client that spells the internal key itself is stripped rather than
  2097. * trusted — the view decides what source a later call may withhold, so it has
  2098. * to come from the server's own record, never from the wire.
  2099. */
  2100. private withSessionView(
  2101. toolName: string,
  2102. args: Record<string, unknown>,
  2103. sessionState: ExploreSessionState | undefined,
  2104. ): Record<string, unknown> {
  2105. if (!(EXPLORE_SESSION_VIEW_ARG in args) && (!sessionState || toolName !== 'codegraph_explore')) {
  2106. return args;
  2107. }
  2108. const copy = { ...args };
  2109. delete copy[EXPLORE_SESSION_VIEW_ARG];
  2110. if (sessionState && toolName === 'codegraph_explore') {
  2111. copy[EXPLORE_SESSION_VIEW_ARG] = sessionState.view();
  2112. }
  2113. return copy;
  2114. }
  2115. /**
  2116. * Record an explore call's emission into the caller's session state and strip
  2117. * it from the result (CG-17).
  2118. *
  2119. * Unconditional strip: the property is internal, so it comes off even when
  2120. * there is no session state to record it into (the CLI path) — that is what
  2121. * keeps the agent-facing response byte-identical. Recording is wrapped
  2122. * because a bookkeeping bug must never fail a tool call that already
  2123. * succeeded.
  2124. */
  2125. private takeExploreEmission(
  2126. result: ToolResult,
  2127. sessionState: ExploreSessionState | undefined,
  2128. ): ToolResult {
  2129. const emission = result?.[EXPLORE_EMISSION_KEY];
  2130. if (emission === undefined) return result;
  2131. delete result[EXPLORE_EMISSION_KEY];
  2132. if (sessionState) {
  2133. try {
  2134. sessionState.record(emission);
  2135. } catch { /* bookkeeping only — never fail a served call */ }
  2136. }
  2137. return result;
  2138. }
  2139. /**
  2140. * Run a single read tool to completion and return its raw {@link ToolResult},
  2141. * classifying expected failures the same way {@link execute}'s catch does so
  2142. * the SHAPE is identical whether dispatch runs in-process or on a worker:
  2143. * NotIndexed → success-shaped guidance, PathRefusal → clean error, anything
  2144. * else → internal-error-with-retry. Never throws.
  2145. *
  2146. * This is the worker thread's entry point (see {@link ./query-worker}) and the
  2147. * in-process fallback for {@link execute}. It deliberately does NOT run the
  2148. * catch-up gate or the staleness/worktree notices — those need the daemon's
  2149. * watched main instance and stay on the main thread. Cross-cutting allowlist +
  2150. * path validation already ran in {@link execute} before routing here.
  2151. */
  2152. async executeReadTool(toolName: string, args: Record<string, unknown>): Promise<ToolResult> {
  2153. try {
  2154. return await this.dispatchTool(toolName, args);
  2155. } catch (err) {
  2156. if (err instanceof NotIndexedError) {
  2157. return this.textResult(err.message);
  2158. }
  2159. if (err instanceof PathRefusalError) {
  2160. return this.errorResult(err.message);
  2161. }
  2162. return this.errorResult(
  2163. `Tool execution failed: ${err instanceof Error ? err.message : String(err)}. ` +
  2164. 'This is an internal codegraph error — retry the call once; if it persists, ' +
  2165. 'continue without codegraph for this task.'
  2166. );
  2167. }
  2168. }
  2169. /**
  2170. * Pure dispatch over the read tools — the switch, with no gate, no notices, no
  2171. * allowlist/validation (the caller owns those). `codegraph_status` is handled
  2172. * on the main thread in {@link execute} and never reaches here. May throw
  2173. * NotIndexed/PathRefusal, which {@link executeReadTool} classifies.
  2174. */
  2175. private async dispatchTool(toolName: string, args: Record<string, unknown>): Promise<ToolResult> {
  2176. switch (toolName) {
  2177. case 'codegraph_search': return await this.handleSearch(args);
  2178. case 'codegraph_callers': return await this.handleCallers(args);
  2179. case 'codegraph_callees': return await this.handleCallees(args);
  2180. case 'codegraph_impact': return await this.handleImpact(args);
  2181. case 'codegraph_explore': return await this.handleExplore(args);
  2182. case 'codegraph_node': return await this.handleNode(args);
  2183. case 'codegraph_files': return await this.handleFiles(args);
  2184. default: return this.errorResult(`Unknown tool: ${toolName}`);
  2185. }
  2186. }
  2187. /**
  2188. * Handle codegraph_search
  2189. */
  2190. private async handleSearch(args: Record<string, unknown>): Promise<ToolResult> {
  2191. const query = this.validateString(args.query, 'query');
  2192. if (typeof query !== 'string') return query;
  2193. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2194. const rawKind = args.kind as string | undefined;
  2195. // The schema enum says 'type' (what agents naturally reach for); the
  2196. // NodeKind is 'type_alias'. Without the mapping, kind: "type" silently
  2197. // matched nothing — a filter value we advertise must work.
  2198. const kind = rawKind === 'type' ? 'type_alias' : rawKind;
  2199. const rawLimit = Number(args.limit) || 10;
  2200. const limit = clamp(rawLimit, 1, 100);
  2201. const results = cg.searchNodes(query, {
  2202. limit,
  2203. kinds: kind ? [kind as NodeKind] : undefined,
  2204. });
  2205. if (results.length === 0) {
  2206. return this.textResult(`No results found for "${query}"`);
  2207. }
  2208. // Down-rank generated files within the FTS-returned set so a search
  2209. // for "Send" surfaces the hand-written keeper before .pb.go stubs
  2210. // that share the name. Stable: only reorders generated vs. not.
  2211. const isGen = cg.generatedFilePredicate(results.map((r) => r.node.filePath));
  2212. const ranked = [...results].sort((a, b) => {
  2213. const aGen = isGen(a.node.filePath) ? 1 : 0;
  2214. const bGen = isGen(b.node.filePath) ? 1 : 0;
  2215. return aGen - bGen;
  2216. });
  2217. const formatted = this.formatSearchResults(ranked);
  2218. return this.textResult(this.truncateOutput(formatted));
  2219. }
  2220. /**
  2221. * Group symbol matches into DISTINCT DEFINITIONS — one group per
  2222. * (filePath, qualifiedName), so same-file overloads stay together while
  2223. * unrelated same-named classes across a monorepo's apps (#764: one
  2224. * `UserService` per NestJS app) are kept apart. Optionally narrowed by a
  2225. * `file` path/suffix first.
  2226. */
  2227. private groupDefinitions(
  2228. nodes: Node[],
  2229. fileFilter: string | undefined
  2230. ): { groups: Node[][]; filteredOut: boolean } {
  2231. let pool = nodes;
  2232. let filteredOut = false;
  2233. if (fileFilter) {
  2234. const wanted = fileFilter.replace(/^\.\//, '');
  2235. const narrowed = pool.filter(
  2236. (n) => n.filePath === wanted || n.filePath.endsWith(wanted) || n.filePath.endsWith(`/${wanted}`)
  2237. );
  2238. if (narrowed.length > 0) {
  2239. pool = narrowed;
  2240. } else {
  2241. filteredOut = true;
  2242. }
  2243. }
  2244. const byDef = new Map<string, Node[]>();
  2245. for (const n of pool) {
  2246. const key = `${n.filePath}|${n.qualifiedName}`;
  2247. const group = byDef.get(key);
  2248. if (group) group.push(n);
  2249. else byDef.set(key, [n]);
  2250. }
  2251. return { groups: [...byDef.values()], filteredOut };
  2252. }
  2253. /** Section heading for one distinct definition in grouped output. */
  2254. private definitionHeading(group: Node[]): string {
  2255. const head = group[0]!;
  2256. const line = head.startLine ? `:${head.startLine}` : '';
  2257. return `**${head.qualifiedName}** (${head.kind}) — ${head.filePath}${line}`;
  2258. }
  2259. /**
  2260. * Handle codegraph_callers
  2261. */
  2262. private async handleCallers(args: Record<string, unknown>): Promise<ToolResult> {
  2263. const symbol = this.validateString(args.symbol, 'symbol');
  2264. if (typeof symbol !== 'string') return symbol;
  2265. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2266. const limit = clamp((args.limit as number) || 20, 1, 100);
  2267. const fileFilter = typeof args.file === 'string' ? args.file : undefined;
  2268. const allMatches = this.findAllSymbols(cg, symbol);
  2269. if (allMatches.nodes.length === 0) {
  2270. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  2271. }
  2272. const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
  2273. const filterNote = filteredOut
  2274. ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
  2275. : '';
  2276. const collect = (defNodes: Node[]) => {
  2277. const seen = new Set<string>();
  2278. const callers: Node[] = [];
  2279. const labels = new Map<string, string>();
  2280. for (const node of defNodes) {
  2281. for (const c of cg.getCallers(node.id)) {
  2282. if (!seen.has(c.node.id)) {
  2283. seen.add(c.node.id);
  2284. callers.push(c.node);
  2285. const label = this.edgeLabel(c.edge);
  2286. if (label) labels.set(c.node.id, label);
  2287. }
  2288. }
  2289. }
  2290. return { callers, labels };
  2291. };
  2292. // Single definition (or same-file overloads): the familiar flat list.
  2293. if (groups.length === 1) {
  2294. const { callers, labels } = collect(groups[0]!);
  2295. if (callers.length === 0) {
  2296. return this.textResult(`No callers found for "${symbol}"${allMatches.note}${filterNote}`);
  2297. }
  2298. // A successful `file` narrowing makes the multi-symbol aggregation note
  2299. // stale — suppress it.
  2300. const note = fileFilter && !filteredOut ? '' : allMatches.note;
  2301. const formatted = this.formatNodeList(callers.slice(0, limit), `Callers of ${symbol}`, labels) + note + filterNote;
  2302. return this.textResult(this.truncateOutput(formatted));
  2303. }
  2304. // Multiple DISTINCT definitions (#764): one section per definition so an
  2305. // agent never mistakes one app's callers for another's. Narrow with
  2306. // `file` to focus a single definition.
  2307. const lines: string[] = [
  2308. `**Callers of ${symbol} — ${groups.length} distinct definitions (narrow with \`file\`)**`,
  2309. ];
  2310. for (const group of groups) {
  2311. const { callers, labels } = collect(group);
  2312. lines.push('', this.definitionHeading(group));
  2313. if (callers.length === 0) {
  2314. lines.push('- (no callers)');
  2315. continue;
  2316. }
  2317. for (const node of callers.slice(0, limit)) {
  2318. const location = node.startLine ? `:${node.startLine}` : '';
  2319. const label = labels.get(node.id);
  2320. lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
  2321. }
  2322. }
  2323. return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
  2324. }
  2325. /**
  2326. * Handle codegraph_callees
  2327. */
  2328. private async handleCallees(args: Record<string, unknown>): Promise<ToolResult> {
  2329. const symbol = this.validateString(args.symbol, 'symbol');
  2330. if (typeof symbol !== 'string') return symbol;
  2331. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2332. const limit = clamp((args.limit as number) || 20, 1, 100);
  2333. const fileFilter = typeof args.file === 'string' ? args.file : undefined;
  2334. const allMatches = this.findAllSymbols(cg, symbol);
  2335. if (allMatches.nodes.length === 0) {
  2336. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  2337. }
  2338. const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
  2339. const filterNote = filteredOut
  2340. ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
  2341. : '';
  2342. const collect = (defNodes: Node[]) => {
  2343. const seen = new Set<string>();
  2344. const callees: Node[] = [];
  2345. const labels = new Map<string, string>();
  2346. for (const node of defNodes) {
  2347. for (const c of cg.getCallees(node.id)) {
  2348. if (!seen.has(c.node.id)) {
  2349. seen.add(c.node.id);
  2350. callees.push(c.node);
  2351. const label = this.edgeLabel(c.edge);
  2352. if (label) labels.set(c.node.id, label);
  2353. }
  2354. }
  2355. }
  2356. return { callees, labels };
  2357. };
  2358. if (groups.length === 1) {
  2359. const { callees, labels } = collect(groups[0]!);
  2360. if (callees.length === 0) {
  2361. return this.textResult(`No callees found for "${symbol}"${allMatches.note}${filterNote}`);
  2362. }
  2363. // A successful `file` narrowing makes the multi-symbol aggregation note
  2364. // stale — suppress it.
  2365. const note = fileFilter && !filteredOut ? '' : allMatches.note;
  2366. const formatted = this.formatNodeList(callees.slice(0, limit), `Callees of ${symbol}`, labels) + note + filterNote;
  2367. return this.textResult(this.truncateOutput(formatted));
  2368. }
  2369. // Multiple DISTINCT definitions (#764): per-definition sections.
  2370. const lines: string[] = [
  2371. `**Callees of ${symbol} — ${groups.length} distinct definitions (narrow with \`file\`)**`,
  2372. ];
  2373. for (const group of groups) {
  2374. const { callees, labels } = collect(group);
  2375. lines.push('', this.definitionHeading(group));
  2376. if (callees.length === 0) {
  2377. lines.push('- (no callees)');
  2378. continue;
  2379. }
  2380. for (const node of callees.slice(0, limit)) {
  2381. const location = node.startLine ? `:${node.startLine}` : '';
  2382. const label = labels.get(node.id);
  2383. lines.push(`- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`);
  2384. }
  2385. }
  2386. return this.textResult(this.truncateOutput(lines.join('\n') + filterNote));
  2387. }
  2388. /**
  2389. * Handle codegraph_impact
  2390. */
  2391. private async handleImpact(args: Record<string, unknown>): Promise<ToolResult> {
  2392. const symbol = this.validateString(args.symbol, 'symbol');
  2393. if (typeof symbol !== 'string') return symbol;
  2394. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  2395. const depth = clamp((args.depth as number) || 2, 1, 10);
  2396. const fileFilter = typeof args.file === 'string' ? args.file : undefined;
  2397. const allMatches = this.findAllSymbols(cg, symbol);
  2398. if (allMatches.nodes.length === 0) {
  2399. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  2400. }
  2401. const { groups, filteredOut } = this.groupDefinitions(allMatches.nodes, fileFilter);
  2402. const filterNote = filteredOut
  2403. ? `\n\n> **Note:** no definition of "${symbol}" matches file "${fileFilter}" — showing all definitions instead.`
  2404. : '';
  2405. const impactOf = (defNodes: Node[]) => {
  2406. const mergedNodes = new Map<string, Node>();
  2407. const mergedEdges: Edge[] = [];
  2408. const seenEdges = new Set<string>();
  2409. for (const node of defNodes) {
  2410. const impact = cg.getImpactRadius(node.id, depth);
  2411. for (const [id, n] of impact.nodes) {
  2412. mergedNodes.set(id, n);
  2413. }
  2414. for (const e of impact.edges) {
  2415. const key = `${e.source}->${e.target}:${e.kind}`;
  2416. if (!seenEdges.has(key)) {
  2417. seenEdges.add(key);
  2418. mergedEdges.push(e);
  2419. }
  2420. }
  2421. }
  2422. return { nodes: mergedNodes, edges: mergedEdges, roots: defNodes.map((n) => n.id) };
  2423. };
  2424. // Single definition (or same-file overloads): the familiar merged report.
  2425. if (groups.length === 1) {
  2426. const formatted = this.formatImpact(symbol, impactOf(groups[0]!)) + (fileFilter && !filteredOut ? "" : allMatches.note) + filterNote;
  2427. return this.textResult(this.truncateOutput(formatted));
  2428. }
  2429. // Multiple DISTINCT definitions (#764): a blast radius PER definition —
  2430. // merging unrelated same-named classes (one UserService per monorepo app)
  2431. // overstated impact and confused agents. Narrow with `file`.
  2432. const sections: string[] = [
  2433. `**Impact of ${symbol} — ${groups.length} distinct definitions (each with its own blast radius; narrow with \`file\`)**`,
  2434. ];
  2435. for (const group of groups) {
  2436. const head = group[0]!;
  2437. const line = head.startLine ? `:${head.startLine}` : '';
  2438. sections.push(
  2439. '',
  2440. this.formatImpact(`${head.qualifiedName} (${head.filePath}${line})`, impactOf(group))
  2441. );
  2442. }
  2443. return this.textResult(this.truncateOutput(sections.join('\n') + filterNote));
  2444. }
  2445. /**
  2446. * Describe a synthesized (dynamic-dispatch) edge for human output: how the
  2447. * callback was wired up — the bridge static parsing can't see. Returns null
  2448. * for ordinary static edges. Used by trace + the node trail so a synthesized
  2449. * hop reads as "registered via onUpdate at App.tsx:3148", not a bare arrow.
  2450. */
  2451. /**
  2452. * The branch conditions a flow hop's call site runs under, read from the
  2453. * caller's source now (`graph/branch-guards.ts`); '' when unconditional,
  2454. * unreadable, or the grammar for that language is not loaded.
  2455. */
  2456. private whenLabel(cg: CodeGraph, caller: Node, edge: Edge): string {
  2457. if (!edge.line || !supportsBranchGuards(caller.language)) return '';
  2458. try {
  2459. const rec = cg.getFile(caller.filePath);
  2460. if (!rec) return '';
  2461. const abs = validatePathWithinRoot(cg.getProjectRoot(), caller.filePath);
  2462. if (!abs) return '';
  2463. const st = statSync(abs);
  2464. // Drifted since the index: the recorded line may point elsewhere.
  2465. if (st.size !== rec.size || Math.floor(st.mtimeMs) !== Math.floor(rec.modifiedAt)) return '';
  2466. const site = { line: edge.line, column: typeof edge.column === 'number' ? edge.column : null };
  2467. const g = guardsForFileSync(abs, caller.language, [site]).get(siteKey(site));
  2468. return g ? guardLabel(g) : '';
  2469. } catch {
  2470. return '';
  2471. }
  2472. }
  2473. private synthEdgeNote(edge: Edge | null): { label: string; compact: string; registeredAt?: string } | null {
  2474. if (!edge || edge.provenance !== 'heuristic') return null;
  2475. const m = edge.metadata as Record<string, unknown> | undefined;
  2476. const registeredAt = typeof m?.registeredAt === 'string' ? m.registeredAt : undefined;
  2477. const at = registeredAt ? ` @${registeredAt}` : '';
  2478. if (m?.synthesizedBy === 'callback') {
  2479. const via = m.via ? `\`${String(m.via)}\`` : 'a registrar';
  2480. const field = m.field ? ` on .${String(m.field)}` : '';
  2481. return {
  2482. label: `callback — registered via ${via}${field} (dynamic dispatch)`,
  2483. compact: `dynamic: callback via ${via}${at}`,
  2484. registeredAt,
  2485. };
  2486. }
  2487. if (m?.synthesizedBy === 'http-client') {
  2488. const req = `${String(m.method ?? 'GET')} ${String(m.href ?? '')}`.trim();
  2489. return {
  2490. label: `HTTP request \`${req}\` — the client's call onto its own route (cross-tier)`,
  2491. compact: `dynamic: HTTP ${req}${at}`,
  2492. registeredAt,
  2493. };
  2494. }
  2495. if (m?.synthesizedBy === 'queue-job') {
  2496. const job = m.event ? `\`${String(m.event)}\`` : 'a job';
  2497. const queue = m.queue ? ` on queue \`${String(m.queue)}\`` : '';
  2498. return {
  2499. label: `queue job ${job}${queue} — producer → consumer (cross-tier)`,
  2500. compact: `dynamic: queue job ${job}${at}`,
  2501. registeredAt,
  2502. };
  2503. }
  2504. if (m?.synthesizedBy === 'event-bus') {
  2505. const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
  2506. const what = m.channel === 'socket' ? 'socket message' : 'bus event';
  2507. const dir = m.tier === 'client→server' ? ', client → server' : m.tier === 'server→client' ? ', server → client' : '';
  2508. return {
  2509. label: `${what} ${ev} — emit → handler${dir} (dynamic dispatch)`,
  2510. compact: `dynamic: ${what} ${ev}${at}`,
  2511. registeredAt,
  2512. };
  2513. }
  2514. if (m?.synthesizedBy === 'event-emitter') {
  2515. const ev = m.event ? `\`${String(m.event)}\`` : 'an event';
  2516. return {
  2517. label: `event ${ev} — emit → handler (dynamic dispatch)`,
  2518. compact: `dynamic: event ${ev}${at}`,
  2519. registeredAt,
  2520. };
  2521. }
  2522. if (m?.synthesizedBy === 'react-render') {
  2523. return {
  2524. label: `React re-render — \`setState\` re-runs render() (dynamic dispatch)`,
  2525. compact: `dynamic: React re-render via setState${at}`,
  2526. registeredAt,
  2527. };
  2528. }
  2529. if (m?.synthesizedBy === 'jsx-render') {
  2530. const child = m.via ? `<${String(m.via)}>` : 'a child component';
  2531. return {
  2532. label: `renders ${child} (JSX child — dynamic dispatch)`,
  2533. compact: `dynamic: renders ${child}`,
  2534. registeredAt,
  2535. };
  2536. }
  2537. if (m?.synthesizedBy === 'vue-handler') {
  2538. const ev = m.event ? `@${String(m.event)}` : 'a template event';
  2539. return {
  2540. label: `Vue template handler — bound to ${ev} (dynamic dispatch)`,
  2541. compact: `dynamic: Vue ${ev} handler`,
  2542. registeredAt,
  2543. };
  2544. }
  2545. if (m?.synthesizedBy === 'interface-impl') {
  2546. return {
  2547. label: `interface/abstract dispatch — runs the implementation override (dynamic dispatch)`,
  2548. compact: `dynamic: interface → impl${at}`,
  2549. registeredAt,
  2550. };
  2551. }
  2552. if (m?.synthesizedBy === 'closure-collection') {
  2553. const field = m.field ? `\`${String(m.field)}\`` : 'a collection';
  2554. return {
  2555. label: `closure collection — runs handlers appended to ${field} (dynamic dispatch)`,
  2556. compact: `dynamic: runs ${field} handlers${at}`,
  2557. registeredAt,
  2558. };
  2559. }
  2560. if (m?.synthesizedBy === 'fn-pointer-dispatch') {
  2561. const via = m.via ? `\`${String(m.via)}\`` : 'a function pointer';
  2562. return {
  2563. label: `function-pointer dispatch via ${via} (dynamic dispatch)`,
  2564. compact: `dynamic: fn-pointer ${m.via ? String(m.via) : ''}${at}`,
  2565. registeredAt,
  2566. };
  2567. }
  2568. if (m?.synthesizedBy === 'goframe-route') {
  2569. const route = m.route ? `\`${String(m.route)}\`` : 'a route';
  2570. return {
  2571. label: `GoFrame route ${route} — reflective Bind → controller method (dynamic dispatch)`,
  2572. compact: `dynamic: GoFrame route ${m.route ? String(m.route) : ''}${at}`,
  2573. registeredAt,
  2574. };
  2575. }
  2576. // Generic fallback for any other synthesizer (redux-thunk, gin-middleware-chain,
  2577. // flutter-build, …): a synthesized hop must never read as a bare static `calls`.
  2578. // It's a dynamic-dispatch bridge — label it as one and keep its wiring site.
  2579. if (typeof m?.synthesizedBy === 'string') {
  2580. const kind = m.synthesizedBy.replace(/-/g, ' ');
  2581. return { label: `${kind} (dynamic dispatch)`, compact: `dynamic: ${kind}${at}`, registeredAt };
  2582. }
  2583. return null;
  2584. }
  2585. /**
  2586. * Flow-from-named-symbols: an agent's codegraph_explore query is a bag of
  2587. * symbol names that usually spans the flow it's investigating (e.g.
  2588. * "PmsProductController getList PmsProductService list PmsProductServiceImpl").
  2589. * Surface the longest call chain AMONG those named symbols — scoped to what the
  2590. * agent explicitly named, so (unlike a fuzzy relevance set) there's no
  2591. * wrong-feature wandering. Rides synthesized edges, so controller→service-
  2592. * interface→impl shows up. Returns '' if no chain of >=3 nodes exists.
  2593. *
  2594. * Ambiguous tokens (Java `list` → dozens of nodes) are disambiguated by
  2595. * CO-NAMING: the agent names the class too, so we keep only `list` candidates
  2596. * whose qualifiedName contains another named token (`PmsProductServiceImpl::list`),
  2597. * dropping unrelated `OmsOrderService::list`.
  2598. */
  2599. private buildFlowFromNamedSymbols(cg: CodeGraph, query: string): { text: string; pathNodeIds: Set<string>; namedNodeIds: Set<string>; uniqueNamedNodeIds: Set<string>; spineCallSites: Map<string, number> } {
  2600. // spineCallSites: for each spine node, the line where it CALLS the next hop —
  2601. // lets the source assembler window an oversize spine method (e.g. n8n's 962-line
  2602. // processRunExecutionData) to the call site instead of dumping the whole body.
  2603. const EMPTY = { text: '', pathNodeIds: new Set<string>(), namedNodeIds: new Set<string>(), uniqueNamedNodeIds: new Set<string>(), spineCallSites: new Map<string, number>() };
  2604. try {
  2605. // Token resolution — parsing, overload disambiguation, the CONSTANT/
  2606. // VARIABLE synth endpoints — is shared with `/api/flow`, so a name written
  2607. // in the viewer's search box resolves to the same nodes it does here.
  2608. const flow = resolveNamedSymbolFlow(cg, query);
  2609. const { named, dynNamed, tokenNodes, tokenFamily, uniqueNamedNodeIds, preciseNamedIds } =
  2610. flow;
  2611. if (flow.tokens.length < 2) return EMPTY;
  2612. // Surface synthesized (heuristic) edges incident to a named symbol — INCLUDING
  2613. // the non-callable CONSTANT endpoints in `dynNamed`. `skipInChain` drops a hop
  2614. // already shown in the rendered main chain (a 2-node chain renders nothing, so a
  2615. // direct named→named synth hop still surfaces — #687).
  2616. const collectSynthLinks = (skipInChain: ((e: Edge) => boolean) | null): string[] => {
  2617. const synthLines: string[] = [];
  2618. const synthSeen = new Set<string>();
  2619. for (const n of [...named.values(), ...dynNamed.values()]) {
  2620. if (synthLines.length >= 6) break;
  2621. for (const { node: other, edge } of [...cg.getCallers(n.id), ...cg.getCallees(n.id)]) {
  2622. if (synthLines.length >= 6) break;
  2623. if (edge.provenance !== 'heuristic' || other.id === n.id) continue;
  2624. if (skipInChain && skipInChain(edge)) continue;
  2625. const src = edge.source === n.id ? n : other;
  2626. const tgt = edge.source === n.id ? other : n;
  2627. const key = `${src.name}>${tgt.name}`;
  2628. if (synthSeen.has(key)) continue;
  2629. synthSeen.add(key);
  2630. const note = this.synthEdgeNote(edge);
  2631. synthLines.push(`- ${src.name} → ${tgt.name} [${note ? note.compact : edge.kind}]`);
  2632. }
  2633. }
  2634. return synthLines;
  2635. };
  2636. /**
  2637. * No narrative to print — but the agent still NAMED symbols, and their
  2638. * identity is a separate output from the prose (CG-38).
  2639. *
  2640. * `namedNodeIds` is not decoration: downstream it injects the named def into
  2641. * the file's cluster ranges and ranks it importance 9, which is the whole
  2642. * mechanism behind "a symbol the agent named renders" (the assembler's
  2643. * named-def injection). Returning EMPTY here threw that away whenever the
  2644. * named symbols happened not to form a call chain — two sibling closures in
  2645. * one factory (`queueMessage` / `flushQueuedMessages`, neither calling the
  2646. * other) produce no chain, no synth hop and no dispatch boundary, so BOTH
  2647. * defs lost importance 9 and the file rendered from its head instead: the
  2648. * agent got the `QueuedMessage` interface at L70 and had to Read the file
  2649. * for the functions at L1087/L1102 it had asked for by name.
  2650. *
  2651. * Restricted to SHAPE-PRECISE tokens. With a narrative present the prose is
  2652. * itself corroboration that the resolution was right, so that path keeps
  2653. * every named id as before; with nothing corroborating it, only an
  2654. * unambiguous symbol reference may promote — an English word in a prose
  2655. * question that happens to exact-match a callable must not earn importance 9.
  2656. * Same distinction, same test, as the gather path's `isPreciseToken`.
  2657. */
  2658. const identityOnly = () => (preciseNamedIds.size === 0 ? EMPTY : {
  2659. text: '',
  2660. pathNodeIds: new Set<string>(),
  2661. namedNodeIds: new Set<string>(preciseNamedIds),
  2662. uniqueNamedNodeIds: new Set<string>([...uniqueNamedNodeIds].filter((id) => preciseNamedIds.has(id))),
  2663. spineCallSites: new Map<string, number>(),
  2664. });
  2665. if (named.size < 2) {
  2666. // <2 CALLABLES resolved. Two recoveries before giving up: (1) synthesized
  2667. // edges among named CONSTANT/VARIABLE endpoints — RTK thunk→thunk is
  2668. // constant→constant, so `named` can be empty while `dynNamed` holds the
  2669. // whole chain; (2) the one resolved callable's body may hold the
  2670. // dynamic-dispatch site that EXPLAINS a half-connected flow.
  2671. const synthLines = collectSynthLinks(null);
  2672. const boundaries = named.size === 0 ? '' : (this.buildDynamicBoundaries(cg, [...named.values()], named) || '');
  2673. if (synthLines.length === 0 && !boundaries) return identityOnly();
  2674. const out: string[] = [];
  2675. if (synthLines.length) out.push(
  2676. '**Dynamic-dispatch links among your symbols**',
  2677. '(synthesized — the indirect hops grep/Read would reconstruct; the `@file:line` is the wiring site)',
  2678. '', ...synthLines, '');
  2679. if (boundaries) out.push(boundaries);
  2680. out.push('> Full source for these symbols is below.\n');
  2681. return { text: out.join('\n'), pathNodeIds: new Set(), namedNodeIds: new Set<string>([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites: new Map<string, number>() };
  2682. }
  2683. // The search itself lives in `../graph/named-symbol-flow`, so the viewer's
  2684. // Flow strip rides exactly this path finder rather than a second one that
  2685. // could disagree with it. What stays here is the PROSE — the narrative,
  2686. // the dynamic-dispatch links, the boundary announcements.
  2687. const best = flow.chains[0]?.steps ?? null;
  2688. const hasMain = !!best && best.length >= 3;
  2689. const pathIds = new Set((best ?? []).map((s) => s.node.id));
  2690. // Where each spine node calls the NEXT hop — lets the assembler window an
  2691. // oversize spine method to the call instead of dumping the whole body.
  2692. const spineCallSites = flow.chains[0]?.callSites ?? new Map<string, number>();
  2693. // Dynamic-boundary scan (#687) — fires ONLY when the flow the agent
  2694. // asked about did not fully connect: some token resolved to nodes but
  2695. // none of them sit on the main chain (or there is no chain at all). A
  2696. // healthy flow skips this entirely. Scan order: the chain's dead end
  2697. // first (where the partial flow stops), then the disconnected symbols,
  2698. // agent-specific (unique-named) ones first.
  2699. let boundaryText = '';
  2700. {
  2701. const uncovered: Node[] = [];
  2702. if (!hasMain) {
  2703. // No rendered chain — but a 2-node chain still CONNECTS its two
  2704. // endpoints (e.g. via one synthesized hop, surfaced below as a
  2705. // dynamic-dispatch link). Only nodes off that short chain are
  2706. // unexplained breaks worth scanning.
  2707. for (const n of named.values()) if (!pathIds.has(n.id)) uncovered.push(n);
  2708. } else {
  2709. for (const ids of tokenNodes.values()) {
  2710. if (ids.length === 0 || ids.some((id) => pathIds.has(id))) continue;
  2711. for (const id of ids) { const n = named.get(id); if (n) uncovered.push(n); }
  2712. }
  2713. }
  2714. if (uncovered.length > 0) {
  2715. const scanList: Node[] = [];
  2716. if (hasMain) scanList.push(best![best!.length - 1]!.node);
  2717. scanList.push(...uncovered.sort((a, b) =>
  2718. (uniqueNamedNodeIds.has(b.id) ? 1 : 0) - (uniqueNamedNodeIds.has(a.id) ? 1 : 0)));
  2719. boundaryText = this.buildDynamicBoundaries(cg, scanList, named);
  2720. }
  2721. }
  2722. // Interface/registry-dispatch announcement (extends #687 to GRAPH-visible
  2723. // polymorphism). A method the agent NAMED that resolves to a large same-name
  2724. // family AND did not land on the main chain is almost always a runtime
  2725. // dispatch (plugin/strategy/handler interface): the concrete target is chosen
  2726. // at runtime from N implementations, so no single static edge is the answer.
  2727. // The body-scan above can't see this — `nodeType.execute()` is textually an
  2728. // ordinary call; the polymorphism lives in the graph (implements edges), so
  2729. // detect it there. Fires ONLY for an uncovered named token; a connected flow
  2730. // stays silent.
  2731. let polyText = '';
  2732. {
  2733. const POLY_MIN_FAMILY = 8; // smaller families are overload sets, not dispatch
  2734. const polyCands: Array<{ token: string; family: Node[] }> = [];
  2735. for (const [t, fam] of tokenFamily) {
  2736. if (fam.length < POLY_MIN_FAMILY) continue;
  2737. const ids = tokenNodes.get(t) || [];
  2738. if (ids.some((id) => pathIds.has(id))) continue; // covered by the flow — silent
  2739. polyCands.push({ token: t, family: fam });
  2740. }
  2741. if (polyCands.length) polyText = this.buildPolymorphicBoundaries(cg, polyCands, named);
  2742. }
  2743. // Supplementary: dynamic-dispatch (synthesized) edges incident to a named
  2744. // symbol (incl. the non-callable CONSTANT endpoints in `dynNamed`) — the
  2745. // indirect hops an agent would otherwise grep/Read to reconstruct ("where do
  2746. // the appended `validators` actually run?"). Surfaced even when the OTHER end
  2747. // wasn't named. The skip drops a hop already in the rendered main chain; a
  2748. // 2-node chain renders nothing (hasMain false) so a direct named→named synth
  2749. // hop still surfaces — too short for Flow, but #687-visible here.
  2750. const synthLines = collectSynthLinks(
  2751. hasMain ? (e: Edge) => pathIds.has(e.source) && pathIds.has(e.target) : null
  2752. );
  2753. if (!hasMain && synthLines.length === 0 && !boundaryText && !polyText) return identityOnly();
  2754. const out: string[] = [];
  2755. if (hasMain) {
  2756. out.push('**Flow (call path among the symbols you queried)**', '');
  2757. for (let i = 0; i < best!.length; i++) {
  2758. const step = best![i]!;
  2759. if (step.edge) {
  2760. const sy = this.synthEdgeNote(step.edge);
  2761. const when = i > 0 ? this.whenLabel(cg, best![i - 1]!.node, step.edge) : '';
  2762. out.push(` ↓ ${sy ? sy.compact : step.edge.kind}${when ? ` (when ${when})` : ''}`);
  2763. }
  2764. out.push(`${i + 1}. ${step.node.name} (${step.node.filePath}:${step.node.startLine})`);
  2765. }
  2766. out.push('');
  2767. }
  2768. if (synthLines.length) {
  2769. out.push(
  2770. '**Dynamic-dispatch links among your symbols**',
  2771. '(synthesized — the indirect hops grep/Read would reconstruct; the `@file:line` is the wiring site)',
  2772. '',
  2773. ...synthLines,
  2774. ''
  2775. );
  2776. }
  2777. if (boundaryText) out.push(boundaryText);
  2778. if (polyText) out.push(polyText);
  2779. out.push('> Full source for these symbols is below — the call flow among them, followed by their bodies.', '');
  2780. // namedNodeIds = every callable the agent explicitly named (a superset of
  2781. // the spine). A file holding one is something the agent asked to SEE, so it
  2782. // must keep full source even if it's an off-spine polymorphic sibling — the
  2783. // agent named `getResponseWithInterceptorChain` / `SQLCompiler.execute_sql`
  2784. // as the mechanism, not as an interchangeable leaf. See the skeleton gate.
  2785. return { text: out.join('\n'), pathNodeIds: pathIds, namedNodeIds: new Set<string>([...named.keys(), ...dynNamed.keys()]), uniqueNamedNodeIds, spineCallSites };
  2786. } catch {
  2787. return EMPTY;
  2788. }
  2789. }
  2790. /**
  2791. * Dynamic-boundary surfacing (#687): when the flow among the agent's named
  2792. * symbols does not fully connect, scan the disconnected symbols' bodies for
  2793. * dynamic-dispatch sites (computed member calls, getattr, reflection, typed
  2794. * message buses, runtime-keyed emits) and ANNOUNCE the boundary — the exact
  2795. * site, the form, and (when a key is statically visible) candidate targets —
  2796. * instead of guessing edges. The answer to "how does A reach B" when no
  2797. * static path exists IS the dispatch site: that's where the flow continues
  2798. * at runtime. Query-time, deterministic, zero graph mutation; a fully
  2799. * connected flow never reaches this method.
  2800. */
  2801. private buildDynamicBoundaries(cg: CodeGraph, scanList: Node[], named: Map<string, Node>): string {
  2802. const MAX_NOTES = 4; // boundary bullets per explore
  2803. // The verdict is not derived here — `findDynamicBoundaries` produces it and
  2804. // the viewer's end cap renders the same object, so the two can never
  2805. // disagree about where a flow stops. What is left here is the prose.
  2806. const reports = findDynamicBoundaries(cg, scanList, { named, maxSites: MAX_NOTES });
  2807. const notes: string[] = [];
  2808. for (const report of reports) {
  2809. if (notes.length >= MAX_NOTES) break;
  2810. for (const site of report.sites) {
  2811. if (notes.length >= MAX_NOTES) break;
  2812. const more = site.moreSites
  2813. ? ` (+${site.moreSites} more such site${site.moreSites > 1 ? 's' : ''} in this body)`
  2814. : '';
  2815. notes.push(`- \`${report.node.name}\` (${report.node.filePath}:${site.line}) — ${site.label}: \`${site.snippet}\`${more}`);
  2816. const cand = this.boundaryCandidates(site);
  2817. if (cand) notes.push(` ${cand}`);
  2818. }
  2819. }
  2820. if (notes.length === 0) return '';
  2821. return [
  2822. '**Dynamic boundaries (the static path ends at runtime dispatch)**',
  2823. '',
  2824. ...notes,
  2825. '',
  2826. '> 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.',
  2827. '',
  2828. ].join('\n');
  2829. }
  2830. /**
  2831. * Interface/registry-dispatch announcement — #687 extended to GRAPH-visible
  2832. * polymorphism (the body-scan can't see it: `nodeType.execute()` is textually
  2833. * an ordinary call; the polymorphism lives in the `implements`/`extends` edges).
  2834. *
  2835. * A method the agent named that resolves to a large same-name family whose
  2836. * definers overwhelmingly implement/extend ONE supertype is a runtime dispatch:
  2837. * the concrete target is chosen at runtime from N implementations, so no single
  2838. * static edge is "the answer" — the implementations ARE the continuations. We
  2839. * announce the supertype, its TRUE implementer count, and a few concrete targets,
  2840. * then steer to codegraph_explore. Graph-only, query-time, zero mutation; the
  2841. * caller fires it ONLY for an UNCOVERED named token, so a connected flow is silent.
  2842. *
  2843. * Robust to FTS sampling bias: the same-name family is a capped FTS sample that
  2844. * over-represents whatever FTS ranks first (n8n: DB `TableOperation.execute`
  2845. * outnumbered `INodeType.execute` in the sample 7:6 even though INodeType has
  2846. * 611 implementers vs a handful). So candidate supertypes are ranked by their
  2847. * TRUE graph-wide implementer count, NOT their frequency in the sample.
  2848. */
  2849. private buildPolymorphicBoundaries(cg: CodeGraph, candidates: Array<{ token: string; family: Node[] }>, named: Map<string, Node>): string {
  2850. const CLASSY = new Set(['class', 'struct', 'interface', 'trait', 'protocol', 'abstract']);
  2851. const MIN_IMPL = 8; // a supertype needs >= this many implementers to count as "polymorphic"
  2852. const MIN_SUPPORT = 2; // >= this many sampled definers must share the supertype (ties it to the token)
  2853. const SAMPLE = 40; // family members inspected per token
  2854. const MAX_NOTES = 3;
  2855. const rel = (p: string) => p.replace(/\\/g, '/');
  2856. const containerOf = (m: Node): Node | null => {
  2857. try { const ce = cg.getIncomingEdges(m.id).find((e) => e.kind === 'contains'); return ce ? cg.getNode(ce.source) : null; }
  2858. catch { return null; }
  2859. };
  2860. const notes: string[] = [];
  2861. const seenSuper = new Set<string>();
  2862. for (const { token, family } of candidates) {
  2863. if (notes.length >= MAX_NOTES) break;
  2864. // supertype id → how many sampled definers share it + a few example definers
  2865. const supers = new Map<string, { node: Node; count: number; targets: Node[] }>();
  2866. for (const m of family.slice(0, SAMPLE)) {
  2867. const container = containerOf(m);
  2868. if (!container || !CLASSY.has(container.kind)) continue;
  2869. let sups: Node[] = [];
  2870. try {
  2871. sups = cg.getOutgoingEdges(container.id)
  2872. .filter((e) => e.kind === 'implements' || e.kind === 'extends')
  2873. .map((e) => { try { return cg.getNode(e.target); } catch { return null; } })
  2874. .filter((n): n is Node => !!n && CLASSY.has(n.kind) && (n.name?.length || 0) >= 3);
  2875. } catch { /* no supertypes — free function or unresolved */ }
  2876. for (const s of sups) {
  2877. const e = supers.get(s.id) || { node: s, count: 0, targets: [] };
  2878. e.count++;
  2879. if (e.targets.length < 6) e.targets.push(m);
  2880. supers.set(s.id, e);
  2881. }
  2882. }
  2883. // Pick the supertype with the most TRUE implementers (graph-wide), among
  2884. // those genuinely shared by the token's definers.
  2885. let best: { node: Node; impl: number; targets: Node[] } | null = null;
  2886. for (const { node, count, targets } of supers.values()) {
  2887. if (count < MIN_SUPPORT) continue;
  2888. // The implementer count is `countImplementers` — the same function the
  2889. // viewer's type-hierarchy fan counts with, so "dispatch to N types
  2890. // implementing X" is the same N on both surfaces (CG-58). Distinct
  2891. // types, not edges: a class tied to its supertype by both a parsed
  2892. // `extends` and a synthesized `implements` is one implementation.
  2893. const impl = countImplementers(cg, node.id);
  2894. if (impl < MIN_IMPL) continue;
  2895. if (!best || impl > best.impl) best = { node, impl, targets };
  2896. }
  2897. if (!best || seenSuper.has(best.node.id)) continue;
  2898. seenSuper.add(best.node.id);
  2899. const namedNames = new Set([...named.values()].map((n) => n.name));
  2900. const eg = best.targets.slice(0, 4).map((m) => {
  2901. const cont = containerOf(m);
  2902. const disp = cont ? `${cont.name}.${m.name}` : (m.qualifiedName || m.name);
  2903. const mark = cont && namedNames.has(cont.name) ? ' ← you named this' : '';
  2904. return `\`${disp}\` (${rel(m.filePath)}:${m.startLine})${mark}`;
  2905. });
  2906. const more = best.impl > eg.length ? ` +${best.impl - eg.length} more` : '';
  2907. notes.push(`- \`${token}\` → runtime dispatch to **${best.impl}** types implementing \`${best.node.name}\` — the static path ends here, the target is chosen at runtime. e.g. ${eg.join(', ')}${more}`);
  2908. }
  2909. if (notes.length === 0) return '';
  2910. return [
  2911. '**Interface dispatch (a named method has many implementations)**',
  2912. '',
  2913. ...notes,
  2914. '',
  2915. '> The method above is dispatched at runtime to one of the listed implementations (a registry / plugin / strategy interface) — there is no single static caller→callee edge; the implementations ARE the continuations. To follow one, run codegraph_explore on a listed target.',
  2916. '',
  2917. ].join('\n');
  2918. }
  2919. /**
  2920. * Render the candidate shortlist for a dispatch site as one line.
  2921. *
  2922. * The shortlist itself is `shortlistBoundaryCandidates` in
  2923. * `../graph/dynamic-boundary-report` — shared with the viewer's end cap, so
  2924. * "candidates for key `save`" names the same symbols in both places. Symbols
  2925. * the agent already named are marked: that is the "you were right, here's the
  2926. * wiring" case.
  2927. */
  2928. private boundaryCandidates(site: BoundarySite): string {
  2929. if (site.candidates.length === 0) return site.candidateNote ?? '';
  2930. const list = site.candidates.map((c) =>
  2931. `\`${c.display}\` (${c.node.filePath}:${c.node.startLine})${c.named ? ' ← you named this' : ''}`
  2932. );
  2933. return `candidates for key \`${site.key}\`: ${list.join(', ')}`;
  2934. }
  2935. /**
  2936. * Compact "blast radius" for the entry symbols of an explore result: who
  2937. * depends on each (callers) and which test files cover it — LOCATIONS ONLY,
  2938. * no source, so the agent knows what to update / re-verify before editing
  2939. * without reaching for a separate impact call. Always-on, but skips symbols
  2940. * that have no dependents (nothing to warn about), and returns '' when none
  2941. * qualify so a leaf-only exploration stays clean.
  2942. */
  2943. private buildBlastRadiusSection(cg: CodeGraph, subgraph: Subgraph): string {
  2944. const ROOT_CAP = 5; // only the symbols the query actually targeted
  2945. const FILE_CAP = 4; // caller files listed per symbol before "+N more"
  2946. const MEANINGFUL = new Set<string>([
  2947. 'function', 'method', 'class', 'interface', 'struct', 'union', 'trait', 'protocol',
  2948. 'enum', 'type_alias', 'component', 'constant', 'variable', 'property', 'field',
  2949. ]);
  2950. const rel = (p: string) => p.replace(/\\/g, '/');
  2951. const roots = subgraph.roots
  2952. .map((id) => subgraph.nodes.get(id))
  2953. .filter((n): n is Node => !!n && MEANINGFUL.has(n.kind))
  2954. .slice(0, ROOT_CAP);
  2955. if (roots.length === 0) return '';
  2956. const entries: string[] = [];
  2957. for (const root of roots) {
  2958. let callers: Array<{ node: Node }> = [];
  2959. try { callers = cg.getCallers(root.id) as Array<{ node: Node }>; } catch { /* skip this root */ }
  2960. const seen = new Set<string>();
  2961. const uniq: Node[] = [];
  2962. for (const c of callers) {
  2963. if (c?.node && !seen.has(c.node.id)) { seen.add(c.node.id); uniq.push(c.node); }
  2964. }
  2965. if (uniq.length === 0) continue; // no blast radius → nothing to flag
  2966. const callerFiles = [...new Set(uniq.map((n) => rel(n.filePath)))];
  2967. const testFiles = callerFiles.filter((f) => isTestFile(f));
  2968. const nonTest = callerFiles.filter((f) => !isTestFile(f));
  2969. const shown = nonTest.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ');
  2970. const more = nonTest.length > FILE_CAP ? ` +${nonTest.length - FILE_CAP} more` : '';
  2971. const where = nonTest.length > 0 ? ` in ${shown}${more}` : '';
  2972. const tests = testFiles.length > 0
  2973. ? `; tests: ${testFiles.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ')}${testFiles.length > FILE_CAP ? ` +${testFiles.length - FILE_CAP}` : ''}`
  2974. : this.indirectTestNote(cg, uniq, rel);
  2975. entries.push(
  2976. `- \`${root.name}\` (${rel(root.filePath)}:${root.startLine}) — ${uniq.length} caller${uniq.length === 1 ? '' : 's'}${where}${tests}`,
  2977. );
  2978. }
  2979. if (entries.length === 0) return '';
  2980. return [
  2981. '**Blast radius — what depends on these (update/verify before editing)**',
  2982. '',
  2983. ...entries,
  2984. '',
  2985. ].join('\n');
  2986. }
  2987. /**
  2988. * Test-coverage note for a blast-radius entry whose DIRECT callers include no
  2989. * test file. A helper called only by production code can still be exercised
  2990. * by tests further up the caller chain (#1475: 40% of directly-unflagged
  2991. * symbols had a test within 2-3 hops), so walk up to 2 more hops before
  2992. * claiming anything — and even then claim only what was measured.
  2993. */
  2994. private indirectTestNote(cg: CodeGraph, directCallers: Node[], rel: (p: string) => string): string {
  2995. const MAX_HOPS = 3; // direct callers are hop 1
  2996. const BUDGET = 64; // getCallers lookups per entry — bounds god-fan-in symbols
  2997. const FILE_CAP = 2;
  2998. let budget = BUDGET;
  2999. const visited = new Set(directCallers.map((n) => n.id));
  3000. let frontier = directCallers;
  3001. for (let hop = 2; hop <= MAX_HOPS && frontier.length > 0 && budget > 0; hop++) {
  3002. const next: Node[] = [];
  3003. const found = new Set<string>();
  3004. for (const node of frontier) {
  3005. if (budget-- <= 0) break;
  3006. let callers: Array<{ node: Node }> = [];
  3007. try { callers = cg.getCallers(node.id) as Array<{ node: Node }>; } catch { continue; }
  3008. for (const c of callers) {
  3009. const n = c?.node;
  3010. if (!n || visited.has(n.id)) continue;
  3011. visited.add(n.id);
  3012. const f = rel(n.filePath);
  3013. if (isTestFile(f)) found.add(f);
  3014. else next.push(n);
  3015. }
  3016. }
  3017. if (found.size > 0) {
  3018. const files = [...found];
  3019. const shown = files.slice(0, FILE_CAP).map((f) => `\`${f}\``).join(', ');
  3020. const more = files.length > FILE_CAP ? ` +${files.length - FILE_CAP}` : '';
  3021. return `; tested via callers: ${shown}${more}`;
  3022. }
  3023. frontier = next;
  3024. }
  3025. // Budget exhaustion means hops 2-3 weren't fully searched — fall back to
  3026. // the weaker claim that IS established by the direct-caller check.
  3027. return budget > 0
  3028. ? `; no tests found within ${MAX_HOPS} caller hops`
  3029. : '; no test calls this directly';
  3030. }
  3031. /**
  3032. * Graph-connectivity relevance via Random-Walk-with-Restart (personalized
  3033. * PageRank) from the query's matched SEED nodes over the call/reference graph.
  3034. *
  3035. * This is the ranking signal text search (FTS/bm25) CANNOT provide, and it's
  3036. * codegraph's home turf: relevance by STRUCTURE, not words. A file whose
  3037. * symbols are call-connected to the matched cluster accrues walk mass and
  3038. * ranks high; a lone TEXT match — e.g. `LensSwitcher.swift` matched the word
  3039. * "switch" from `switchOrganization`, but calls none of `setUser`/`fetchUser`
  3040. * — gets only its own restart probability and ranks ~0. Immune to the
  3041. * tokenization trap that fools term matching, deterministic, no embeddings.
  3042. *
  3043. * Undirected adjacency (reachability both ways), restart α=0.25 to the seeds,
  3044. * power iteration to convergence. Bounded to the already-relevant subgraph, so
  3045. * it's a few hundred nodes × ~25 iterations — negligible cost.
  3046. */
  3047. private computeGraphRelevance(
  3048. nodeIds: string[],
  3049. edges: Edge[],
  3050. seedIds: Set<string>,
  3051. ): Map<string, number> {
  3052. const out = new Map<string, number>();
  3053. const n = nodeIds.length;
  3054. if (n === 0) return out;
  3055. const idx = new Map<string, number>();
  3056. for (let i = 0; i < n; i++) idx.set(nodeIds[i]!, i);
  3057. const RANK_EDGES = new Set<string>([
  3058. 'calls', 'references', 'extends', 'implements', 'overrides',
  3059. 'instantiates', 'returns', 'type_of', 'imports', 'navigates',
  3060. ]);
  3061. const adj: number[][] = Array.from({ length: n }, () => []);
  3062. for (const e of edges) {
  3063. if (!RANK_EDGES.has(e.kind)) continue;
  3064. const i = idx.get(e.source);
  3065. const j = idx.get(e.target);
  3066. if (i === undefined || j === undefined || i === j) continue;
  3067. adj[i]!.push(j);
  3068. adj[j]!.push(i); // undirected — reachable either direction
  3069. }
  3070. // Restart vector: uniform over seeds present in the candidate set. (Falls
  3071. // back to uniform-over-all if no seed landed in the set, so we never return
  3072. // all-zero.)
  3073. const r = new Array<number>(n).fill(0);
  3074. let rsum = 0;
  3075. for (const id of seedIds) {
  3076. const i = idx.get(id);
  3077. if (i !== undefined) { r[i] = 1; rsum += 1; }
  3078. }
  3079. if (rsum === 0) { for (let i = 0; i < n; i++) r[i] = 1; rsum = n; }
  3080. for (let i = 0; i < n; i++) r[i]! /= rsum;
  3081. const alpha = 0.25;
  3082. let s = r.slice();
  3083. for (let iter = 0; iter < 25; iter++) {
  3084. const next = new Array<number>(n).fill(0);
  3085. for (let i = 0; i < n; i++) {
  3086. const si = s[i]!;
  3087. if (si === 0) continue;
  3088. const d = adj[i]!.length;
  3089. if (d === 0) { next[i]! += si; continue; } // dangling: keep its mass
  3090. const share = si / d;
  3091. for (const j of adj[i]!) next[j]! += share;
  3092. }
  3093. for (let i = 0; i < n; i++) s[i] = (1 - alpha) * next[i]! + alpha * r[i]!;
  3094. }
  3095. for (let i = 0; i < n; i++) out.set(nodeIds[i]!, s[i]!);
  3096. return out;
  3097. }
  3098. /**
  3099. * Handle codegraph_explore — deep exploration in a single call
  3100. *
  3101. * Strategy: find relevant symbols via graph traversal, group by file,
  3102. * then read contiguous file sections covering all symbols per file.
  3103. * This replaces multiple codegraph_node + Read calls.
  3104. *
  3105. * Output size is adaptive to project file count via
  3106. * `getExploreOutputBudget` — see #185 for why a fixed 35k cap was a
  3107. * tax on small projects while earning its keep on large ones.
  3108. */
  3109. private async handleExplore(args: Record<string, unknown>): Promise<ToolResult> {
  3110. const rawQuery = this.validateString(args.query, 'query');
  3111. if (typeof rawQuery !== 'string') return rawQuery;
  3112. // One normalization point so the flow-builder, relevance search, and
  3113. // ranking all see the same canonical spelling (Erlang `mod:fn/arity`).
  3114. const query = normalizeQuerySpelling(rawQuery);
  3115. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  3116. const projectRoot = cg.getProjectRoot();
  3117. // Resolve adaptive output budget from project size. Falls back to the
  3118. // largest-tier defaults if stats aren't available, which preserves
  3119. // pre-#185 behavior for callers that hit the rare stats failure.
  3120. let budget: ExploreOutputBudget;
  3121. let indexedFileCount = -1;
  3122. try {
  3123. indexedFileCount = cg.getStats().fileCount;
  3124. budget = getExploreOutputBudget(indexedFileCount);
  3125. } catch {
  3126. budget = getExploreOutputBudget(Infinity);
  3127. }
  3128. const maxFiles = clamp((args.maxFiles as number) || budget.defaultMaxFiles, 1, 20);
  3129. // File paths named in the query become PINNED files: guaranteed admission,
  3130. // top of the rank order, funded first — and their span is REMOVED from the
  3131. // matching query. Runs on the RAW query (normalizeQuerySpelling strips
  3132. // `/digits` tails, which would mangle numeric path segments). Without this,
  3133. // a SvelteKit path like `runs/[runId]/+page.svelte` was shredded by the
  3134. // seeding tokenizer (splits on brackets → `runId` seeded as a "named
  3135. // symbol") and by FTS (`page`/`runs` fragments admitted every sibling
  3136. // `+page.svelte`), starving the very files the agent asked for.
  3137. let pinnedFiles: string[] = [];
  3138. let unresolvedPathSpans: string[] = [];
  3139. let matchQuery = query;
  3140. if (queryMightContainPaths(rawQuery)) {
  3141. try {
  3142. const extraction = extractQueryPaths(
  3143. rawQuery,
  3144. cg.getFiles().map((f) => f.path),
  3145. { maxPins: maxFiles },
  3146. );
  3147. if (extraction.pinnedFiles.length > 0 || extraction.unresolvedPathSpans.length > 0) {
  3148. pinnedFiles = extraction.pinnedFiles;
  3149. unresolvedPathSpans = extraction.unresolvedPathSpans;
  3150. matchQuery = normalizeQuerySpelling(extraction.strippedQuery);
  3151. }
  3152. } catch { /* path pinning must never fail an explore call */ }
  3153. }
  3154. const pinnedSet = new Set(pinnedFiles);
  3155. const pinnedOrder = new Map(pinnedFiles.map((p, i) => [p, i]));
  3156. // Per-file allocation diagnostic (CG-4). `null` unless CODEGRAPH_EXPLORE_DEBUG
  3157. // is set — every `diag?.` below is then a no-op and the response is
  3158. // byte-identical. It only OBSERVES: it must never feed back into rendering.
  3159. const diag = ExploreDiagnostics.start(query, projectRoot, budget, maxFiles, indexedFileCount);
  3160. // What this session has already been served for THIS project (CG-17), and
  3161. // whether this call may act on it (CG-18). Dedup is off on the session's
  3162. // first call by construction — there is nothing to point back AT — and off
  3163. // entirely under `CODEGRAPH_EXPLORE_DEDUP=0`.
  3164. const priorCalls = viewForProject(readExploreSessionView(args), projectRoot);
  3165. diag?.noteSession(priorCalls);
  3166. const dedupEnabled = exploreDedupEnabled() && (priorCalls?.calls.length ?? 0) > 0;
  3167. // Cross-call dedup accounting (CG-18). `newSourceChars` is the load-bearing
  3168. // one: a response whose source is ENTIRELY back-references is the shape that
  3169. // reads as a failure, so the loop keeps the top suppressed file's real
  3170. // section in hand and restores it if nothing new made it in — see
  3171. // `suppressedFallback` below.
  3172. let newSourceChars = 0;
  3173. const backReferencedFiles: string[] = [];
  3174. // What this call ends up emitting, per file — the record handed back to the
  3175. // session state on the main thread. Filled by every render path below, then
  3176. // filtered to the files that SURVIVE the final hard-ceiling cut, so the
  3177. // record is what the agent actually received rather than what the loop
  3178. // hoped to send.
  3179. //
  3180. // Back-referenced spans are recorded too, with zero bytes (CG-18): the
  3181. // record means "source the agent HOLDS for this file", not "bytes this call
  3182. // spent". Re-recording them refreshes them inside the retained-call window,
  3183. // so a file pointed at across many calls doesn't age out of the history and
  3184. // get re-served for no reason.
  3185. const emittedByFile = new Map<
  3186. string,
  3187. { ranges: ExploreLineRange[]; bytes: number; fingerprint?: string }
  3188. >();
  3189. const noteEmitted = (
  3190. fp: string,
  3191. ranges: ExploreLineRange[],
  3192. bytes: number,
  3193. fingerprint?: string,
  3194. ): void => {
  3195. const existing = emittedByFile.get(fp);
  3196. if (existing) {
  3197. existing.ranges.push(...ranges);
  3198. existing.bytes += bytes;
  3199. if (fingerprint) existing.fingerprint = fingerprint;
  3200. } else {
  3201. emittedByFile.set(fp, { ranges: [...ranges], bytes, fingerprint });
  3202. }
  3203. };
  3204. // Step 1: Find relevant context with generous parameters.
  3205. // Use a large maxNodes budget — explore has its own 35k char output limit
  3206. // that prevents context bloat, so more nodes just means better coverage
  3207. // across entry points (especially for large files like Svelte components).
  3208. // Matching runs on the path-stripped query; `query` stays for display.
  3209. const subgraph = await cg.findRelevantContext(matchQuery, {
  3210. searchLimit: 8,
  3211. traversalDepth: 3,
  3212. maxNodes: 200,
  3213. minScore: 0.2,
  3214. });
  3215. // Pinned files' symbols enter the gather unconditionally — the agent named
  3216. // the file itself, so its contents ARE the answer regardless of what the
  3217. // stripped query text matched (which, for a pure-path query, is nothing).
  3218. const PINNED_FILE_NODE_CAP = 300;
  3219. for (const fp of pinnedFiles) {
  3220. let fileNodes: Node[] = [];
  3221. try { fileNodes = cg.getNodesInFile(fp); } catch { continue; }
  3222. fileNodes
  3223. .filter((n) => n.kind !== 'file' && n.kind !== 'import' && n.kind !== 'export')
  3224. .sort((a, b) => a.startLine - b.startLine)
  3225. .slice(0, PINNED_FILE_NODE_CAP)
  3226. .forEach((n) => { if (!subgraph.nodes.has(n.id)) subgraph.nodes.set(n.id, n); });
  3227. }
  3228. if (subgraph.nodes.size === 0) {
  3229. diag?.finishEmpty('no relevant code found — empty subgraph');
  3230. const missNote = unresolvedPathSpans.length > 0
  3231. ? ` (no indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')})`
  3232. : '';
  3233. const empty = `No relevant code found for "${query}"${missNote}`;
  3234. // Still an explore call, so it is still recorded: an empty answer spends a
  3235. // call against the tier budget even though it emits no source.
  3236. return this.exploreResult(empty, {
  3237. projectRoot, query, files: [], sourceBytes: 0, responseBytes: empty.length,
  3238. });
  3239. }
  3240. // Graph-aware glue: findRelevantContext builds the subgraph from name/text
  3241. // search, so a method that BRIDGES named symbols — e.g. App.tsx's
  3242. // triggerRender, which calls the named triggerUpdate — is never a search hit
  3243. // and gets missed, forcing the agent to Read the file to trace it. Pull in
  3244. // the callers/callees of the entry (root) nodes, but ONLY those that live in
  3245. // files the subgraph already surfaces (where the agent reads to fill gaps),
  3246. // so we add wiring without dragging in unrelated files. These get an
  3247. // importance boost below so they survive the per-file cluster budget.
  3248. const glueNodeIds = new Set<string>();
  3249. const subgraphFiles = new Set<string>();
  3250. for (const n of subgraph.nodes.values()) subgraphFiles.add(n.filePath);
  3251. const GLUE_NODE_CAP = 60;
  3252. for (const rootId of subgraph.roots) {
  3253. if (glueNodeIds.size >= GLUE_NODE_CAP) break;
  3254. let neighbors: Node[] = [];
  3255. try {
  3256. neighbors = [
  3257. ...cg.getCallers(rootId).map(c => c.node),
  3258. ...cg.getCallees(rootId).map(c => c.node),
  3259. ];
  3260. } catch {
  3261. continue;
  3262. }
  3263. for (const nb of neighbors) {
  3264. if (glueNodeIds.size >= GLUE_NODE_CAP) break;
  3265. if (subgraph.nodes.has(nb.id)) continue;
  3266. if (!subgraphFiles.has(nb.filePath)) continue;
  3267. subgraph.nodes.set(nb.id, nb);
  3268. glueNodeIds.add(nb.id);
  3269. }
  3270. }
  3271. // Named-symbol seeding: findRelevantContext is an FTS/text rank, so a query
  3272. // that's a BAG of symbol names skewed toward one phase (Alamofire: 5 build
  3273. // terms, each a high-frequency name, vs 3 validate terms) lets the
  3274. // lower-frequency names fall below the search cut — their definitions, and
  3275. // whole files (Validation.swift), never get gathered, so they can never
  3276. // render and the agent Reads them. Resolve EACH named token to its
  3277. // substantive definition (skip empty stubs + test files, same relevance the
  3278. // trace endpoint picker uses) and inject it as an entry, so every symbol the
  3279. // agent explicitly named is in the subgraph and its file is scored.
  3280. const namedSeedIds = new Set<string>();
  3281. // The subset of named seeds that earns the named-FIRST sort tier. We still
  3282. // SEED every ≤3-def name (so RWR / flow ranking is unchanged), but only the
  3283. // most-substantive def is tiered — a bare name's unrelated namesakes (Go's
  3284. // `NewClient` = real client + test fake + xds pool) must not fill the tier
  3285. // and crowd out the real answer file (grpc's `dialoptions.go`). Corroborated
  3286. // overloads (the query also named the type) all earn it. (#1064)
  3287. const tierSeedIds = new Set<string>();
  3288. // Files declaring a TYPE the query named by name — the counter-case guard
  3289. // for the declaration-only penalty (CG-28). Populated in the token loop.
  3290. const namedTypeFiles = new Set<string>();
  3291. {
  3292. const FILE_EXT = /\.(?:java|kt|kts|ts|tsx|js|jsx|mjs|cjs|cs|py|go|rb|php|swift|rs|cpp|cc|cxx|c|h|hpp|scala|lua|dart|vue|svelte|astro|erl|hrl)$/i;
  3293. const CALLABLE = new Set(['method', 'function', 'component', 'constructor']);
  3294. // Variables/constants seed too: in Svelte/React a `$state` variable
  3295. // (`chatAtBottom`, `feedAtBottom`) is exactly the kind of symbol an agent
  3296. // names in a query, and the exact-name search channel already returns
  3297. // them — only this seeding tier was callable-only. The NL-stopword guard
  3298. // below applies unchanged, so bare English words still can't seed a
  3299. // same-named local. Callables keep priority via the body-size sort.
  3300. const SEEDABLE = new Set([...CALLABLE, 'variable', 'constant']);
  3301. const isTestPath = (p: string) => /(^|\/)(tests?|specs?|__tests__|testdata|mocks?|fixtures?)\//i.test(p) || /\.(test|spec)\.[a-z]+$/i.test(p);
  3302. const bodyLines = (n: Node) => Math.max(0, (n.endLine ?? n.startLine) - n.startLine);
  3303. const callerCount = (n: Node) => { try { return cg.getCallers(n.id).length; } catch { return 0; } };
  3304. const tokens = [...new Set(
  3305. matchQuery.split(/[\s,()[\]]+/)
  3306. .map((t) => t.replace(FILE_EXT, '').trim())
  3307. .filter((t) => t.length >= 3 && /^[A-Za-z_$][\w$]*(?:(?:::|\.)[\w$]+)*$/.test(t))
  3308. )].slice(0, 16);
  3309. // PascalCase tokens in the query are type/file disambiguators — when the
  3310. // agent writes "DataRequest task validate", the `task`/`validate` it wants
  3311. // are DataRequest's, NOT the same-named overloads in Validation.swift /
  3312. // Concurrency.swift / the abstract base. Used below to bias overloaded
  3313. // names toward the file/class the query also names. EXCLUDE the project
  3314. // name (a PascalCase token a user naturally includes) — it names the whole
  3315. // repo, so biasing toward it just pulls overloads to whichever stack
  3316. // embeds it, re-burying the rest (#720).
  3317. const projectNameTokens = cg.getProjectNameTokens();
  3318. const typeTokens = tokens.filter(
  3319. (o) => /^[A-Z][A-Za-z0-9]{3,}/.test(o) && !projectNameTokens.has(normalizeNameToken(o)),
  3320. );
  3321. const inNamedContext = (n: Node) =>
  3322. typeTokens.some((ct) => {
  3323. const lc = ct.toLowerCase();
  3324. return n.filePath.toLowerCase().includes(lc) || n.qualifiedName.toLowerCase().includes(lc);
  3325. });
  3326. // NL-stopword guard: this seeding treats every token as "a symbol the
  3327. // agent named", but explore also takes natural-language questions, whose
  3328. // ordinary English words collide with real callables — "…check the latest
  3329. // version…" exact-matched a lone `check()` method, which then earned the
  3330. // named-FIRST sort tier and displaced the corroborated answer files from
  3331. // the whole render budget (the agent fell back to Read). A shape-precise
  3332. // token (camelCase, PascalCase, snake_case, qualified) is an unambiguous
  3333. // symbol reference and seeds unconditionally; a BARE lowercase word seeds
  3334. // only where the query corroborates the file — another query token is
  3335. // itself a symbol defined in that same file (the "check drain fire"
  3336. // sibling-bag case), which an incidental English-word collision never is.
  3337. const lcTokens = new Set(tokens.map((x) => x.toLowerCase()));
  3338. const isPreciseToken = (x: string) =>
  3339. /[._$]|::|\//.test(x) || /[a-z][A-Z]/.test(x) || /^[A-Z]/.test(x);
  3340. const fileNameSets = new Map<string, Set<string>>();
  3341. const coNamedInFile = (t: string, fp: string): boolean => {
  3342. let names = fileNameSets.get(fp);
  3343. if (!names) {
  3344. names = new Set<string>();
  3345. try {
  3346. for (const n of cg.getNodesInFile(fp)) names.add(n.name.toLowerCase());
  3347. } catch { /* unreadable file entry — treat as uncorroborated */ }
  3348. fileNameSets.set(fp, names);
  3349. }
  3350. const self = t.toLowerCase();
  3351. for (const o of lcTokens) {
  3352. if (o !== self && names.has(o)) return true;
  3353. }
  3354. return false;
  3355. };
  3356. for (const t of tokens) {
  3357. // Enumerate ALL defs of a bare token via the direct index, not FTS — a
  3358. // 50+-overload name (tokio `poll`) ranks the wanted def (`Harness::poll`)
  3359. // below the FTS cut, so findAllSymbols would never see it and the
  3360. // type-token bias below couldn't pick the harness.rs one. (Same fix as
  3361. // codegraph_node's findSymbolMatches.) Qualified tokens keep findAllSymbols.
  3362. const isQual = /[.\/]|::/.test(t);
  3363. const raw = isQual ? this.findAllSymbols(cg, t).nodes : cg.getNodesByName(t);
  3364. // A query that NAMES a declared type is a question ABOUT that type, and
  3365. // must still reach its declaration file at full weight — so record the
  3366. // files those declarations live in and exempt them from the
  3367. // declaration-only penalty below (CG-28). Only PRECISE tokens count, by
  3368. // the same NL-stopword reasoning as the seeding above: "…the file body…"
  3369. // must not exempt a `Body` interface it never meant to name. Kept
  3370. // separate from `namedSeedIds`, which is callable-only by construction —
  3371. // a type never becomes a named seed, so it cannot be the guard here.
  3372. if (isPreciseToken(t)) {
  3373. for (const n of raw) {
  3374. if (DECLARATION_KINDS.has(n.kind) && n.name.toLowerCase() === t.toLowerCase()) {
  3375. namedTypeFiles.add(n.filePath);
  3376. }
  3377. }
  3378. }
  3379. let cands = raw
  3380. .filter((n) => SEEDABLE.has(n.kind) && !isTestPath(n.filePath))
  3381. .sort((a, b) => (bodyLines(b) > 1 ? 1 : 0) - (bodyLines(a) > 1 ? 1 : 0) || bodyLines(b) - bodyLines(a));
  3382. // Field-name seeding fallback (#1196): a camelCase token that names NO
  3383. // definition of its own is usually an object-literal key / API field
  3384. // (`profileInfo`) — no node exists, so it contributed zero seeds and
  3385. // the files that DEFINE it (`getProfileInfoV2` in profileController)
  3386. // never surfaced. Seed its camel-infix definers instead: seedable
  3387. // symbols (callables + variables — `atBottom` must reach the `$state`
  3388. // variables `feedAtBottom`/`chatAtBottom`) whose name contains the
  3389. // token at a hump boundary or as a prefix.
  3390. // Exact-empty + camel-shaped only (bare words keep the NL-stopword
  3391. // guard below), shortest-first, capped so a hot infix can't flood.
  3392. if (cands.length === 0 && !isQual && /[a-z][A-Z]/.test(t)) {
  3393. const lcToken = t.toLowerCase();
  3394. cands = cg
  3395. .getNodesByNameSubstring(t, {
  3396. kinds: ['function', 'method', 'component', 'variable', 'constant'],
  3397. limit: 60,
  3398. })
  3399. .filter((n) => SEEDABLE.has(n.kind) && !isTestPath(n.filePath))
  3400. .filter((n) => {
  3401. const idx = n.name.toLowerCase().indexOf(lcToken);
  3402. if (idx < 0) return false;
  3403. if (idx === 0) return n.name.length > t.length; // prefix definer
  3404. return /[A-Z]/.test(n.name.charAt(idx)); // camel-hump boundary
  3405. })
  3406. .sort((a, b) => a.name.length - b.name.length)
  3407. .slice(0, 3);
  3408. }
  3409. // Bare lowercase words only seed defs their query-siblings corroborate
  3410. // (see the NL-stopword guard above). Filtering CANDS (not picks) applies
  3411. // the guard uniformly to both branches below, including the >3-def
  3412. // single-pick fallback — an uncorroborated bare `run` must not tier its
  3413. // most-substantive namesake any more than a 1-def `check` may.
  3414. if (!isPreciseToken(t)) {
  3415. cands = cands.filter((n) => coNamedInFile(t, n.filePath));
  3416. }
  3417. // A specific name (<=3 defs) injects all its defs. An overloaded name
  3418. // (`validate` = 10, `request` = 44) would flood the subgraph, so inject
  3419. // only: the overloads whose file/class the query ALSO names (the agent
  3420. // told us which one it wants — DataRequest's, not Validation.swift's),
  3421. // capped; else fall back to the single most-substantive def. This is the
  3422. // explore-side mirror of codegraph_node's overload disambiguation.
  3423. let picks: Node[];
  3424. let tierPicks: Node[]; // subset that earns the named-first tier (#1064)
  3425. if (cands.length <= 3) {
  3426. picks = cands;
  3427. // Centrality de-noise: tier the most-substantive def PLUS any co-named
  3428. // def of comparable centrality (a real overload/wrapper — excalidraw's
  3429. // `mutateElement` lives in mutateElement.ts, App.tsx AND Scene.ts, all
  3430. // within ~2x callers). EXCLUDE a vastly-less-central namesake (Go's
  3431. // `NewClient`: real client 492 callers vs xds-pool 11, test-fake 3 →
  3432. // ratio <0.025) so it doesn't fill the tier and crowd out the answer.
  3433. const counts = new Map(cands.map((c) => [c.id, callerCount(c)]));
  3434. const maxCallers = Math.max(1, ...counts.values());
  3435. tierPicks = cands.filter((c, i) => i === 0 || (counts.get(c.id) ?? 0) >= maxCallers * 0.25);
  3436. } else {
  3437. const ctx = cands.filter(inNamedContext);
  3438. picks = ctx.length > 0 ? ctx.slice(0, 4) : cands.slice(0, 1);
  3439. tierPicks = picks; // corroborated overloads (or the single fallback) all earn it
  3440. }
  3441. for (const n of picks) {
  3442. if (!subgraph.nodes.has(n.id)) subgraph.nodes.set(n.id, n);
  3443. // Mark as a named seed EVEN IF the FTS gather already had it — being
  3444. // "named by the agent" is independent of whether search happened to
  3445. // surface it, and it drives the +50 score, the gate, and the
  3446. // named-file sort below. (Previously only NEW injections were marked,
  3447. // so a named symbol FTS already gathered never sorted to the top.)
  3448. namedSeedIds.add(n.id);
  3449. }
  3450. for (const n of tierPicks) tierSeedIds.add(n.id);
  3451. }
  3452. }
  3453. // Step 2: Group nodes by file, score by relevance
  3454. // `peripheral` accumulates separately so it can be capped — see
  3455. // PERIPHERAL_SCORE_CAP; it is folded into `score` once the loop is done.
  3456. const fileGroups = new Map<string, { nodes: Node[]; score: number; peripheral: number }>();
  3457. const entryNodeIds = new Set([...subgraph.roots, ...namedSeedIds]);
  3458. // Build a set of nodes directly connected to entry points (depth 1)
  3459. const connectedToEntry = new Set<string>();
  3460. for (const edge of subgraph.edges) {
  3461. if (entryNodeIds.has(edge.source)) connectedToEntry.add(edge.target);
  3462. if (entryNodeIds.has(edge.target)) connectedToEntry.add(edge.source);
  3463. }
  3464. // Usage degree within the subgraph, for the weak-kind isolation test below.
  3465. // Free (the edges are already in hand) and it answers most cases; only a
  3466. // weak-kind node that looks isolated HERE pays for a DB probe.
  3467. const subgraphUsageDegree = new Map<string, number>();
  3468. for (const edge of subgraph.edges) {
  3469. if (!RELEVANCE_USAGE_EDGES.has(edge.kind) || edge.source === edge.target) continue;
  3470. subgraphUsageDegree.set(edge.source, (subgraphUsageDegree.get(edge.source) ?? 0) + 1);
  3471. subgraphUsageDegree.set(edge.target, (subgraphUsageDegree.get(edge.target) ?? 0) + 1);
  3472. }
  3473. /**
  3474. * Relevance weight for one matched symbol: its NodeKind, further discounted
  3475. * when it is a weak kind that NOTHING uses. The DB probe (full-graph, since
  3476. * a usage can sit outside the traversal) is paid for only by weak-kind
  3477. * symbols in the top two tiers — the ones whose weight can carry a whole
  3478. * file. A `connectedToEntry` or peripheral node is worth <= 3 either way, so
  3479. * probing it would buy nothing.
  3480. */
  3481. const isolationCache = new Map<string, boolean>();
  3482. const isUsageIsolated = (node: Node): boolean => {
  3483. if ((subgraphUsageDegree.get(node.id) ?? 0) > 0) return false;
  3484. const cached = isolationCache.get(node.id);
  3485. if (cached !== undefined) return cached;
  3486. let isolated = true;
  3487. try {
  3488. const used = (e: Edge) => RELEVANCE_USAGE_EDGES.has(e.kind);
  3489. isolated = !cg.getIncomingEdges(node.id).some(used)
  3490. && !cg.getOutgoingEdges(node.id).some(used);
  3491. } catch {
  3492. isolated = false; // a probe failure must not manufacture a penalty
  3493. }
  3494. isolationCache.set(node.id, isolated);
  3495. return isolated;
  3496. };
  3497. const relevanceWeight = (node: Node, probeIsolation: boolean): number => {
  3498. const weight = RELEVANCE_KIND_WEIGHT[node.kind] ?? DEFAULT_RELEVANCE_KIND_WEIGHT;
  3499. if (!probeIsolation || !WEAK_RELEVANCE_KINDS.has(node.kind)) return weight;
  3500. return isUsageIsolated(node) ? ISOLATED_WEAK_KIND_WEIGHT : weight;
  3501. };
  3502. // CHANGE SURFACE (#1064): a named method's signature types — its parameter
  3503. // and return types — are part of what you'd edit to "add a parameter to X",
  3504. // yet they can be lexically dissimilar to the query ("add a parameter to
  3505. // NewClient" shares no words with `dialoptions.go`, which defines NewClient's
  3506. // `DialOption`) and sit a hop away. COLLECT them here from each named-seed
  3507. // callable's outgoing signature edges (full graph — the type is often not in
  3508. // the subgraph); the decision to surface one is DEFERRED to the buried-rescue
  3509. // pass below, which fires only when the type's file would otherwise be
  3510. // dropped — so a well-connected type (excalidraw's element types, Alamofire's
  3511. // `DataRequest` on a flow query) is left to rank on its own and never
  3512. // displaces a flow-central file. Bounded: only the few named seeds, only the
  3513. // types in their signatures.
  3514. const CALLABLE_KINDS = new Set(['method', 'function', 'component', 'constructor']);
  3515. const TYPE_KINDS = new Set(['class', 'struct', 'union', 'interface', 'trait', 'protocol', 'enum', 'type_alias']);
  3516. const SIG_EDGE = new Set(['references', 'type_of', 'returns']);
  3517. const changeSurfaceCandidates: Node[] = [];
  3518. const seenChangeSurface = new Set<string>();
  3519. for (const seedId of tierSeedIds) {
  3520. const seedNode = subgraph.nodes.get(seedId);
  3521. if (!seedNode || !CALLABLE_KINDS.has(seedNode.kind)) continue;
  3522. let outs: Edge[] = [];
  3523. try { outs = cg.getOutgoingEdges(seedId); } catch { continue; }
  3524. for (const e of outs) {
  3525. if (!SIG_EDGE.has(e.kind)) continue;
  3526. const tgt = cg.getNode(e.target);
  3527. if (!tgt || !TYPE_KINDS.has(tgt.kind) || namedSeedIds.has(tgt.id)) continue;
  3528. if (seenChangeSurface.has(tgt.id)) continue;
  3529. seenChangeSurface.add(tgt.id);
  3530. changeSurfaceCandidates.push(tgt);
  3531. }
  3532. }
  3533. for (const node of subgraph.nodes.values()) {
  3534. // Skip import/export nodes — they add noise without information
  3535. if (node.kind === 'import' || node.kind === 'export') continue;
  3536. // SECURITY (#383): never render the on-disk source of a config-leaf
  3537. // (Spring application.{yml,properties} key) — its line is `key = <secret>`,
  3538. // so whole-file/cluster rendering here would push secrets into context
  3539. // unbidden. The key still appears in the flow/symbol listing above.
  3540. if (isConfigLeafNode(node)) continue;
  3541. const group = fileGroups.get(node.filePath) || { nodes: [], score: 0, peripheral: 0 };
  3542. group.nodes.push(node);
  3543. // Score: a NAMED-SEED node (a symbol the agent named that FTS missed, now
  3544. // injected) is worth far more than a mere reference — its file is where the
  3545. // answer lives. Without this, an incidental file that name-drops the flow
  3546. // (Combine.swift references request/task → score 23 from connected nodes)
  3547. // outranks the file that DEFINES a named symbol (Validation.swift's
  3548. // `validate` → 10) and steals its render slot. Definition ≫ reference.
  3549. //
  3550. // Each tier is then scaled by WHAT was matched (RELEVANCE_KIND_WEIGHT): the
  3551. // tier says how the symbol reached us, the kind weight says whether the
  3552. // match is evidence. A file whose only claim is an unused local `explore`
  3553. // constant is a name collision, not an answer (#1500).
  3554. if (namedSeedIds.has(node.id)) {
  3555. group.score += 50 * relevanceWeight(node, true);
  3556. } else if (entryNodeIds.has(node.id)) {
  3557. group.score += 10 * relevanceWeight(node, true);
  3558. } else if (connectedToEntry.has(node.id)) {
  3559. group.score += 3 * relevanceWeight(node, false);
  3560. } else {
  3561. // Peripheral: in the subgraph but ≥2 hops from anything the query
  3562. // matched. Accumulated separately and capped below, so a file cannot
  3563. // buy relevance with size alone.
  3564. group.peripheral += relevanceWeight(node, false);
  3565. }
  3566. fileGroups.set(node.filePath, group);
  3567. }
  3568. // Extract query terms for relevance checking (path-stripped: a pinned
  3569. // file's own path fragments must not count as "term hits" everywhere)
  3570. const queryTerms = matchQuery.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
  3571. // Test/spec/icon/i18n file detector — used by the pre-floor hard filter, the
  3572. // rank penalty, and the comparator deprioritization.
  3573. //
  3574. // The directory pattern is anchored at `^` as well as `/`: a repo-ROOT
  3575. // `test/` or `spec/` directory (express, cobra, and most of npm/Go) produced
  3576. // paths like `test/express.raw.js`, which the old leading-`/` form could
  3577. // never match — so express's routing question spent 59% of its envelope on
  3578. // three test files while `lib/router/index.js` never rendered.
  3579. const isLowValue = (p: string) => {
  3580. const lp = p.toLowerCase();
  3581. return (
  3582. /(?:^|\/)(tests?|__tests?__|specs?)\//.test(lp) ||
  3583. /_test\.go$/.test(lp) ||
  3584. /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
  3585. /_test\.py$/.test(lp) ||
  3586. /_spec\.rb$/.test(lp) ||
  3587. /_test\.rb$/.test(lp) ||
  3588. /\.(test|spec)\.[jt]sx?$/.test(lp) ||
  3589. /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
  3590. /(tests?|spec)\.cs$/.test(lp) ||
  3591. /tests?\.swift$/.test(lp) ||
  3592. /_test\.dart$/.test(lp) ||
  3593. /\bicons?\b/.test(lp) ||
  3594. /\bi18n\b/.test(lp)
  3595. );
  3596. };
  3597. // One DB probe over every file the query touched, then O(1) per lookup.
  3598. // Unions the index-time content-banner flag (CG-5) with the filename
  3599. // convention, so a Go monorepo's generated CRUD (`payroll.go` carrying a
  3600. // DO-NOT-EDIT banner and nothing in its name) down-ranks the same way
  3601. // `.pb.go` always has (#1500). Covers the whole subgraph, not just the
  3602. // grouped files, because the graph-mass penalty below is keyed on it too.
  3603. const penaltyCandidates = new Set([
  3604. ...fileGroups.keys(),
  3605. ...[...subgraph.nodes.values()].map((n) => n.filePath),
  3606. ]);
  3607. const isGeneratedCandidate = cg.generatedFilePredicate(penaltyCandidates);
  3608. // Second bounded probe over the same set: files declaring nothing but types
  3609. // that nothing in the index depends on (CG-28). A query that NAMED one of
  3610. // those types is asking about the declaration, so its file is exempt and
  3611. // ranks at full weight.
  3612. const isAmbientDeclaration = cg.ambientDeclarationFilePredicate(penaltyCandidates);
  3613. const isDampedDeclaration = (filePath: string): boolean =>
  3614. isAmbientDeclaration(filePath) && !namedTypeFiles.has(filePath);
  3615. /**
  3616. * Rank penalty for a file, applied to its relevance score AND (below) to its
  3617. * graph mass — the two signals the sort actually keys on. Applying it to the
  3618. * score alone would leave the #1500 case unfixed: the generated CRUD carries
  3619. * MORE graph mass than the hand-written use-case, and graph mass outranks
  3620. * score in the comparator.
  3621. *
  3622. * Generated and ambient-declaration are taken as the STRONGER of the two,
  3623. * never multiplied: a generated `.d.ts` has one property — "not the
  3624. * implementation" — that both signals happen to see, and charging it twice is
  3625. * how a file gets cliffed out of answers where it is genuinely relevant
  3626. * (CG-28). The low-value multiplier is orthogonal (a test file that is also
  3627. * generated is two independent reasons) and still compounds.
  3628. */
  3629. const rankPenalty = (filePath: string): number =>
  3630. Math.min(
  3631. isGeneratedCandidate(filePath) ? GENERATED_RANK_PENALTY : 1,
  3632. isDampedDeclaration(filePath) ? AMBIENT_DECLARATION_RANK_PENALTY : 1,
  3633. )
  3634. * (isLowValue(filePath) ? LOW_VALUE_RANK_PENALTY : 1);
  3635. for (const [filePath, group] of fileGroups) {
  3636. group.score = (group.score + Math.min(PERIPHERAL_SCORE_CAP, group.peripheral))
  3637. * rankPenalty(filePath);
  3638. }
  3639. // Hard-exclude test/spec files (ALL tiers — the per-tier `excludeLowValueFiles`
  3640. // flag this used to be gated on was dead config and is gone). One slipped test
  3641. // file dominates the per-file budget on small repos (cobra's `command_test.go`
  3642. // displaced `args.go`) AND wastes budget on large ones (Django's
  3643. // `custom_lookups/tests.py` ate ~2.3 KB of the 28 KB cap, crowding out the
  3644. // SQLCompiler mechanism the agent then Read). A test file almost never answers
  3645. // an architecture question. Skip when the query itself is about tests — the
  3646. // legitimate "explore the tests" case — and only cut if ≥2 non-test candidates
  3647. // remain (else tests are the only signal for this area).
  3648. //
  3649. // Runs BEFORE the score floor, on the whole gather. Judging "are there other
  3650. // candidates?" on the post-floor set was too late: express's routing question
  3651. // left one non-test file past the floor, the guard stood down, and the floor's
  3652. // keep-minimum then pulled two test files back in as the "spread".
  3653. let candidateFiles = [...fileGroups.entries()];
  3654. {
  3655. const queryMentionsTests = /\b(test|tests|testing|spec|verify|verifies)\b/i.test(matchQuery);
  3656. if (!queryMentionsTests) {
  3657. // A pinned file is exempt: naming a test file by path IS asking for it.
  3658. const nonLow = candidateFiles.filter(([p]) => !isLowValue(p) || pinnedSet.has(p));
  3659. if (nonLow.length >= 2) {
  3660. candidateFiles = nonLow;
  3661. }
  3662. }
  3663. diag?.setLowValueFiltered(fileGroups.size, candidateFiles.length);
  3664. }
  3665. // Relative score floor — see SCORE_FLOOR_* for why it is a fraction of the
  3666. // best file's score and why that fraction is clamped at both ends.
  3667. const topScore = Math.max(0, ...candidateFiles.map(([, g]) => g.score));
  3668. const scoreFloor = Math.max(
  3669. SCORE_FLOOR_ABSOLUTE,
  3670. Math.min(SCORE_FLOOR_MAX, topScore * SCORE_FLOOR_FRACTION_OF_TOP),
  3671. );
  3672. let relevantFiles = candidateFiles.filter(
  3673. ([fp, group]) => group.score >= scoreFloor || pinnedSet.has(fp),
  3674. );
  3675. if (relevantFiles.length < SCORE_FLOOR_KEEP_MIN) {
  3676. // Backfill from what the RELATIVE floor cut, best first, at two strengths:
  3677. //
  3678. // - THIN (1-2 files survived): only files with real evidence. A file whose
  3679. // entire claim is one isolated variable scores 0.8 and stays out —
  3680. // express's `examples/route-middleware` matched nothing but a local
  3681. // `app` and would otherwise have taken 48% of that envelope. Padding a
  3682. // precise answer with a wrong file doesn't save the agent the follow-up
  3683. // call it would pad against.
  3684. // - EMPTY (nothing survived): take the best of whatever matched. Returning
  3685. // "no relevant code found" when the gather DID find candidates is the
  3686. // worst outcome on the board — the agent falls straight back to grep.
  3687. const minEvidence = relevantFiles.length === 0 ? Number.EPSILON : SCORE_FLOOR_ABSOLUTE;
  3688. relevantFiles = candidateFiles
  3689. .filter(([fp, group]) => group.score >= minEvidence || pinnedSet.has(fp))
  3690. .sort((a, b) =>
  3691. (pinnedSet.has(b[0]) ? 1 : 0) - (pinnedSet.has(a[0]) ? 1 : 0)
  3692. || b[1].score - a[1].score
  3693. || b[1].nodes.length - a[1].nodes.length)
  3694. .slice(0, Math.max(SCORE_FLOOR_KEEP_MIN, relevantFiles.length));
  3695. }
  3696. diag?.setScoreFloor(scoreFloor, relevantFiles.length);
  3697. // Secondary signal: how many DISTINCT query terms each file matches (path +
  3698. // symbol names). Kept only as a tiebreak — the PRIMARY relevance is graph
  3699. // connectivity below. (Term counting alone tied the real central file with
  3700. // incidental same-word matches; it's a weak text signal, not the ranker.)
  3701. const uniqueQueryTerms = [...new Set(queryTerms)].filter(t => t.length >= 3);
  3702. const fileTermHits = new Map<string, number>();
  3703. for (const [fp, group] of relevantFiles) {
  3704. const hay = fp.toLowerCase() + ' ' + group.nodes.map(n => n.name.toLowerCase()).join(' ');
  3705. let hits = 0;
  3706. for (const t of uniqueQueryTerms) if (hay.includes(t)) hits++;
  3707. fileTermHits.set(fp, hits);
  3708. }
  3709. // PRIMARY relevance: graph connectivity (Random-Walk-with-Restart from the
  3710. // matched seeds — see computeGraphRelevance). Aggregate each file's nodes'
  3711. // walk mass. This is the signal text search lacks: the real cluster
  3712. // (org-user.storage.ts, call-connected to the matches) accrues mass; a lone
  3713. // text match (LensSwitcher.swift, matched "switch" but calls nothing in the
  3714. // flow) gets only its restart probability → ~0, and is dropped by the gate.
  3715. const nodeRwr = this.computeGraphRelevance(
  3716. [...subgraph.nodes.keys()], subgraph.edges, entryNodeIds,
  3717. );
  3718. //
  3719. // Carries `rankPenalty` too, so generated/low-value files are demoted on the
  3720. // sort's PRIMARY key rather than only at the tiebreak. Everything downstream
  3721. // (centrality, the relevance gate, the buried-rescue test, the comparator)
  3722. // reads this map, so the penalty applies once and applies everywhere.
  3723. const fileGraphScore = new Map<string, number>();
  3724. for (const node of subgraph.nodes.values()) {
  3725. fileGraphScore.set(
  3726. node.filePath,
  3727. (fileGraphScore.get(node.filePath) ?? 0) + (nodeRwr.get(node.id) ?? 0),
  3728. );
  3729. }
  3730. for (const [fp, mass] of fileGraphScore) fileGraphScore.set(fp, mass * rankPenalty(fp));
  3731. const maxGraph = Math.max(0, ...fileGraphScore.values());
  3732. // Central file(s): the 1-2 most graph-central files that also match the
  3733. // query textually (so a connected hub-utility with no term match isn't
  3734. // mistaken for the subject). The heart of the answer — they earn the larger
  3735. // WHOLE-FILE ceiling below (a god-file central file still exceeds it and
  3736. // falls to generous full-method sectioning — never a whole dump).
  3737. const centralFiles = new Set(
  3738. [...fileGraphScore.entries()]
  3739. .filter(([fp, g]) => g > 0 && (fileTermHits.get(fp) ?? 0) >= 1)
  3740. .sort((a, b) => b[1] - a[1] || (fileTermHits.get(b[0]) ?? 0) - (fileTermHits.get(a[0]) ?? 0))
  3741. .slice(0, 2)
  3742. .map(([f]) => f),
  3743. );
  3744. // Files that DEFINE a symbol the agent named (or a subgraph root). These are
  3745. // the highest-relevance files there are — the agent asked for them by name —
  3746. // so the connectivity gate below must never drop them, even when their RWR
  3747. // mass is low (a leaf family file like codec.ts is call-connected to little
  3748. // but is exactly what the agent queried). Without this protection the gate
  3749. // prunes a named file and the agent Reads it back.
  3750. const entryFiles = new Set<string>();
  3751. for (const id of entryNodeIds) {
  3752. const n = subgraph.nodes.get(id);
  3753. if (n) entryFiles.add(n.filePath);
  3754. }
  3755. // Buried-rescue pass (#1064): surface a named method's signature type ONLY
  3756. // when its file is genuinely buried — near-zero graph mass AND not lexically
  3757. // matched. That is the invisible case (grpc's `DialOption` → `dialoptions.go`,
  3758. // g≈0, 0 term hits): reachable but ranked nowhere, so the agent greps. A
  3759. // well-connected type file (excalidraw element types, Alamofire `DataRequest`)
  3760. // is NOT buried and is left alone — rescuing it would displace a flow-central
  3761. // file (App.tsx, Validation.swift). Buried is judged on the PRE-rescue graph,
  3762. // so injecting the type below can't make it look connected. A rescued file is
  3763. // injected (so it renders), force-kept (gate + relevantFiles), and tiered.
  3764. const changeSurfaceFiles = new Set<string>();
  3765. for (const t of changeSurfaceCandidates) {
  3766. const fp = t.filePath;
  3767. const buried = (fileGraphScore.get(fp) ?? 0) < maxGraph * 0.06
  3768. && (fileTermHits.get(fp) ?? 0) < 2;
  3769. if (!buried) continue;
  3770. changeSurfaceFiles.add(fp);
  3771. if (!subgraph.nodes.has(t.id)) subgraph.nodes.set(t.id, t);
  3772. let group = fileGroups.get(fp);
  3773. if (!group) { group = { nodes: [], score: 0, peripheral: 0 }; fileGroups.set(fp, group); }
  3774. if (!group.nodes.some((n) => n.id === t.id)) group.nodes.push(t);
  3775. group.score = Math.max(group.score, 45);
  3776. if (!relevantFiles.some(([f]) => f === fp)) relevantFiles.push([fp, group]);
  3777. }
  3778. // Relevance gate (so the generous budget is a CEILING, not a target): keep a
  3779. // file only if it is STRUCTURALLY relevant by ANY of:
  3780. // - graph score within a fraction of the top (it's on/near the flow), OR
  3781. // - central (a query entry-point lives here), OR
  3782. // - it DEFINES a symbol the agent named (entryFiles), OR
  3783. // - it matches >= 2 DISTINCT named query terms — a strong text signal that
  3784. // the agent is asking about this file even when nothing calls it (codec.ts:
  3785. // the agent named `encode`/`Codec`/`JsonCodec`, all leaf classes with zero
  3786. // RWR mass — graph alone wrongly drops it).
  3787. // A lone text match on one shared word (LensSwitcher: term=1, g~0) is still
  3788. // dropped, so the budget never fills with incidental files. Guarded so it
  3789. // never prunes below 2.
  3790. if (maxGraph > 0) {
  3791. const gated = relevantFiles.filter(([fp]) =>
  3792. pinnedSet.has(fp)
  3793. || (fileGraphScore.get(fp) ?? 0) >= maxGraph * 0.06
  3794. || centralFiles.has(fp)
  3795. || entryFiles.has(fp)
  3796. || changeSurfaceFiles.has(fp)
  3797. || (fileTermHits.get(fp) ?? 0) >= 2,
  3798. );
  3799. if (gated.length >= 2) relevantFiles = gated;
  3800. diag?.setRelevanceGate(maxGraph, maxGraph * 0.06, gated.length >= 2, relevantFiles.length);
  3801. } else {
  3802. diag?.setRelevanceGate(maxGraph, 0, false, relevantFiles.length);
  3803. }
  3804. // Sort files: graph-central first, then distinct-term match, then the
  3805. // existing low-value/generated/score tiebreaks.
  3806. // Files that DEFINE a symbol the agent NAMED. These sort first — ahead of
  3807. // graph connectivity — because the agent asked for them by name. Without
  3808. // this, a named leaf override reached only by dynamic dispatch (Alamofire's
  3809. // `DataRequest.task`/`validate`, low RWR mass) sorts below the high-
  3810. // connectivity abstract base (`Request.swift`) and the same-named overloads
  3811. // in other files (`Validation.swift`), falls outside the budget, and the
  3812. // agent Reads it. The named file is the answer — rank it at the top.
  3813. const namedSeedFiles = new Set<string>();
  3814. for (const id of tierSeedIds) {
  3815. const n = subgraph.nodes.get(id);
  3816. if (n) namedSeedFiles.add(n.filePath);
  3817. }
  3818. // A rescued change-surface file (only the genuinely-buried ones — see the
  3819. // buried-rescue pass) is the lexically-dissimilar answer; give it the named
  3820. // tier so it isn't buried under files that merely share surface words (#1064).
  3821. for (const fp of changeSurfaceFiles) namedSeedFiles.add(fp);
  3822. // Multi-term corroboration tier: a file that is BOTH (a) an entry/central file
  3823. // (a search root, named seed, or graph-central hub — i.e. structurally part of
  3824. // the answer) AND (b) matched by ≥2 DISTINCT query terms must not be buried by
  3825. // graph-centrality mass that accrued to a denser-but-off-topic cluster. In a
  3826. // cross-layer monorepo (an API server alongside a much larger, internally dense
  3827. // frontend that mirrors the same domain words) the Random-Walk-with-Restart mass
  3828. // — seeded from text matches that skew to the bigger layer — floats hits=0
  3829. // frontend files above the hits=2/3 backend service that IS the answer (its many
  3830. // callers don't help: it's call-isolated from the frontend seed cluster). The
  3831. // entry/central GUARD keeps this safe: an INCIDENTAL multi-term file that is
  3832. // neither entry nor central (a type/util file that matches "element"+x but isn't
  3833. // the flow) is NOT promoted, so it can't displace the graph-central answer file
  3834. // (hits=1) the way a blunt hits-only tier would. Single-layer repos with one
  3835. // cluster are unaffected (no competing mass). Set CODEGRAPH_RANK_NO_MULTITERM=1
  3836. // to disable.
  3837. const MULTITERM_OFF = process.env.CODEGRAPH_RANK_NO_MULTITERM === '1';
  3838. const isCorroborated = (fp: string) =>
  3839. !MULTITERM_OFF &&
  3840. (fileTermHits.get(fp) ?? 0) >= 2 &&
  3841. (entryFiles.has(fp) || centralFiles.has(fp));
  3842. const sortedFiles = relevantFiles.sort((a, b) => {
  3843. const aPath = a[0].toLowerCase();
  3844. const bPath = b[0].toLowerCase();
  3845. // Pinned files first of all — the agent named the FILE by path, which is
  3846. // even more explicit than naming a symbol in it. Among pins, keep the
  3847. // order they appeared in the query.
  3848. const aPin = pinnedSet.has(a[0]) ? 1 : 0;
  3849. const bPin = pinnedSet.has(b[0]) ? 1 : 0;
  3850. if (aPin !== bPin) return bPin - aPin;
  3851. if (aPin && bPin) return (pinnedOrder.get(a[0]) ?? 0) - (pinnedOrder.get(b[0]) ?? 0);
  3852. // Agent-named files next (it asked for a symbol defined here by name).
  3853. const aNamed = namedSeedFiles.has(a[0]) ? 1 : 0;
  3854. const bNamed = namedSeedFiles.has(b[0]) ? 1 : 0;
  3855. if (aNamed !== bNamed) return bNamed - aNamed;
  3856. // Corroborated (entry/central + ≥2 terms) tier, above the graph signal.
  3857. const aCorr = isCorroborated(a[0]) ? 1 : 0;
  3858. const bCorr = isCorroborated(b[0]) ? 1 : 0;
  3859. if (aCorr !== bCorr) return bCorr - aCorr;
  3860. // Graph connectivity is the next key (small epsilon so near-ties fall
  3861. // through to the text signal rather than coin-flipping on float noise).
  3862. const aG = fileGraphScore.get(a[0]) ?? 0;
  3863. const bG = fileGraphScore.get(b[0]) ?? 0;
  3864. if (Math.abs(aG - bG) > maxGraph * 0.01) return bG - aG;
  3865. const aHits = fileTermHits.get(a[0]) ?? 0;
  3866. const bHits = fileTermHits.get(b[0]) ?? 0;
  3867. if (aHits !== bHits) return bHits - aHits;
  3868. const aLow = isLowValue(aPath);
  3869. const bLow = isLowValue(bPath);
  3870. if (aLow !== bLow) return aLow ? 1 : -1;
  3871. // Deprioritize generated source (.pb.go / .pulsar.go / _mocks.go / …) —
  3872. // the agent rarely needs to see the protobuf scaffold or gomock output
  3873. // when asking about the actual flow, and dumping their bodies inflates
  3874. // the response (the cosmos Q3 explore otherwise leads with
  3875. // `expected_keepers_mocks.go`, displacing the real `tally.go` content
  3876. // and forcing the agent to Read tally.go anyway). Both this and the
  3877. // low-value key above are now BACKSTOPS: `rankPenalty` has already scaled
  3878. // the score and the graph mass these files reach this comparison with, so
  3879. // a generated file no longer outranks a hand-written one just by scoring
  3880. // higher (#1500). This still settles the exact ties the penalty leaves.
  3881. const aGen = isGeneratedCandidate(a[0]);
  3882. const bGen = isGeneratedCandidate(b[0]);
  3883. if (aGen !== bGen) return aGen ? 1 : -1;
  3884. if (a[1].score !== b[1].score) return b[1].score - a[1].score;
  3885. return b[1].nodes.length - a[1].nodes.length;
  3886. });
  3887. // Step 3: Build relationship map
  3888. const lines: string[] = [
  3889. `**Exploration: ${query}**`,
  3890. '',
  3891. // Curated summary — filled in after the source loop (see below). We do NOT
  3892. // report `subgraph.nodes.size` / `fileGroups.size` here: that's the raw
  3893. // candidate gather, which a broad natural-language query inflates wildly
  3894. // (260 symbols / 124 files on a 636-file repo) even though only a handful
  3895. // render. Reporting the pool read as "260 results to wade through" when the
  3896. // real, correctly-ranked answer is the few files below (#1046).
  3897. '',
  3898. '',
  3899. ];
  3900. const summaryLineIdx = 2;
  3901. // Blast radius (always-on, compact): for the entry symbols, who depends on
  3902. // them + which tests cover them — locations only, no source — so the agent
  3903. // knows what to update/verify before editing without a separate call.
  3904. const blastRadius = this.buildBlastRadiusSection(cg, subgraph);
  3905. if (blastRadius) lines.push(blastRadius);
  3906. // Relationship map — show how symbols connect
  3907. const significantEdges = subgraph.edges.filter(e =>
  3908. e.kind !== 'contains' // skip contains — it's implied by file grouping
  3909. );
  3910. if (budget.includeRelationships && significantEdges.length > 0) {
  3911. lines.push('**Relationships**');
  3912. lines.push('');
  3913. // Group edges by kind for readability
  3914. const byKind = new Map<string, Array<{ source: string; target: string }>>();
  3915. for (const edge of significantEdges) {
  3916. const sourceNode = subgraph.nodes.get(edge.source);
  3917. const targetNode = subgraph.nodes.get(edge.target);
  3918. if (!sourceNode || !targetNode) continue;
  3919. const group = byKind.get(edge.kind) || [];
  3920. group.push({ source: sourceNode.name, target: targetNode.name });
  3921. byKind.set(edge.kind, group);
  3922. }
  3923. for (const [kind, edges] of byKind) {
  3924. const cap = budget.maxEdgesPerRelationshipKind;
  3925. const shown = edges.slice(0, cap);
  3926. lines.push(`**${kind}:**`);
  3927. for (const e of shown) {
  3928. lines.push(`- ${e.source} → ${e.target}`);
  3929. }
  3930. if (edges.length > cap) {
  3931. lines.push(`- ... and ${edges.length - cap} more`);
  3932. }
  3933. lines.push('');
  3934. }
  3935. }
  3936. // Step 4: Read contiguous file sections
  3937. // Compute the flow spine once — used both to prepend the Flow section (below)
  3938. // and to gate adaptive source sizing: files on the spine get full source,
  3939. // off-spine peers skeletonize.
  3940. // The Flow section labels each hop with its branch conditions; that read
  3941. // is synchronous, so the grammars it needs are loaded here, once.
  3942. await warmBranchGuardGrammars();
  3943. const flow = this.buildFlowFromNamedSymbols(cg, matchQuery);
  3944. // Snapshot every ranked candidate's scoring inputs, in final sort order, so
  3945. // the diagnostic can show what each file's share of the envelope was BOUGHT
  3946. // with (score, graph mass, term hits, flags) — not just what it cost.
  3947. if (diag) {
  3948. const kindMix = (nodes: Node[]): string => {
  3949. const counts = new Map<string, number>();
  3950. for (const n of nodes) counts.set(n.kind, (counts.get(n.kind) ?? 0) + 1);
  3951. return [...counts.entries()]
  3952. .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
  3953. .map(([k, c]) => `${k}:${c}`)
  3954. .join(' ');
  3955. };
  3956. sortedFiles.forEach(([fp, group], i) => {
  3957. diag.noteCandidate(fp, {
  3958. rank: i + 1,
  3959. score: group.score,
  3960. graphScore: fileGraphScore.get(fp) ?? 0,
  3961. termHits: fileTermHits.get(fp) ?? 0,
  3962. nodes: group.nodes.length,
  3963. pinned: pinnedSet.has(fp),
  3964. named: namedSeedFiles.has(fp),
  3965. central: centralFiles.has(fp),
  3966. entry: entryFiles.has(fp),
  3967. spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id)),
  3968. lowValue: isLowValue(fp),
  3969. generated: isGeneratedCandidate(fp),
  3970. ambientDeclaration: isAmbientDeclaration(fp),
  3971. penalty: rankPenalty(fp),
  3972. kinds: kindMix(group.nodes),
  3973. });
  3974. });
  3975. }
  3976. // Score-proportional byte allocation (CG-12). Every file's share of the
  3977. // envelope is reserved HERE, before a single byte renders, so the render loop
  3978. // spends a reservation instead of racing for whatever the files above it left.
  3979. const allocation = allocateExploreBudget(
  3980. sortedFiles.map(([fp, group]) => ({
  3981. path: fp,
  3982. score: group.score,
  3983. // A pinned file's bytes are worth full price by definition — the agent
  3984. // asked for the file itself, generated/test or not.
  3985. worth: pinnedSet.has(fp) ? 1 : rankPenalty(fp),
  3986. spine: group.nodes.some((n) => flow.pathNodeIds.has(n.id)),
  3987. pinned: pinnedSet.has(fp),
  3988. })),
  3989. budget,
  3990. maxFiles,
  3991. );
  3992. diag?.setAllocation(allocation.allowances, allocation.cliffed, allocation.cliffAt, allocation.pool);
  3993. // Cliffed files ship as pointers — path, symbols, line numbers — so the agent
  3994. // can name one in a follow-up explore. Rendered below with the other
  3995. // not-shown files, and force-enabled even on tiers that suppress that list:
  3996. // a file we deliberately withheld source for must still be nameable.
  3997. const cliffedFiles = new Set(allocation.cliffed);
  3998. // Polymorphic-sibling detector for adaptive sizing. A class that implements/
  3999. // extends a supertype shared by >= MIN_SIBLINGS classes is one of many
  4000. // INTERCHANGEABLE implementations (OkHttp's 14 `: Interceptor` classes —
  4001. // showing one + the rest as signatures is enough), as opposed to a DISTINCT
  4002. // pipeline step (Excalidraw's `renderStaticScene`, which shares no supertype and
  4003. // must stay full or the agent loses real content). Only off-spine sibling files
  4004. // skeletonize; distinct steps and on-spine files keep full source. Cache
  4005. // supertype→(has ≥N implementers) so this stays a handful of edge queries.
  4006. const MIN_SIBLINGS = 3;
  4007. const siblingSuper = new Map<string, boolean>();
  4008. const isPolymorphicSibling = (nodes: Node[]): boolean => {
  4009. for (const n of nodes) {
  4010. for (const e of cg.getOutgoingEdges(n.id)) {
  4011. if (e.kind !== 'implements' && e.kind !== 'extends') continue;
  4012. let many = siblingSuper.get(e.target);
  4013. if (many === undefined) {
  4014. many = cg.getIncomingEdges(e.target)
  4015. .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
  4016. siblingSuper.set(e.target, many);
  4017. }
  4018. if (many) return true;
  4019. }
  4020. }
  4021. return false;
  4022. };
  4023. // A file that DEFINES a polymorphic supertype (a class/interface with ≥
  4024. // MIN_SIBLINGS implementers) AND co-locates its subclasses is a redundant
  4025. // "family" file — Django's compiler.py holds `SQLCompiler` + its 4 subclasses
  4026. // (SQLInsert/Update/Delete/AggregateCompiler) in 2,266 lines. Such files are
  4027. // huge and read-anyway, so they should STILL skeletonize even when the agent
  4028. // named a method in them: a full one eats ~6.5K of the explore budget (Django
  4029. // is pinned at the 28K cap, truncating), starving the sibling files the agent
  4030. // then Reads. This flag OVERRIDES the named-callable spare below — it does NOT
  4031. // by itself spare a file. (OkHttp's RealCall implements the `Lockable` mixin
  4032. // but defines no ≥3-impl supertype, so the named spare keeps it full.)
  4033. const superMany = new Map<string, boolean>();
  4034. const definesPolymorphicSupertype = (nodes: Node[]): boolean => {
  4035. for (const n of nodes) {
  4036. if (n.kind !== 'class' && n.kind !== 'interface' && n.kind !== 'struct' && n.kind !== 'union'
  4037. && n.kind !== 'trait' && n.kind !== 'protocol' && n.kind !== 'type_alias') continue;
  4038. let many = superMany.get(n.id);
  4039. if (many === undefined) {
  4040. many = cg.getIncomingEdges(n.id)
  4041. .filter((x) => x.kind === 'implements' || x.kind === 'extends').length >= MIN_SIBLINGS;
  4042. superMany.set(n.id, many);
  4043. }
  4044. if (many) return true;
  4045. }
  4046. return false;
  4047. };
  4048. lines.push('**Source Code**');
  4049. lines.push('');
  4050. // Recorded so the drift pass below (#1474) can append a per-file exception
  4051. // to this guarantee after the render loop knows which files drifted.
  4052. const verbatimHeaderIdx = lines.length;
  4053. 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.');
  4054. lines.push('');
  4055. // The response's absolute cap. It MUST stay under the host's inline
  4056. // tool-result limit (~25K chars): above it the result is externalized to a
  4057. // file the agent Reads back (a 35K vscode explore did exactly this in the
  4058. // n=4 A/B).
  4059. const hardCeiling = Math.min(Math.round(budget.maxOutputChars * 1.5), 25000);
  4060. // What the epilogue is OWED — the part of it the loop must not spend (CG-26).
  4061. // Not a flat margin: the old 600 was neither the epilogue's size (1,064 on
  4062. // gin, 2,231 on excalidraw) nor a bound on it, so the loop budgeted for a
  4063. // thing that did not exist and the response then discarded the whole
  4064. // epilogue to fit. The floor is what the epilogue owes the AGENT rather
  4065. // than what it costs us:
  4066. // - the one-line note that says an uncovered area exists (always), and
  4067. // - a pointer for every file whose source was deliberately WITHHELD.
  4068. // A cliffed file's bytes were traded away on the promise that the agent
  4069. // can still name it in a follow-up call (CG-12); if the ceiling then
  4070. // eats that name the trade was a silent drop.
  4071. // Everything above the floor — the rest of the pointer list, the reminders
  4072. // — is elastic and fitted to the room that is actually left, at the end of
  4073. // this method. Sized from the REAL strings, never tuned: a constant swept
  4074. // against the suite is what CG-30's record warns about.
  4075. const cliffPointerFloor = [...cliffedFiles]
  4076. .slice(0, POINTER_MAX_FILES)
  4077. .reduce((n, fp) => {
  4078. const g = fileGroups.get(fp);
  4079. return g ? n + pointerLineFor(fp, g.nodes).length + 1 : n;
  4080. }, cliffedFiles.size > 0 ? POINTER_HEADER.length + 2 : 0);
  4081. const epilogueFloor = EPILOGUE_LOST_NOTE.length + 2 + cliffPointerFloor;
  4082. // Absolute stop for the render loop. Reservations already fit the envelope, so
  4083. // this only catches their bounded overshoot (the whole-file grace, an oversize
  4084. // first cluster) — and catches it HERE, where a file can be skipped cleanly and
  4085. // a later one still render, instead of at the final truncation, which lops off
  4086. // whichever section happened to land last.
  4087. const renderCeiling = hardCeiling - epilogueFloor;
  4088. // `flow.text` is PART of the response — it is prepended to `lines` to make
  4089. // the final output — so the render loop has to spend against it, and it
  4090. // never did. Counting it is what makes `renderCeiling` the ceiling it
  4091. // claims to be: without it the loop believed it had room for a trailing
  4092. // section the final truncation then threw away whole, and (CG-31) the
  4093. // displacement guard dutifully held bytes back to pay for that section —
  4094. // taking them off a file the agent DOES receive and handing them to one it
  4095. // never sees.
  4096. let totalChars = flow.text.length + lines.join('\n').length;
  4097. let filesIncluded = 0;
  4098. // Paths we actually render source for below. Drives the curated header count
  4099. // (#1046) — it must reflect what we show, not the raw candidate gather.
  4100. const renderedFilePaths: string[] = [];
  4101. let anyFileTrimmed = false;
  4102. // Files that changed on disk after their last index sync (#1474). Their
  4103. // indexed line ranges are untrustworthy, so sliced renders (adaptive /
  4104. // skeleton / clusters) are OFF for them: a small drifted file still ships
  4105. // whole (current bytes, correct by construction → staleRendered), a big one
  4106. // is omitted with an explicit notice (→ staleOmitted) — honest absence
  4107. // instead of a different symbol's code under the requested name.
  4108. const staleRendered: string[] = [];
  4109. const staleOmitted: string[] = [];
  4110. // Anti-abandonment hold-back (CG-18). The first file dedup suppressed
  4111. // ENTIRELY, kept with its real section so it can be put back if the loop
  4112. // ends with no new source anywhere. A response made only of pointers is the
  4113. // shape that reads as "codegraph has nothing" — and one such response early
  4114. // in a session is enough to make an agent stop calling the tool at all — so
  4115. // the highest-ranked suppressed file is restored rather than risk it. It
  4116. // costs a re-serve of one file, on the one call shape where dedup would
  4117. // otherwise have saved everything: the safe direction.
  4118. type SuppressedFallback = {
  4119. filePath: string;
  4120. /** Index in `lines` where this file's pointer block starts. */
  4121. at: number;
  4122. /** How many `lines` entries the pointer block occupies. */
  4123. replacing: number;
  4124. /** The full, undeduped section to splice back in. */
  4125. section: string[];
  4126. sourceChars: number;
  4127. overhead: number;
  4128. ranges: ExploreLineRange[];
  4129. fingerprint: string;
  4130. };
  4131. let suppressedFallback: SuppressedFallback | null = null;
  4132. // Reservation carry-forward (CG-21). A reservation is a promise the render
  4133. // loop has to KEEP, not a cap it may quietly under-use: a file that cannot
  4134. // spend what it was given — thin matched-symbol set, unreadable, drifted off
  4135. // disk, skipped for the ceiling — must hand the difference DOWN the rank
  4136. // order, not drop it. Tracked as two running totals rather than a `spent`
  4137. // variable threaded through the dozen `continue`s below, so no exit path can
  4138. // forget to account: everything the loop has PROMISED so far, and everything
  4139. // it has actually EMITTED. Their gap is the slack the next file may add to
  4140. // its own reservation.
  4141. //
  4142. // Symmetric on the other side: a whole-file buy that overshoots makes
  4143. // `sourceSpent` outrun `reservedSoFar`, which suppresses slack until a later
  4144. // under-spend covers the debt. So the pool is conserved in both directions,
  4145. // and no file is ever cut BELOW the reservation it was promised.
  4146. let reservedSoFar = 0;
  4147. let sourceSpent = 0;
  4148. // Funding line for the whole-file BUY rule: the response's SOURCE may reach
  4149. // everything the allocator promised plus one bounded overshoot, and no more.
  4150. // Measured against the promise rather than `renderCeiling` on purpose — the
  4151. // ceiling sits 50% above the envelope and says nothing about who is owed
  4152. // what, so funding a buy from it just moves the shortfall to whichever file
  4153. // the loop reaches last. See WHOLE_FILE_BUY_OVERSHOOT_FRACTION.
  4154. const reservedTotal = [...allocation.allowances.values()].reduce((sum, n) => sum + n, 0);
  4155. const sourceCeiling = reservedTotal + Math.round(
  4156. budget.maxOutputChars * EXPLORE_ALLOCATION.WHOLE_FILE_BUY_OVERSHOOT_FRACTION,
  4157. );
  4158. /**
  4159. * What a file's section costs BESIDES its source, in render space: the
  4160. * header (path + up to `maxSymbolsInFileHeader` symbol names) plus the code
  4161. * fence and the blank lines around them (CG-26).
  4162. *
  4163. * `EXPLORE_ALLOCATION.FILE_OVERHEAD` is the ALLOCATOR's constant — the flat
  4164. * 200 it charges each admitted file when it splits the envelope — and using
  4165. * it here too was a category error worth ~250 chars per pending file: the
  4166. * render loop then held back a file's reservation but not the header that
  4167. * reservation has to arrive under, so the last admitted file was left just
  4168. * short of the room it needed and skipped whole. Estimated from the file's
  4169. * own candidate symbols, which is what the header is actually built from.
  4170. */
  4171. const overheadCache = new Map<string, number>();
  4172. const sectionOverhead = (filePath: string, nodes: readonly Node[]): number => {
  4173. const hit = overheadCache.get(filePath);
  4174. if (hit !== undefined) return hit;
  4175. const names = [...new Set(
  4176. nodes.filter((n) => n.kind !== 'import' && n.kind !== 'export')
  4177. .map((n) => `${n.name}(${n.kind})`),
  4178. )].slice(0, budget.maxSymbolsInFileHeader);
  4179. // header + blank, then ```lang / body / ``` / blank around the source.
  4180. const cost = fileSectionHeader(filePath, names.join(', ')).length + 2
  4181. + (nodes[0]?.language?.length ?? 0) + 11;
  4182. overheadCache.set(filePath, cost);
  4183. return cost;
  4184. };
  4185. /**
  4186. * How much of what is still owed BELOW `fileIndex` the response can actually
  4187. * still PAY, in render-space chars (CG-31).
  4188. *
  4189. * Not the same as the sum of those reservations. The allocator splits the
  4190. * envelope; the render loop spends against a ceiling that also has to hold
  4191. * the response's own prose, so on a saturated response the promises are
  4192. * OVER-SUBSCRIBED and the tail is going to be dropped whatever happens
  4193. * above it. Bytes held back for a file that then gets dropped are bytes
  4194. * nobody ever receives — measured on django, holding the full owed sum cost
  4195. * the rank-#1 file 2,126 chars and handed them to a rank-#6 section the
  4196. * hard ceiling threw away. So walk the remaining files in RANK order and
  4197. * hold back only the prefix that fits `budgetLeft`; the first one that does
  4198. * not fit ends it, because everything after it is further out of reach.
  4199. *
  4200. * Conservative and self-correcting: it assumes each file below spends its
  4201. * whole reservation, and when they do not, the carry-forward hands the
  4202. * difference to whoever comes next anyway.
  4203. */
  4204. const owedPayableBelow = (fileIndex: number, budgetLeft: number): number => {
  4205. let held = 0;
  4206. for (let j = fileIndex + 1; j < sortedFiles.length; j++) {
  4207. const path = sortedFiles[j]![0];
  4208. const r = allocation.allowances.get(path);
  4209. if (r === undefined) continue;
  4210. const overhead = sectionOverhead(path, sortedFiles[j]![1].nodes);
  4211. const need = r + overhead;
  4212. if (held + need > budgetLeft) {
  4213. // PART of a reservation is still a delivered file (CG-26). Holding
  4214. // all-or-nothing zeroed the last admitted file whenever its full
  4215. // reservation no longer fit: on the precise-query fixture the rank-5
  4216. // file took 4,134 chars against a 2,948 reservation while rank 6 —
  4217. // admitted, reserved 2,539 — was left 4 chars and skipped. Hold the
  4218. // remainder instead, but only while it is still worth a section:
  4219. // under MIN_CHARS a slice cannot hold one complete method, and a
  4220. // fragment forces the Read this tool exists to prevent.
  4221. const partial = budgetLeft - held;
  4222. if (partial >= EXPLORE_ALLOCATION.MIN_CHARS + overhead) held += partial;
  4223. break;
  4224. }
  4225. held += need;
  4226. }
  4227. return held;
  4228. };
  4229. for (let fileIndex = 0; fileIndex < sortedFiles.length; fileIndex++) {
  4230. const [filePath, group] = sortedFiles[fileIndex]!;
  4231. if (filesIncluded >= maxFiles) {
  4232. if (diag) for (const [fp] of sortedFiles) diag.recordSkip(fp, 'max-files');
  4233. break;
  4234. }
  4235. // Below the relevance cliff: no source, no `maxFiles` slot. It is still
  4236. // named — with its matched symbols and their line numbers — in the
  4237. // not-shown list, so one follow-up explore fetches it in full.
  4238. if (cliffedFiles.has(filePath)) {
  4239. diag?.recordSkip(filePath, 'cliff');
  4240. continue;
  4241. }
  4242. // This file's reserved share of the envelope. Every render path below is
  4243. // bounded by it instead of by the flat per-file cap, which is what stops
  4244. // allocation from following file size: a small weakly-relevant file no
  4245. // longer ships whole while the strongly-relevant one is clipped.
  4246. const reserved = allocation.allowances.get(filePath);
  4247. if (reserved === undefined) {
  4248. diag?.recordSkip(filePath, 'max-files');
  4249. continue;
  4250. }
  4251. // What this file may actually spend: its own reservation PLUS whatever the
  4252. // files above it left on the table. Every render bound below reads this,
  4253. // never `reserved` — that is what makes the carry-forward reach the render
  4254. // paths instead of being bookkeeping. Slack flows to the next file in RANK
  4255. // order because that is the only file a single-pass loop can still pay;
  4256. // `MAX_SHARE` keeps that from turning a weak tail file into the response,
  4257. // so the allocator's share ceiling holds end-to-end and not just at
  4258. // reservation time.
  4259. const allowance = Math.min(
  4260. reserved + Math.max(0, reservedSoFar - sourceSpent),
  4261. Math.max(reserved, Math.round(budget.maxOutputChars * EXPLORE_ALLOCATION.MAX_SHARE)),
  4262. );
  4263. reservedSoFar += reserved;
  4264. diag?.recordSpendable(filePath, allowance);
  4265. // DISPLACEMENT GUARD, in render space (CG-31). `allowance` says what this
  4266. // file MAY spend; it does not say the bytes are still there to spend. The
  4267. // hard ceiling is shared with every file the loop has not reached yet, and
  4268. // their reservations are promises the allocator already made — so what is
  4269. // left before the ceiling is not all ours. Holding that back is the same
  4270. // inequality the whole-file BUY arm enforces with `owedBelow` (see below),
  4271. // moved into the units the cluster path actually spends in: source PLUS
  4272. // the per-section overhead each pending file will charge.
  4273. //
  4274. // Held back only where it can be PAID — see `owedPayableBelow`. A promise
  4275. // the ceiling cannot reach is not a claim on this file's bytes; honouring
  4276. // it anyway just moves source from a file the agent gets to one it does
  4277. // not.
  4278. //
  4279. // Floored at this file's OWN reservation, never below: a kept promise is
  4280. // not a displacement, and cutting a file under what it earned is the
  4281. // failure this whole allocation layer exists to prevent.
  4282. //
  4283. // Slack still reaches the file: a file above that under-spends leaves
  4284. // `totalChars` lower, which raises `headroom` one-for-one, so the
  4285. // carry-forward the `allowance` line grants is exactly the carry-forward
  4286. // this bound funds.
  4287. const headroom = Math.max(0, renderCeiling - totalChars - sectionOverhead(filePath, group.nodes));
  4288. const fundedHeadroom = Math.max(
  4289. Math.min(reserved, headroom),
  4290. headroom - owedPayableBelow(fileIndex, Math.max(0, headroom - reserved)),
  4291. );
  4292. diag?.recordFunded(filePath, fundedHeadroom);
  4293. const absPath = validatePathWithinRoot(projectRoot, filePath);
  4294. if (!absPath || !existsSync(absPath)) {
  4295. diag?.recordSkip(filePath, 'unreadable');
  4296. continue;
  4297. }
  4298. let fileContent: string;
  4299. try {
  4300. fileContent = readFileSync(absPath, 'utf-8');
  4301. } catch {
  4302. diag?.recordSkip(filePath, 'unreadable');
  4303. continue;
  4304. }
  4305. const fileLines = fileContent.split('\n');
  4306. const lang = group.nodes[0]?.language || '';
  4307. const withLineNumbers = exploreLineNumbersEnabled();
  4308. // Language-neutral separator between two non-contiguous slices of one file
  4309. // (no `//` — not a comment in Python, Ruby, etc.). With line numbers on,
  4310. // the line-number jump also signals the gap.
  4311. const GAP_MARKER = '\n\n... (gap) ...\n\n';
  4312. // Full file index — not just the relevance-gathered `group.nodes`. A trim
  4313. // often drops filler symbols that never scored into the gather set; naming
  4314. // those holes still needs their defs (#1711).
  4315. const fileIndexNodes = cg.getNodesInFile(filePath);
  4316. // Cross-call dedup (CG-18). `served` is what THIS session already sent the
  4317. // agent for THIS file, and it is empty unless the file still hashes to the
  4318. // bytes those spans were sliced from — an edit between calls means the
  4319. // agent's copy is wrong, so nothing is withheld. Every render path below
  4320. // routes its spans through `dedupeSpans`, which is the only place a span
  4321. // is ever dropped.
  4322. const fingerprint = fileFingerprint(fileContent);
  4323. const served = dedupEnabled ? servedRangesForFile(priorCalls, filePath, fingerprint) : [];
  4324. /** Render one line span exactly as the render paths do. */
  4325. const renderSpan = (r: ExploreLineRange): string => {
  4326. const slice = fileLines.slice(r.start - 1, r.end).join('\n');
  4327. return withLineNumbers ? numberSourceLines(slice, r.start) : slice;
  4328. };
  4329. /**
  4330. * Apply the session history to a set of spans-with-text. A span the agent
  4331. * already holds is dropped and reported in `covered`; a partially-held one
  4332. * is re-rendered down to its new lines. Text is rebuilt from the surviving
  4333. * spans rather than sliced out of the original string — the spans ARE the
  4334. * contract with the session record, so rebuilding from them is what keeps
  4335. * what we claim to have sent and what we sent the same thing.
  4336. */
  4337. const dedupeSpans = (
  4338. parts: ReadonlyArray<{ range: ExploreLineRange; text: string }>,
  4339. ): { parts: Array<{ range: ExploreLineRange; text: string }>; covered: ExploreLineRange[] } => {
  4340. if (served.length === 0) return { parts: [...parts], covered: [] };
  4341. const kept: Array<{ range: ExploreLineRange; text: string }> = [];
  4342. const covered: ExploreLineRange[] = [];
  4343. for (const part of parts) {
  4344. const split = dedupeRange(part.range, served);
  4345. if (split.covered.length === 0) {
  4346. kept.push(part);
  4347. continue;
  4348. }
  4349. covered.push(...split.covered);
  4350. for (const r of split.emit) kept.push({ range: r, text: renderSpan(r) });
  4351. }
  4352. return { parts: kept, covered: mergeRanges(covered) };
  4353. };
  4354. const coveredChars = (spans: ReadonlyArray<ExploreLineRange>): number =>
  4355. spans.reduce((sum, r) => sum + fileLines.slice(r.start - 1, r.end).join('\n').length, 0);
  4356. /**
  4357. * Emit one file's section — header, the back-reference for whatever the
  4358. * agent already holds, and the fence for what is new. Every render path
  4359. * ends here so that the dedup bookkeeping (freed bytes, freed `maxFiles`
  4360. * slot, the session record, the diagnostic) is written in exactly one
  4361. * place and no path can forget a piece of it.
  4362. *
  4363. * A fully-held file emits its header and pointer and NO fence, and
  4364. * deliberately does not consume a `maxFiles` slot: that is half of where
  4365. * the reclaimed budget goes (the other half is `sourceSpent`, which the
  4366. * carry-forward pool hands down the rank order). Both send bytes to files
  4367. * the agent has NOT seen, which is the whole point.
  4368. */
  4369. const emitFileSection = (opts: {
  4370. header: string;
  4371. /** Deduped source. Empty ⇒ the agent already holds all of it. */
  4372. body: string;
  4373. /** Spans `body` covers. */
  4374. ranges: ExploreLineRange[];
  4375. /** Spans replaced by the back-reference. */
  4376. covered: ExploreLineRange[];
  4377. /**
  4378. * Chars charged on top of the body by the ANTI-ABANDONMENT RESTORE path
  4379. * only (it re-splices a section after the loop and needs one number for
  4380. * it). The loop itself charges the real cost — see `sectionCost`.
  4381. */
  4382. overhead: number;
  4383. mode: 'whole' | 'clusters' | 'focused' | 'skeleton';
  4384. clipped: boolean;
  4385. /** The undeduped render, kept for the no-new-source fallback. */
  4386. fullBody: string;
  4387. fullRanges: ExploreLineRange[];
  4388. }): void => {
  4389. // A remainder too small to be worth a fence is folded into the pointer
  4390. // (see MIN_DELTA_CHARS). Its ranges are then NOT recorded — the record
  4391. // must only ever claim source that was actually sent.
  4392. const folded = opts.covered.length > 0 && opts.body.length < EXPLORE_DEDUP.MIN_DELTA_CHARS;
  4393. const body = folded ? '' : opts.body;
  4394. const ranges = folded ? [] : opts.ranges;
  4395. const at = lines.length;
  4396. lines.push(opts.header, '');
  4397. // Charge what the section ACTUALLY costs, not a flat 200 (CG-26). A
  4398. // header carries the path plus up to `maxSymbolsInFileHeader` symbol
  4399. // names and routinely runs 300–500 chars, so the flat charge made the
  4400. // loop believe it had room it did not have: okhttp rendered 26,601
  4401. // chars against a 24,400 ceiling and the final truncation threw a
  4402. // fully-rendered section away. Everything downstream is expressed in
  4403. // these units — `headroom`, `fundedHeadroom`, every fit test — so an
  4404. // under-count is not a rounding error, it funds a promise out of bytes
  4405. // that do not exist and starves whoever the loop reaches last.
  4406. totalChars += opts.header.length + 2;
  4407. if (opts.covered.length > 0) {
  4408. const pointer = formatBackReference(
  4409. filePath,
  4410. opts.covered,
  4411. symbolsInSpans(group.nodes, opts.covered),
  4412. { partial: body.length > 0 },
  4413. );
  4414. lines.push(pointer, '');
  4415. totalChars += pointer.length + 2;
  4416. backReferencedFiles.push(filePath);
  4417. }
  4418. if (body.length > 0) {
  4419. lines.push('```' + lang, body, '```', '');
  4420. // ```lang \n body \n ``` \n '' \n — exact, same as the header above.
  4421. totalChars += body.length + lang.length + 11;
  4422. sourceSpent += body.length;
  4423. newSourceChars += body.length;
  4424. diag?.recordRender(filePath, opts.mode, body.length, opts.clipped || opts.covered.length > 0);
  4425. if (opts.covered.length > 0) diag?.recordDedup(filePath, coveredChars(opts.covered), opts.covered);
  4426. noteEmitted(filePath, [...ranges, ...opts.covered], body.length, fingerprint);
  4427. renderedFilePaths.push(filePath);
  4428. filesIncluded++;
  4429. return;
  4430. }
  4431. // Fully held. The section is the pointer; the slot and the bytes go to a
  4432. // file the agent has not seen. The spans are still recorded (at zero
  4433. // bytes) because the record means "source the agent HAS", not "bytes
  4434. // this call spent" — refreshing them keeps a long session from ageing
  4435. // them out of the retained window and re-serving them for nothing.
  4436. // (The header is already charged above; a fully-held section is the
  4437. // header plus the pointer and nothing else.)
  4438. diag?.recordRender(filePath, 'backref', 0, false);
  4439. diag?.recordDedup(filePath, coveredChars(opts.covered), opts.covered);
  4440. noteEmitted(filePath, opts.covered, 0, fingerprint);
  4441. renderedFilePaths.push(filePath);
  4442. if (!suppressedFallback && opts.fullBody.length > 0) {
  4443. suppressedFallback = {
  4444. filePath,
  4445. at,
  4446. replacing: lines.length - at,
  4447. section: [opts.header, '', '```' + lang, opts.fullBody, '```', ''],
  4448. sourceChars: opts.fullBody.length,
  4449. overhead: opts.overhead,
  4450. ranges: opts.fullRanges,
  4451. fingerprint,
  4452. };
  4453. }
  4454. };
  4455. // Disk-drift gate (#1474): every render branch below except whole-file
  4456. // slices fileContent (CURRENT bytes) at INDEXED line ranges. Content is
  4457. // already in hand, so the check costs one stat (hash only on mismatch).
  4458. const fileStale = this.isFileStaleOnDisk(cg, filePath, fileContent);
  4459. // Adaptive sizing (CODEGRAPH_ADAPTIVE_EXPLORE, default on): collapse a file
  4460. // to a per-symbol view when it's a redundant member of a polymorphic family.
  4461. // Engages iff ALL hold:
  4462. // 1. a flow spine exists,
  4463. // 2. no symbol in the file is on that spine (it's not the mechanism path),
  4464. // 3. it IS a polymorphic sibling (≥ MIN_SIBLINGS impls of a shared supertype),
  4465. // 4. it is NOT SPARED, where a file is spared iff the agent named a
  4466. // (near-)UNIQUE callable in it (`getResponseWithInterceptorChain`, 1 def →
  4467. // keep RealCall.kt full) UNLESS the file DEFINES the family supertype (a
  4468. // base+subclasses "family" file like Django's compiler.py — collapse it).
  4469. // Uniqueness matters: `as_sql` has 110 defs across every Compiler/Expression
  4470. // subclass; naming it must NOT keep every backend variant + test file full
  4471. // and flood the budget. That's why the spare reads uniqueNamedNodeIds.
  4472. // Within a collapsed file the render is PER-SYMBOL (condition B): a method the
  4473. // agent NAMED or that's on the spine is shown with its FULL body (so the agent
  4474. // doesn't Read the file back for it — Django's SQLCompiler.execute_sql/as_sql);
  4475. // every other symbol is just its signature. So the base mechanism survives while
  4476. // the file's other ~80 symbols + the redundant subclasses collapse to one line each.
  4477. const spareNamed = group.nodes.some(n => flow.uniqueNamedNodeIds.has(n.id));
  4478. const fileDefinesSuper = definesPolymorphicSupertype(group.nodes);
  4479. const spared = spareNamed && !fileDefinesSuper;
  4480. const CALLABLE_BODY = new Set(['method', 'function', 'constructor', 'component']);
  4481. const hasSpineNode = group.nodes.some(n => flow.pathNodeIds.has(n.id));
  4482. // On-spine god-file: the flow path runs THROUGH this file, but it also holds
  4483. // many OTHER named methods, and rendering all of them in full blows the
  4484. // per-file budget and starves the other flow files (Alamofire: the agent
  4485. // names ~7 Session.swift methods — the build spine PLUS off-path
  4486. // task/didCompleteTask — far past the whole response budget). Engage the
  4487. // per-symbol view to keep the SPINE full and collapse the off-path named
  4488. // methods to signatures. Only when there IS off-path content to shed —
  4489. // otherwise the spine is irreducible (a sequential flow has no redundancy),
  4490. // so leave it to the normal full render.
  4491. const namedBodyChars = group.nodes
  4492. .filter(n => CALLABLE_BODY.has(n.kind) && (flow.pathNodeIds.has(n.id) || flow.uniqueNamedNodeIds.has(n.id)))
  4493. .reduce((s, n) => s + fileLines.slice(n.startLine - 1, n.endLine).join('\n').length, 0);
  4494. const onSpineGodFile = hasSpineNode
  4495. && namedBodyChars > allowance
  4496. && group.nodes.some(n => CALLABLE_BODY.has(n.kind) && flow.uniqueNamedNodeIds.has(n.id) && !flow.pathNodeIds.has(n.id));
  4497. if (!fileStale && adaptiveExploreEnabled() && flow.pathNodeIds.size > 0
  4498. && (onSpineGodFile || (!hasSpineNode && isPolymorphicSibling(group.nodes) && !spared))) {
  4499. const syms = group.nodes
  4500. .filter(n => n.kind !== 'import' && n.kind !== 'export' && n.startLine > 0)
  4501. .sort((a, b) => a.startLine - b.startLine);
  4502. // Pass 1: choose which symbols get a FULL body, by priority, greedily within
  4503. // a per-file body cap — so one huge family file can't body every named method
  4504. // and crowd out the other flow files (Django's query.py). A symbol earns a
  4505. // body if it's on-spine, or UNIQUELY named (`SQLCompiler.execute_sql`), or a
  4506. // co-named method WHEN this file DEFINES the family supertype (so the base
  4507. // `SQLCompiler.as_sql` body shows, but the 110 leaf `as_sql` overrides — and
  4508. // OkHttp's 5 `intercept`s if the agent names `intercept` — stay signatures).
  4509. const prio = (n: Node) => !CALLABLE_BODY.has(n.kind) ? 99
  4510. : flow.pathNodeIds.has(n.id) ? 0
  4511. : flow.uniqueNamedNodeIds.has(n.id) ? 1
  4512. : (fileDefinesSuper && flow.namedNodeIds.has(n.id)) ? 2 : 99;
  4513. // One WINDOW per file, sized by this file's RESERVATION. syms are taken by
  4514. // priority (spine first, then uniquely-named, then family-base), and the cap
  4515. // applies to ALL of them — including the spine — so a big-spine god-file
  4516. // (tokio's worker.rs: run→run_task→next_task→steal_work) can't eat the whole
  4517. // response and starve the co-flow file (harness.rs's poll). The native agent
  4518. // windows such a file too (~190 lines at a time), so this mimics, not
  4519. // truncates. Always emit ≥1 (never an empty section).
  4520. //
  4521. // Held to `fundedHeadroom` as well (CG-31) so this path cannot spend a
  4522. // reservation still owed below it either. It never exceeds `allowance`
  4523. // today, so the bound only bites once the ceiling is genuinely tight —
  4524. // but "every render path" has to mean every one, or the guard is just a
  4525. // detour the next god-file takes.
  4526. const bodyCap = Math.min(allowance, fundedHeadroom);
  4527. const bodyIds = new Set<string>();
  4528. let bodyChars = 0;
  4529. for (const n of syms.filter(n => prio(n) < 99 && n.endLine >= n.startLine).sort((a, b) => prio(a) - prio(b))) {
  4530. const sz = fileLines.slice(n.startLine - 1, n.endLine).join('\n').length;
  4531. if (bodyChars + sz > bodyCap && bodyIds.size > 0) continue;
  4532. bodyIds.add(n.id);
  4533. bodyChars += sz;
  4534. }
  4535. // Pass 2: render in line order — full body for chosen symbols, else the
  4536. // signature line (capped, with a "+N more" tail so the structure map of a
  4537. // god-file doesn't itself bloat the budget).
  4538. const skel: Array<{ range: ExploreLineRange; text: string }> = [];
  4539. let coveredUntil = 0; // skip symbols already inside an emitted body
  4540. let sigCount = 0, sigDropped = 0;
  4541. const SIG_MAX = Math.max(12, budget.maxSymbolsInFileHeader * 2);
  4542. for (const n of syms) {
  4543. if (n.startLine <= coveredUntil) continue;
  4544. if (bodyIds.has(n.id)) {
  4545. const end = n.endLine;
  4546. const body = fileLines.slice(n.startLine - 1, end).join('\n');
  4547. skel.push({
  4548. range: { start: n.startLine, end },
  4549. text: withLineNumbers ? numberSourceLines(body, n.startLine) : body,
  4550. });
  4551. coveredUntil = end;
  4552. } else {
  4553. // Elide the body, emit the signature. node.startLine can point at a
  4554. // decorator/annotation, so scan forward for the line that names the symbol.
  4555. let lineNo = n.startLine;
  4556. for (let k = 0; k < 4; k++) {
  4557. if ((fileLines[n.startLine - 1 + k] || '').includes(n.name)) { lineNo = n.startLine + k; break; }
  4558. }
  4559. if (lineNo <= coveredUntil) continue;
  4560. if (sigCount >= SIG_MAX) { sigDropped++; continue; }
  4561. const sig = (fileLines[lineNo - 1] || '').trim();
  4562. if (sig) {
  4563. skel.push({
  4564. range: { start: lineNo, end: lineNo },
  4565. text: withLineNumbers ? `${lineNo}\t${sig}` : sig,
  4566. });
  4567. sigCount++;
  4568. }
  4569. }
  4570. }
  4571. const sigTail = sigDropped > 0 ? `… +${sigDropped} more (signatures elided)` : '';
  4572. if (skel.length > 0) {
  4573. const names = [...new Set(group.nodes.filter(n => n.kind !== 'import' && n.kind !== 'export').map(n => n.name))]
  4574. .slice(0, budget.maxSymbolsInFileHeader).join(', ');
  4575. // Steer the agent to codegraph_explore for an elided body — NEVER to
  4576. // Read. The old "Read for more" / "Read for a full body" tags invited
  4577. // a Read of the very file just skeletonized; on a central, wanted file
  4578. // (Session.swift, DataRequest.swift) that fired an over-investigation
  4579. // spiral (the agent Read the skeletonized file, then kept digging).
  4580. // CLAUDE.md: explore output must never tell the agent to Read.
  4581. const tag = bodyIds.size > 0
  4582. ? 'focused (the methods you named in full, the rest as signatures — codegraph_explore a signature by name for its body; do NOT Read)'
  4583. : 'skeleton (signatures only — codegraph_explore a name for its full body; do NOT Read)';
  4584. // Dedup runs on the per-symbol parts, so a body the agent already has
  4585. // becomes a pointer while the signature map around it survives intact
  4586. // (a one-line signature is far under MIN_COVERED_LINES and is never
  4587. // withheld — the structure map is what makes this render legible).
  4588. const dd = dedupeSpans(skel);
  4589. const withTail = (parts: ReadonlyArray<{ text: string }>) =>
  4590. [...parts.map((p) => p.text), ...(sigTail ? [sigTail] : [])].join('\n');
  4591. emitFileSection({
  4592. header: fileSectionHeader(filePath, `${names} · ${tag}`),
  4593. body: dd.parts.length > 0 ? withTail(dd.parts) : '',
  4594. ranges: dd.parts.map((p) => p.range),
  4595. covered: dd.covered,
  4596. overhead: 120,
  4597. mode: bodyIds.size > 0 ? 'focused' : 'skeleton',
  4598. // Always "clipped": the per-symbol view elides bodies by construction.
  4599. clipped: true,
  4600. fullBody: withTail(skel),
  4601. fullRanges: skel.map((p) => p.range),
  4602. });
  4603. continue;
  4604. }
  4605. }
  4606. // Whole-file rule: if a relevant file is small enough to afford, return it
  4607. // ENTIRELY instead of clustering. Clustering exists to tame god-files
  4608. // (App.tsx ~13k lines); on a ~134-line component a cluster is a lossy
  4609. // subset of a file the agent will just Read in full anyway — costing a
  4610. // round-trip and a re-read every later turn. Reserve clustering for files
  4611. // too big to ship whole. Still bounded by the total maxOutputChars check.
  4612. //
  4613. // CENTRAL files (where the query's entry points live) get a larger — but
  4614. // bounded — ceiling: they're the heart of the answer, the file(s) the agent
  4615. // would Read whole, so a genuinely small one comes back whole rather than as
  4616. // thin clusters. A LARGE central file (the 791-line org-user store) exceeds
  4617. // the ceiling and falls through to sectioning/clustering below — full method
  4618. // bodies + signatures — so we never dump (or overflow on) a whole god-file.
  4619. const isCentralFile = centralFiles.has(filePath);
  4620. // A file ships whole when it fits its RESERVATION (plus a small grace — see
  4621. // WHOLE_FILE_GRACE). This is the site of the #1500 allocation bug: the
  4622. // peripheral bound used to be a flat `maxCharsPerFile * 3`, so ANY file under
  4623. // ~11K shipped its entire contents regardless of relevance, while a
  4624. // high-scoring file too big for that window was clipped to `maxCharsPerFile`
  4625. // — a 3x swing decided by file size alone. Tying both bounds to the
  4626. // reservation removes the swing without touching the rule's purpose (a small
  4627. // file sliced is a lossy subset the agent just Reads in full anyway).
  4628. const WHOLE_FILE_MAX_LINES = isCentralFile ? 280 : 220;
  4629. // Two bounds, whichever is larger (CG-21):
  4630. // GRACE — the reservation plus a sliver, for a file that essentially fits;
  4631. // BUY — the reservation already covers most of the file, so the rest is
  4632. // cheaper to ship than to lose. A file between the two used to
  4633. // fall through to clustering and then spend a FRACTION of its
  4634. // reservation, and the remainder was neither delivered nor
  4635. // redistributed. See WHOLE_FILE_BUY_FRACTION.
  4636. //
  4637. // The BUY arm is two independent tests, and keeping them apart is the whole
  4638. // design. MERIT reads `reserved` — did THIS file's own relevance earn most
  4639. // of itself? — so borrowed slack can never promote a weak file to whole.
  4640. // FUNDING reads the shared overshoot pool, so the bytes exist to pay for it.
  4641. // Slack still reaches the file through `allowance`: it raises the GRACE arm
  4642. // and shrinks what a buy has to borrow.
  4643. const graceBound = allowance + Math.min(
  4644. EXPLORE_ALLOCATION.WHOLE_FILE_GRACE_MAX,
  4645. Math.round(allowance * EXPLORE_ALLOCATION.WHOLE_FILE_GRACE_FRACTION),
  4646. );
  4647. // FUNDING, as one inequality: after this file ships whole, does the source
  4648. // still fit the promise-plus-overshoot line WITH every reservation below
  4649. // it left payable? `owedBelow` is what makes it a displacement guard
  4650. // rather than a size cap — a buy that fits the line only by spending a
  4651. // lower-ranked file's reservation is the trade that dropped
  4652. // `payslip_builder.go`, and it is refused here. Self-limiting: each buy
  4653. // grows `sourceSpent`, so the pool cannot be spent twice. The cluster path
  4654. // below enforces the same inequality in render space — see
  4655. // `fundedHeadroom` / `owedPayableBelow` (CG-31).
  4656. const owedBelow = Math.max(0, reservedTotal - reservedSoFar);
  4657. // Third condition on the BUY arm only: it must also FIT. A whole render
  4658. // that overruns the ceiling is skipped ENTIRELY (the branch refuses to
  4659. // slice a file mid-method), so attempting a buy that cannot fit trades a
  4660. // clustered section for NO section — the same trade the funding pool
  4661. // exists to refuse, arriving by a different route. Failing the test here
  4662. // instead drops through to the cluster path, which is bounded by
  4663. // `fundedHeadroom` and always renders something.
  4664. //
  4665. // Measured against `fundedHeadroom`, not against `renderCeiling - totalChars`
  4666. // (CG-26). The two differ by exactly the displacement term: room before
  4667. // the ceiling belongs to every file the loop has not reached yet, and
  4668. // this arm used to read the raw room while its source-space sibling
  4669. // (`owedBelow`, above) refused the same trade. Source-space alone was not
  4670. // enough — the funding line is `reservedTotal + 0.15 * envelope` (~27.2K
  4671. // when a medium repo saturates) while the render ceiling is ~24.2K, so a
  4672. // buy can clear `sourceCeiling` and still take its bytes out of a
  4673. // lower-ranked file's reservation on the way to the ceiling. Now both
  4674. // arms enforce the same inequality in their own units, and the invariant
  4675. // holds on every path.
  4676. //
  4677. // The GRACE arm keeps its own bound (a file within a sliver of its
  4678. // reservation) but is fit-tested on the render it actually produces, at
  4679. // the emission site below, so it cannot displace either.
  4680. const buysWhole = fileContent.length <= graceBound
  4681. || (reserved >= fileContent.length * EXPLORE_ALLOCATION.WHOLE_FILE_BUY_FRACTION
  4682. && sourceSpent + fileContent.length + owedBelow <= sourceCeiling
  4683. && fileContent.length <= fundedHeadroom);
  4684. // Set by the whole-file arm when it actually emits. A whole render that
  4685. // does not FIT no longer ends the file's turn (CG-26) — it falls through
  4686. // to the cluster path below, which is bounded by `fundedHeadroom` and
  4687. // renders something. Skipping outright was the trade the funding pool
  4688. // exists to refuse: a clustered section traded for no section at all.
  4689. let renderedWhole = false;
  4690. if (fileLines.length <= WHOLE_FILE_MAX_LINES && buysWhole) {
  4691. const body = fileContent.replace(/\n+$/, '');
  4692. const wholeRange: ExploreLineRange = { start: 1, end: body.split('\n').length };
  4693. const fullSection = withLineNumbers ? numberSourceLines(body, 1) : body;
  4694. // The buy decision above was made on the file's FULL size on purpose: it
  4695. // asks "did this file's relevance earn all of itself", which dedup does
  4696. // not change. Dedup then only ever makes the render smaller, so a buy
  4697. // that was funded stays funded.
  4698. const ddWhole = dedupeSpans([{ range: wholeRange, text: fullSection }]);
  4699. const wholeSection = ddWhole.parts.map((p) => p.text).join(GAP_MARKER);
  4700. const uniqSymbols = [...new Set(
  4701. group.nodes
  4702. .filter(n => n.kind !== 'import' && n.kind !== 'export')
  4703. .map(n => `${n.name}(${n.kind})`)
  4704. )];
  4705. const headerNames = uniqSymbols.slice(0, budget.maxSymbolsInFileHeader);
  4706. const omitted = uniqSymbols.length - headerNames.length;
  4707. // A drifted file rendered WHOLE is still correct (current bytes,
  4708. // numbered from 1) — only the index-derived symbol list / line refs to
  4709. // it elsewhere in this response may be shifted (#1474). Flag that.
  4710. const staleSuffix = fileStale ? ' · ⚠ changed since last index sync — source below is current; the symbol list may be outdated' : '';
  4711. const wholeHeader = fileSectionHeader(filePath, (omitted > 0 ? `${headerNames.join(', ')}, +${omitted} more` : headerNames.join(', ')) + staleSuffix);
  4712. // The fit test, on the bytes this render ACTUALLY costs (the numbered
  4713. // body, after dedup) rather than on the raw file — and against
  4714. // `fundedHeadroom`, so a whole render can no more spend a pending
  4715. // file's reservation than a clustered one can (CG-26). Both whole-file
  4716. // arms come through here, which is what closes the invariant on the
  4717. // GRACE path: grace is measured against this file's own allowance and
  4718. // says nothing about whether the bytes are still there to spend.
  4719. // Two tests, and they are different questions. `fundedHeadroom` is the
  4720. // DISPLACEMENT bound — may these bytes be spent without taking a
  4721. // pending file's reservation. `sectionCost` is the CEILING bound — do
  4722. // the header, fences and body actually fit what is left. The second one
  4723. // is exact now that the loop charges real section costs.
  4724. const wholeCost = wholeHeader.length + 2 + wholeSection.length + lang.length + 11;
  4725. if (wholeSection.length <= fundedHeadroom && totalChars + wholeCost <= renderCeiling) {
  4726. emitFileSection({
  4727. header: wholeHeader,
  4728. body: wholeSection,
  4729. // The whole file, minus any trailing blank lines the render trimmed.
  4730. ranges: ddWhole.parts.map((p) => p.range),
  4731. covered: ddWhole.covered,
  4732. overhead: 200,
  4733. mode: 'whole',
  4734. clipped: false,
  4735. fullBody: fullSection,
  4736. fullRanges: [wholeRange],
  4737. });
  4738. if (fileStale) staleRendered.push(filePath);
  4739. renderedWhole = true;
  4740. } else {
  4741. // Doesn't fit whole — don't slice a whole file mid-method here; fall
  4742. // through and let the cluster path pick body-shaped pieces of it.
  4743. anyFileTrimmed = true;
  4744. }
  4745. }
  4746. if (renderedWhole) continue;
  4747. // Drifted file too big for the whole-file window (#1474): the cluster /
  4748. // skeleton renders below would slice current bytes at indexed ranges —
  4749. // on a shifted file that serves a DIFFERENT symbol's code under the
  4750. // requested name. Omit the source with an explicit notice instead;
  4751. // never render a possibly-wrong slice.
  4752. if (fileStale) {
  4753. staleOmitted.push(filePath);
  4754. const staleHeader = fileSectionHeader(filePath, '⚠ changed on disk after the last index sync — source omitted (indexed line ranges no longer match, so a slice could show the wrong code). Read this file directly for current content; the change is picked up on that project\'s next index sync.');
  4755. lines.push(staleHeader, '');
  4756. totalChars += staleHeader.length + 2;
  4757. diag?.recordRender(filePath, 'stale-omitted', 0, true);
  4758. continue;
  4759. }
  4760. // Cluster nearby symbols to avoid reading huge gaps between distant symbols.
  4761. // Sort by start line, then merge overlapping/adjacent ranges (within the
  4762. // adaptive gap threshold). Include both node ranges AND edge source
  4763. // locations so template sections with component usages/calls are
  4764. // covered (not just script block symbols).
  4765. //
  4766. // Each range carries an `importance` score so we can rank clusters
  4767. // when the per-file budget forces us to drop some: entry-point nodes
  4768. // are worth 10, directly-connected nodes 3, peripheral nodes 1, and
  4769. // bare edge-source lines 2 (less than a connected node but more than
  4770. // a peripheral one — they hint at a reference but aren't a definition).
  4771. // Container kinds whose body can span most/all of a file. When such a
  4772. // node covers most of the file we drop it from the ranges: keeping it
  4773. // would merge every method inside it into one giant cluster spanning
  4774. // the whole file, which then tail-trims down to just the container's
  4775. // opening lines (its header/declarations) and buries the methods the
  4776. // query actually asked about (#185 follow-up — Session.swift in
  4777. // Alamofire is the canonical case: the `Session` class spans ~1,400
  4778. // lines). We want the granular symbols inside, not the envelope.
  4779. const ENVELOPE_KINDS = new Set(['file', 'module', 'class', 'struct', 'union', 'interface', 'enum', 'namespace', 'protocol', 'trait', 'component']);
  4780. // Cluster from this file's gathered nodes PLUS any callable the agent NAMED that
  4781. // lives here. Explore's relevance gather can miss a named method def in a huge
  4782. // non-sibling file — Django's query.py is 3,040 lines and `_fetch_all` (L2237)
  4783. // was gathered only as call-reference edges, never as a def, so it formed no
  4784. // cluster and the agent Read it back. Inject named defs directly and rank them
  4785. // ABOVE connected/glue nodes (importance 9) so their cluster wins the per-file
  4786. // budget — the agent explicitly asked for these symbols.
  4787. const rangeNodes = new Map<string, Node>();
  4788. for (const n of group.nodes) if (n.startLine > 0 && n.endLine > 0) rangeNodes.set(n.id, n);
  4789. for (const id of flow.namedNodeIds) {
  4790. if (rangeNodes.has(id)) continue;
  4791. const n = cg.getNode(id);
  4792. if (n && n.filePath === filePath && n.startLine > 0 && n.endLine > 0) rangeNodes.set(id, n);
  4793. }
  4794. const ranges: Array<{ start: number; end: number; name: string; kind: string; importance: number; spine: boolean; spineCallLine?: number }> = [...rangeNodes.values()]
  4795. // Drop whole-file envelope nodes (containers covering >50% of the file).
  4796. .filter(n => !(ENVELOPE_KINDS.has(n.kind) && (n.endLine - n.startLine + 1) > fileLines.length * 0.5))
  4797. .map(n => {
  4798. let importance = 1;
  4799. if (entryNodeIds.has(n.id)) importance = 10;
  4800. else if (flow.namedNodeIds.has(n.id)) importance = 9; // agent named it → keep its cluster
  4801. else if (glueNodeIds.has(n.id)) importance = 6; // bridging caller/callee of an entry
  4802. else if (connectedToEntry.has(n.id)) importance = 3;
  4803. // On the rendered call-path spine? That IS the flow answer — its cluster
  4804. // must never be dropped by the per-file budget (n8n's huge workflow-execute.ts:
  4805. // processRunExecutionData, the named flow ENTRY at L1562, is a large
  4806. // low-density method that lost the budget to denser blocks and got cut, so
  4807. // the agent Read it back — the very thing explore exists to prevent).
  4808. return { start: n.startLine, end: n.endLine, name: n.name, kind: n.kind, importance, spine: flow.pathNodeIds.has(n.id), spineCallLine: flow.spineCallSites.get(n.id) };
  4809. });
  4810. // Add edge source locations in this file — captures template references
  4811. // (component usages, event handlers) that aren't nodes themselves.
  4812. // Query edges directly from the DB (not just the subgraph) because BFS
  4813. // traversal may have pruned template reference targets due to node budget.
  4814. const edgeLines = new Set<string>(); // dedup by "line:name"
  4815. for (const node of group.nodes) {
  4816. const outgoing = cg.getOutgoingEdges(node.id);
  4817. for (const edge of outgoing) {
  4818. if (!edge.line || edge.line <= 0 || edge.kind === 'contains') continue;
  4819. const key = `${edge.line}:${edge.target}`;
  4820. if (edgeLines.has(key)) continue;
  4821. edgeLines.add(key);
  4822. // Look up target name from subgraph first, fall back to edge kind
  4823. const targetNode = subgraph.nodes.get(edge.target);
  4824. const targetName = targetNode?.name ?? edge.kind;
  4825. ranges.push({ start: edge.line, end: edge.line, name: targetName, kind: edge.kind, importance: 2, spine: false });
  4826. }
  4827. }
  4828. ranges.sort((a, b) => a.start - b.start);
  4829. if (ranges.length === 0) {
  4830. diag?.recordSkip(filePath, 'no-ranges');
  4831. continue;
  4832. }
  4833. const gapThreshold = budget.gapThreshold;
  4834. type ExploreRange = typeof ranges[number];
  4835. type ExploreCluster = {
  4836. start: number; end: number; symbols: string[]; score: number;
  4837. maxImportance: number; hasSpine: boolean; spineCallLine?: number;
  4838. /** The whole symbol ranges this cluster merged — the unit an oversize
  4839. * cluster is shrunk by, so shrinking never cuts through a body. */
  4840. members: ExploreRange[];
  4841. };
  4842. const clusters: ExploreCluster[] = [];
  4843. let current: ExploreCluster = {
  4844. start: ranges[0]!.start,
  4845. end: ranges[0]!.end,
  4846. symbols: [`${ranges[0]!.name}(${ranges[0]!.kind})`],
  4847. score: ranges[0]!.importance,
  4848. maxImportance: ranges[0]!.importance,
  4849. hasSpine: ranges[0]!.spine,
  4850. spineCallLine: ranges[0]!.spineCallLine,
  4851. members: [ranges[0]!],
  4852. };
  4853. for (let i = 1; i < ranges.length; i++) {
  4854. const r = ranges[i]!;
  4855. if (r.start <= current.end + gapThreshold) {
  4856. current.end = Math.max(current.end, r.end);
  4857. current.symbols.push(`${r.name}(${r.kind})`);
  4858. current.score += r.importance;
  4859. current.maxImportance = Math.max(current.maxImportance, r.importance);
  4860. current.hasSpine = current.hasSpine || r.spine;
  4861. current.spineCallLine = current.spineCallLine ?? r.spineCallLine;
  4862. current.members.push(r);
  4863. } else {
  4864. clusters.push(current);
  4865. current = {
  4866. start: r.start,
  4867. end: r.end,
  4868. symbols: [`${r.name}(${r.kind})`],
  4869. score: r.importance,
  4870. maxImportance: r.importance,
  4871. hasSpine: r.spine,
  4872. spineCallLine: r.spineCallLine,
  4873. members: [r],
  4874. };
  4875. }
  4876. }
  4877. clusters.push(current);
  4878. // Build file section output from clusters, capped by per-file budget.
  4879. // The pathological case (#185): a file like Session.swift where every
  4880. // method is adjacent collapses into one cluster spanning the whole
  4881. // file, and dumping that into the agent's context is most of the
  4882. // token cost on small projects. We pick clusters in priority order
  4883. // until the per-file char cap is hit. Truly enormous single clusters
  4884. // get tail-trimmed with a marker.
  4885. const contextPadding = 3;
  4886. // An oversize spine method (the call path runs THROUGH a god-method — n8n's
  4887. // processRunExecutionData is 962 lines) is windowed to its next-hop CALL site
  4888. // plus the signature head, NOT dumped whole. Without this the cluster is too big
  4889. // for any per-file cap and gets dropped, so the agent Reads the method back —
  4890. // the exact gap this closes. Bounded, so a god-method can't blow the budget yet
  4891. // the spine's call still appears in context.
  4892. const OVERSIZE_SPINE_LINES = 200;
  4893. const SPINE_WINDOW = 28; // lines each side of the next-hop call site
  4894. // Returns the rendered text as SPAN-KEYED PARTS. Every part carries the
  4895. // exact line range its text was sliced from, which two things depend on:
  4896. // the session record (CG-17) — a record claiming lines it never sent would
  4897. // withhold them from a later call, costing a Read — and cross-call dedup
  4898. // (CG-18), which rebuilds a part's text from a narrower span when the
  4899. // agent already holds the rest. Both read the spans from the function that
  4900. // does the slicing; a second function mirroring these window/padding rules
  4901. // would drift.
  4902. type SectionPart = { range: ExploreLineRange; text: string };
  4903. // Named gaps (#1711): a bare `... (gap) ...` hid the answer when the
  4904. // trim dropped the symbols the query was asking for. Budget estimates
  4905. // still use GAP_MARKER.length (a lower bound); the final fit test
  4906. // measures the real joined text.
  4907. const sectionText = (parts: ReadonlyArray<SectionPart>): string =>
  4908. joinPartsWithNamedGaps(filePath, parts, fileIndexNodes);
  4909. const buildSection = (
  4910. c: { start: number; end: number; hasSpine?: boolean; spineCallLine?: number },
  4911. ): SectionPart[] => {
  4912. if (c.hasSpine && c.spineCallLine && (c.end - c.start + 1) > OVERSIZE_SPINE_LINES) {
  4913. const call = c.spineCallLine;
  4914. const winStart = Math.max(c.start, call - SPINE_WINDOW);
  4915. const winEnd = Math.min(c.end, call + SPINE_WINDOW);
  4916. const parts: SectionPart[] = [];
  4917. // Signature head, only when it sits clearly above the window (else the
  4918. // window already covers the method opening).
  4919. const headEnd = Math.min(c.start + 4, winStart - 2);
  4920. if (headEnd >= c.start) {
  4921. const head = fileLines.slice(c.start - 1, headEnd).join('\n');
  4922. parts.push({
  4923. range: { start: c.start, end: headEnd },
  4924. text: withLineNumbers ? numberSourceLines(head, c.start) : head,
  4925. });
  4926. }
  4927. const win = fileLines.slice(winStart - 1, winEnd).join('\n');
  4928. parts.push({
  4929. range: { start: winStart, end: winEnd },
  4930. text: withLineNumbers ? numberSourceLines(win, winStart) : win,
  4931. });
  4932. return parts;
  4933. }
  4934. const startIdx = Math.max(0, c.start - 1 - contextPadding);
  4935. const endIdx = Math.min(fileLines.length, c.end + contextPadding);
  4936. const slice = fileLines.slice(startIdx, endIdx).join('\n');
  4937. // startIdx is 0-based, so the slice's first line is line startIdx + 1.
  4938. return [{
  4939. range: { start: startIdx + 1, end: endIdx },
  4940. text: withLineNumbers ? numberSourceLines(slice, startIdx + 1) : slice,
  4941. }];
  4942. };
  4943. /**
  4944. * Shrink an oversize cluster to the highest-importance symbols inside it
  4945. * that fit `cap`, rendered in source order with gap markers (CG-12).
  4946. *
  4947. * A cluster is a MERGE of whole symbol ranges, and on a densely-packed file
  4948. * every symbol merges into one blob spanning the file — cycle.go's 209-line
  4949. * `Service` is one cluster covering `RunCycle`, `runPayrollCycleAll` and
  4950. * seven incidental accessors. The old rule took the top-ranked cluster whole
  4951. * however big it was, so a single-cluster file simply ignored its budget:
  4952. * it took ~40% more than it was allotted, and the file below it was then
  4953. * dropped for lack of room (that is how `BuildPayslip` — the "calculate"
  4954. * half of the #1500 query — went missing entirely). Shrinking by MEMBER
  4955. * keeps every rule that matters: only whole symbol ranges are emitted, so a
  4956. * body is never cut, and the members are chosen by the same importance the
  4957. * cluster ranking uses. Returns null when nothing needed shrinking.
  4958. *
  4959. * `sizeOf` measures the RAW source span, while the render adds
  4960. * `contextPadding` around every block and a line-number prefix to every
  4961. * line — so this over-keeps (measured ~60% under on a 1,414-line file:
  4962. * 16.5K accounted, 26.3K rendered). That is deliberate, not an oversight:
  4963. * `bound()` clamps the result to the ceiling exactly, so the slack costs no
  4964. * bytes, and making the estimate exact instead measured WORSE — it stops at
  4965. * the last member that fits whole, and the released bytes carry forward to
  4966. * lower-ranked files (payroll-go's `runPayrollCycleAll` body lost its
  4967. * `s.store.Upsert` call to a rank-5 file). What the slack must NOT do is
  4968. * decide WHICH members survive: that is the ceiling trim's job, and CG-38 is
  4969. * why that trim now protects the named spans instead of cutting in source
  4970. * order. See `docs/benchmarks/explore-tail-render-cg38.md`.
  4971. */
  4972. const shrinkCluster = (c: ExploreCluster, cap: number): SectionPart[] | null => {
  4973. if (c.members.length < 2) return null;
  4974. const byImportance = [...c.members].sort((a, b) =>
  4975. b.importance - a.importance || (a.end - a.start) - (b.end - b.start) || a.start - b.start);
  4976. const sizeOf = (r: ExploreRange) => fileLines.slice(r.start - 1, r.end).join('\n').length;
  4977. const keep: ExploreRange[] = [];
  4978. let kept = 0;
  4979. for (const r of byImportance) {
  4980. const sz = sizeOf(r) + GAP_MARKER.length;
  4981. // Always keep the most important range, even if it alone is oversize —
  4982. // an empty section sends the agent to Read, which costs far more. How
  4983. // far it may overshoot is bounded by the caller's ceiling (CG-30), which
  4984. // windows a runaway member instead of dropping it.
  4985. if (keep.length > 0 && kept + sz > cap) continue;
  4986. keep.push(r);
  4987. kept += sz;
  4988. }
  4989. if (keep.length === c.members.length) return null;
  4990. // Re-merge the kept ranges in source order so adjacent survivors read as
  4991. // one block rather than a stutter of one-symbol fragments.
  4992. keep.sort((a, b) => a.start - b.start);
  4993. const merged: Array<{ start: number; end: number }> = [];
  4994. for (const r of keep) {
  4995. const last = merged[merged.length - 1];
  4996. if (last && r.start <= last.end + gapThreshold) last.end = Math.max(last.end, r.end);
  4997. else merged.push({ start: r.start, end: r.end });
  4998. }
  4999. return merged.flatMap((m) => buildSection(m));
  5000. };
  5001. /**
  5002. * Bounded overshoot for one cluster's render (CG-30).
  5003. *
  5004. * `shrinkCluster` keeps the highest-importance member whole even when that
  5005. * member alone is oversize — an empty file section sends the agent to Read,
  5006. * which is exactly what explore exists to prevent. But "never empty" is not
  5007. * "any size": with nothing bounding it, one 22K member rendered against a
  5008. * 9K reservation (2.4x), which collapses the headroom every file ranked
  5009. * below it draws from. Past the ceiling the member is WINDOWED rather than
  5010. * dropped — a leading window (signature + head of the body), plus a window
  5011. * on the spine's call site when the head misses it, since on a flow cluster
  5012. * the call path IS the answer.
  5013. */
  5014. const MIN_WINDOW_LINES = 12;
  5015. /** Rendered cost of one source line, line numbering included. */
  5016. const lineCost = (ln: number): number =>
  5017. (fileLines[ln - 1] ?? '').length + 1 + (withLineNumbers ? String(ln).length + 1 : 0);
  5018. /**
  5019. * Longest prefix of `r` that fits `room`. `minLines` is the never-empty
  5020. * floor — it may overrun `room`, so it is only ever asked for when nothing
  5021. * else has been emitted and the alternative is an empty section.
  5022. */
  5023. const headWindowOf = (
  5024. r: ExploreLineRange, room: number, minLines = 0,
  5025. ): ExploreLineRange | null => {
  5026. let end = r.start - 1;
  5027. let chars = 0;
  5028. for (let ln = r.start; ln <= r.end; ln++) {
  5029. const cost = lineCost(ln);
  5030. if (chars + cost > room && end - r.start + 1 >= minLines) break;
  5031. chars += cost;
  5032. end = ln;
  5033. }
  5034. return end >= r.start ? { start: r.start, end } : null;
  5035. };
  5036. /** Widest window around `line` inside [lo, hi] that fits `room`. */
  5037. const centeredWindowOf = (
  5038. line: number, lo: number, hi: number, room: number,
  5039. ): ExploreLineRange | null => {
  5040. if (line < lo || line > hi) return null;
  5041. let start = line, end = line, chars = lineCost(line);
  5042. for (let grown = true; grown;) {
  5043. grown = false;
  5044. if (end + 1 <= hi && chars + lineCost(end + 1) <= room) { end += 1; chars += lineCost(end); grown = true; }
  5045. if (start - 1 >= lo && chars + lineCost(start - 1) <= room) { start -= 1; chars += lineCost(start); grown = true; }
  5046. }
  5047. return { start, end };
  5048. };
  5049. /**
  5050. * Reduce rendered parts to fit `ceiling`, never to nothing. Whole parts are
  5051. * kept while they fit; the first part that overruns is cut to a leading
  5052. * window on whole lines (a body is never cut mid-line), and everything past
  5053. * it is dropped. The GAP_MARKER between surviving parts — and the line-number
  5054. * jump — is what tells the agent the cut happened.
  5055. *
  5056. * A partial window shorter than MIN_WINDOW_LINES is not worth emitting, and
  5057. * emitting one is actively harmful: the session record then claims a 4-line
  5058. * sliver, and the NEXT call's dedup has to either shred a whole block around
  5059. * it or re-send it. Below that floor the part is simply dropped — unless
  5060. * nothing has been emitted at all, where the floor wins over the ceiling
  5061. * because an empty section is the one outcome worse than an oversize one.
  5062. *
  5063. * `focusLines` are the lines this trim must not lose: the spine's next-hop
  5064. * call site (CG-30) and every definition the agent NAMED inside the cluster
  5065. * (CG-38). The head fill is source-ordered, so a named def in the TAIL of a
  5066. * large file is otherwise always the first thing an over-ceiling render
  5067. * drops — the one span the agent asked for by name, cut in favour of
  5068. * head-of-file filler it did not ask for. The full-ceiling fill is tried
  5069. * FIRST and the 60% hold-back applies only when a focus line is actually
  5070. * left uncovered, so a cluster whose head already reaches its focus keeps
  5071. * the whole ceiling for source.
  5072. */
  5073. const windowToCeiling = (
  5074. parts: ReadonlyArray<SectionPart>,
  5075. ceiling: number,
  5076. focusLines: ReadonlyArray<number> = [],
  5077. ): SectionPart[] => {
  5078. const inParts = (line: number) =>
  5079. parts.some((p) => line >= p.range.start && line <= p.range.end);
  5080. const focus = [...new Set(focusLines)]
  5081. .filter((l) => typeof l === 'number' && l > 0 && inParts(l))
  5082. .sort((a, b) => a - b);
  5083. /** Source-ordered fill of whole parts, the overrunning one cut to a head window. */
  5084. const fill = (room: number): { emit: ExploreLineRange[]; used: number } => {
  5085. const emit: ExploreLineRange[] = [];
  5086. let used = 0;
  5087. for (const p of parts) {
  5088. const join = emit.length > 0 ? GAP_MARKER.length : 0;
  5089. if (used + join + p.text.length <= room) {
  5090. emit.push(p.range);
  5091. used += join + p.text.length;
  5092. continue;
  5093. }
  5094. const first = emit.length === 0;
  5095. const win = headWindowOf(
  5096. p.range, Math.max(0, room - used - join), first ? MIN_WINDOW_LINES : 0);
  5097. if (win && (first || win.end - win.start + 1 >= MIN_WINDOW_LINES)) {
  5098. emit.push(win);
  5099. used += join + renderSpan(win).length;
  5100. }
  5101. break;
  5102. }
  5103. return { emit, used };
  5104. };
  5105. let { emit, used } = fill(ceiling);
  5106. const reached = () => (emit.length ? emit[emit.length - 1]!.end : 0);
  5107. if (focus.some((l) => l > reached())) {
  5108. // Hold room back for the focus windows so the head can't eat all of it.
  5109. ({ emit, used } = fill(Math.floor(ceiling * 0.6)));
  5110. }
  5111. // What is left is SPLIT between the uncovered focus lines rather than
  5112. // handed to them in order. Greedy-in-source-order reproduces the very bug
  5113. // this guards: on a prose query resolving four focus lines, the two
  5114. // earliest took the whole reserve and `flushQueuedMessages` at L1102 —
  5115. // named in the question — was dropped again. A skipped or undersized
  5116. // window returns its share to the pool for the ones after it.
  5117. let covered = reached();
  5118. let room = Math.max(0, ceiling - used);
  5119. const pending = focus.filter((l) => l > covered);
  5120. for (let i = 0; i < pending.length; i++) {
  5121. const line = pending[i]!;
  5122. if (line <= covered) continue; // an earlier window already reached it
  5123. const share = Math.floor(room / (pending.length - i)) - GAP_MARKER.length;
  5124. if (share <= 0) continue;
  5125. const host = parts.find((p) => line >= p.range.start && line <= p.range.end)!;
  5126. const lo = Math.max(host.range.start, line - SPINE_WINDOW, covered + 1);
  5127. const hi = Math.min(host.range.end, line + SPINE_WINDOW);
  5128. const win = centeredWindowOf(line, lo, hi, share);
  5129. // Same sliver floor as the head window — a two-line peek at the call
  5130. // site teaches the next call's dedup to shred the block around it.
  5131. if (!win || win.end - win.start + 1 < MIN_WINDOW_LINES) continue;
  5132. emit.push(win);
  5133. const cost = GAP_MARKER.length + renderSpan(win).length;
  5134. used += cost;
  5135. room -= cost;
  5136. covered = win.end;
  5137. }
  5138. // Never empty: a section with no source sends the agent to Read.
  5139. if (emit.length === 0 && parts.length > 0) {
  5140. const first = headWindowOf(parts[0]!.range, ceiling, MIN_WINDOW_LINES);
  5141. if (first) emit.push(first);
  5142. }
  5143. return emit
  5144. .sort((a, b) => a.start - b.start)
  5145. .map((r) => ({ range: r, text: renderSpan(r) }));
  5146. };
  5147. /**
  5148. * The lines a ceiling trim of this cluster must not lose: the spine's
  5149. * next-hop call site, and the definition line of every member the agent
  5150. * NAMED or that is a query entry point (importance >= 9). Capped, because
  5151. * each one costs a window and too many turn a section into confetti; the
  5152. * most important come first, source order within a tier so the windows read
  5153. * top-down.
  5154. */
  5155. const MAX_FOCUS_LINES = 6;
  5156. const focusLinesOf = (c: ExploreCluster): number[] => {
  5157. const named = c.members
  5158. .filter((m) => m.importance >= 9)
  5159. .sort((a, b) => b.importance - a.importance || a.start - b.start)
  5160. .slice(0, MAX_FOCUS_LINES)
  5161. .map((m) => m.start);
  5162. return c.spineCallLine ? [c.spineCallLine, ...named] : named;
  5163. };
  5164. /**
  5165. * One cluster's final parts: built, shrunk if it overruns `cap`, then
  5166. * passed through the session history (CG-18).
  5167. *
  5168. * The shrink decision reads the DEDUPED length on purpose. A cluster whose
  5169. * bytes the agent already holds costs this response nothing, so shrinking
  5170. * it on its raw size would drop new symbols to make room for source that
  5171. * is not being sent — spending the file's budget on nothing.
  5172. */
  5173. const renderCluster = (
  5174. c: ExploreCluster,
  5175. cap: number,
  5176. /**
  5177. * Hard bound on the rendered result (CG-30). `cap` is what selection asks
  5178. * for; this is how far a single oversize member is allowed to overshoot it
  5179. * before being windowed. Always >= `cap`, so a cluster that already fits is
  5180. * never touched.
  5181. */
  5182. ceiling: number = Infinity,
  5183. ): { parts: SectionPart[]; covered: ExploreLineRange[]; shrunk: boolean } => {
  5184. const base = dedupeSpans(buildSection(c));
  5185. const bound = (
  5186. r: { parts: SectionPart[]; covered: ExploreLineRange[]; shrunk: boolean },
  5187. ) => {
  5188. if (!Number.isFinite(ceiling) || sectionText(r.parts).length <= ceiling) return r;
  5189. // Windows are subsets of spans dedupeSpans already cleared, so the record
  5190. // still only ever claims source that was actually sent.
  5191. const parts = windowToCeiling(r.parts, ceiling, focusLinesOf(c));
  5192. return { parts, covered: r.covered, shrunk: true };
  5193. };
  5194. if (sectionText(base.parts).length <= cap) {
  5195. return { parts: base.parts, covered: base.covered, shrunk: false };
  5196. }
  5197. const shrunk = shrinkCluster(c, cap);
  5198. if (shrunk === null) {
  5199. return bound({ parts: base.parts, covered: base.covered, shrunk: false });
  5200. }
  5201. const dd = dedupeSpans(shrunk);
  5202. return bound({ parts: dd.parts, covered: dd.covered, shrunk: true });
  5203. };
  5204. // Rank clusters for inclusion under the per-file cap. Entry-point
  5205. // clusters come first: a cluster containing a query entry point
  5206. // (importance 10) must outrank a dense block of mere declarations,
  5207. // otherwise on a large file like Session.swift the top-of-file class
  5208. // header + property list (many adjacent low-importance nodes, high
  5209. // density) wins the budget and buries the actual methods the query
  5210. // asked about (perform/didCreateURLRequest/task live deep in the
  5211. // file). Within the same importance tier, prefer density (score per
  5212. // line) so we still favor focused clusters over sprawling ones, then
  5213. // smaller span as a cheap-to-include tiebreak.
  5214. const rankedClusters = clusters
  5215. .map((c, i) => ({ idx: i, span: c.end - c.start + 1, c }))
  5216. .sort((a, b) => {
  5217. // Spine clusters first — the rendered call path IS the flow answer, so it
  5218. // outranks any denser block of peripheral declarations (a low-density entry
  5219. // method must not lose the budget to them). Within spine / within non-spine,
  5220. // the existing importance → density → score → span order holds.
  5221. if (a.c.hasSpine !== b.c.hasSpine) return (b.c.hasSpine ? 1 : 0) - (a.c.hasSpine ? 1 : 0);
  5222. if (b.c.maxImportance !== a.c.maxImportance) return b.c.maxImportance - a.c.maxImportance;
  5223. const densityA = a.c.score / a.span;
  5224. const densityB = b.c.score / b.span;
  5225. if (densityB !== densityA) return densityB - densityA;
  5226. if (b.c.score !== a.c.score) return b.c.score - a.c.score;
  5227. return a.span - b.span;
  5228. });
  5229. // Per-file budget is this file's RESERVATION, bounded by what's left before
  5230. // the hard ceiling — so selection (which ranks by importance) keeps the
  5231. // high-importance clusters and drops peripheral ones, instead of the
  5232. // downstream source-order trim slicing off whatever comes last in the file.
  5233. // That source-order slice is what cut Django's `_fetch_all` (L2237, importance
  5234. // 9 — agent-named) when query.py was the last of four big files to be emitted.
  5235. // It used to be `min(maxCharsPerFile, remaining)`: a flat cap that clipped the
  5236. // top-scoring file at the same 3,800 as the weakest one, while the whole-file
  5237. // branch above handed a small file 3x that. The reservation is the whole point
  5238. // of CG-12 — bytes follow relevance, not file size.
  5239. //
  5240. // `fundedHeadroom`, not `headroom` (CG-31): what is left before the hard
  5241. // ceiling includes every unreached file's reservation, and spending that
  5242. // is how one clustered file zeroed five admitted peers. It is ≤ `headroom`
  5243. // by construction, so it is the only bound these three lines need.
  5244. const fileBudget = Math.min(allowance, fundedHeadroom);
  5245. // Spine ceiling: a flow-path cluster may exceed the reservation (the call path
  5246. // IS the answer and clipping it forces the Read), but bounded — 1.5x the
  5247. // reservation and never past the ceiling — so a pathological long in-file
  5248. // spine can't run away or starve co-flow files entirely. The 1.5x is drawn
  5249. // from the shared envelope, so it is exactly the overshoot the displacement
  5250. // guard has to fund: past `fundedHeadroom` the extra half-reservation is
  5251. // another file's, not spare room.
  5252. const SPINE_CEILING = Math.min(Math.round(allowance * 1.5), fundedHeadroom);
  5253. const chosenIndices = new Set<number>();
  5254. // Final renders (deduped, shrunk where oversize) by cluster index. Computed
  5255. // during selection and reused at emission so the two never disagree.
  5256. const renderedClusters = new Map<number, ReturnType<typeof renderCluster>>();
  5257. let anyClusterShrunk = false;
  5258. let projectedChars = 0;
  5259. for (const rc of rankedClusters) {
  5260. // The top-ranked cluster is always taken — an empty file section sends the
  5261. // agent to Read, negating the savings. But "always taken" is not "taken at
  5262. // any size": when it overruns the reservation it is SHRUNK to the
  5263. // highest-importance whole symbol ranges inside it, so a single-cluster
  5264. // god-file spends its allotment instead of the whole response's.
  5265. const first = chosenIndices.size === 0;
  5266. // A spine cluster (the rendered call path) is the flow answer — it may run
  5267. // past the per-file budget up to the spine ceiling; non-spine clusters obey
  5268. // the normal per-file budget.
  5269. const cap = rc.c.hasSpine ? SPINE_CEILING : fileBudget;
  5270. // CG-30: shrinking keeps the top member whole however big it is, so bound
  5271. // how far that member may overshoot — the same 1.5x-of-reservation bound
  5272. // SPINE_CEILING already draws, never below `cap` (a cluster that fits its
  5273. // cap is never windowed). A spine cluster's cap already IS that bound, so
  5274. // this holds it to it rather than letting the member rule walk past it.
  5275. const ceiling = Math.max(cap, SPINE_CEILING);
  5276. if (first) {
  5277. const section = renderCluster(rc.c, cap, ceiling);
  5278. renderedClusters.set(rc.idx, section);
  5279. anyClusterShrunk = anyClusterShrunk || section.shrunk;
  5280. chosenIndices.add(rc.idx);
  5281. projectedChars += sectionText(section.parts).length;
  5282. continue;
  5283. }
  5284. // Later clusters used to be all-or-nothing: rendered whole, then taken
  5285. // only if the whole thing fit the remainder. On a file whose top-ranked
  5286. // cluster is TRIVIAL that discards the answer and leaves the reservation
  5287. // unspent — django's `sql/query.py` keeps a 22-line glue cluster (one
  5288. // importance-6 bridging symbol) and drops the 624-line `Query` body
  5289. // beneath it whole, spending 1,923 of 7,947; the slack then carries
  5290. // forward to a file scoring a fifth as much (CG-36). Same shape in
  5291. // okhttp's `RealInterceptorChain.kt`, where an import header displaces
  5292. // the chain itself.
  5293. //
  5294. // So a later cluster is shrunk INTO the remainder by the same whole-member
  5295. // rule the first one already uses — CG-26's between-FILES lesson ("hold the
  5296. // remainder while it is still worth a section; zeroing it delivers
  5297. // nothing") applied between CLUSTERS. Below `MIN_CHARS` the remainder can't
  5298. // hold one readable block, so it stays a drop rather than a stutter of
  5299. // fragments the next call's dedup then has to shred around.
  5300. const room = cap - projectedChars - GAP_MARKER.length;
  5301. if (room < EXPLORE_ALLOCATION.MIN_CHARS) continue;
  5302. const section = renderCluster(rc.c, room, room);
  5303. const text = sectionText(section.parts);
  5304. if (text.length === 0) continue;
  5305. // The never-empty floors inside the windowing may overrun `room` (a
  5306. // 12-line minimum window on a file of very long lines). The first cluster
  5307. // is allowed that overshoot — an empty section is worse — but a later one
  5308. // is not: it would be spending a lower-ranked FILE's reservation for a
  5309. // fragment. Drop it, exactly as before.
  5310. if (projectedChars + text.length + GAP_MARKER.length > cap) continue;
  5311. renderedClusters.set(rc.idx, section);
  5312. anyClusterShrunk = anyClusterShrunk || section.shrunk;
  5313. chosenIndices.add(rc.idx);
  5314. projectedChars += text.length + GAP_MARKER.length;
  5315. }
  5316. // Emit chosen clusters in source order so the file reads top-to-bottom.
  5317. // Assembled through a function because it may have to run more than once:
  5318. // the fit test below trims the weakest cluster and re-assembles rather
  5319. // than skipping the file (CG-26).
  5320. const assembleSection = (chosen: ReadonlySet<number>) => {
  5321. const parts: SectionPart[] = [];
  5322. const symbols: string[] = [];
  5323. const covered: ExploreLineRange[] = [];
  5324. for (let i = 0; i < clusters.length; i++) {
  5325. if (!chosen.has(i)) continue;
  5326. const cluster = clusters[i]!;
  5327. const section = renderedClusters.get(i)!;
  5328. parts.push(...section.parts);
  5329. covered.push(...section.covered);
  5330. symbols.push(...cluster.symbols);
  5331. }
  5332. // Every member across ALL clusters (chosen or not) is a candidate for
  5333. // the header bias — a dropped cluster's symbols used to vanish from
  5334. // the header entirely (#1711).
  5335. const memberRefs: ElidedSymbolRef[] = [];
  5336. const seenMember = new Set<string>();
  5337. for (const c of clusters) {
  5338. for (const m of c.members) {
  5339. if (seenMember.has(m.name)) continue;
  5340. seenMember.add(m.name);
  5341. memberRefs.push({ name: m.name, kind: m.kind, startLine: m.start });
  5342. }
  5343. }
  5344. const ranges = parts.map((p) => p.range);
  5345. const text = joinPartsWithNamedGaps(filePath, parts, fileIndexNodes);
  5346. // Header bias prefers RELEVANT elisions (cluster members the trim cut)
  5347. // over incidental index filler — otherwise locale-sorted `calls0`…
  5348. // crowds out the answer methods (#1711).
  5349. const elided = symbolsNotInRanges(memberRefs, ranges);
  5350. return { text, symbols, ranges, covered, elided };
  5351. };
  5352. let assembled = assembleSection(chosenIndices);
  5353. // A chosen cluster is a COMPLETE method-range — we never cut through a body,
  5354. // and a shrunk cluster drops WHOLE members for the same reason. An oversize
  5355. // single MEMBER (one long monolithic function) is kept whole for as long as
  5356. // it fits the bounded overshoot (half a method is useless — the agent just
  5357. // Reads the rest, the fallback explore exists to prevent); past that bound it
  5358. // is WINDOWED on whole lines rather than dropped (CG-30), so a god-method
  5359. // can neither be silently lost nor spend the response's whole envelope.
  5360. if (chosenIndices.size < clusters.length || anyClusterShrunk) {
  5361. anyFileTrimmed = true;
  5362. }
  5363. // Dedupe + cap the symbols list shown in the per-file header. Some
  5364. // files (Session.swift in Alamofire) produced 3.4KB symbol lists
  5365. // from cluster scoring + edge-source lines, dwarfing the per-file
  5366. // body cap. Prefer symbols the trim elided (#1711), then frequency,
  5367. // with a "+N more" tail.
  5368. const headerFor = (
  5369. symbols: readonly string[],
  5370. elided: ReadonlyArray<ElidedSymbolRef> = [],
  5371. ): string => {
  5372. const { shown, omitted } = biasHeaderSymbols(
  5373. symbols, elided, budget.maxSymbolsInFileHeader,
  5374. );
  5375. return fileSectionHeader(filePath, omitted > 0
  5376. ? `${shown.join(', ')}, +${omitted} more`
  5377. : shown.join(', '));
  5378. };
  5379. // Last stop before the hard ceiling. The reservation already bounded cluster
  5380. // selection above, so reaching this means the bounded overshoot (an oversize
  5381. // first cluster, taken whole rather than sliced mid-method) ran the response
  5382. // out of room.
  5383. //
  5384. // Exact, like the whole-file arm above (CG-26): header + fences + body,
  5385. // not body + a flat 200. The displacement half of the invariant is
  5386. // already enforced on the body itself (`bodyCap` / `SPINE_CEILING` read
  5387. // `fundedHeadroom`); this is the ceiling half. And because it is exact it
  5388. // now bites at the margin — a header runs 300–500 chars where the body
  5389. // budget assumed 200 — so an overrun TRIMS the weakest cluster and
  5390. // re-assembles instead of skipping the file whole. Skipping a file over a
  5391. // ~300-char accounting difference is starvation by rounding: the file was
  5392. // admitted, reserved and rendered, and would have delivered nothing.
  5393. // Only when the top-ranked cluster alone cannot fit is the file skipped —
  5394. // that one is never sliced mid-method.
  5395. let fileHeader = headerFor(assembled.symbols, assembled.elided);
  5396. let chosenNow = chosenIndices;
  5397. const costOfSection = (header: string, body: string) =>
  5398. header.length + 2 + (body.length > 0 ? body.length + lang.length + 11 : 0);
  5399. // The weakest cluster is SHRUNK into the room that is left before it is
  5400. // dropped (CG-36). Dropping it whole makes this loop as all-or-nothing as
  5401. // the selection above it was, and at the same cost: on excalidraw's
  5402. // `typeChecks.ts` the estimate missed by 13 chars and a 1,512-char cluster
  5403. // — the file's highest-SCORING one, last only because rank breaks ties on
  5404. // density — was thrown away to pay for it. Below MIN_CHARS the remainder
  5405. // cannot hold a readable block, and only then is the cluster dropped.
  5406. const reshrunkOnce = new Set<number>();
  5407. while (totalChars + costOfSection(fileHeader, assembled.text) > renderCeiling
  5408. && chosenNow.size > 1) {
  5409. // Weakest first: `rankedClusters` is best-first, so walk it backwards.
  5410. let weakest = -1;
  5411. for (let i = rankedClusters.length - 1; i >= 0; i--) {
  5412. const idx = rankedClusters[i]!.idx;
  5413. if (chosenNow.has(idx)) { weakest = idx; break; }
  5414. }
  5415. if (weakest < 0) break;
  5416. const over = totalChars + costOfSection(fileHeader, assembled.text) - renderCeiling;
  5417. const current = renderedClusters.get(weakest)!;
  5418. const currentLen = sectionText(current.parts).length;
  5419. const room = currentLen - over;
  5420. let reduced = false;
  5421. // One attempt per cluster: a second pass means the first re-render did
  5422. // not buy enough (the header moved with it), and the cluster is then
  5423. // dropped rather than whittled a few chars at a time.
  5424. if (room >= EXPLORE_ALLOCATION.MIN_CHARS && !reshrunkOnce.has(weakest)) {
  5425. reshrunkOnce.add(weakest);
  5426. const reshrunk = renderCluster(clusters[weakest]!, room, room);
  5427. const reshrunkLen = sectionText(reshrunk.parts).length;
  5428. // Strictly smaller, or this loop cannot make progress and would spin.
  5429. if (reshrunkLen > 0 && reshrunkLen < currentLen) {
  5430. renderedClusters.set(weakest, reshrunk);
  5431. anyClusterShrunk = true;
  5432. reduced = true;
  5433. }
  5434. }
  5435. if (!reduced) {
  5436. const trimmed = new Set(chosenNow);
  5437. trimmed.delete(weakest);
  5438. chosenNow = trimmed;
  5439. }
  5440. assembled = assembleSection(chosenNow);
  5441. fileHeader = headerFor(assembled.symbols, assembled.elided);
  5442. anyFileTrimmed = true;
  5443. }
  5444. // One cluster left and still over — by the header estimate's error, at
  5445. // most a few hundred chars. Re-render it INTO the room that is actually
  5446. // left rather than skip the file: the same whole-line windowing an
  5447. // oversize cluster already gets (CG-30), just against an exact bound.
  5448. // The header is built from the cluster's symbols, not its text, so
  5449. // re-rendering cannot move the target.
  5450. if (totalChars + costOfSection(fileHeader, assembled.text) > renderCeiling
  5451. && chosenNow.size === 1) {
  5452. const idx = [...chosenNow][0]!;
  5453. const room = renderCeiling - totalChars
  5454. - (fileHeader.length + 2 + lang.length + 11);
  5455. if (room > 0) {
  5456. const reshrunk = renderCluster(clusters[idx]!, room, room);
  5457. renderedClusters.set(idx, reshrunk);
  5458. anyClusterShrunk = anyClusterShrunk || reshrunk.shrunk;
  5459. assembled = assembleSection(chosenNow);
  5460. anyFileTrimmed = true;
  5461. }
  5462. }
  5463. if (totalChars + costOfSection(fileHeader, assembled.text) > renderCeiling) {
  5464. anyFileTrimmed = true;
  5465. diag?.recordSkip(filePath, 'budget-clusters');
  5466. continue;
  5467. }
  5468. const fileSection = assembled.text;
  5469. const sectionRanges = assembled.ranges;
  5470. const coveredRanges = assembled.covered;
  5471. // The undeduped render of the same clusters, needed only if this file ends
  5472. // up fully back-referenced AND the whole call finds nothing new to say —
  5473. // see `suppressedFallback`. Built lazily: on every other call it is dead
  5474. // weight.
  5475. const fullClusterParts = fileSection.length === 0
  5476. ? clusters.flatMap((c, i) => (chosenNow.has(i) ? buildSection(c) : []))
  5477. : [];
  5478. emitFileSection({
  5479. header: fileHeader,
  5480. body: fileSection,
  5481. ranges: sectionRanges,
  5482. covered: mergeRanges(coveredRanges),
  5483. overhead: 200,
  5484. mode: 'clusters',
  5485. // Windowing an oversize member elides source too — reporting it as
  5486. // unclipped would hide exactly the cut the diagnostic exists to show.
  5487. clipped: chosenNow.size < clusters.length || anyClusterShrunk,
  5488. fullBody: sectionText(fullClusterParts),
  5489. fullRanges: fullClusterParts.map((p) => p.range),
  5490. });
  5491. }
  5492. // Anti-abandonment restore (CG-18). Dedup withheld everything and nothing new
  5493. // took its place — the response would be pointers only, which is the shape
  5494. // that reads as "codegraph found nothing" and sends the agent to Read for
  5495. // good. Put the top suppressed file back, in full, and keep its pointer off.
  5496. // Deliberately checked against `newSourceChars` (source THIS call emitted)
  5497. // rather than the response length: the flow and blast-radius sections are
  5498. // always there, and they are not what makes a response feel sufficient.
  5499. // Cast, not annotation: the only writer is the render loop's `emitFileSection`
  5500. // closure, which TypeScript's flow analysis cannot see, so it narrows the
  5501. // variable to `null` here and the truthiness check below would be `never`.
  5502. const restore = suppressedFallback as SuppressedFallback | null;
  5503. if (newSourceChars === 0 && restore) {
  5504. if (totalChars + restore.sourceChars + restore.overhead <= renderCeiling) {
  5505. lines.splice(restore.at, restore.replacing, ...restore.section);
  5506. totalChars += restore.sourceChars + restore.overhead;
  5507. sourceSpent += restore.sourceChars;
  5508. newSourceChars += restore.sourceChars;
  5509. filesIncluded++;
  5510. const idx = backReferencedFiles.indexOf(restore.filePath);
  5511. if (idx >= 0) backReferencedFiles.splice(idx, 1);
  5512. emittedByFile.set(restore.filePath, {
  5513. ranges: [...restore.ranges],
  5514. bytes: restore.sourceChars,
  5515. fingerprint: restore.fingerprint,
  5516. });
  5517. diag?.recordRender(restore.filePath, 'clusters', restore.sourceChars, false);
  5518. diag?.recordDedup(restore.filePath, 0, []);
  5519. }
  5520. }
  5521. // The back-reference convention, stated once where the verbatim guarantee is
  5522. // (#1474 does the same for drift). Without it a pointer reads as an
  5523. // apology for missing source rather than as an index into source the agent
  5524. // already has.
  5525. if (backReferencedFiles.length > 0) {
  5526. lines[verbatimHeaderIdx] += ` (Files marked **"Already sent earlier in this conversation"** are not repeated: their source came back on an earlier codegraph_explore call in THIS conversation and the file has not changed since, so that copy is exact and current — scroll back for it rather than re-fetching or Reading.)`;
  5527. }
  5528. // Drift epilogue (#1474). The "verbatim / do not Read" guarantee above
  5529. // stays TRUE for everything actually rendered (drifted files ship whole or
  5530. // not at all — never as a possibly-wrong slice), but two caveats must be
  5531. // explicit: omitted files need Reading, and index-derived LINE REFERENCES
  5532. // to any drifted file (flow steps, blast radius, trail) may be shifted.
  5533. if (staleOmitted.length > 0) {
  5534. lines[verbatimHeaderIdx] += ' (Exception: files flagged "⚠ changed on disk" below drifted from the index after their last sync — their source is omitted rather than risk a mis-sliced block; Read those specific files.)';
  5535. }
  5536. const staleAll = [...new Set([...staleOmitted, ...staleRendered])];
  5537. if (staleAll.length > 0) {
  5538. lines.push(
  5539. '',
  5540. `> ⚠ Changed on disk after the last index sync: ${staleAll.join(', ')}. Line numbers referencing ${staleAll.length === 1 ? 'this file' : 'these files'} elsewhere in this response (flow steps, blast radius, symbol lists) may be shifted until that project's next sync re-indexes ${staleAll.length === 1 ? 'it' : 'them'}.`,
  5541. );
  5542. }
  5543. // Everything pushed from here on is EPILOGUE — meta-text ABOUT the response
  5544. // rather than part of it. Marked so the hard-ceiling cut at the end can
  5545. // spend it before it spends a rendered file section (CG-31): a section is
  5546. // source the agent otherwise has to Read; the epilogue is a pointer list and
  5547. // two reminders, and the note that replaces it carries their instruction.
  5548. //
  5549. // Drawn AFTER the drift warning on purpose — that one is an honesty claim
  5550. // about source we did render, not a note about the response, so it is never
  5551. // the thing we drop. Lines already in `lines` are only MUTATED from here on
  5552. // (the verbatim header, the summary sentinel), never re-ordered, so the
  5553. // index stays valid.
  5554. const epilogueStart = lines.length;
  5555. // The curated header count is computed from the files that SURVIVE the final
  5556. // truncation (see end of method) — `filesIncluded` can over-count when the
  5557. // hard ceiling drops trailing sections — so leave a sentinel here and fill it
  5558. // in once the output is final.
  5559. lines[summaryLineIdx] = SUMMARY_SENTINEL;
  5560. // Add remaining files as references (from both relevant and peripheral files).
  5561. // Small projects (per budget) skip this — the relevant story already fits
  5562. // in the source section, and a trailing pointer list is pure overhead. But a
  5563. // CLIFFED file is source we deliberately withheld, so the list is forced on
  5564. // whenever there is one: withholding a file's bytes is only cheap if the agent
  5565. // can still name it in a follow-up call (CG-12).
  5566. // The epilogue's three blocks are BUILT here and FITTED below (CG-26) —
  5567. // they are not pushed straight into `lines` any more. The render loop
  5568. // budgets for the epilogue floor it committed to (`EPILOGUE_FLOOR`); what
  5569. // the response can afford above that floor is only known now, so the
  5570. // blocks are assembled against the room that actually remains, in priority
  5571. // order, instead of being emitted whole and then discarded whole.
  5572. const pointerEntries: string[] = [];
  5573. let pointerOmitted = 0;
  5574. if (budget.includeAdditionalFiles || cliffedFiles.size > 0) {
  5575. // Everything ranked that didn't render, in rank order — cliffed files first,
  5576. // since they outrank whatever the file cap cut. (Indexing by `filesIncluded`
  5577. // would be wrong now that cliffed files are skipped without consuming a slot.)
  5578. const rendered = new Set(renderedFilePaths);
  5579. const remainingRelevant = sortedFiles.filter(([fp]) => !rendered.has(fp));
  5580. // Ranked files are already covered by `remainingRelevant`; the rest of the
  5581. // gather (below the floor) becomes the pointer list. The Set guards the
  5582. // one overlap case — a file the SCORE_FLOOR_KEEP_MIN fallback pulled in
  5583. // despite scoring under the relative floor.
  5584. const rankedPaths = new Set(sortedFiles.map(([fp]) => fp));
  5585. const peripheralFiles = [...fileGroups.entries()]
  5586. .filter(([fp, group]) => group.score < scoreFloor && !rankedPaths.has(fp))
  5587. .sort((a, b) => b[1].score - a[1].score);
  5588. const remainingFiles = [...remainingRelevant, ...peripheralFiles];
  5589. for (const [filePath, group] of remainingFiles.slice(0, POINTER_MAX_FILES)) {
  5590. pointerEntries.push(pointerLineFor(filePath, group.nodes));
  5591. }
  5592. pointerOmitted = Math.max(0, remainingFiles.length - pointerEntries.length);
  5593. }
  5594. // Completeness signal so agents know they don't need to re-read these files.
  5595. // On small projects the budget gates this off — but if we actually had to
  5596. // trim or drop clusters, surface a brief note so the agent knows it can
  5597. // still Read for more detail.
  5598. const completenessBlock: string[] = budget.includeCompletenessSignal
  5599. ? ['', '---', `> **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.`]
  5600. : anyFileTrimmed
  5601. ? ['', `> Some file sections were trimmed for size. Elided symbols are named inside gap markers as \`name (file:line)\` and preferred in the file header — run another \`codegraph_explore\` (or \`codegraph_node\`) with those exact names for their source.`]
  5602. : [];
  5603. // Explore budget note based on project size.
  5604. let budgetBlock: string[] = [];
  5605. if (budget.includeBudgetNote) {
  5606. try {
  5607. const stats = cg.getStats();
  5608. const callBudget = getExploreBudget(stats.fileCount);
  5609. budgetBlock = ['', `> **Explore budget: ${callBudget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).** Each call covers ~6 files; if your question spans more, spend your remaining calls on the uncovered area BEFORE falling back to Read — another explore is cheaper and more complete than reading those files. Synthesize once you've used ${callBudget}.`];
  5610. } catch {
  5611. // Stats unavailable — skip budget note
  5612. }
  5613. }
  5614. // FIT THE EPILOGUE (CG-26). Before this, the epilogue was emitted whole and
  5615. // then, on a saturated response, discarded whole by the hard ceiling — four
  5616. // of six suite repos shipped with no pointer list and no reminders at all,
  5617. // and the render loop had "budgeted" 600 chars for something that measures
  5618. // 1,064–2,231. Neither number was the real one, because the epilogue is not
  5619. // one thing: a fixed floor the loop reserves for (the cut note, plus a
  5620. // pointer for every file whose bytes were deliberately WITHHELD — CG-12
  5621. // makes those names load-bearing) and an elastic tail that takes what is
  5622. // left. Assembled in priority order — the do-not-re-read reminder first,
  5623. // then pointers in rank order, then the budget note — and emitted in
  5624. // document order.
  5625. const roomFor = (block: readonly string[]): number =>
  5626. block.reduce((n, s) => n + s.length + 1, 0);
  5627. let room = hardCeiling - (flow.text.length + lines.join('\n').length);
  5628. const keepCompleteness = completenessBlock.length > 0
  5629. && roomFor(completenessBlock) <= room;
  5630. if (keepCompleteness) room -= roomFor(completenessBlock);
  5631. const pointerBlock: string[] = [];
  5632. if (pointerEntries.length > 0) {
  5633. const head = [POINTER_HEADER, ''];
  5634. let left = room - roomFor(head);
  5635. if (left >= 0) {
  5636. let taken = 0;
  5637. for (const entry of pointerEntries) {
  5638. // Every entry we do NOT take has to be confessed by the tail line, so
  5639. // the tail's cost is part of taking one less than all of them.
  5640. const dropped = pointerEntries.length - taken - 1 + pointerOmitted;
  5641. const tail = dropped > 0 ? roomFor([`- ... and ${dropped} more files`]) : 0;
  5642. if (entry.length + 1 + tail > left) break;
  5643. left -= entry.length + 1;
  5644. taken++;
  5645. }
  5646. if (taken > 0) {
  5647. pointerBlock.push(...head, ...pointerEntries.slice(0, taken));
  5648. const dropped = pointerEntries.length - taken + pointerOmitted;
  5649. if (dropped > 0) pointerBlock.push(`- ... and ${dropped} more files`);
  5650. room -= roomFor(pointerBlock);
  5651. }
  5652. }
  5653. }
  5654. // Nothing of the pointer list survived, but there WAS one — say so, in the
  5655. // one line that carries its instruction forward.
  5656. const pointersLost = pointerEntries.length > 0 && pointerBlock.length === 0;
  5657. const keepBudgetNote = budgetBlock.length > 0 && roomFor(budgetBlock) <= room;
  5658. if (keepBudgetNote) room -= roomFor(budgetBlock);
  5659. lines.push(...pointerBlock);
  5660. if (keepCompleteness) lines.push(...completenessBlock);
  5661. if (keepBudgetNote) lines.push(...budgetBlock);
  5662. if (pointersLost && roomFor([EPILOGUE_LOST_NOTE, '']) <= room) {
  5663. lines.push('', EPILOGUE_LOST_NOTE);
  5664. }
  5665. const output = flow.text + lines.join('\n');
  5666. let finalText: string;
  5667. // The epilogue costs less than a file section, so it is cut FIRST (CG-31).
  5668. // Dropping a trailing section throws away source the render loop had already
  5669. // set that file's reservation aside for — the exact starvation the
  5670. // displacement guard exists to prevent, arriving after the guard has done
  5671. // its work. The epilogue is a pointer list and two reminders; its own
  5672. // "explore these names" instruction survives in the note below.
  5673. const epilogueOnlyCut = epilogueStart < lines.length
  5674. ? flow.text + lines.slice(0, epilogueStart).join('\n')
  5675. : null;
  5676. const EPILOGUE_CUT_NOTE = '\n\n> (Trailing notes omitted for size. The source above is complete and verbatim — treat it as already Read. For anything this call did not cover, run another codegraph_explore with the specific names rather than reading those files.)';
  5677. if (output.length > hardCeiling
  5678. && epilogueOnlyCut !== null
  5679. && epilogueOnlyCut.length + EPILOGUE_CUT_NOTE.length <= hardCeiling) {
  5680. finalText = epilogueOnlyCut + EPILOGUE_CUT_NOTE;
  5681. } else if (output.length > hardCeiling) {
  5682. // Still over with the epilogue gone: cut at a FILE-SECTION boundary (the
  5683. // last ``**` `` file header before the ceiling) so we drop whole trailing
  5684. // file-sections rather than slicing
  5685. // through a method body — a half-rendered method just forces the Read this
  5686. // tool exists to prevent. Fall back to a line boundary only if no section
  5687. // header sits in the back half (degenerate single-giant-section case).
  5688. const cut = output.slice(0, hardCeiling);
  5689. const lastSection = cut.lastIndexOf('\n' + FILE_SECTION_PREFIX);
  5690. const boundary = lastSection > hardCeiling * 0.5 ? lastSection : cut.lastIndexOf('\n');
  5691. const safe = boundary > 0 ? cut.slice(0, boundary) : cut;
  5692. finalText = safe + '\n\n... (output truncated to budget; the source above is complete and verbatim — treat it as already Read. For any area not covered, run another codegraph_explore with the specific names — do NOT Read these files.)';
  5693. } else {
  5694. finalText = output;
  5695. }
  5696. // Curated header (#1046): substitute the sentinel with the count of files
  5697. // whose source SURVIVES in the final text — not `subgraph`/`fileGroups` (the
  5698. // raw gather a broad query inflates) and not `filesIncluded` (which can
  5699. // over-count when the ceiling above drops trailing sections). A file counts
  5700. // only if its section header is still present; its relevant (non-import)
  5701. // symbols are summed for N. Files we couldn't fit are still named under "Not
  5702. // shown above" + the budget note, so nothing is silently dropped.
  5703. const survivors = renderedFilePaths.filter((fp) =>
  5704. finalText.includes(`${FILE_SECTION_PREFIX}${fp}\``));
  5705. const shownSymbols = survivors.reduce((sum, fp) => {
  5706. const g = fileGroups.get(fp);
  5707. if (!g) return sum;
  5708. return sum + new Set(
  5709. g.nodes.filter((n) => n.kind !== 'import' && n.kind !== 'export').map((n) => n.id),
  5710. ).size;
  5711. }, 0);
  5712. let summaryLine = survivors.length > 0
  5713. ? `Found ${shownSymbols} symbol${shownSymbols === 1 ? '' : 's'} across ${survivors.length} file${survivors.length === 1 ? '' : 's'}.`
  5714. : `Found ${subgraph.nodes.size} symbol${subgraph.nodes.size === 1 ? '' : 's'} across ${fileGroups.size} file${fileGroups.size === 1 ? '' : 's'}.`;
  5715. // Path pinning is visible, not silent: say which query-named files were
  5716. // honored, and which path spans matched nothing so the agent can correct
  5717. // them instead of trusting a response that quietly ignored the path.
  5718. const pinnedShown = pinnedFiles.filter((fp) => survivors.includes(fp)).length;
  5719. if (pinnedShown > 0) {
  5720. summaryLine += ` ${pinnedShown} file${pinnedShown === 1 ? '' : 's'} pinned from the query.`;
  5721. }
  5722. if (unresolvedPathSpans.length > 0) {
  5723. summaryLine += ` No indexed file uniquely matches ${unresolvedPathSpans.map((s) => `\`${s}\``).join(', ')}.`;
  5724. }
  5725. finalText = finalText.replace(SUMMARY_SENTINEL, summaryLine);
  5726. // Emit the allocation diagnostic from the FINAL text, so per-file bytes and
  5727. // shares account for the hard-ceiling truncation above (CG-4).
  5728. diag?.finish(finalText, output.length, hardCeiling, filesIncluded);
  5729. // Session record (CG-17): only the files that SURVIVED the hard ceiling —
  5730. // a section the truncation dropped was never delivered, and recording it
  5731. // would let a later call withhold source the agent has never seen.
  5732. //
  5733. // A back-referenced file records its spans at ZERO bytes (CG-18) — it is
  5734. // still source the agent holds for this file, which is what the record
  5735. // means; dropping it would let the span age out of the retained window and
  5736. // be re-served for nothing.
  5737. const emittedFiles: ExploreFileEmission[] = [];
  5738. let sourceBytes = 0;
  5739. for (const fp of survivors) {
  5740. const emitted = emittedByFile.get(fp);
  5741. if (!emitted || emitted.ranges.length === 0) continue;
  5742. emittedFiles.push({
  5743. path: fp,
  5744. ranges: emitted.ranges,
  5745. bytes: emitted.bytes,
  5746. fingerprint: emitted.fingerprint,
  5747. });
  5748. sourceBytes += emitted.bytes;
  5749. }
  5750. return this.exploreResult(finalText, {
  5751. projectRoot,
  5752. query,
  5753. files: emittedFiles,
  5754. sourceBytes,
  5755. responseBytes: finalText.length,
  5756. });
  5757. }
  5758. /**
  5759. * An explore response plus the record of what it emitted (CG-17). The record
  5760. * rides the result only as far as {@link execute}, which files it into the
  5761. * calling session's state and deletes it — see {@link EXPLORE_EMISSION_KEY}.
  5762. */
  5763. private exploreResult(text: string, emission: ExploreEmission): ToolResult {
  5764. const result = this.textResult(text);
  5765. result[EXPLORE_EMISSION_KEY] = emission;
  5766. return result;
  5767. }
  5768. /**
  5769. * Handle codegraph_node
  5770. */
  5771. private async handleNode(args: Record<string, unknown>): Promise<ToolResult> {
  5772. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  5773. // Default to false to minimize context usage
  5774. const includeCode = args.includeCode === true;
  5775. const fileHint = typeof args.file === 'string' && args.file.trim() ? args.file.trim() : undefined;
  5776. const lineHint = typeof args.line === 'number' && args.line > 0 ? args.line : undefined;
  5777. const offset = typeof args.offset === 'number' && args.offset > 0 ? Math.floor(args.offset) : undefined;
  5778. const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : undefined;
  5779. const symbolsOnly = args.symbolsOnly === true;
  5780. const symbolRaw = typeof args.symbol === 'string' ? args.symbol.trim() : '';
  5781. // FILE READ MODE: a `file` with no `symbol` reads that file like the Read
  5782. // tool — its current on-disk source with line numbers, narrowable with
  5783. // `offset`/`limit` exactly as Read does — PLUS a one-line blast-radius
  5784. // header (which files depend on it). `symbolsOnly` returns just the
  5785. // structural map instead. Backed by the index: same bytes Read gives you.
  5786. if (!symbolRaw && fileHint) {
  5787. return this.handleFileView(cg, fileHint, { offset, limit, symbolsOnly });
  5788. }
  5789. const symbol = this.validateString(args.symbol, 'symbol');
  5790. if (typeof symbol !== 'string') return symbol;
  5791. let matches = this.findSymbolMatches(cg, symbol);
  5792. if (matches.length === 0) {
  5793. return this.textResult(`Symbol "${symbol}" not found in the codebase`);
  5794. }
  5795. // Disambiguate a heavily-overloaded name to a specific definition the caller
  5796. // pinned by file/line (the `file:line` a trail or another tool showed it) —
  5797. // so it can fetch e.g. `Harness::poll` at harness.rs:153 out of 50+ `poll`s
  5798. // instead of Reading. file matches by path suffix/substring; line prefers the
  5799. // def whose body contains it, else the nearest start. Only narrows (never
  5800. // empties — if a hint matches nothing it's ignored).
  5801. if (matches.length > 1 && (fileHint || lineHint !== undefined)) {
  5802. const norm = (p: string) => p.replace(/\\/g, '/').toLowerCase();
  5803. let narrowed = matches;
  5804. if (fileHint) {
  5805. const fh = norm(fileHint);
  5806. const byFile = narrowed.filter((n) => norm(n.filePath).endsWith(fh) || norm(n.filePath).includes(fh));
  5807. if (byFile.length > 0) narrowed = byFile;
  5808. }
  5809. if (lineHint !== undefined && narrowed.length > 1) {
  5810. const containing = narrowed.filter((n) => n.startLine <= lineHint && (n.endLine ?? n.startLine) >= lineHint);
  5811. narrowed = containing.length > 0
  5812. ? containing
  5813. : [...narrowed].sort((a, b) => Math.abs(a.startLine - lineHint) - Math.abs(b.startLine - lineHint)).slice(0, 1);
  5814. }
  5815. if (narrowed.length > 0) matches = narrowed;
  5816. }
  5817. // Single definition — the common case.
  5818. if (matches.length === 1) {
  5819. return this.textResult(this.truncateOutput(await this.renderNodeSection(cg, matches[0]!, includeCode)));
  5820. }
  5821. // Multiple definitions share this name — overloads, or same-named methods on
  5822. // different types (Alamofire `didCompleteTask`/`task`/`validate`, gin
  5823. // `reset`). Returning ONE forces the agent to guess, and when it guesses
  5824. // wrong it READS the file to find the right overload — the dominant
  5825. // codegraph_node read cause on Swift/Go. So return them ALL: pack as many
  5826. // FULL bodies as fit a char budget (the agent gets the one it needs in this
  5827. // one call, no follow-up parameter to learn), and list any remainder by
  5828. // file:line so a large overload set can't overflow the per-tool cap.
  5829. const header = `**${matches.length} definitions named "${symbol}"**`;
  5830. if (!includeCode) {
  5831. const list = matches.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`);
  5832. return this.textResult(this.truncateOutput(
  5833. [header, '', 'Re-query with `includeCode: true` to get every body in one call — no need to pick one first.', '', ...list].join('\n'),
  5834. ));
  5835. }
  5836. const BODY_BUDGET = 12000; // leaves room under MAX_OUTPUT_LENGTH for the header + list
  5837. // The CHAR budget is the real limiter — keep the count cap high so a set of
  5838. // SHORT overloads (Alamofire's 10 `validate` variants, each a few lines) all
  5839. // render in full rather than relegating the one the agent wanted to a
  5840. // bodiless list. Only a set of many LARGE bodies hits the char budget first.
  5841. const HARD_CAP = 16;
  5842. const rendered: string[] = [];
  5843. const listed: Node[] = [];
  5844. let used = 0;
  5845. for (const n of matches) {
  5846. if (rendered.length >= HARD_CAP) { listed.push(n); continue; }
  5847. const section = await this.renderNodeSection(cg, n, true);
  5848. // Always emit the first; emit the rest only while within the char budget.
  5849. if (rendered.length === 0 || used + section.length <= BODY_BUDGET) {
  5850. rendered.push(section);
  5851. used += section.length;
  5852. } else {
  5853. listed.push(n);
  5854. }
  5855. }
  5856. const out: string[] = [
  5857. header,
  5858. `Returning ${rendered.length} in full${listed.length ? `; ${listed.length} more listed below` : ''} — pick the one you need (no Read required).`,
  5859. '',
  5860. rendered.join('\n\n---\n\n'),
  5861. ];
  5862. if (listed.length) {
  5863. const LIST_CAP = 20;
  5864. const shownList = listed.slice(0, LIST_CAP);
  5865. out.push(
  5866. '',
  5867. '**Other definitions**',
  5868. ...shownList.map((n) => `- \`${n.name}\` (${n.kind}) — ${n.filePath}:${n.startLine}`),
  5869. );
  5870. if (listed.length > LIST_CAP) out.push(`- … +${listed.length - LIST_CAP} more`);
  5871. out.push(
  5872. '',
  5873. `> 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.`,
  5874. );
  5875. }
  5876. return this.textResult(this.truncateOutput(out.join('\n')));
  5877. }
  5878. /**
  5879. * FILE READ MODE: resolve `fileArg` (path or basename) to an indexed file and
  5880. * read it like the Read tool — its current on-disk source with line numbers,
  5881. * narrowable with `offset`/`limit` exactly as Read's are — preceded by a
  5882. * one-line blast-radius header (which files depend on it). `symbolsOnly`
  5883. * returns just the structural map (symbols + dependents) instead of source.
  5884. *
  5885. * Parity goal: the numbered source block is byte-for-byte the shape Read
  5886. * returns (`<n>\t<line>`, no padding), so the agent treats it as a Read — only
  5887. * faster (served from the index) and with the blast radius attached. Security:
  5888. * yaml/properties files are summarized by key, never dumped (#383); reads go
  5889. * through validatePathWithinRoot (#527).
  5890. */
  5891. private async handleFileView(
  5892. cg: CodeGraph,
  5893. fileArg: string,
  5894. opts: { offset?: number; limit?: number; symbolsOnly?: boolean } = {},
  5895. ): Promise<ToolResult> {
  5896. const normalize = (p: string) => p.replace(/\\/g, '/').replace(/^(?:\.?\/+)+/, '').replace(/\/+$/, '');
  5897. const wantLower = normalize(fileArg).toLowerCase();
  5898. const allFiles = cg.getFiles();
  5899. if (allFiles.length === 0) return this.textResult('No files indexed. Run `codegraph index` first.');
  5900. let resolved = allFiles.find((f) => f.path.toLowerCase() === wantLower);
  5901. let candidates: typeof allFiles = [];
  5902. if (!resolved) {
  5903. candidates = allFiles.filter((f) => f.path.toLowerCase().endsWith('/' + wantLower));
  5904. if (candidates.length === 1) resolved = candidates[0];
  5905. }
  5906. if (!resolved && candidates.length === 0) {
  5907. candidates = allFiles.filter((f) => f.path.toLowerCase().includes(wantLower));
  5908. if (candidates.length === 1) resolved = candidates[0];
  5909. }
  5910. if (!resolved && candidates.length > 1) {
  5911. return this.textResult(
  5912. [`"${fileArg}" matches ${candidates.length} indexed files — pass a longer path:`, '',
  5913. ...candidates.slice(0, 25).map((f) => `- ${f.path}`)].join('\n'),
  5914. );
  5915. }
  5916. if (!resolved) {
  5917. return this.textResult(
  5918. `No indexed file matches "${fileArg}". Codegraph indexes source files; configs/docs it doesn't parse won't appear — Read those directly.`,
  5919. );
  5920. }
  5921. const filePath = resolved.path;
  5922. const nodes = cg.getNodesInFile(filePath)
  5923. .filter((n) => n.kind !== 'file' && n.kind !== 'import' && n.kind !== 'export')
  5924. .sort((a, b) => a.startLine - b.startLine);
  5925. const dependents = cg.getFileDependents(filePath);
  5926. // Compact, one-line blast radius (codegraph's value-add over a plain Read).
  5927. const depSummary = dependents.length
  5928. ? `used by ${dependents.length} file${dependents.length === 1 ? '' : 's'}: ${dependents.slice(0, 8).join(', ')}${dependents.length > 8 ? `, +${dependents.length - 8} more` : ''}`
  5929. : 'no other indexed file depends on it';
  5930. // Symbol-map renderer — for symbolsOnly, the config fallback, and read errors.
  5931. const symbolMap = (heading: string, limit = 200): string[] => {
  5932. const lines: string[] = [heading];
  5933. for (const n of nodes.slice(0, limit)) {
  5934. const sig = n.signature ? ` ${n.signature.replace(/\s+/g, ' ').trim()}` : '';
  5935. lines.push(`- \`${n.name}\` (${n.kind})${sig} — :${n.startLine}`);
  5936. }
  5937. if (nodes.length > limit) lines.push(`- … +${nodes.length - limit} more`);
  5938. return lines;
  5939. };
  5940. // symbolsOnly → the cheap structural overview, no source.
  5941. if (opts.symbolsOnly) {
  5942. const out = [`**${filePath}** — ${nodes.length} symbol${nodes.length === 1 ? '' : 's'}, ${depSummary}`, ''];
  5943. if (nodes.length) out.push(...symbolMap('**Symbols**'));
  5944. else out.push('_No indexed symbols in this file._');
  5945. out.push('', '> Drop `symbolsOnly` (or pass `offset`/`limit`) to read the source, like Read.');
  5946. return this.textResult(this.truncateOutput(out.join('\n')));
  5947. }
  5948. // SECURITY (#383): never dump a raw config/data file — a yaml/properties
  5949. // line is `key: <secret>`. Summarize by key and point to a real Read.
  5950. if (CONFIG_LEAF_LANGUAGES.has(resolved.language)) {
  5951. const out = [`**${filePath}** — configuration/data file, ${depSummary}`, ''];
  5952. if (nodes.length) out.push(...symbolMap('**Keys (values withheld for safety)**'));
  5953. out.push('', '> Values may be secrets, so codegraph indexes keys only. Read the file directly if you need a value.');
  5954. return this.textResult(this.truncateOutput(out.join('\n')));
  5955. }
  5956. // Read the current bytes from disk through the security chokepoint
  5957. // (validatePathWithinRoot: blocks `../` traversal and symlink escapes, #527).
  5958. const abs = validatePathWithinRoot(cg.getProjectRoot(), filePath);
  5959. let content: string | null = null;
  5960. if (abs) {
  5961. try { content = readFileSync(abs, 'utf-8'); } catch { content = null; }
  5962. }
  5963. if (content === null) {
  5964. const out = [`**${filePath}** — could not read from disk (it may have moved since indexing). ${depSummary}`, ''];
  5965. if (nodes.length) out.push(...symbolMap('**Symbols**'));
  5966. out.push('', `> Read \`${filePath}\` directly for its current content.`);
  5967. return this.textResult(this.truncateOutput(out.join('\n')));
  5968. }
  5969. // Split exactly as Read does — keep the trailing empty line a final newline
  5970. // produces (Read numbers it too), so line numbers line up byte-for-byte.
  5971. const fileLines = content.split('\n');
  5972. const total = fileLines.length;
  5973. // Read-parity windowing: `offset`/`limit` mean exactly what they do on Read
  5974. // (1-based start line; max line count). Default: the whole file, capped like
  5975. // Read at 2000 lines and bounded by a char budget that tracks explore's
  5976. // proven-safe ~38k response ceiling. Overflow is stated explicitly (Read
  5977. // paginates too) — never the silent 15k truncateOutput chop.
  5978. const CHAR_BUDGET = 38000;
  5979. const DEFAULT_LIMIT = 2000;
  5980. const offset = Math.max(1, opts.offset ?? 1);
  5981. if (offset > total) {
  5982. return this.textResult(`**${filePath}** has ${total} line${total === 1 ? '' : 's'} — offset ${offset} is past the end. ${depSummary}`);
  5983. }
  5984. const maxLines = Math.max(1, opts.limit ?? DEFAULT_LIMIT);
  5985. const start = offset - 1; // 0-based
  5986. const header = `**${filePath}** — ${total} lines, ${nodes.length} symbol${nodes.length === 1 ? '' : 's'} · ${depSummary}`;
  5987. // Numbered lines, byte-for-byte Read's shape: `<n>\t<line>`, no left-pad.
  5988. const numbered: string[] = [];
  5989. let used = header.length + 8;
  5990. let i = start;
  5991. for (; i < total && numbered.length < maxLines; i++) {
  5992. const ln = `${i + 1}\t${fileLines[i]}`;
  5993. if (used + ln.length + 1 > CHAR_BUDGET && numbered.length > 0) break;
  5994. numbered.push(ln);
  5995. used += ln.length + 1;
  5996. }
  5997. const shownEnd = start + numbered.length;
  5998. const complete = offset === 1 && shownEnd >= total;
  5999. const out: string[] = [header, '', ...numbered];
  6000. if (!complete) {
  6001. out.push(
  6002. '',
  6003. `(lines ${offset}–${shownEnd} of ${total} — pass \`offset\`/\`limit\` for another range, or \`codegraph_node <symbol>\` for one symbol in full)`,
  6004. );
  6005. }
  6006. // Self-bounded to CHAR_BUDGET — do NOT route through truncateOutput (15k).
  6007. return this.textResult(out.join('\n'));
  6008. }
  6009. /** Render one symbol: details + (optional) body/outline + its caller/callee trail. */
  6010. private async renderNodeSection(cg: CodeGraph, node: Node, includeCode: boolean): Promise<string> {
  6011. // Disk-drift gate (issue #1474): the body below is CURRENT bytes sliced at
  6012. // INDEXED line ranges. If the file changed since its last index sync, that
  6013. // slice can be a DIFFERENT symbol's code served under this node's name —
  6014. // confidently wrong, with no watcher banner to catch it on a `projectPath`
  6015. // (cross-project) target. Never emit a slice from a drifted file.
  6016. if (this.isFileStaleOnDisk(cg, node.filePath)) {
  6017. return this.renderStaleNodeSection(cg, node, includeCode);
  6018. }
  6019. let code: string | null = null;
  6020. let outline: string | null = null;
  6021. if (includeCode) {
  6022. // For container symbols (class/interface/struct/…), the full body is the
  6023. // sum of every method body — a wall of source. Return a structural outline
  6024. // (members + signatures + line numbers) instead; leaf symbols return their
  6025. // full body.
  6026. if (CONTAINER_NODE_KINDS.has(node.kind)) {
  6027. outline = this.buildContainerOutline(cg, node);
  6028. }
  6029. if (!outline) {
  6030. code = await cg.getCode(node.id);
  6031. }
  6032. }
  6033. return this.formatNodeDetails(node, code, outline) + this.formatTrail(cg, node);
  6034. }
  6035. // Whole-file fallback caps for a drifted file (#1474): small enough to fit
  6036. // codegraph_node's output cap (MAX_OUTPUT_LENGTH) with headroom for the
  6037. // header + trail. A file within these bounds is served WHOLE and CURRENT
  6038. // (Read-parity, correct by construction) instead of a possibly-wrong slice.
  6039. private static readonly STALE_WHOLE_FILE_MAX_LINES = 300;
  6040. private static readonly STALE_WHOLE_FILE_MAX_CHARS = 12000;
  6041. /**
  6042. * codegraph_node render for a symbol whose file changed on disk after the
  6043. * last index sync (issue #1474). The indexed line range is no longer
  6044. * trustworthy, so no slice is emitted: a small file gets its full CURRENT
  6045. * source (Read-parity — sufficiency preserved, the agent still doesn't need
  6046. * Read); a large one gets an explicit notice steering to the tool's own
  6047. * file-read mode (or Read) — honest absence instead of confident wrongness.
  6048. * Location/signature stay (they're the index's answer) but are flagged as
  6049. * possibly shifted.
  6050. */
  6051. private renderStaleNodeSection(cg: CodeGraph, node: Node, includeCode: boolean): string {
  6052. const lines: string[] = [
  6053. `**${node.name}** (${node.kind})`,
  6054. '',
  6055. `**Location:** ${node.filePath}${node.startLine ? `:${node.startLine}` : ''} — ⚠ as of the last index sync; the file has changed on disk since, so this line may be shifted`,
  6056. ];
  6057. if (node.signature) {
  6058. lines.push(`**Signature:** \`${node.signature}\``);
  6059. }
  6060. lines.push('');
  6061. let embedded = false;
  6062. if (includeCode) {
  6063. try {
  6064. const absPath = validatePathWithinRoot(cg.getProjectRoot(), node.filePath);
  6065. if (absPath && existsSync(absPath) && !isConfigLeafNode(node)) {
  6066. const content = readFileSync(absPath, 'utf-8');
  6067. const body = content.replace(/\n+$/, '');
  6068. if (
  6069. body.length <= ToolHandler.STALE_WHOLE_FILE_MAX_CHARS &&
  6070. body.split('\n').length <= ToolHandler.STALE_WHOLE_FILE_MAX_LINES
  6071. ) {
  6072. lines.push(
  6073. `> ⚠ \`${node.filePath}\` changed on disk after it was last indexed, so the indexed line range for this symbol may no longer match. Showing the file's full CURRENT source instead (Read-parity — treat it as already Read):`,
  6074. '',
  6075. '```' + (node.language || ''),
  6076. numberSourceLines(body, 1),
  6077. '```',
  6078. );
  6079. embedded = true;
  6080. }
  6081. }
  6082. } catch {
  6083. /* fall through to the notice */
  6084. }
  6085. }
  6086. if (!embedded) {
  6087. lines.push(
  6088. `> ⚠ \`${node.filePath}\` changed on disk after it was last indexed — the indexed line range for this symbol no longer reliably matches, so its body is omitted rather than risk showing a different symbol's code. For current content, call codegraph_node with \`file: "${node.filePath}"\` (no symbol; \`offset\`/\`limit\` narrow it like Read), or Read the file. The change is picked up automatically on that project's next index sync.`,
  6089. );
  6090. }
  6091. return lines.join('\n') + this.formatTrail(cg, node);
  6092. }
  6093. /**
  6094. * Build the "trail" for a symbol: its direct callees (what it calls) and
  6095. * callers (what calls it), each with file:line — so codegraph_node doubles as
  6096. * the structural Grep→Read→expand primitive: a spot PLUS where to go next.
  6097. * Capped to stay cheap. Walk the graph by calling codegraph_node on a trail
  6098. * entry; no Read needed for covered hops. Empty edges on a non-leaf often mean
  6099. * dynamic dispatch the static graph couldn't resolve — that absence is itself
  6100. * a signal (read that one hop) rather than a dead end.
  6101. */
  6102. private formatTrail(cg: CodeGraph, node: Node): string {
  6103. const TRAIL_CAP = 12;
  6104. const fmt = (e: { node: Node; edge: Edge }) => {
  6105. const base = `${e.node.name} (${e.node.filePath}:${e.node.startLine})`;
  6106. const synth = this.synthEdgeNote(e.edge);
  6107. return synth ? `${base} [${synth.compact}]` : base;
  6108. };
  6109. const collect = (edges: Array<{ node: Node; edge: Edge }>): Array<{ node: Node; edge: Edge }> => {
  6110. const seen = new Set<string>([node.id]);
  6111. const out: Array<{ node: Node; edge: Edge }> = [];
  6112. for (const e of edges) {
  6113. if (seen.has(e.node.id)) continue;
  6114. seen.add(e.node.id);
  6115. out.push(e);
  6116. }
  6117. return out;
  6118. };
  6119. const callees = collect(cg.getCallees(node.id));
  6120. const callers = collect(cg.getCallers(node.id));
  6121. if (callees.length === 0 && callers.length === 0) return '';
  6122. const lines: string[] = ['', '**Trail — codegraph_node any of these to follow it (no Read needed)**'];
  6123. if (callees.length > 0) {
  6124. lines.push(`**Calls →** ${callees.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callees.length > TRAIL_CAP ? `, +${callees.length - TRAIL_CAP} more` : ''}`);
  6125. }
  6126. if (callers.length > 0) {
  6127. lines.push(`**Called by ←** ${callers.slice(0, TRAIL_CAP).map(fmt).join(', ')}${callers.length > TRAIL_CAP ? `, +${callers.length - TRAIL_CAP} more` : ''}`);
  6128. }
  6129. return lines.join('\n');
  6130. }
  6131. /**
  6132. * Handle codegraph_status
  6133. */
  6134. private async handleStatus(args: Record<string, unknown>): Promise<ToolResult> {
  6135. let cg = this.getCodeGraph(args.projectPath as string | undefined);
  6136. // Same trick as withStalenessNotice — when an explicit projectPath
  6137. // resolves to the same project as the default session cg, prefer the
  6138. // default so getPendingFiles() (only populated by the default's watcher)
  6139. // is non-empty when there are pending edits.
  6140. if (this.cg && cg !== this.cg) {
  6141. try {
  6142. if (resolvePath(this.cg.getProjectRoot()) === resolvePath(cg.getProjectRoot())) {
  6143. cg = this.cg;
  6144. }
  6145. } catch { /* closed instance — leave as is */ }
  6146. }
  6147. const stats = cg.getStats();
  6148. // Warn when this index actually belongs to a different git working tree
  6149. // (e.g. the server resolved up from a nested worktree to the main checkout).
  6150. // Queries then reflect that tree's branch, not the worktree being edited.
  6151. // status shows the verbose, multi-line form; the read tools get the compact
  6152. // one-liner via withWorktreeNotice. Both share the cached detection.
  6153. const mismatch = this.worktreeMismatchFor(args.projectPath as string | undefined);
  6154. const lines: string[] = [
  6155. '**CodeGraph Status**',
  6156. '',
  6157. ];
  6158. if (mismatch) {
  6159. lines.push(`> ⚠ ${worktreeMismatchWarning(mismatch).replace(/\n/g, '\n> ')}`, '');
  6160. }
  6161. lines.push(
  6162. `**Files indexed:** ${stats.fileCount}`,
  6163. `**Total nodes:** ${stats.nodeCount}`,
  6164. `**Total edges:** ${stats.edgeCount}`,
  6165. `**Database size:** ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`,
  6166. );
  6167. // Surface the active SQLite backend (node:sqlite, Node's built-in real
  6168. // SQLite — full WAL + FTS5, no native build).
  6169. lines.push(`**Backend:** node:sqlite (Node built-in) — full WAL + FTS5`);
  6170. // Effective journal mode. 'wal' ⇒ concurrent reads never block on a writer;
  6171. // anything else ⇒ they can ("database is locked"). node:sqlite supports WAL
  6172. // everywhere, so a non-wal mode means the filesystem can't (network/
  6173. // virtualized mounts, WSL2 /mnt). See issue #238.
  6174. const journalMode = cg.getJournalMode();
  6175. if (journalMode === 'wal') {
  6176. lines.push(`**Journal mode:** wal (concurrent reads safe)`);
  6177. } else {
  6178. lines.push(
  6179. `**Journal mode:** ⚠ ${journalMode || 'unknown'} — WAL not active, so reads ` +
  6180. `can block on a concurrent write (WAL appears unsupported on this filesystem)`
  6181. );
  6182. }
  6183. // A newer release exists (#1243) — status is where users and agents look
  6184. // when something seems off, so surface the drift here too. Cheap memoized
  6185. // cache read; absent entirely when up to date or opted out.
  6186. const updateNotice = getUpdateNotice();
  6187. if (updateNotice) {
  6188. lines.push(`**Update available:** ${updateNotice}`);
  6189. }
  6190. // Non-zero at rest means a resolution pass was interrupted mid-run, so
  6191. // some files' call/impact edges are missing until the next sync sweeps
  6192. // the leftovers (#1187). Surface it — an agent trusting an incomplete
  6193. // blast radius is worse than one that knows to re-sync.
  6194. const pendingRefs = cg.getPendingReferenceCount();
  6195. if (pendingRefs > 0) {
  6196. lines.push(
  6197. `**Pending resolution:** ⚠ ${pendingRefs} references from an interrupted ` +
  6198. `index run — some caller/impact edges are missing until the next sync ` +
  6199. `(any file change triggers it, or run \`codegraph sync\`)`
  6200. );
  6201. }
  6202. lines.push('', '**Nodes by Kind:**');
  6203. for (const [kind, count] of Object.entries(stats.nodesByKind)) {
  6204. if ((count as number) > 0) {
  6205. lines.push(`- ${kind}: ${count}`);
  6206. }
  6207. }
  6208. lines.push('', '**Languages:**');
  6209. for (const [lang, count] of Object.entries(stats.filesByLanguage)) {
  6210. if ((count as number) > 0) {
  6211. lines.push(`- ${lang}: ${count}`);
  6212. }
  6213. }
  6214. // Whole-index degradation (#876): when live watching has permanently
  6215. // stopped, getPendingFiles() is empty (so no "Pending sync" section below)
  6216. // but the index is frozen — call that out explicitly here, the one place an
  6217. // agent asks "is the index caught up?".
  6218. if (cg.isWatcherDegraded()) {
  6219. lines.push(
  6220. '',
  6221. '**Auto-sync disabled:**',
  6222. `- ${cg.getWatcherDegradedReason() ?? 'live file watching stopped'}`,
  6223. '- The index is frozen; Read files directly for current content.'
  6224. );
  6225. }
  6226. // Per-file freshness — the inverse of the auto-prepended staleness banner
  6227. // (issue #403). Surfacing it inside `status` gives the agent a single
  6228. // place to ask "is the index caught up?" rather than inferring from
  6229. // banners on other tool calls.
  6230. const pending = cg.getPendingFiles();
  6231. if (pending.length > 0) {
  6232. lines.push('', '**Pending sync:**');
  6233. const now = Date.now();
  6234. for (const p of pending) {
  6235. const ageMs = Math.max(0, now - p.lastSeenMs);
  6236. const label = p.indexing ? 'indexing in progress' : 'pending sync';
  6237. lines.push(`- ${p.path} (edited ${ageMs}ms ago, ${label})`);
  6238. }
  6239. }
  6240. return this.textResult(lines.join('\n'));
  6241. }
  6242. /**
  6243. * Handle codegraph_files - get project file structure from the index
  6244. */
  6245. private async handleFiles(args: Record<string, unknown>): Promise<ToolResult> {
  6246. const cg = this.getCodeGraph(args.projectPath as string | undefined);
  6247. const pathFilter = args.path as string | undefined;
  6248. const pattern = args.pattern as string | undefined;
  6249. const format = (args.format as 'tree' | 'flat' | 'grouped') || 'tree';
  6250. const includeMetadata = args.includeMetadata !== false;
  6251. const maxDepth = args.maxDepth != null ? clamp(args.maxDepth as number, 1, 20) : undefined;
  6252. // Get all files from the index
  6253. const allFiles = cg.getFiles();
  6254. if (allFiles.length === 0) {
  6255. return this.textResult('No files indexed. Run `codegraph index` first.');
  6256. }
  6257. // Filter by path prefix. Stored paths are project-relative POSIX (e.g.
  6258. // "src/foo.ts"), but agents commonly pass project-root variants like "/",
  6259. // ".", "./", "" or Windows-style "src\foo" — and prefixes with leading
  6260. // "/", "./" or "\". Normalize all of those before matching so the agent
  6261. // gets results instead of falling back to Read/Glob (see #426).
  6262. const normalizedFilter = pathFilter
  6263. ? pathFilter
  6264. .replace(/\\/g, '/')
  6265. .replace(/^(?:\.?\/+)+/, '')
  6266. .replace(/^\.$/, '')
  6267. .replace(/\/+$/, '')
  6268. : '';
  6269. let files = normalizedFilter
  6270. ? allFiles.filter(f => f.path === normalizedFilter || f.path.startsWith(normalizedFilter + '/'))
  6271. : allFiles;
  6272. // Filter by glob pattern
  6273. if (pattern) {
  6274. const regex = this.globToRegex(pattern);
  6275. files = files.filter(f => regex.test(f.path));
  6276. }
  6277. if (files.length === 0) {
  6278. return this.textResult(`No files found matching the criteria.`);
  6279. }
  6280. // Format output
  6281. let output: string;
  6282. switch (format) {
  6283. case 'flat':
  6284. output = this.formatFilesFlat(files, includeMetadata);
  6285. break;
  6286. case 'grouped':
  6287. output = this.formatFilesGrouped(files, includeMetadata);
  6288. break;
  6289. case 'tree':
  6290. default:
  6291. output = this.formatFilesTree(files, includeMetadata, maxDepth);
  6292. break;
  6293. }
  6294. return this.textResult(this.truncateOutput(output));
  6295. }
  6296. /**
  6297. * Convert glob pattern to regex
  6298. */
  6299. private globToRegex(pattern: string): RegExp {
  6300. const escaped = pattern
  6301. .replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special regex chars except * and ?
  6302. .replace(/\*\*/g, '{{GLOBSTAR}}') // Temp placeholder for **
  6303. .replace(/\*/g, '[^/]*') // * matches anything except /
  6304. .replace(/\?/g, '[^/]') // ? matches single char except /
  6305. .replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** matches anything including /
  6306. return new RegExp(escaped);
  6307. }
  6308. /**
  6309. * Format files as a flat list
  6310. */
  6311. private formatFilesFlat(files: { path: string; language: string; nodeCount: number }[], includeMetadata: boolean): string {
  6312. const lines: string[] = [`**Files (${files.length})**`, ''];
  6313. for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
  6314. if (includeMetadata) {
  6315. lines.push(`- ${file.path} (${file.language}, ${file.nodeCount} symbols)`);
  6316. } else {
  6317. lines.push(`- ${file.path}`);
  6318. }
  6319. }
  6320. return lines.join('\n');
  6321. }
  6322. /**
  6323. * Format files grouped by language
  6324. */
  6325. private formatFilesGrouped(files: { path: string; language: string; nodeCount: number }[], includeMetadata: boolean): string {
  6326. const byLang = new Map<string, typeof files>();
  6327. for (const file of files) {
  6328. const existing = byLang.get(file.language) || [];
  6329. existing.push(file);
  6330. byLang.set(file.language, existing);
  6331. }
  6332. const lines: string[] = [`**Files by Language (${files.length} total)**`, ''];
  6333. // Sort languages by file count (descending)
  6334. const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
  6335. for (const [lang, langFiles] of sortedLangs) {
  6336. lines.push(`**${lang} (${langFiles.length})**`);
  6337. for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
  6338. if (includeMetadata) {
  6339. lines.push(`- ${file.path} (${file.nodeCount} symbols)`);
  6340. } else {
  6341. lines.push(`- ${file.path}`);
  6342. }
  6343. }
  6344. lines.push('');
  6345. }
  6346. return lines.join('\n');
  6347. }
  6348. /**
  6349. * Format files as a tree structure
  6350. */
  6351. private formatFilesTree(
  6352. files: { path: string; language: string; nodeCount: number }[],
  6353. includeMetadata: boolean,
  6354. maxDepth?: number
  6355. ): string {
  6356. // Build tree structure
  6357. interface TreeNode {
  6358. name: string;
  6359. children: Map<string, TreeNode>;
  6360. file?: { language: string; nodeCount: number };
  6361. }
  6362. const root: TreeNode = { name: '', children: new Map() };
  6363. for (const file of files) {
  6364. const parts = file.path.split('/');
  6365. let current = root;
  6366. for (let i = 0; i < parts.length; i++) {
  6367. const part = parts[i];
  6368. if (!part) continue;
  6369. if (!current.children.has(part)) {
  6370. current.children.set(part, { name: part, children: new Map() });
  6371. }
  6372. current = current.children.get(part)!;
  6373. // If this is the last part, it's a file
  6374. if (i === parts.length - 1) {
  6375. current.file = { language: file.language, nodeCount: file.nodeCount };
  6376. }
  6377. }
  6378. }
  6379. // Render tree
  6380. const lines: string[] = [`**Project Structure (${files.length} files)**`, ''];
  6381. const renderNode = (node: TreeNode, prefix: string, isLast: boolean, depth: number): void => {
  6382. if (maxDepth !== undefined && depth > maxDepth) return;
  6383. const connector = isLast ? '└── ' : '├── ';
  6384. const childPrefix = isLast ? ' ' : '│ ';
  6385. if (node.name) {
  6386. let line = prefix + connector + node.name;
  6387. if (node.file && includeMetadata) {
  6388. line += ` (${node.file.language}, ${node.file.nodeCount} symbols)`;
  6389. }
  6390. lines.push(line);
  6391. }
  6392. const children = [...node.children.values()];
  6393. // Sort: directories first, then files, both alphabetically
  6394. children.sort((a, b) => {
  6395. const aIsDir = a.children.size > 0 && !a.file;
  6396. const bIsDir = b.children.size > 0 && !b.file;
  6397. if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
  6398. return a.name.localeCompare(b.name);
  6399. });
  6400. for (let i = 0; i < children.length; i++) {
  6401. const child = children[i]!;
  6402. const nextPrefix = node.name ? prefix + childPrefix : prefix;
  6403. renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
  6404. }
  6405. };
  6406. renderNode(root, '', true, 0);
  6407. return lines.join('\n');
  6408. }
  6409. // =========================================================================
  6410. // Symbol resolution helpers
  6411. // =========================================================================
  6412. /**
  6413. * Find a symbol by name, handling disambiguation when multiple matches exist.
  6414. * Returns the best match and a note about alternatives if any.
  6415. */
  6416. /**
  6417. * Check if a node matches a symbol query — see `matchesSymbol` in
  6418. * `../graph/named-symbol-flow`, which owns the rules.
  6419. */
  6420. private matchesSymbol(node: Node, symbol: string): boolean {
  6421. return matchesSymbol(node, symbol);
  6422. }
  6423. /**
  6424. * Find ALL definitions matching a name, ranked, so codegraph_node can return
  6425. * every overload instead of guessing one (the wrong guess → a Read). Keepers
  6426. * rank before generated stubs (.pb.go etc.); stable within a group preserves
  6427. * FTS order. Returns [] when nothing matches; a qualified lookup that finds no
  6428. * exact match returns [] rather than a misleading fuzzy file hit (#173); a
  6429. * bare name with no exact match falls back to the single top fuzzy result.
  6430. */
  6431. private findSymbolMatches(cg: CodeGraph, symbol: string): Node[] {
  6432. const isQualified = /[.\/]|::/.test(symbol);
  6433. // For a bare name, enumerate EVERY exact-name definition via the direct index
  6434. // (not FTS, which caps + ranks): tokio's `poll` has 50+ defs and the one the
  6435. // caller wants (`Harness::poll` at harness.rs:153) ranks below any search cut,
  6436. // so it could be neither rendered nor pinned by the file/line disambiguator —
  6437. // and the agent Read it. With the full set, the multi-overload render + the
  6438. // file/line filter can both reach it.
  6439. if (!isQualified) {
  6440. const exact = cg.getNodesByName(symbol);
  6441. if (exact.length > 0) {
  6442. const isGen = cg.generatedFilePredicate(exact.map((n) => n.filePath));
  6443. return [...exact].sort((a, b) => (isGen(a.filePath) ? 1 : 0) - (isGen(b.filePath) ? 1 : 0));
  6444. }
  6445. // No exact match — use the single top fuzzy result (e.g. a file basename).
  6446. const fuzzy = cg.searchNodes(symbol, { limit: 10 });
  6447. return fuzzy[0] ? [fuzzy[0].node] : [];
  6448. }
  6449. // Qualified lookup (`Session.request`, `stage_apply::run`): FTS + matchesSymbol.
  6450. const limit = 50;
  6451. let results = cg.searchNodes(symbol, { limit });
  6452. // FTS strips colons, so `stage_apply::run` searches the literal
  6453. // `stage_applyrun` and finds nothing. Re-search by the bare last part and
  6454. // let `matchesSymbol` filter by qualifier.
  6455. if (isQualified && results.length === 0) {
  6456. const tail = lastQualifierPart(symbol);
  6457. if (tail && tail !== symbol) results = cg.searchNodes(tail, { limit });
  6458. }
  6459. if (results.length === 0) return [];
  6460. const exactMatches = results.filter((r) => this.matchesSymbol(r.node, symbol));
  6461. if (exactMatches.length === 0) {
  6462. // No exact match — a qualified lookup must not fall back to a fuzzy file
  6463. // hit (#173); a bare name may use the single top fuzzy result.
  6464. return isQualified ? [] : results[0] ? [results[0].node] : [];
  6465. }
  6466. // Down-rank generated files (.pb.go, .pulsar.go, _grpc.pb.go, and anything
  6467. // whose header declares it generated) so a flow query prefers the keeper
  6468. // implementation over the generated stub.
  6469. const isGen = cg.generatedFilePredicate(exactMatches.map((r) => r.node.filePath));
  6470. return [...exactMatches]
  6471. .sort((a, b) => (isGen(a.node.filePath) ? 1 : 0) - (isGen(b.node.filePath) ? 1 : 0))
  6472. .map((r) => r.node);
  6473. }
  6474. /**
  6475. * Find ALL symbols matching a name. Used by callers/callees/impact to aggregate
  6476. * results across all matching symbols (e.g., multiple classes with an `execute` method).
  6477. *
  6478. * The resolution itself lives in `../graph/named-symbol-flow`, so the Flow
  6479. * strip and `codegraph_explore` resolve a written name to the same nodes.
  6480. */
  6481. private findAllSymbols(cg: CodeGraph, symbol: string): { nodes: Node[]; note: string } {
  6482. return findAllSymbols(cg, symbol);
  6483. }
  6484. /**
  6485. * Truncate output if it exceeds the maximum length
  6486. */
  6487. private truncateOutput(text: string): string {
  6488. if (text.length <= MAX_OUTPUT_LENGTH) return text;
  6489. const truncated = text.slice(0, MAX_OUTPUT_LENGTH);
  6490. const lastNewline = truncated.lastIndexOf('\n');
  6491. const cutPoint = lastNewline > MAX_OUTPUT_LENGTH * 0.8 ? lastNewline : MAX_OUTPUT_LENGTH;
  6492. return truncated.slice(0, cutPoint) + '\n\n... (output truncated)';
  6493. }
  6494. // =========================================================================
  6495. // Formatting helpers (compact by default to reduce context usage)
  6496. // =========================================================================
  6497. private formatSearchResults(results: SearchResult[]): string {
  6498. const lines: string[] = [`**Search Results (${results.length} found)**`, ''];
  6499. for (const result of results) {
  6500. const { node } = result;
  6501. const location = node.startLine ? `:${node.startLine}` : '';
  6502. // Compact format: one line per result with key info
  6503. lines.push(`**${node.name}** (${node.kind})`);
  6504. lines.push(`${node.filePath}${location}`);
  6505. if (node.signature) lines.push(`\`${node.signature}\``);
  6506. lines.push('');
  6507. }
  6508. return lines.join('\n');
  6509. }
  6510. private formatNodeList(nodes: Node[], title: string, labels?: Map<string, string>): string {
  6511. const lines: string[] = [`**${title} (${nodes.length} found)**`, ''];
  6512. for (const node of nodes) {
  6513. const location = node.startLine ? `:${node.startLine}` : '';
  6514. // Compact: just name, kind, location — plus the relationship when it
  6515. // isn't a plain call (callback registration, instantiation, …).
  6516. const label = labels?.get(node.id);
  6517. lines.push(
  6518. `- ${node.name} (${node.kind}) - ${node.filePath}${location}${label ? ` — via ${label}` : ''}`
  6519. );
  6520. }
  6521. return lines.join('\n');
  6522. }
  6523. /**
  6524. * Relationship label for a non-`calls` edge in callers/callees lists. A
  6525. * function-as-value edge (#756) is the high-signal one: `callers(cb)`
  6526. * showing "via callback registration" tells the agent this is where the
  6527. * callback is WIRED, not where it's invoked.
  6528. */
  6529. private edgeLabel(edge: Edge): string | null {
  6530. if (edge.kind === 'calls') return null;
  6531. if (edge.metadata?.fnRef === true) return 'callback registration';
  6532. if (edge.kind === 'instantiates') return 'instantiation';
  6533. if (edge.kind === 'imports') return 'import';
  6534. if (edge.kind === 'references') return 'reference';
  6535. return edge.kind;
  6536. }
  6537. private formatImpact(symbol: string, impact: Subgraph): string {
  6538. const nodeCount = impact.nodes.size;
  6539. // Compact format: just list affected symbols grouped by file
  6540. const lines: string[] = [
  6541. `**Impact: "${symbol}" affects ${nodeCount} symbols**`,
  6542. '',
  6543. ];
  6544. // Group by file
  6545. const byFile = new Map<string, Node[]>();
  6546. for (const node of impact.nodes.values()) {
  6547. const existing = byFile.get(node.filePath) || [];
  6548. existing.push(node);
  6549. byFile.set(node.filePath, existing);
  6550. }
  6551. for (const [file, nodes] of byFile) {
  6552. lines.push(`**${file}:**`);
  6553. // Compact: inline list
  6554. const nodeList = nodes.map(n => `${n.name}:${n.startLine}`).join(', ');
  6555. lines.push(nodeList);
  6556. lines.push('');
  6557. }
  6558. return lines.join('\n');
  6559. }
  6560. /**
  6561. * Build a compact structural outline of a container symbol from its
  6562. * indexed children (methods, fields, properties, …) — name, kind,
  6563. * line number, and signature — so the agent gets the shape of a class
  6564. * without the full source of every method. Returns '' when the container
  6565. * has no indexed children, so the caller can fall back to full source.
  6566. */
  6567. private buildContainerOutline(cg: CodeGraph, node: Node): string {
  6568. const children = cg.getChildren(node.id)
  6569. .filter(c => c.kind !== 'import' && c.kind !== 'export')
  6570. .sort((a, b) => (a.startLine ?? 0) - (b.startLine ?? 0));
  6571. if (children.length === 0) return '';
  6572. const lines = [`**Members (${children.length}):**`, ''];
  6573. for (const c of children) {
  6574. const loc = c.startLine ? `:${c.startLine}` : '';
  6575. const sig = c.signature ? ` — \`${c.signature}\`` : '';
  6576. lines.push(`- ${c.name} (${c.kind})${loc}${sig}`);
  6577. }
  6578. return lines.join('\n');
  6579. }
  6580. private formatNodeDetails(node: Node, code: string | null, outline?: string | null): string {
  6581. const location = node.startLine ? `:${node.startLine}` : '';
  6582. const lines: string[] = [
  6583. `**${node.name}** (${node.kind})`,
  6584. '',
  6585. `**Location:** ${node.filePath}${location}`,
  6586. ];
  6587. if (node.signature) {
  6588. lines.push(`**Signature:** \`${node.signature}\``);
  6589. }
  6590. // Only include docstring if it's short and useful
  6591. if (node.docstring && node.docstring.length < 200) {
  6592. lines.push('', node.docstring);
  6593. }
  6594. if (outline) {
  6595. lines.push('', outline, '',
  6596. `> Structural outline only. Read \`${node.filePath}\` or call codegraph_node on a specific member for its body.`);
  6597. } else if (code) {
  6598. // Line-numbered (cat -n style, like codegraph_explore and Read) so the
  6599. // agent can cite/edit exact lines without re-Reading the file for them.
  6600. const numbered = node.startLine ? numberSourceLines(code, node.startLine) : code;
  6601. lines.push('', '```' + node.language, numbered, '```');
  6602. }
  6603. return lines.join('\n');
  6604. }
  6605. private textResult(text: string): ToolResult {
  6606. return {
  6607. content: [{ type: 'text', text }],
  6608. };
  6609. }
  6610. private errorResult(message: string): ToolResult {
  6611. return {
  6612. content: [{ type: 'text', text: `Error: ${message}` }],
  6613. isError: true,
  6614. };
  6615. }
  6616. }