tools.ts 333 KB

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