store.ts 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413
  1. /**
  2. * QMD Store - Core data access and retrieval functions
  3. *
  4. * This module provides all database operations, search functions, and document
  5. * retrieval for QMD. It returns raw data structures that can be formatted by
  6. * CLI or MCP consumers.
  7. *
  8. * Usage:
  9. * const store = createStore("/path/to/db.sqlite");
  10. * // or use default path:
  11. * const store = createStore();
  12. */
  13. import { openDatabase, loadSqliteVec } from "./db.js";
  14. import type { Database } from "./db.js";
  15. import picomatch from "picomatch";
  16. import { createHash } from "crypto";
  17. import { readFileSync, realpathSync, statSync, mkdirSync } from "node:fs";
  18. // Note: node:path resolve is not imported — we export our own cross-platform resolve()
  19. import fastGlob from "fast-glob";
  20. import {
  21. LlamaCpp,
  22. getDefaultLlamaCpp,
  23. formatQueryForEmbedding,
  24. formatDocForEmbedding,
  25. withLLMSessionForLlm,
  26. type RerankDocument,
  27. type ILLMSession,
  28. } from "./llm.js";
  29. import type {
  30. NamedCollection,
  31. Collection,
  32. CollectionConfig,
  33. ContextMap,
  34. } from "./collections.js";
  35. // =============================================================================
  36. // Configuration
  37. // =============================================================================
  38. const HOME = process.env.HOME || "/tmp";
  39. export const DEFAULT_EMBED_MODEL = "embeddinggemma";
  40. export const DEFAULT_RERANK_MODEL = "ExpedientFalcon/qwen3-reranker:0.6b-q8_0";
  41. export const DEFAULT_QUERY_MODEL = "Qwen/Qwen3-1.7B";
  42. export const DEFAULT_GLOB = "**/*.md";
  43. export const DEFAULT_MULTI_GET_MAX_BYTES = 10 * 1024; // 10KB
  44. export const DEFAULT_EMBED_MAX_DOCS_PER_BATCH = 64;
  45. export const DEFAULT_EMBED_MAX_BATCH_BYTES = 64 * 1024 * 1024; // 64MB
  46. // Chunking: 900 tokens per chunk with 15% overlap
  47. // Increased from 800 to accommodate smart chunking finding natural break points
  48. export const CHUNK_SIZE_TOKENS = 900;
  49. export const CHUNK_OVERLAP_TOKENS = Math.floor(CHUNK_SIZE_TOKENS * 0.15); // 135 tokens (15% overlap)
  50. // Fallback char-based approximation for sync chunking (~4 chars per token)
  51. export const CHUNK_SIZE_CHARS = CHUNK_SIZE_TOKENS * 4; // 3600 chars
  52. export const CHUNK_OVERLAP_CHARS = CHUNK_OVERLAP_TOKENS * 4; // 540 chars
  53. // Search window for finding optimal break points (in tokens, ~200 tokens)
  54. export const CHUNK_WINDOW_TOKENS = 200;
  55. export const CHUNK_WINDOW_CHARS = CHUNK_WINDOW_TOKENS * 4; // 800 chars
  56. /**
  57. * Get the LlamaCpp instance for a store — prefers the store's own instance,
  58. * falls back to the global singleton.
  59. */
  60. function getLlm(store: Store): LlamaCpp {
  61. return store.llm ?? getDefaultLlamaCpp();
  62. }
  63. // =============================================================================
  64. // Smart Chunking - Break Point Detection
  65. // =============================================================================
  66. /**
  67. * A potential break point in the document with a base score indicating quality.
  68. */
  69. export interface BreakPoint {
  70. pos: number; // character position
  71. score: number; // base score (higher = better break point)
  72. type: string; // for debugging: 'h1', 'h2', 'blank', etc.
  73. }
  74. /**
  75. * A region where a code fence exists (between ``` markers).
  76. * We should never split inside a code fence.
  77. */
  78. export interface CodeFenceRegion {
  79. start: number; // position of opening ```
  80. end: number; // position of closing ``` (or document end if unclosed)
  81. }
  82. /**
  83. * Patterns for detecting break points in markdown documents.
  84. * Higher scores indicate better places to split.
  85. * Scores are spread wide so headings decisively beat lower-quality breaks.
  86. * Order matters for scoring - more specific patterns first.
  87. */
  88. export const BREAK_PATTERNS: [RegExp, number, string][] = [
  89. [/\n#{1}(?!#)/g, 100, 'h1'], // # but not ##
  90. [/\n#{2}(?!#)/g, 90, 'h2'], // ## but not ###
  91. [/\n#{3}(?!#)/g, 80, 'h3'], // ### but not ####
  92. [/\n#{4}(?!#)/g, 70, 'h4'], // #### but not #####
  93. [/\n#{5}(?!#)/g, 60, 'h5'], // ##### but not ######
  94. [/\n#{6}(?!#)/g, 50, 'h6'], // ######
  95. [/\n```/g, 80, 'codeblock'], // code block boundary (same as h3)
  96. [/\n(?:---|\*\*\*|___)\s*\n/g, 60, 'hr'], // horizontal rule
  97. [/\n\n+/g, 20, 'blank'], // paragraph boundary
  98. [/\n[-*]\s/g, 5, 'list'], // unordered list item
  99. [/\n\d+\.\s/g, 5, 'numlist'], // ordered list item
  100. [/\n/g, 1, 'newline'], // minimal break
  101. ];
  102. /**
  103. * Scan text for all potential break points.
  104. * Returns sorted array of break points with higher-scoring patterns taking precedence
  105. * when multiple patterns match the same position.
  106. */
  107. export function scanBreakPoints(text: string): BreakPoint[] {
  108. const points: BreakPoint[] = [];
  109. const seen = new Map<number, BreakPoint>(); // pos -> best break point at that pos
  110. for (const [pattern, score, type] of BREAK_PATTERNS) {
  111. for (const match of text.matchAll(pattern)) {
  112. const pos = match.index!;
  113. const existing = seen.get(pos);
  114. // Keep higher score if position already seen
  115. if (!existing || score > existing.score) {
  116. const bp = { pos, score, type };
  117. seen.set(pos, bp);
  118. }
  119. }
  120. }
  121. // Convert to array and sort by position
  122. for (const bp of seen.values()) {
  123. points.push(bp);
  124. }
  125. return points.sort((a, b) => a.pos - b.pos);
  126. }
  127. /**
  128. * Find all code fence regions in the text.
  129. * Code fences are delimited by ``` and we should never split inside them.
  130. */
  131. export function findCodeFences(text: string): CodeFenceRegion[] {
  132. const regions: CodeFenceRegion[] = [];
  133. const fencePattern = /\n```/g;
  134. let inFence = false;
  135. let fenceStart = 0;
  136. for (const match of text.matchAll(fencePattern)) {
  137. if (!inFence) {
  138. fenceStart = match.index!;
  139. inFence = true;
  140. } else {
  141. regions.push({ start: fenceStart, end: match.index! + match[0].length });
  142. inFence = false;
  143. }
  144. }
  145. // Handle unclosed fence - extends to end of document
  146. if (inFence) {
  147. regions.push({ start: fenceStart, end: text.length });
  148. }
  149. return regions;
  150. }
  151. /**
  152. * Check if a position is inside a code fence region.
  153. */
  154. export function isInsideCodeFence(pos: number, fences: CodeFenceRegion[]): boolean {
  155. return fences.some(f => pos > f.start && pos < f.end);
  156. }
  157. /**
  158. * Find the best cut position using scored break points with distance decay.
  159. *
  160. * Uses squared distance for gentler early decay - headings far back still win
  161. * over low-quality breaks near the target.
  162. *
  163. * @param breakPoints - Pre-scanned break points from scanBreakPoints()
  164. * @param targetCharPos - The ideal cut position (e.g., maxChars boundary)
  165. * @param windowChars - How far back to search for break points (default ~200 tokens)
  166. * @param decayFactor - How much to penalize distance (0.7 = 30% score at window edge)
  167. * @param codeFences - Code fence regions to avoid splitting inside
  168. * @returns The best position to cut at
  169. */
  170. export function findBestCutoff(
  171. breakPoints: BreakPoint[],
  172. targetCharPos: number,
  173. windowChars: number = CHUNK_WINDOW_CHARS,
  174. decayFactor: number = 0.7,
  175. codeFences: CodeFenceRegion[] = []
  176. ): number {
  177. const windowStart = targetCharPos - windowChars;
  178. let bestScore = -1;
  179. let bestPos = targetCharPos;
  180. for (const bp of breakPoints) {
  181. if (bp.pos < windowStart) continue;
  182. if (bp.pos > targetCharPos) break; // sorted, so we can stop
  183. // Skip break points inside code fences
  184. if (isInsideCodeFence(bp.pos, codeFences)) continue;
  185. const distance = targetCharPos - bp.pos;
  186. // Squared distance decay: gentle early, steep late
  187. // At target: multiplier = 1.0
  188. // At 25% back: multiplier = 0.956
  189. // At 50% back: multiplier = 0.825
  190. // At 75% back: multiplier = 0.606
  191. // At window edge: multiplier = 0.3
  192. const normalizedDist = distance / windowChars;
  193. const multiplier = 1.0 - (normalizedDist * normalizedDist) * decayFactor;
  194. const finalScore = bp.score * multiplier;
  195. if (finalScore > bestScore) {
  196. bestScore = finalScore;
  197. bestPos = bp.pos;
  198. }
  199. }
  200. return bestPos;
  201. }
  202. // Hybrid query: strong BM25 signal detection thresholds
  203. // Skip expensive LLM expansion when top result is strong AND clearly separated from runner-up
  204. export const STRONG_SIGNAL_MIN_SCORE = 0.85;
  205. export const STRONG_SIGNAL_MIN_GAP = 0.15;
  206. // Max candidates to pass to reranker — balances quality vs latency.
  207. // 40 keeps rank 31-40 visible to the reranker (matters for recall on broad queries).
  208. export const RERANK_CANDIDATE_LIMIT = 40;
  209. /**
  210. * A typed query expansion result. Decoupled from llm.ts internal Queryable —
  211. * same shape, but store.ts owns its own public API type.
  212. *
  213. * - lex: keyword variant → routes to FTS only
  214. * - vec: semantic variant → routes to vector only
  215. * - hyde: hypothetical document → routes to vector only
  216. */
  217. export type ExpandedQuery = {
  218. type: 'lex' | 'vec' | 'hyde';
  219. query: string;
  220. /** Optional line number for error reporting (CLI parser) */
  221. line?: number;
  222. };
  223. // =============================================================================
  224. // Path utilities
  225. // =============================================================================
  226. export function homedir(): string {
  227. return HOME;
  228. }
  229. /**
  230. * Check if a path is absolute.
  231. * Supports:
  232. * - Unix paths: /path/to/file
  233. * - Windows native: C:\path or C:/path
  234. * - Git Bash: /c/path or /C/path (C-Z drives, excluding A/B floppy drives)
  235. *
  236. * Note: /c without trailing slash is treated as Unix path (directory named "c"),
  237. * while /c/ or /c/path are treated as Git Bash paths (C: drive).
  238. */
  239. export function isAbsolutePath(path: string): boolean {
  240. if (!path) return false;
  241. // Unix absolute path
  242. if (path.startsWith('/')) {
  243. // Check if it's a Git Bash style path like /c/ or /c/Users (C-Z only, not A or B)
  244. // Requires path[2] === '/' to distinguish from Unix paths like /c or /cache
  245. // Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
  246. if (!isWSL() && path.length >= 3 && path[2] === '/') {
  247. const driveLetter = path[1];
  248. if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
  249. return true;
  250. }
  251. }
  252. // Any other path starting with / is Unix absolute
  253. return true;
  254. }
  255. // Windows native path: C:\ or C:/ (any letter A-Z)
  256. if (path.length >= 2 && /[a-zA-Z]/.test(path[0]!) && path[1] === ':') {
  257. return true;
  258. }
  259. return false;
  260. }
  261. /**
  262. * Normalize path separators to forward slashes.
  263. * Converts Windows backslashes to forward slashes.
  264. */
  265. export function normalizePathSeparators(path: string): string {
  266. return path.replace(/\\/g, '/');
  267. }
  268. /**
  269. * Detect if running inside WSL (Windows Subsystem for Linux).
  270. * On WSL, paths like /c/work/... are valid drvfs mount points, not Git Bash paths.
  271. */
  272. function isWSL(): boolean {
  273. return !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);
  274. }
  275. /**
  276. * Get the relative path from a prefix.
  277. * Returns null if path is not under prefix.
  278. * Returns empty string if path equals prefix.
  279. */
  280. export function getRelativePathFromPrefix(path: string, prefix: string): string | null {
  281. // Empty prefix is invalid
  282. if (!prefix) {
  283. return null;
  284. }
  285. const normalizedPath = normalizePathSeparators(path);
  286. const normalizedPrefix = normalizePathSeparators(prefix);
  287. // Ensure prefix ends with / for proper matching
  288. const prefixWithSlash = !normalizedPrefix.endsWith('/')
  289. ? normalizedPrefix + '/'
  290. : normalizedPrefix;
  291. // Exact match
  292. if (normalizedPath === normalizedPrefix) {
  293. return '';
  294. }
  295. // Check if path starts with prefix
  296. if (normalizedPath.startsWith(prefixWithSlash)) {
  297. return normalizedPath.slice(prefixWithSlash.length);
  298. }
  299. return null;
  300. }
  301. export function resolve(...paths: string[]): string {
  302. if (paths.length === 0) {
  303. throw new Error("resolve: at least one path segment is required");
  304. }
  305. // Normalize all paths to use forward slashes
  306. const normalizedPaths = paths.map(normalizePathSeparators);
  307. let result = '';
  308. let windowsDrive = '';
  309. // Check if first path is absolute
  310. const firstPath = normalizedPaths[0]!;
  311. if (isAbsolutePath(firstPath)) {
  312. result = firstPath;
  313. // Extract Windows drive letter if present
  314. if (firstPath.length >= 2 && /[a-zA-Z]/.test(firstPath[0]!) && firstPath[1] === ':') {
  315. windowsDrive = firstPath.slice(0, 2);
  316. result = firstPath.slice(2);
  317. } else if (!isWSL() && firstPath.startsWith('/') && firstPath.length >= 3 && firstPath[2] === '/') {
  318. // Git Bash style: /c/ -> C: (C-Z drives only, not A or B)
  319. // Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
  320. const driveLetter = firstPath[1];
  321. if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
  322. windowsDrive = driveLetter.toUpperCase() + ':';
  323. result = firstPath.slice(2);
  324. }
  325. }
  326. } else {
  327. // Start with PWD or cwd, then append the first relative path
  328. const pwd = normalizePathSeparators(process.env.PWD || process.cwd());
  329. // Extract Windows drive from PWD if present
  330. if (pwd.length >= 2 && /[a-zA-Z]/.test(pwd[0]!) && pwd[1] === ':') {
  331. windowsDrive = pwd.slice(0, 2);
  332. result = pwd.slice(2) + '/' + firstPath;
  333. } else {
  334. result = pwd + '/' + firstPath;
  335. }
  336. }
  337. // Process remaining paths
  338. for (let i = 1; i < normalizedPaths.length; i++) {
  339. const p = normalizedPaths[i]!;
  340. if (isAbsolutePath(p)) {
  341. // Absolute path replaces everything
  342. result = p;
  343. // Update Windows drive if present
  344. if (p.length >= 2 && /[a-zA-Z]/.test(p[0]!) && p[1] === ':') {
  345. windowsDrive = p.slice(0, 2);
  346. result = p.slice(2);
  347. } else if (!isWSL() && p.startsWith('/') && p.length >= 3 && p[2] === '/') {
  348. // Git Bash style (C-Z drives only, not A or B)
  349. // Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
  350. const driveLetter = p[1];
  351. if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
  352. windowsDrive = driveLetter.toUpperCase() + ':';
  353. result = p.slice(2);
  354. } else {
  355. windowsDrive = '';
  356. }
  357. } else {
  358. windowsDrive = '';
  359. }
  360. } else {
  361. // Relative path - append
  362. result = result + '/' + p;
  363. }
  364. }
  365. // Normalize . and .. components
  366. const parts = result.split('/').filter(Boolean);
  367. const normalized: string[] = [];
  368. for (const part of parts) {
  369. if (part === '..') {
  370. normalized.pop();
  371. } else if (part !== '.') {
  372. normalized.push(part);
  373. }
  374. }
  375. // Build final path
  376. const finalPath = '/' + normalized.join('/');
  377. // Prepend Windows drive if present
  378. if (windowsDrive) {
  379. return windowsDrive + finalPath;
  380. }
  381. return finalPath;
  382. }
  383. // Flag to indicate production mode (set by qmd.ts at startup)
  384. let _productionMode = false;
  385. export function enableProductionMode(): void {
  386. _productionMode = true;
  387. }
  388. export function getDefaultDbPath(indexName: string = "index"): string {
  389. // Always allow override via INDEX_PATH (for testing)
  390. if (process.env.INDEX_PATH) {
  391. return process.env.INDEX_PATH;
  392. }
  393. // In non-production mode (tests), require explicit path
  394. if (!_productionMode) {
  395. throw new Error(
  396. "Database path not set. Tests must set INDEX_PATH env var or use createStore() with explicit path. " +
  397. "This prevents tests from accidentally writing to the global index."
  398. );
  399. }
  400. const cacheDir = process.env.XDG_CACHE_HOME || resolve(homedir(), ".cache");
  401. const qmdCacheDir = resolve(cacheDir, "qmd");
  402. try { mkdirSync(qmdCacheDir, { recursive: true }); } catch { }
  403. return resolve(qmdCacheDir, `${indexName}.sqlite`);
  404. }
  405. export function getPwd(): string {
  406. return process.env.PWD || process.cwd();
  407. }
  408. export function getRealPath(path: string): string {
  409. try {
  410. return realpathSync(path);
  411. } catch {
  412. return resolve(path);
  413. }
  414. }
  415. // =============================================================================
  416. // Virtual Path Utilities (qmd://)
  417. // =============================================================================
  418. export type VirtualPath = {
  419. collectionName: string;
  420. path: string; // relative path within collection
  421. };
  422. /**
  423. * Normalize explicit virtual path formats to standard qmd:// format.
  424. * Only handles paths that are already explicitly virtual:
  425. * - qmd://collection/path.md (already normalized)
  426. * - qmd:////collection/path.md (extra slashes - normalize)
  427. * - //collection/path.md (missing qmd: prefix - add it)
  428. *
  429. * Does NOT handle:
  430. * - collection/path.md (bare paths - could be filesystem relative)
  431. * - :linenum suffix (should be parsed separately before calling this)
  432. */
  433. export function normalizeVirtualPath(input: string): string {
  434. let path = input.trim();
  435. // Handle qmd:// with extra slashes: qmd:////collection/path -> qmd://collection/path
  436. if (path.startsWith('qmd:')) {
  437. // Remove qmd: prefix and normalize slashes
  438. path = path.slice(4);
  439. // Remove leading slashes and re-add exactly two
  440. path = path.replace(/^\/+/, '');
  441. return `qmd://${path}`;
  442. }
  443. // Handle //collection/path (missing qmd: prefix)
  444. if (path.startsWith('//')) {
  445. path = path.replace(/^\/+/, '');
  446. return `qmd://${path}`;
  447. }
  448. // Return as-is for other cases (filesystem paths, docids, bare collection/path, etc.)
  449. return path;
  450. }
  451. /**
  452. * Parse a virtual path like "qmd://collection-name/path/to/file.md"
  453. * into its components.
  454. * Also supports collection root: "qmd://collection-name/" or "qmd://collection-name"
  455. */
  456. export function parseVirtualPath(virtualPath: string): VirtualPath | null {
  457. // Normalize the path first
  458. const normalized = normalizeVirtualPath(virtualPath);
  459. // Match: qmd://collection-name[/optional-path]
  460. // Allows: qmd://name, qmd://name/, qmd://name/path
  461. const match = normalized.match(/^qmd:\/\/([^\/]+)\/?(.*)$/);
  462. if (!match?.[1]) return null;
  463. return {
  464. collectionName: match[1],
  465. path: match[2] ?? '', // Empty string for collection root
  466. };
  467. }
  468. /**
  469. * Build a virtual path from collection name and relative path.
  470. */
  471. export function buildVirtualPath(collectionName: string, path: string): string {
  472. return `qmd://${collectionName}/${path}`;
  473. }
  474. /**
  475. * Check if a path is explicitly a virtual path.
  476. * Only recognizes explicit virtual path formats:
  477. * - qmd://collection/path.md
  478. * - //collection/path.md
  479. *
  480. * Does NOT consider bare collection/path.md as virtual - that should be
  481. * handled separately by checking if the first component is a collection name.
  482. */
  483. export function isVirtualPath(path: string): boolean {
  484. const trimmed = path.trim();
  485. // Explicit qmd:// prefix (with any number of slashes)
  486. if (trimmed.startsWith('qmd:')) return true;
  487. // //collection/path format (missing qmd: prefix)
  488. if (trimmed.startsWith('//')) return true;
  489. return false;
  490. }
  491. /**
  492. * Resolve a virtual path to absolute filesystem path.
  493. */
  494. export function resolveVirtualPath(db: Database, virtualPath: string): string | null {
  495. const parsed = parseVirtualPath(virtualPath);
  496. if (!parsed) return null;
  497. const coll = getCollectionByName(db, parsed.collectionName);
  498. if (!coll) return null;
  499. return resolve(coll.pwd, parsed.path);
  500. }
  501. /**
  502. * Convert an absolute filesystem path to a virtual path.
  503. * Returns null if the file is not in any indexed collection.
  504. */
  505. export function toVirtualPath(db: Database, absolutePath: string): string | null {
  506. // Get all collections from DB
  507. const collections = getStoreCollections(db);
  508. // Find which collection this absolute path belongs to
  509. for (const coll of collections) {
  510. if (absolutePath.startsWith(coll.path + '/') || absolutePath === coll.path) {
  511. // Extract relative path
  512. const relativePath = absolutePath.startsWith(coll.path + '/')
  513. ? absolutePath.slice(coll.path.length + 1)
  514. : '';
  515. // Verify this document exists in the database
  516. const doc = db.prepare(`
  517. SELECT d.path
  518. FROM documents d
  519. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  520. LIMIT 1
  521. `).get(coll.name, relativePath) as { path: string } | null;
  522. if (doc) {
  523. return buildVirtualPath(coll.name, relativePath);
  524. }
  525. }
  526. }
  527. return null;
  528. }
  529. // =============================================================================
  530. // Database initialization
  531. // =============================================================================
  532. function createSqliteVecUnavailableError(reason: string): Error {
  533. return new Error(
  534. "sqlite-vec extension is unavailable. " +
  535. `${reason}. ` +
  536. "Install Homebrew SQLite so the sqlite-vec extension can be loaded, " +
  537. "and set BREW_PREFIX if Homebrew is installed in a non-standard location."
  538. );
  539. }
  540. function getErrorMessage(err: unknown): string {
  541. return err instanceof Error ? err.message : String(err);
  542. }
  543. export function verifySqliteVecLoaded(db: Database): void {
  544. try {
  545. const row = db.prepare(`SELECT vec_version() AS version`).get() as { version?: string } | null;
  546. if (!row?.version || typeof row.version !== "string") {
  547. throw new Error("vec_version() returned no version");
  548. }
  549. } catch (err) {
  550. const message = getErrorMessage(err);
  551. throw createSqliteVecUnavailableError(`sqlite-vec probe failed (${message})`);
  552. }
  553. }
  554. let _sqliteVecAvailable: boolean | null = null;
  555. function initializeDatabase(db: Database): void {
  556. try {
  557. loadSqliteVec(db);
  558. verifySqliteVecLoaded(db);
  559. _sqliteVecAvailable = true;
  560. } catch (err) {
  561. // sqlite-vec is optional — vector search won't work but FTS is fine
  562. _sqliteVecAvailable = false;
  563. console.warn(getErrorMessage(err));
  564. }
  565. db.exec("PRAGMA journal_mode = WAL");
  566. db.exec("PRAGMA foreign_keys = ON");
  567. // Drop legacy tables that are now managed in YAML
  568. db.exec(`DROP TABLE IF EXISTS path_contexts`);
  569. db.exec(`DROP TABLE IF EXISTS collections`);
  570. // Content-addressable storage - the source of truth for document content
  571. db.exec(`
  572. CREATE TABLE IF NOT EXISTS content (
  573. hash TEXT PRIMARY KEY,
  574. doc TEXT NOT NULL,
  575. created_at TEXT NOT NULL
  576. )
  577. `);
  578. // Documents table - file system layer mapping virtual paths to content hashes
  579. // Collections are now managed in ~/.config/qmd/index.yml
  580. db.exec(`
  581. CREATE TABLE IF NOT EXISTS documents (
  582. id INTEGER PRIMARY KEY AUTOINCREMENT,
  583. collection TEXT NOT NULL,
  584. path TEXT NOT NULL,
  585. title TEXT NOT NULL,
  586. hash TEXT NOT NULL,
  587. created_at TEXT NOT NULL,
  588. modified_at TEXT NOT NULL,
  589. active INTEGER NOT NULL DEFAULT 1,
  590. FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
  591. UNIQUE(collection, path)
  592. )
  593. `);
  594. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection, active)`);
  595. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)`);
  596. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path, active)`);
  597. // Cache table for LLM API calls
  598. db.exec(`
  599. CREATE TABLE IF NOT EXISTS llm_cache (
  600. hash TEXT PRIMARY KEY,
  601. result TEXT NOT NULL,
  602. created_at TEXT NOT NULL
  603. )
  604. `);
  605. // Content vectors
  606. const cvInfo = db.prepare(`PRAGMA table_info(content_vectors)`).all() as { name: string }[];
  607. const hasSeqColumn = cvInfo.some(col => col.name === 'seq');
  608. if (cvInfo.length > 0 && !hasSeqColumn) {
  609. db.exec(`DROP TABLE IF EXISTS content_vectors`);
  610. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  611. }
  612. db.exec(`
  613. CREATE TABLE IF NOT EXISTS content_vectors (
  614. hash TEXT NOT NULL,
  615. seq INTEGER NOT NULL DEFAULT 0,
  616. pos INTEGER NOT NULL DEFAULT 0,
  617. model TEXT NOT NULL,
  618. embedded_at TEXT NOT NULL,
  619. PRIMARY KEY (hash, seq)
  620. )
  621. `);
  622. // Store collections — makes the DB self-contained (no external config needed)
  623. db.exec(`
  624. CREATE TABLE IF NOT EXISTS store_collections (
  625. name TEXT PRIMARY KEY,
  626. path TEXT NOT NULL,
  627. pattern TEXT NOT NULL DEFAULT '**/*.md',
  628. ignore_patterns TEXT,
  629. include_by_default INTEGER DEFAULT 1,
  630. update_command TEXT,
  631. context TEXT
  632. )
  633. `);
  634. // Store config — key-value metadata (e.g. config_hash for sync optimization)
  635. db.exec(`
  636. CREATE TABLE IF NOT EXISTS store_config (
  637. key TEXT PRIMARY KEY,
  638. value TEXT
  639. )
  640. `);
  641. // FTS - index filepath (collection/path), title, and content
  642. db.exec(`
  643. CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
  644. filepath, title, body,
  645. tokenize='porter unicode61'
  646. )
  647. `);
  648. // Triggers to keep FTS in sync
  649. db.exec(`
  650. CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents
  651. WHEN new.active = 1
  652. BEGIN
  653. INSERT INTO documents_fts(rowid, filepath, title, body)
  654. SELECT
  655. new.id,
  656. new.collection || '/' || new.path,
  657. new.title,
  658. (SELECT doc FROM content WHERE hash = new.hash)
  659. WHERE new.active = 1;
  660. END
  661. `);
  662. db.exec(`
  663. CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents BEGIN
  664. DELETE FROM documents_fts WHERE rowid = old.id;
  665. END
  666. `);
  667. db.exec(`
  668. CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents
  669. BEGIN
  670. -- Delete from FTS if no longer active
  671. DELETE FROM documents_fts WHERE rowid = old.id AND new.active = 0;
  672. -- Update FTS if still/newly active
  673. INSERT OR REPLACE INTO documents_fts(rowid, filepath, title, body)
  674. SELECT
  675. new.id,
  676. new.collection || '/' || new.path,
  677. new.title,
  678. (SELECT doc FROM content WHERE hash = new.hash)
  679. WHERE new.active = 1;
  680. END
  681. `);
  682. }
  683. // =============================================================================
  684. // Store Collections — DB accessor functions
  685. // =============================================================================
  686. type StoreCollectionRow = {
  687. name: string;
  688. path: string;
  689. pattern: string;
  690. ignore_patterns: string | null;
  691. include_by_default: number;
  692. update_command: string | null;
  693. context: string | null;
  694. };
  695. function rowToNamedCollection(row: StoreCollectionRow): NamedCollection {
  696. return {
  697. name: row.name,
  698. path: row.path,
  699. pattern: row.pattern,
  700. ...(row.ignore_patterns ? { ignore: JSON.parse(row.ignore_patterns) as string[] } : {}),
  701. ...(row.include_by_default === 0 ? { includeByDefault: false } : {}),
  702. ...(row.update_command ? { update: row.update_command } : {}),
  703. ...(row.context ? { context: JSON.parse(row.context) as ContextMap } : {}),
  704. };
  705. }
  706. export function getStoreCollections(db: Database): NamedCollection[] {
  707. const rows = db.prepare(`SELECT * FROM store_collections`).all() as StoreCollectionRow[];
  708. return rows.map(rowToNamedCollection);
  709. }
  710. export function getStoreCollection(db: Database, name: string): NamedCollection | null {
  711. const row = db.prepare(`SELECT * FROM store_collections WHERE name = ?`).get(name) as StoreCollectionRow | null | undefined;
  712. if (row == null) return null;
  713. return rowToNamedCollection(row);
  714. }
  715. export function getStoreGlobalContext(db: Database): string | undefined {
  716. const row = db.prepare(`SELECT value FROM store_config WHERE key = 'global_context'`).get() as { value: string } | null | undefined;
  717. if (row == null) return undefined;
  718. return row.value || undefined;
  719. }
  720. export function getStoreContexts(db: Database): Array<{ collection: string; path: string; context: string }> {
  721. const results: Array<{ collection: string; path: string; context: string }> = [];
  722. // Global context
  723. const globalCtx = getStoreGlobalContext(db);
  724. if (globalCtx) {
  725. results.push({ collection: "*", path: "/", context: globalCtx });
  726. }
  727. // Collection contexts
  728. const rows = db.prepare(`SELECT name, context FROM store_collections WHERE context IS NOT NULL`).all() as { name: string; context: string }[];
  729. for (const row of rows) {
  730. const ctxMap = JSON.parse(row.context) as ContextMap;
  731. for (const [path, context] of Object.entries(ctxMap)) {
  732. results.push({ collection: row.name, path, context });
  733. }
  734. }
  735. return results;
  736. }
  737. export function upsertStoreCollection(db: Database, name: string, collection: Omit<Collection, 'pattern'> & { pattern?: string }): void {
  738. db.prepare(`
  739. INSERT INTO store_collections (name, path, pattern, ignore_patterns, include_by_default, update_command, context)
  740. VALUES (?, ?, ?, ?, ?, ?, ?)
  741. ON CONFLICT(name) DO UPDATE SET
  742. path = excluded.path,
  743. pattern = excluded.pattern,
  744. ignore_patterns = excluded.ignore_patterns,
  745. include_by_default = excluded.include_by_default,
  746. update_command = excluded.update_command,
  747. context = excluded.context
  748. `).run(
  749. name,
  750. collection.path,
  751. collection.pattern || '**/*.md',
  752. collection.ignore ? JSON.stringify(collection.ignore) : null,
  753. collection.includeByDefault === false ? 0 : 1,
  754. collection.update || null,
  755. collection.context ? JSON.stringify(collection.context) : null,
  756. );
  757. }
  758. export function deleteStoreCollection(db: Database, name: string): boolean {
  759. const result = db.prepare(`DELETE FROM store_collections WHERE name = ?`).run(name);
  760. return result.changes > 0;
  761. }
  762. export function renameStoreCollection(db: Database, oldName: string, newName: string): boolean {
  763. // Check target doesn't exist
  764. const existing = db.prepare(`SELECT name FROM store_collections WHERE name = ?`).get(newName) as { name: string } | null | undefined;
  765. if (existing != null) {
  766. throw new Error(`Collection '${newName}' already exists`);
  767. }
  768. const result = db.prepare(`UPDATE store_collections SET name = ? WHERE name = ?`).run(newName, oldName);
  769. return result.changes > 0;
  770. }
  771. export function updateStoreContext(db: Database, collectionName: string, path: string, text: string): boolean {
  772. const row = db.prepare(`SELECT context FROM store_collections WHERE name = ?`).get(collectionName) as { context: string | null } | null | undefined;
  773. if (row == null) return false;
  774. const ctxMap: ContextMap = row.context ? JSON.parse(row.context) : {};
  775. ctxMap[path] = text;
  776. db.prepare(`UPDATE store_collections SET context = ? WHERE name = ?`).run(JSON.stringify(ctxMap), collectionName);
  777. return true;
  778. }
  779. export function removeStoreContext(db: Database, collectionName: string, path: string): boolean {
  780. const row = db.prepare(`SELECT context FROM store_collections WHERE name = ?`).get(collectionName) as { context: string | null } | null | undefined;
  781. if (row == null) return false;
  782. if (!row.context) return false;
  783. const ctxMap: ContextMap = JSON.parse(row.context);
  784. if (!(path in ctxMap)) return false;
  785. delete ctxMap[path];
  786. const newCtx = Object.keys(ctxMap).length > 0 ? JSON.stringify(ctxMap) : null;
  787. db.prepare(`UPDATE store_collections SET context = ? WHERE name = ?`).run(newCtx, collectionName);
  788. return true;
  789. }
  790. export function setStoreGlobalContext(db: Database, value: string | undefined): void {
  791. if (value === undefined) {
  792. db.prepare(`DELETE FROM store_config WHERE key = 'global_context'`).run();
  793. } else {
  794. db.prepare(`INSERT INTO store_config (key, value) VALUES ('global_context', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(value);
  795. }
  796. }
  797. /**
  798. * Sync external config (YAML/inline) into SQLite store_collections.
  799. * External config always wins. Skips sync if config hash hasn't changed.
  800. */
  801. export function syncConfigToDb(db: Database, config: CollectionConfig): void {
  802. // Check config hash — skip sync if unchanged
  803. const configJson = JSON.stringify(config);
  804. const hash = createHash('sha256').update(configJson).digest('hex');
  805. const existingHash = db.prepare(`SELECT value FROM store_config WHERE key = 'config_hash'`).get() as { value: string } | null | undefined;
  806. if (existingHash != null && existingHash.value === hash) {
  807. return; // Config unchanged, skip sync
  808. }
  809. // Sync collections
  810. const configNames = new Set(Object.keys(config.collections));
  811. for (const [name, coll] of Object.entries(config.collections)) {
  812. upsertStoreCollection(db, name, coll);
  813. }
  814. // Delete collections not in config
  815. const dbCollections = db.prepare(`SELECT name FROM store_collections`).all() as { name: string }[];
  816. for (const row of dbCollections) {
  817. if (!configNames.has(row.name)) {
  818. db.prepare(`DELETE FROM store_collections WHERE name = ?`).run(row.name);
  819. }
  820. }
  821. // Sync global context
  822. if (config.global_context !== undefined) {
  823. setStoreGlobalContext(db, config.global_context);
  824. } else {
  825. setStoreGlobalContext(db, undefined);
  826. }
  827. // Save config hash
  828. db.prepare(`INSERT INTO store_config (key, value) VALUES ('config_hash', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(hash);
  829. }
  830. export function isSqliteVecAvailable(): boolean {
  831. return _sqliteVecAvailable === true;
  832. }
  833. function ensureVecTableInternal(db: Database, dimensions: number): void {
  834. if (!_sqliteVecAvailable) {
  835. throw new Error("sqlite-vec is not available. Vector operations require a SQLite build with extension loading support.");
  836. }
  837. const tableInfo = db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get() as { sql: string } | null;
  838. if (tableInfo) {
  839. const match = tableInfo.sql.match(/float\[(\d+)\]/);
  840. const hasHashSeq = tableInfo.sql.includes('hash_seq');
  841. const hasCosine = tableInfo.sql.includes('distance_metric=cosine');
  842. const existingDims = match?.[1] ? parseInt(match[1], 10) : null;
  843. if (existingDims === dimensions && hasHashSeq && hasCosine) return;
  844. // Table exists but wrong schema - need to rebuild
  845. db.exec("DROP TABLE IF EXISTS vectors_vec");
  846. }
  847. db.exec(`CREATE VIRTUAL TABLE vectors_vec USING vec0(hash_seq TEXT PRIMARY KEY, embedding float[${dimensions}] distance_metric=cosine)`);
  848. }
  849. // =============================================================================
  850. // Store Factory
  851. // =============================================================================
  852. export type Store = {
  853. db: Database;
  854. dbPath: string;
  855. /** Optional LlamaCpp instance for this store (overrides the global singleton) */
  856. llm?: LlamaCpp;
  857. close: () => void;
  858. ensureVecTable: (dimensions: number) => void;
  859. // Index health
  860. getHashesNeedingEmbedding: () => number;
  861. getIndexHealth: () => IndexHealthInfo;
  862. getStatus: () => IndexStatus;
  863. // Caching
  864. getCacheKey: typeof getCacheKey;
  865. getCachedResult: (cacheKey: string) => string | null;
  866. setCachedResult: (cacheKey: string, result: string) => void;
  867. clearCache: () => void;
  868. // Cleanup and maintenance
  869. deleteLLMCache: () => number;
  870. deleteInactiveDocuments: () => number;
  871. cleanupOrphanedContent: () => number;
  872. cleanupOrphanedVectors: () => number;
  873. vacuumDatabase: () => void;
  874. // Context
  875. getContextForFile: (filepath: string) => string | null;
  876. getContextForPath: (collectionName: string, path: string) => string | null;
  877. getCollectionByName: (name: string) => { name: string; pwd: string; glob_pattern: string } | null;
  878. getCollectionsWithoutContext: () => { name: string; pwd: string; doc_count: number }[];
  879. getTopLevelPathsWithoutContext: (collectionName: string) => string[];
  880. // Virtual paths
  881. parseVirtualPath: typeof parseVirtualPath;
  882. buildVirtualPath: typeof buildVirtualPath;
  883. isVirtualPath: typeof isVirtualPath;
  884. resolveVirtualPath: (virtualPath: string) => string | null;
  885. toVirtualPath: (absolutePath: string) => string | null;
  886. // Search
  887. searchFTS: (query: string, limit?: number, collectionName?: string) => SearchResult[];
  888. searchVec: (query: string, model: string, limit?: number, collectionName?: string, session?: ILLMSession, precomputedEmbedding?: number[]) => Promise<SearchResult[]>;
  889. // Query expansion & reranking
  890. expandQuery: (query: string, model?: string, intent?: string) => Promise<ExpandedQuery[]>;
  891. rerank: (query: string, documents: { file: string; text: string }[], model?: string, intent?: string) => Promise<{ file: string; score: number }[]>;
  892. // Document retrieval
  893. findDocument: (filename: string, options?: { includeBody?: boolean }) => DocumentResult | DocumentNotFound;
  894. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => string | null;
  895. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => { docs: MultiGetResult[]; errors: string[] };
  896. // Fuzzy matching and docid lookup
  897. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => string[];
  898. matchFilesByGlob: (pattern: string) => { filepath: string; displayPath: string; bodyLength: number }[];
  899. findDocumentByDocid: (docid: string) => { filepath: string; hash: string } | null;
  900. // Document indexing operations
  901. insertContent: (hash: string, content: string, createdAt: string) => void;
  902. insertDocument: (collectionName: string, path: string, title: string, hash: string, createdAt: string, modifiedAt: string) => void;
  903. findActiveDocument: (collectionName: string, path: string) => { id: number; hash: string; title: string } | null;
  904. updateDocumentTitle: (documentId: number, title: string, modifiedAt: string) => void;
  905. updateDocument: (documentId: number, title: string, hash: string, modifiedAt: string) => void;
  906. deactivateDocument: (collectionName: string, path: string) => void;
  907. getActiveDocumentPaths: (collectionName: string) => string[];
  908. // Vector/embedding operations
  909. getHashesForEmbedding: () => { hash: string; body: string; path: string }[];
  910. clearAllEmbeddings: () => void;
  911. insertEmbedding: (hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string) => void;
  912. };
  913. // =============================================================================
  914. // Reindex & Embed — pure-logic functions for SDK and CLI
  915. // =============================================================================
  916. export type ReindexProgress = {
  917. file: string;
  918. current: number;
  919. total: number;
  920. };
  921. export type ReindexResult = {
  922. indexed: number;
  923. updated: number;
  924. unchanged: number;
  925. removed: number;
  926. orphanedCleaned: number;
  927. };
  928. /**
  929. * Re-index a single collection by scanning the filesystem and updating the database.
  930. * Pure function — no console output, no db lifecycle management.
  931. */
  932. export async function reindexCollection(
  933. store: Store,
  934. collectionPath: string,
  935. globPattern: string,
  936. collectionName: string,
  937. options?: {
  938. ignorePatterns?: string[];
  939. onProgress?: (info: ReindexProgress) => void;
  940. }
  941. ): Promise<ReindexResult> {
  942. const db = store.db;
  943. const now = new Date().toISOString();
  944. const excludeDirs = ["node_modules", ".git", ".cache", "vendor", "dist", "build"];
  945. const allIgnore = [
  946. ...excludeDirs.map(d => `**/${d}/**`),
  947. ...(options?.ignorePatterns || []),
  948. ];
  949. const allFiles: string[] = await fastGlob(globPattern, {
  950. cwd: collectionPath,
  951. onlyFiles: true,
  952. followSymbolicLinks: false,
  953. dot: false,
  954. ignore: allIgnore,
  955. });
  956. // Filter hidden files/folders
  957. const files = allFiles.filter(file => {
  958. const parts = file.split("/");
  959. return !parts.some(part => part.startsWith("."));
  960. });
  961. const total = files.length;
  962. let indexed = 0, updated = 0, unchanged = 0, processed = 0;
  963. const seenPaths = new Set<string>();
  964. for (const relativeFile of files) {
  965. const filepath = getRealPath(resolve(collectionPath, relativeFile));
  966. const path = handelize(relativeFile);
  967. seenPaths.add(path);
  968. let content: string;
  969. try {
  970. content = readFileSync(filepath, "utf-8");
  971. } catch {
  972. processed++;
  973. options?.onProgress?.({ file: relativeFile, current: processed, total });
  974. continue;
  975. }
  976. if (!content.trim()) {
  977. processed++;
  978. continue;
  979. }
  980. const hash = await hashContent(content);
  981. const title = extractTitle(content, relativeFile);
  982. const existing = findActiveDocument(db, collectionName, path);
  983. if (existing) {
  984. if (existing.hash === hash) {
  985. if (existing.title !== title) {
  986. updateDocumentTitle(db, existing.id, title, now);
  987. updated++;
  988. } else {
  989. unchanged++;
  990. }
  991. } else {
  992. insertContent(db, hash, content, now);
  993. const stat = statSync(filepath);
  994. updateDocument(db, existing.id, title, hash,
  995. stat ? new Date(stat.mtime).toISOString() : now);
  996. updated++;
  997. }
  998. } else {
  999. indexed++;
  1000. insertContent(db, hash, content, now);
  1001. const stat = statSync(filepath);
  1002. insertDocument(db, collectionName, path, title, hash,
  1003. stat ? new Date(stat.birthtime).toISOString() : now,
  1004. stat ? new Date(stat.mtime).toISOString() : now);
  1005. }
  1006. processed++;
  1007. options?.onProgress?.({ file: relativeFile, current: processed, total });
  1008. }
  1009. // Deactivate documents that no longer exist
  1010. const allActive = getActiveDocumentPaths(db, collectionName);
  1011. let removed = 0;
  1012. for (const path of allActive) {
  1013. if (!seenPaths.has(path)) {
  1014. deactivateDocument(db, collectionName, path);
  1015. removed++;
  1016. }
  1017. }
  1018. const orphanedCleaned = cleanupOrphanedContent(db);
  1019. return { indexed, updated, unchanged, removed, orphanedCleaned };
  1020. }
  1021. export type EmbedProgress = {
  1022. chunksEmbedded: number;
  1023. totalChunks: number;
  1024. bytesProcessed: number;
  1025. totalBytes: number;
  1026. errors: number;
  1027. };
  1028. export type EmbedResult = {
  1029. docsProcessed: number;
  1030. chunksEmbedded: number;
  1031. errors: number;
  1032. durationMs: number;
  1033. };
  1034. export type EmbedOptions = {
  1035. force?: boolean;
  1036. model?: string;
  1037. maxDocsPerBatch?: number;
  1038. maxBatchBytes?: number;
  1039. onProgress?: (info: EmbedProgress) => void;
  1040. };
  1041. type PendingEmbeddingDoc = {
  1042. hash: string;
  1043. path: string;
  1044. bytes: number;
  1045. };
  1046. type EmbeddingDoc = PendingEmbeddingDoc & {
  1047. body: string;
  1048. };
  1049. type ChunkItem = {
  1050. hash: string;
  1051. title: string;
  1052. text: string;
  1053. seq: number;
  1054. pos: number;
  1055. tokens: number;
  1056. bytes: number;
  1057. };
  1058. function validatePositiveIntegerOption(name: string, value: number | undefined, fallback: number): number {
  1059. if (value === undefined) return fallback;
  1060. if (!Number.isInteger(value) || value < 1) {
  1061. throw new Error(`${name} must be a positive integer`);
  1062. }
  1063. return value;
  1064. }
  1065. function resolveEmbedOptions(options?: EmbedOptions): Required<Pick<EmbedOptions, "maxDocsPerBatch" | "maxBatchBytes">> {
  1066. return {
  1067. maxDocsPerBatch: validatePositiveIntegerOption("maxDocsPerBatch", options?.maxDocsPerBatch, DEFAULT_EMBED_MAX_DOCS_PER_BATCH),
  1068. maxBatchBytes: validatePositiveIntegerOption("maxBatchBytes", options?.maxBatchBytes, DEFAULT_EMBED_MAX_BATCH_BYTES),
  1069. };
  1070. }
  1071. function getPendingEmbeddingDocs(db: Database): PendingEmbeddingDoc[] {
  1072. return db.prepare(`
  1073. SELECT d.hash, MIN(d.path) as path, length(CAST(c.doc AS BLOB)) as bytes
  1074. FROM documents d
  1075. JOIN content c ON d.hash = c.hash
  1076. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  1077. WHERE d.active = 1 AND v.hash IS NULL
  1078. GROUP BY d.hash
  1079. ORDER BY MIN(d.path)
  1080. `).all() as PendingEmbeddingDoc[];
  1081. }
  1082. function buildEmbeddingBatches(
  1083. docs: PendingEmbeddingDoc[],
  1084. maxDocsPerBatch: number,
  1085. maxBatchBytes: number,
  1086. ): PendingEmbeddingDoc[][] {
  1087. const batches: PendingEmbeddingDoc[][] = [];
  1088. let currentBatch: PendingEmbeddingDoc[] = [];
  1089. let currentBytes = 0;
  1090. for (const doc of docs) {
  1091. const docBytes = Math.max(0, doc.bytes);
  1092. const wouldExceedDocs = currentBatch.length >= maxDocsPerBatch;
  1093. const wouldExceedBytes = currentBatch.length > 0 && (currentBytes + docBytes) > maxBatchBytes;
  1094. if (wouldExceedDocs || wouldExceedBytes) {
  1095. batches.push(currentBatch);
  1096. currentBatch = [];
  1097. currentBytes = 0;
  1098. }
  1099. currentBatch.push(doc);
  1100. currentBytes += docBytes;
  1101. }
  1102. if (currentBatch.length > 0) {
  1103. batches.push(currentBatch);
  1104. }
  1105. return batches;
  1106. }
  1107. function getEmbeddingDocsForBatch(db: Database, batch: PendingEmbeddingDoc[]): EmbeddingDoc[] {
  1108. if (batch.length === 0) return [];
  1109. const placeholders = batch.map(() => "?").join(",");
  1110. const rows = db.prepare(`
  1111. SELECT hash, doc as body
  1112. FROM content
  1113. WHERE hash IN (${placeholders})
  1114. `).all(...batch.map(doc => doc.hash)) as { hash: string; body: string }[];
  1115. const bodyByHash = new Map(rows.map(row => [row.hash, row.body]));
  1116. return batch.map((doc) => ({
  1117. ...doc,
  1118. body: bodyByHash.get(doc.hash) ?? "",
  1119. }));
  1120. }
  1121. /**
  1122. * Generate vector embeddings for documents that need them.
  1123. * Pure function — no console output, no db lifecycle management.
  1124. * Uses the store's LlamaCpp instance if set, otherwise the global singleton.
  1125. */
  1126. export async function generateEmbeddings(
  1127. store: Store,
  1128. options?: EmbedOptions
  1129. ): Promise<EmbedResult> {
  1130. const db = store.db;
  1131. const model = options?.model ?? DEFAULT_EMBED_MODEL;
  1132. const now = new Date().toISOString();
  1133. const { maxDocsPerBatch, maxBatchBytes } = resolveEmbedOptions(options);
  1134. const encoder = new TextEncoder();
  1135. if (options?.force) {
  1136. clearAllEmbeddings(db);
  1137. }
  1138. const docsToEmbed = getPendingEmbeddingDocs(db);
  1139. if (docsToEmbed.length === 0) {
  1140. return { docsProcessed: 0, chunksEmbedded: 0, errors: 0, durationMs: 0 };
  1141. }
  1142. const totalBytes = docsToEmbed.reduce((sum, doc) => sum + Math.max(0, doc.bytes), 0);
  1143. const totalDocs = docsToEmbed.length;
  1144. const startTime = Date.now();
  1145. // Use store's LlamaCpp or global singleton, wrapped in a session
  1146. const llm = getLlm(store);
  1147. // Create a session manager for this llm instance
  1148. const result = await withLLMSessionForLlm(llm, async (session) => {
  1149. let chunksEmbedded = 0;
  1150. let errors = 0;
  1151. let bytesProcessed = 0;
  1152. let totalChunks = 0;
  1153. let vectorTableInitialized = false;
  1154. const BATCH_SIZE = 32;
  1155. const batches = buildEmbeddingBatches(docsToEmbed, maxDocsPerBatch, maxBatchBytes);
  1156. for (const batchMeta of batches) {
  1157. // Abort early if session has been invalidated
  1158. if (!session.isValid) {
  1159. console.warn(`⚠ Session expired — skipping remaining document batches`);
  1160. break;
  1161. }
  1162. const batchDocs = getEmbeddingDocsForBatch(db, batchMeta);
  1163. const batchChunks: ChunkItem[] = [];
  1164. const batchBytes = batchMeta.reduce((sum, doc) => sum + Math.max(0, doc.bytes), 0);
  1165. for (const doc of batchDocs) {
  1166. if (!doc.body.trim()) continue;
  1167. const title = extractTitle(doc.body, doc.path);
  1168. const chunks = await chunkDocumentByTokens(doc.body, undefined, undefined, undefined, session.signal);
  1169. for (let seq = 0; seq < chunks.length; seq++) {
  1170. batchChunks.push({
  1171. hash: doc.hash,
  1172. title,
  1173. text: chunks[seq]!.text,
  1174. seq,
  1175. pos: chunks[seq]!.pos,
  1176. tokens: chunks[seq]!.tokens,
  1177. bytes: encoder.encode(chunks[seq]!.text).length,
  1178. });
  1179. }
  1180. }
  1181. totalChunks += batchChunks.length;
  1182. if (batchChunks.length === 0) {
  1183. bytesProcessed += batchBytes;
  1184. options?.onProgress?.({ chunksEmbedded, totalChunks, bytesProcessed, totalBytes, errors });
  1185. continue;
  1186. }
  1187. if (!vectorTableInitialized) {
  1188. const firstChunk = batchChunks[0]!;
  1189. const firstText = formatDocForEmbedding(firstChunk.text, firstChunk.title);
  1190. const firstResult = await session.embed(firstText);
  1191. if (!firstResult) {
  1192. throw new Error("Failed to get embedding dimensions from first chunk");
  1193. }
  1194. store.ensureVecTable(firstResult.embedding.length);
  1195. vectorTableInitialized = true;
  1196. }
  1197. const totalBatchChunkBytes = batchChunks.reduce((sum, chunk) => sum + chunk.bytes, 0);
  1198. let batchChunkBytesProcessed = 0;
  1199. for (let batchStart = 0; batchStart < batchChunks.length; batchStart += BATCH_SIZE) {
  1200. // Abort early if session has been invalidated (e.g. max duration exceeded)
  1201. if (!session.isValid) {
  1202. const remaining = batchChunks.length - batchStart;
  1203. errors += remaining;
  1204. console.warn(`⚠ Session expired — skipping ${remaining} remaining chunks`);
  1205. break;
  1206. }
  1207. // Abort early if error rate is too high (>80% of processed chunks failed)
  1208. const processed = chunksEmbedded + errors;
  1209. if (processed >= BATCH_SIZE && errors > processed * 0.8) {
  1210. const remaining = batchChunks.length - batchStart;
  1211. errors += remaining;
  1212. console.warn(`⚠ Error rate too high (${errors}/${processed}) — aborting embedding`);
  1213. break;
  1214. }
  1215. const batchEnd = Math.min(batchStart + BATCH_SIZE, batchChunks.length);
  1216. const chunkBatch = batchChunks.slice(batchStart, batchEnd);
  1217. const texts = chunkBatch.map(chunk => formatDocForEmbedding(chunk.text, chunk.title));
  1218. try {
  1219. const embeddings = await session.embedBatch(texts);
  1220. for (let i = 0; i < chunkBatch.length; i++) {
  1221. const chunk = chunkBatch[i]!;
  1222. const embedding = embeddings[i];
  1223. if (embedding) {
  1224. insertEmbedding(db, chunk.hash, chunk.seq, chunk.pos, new Float32Array(embedding.embedding), model, now);
  1225. chunksEmbedded++;
  1226. } else {
  1227. errors++;
  1228. }
  1229. batchChunkBytesProcessed += chunk.bytes;
  1230. }
  1231. } catch {
  1232. // Batch failed — try individual embeddings as fallback
  1233. // But skip if session is already invalid (avoids N doomed retries)
  1234. if (!session.isValid) {
  1235. errors += chunkBatch.length;
  1236. batchChunkBytesProcessed += chunkBatch.reduce((sum, c) => sum + c.bytes, 0);
  1237. } else {
  1238. for (const chunk of chunkBatch) {
  1239. try {
  1240. const text = formatDocForEmbedding(chunk.text, chunk.title);
  1241. const result = await session.embed(text);
  1242. if (result) {
  1243. insertEmbedding(db, chunk.hash, chunk.seq, chunk.pos, new Float32Array(result.embedding), model, now);
  1244. chunksEmbedded++;
  1245. } else {
  1246. errors++;
  1247. }
  1248. } catch {
  1249. errors++;
  1250. }
  1251. batchChunkBytesProcessed += chunk.bytes;
  1252. }
  1253. }
  1254. }
  1255. const proportionalBytes = totalBatchChunkBytes === 0
  1256. ? batchBytes
  1257. : Math.min(batchBytes, Math.round((batchChunkBytesProcessed / totalBatchChunkBytes) * batchBytes));
  1258. options?.onProgress?.({
  1259. chunksEmbedded,
  1260. totalChunks,
  1261. bytesProcessed: bytesProcessed + proportionalBytes,
  1262. totalBytes,
  1263. errors,
  1264. });
  1265. }
  1266. bytesProcessed += batchBytes;
  1267. options?.onProgress?.({ chunksEmbedded, totalChunks, bytesProcessed, totalBytes, errors });
  1268. }
  1269. return { chunksEmbedded, errors };
  1270. }, { maxDuration: 30 * 60 * 1000, name: 'generateEmbeddings' });
  1271. return {
  1272. docsProcessed: totalDocs,
  1273. chunksEmbedded: result.chunksEmbedded,
  1274. errors: result.errors,
  1275. durationMs: Date.now() - startTime,
  1276. };
  1277. }
  1278. /**
  1279. * Create a new store instance with the given database path.
  1280. * If no path is provided, uses the default path (~/.cache/qmd/index.sqlite).
  1281. *
  1282. * @param dbPath - Path to the SQLite database file
  1283. * @returns Store instance with all methods bound to the database
  1284. */
  1285. export function createStore(dbPath?: string): Store {
  1286. const resolvedPath = dbPath || getDefaultDbPath();
  1287. const db = openDatabase(resolvedPath);
  1288. initializeDatabase(db);
  1289. const store: Store = {
  1290. db,
  1291. dbPath: resolvedPath,
  1292. close: () => db.close(),
  1293. ensureVecTable: (dimensions: number) => ensureVecTableInternal(db, dimensions),
  1294. // Index health
  1295. getHashesNeedingEmbedding: () => getHashesNeedingEmbedding(db),
  1296. getIndexHealth: () => getIndexHealth(db),
  1297. getStatus: () => getStatus(db),
  1298. // Caching
  1299. getCacheKey,
  1300. getCachedResult: (cacheKey: string) => getCachedResult(db, cacheKey),
  1301. setCachedResult: (cacheKey: string, result: string) => setCachedResult(db, cacheKey, result),
  1302. clearCache: () => clearCache(db),
  1303. // Cleanup and maintenance
  1304. deleteLLMCache: () => deleteLLMCache(db),
  1305. deleteInactiveDocuments: () => deleteInactiveDocuments(db),
  1306. cleanupOrphanedContent: () => cleanupOrphanedContent(db),
  1307. cleanupOrphanedVectors: () => cleanupOrphanedVectors(db),
  1308. vacuumDatabase: () => vacuumDatabase(db),
  1309. // Context
  1310. getContextForFile: (filepath: string) => getContextForFile(db, filepath),
  1311. getContextForPath: (collectionName: string, path: string) => getContextForPath(db, collectionName, path),
  1312. getCollectionByName: (name: string) => getCollectionByName(db, name),
  1313. getCollectionsWithoutContext: () => getCollectionsWithoutContext(db),
  1314. getTopLevelPathsWithoutContext: (collectionName: string) => getTopLevelPathsWithoutContext(db, collectionName),
  1315. // Virtual paths
  1316. parseVirtualPath,
  1317. buildVirtualPath,
  1318. isVirtualPath,
  1319. resolveVirtualPath: (virtualPath: string) => resolveVirtualPath(db, virtualPath),
  1320. toVirtualPath: (absolutePath: string) => toVirtualPath(db, absolutePath),
  1321. // Search
  1322. searchFTS: (query: string, limit?: number, collectionName?: string) => searchFTS(db, query, limit, collectionName),
  1323. searchVec: (query: string, model: string, limit?: number, collectionName?: string, session?: ILLMSession, precomputedEmbedding?: number[]) => searchVec(db, query, model, limit, collectionName, session, precomputedEmbedding),
  1324. // Query expansion & reranking
  1325. expandQuery: (query: string, model?: string, intent?: string) => expandQuery(query, model, db, intent, store.llm),
  1326. rerank: (query: string, documents: { file: string; text: string }[], model?: string, intent?: string) => rerank(query, documents, model, db, intent, store.llm),
  1327. // Document retrieval
  1328. findDocument: (filename: string, options?: { includeBody?: boolean }) => findDocument(db, filename, options),
  1329. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => getDocumentBody(db, doc, fromLine, maxLines),
  1330. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => findDocuments(db, pattern, options),
  1331. // Fuzzy matching and docid lookup
  1332. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => findSimilarFiles(db, query, maxDistance, limit),
  1333. matchFilesByGlob: (pattern: string) => matchFilesByGlob(db, pattern),
  1334. findDocumentByDocid: (docid: string) => findDocumentByDocid(db, docid),
  1335. // Document indexing operations
  1336. insertContent: (hash: string, content: string, createdAt: string) => insertContent(db, hash, content, createdAt),
  1337. insertDocument: (collectionName: string, path: string, title: string, hash: string, createdAt: string, modifiedAt: string) => insertDocument(db, collectionName, path, title, hash, createdAt, modifiedAt),
  1338. findActiveDocument: (collectionName: string, path: string) => findActiveDocument(db, collectionName, path),
  1339. updateDocumentTitle: (documentId: number, title: string, modifiedAt: string) => updateDocumentTitle(db, documentId, title, modifiedAt),
  1340. updateDocument: (documentId: number, title: string, hash: string, modifiedAt: string) => updateDocument(db, documentId, title, hash, modifiedAt),
  1341. deactivateDocument: (collectionName: string, path: string) => deactivateDocument(db, collectionName, path),
  1342. getActiveDocumentPaths: (collectionName: string) => getActiveDocumentPaths(db, collectionName),
  1343. // Vector/embedding operations
  1344. getHashesForEmbedding: () => getHashesForEmbedding(db),
  1345. clearAllEmbeddings: () => clearAllEmbeddings(db),
  1346. insertEmbedding: (hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string) => insertEmbedding(db, hash, seq, pos, embedding, model, embeddedAt),
  1347. };
  1348. return store;
  1349. }
  1350. // =============================================================================
  1351. // Core Document Type
  1352. // =============================================================================
  1353. /**
  1354. * Unified document result type with all metadata.
  1355. * Body is optional - use getDocumentBody() to load it separately if needed.
  1356. */
  1357. export type DocumentResult = {
  1358. filepath: string; // Full filesystem path
  1359. displayPath: string; // Short display path (e.g., "docs/readme.md")
  1360. title: string; // Document title (from first heading or filename)
  1361. context: string | null; // Folder context description if configured
  1362. hash: string; // Content hash for caching/change detection
  1363. docid: string; // Short docid (first 6 chars of hash) for quick reference
  1364. collectionName: string; // Parent collection name
  1365. modifiedAt: string; // Last modification timestamp
  1366. bodyLength: number; // Body length in bytes (useful before loading)
  1367. body?: string; // Document body (optional, load with getDocumentBody)
  1368. };
  1369. /**
  1370. * Extract short docid from a full hash (first 6 characters).
  1371. */
  1372. export function getDocid(hash: string): string {
  1373. return hash.slice(0, 6);
  1374. }
  1375. /**
  1376. * Handelize a filename to be more token-friendly.
  1377. * - Convert triple underscore `___` to `/` (folder separator)
  1378. * - Convert to lowercase
  1379. * - Replace sequences of non-word chars (except /) with single dash
  1380. * - Remove leading/trailing dashes from path segments
  1381. * - Preserve folder structure (a/b/c/d.md stays structured)
  1382. * - Preserve file extension
  1383. */
  1384. /** Replace emoji/symbol codepoints with their hex representation (e.g. 🐘 → 1f418) */
  1385. function emojiToHex(str: string): string {
  1386. return str.replace(/(?:\p{So}\p{Mn}?|\p{Sk})+/gu, (run) => {
  1387. // Split the run into individual emoji and convert each to hex, dash-separated
  1388. return [...run].filter(c => /\p{So}|\p{Sk}/u.test(c))
  1389. .map(c => c.codePointAt(0)!.toString(16)).join('-');
  1390. });
  1391. }
  1392. export function handelize(path: string): string {
  1393. if (!path || path.trim() === '') {
  1394. throw new Error('handelize: path cannot be empty');
  1395. }
  1396. // Allow route-style "$" filenames while still rejecting paths with no usable content.
  1397. // Emoji (\p{So}) counts as valid content — they get converted to hex codepoints below.
  1398. const segments = path.split('/').filter(Boolean);
  1399. const lastSegment = segments[segments.length - 1] || '';
  1400. const filenameWithoutExt = lastSegment.replace(/\.[^.]+$/, '');
  1401. const hasValidContent = /[\p{L}\p{N}\p{So}\p{Sk}$]/u.test(filenameWithoutExt);
  1402. if (!hasValidContent) {
  1403. throw new Error(`handelize: path "${path}" has no valid filename content`);
  1404. }
  1405. const result = path
  1406. .replace(/___/g, '/') // Triple underscore becomes folder separator
  1407. .toLowerCase()
  1408. .split('/')
  1409. .map((segment, idx, arr) => {
  1410. const isLastSegment = idx === arr.length - 1;
  1411. // Convert emoji to hex codepoints before cleaning
  1412. segment = emojiToHex(segment);
  1413. if (isLastSegment) {
  1414. // For the filename (last segment), preserve the extension
  1415. const extMatch = segment.match(/(\.[a-z0-9]+)$/i);
  1416. const ext = extMatch ? extMatch[1] : '';
  1417. const nameWithoutExt = ext ? segment.slice(0, -ext.length) : segment;
  1418. const cleanedName = nameWithoutExt
  1419. .replace(/[^\p{L}\p{N}$]+/gu, '-') // Keep route marker "$", dash-separate other chars
  1420. .replace(/^-+|-+$/g, ''); // Remove leading/trailing dashes
  1421. return cleanedName + ext;
  1422. } else {
  1423. // For directories, just clean normally
  1424. return segment
  1425. .replace(/[^\p{L}\p{N}$]+/gu, '-')
  1426. .replace(/^-+|-+$/g, '');
  1427. }
  1428. })
  1429. .filter(Boolean)
  1430. .join('/');
  1431. if (!result) {
  1432. throw new Error(`handelize: path "${path}" resulted in empty string after processing`);
  1433. }
  1434. return result;
  1435. }
  1436. /**
  1437. * Search result extends DocumentResult with score and source info
  1438. */
  1439. export type SearchResult = DocumentResult & {
  1440. score: number; // Relevance score (0-1)
  1441. source: "fts" | "vec"; // Search source (full-text or vector)
  1442. chunkPos?: number; // Character position of matching chunk (for vector search)
  1443. };
  1444. /**
  1445. * Ranked result for RRF fusion (simplified, used internally)
  1446. */
  1447. export type RankedResult = {
  1448. file: string;
  1449. displayPath: string;
  1450. title: string;
  1451. body: string;
  1452. score: number;
  1453. };
  1454. export type RRFContributionTrace = {
  1455. listIndex: number;
  1456. source: "fts" | "vec";
  1457. queryType: "original" | "lex" | "vec" | "hyde";
  1458. query: string;
  1459. rank: number; // 1-indexed rank within list
  1460. weight: number;
  1461. backendScore: number; // Backend-normalized score before fusion
  1462. rrfContribution: number; // weight / (k + rank)
  1463. };
  1464. export type RRFScoreTrace = {
  1465. contributions: RRFContributionTrace[];
  1466. baseScore: number; // Sum of reciprocal-rank contributions
  1467. topRank: number; // Best (lowest) rank seen across lists
  1468. topRankBonus: number; // +0.05 for rank 1, +0.02 for rank 2-3
  1469. totalScore: number; // baseScore + topRankBonus
  1470. };
  1471. export type HybridQueryExplain = {
  1472. ftsScores: number[];
  1473. vectorScores: number[];
  1474. rrf: {
  1475. rank: number; // Rank after RRF fusion (1-indexed)
  1476. positionScore: number; // 1 / rank used in position-aware blending
  1477. weight: number; // Position-aware RRF weight (0.75 / 0.60 / 0.40)
  1478. baseScore: number;
  1479. topRankBonus: number;
  1480. totalScore: number;
  1481. contributions: RRFContributionTrace[];
  1482. };
  1483. rerankScore: number;
  1484. blendedScore: number;
  1485. };
  1486. /**
  1487. * Error result when document is not found
  1488. */
  1489. export type DocumentNotFound = {
  1490. error: "not_found";
  1491. query: string;
  1492. similarFiles: string[];
  1493. };
  1494. /**
  1495. * Result from multi-get operations
  1496. */
  1497. export type MultiGetResult = {
  1498. doc: DocumentResult;
  1499. skipped: false;
  1500. } | {
  1501. doc: Pick<DocumentResult, "filepath" | "displayPath">;
  1502. skipped: true;
  1503. skipReason: string;
  1504. };
  1505. export type CollectionInfo = {
  1506. name: string;
  1507. path: string | null;
  1508. pattern: string | null;
  1509. documents: number;
  1510. lastUpdated: string;
  1511. };
  1512. export type IndexStatus = {
  1513. totalDocuments: number;
  1514. needsEmbedding: number;
  1515. hasVectorIndex: boolean;
  1516. collections: CollectionInfo[];
  1517. };
  1518. // =============================================================================
  1519. // Index health
  1520. // =============================================================================
  1521. export function getHashesNeedingEmbedding(db: Database): number {
  1522. const result = db.prepare(`
  1523. SELECT COUNT(DISTINCT d.hash) as count
  1524. FROM documents d
  1525. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  1526. WHERE d.active = 1 AND v.hash IS NULL
  1527. `).get() as { count: number };
  1528. return result.count;
  1529. }
  1530. export type IndexHealthInfo = {
  1531. needsEmbedding: number;
  1532. totalDocs: number;
  1533. daysStale: number | null;
  1534. };
  1535. export function getIndexHealth(db: Database): IndexHealthInfo {
  1536. const needsEmbedding = getHashesNeedingEmbedding(db);
  1537. const totalDocs = (db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number }).count;
  1538. const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get() as { latest: string | null };
  1539. let daysStale: number | null = null;
  1540. if (mostRecent?.latest) {
  1541. const lastUpdate = new Date(mostRecent.latest);
  1542. daysStale = Math.floor((Date.now() - lastUpdate.getTime()) / (24 * 60 * 60 * 1000));
  1543. }
  1544. return { needsEmbedding, totalDocs, daysStale };
  1545. }
  1546. // =============================================================================
  1547. // Caching
  1548. // =============================================================================
  1549. export function getCacheKey(url: string, body: object): string {
  1550. const hash = createHash("sha256");
  1551. hash.update(url);
  1552. hash.update(JSON.stringify(body));
  1553. return hash.digest("hex");
  1554. }
  1555. export function getCachedResult(db: Database, cacheKey: string): string | null {
  1556. const row = db.prepare(`SELECT result FROM llm_cache WHERE hash = ?`).get(cacheKey) as { result: string } | null;
  1557. return row?.result || null;
  1558. }
  1559. export function setCachedResult(db: Database, cacheKey: string, result: string): void {
  1560. const now = new Date().toISOString();
  1561. db.prepare(`INSERT OR REPLACE INTO llm_cache (hash, result, created_at) VALUES (?, ?, ?)`).run(cacheKey, result, now);
  1562. if (Math.random() < 0.01) {
  1563. db.exec(`DELETE FROM llm_cache WHERE hash NOT IN (SELECT hash FROM llm_cache ORDER BY created_at DESC LIMIT 1000)`);
  1564. }
  1565. }
  1566. export function clearCache(db: Database): void {
  1567. db.exec(`DELETE FROM llm_cache`);
  1568. }
  1569. // =============================================================================
  1570. // Cleanup and maintenance operations
  1571. // =============================================================================
  1572. /**
  1573. * Delete cached LLM API responses.
  1574. * Returns the number of cached responses deleted.
  1575. */
  1576. export function deleteLLMCache(db: Database): number {
  1577. const result = db.prepare(`DELETE FROM llm_cache`).run();
  1578. return result.changes;
  1579. }
  1580. /**
  1581. * Remove inactive document records (active = 0).
  1582. * Returns the number of inactive documents deleted.
  1583. */
  1584. export function deleteInactiveDocuments(db: Database): number {
  1585. const result = db.prepare(`DELETE FROM documents WHERE active = 0`).run();
  1586. return result.changes;
  1587. }
  1588. /**
  1589. * Remove orphaned content hashes that are not referenced by any active document.
  1590. * Returns the number of orphaned content hashes deleted.
  1591. */
  1592. export function cleanupOrphanedContent(db: Database): number {
  1593. const result = db.prepare(`
  1594. DELETE FROM content
  1595. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  1596. `).run();
  1597. return result.changes;
  1598. }
  1599. /**
  1600. * Remove orphaned vector embeddings that are not referenced by any active document.
  1601. * Returns the number of orphaned embedding chunks deleted.
  1602. */
  1603. export function cleanupOrphanedVectors(db: Database): number {
  1604. // sqlite-vec may not be loaded (e.g. Bun's bun:sqlite lacks loadExtension).
  1605. // The vectors_vec virtual table can appear in sqlite_master from a prior
  1606. // session, but querying it without the vec0 module loaded will crash (#380).
  1607. if (!isSqliteVecAvailable()) {
  1608. return 0;
  1609. }
  1610. // The schema entry can exist even when sqlite-vec itself is unavailable
  1611. // (for example when reopening a DB without vec0 loaded). In that case,
  1612. // touching the virtual table throws "no such module: vec0" and cleanup
  1613. // should degrade gracefully like the rest of the vector features.
  1614. try {
  1615. db.prepare(`SELECT 1 FROM vectors_vec LIMIT 0`).get();
  1616. } catch {
  1617. return 0;
  1618. }
  1619. // Count orphaned vectors first
  1620. const countResult = db.prepare(`
  1621. SELECT COUNT(*) as c FROM content_vectors cv
  1622. WHERE NOT EXISTS (
  1623. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  1624. )
  1625. `).get() as { c: number };
  1626. if (countResult.c === 0) {
  1627. return 0;
  1628. }
  1629. // Delete from vectors_vec first
  1630. db.exec(`
  1631. DELETE FROM vectors_vec WHERE hash_seq IN (
  1632. SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
  1633. WHERE NOT EXISTS (
  1634. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  1635. )
  1636. )
  1637. `);
  1638. // Delete from content_vectors
  1639. db.exec(`
  1640. DELETE FROM content_vectors WHERE hash NOT IN (
  1641. SELECT hash FROM documents WHERE active = 1
  1642. )
  1643. `);
  1644. return countResult.c;
  1645. }
  1646. /**
  1647. * Run VACUUM to reclaim unused space in the database.
  1648. * This operation rebuilds the database file to eliminate fragmentation.
  1649. */
  1650. export function vacuumDatabase(db: Database): void {
  1651. db.exec(`VACUUM`);
  1652. }
  1653. // =============================================================================
  1654. // Document helpers
  1655. // =============================================================================
  1656. export async function hashContent(content: string): Promise<string> {
  1657. const hash = createHash("sha256");
  1658. hash.update(content);
  1659. return hash.digest("hex");
  1660. }
  1661. const titleExtractors: Record<string, (content: string) => string | null> = {
  1662. '.md': (content) => {
  1663. const match = content.match(/^##?\s+(.+)$/m);
  1664. if (match) {
  1665. const title = (match[1] ?? "").trim();
  1666. if (title === "📝 Notes" || title === "Notes") {
  1667. const nextMatch = content.match(/^##\s+(.+)$/m);
  1668. if (nextMatch?.[1]) return nextMatch[1].trim();
  1669. }
  1670. return title;
  1671. }
  1672. return null;
  1673. },
  1674. '.org': (content) => {
  1675. const titleProp = content.match(/^#\+TITLE:\s*(.+)$/im);
  1676. if (titleProp?.[1]) return titleProp[1].trim();
  1677. const heading = content.match(/^\*+\s+(.+)$/m);
  1678. if (heading?.[1]) return heading[1].trim();
  1679. return null;
  1680. },
  1681. };
  1682. export function extractTitle(content: string, filename: string): string {
  1683. const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();
  1684. const extractor = titleExtractors[ext];
  1685. if (extractor) {
  1686. const title = extractor(content);
  1687. if (title) return title;
  1688. }
  1689. return filename.replace(/\.[^.]+$/, "").split("/").pop() || filename;
  1690. }
  1691. // =============================================================================
  1692. // Document indexing operations
  1693. // =============================================================================
  1694. /**
  1695. * Insert content into the content table (content-addressable storage).
  1696. * Uses INSERT OR IGNORE so duplicate hashes are skipped.
  1697. */
  1698. export function insertContent(db: Database, hash: string, content: string, createdAt: string): void {
  1699. db.prepare(`INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)`)
  1700. .run(hash, content, createdAt);
  1701. }
  1702. /**
  1703. * Insert a new document into the documents table.
  1704. */
  1705. export function insertDocument(
  1706. db: Database,
  1707. collectionName: string,
  1708. path: string,
  1709. title: string,
  1710. hash: string,
  1711. createdAt: string,
  1712. modifiedAt: string
  1713. ): void {
  1714. db.prepare(`
  1715. INSERT INTO documents (collection, path, title, hash, created_at, modified_at, active)
  1716. VALUES (?, ?, ?, ?, ?, ?, 1)
  1717. ON CONFLICT(collection, path) DO UPDATE SET
  1718. title = excluded.title,
  1719. hash = excluded.hash,
  1720. modified_at = excluded.modified_at,
  1721. active = 1
  1722. `).run(collectionName, path, title, hash, createdAt, modifiedAt);
  1723. }
  1724. /**
  1725. * Find an active document by collection name and path.
  1726. */
  1727. export function findActiveDocument(
  1728. db: Database,
  1729. collectionName: string,
  1730. path: string
  1731. ): { id: number; hash: string; title: string } | null {
  1732. const row = db.prepare(`
  1733. SELECT id, hash, title FROM documents
  1734. WHERE collection = ? AND path = ? AND active = 1
  1735. `).get(collectionName, path) as { id: number; hash: string; title: string } | undefined;
  1736. return row ?? null;
  1737. }
  1738. /**
  1739. * Update the title and modified_at timestamp for a document.
  1740. */
  1741. export function updateDocumentTitle(
  1742. db: Database,
  1743. documentId: number,
  1744. title: string,
  1745. modifiedAt: string
  1746. ): void {
  1747. db.prepare(`UPDATE documents SET title = ?, modified_at = ? WHERE id = ?`)
  1748. .run(title, modifiedAt, documentId);
  1749. }
  1750. /**
  1751. * Update an existing document's hash, title, and modified_at timestamp.
  1752. * Used when content changes but the file path stays the same.
  1753. */
  1754. export function updateDocument(
  1755. db: Database,
  1756. documentId: number,
  1757. title: string,
  1758. hash: string,
  1759. modifiedAt: string
  1760. ): void {
  1761. db.prepare(`UPDATE documents SET title = ?, hash = ?, modified_at = ? WHERE id = ?`)
  1762. .run(title, hash, modifiedAt, documentId);
  1763. }
  1764. /**
  1765. * Deactivate a document (mark as inactive but don't delete).
  1766. */
  1767. export function deactivateDocument(db: Database, collectionName: string, path: string): void {
  1768. db.prepare(`UPDATE documents SET active = 0 WHERE collection = ? AND path = ? AND active = 1`)
  1769. .run(collectionName, path);
  1770. }
  1771. /**
  1772. * Get all active document paths for a collection.
  1773. */
  1774. export function getActiveDocumentPaths(db: Database, collectionName: string): string[] {
  1775. const rows = db.prepare(`
  1776. SELECT path FROM documents WHERE collection = ? AND active = 1
  1777. `).all(collectionName) as { path: string }[];
  1778. return rows.map(r => r.path);
  1779. }
  1780. export { formatQueryForEmbedding, formatDocForEmbedding };
  1781. export function chunkDocument(
  1782. content: string,
  1783. maxChars: number = CHUNK_SIZE_CHARS,
  1784. overlapChars: number = CHUNK_OVERLAP_CHARS,
  1785. windowChars: number = CHUNK_WINDOW_CHARS
  1786. ): { text: string; pos: number }[] {
  1787. if (content.length <= maxChars) {
  1788. return [{ text: content, pos: 0 }];
  1789. }
  1790. // Pre-scan all break points and code fences once
  1791. const breakPoints = scanBreakPoints(content);
  1792. const codeFences = findCodeFences(content);
  1793. const chunks: { text: string; pos: number }[] = [];
  1794. let charPos = 0;
  1795. while (charPos < content.length) {
  1796. // Calculate target end position for this chunk
  1797. const targetEndPos = Math.min(charPos + maxChars, content.length);
  1798. let endPos = targetEndPos;
  1799. // If not at the end, find the best break point
  1800. if (endPos < content.length) {
  1801. // Find best cutoff using scored algorithm
  1802. const bestCutoff = findBestCutoff(
  1803. breakPoints,
  1804. targetEndPos,
  1805. windowChars,
  1806. 0.7,
  1807. codeFences
  1808. );
  1809. // Only use the cutoff if it's within our current chunk
  1810. if (bestCutoff > charPos && bestCutoff <= targetEndPos) {
  1811. endPos = bestCutoff;
  1812. }
  1813. }
  1814. // Ensure we make progress
  1815. if (endPos <= charPos) {
  1816. endPos = Math.min(charPos + maxChars, content.length);
  1817. }
  1818. chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
  1819. // Move forward, but overlap with previous chunk
  1820. // For last chunk, don't overlap (just go to the end)
  1821. if (endPos >= content.length) {
  1822. break;
  1823. }
  1824. charPos = endPos - overlapChars;
  1825. const lastChunkPos = chunks.at(-1)!.pos;
  1826. if (charPos <= lastChunkPos) {
  1827. // Prevent infinite loop - move forward at least a bit
  1828. charPos = endPos;
  1829. }
  1830. }
  1831. return chunks;
  1832. }
  1833. /**
  1834. * Chunk a document by actual token count using the LLM tokenizer.
  1835. * More accurate than character-based chunking but requires async.
  1836. */
  1837. export async function chunkDocumentByTokens(
  1838. content: string,
  1839. maxTokens: number = CHUNK_SIZE_TOKENS,
  1840. overlapTokens: number = CHUNK_OVERLAP_TOKENS,
  1841. windowTokens: number = CHUNK_WINDOW_TOKENS,
  1842. signal?: AbortSignal
  1843. ): Promise<{ text: string; pos: number; tokens: number }[]> {
  1844. const llm = getDefaultLlamaCpp();
  1845. // Use moderate chars/token estimate (prose ~4, code ~2, mixed ~3)
  1846. // If chunks exceed limit, they'll be re-split with actual ratio
  1847. const avgCharsPerToken = 3;
  1848. const maxChars = maxTokens * avgCharsPerToken;
  1849. const overlapChars = overlapTokens * avgCharsPerToken;
  1850. const windowChars = windowTokens * avgCharsPerToken;
  1851. // Chunk in character space with conservative estimate
  1852. let charChunks = chunkDocument(content, maxChars, overlapChars, windowChars);
  1853. // Tokenize and split any chunks that still exceed limit
  1854. const results: { text: string; pos: number; tokens: number }[] = [];
  1855. for (const chunk of charChunks) {
  1856. // Respect abort signal to avoid runaway tokenization
  1857. if (signal?.aborted) break;
  1858. const tokens = await llm.tokenize(chunk.text);
  1859. if (tokens.length <= maxTokens) {
  1860. results.push({ text: chunk.text, pos: chunk.pos, tokens: tokens.length });
  1861. } else {
  1862. // Chunk is still too large - split it further
  1863. // Use actual token count to estimate better char limit
  1864. const actualCharsPerToken = chunk.text.length / tokens.length;
  1865. const safeMaxChars = Math.floor(maxTokens * actualCharsPerToken * 0.95); // 5% safety margin
  1866. const subChunks = chunkDocument(chunk.text, safeMaxChars, Math.floor(overlapChars * actualCharsPerToken / 2), Math.floor(windowChars * actualCharsPerToken / 2));
  1867. for (const subChunk of subChunks) {
  1868. if (signal?.aborted) break;
  1869. const subTokens = await llm.tokenize(subChunk.text);
  1870. results.push({
  1871. text: subChunk.text,
  1872. pos: chunk.pos + subChunk.pos,
  1873. tokens: subTokens.length,
  1874. });
  1875. }
  1876. }
  1877. }
  1878. return results;
  1879. }
  1880. // =============================================================================
  1881. // Fuzzy matching
  1882. // =============================================================================
  1883. function levenshtein(a: string, b: string): number {
  1884. const m = a.length, n = b.length;
  1885. if (m === 0) return n;
  1886. if (n === 0) return m;
  1887. const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
  1888. for (let i = 0; i <= m; i++) dp[i]![0] = i;
  1889. for (let j = 0; j <= n; j++) dp[0]![j] = j;
  1890. for (let i = 1; i <= m; i++) {
  1891. for (let j = 1; j <= n; j++) {
  1892. const cost = a[i - 1] === b[j - 1] ? 0 : 1;
  1893. dp[i]![j] = Math.min(
  1894. dp[i - 1]![j]! + 1,
  1895. dp[i]![j - 1]! + 1,
  1896. dp[i - 1]![j - 1]! + cost
  1897. );
  1898. }
  1899. }
  1900. return dp[m]![n]!;
  1901. }
  1902. /**
  1903. * Normalize a docid input by stripping surrounding quotes and leading #.
  1904. * Handles: "#abc123", 'abc123', "abc123", #abc123, abc123
  1905. * Returns the bare hex string.
  1906. */
  1907. export function normalizeDocid(docid: string): string {
  1908. let normalized = docid.trim();
  1909. // Strip surrounding quotes (single or double)
  1910. if ((normalized.startsWith('"') && normalized.endsWith('"')) ||
  1911. (normalized.startsWith("'") && normalized.endsWith("'"))) {
  1912. normalized = normalized.slice(1, -1);
  1913. }
  1914. // Strip leading # if present
  1915. if (normalized.startsWith('#')) {
  1916. normalized = normalized.slice(1);
  1917. }
  1918. return normalized;
  1919. }
  1920. /**
  1921. * Check if a string looks like a docid reference.
  1922. * Accepts: #abc123, abc123, "#abc123", "abc123", '#abc123', 'abc123'
  1923. * Returns true if the normalized form is a valid hex string of 6+ chars.
  1924. */
  1925. export function isDocid(input: string): boolean {
  1926. const normalized = normalizeDocid(input);
  1927. // Must be at least 6 hex characters
  1928. return normalized.length >= 6 && /^[a-f0-9]+$/i.test(normalized);
  1929. }
  1930. /**
  1931. * Find a document by its short docid (first 6 characters of hash).
  1932. * Returns the document's virtual path if found, null otherwise.
  1933. * If multiple documents match the same short hash (collision), returns the first one.
  1934. *
  1935. * Accepts lenient input: #abc123, abc123, "#abc123", "abc123"
  1936. */
  1937. export function findDocumentByDocid(db: Database, docid: string): { filepath: string; hash: string } | null {
  1938. const shortHash = normalizeDocid(docid);
  1939. if (shortHash.length < 1) return null;
  1940. // Look up documents where hash starts with the short hash
  1941. const doc = db.prepare(`
  1942. SELECT 'qmd://' || d.collection || '/' || d.path as filepath, d.hash
  1943. FROM documents d
  1944. WHERE d.hash LIKE ? AND d.active = 1
  1945. LIMIT 1
  1946. `).get(`${shortHash}%`) as { filepath: string; hash: string } | null;
  1947. return doc;
  1948. }
  1949. export function findSimilarFiles(db: Database, query: string, maxDistance: number = 3, limit: number = 5): string[] {
  1950. const allFiles = db.prepare(`
  1951. SELECT d.path
  1952. FROM documents d
  1953. WHERE d.active = 1
  1954. `).all() as { path: string }[];
  1955. const queryLower = query.toLowerCase();
  1956. const scored = allFiles
  1957. .map(f => ({ path: f.path, dist: levenshtein(f.path.toLowerCase(), queryLower) }))
  1958. .filter(f => f.dist <= maxDistance)
  1959. .sort((a, b) => a.dist - b.dist)
  1960. .slice(0, limit);
  1961. return scored.map(f => f.path);
  1962. }
  1963. export function matchFilesByGlob(db: Database, pattern: string): { filepath: string; displayPath: string; bodyLength: number }[] {
  1964. const allFiles = db.prepare(`
  1965. SELECT
  1966. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  1967. LENGTH(content.doc) as body_length,
  1968. d.path,
  1969. d.collection
  1970. FROM documents d
  1971. JOIN content ON content.hash = d.hash
  1972. WHERE d.active = 1
  1973. `).all() as { virtual_path: string; body_length: number; path: string; collection: string }[];
  1974. const isMatch = picomatch(pattern);
  1975. return allFiles
  1976. .filter(f => isMatch(f.virtual_path) || isMatch(f.path))
  1977. .map(f => ({
  1978. filepath: f.virtual_path, // Virtual path for precise lookup
  1979. displayPath: f.path, // Relative path for display
  1980. bodyLength: f.body_length
  1981. }));
  1982. }
  1983. // =============================================================================
  1984. // Context
  1985. // =============================================================================
  1986. /**
  1987. * Get context for a file path using hierarchical inheritance.
  1988. * Contexts are collection-scoped and inherit from parent directories.
  1989. * For example, context at "/talks" applies to "/talks/2024/keynote.md".
  1990. *
  1991. * @param db Database instance (unused - kept for compatibility)
  1992. * @param collectionName Collection name
  1993. * @param path Relative path within the collection
  1994. * @returns Context string or null if no context is defined
  1995. */
  1996. export function getContextForPath(db: Database, collectionName: string, path: string): string | null {
  1997. const coll = getStoreCollection(db, collectionName);
  1998. if (!coll) return null;
  1999. // Collect ALL matching contexts (global + all path prefixes)
  2000. const contexts: string[] = [];
  2001. // Add global context if present
  2002. const globalCtx = getStoreGlobalContext(db);
  2003. if (globalCtx) {
  2004. contexts.push(globalCtx);
  2005. }
  2006. // Add all matching path contexts (from most general to most specific)
  2007. if (coll.context) {
  2008. const normalizedPath = path.startsWith("/") ? path : `/${path}`;
  2009. // Collect all matching prefixes
  2010. const matchingContexts: { prefix: string; context: string }[] = [];
  2011. for (const [prefix, context] of Object.entries(coll.context)) {
  2012. const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
  2013. if (normalizedPath.startsWith(normalizedPrefix)) {
  2014. matchingContexts.push({ prefix: normalizedPrefix, context });
  2015. }
  2016. }
  2017. // Sort by prefix length (shortest/most general first)
  2018. matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
  2019. // Add all matching contexts
  2020. for (const match of matchingContexts) {
  2021. contexts.push(match.context);
  2022. }
  2023. }
  2024. // Join all contexts with double newline
  2025. return contexts.length > 0 ? contexts.join('\n\n') : null;
  2026. }
  2027. /**
  2028. * Get context for a file path (virtual or filesystem).
  2029. * Resolves the collection and relative path from the DB store_collections table.
  2030. */
  2031. export function getContextForFile(db: Database, filepath: string): string | null {
  2032. // Handle undefined or null filepath
  2033. if (!filepath) return null;
  2034. // Get all collections from DB
  2035. const collections = getStoreCollections(db);
  2036. // Parse virtual path format: qmd://collection/path
  2037. let collectionName: string | null = null;
  2038. let relativePath: string | null = null;
  2039. const parsedVirtual = filepath.startsWith('qmd://') ? parseVirtualPath(filepath) : null;
  2040. if (parsedVirtual) {
  2041. collectionName = parsedVirtual.collectionName;
  2042. relativePath = parsedVirtual.path;
  2043. } else {
  2044. // Filesystem path: find which collection this absolute path belongs to
  2045. for (const coll of collections) {
  2046. // Skip collections with missing paths
  2047. if (!coll || !coll.path) continue;
  2048. if (filepath.startsWith(coll.path + '/') || filepath === coll.path) {
  2049. collectionName = coll.name;
  2050. // Extract relative path
  2051. relativePath = filepath.startsWith(coll.path + '/')
  2052. ? filepath.slice(coll.path.length + 1)
  2053. : '';
  2054. break;
  2055. }
  2056. }
  2057. if (!collectionName || relativePath === null) return null;
  2058. }
  2059. // Get the collection from DB
  2060. const coll = getStoreCollection(db, collectionName);
  2061. if (!coll) return null;
  2062. // Verify this document exists in the database
  2063. const doc = db.prepare(`
  2064. SELECT d.path
  2065. FROM documents d
  2066. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  2067. LIMIT 1
  2068. `).get(collectionName, relativePath) as { path: string } | null;
  2069. if (!doc) return null;
  2070. // Collect ALL matching contexts (global + all path prefixes)
  2071. const contexts: string[] = [];
  2072. // Add global context if present
  2073. const globalCtx = getStoreGlobalContext(db);
  2074. if (globalCtx) {
  2075. contexts.push(globalCtx);
  2076. }
  2077. // Add all matching path contexts (from most general to most specific)
  2078. if (coll.context) {
  2079. const normalizedPath = relativePath.startsWith("/") ? relativePath : `/${relativePath}`;
  2080. // Collect all matching prefixes
  2081. const matchingContexts: { prefix: string; context: string }[] = [];
  2082. for (const [prefix, context] of Object.entries(coll.context)) {
  2083. const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
  2084. if (normalizedPath.startsWith(normalizedPrefix)) {
  2085. matchingContexts.push({ prefix: normalizedPrefix, context });
  2086. }
  2087. }
  2088. // Sort by prefix length (shortest/most general first)
  2089. matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
  2090. // Add all matching contexts
  2091. for (const match of matchingContexts) {
  2092. contexts.push(match.context);
  2093. }
  2094. }
  2095. // Join all contexts with double newline
  2096. return contexts.length > 0 ? contexts.join('\n\n') : null;
  2097. }
  2098. /**
  2099. * Get collection by name from DB store_collections table.
  2100. */
  2101. export function getCollectionByName(db: Database, name: string): { name: string; pwd: string; glob_pattern: string } | null {
  2102. const collection = getStoreCollection(db, name);
  2103. if (!collection) return null;
  2104. return {
  2105. name: collection.name,
  2106. pwd: collection.path,
  2107. glob_pattern: collection.pattern,
  2108. };
  2109. }
  2110. /**
  2111. * List all collections with document counts from database.
  2112. * Merges store_collections config with database statistics.
  2113. */
  2114. export function listCollections(db: Database): { name: string; pwd: string; glob_pattern: string; doc_count: number; active_count: number; last_modified: string | null; includeByDefault: boolean }[] {
  2115. const collections = getStoreCollections(db);
  2116. // Get document counts from database for each collection
  2117. const result = collections.map(coll => {
  2118. const stats = db.prepare(`
  2119. SELECT
  2120. COUNT(d.id) as doc_count,
  2121. SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
  2122. MAX(d.modified_at) as last_modified
  2123. FROM documents d
  2124. WHERE d.collection = ?
  2125. `).get(coll.name) as { doc_count: number; active_count: number; last_modified: string | null } | null;
  2126. return {
  2127. name: coll.name,
  2128. pwd: coll.path,
  2129. glob_pattern: coll.pattern,
  2130. doc_count: stats?.doc_count || 0,
  2131. active_count: stats?.active_count || 0,
  2132. last_modified: stats?.last_modified || null,
  2133. includeByDefault: coll.includeByDefault !== false,
  2134. };
  2135. });
  2136. return result;
  2137. }
  2138. /**
  2139. * Remove a collection and clean up its documents.
  2140. * Uses collections.ts to remove from YAML config and cleans up database.
  2141. */
  2142. export function removeCollection(db: Database, collectionName: string): { deletedDocs: number; cleanedHashes: number } {
  2143. // Delete documents from database
  2144. const docResult = db.prepare(`DELETE FROM documents WHERE collection = ?`).run(collectionName);
  2145. // Clean up orphaned content hashes
  2146. const cleanupResult = db.prepare(`
  2147. DELETE FROM content
  2148. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  2149. `).run();
  2150. // Remove from store_collections
  2151. deleteStoreCollection(db, collectionName);
  2152. return {
  2153. deletedDocs: docResult.changes,
  2154. cleanedHashes: cleanupResult.changes
  2155. };
  2156. }
  2157. /**
  2158. * Rename a collection.
  2159. * Updates both YAML config and database documents table.
  2160. */
  2161. export function renameCollection(db: Database, oldName: string, newName: string): void {
  2162. // Update all documents with the new collection name in database
  2163. db.prepare(`UPDATE documents SET collection = ? WHERE collection = ?`)
  2164. .run(newName, oldName);
  2165. // Rename in store_collections
  2166. renameStoreCollection(db, oldName, newName);
  2167. }
  2168. // =============================================================================
  2169. // Context Management Operations
  2170. // =============================================================================
  2171. /**
  2172. * Insert or update a context for a specific collection and path prefix.
  2173. */
  2174. export function insertContext(db: Database, collectionId: number, pathPrefix: string, context: string): void {
  2175. // Get collection name from ID
  2176. const coll = db.prepare(`SELECT name FROM collections WHERE id = ?`).get(collectionId) as { name: string } | null;
  2177. if (!coll) {
  2178. throw new Error(`Collection with id ${collectionId} not found`);
  2179. }
  2180. // Add context to store_collections
  2181. updateStoreContext(db, coll.name, pathPrefix, context);
  2182. }
  2183. /**
  2184. * Delete a context for a specific collection and path prefix.
  2185. * Returns the number of contexts deleted.
  2186. */
  2187. export function deleteContext(db: Database, collectionName: string, pathPrefix: string): number {
  2188. // Remove context from store_collections
  2189. const success = removeStoreContext(db, collectionName, pathPrefix);
  2190. return success ? 1 : 0;
  2191. }
  2192. /**
  2193. * Delete all global contexts (contexts with empty path_prefix).
  2194. * Returns the number of contexts deleted.
  2195. */
  2196. export function deleteGlobalContexts(db: Database): number {
  2197. let deletedCount = 0;
  2198. // Remove global context
  2199. setStoreGlobalContext(db, undefined);
  2200. deletedCount++;
  2201. // Remove root context (empty string) from all collections
  2202. const collections = getStoreCollections(db);
  2203. for (const coll of collections) {
  2204. const success = removeStoreContext(db, coll.name, '');
  2205. if (success) {
  2206. deletedCount++;
  2207. }
  2208. }
  2209. return deletedCount;
  2210. }
  2211. /**
  2212. * List all contexts, grouped by collection.
  2213. * Returns contexts ordered by collection name, then by path prefix length (longest first).
  2214. */
  2215. export function listPathContexts(db: Database): { collection_name: string; path_prefix: string; context: string }[] {
  2216. const allContexts = getStoreContexts(db);
  2217. // Convert to expected format and sort
  2218. return allContexts.map(ctx => ({
  2219. collection_name: ctx.collection,
  2220. path_prefix: ctx.path,
  2221. context: ctx.context,
  2222. })).sort((a, b) => {
  2223. // Sort by collection name first
  2224. if (a.collection_name !== b.collection_name) {
  2225. return a.collection_name.localeCompare(b.collection_name);
  2226. }
  2227. // Then by path prefix length (longest first)
  2228. if (a.path_prefix.length !== b.path_prefix.length) {
  2229. return b.path_prefix.length - a.path_prefix.length;
  2230. }
  2231. // Then alphabetically
  2232. return a.path_prefix.localeCompare(b.path_prefix);
  2233. });
  2234. }
  2235. /**
  2236. * Get all collections (name only - from YAML config).
  2237. */
  2238. export function getAllCollections(db: Database): { name: string }[] {
  2239. const collections = getStoreCollections(db);
  2240. return collections.map(c => ({ name: c.name }));
  2241. }
  2242. /**
  2243. * Check which collections don't have any context defined.
  2244. * Returns collections that have no context entries at all (not even root context).
  2245. */
  2246. export function getCollectionsWithoutContext(db: Database): { name: string; pwd: string; doc_count: number }[] {
  2247. // Get all collections from DB
  2248. const allCollections = getStoreCollections(db);
  2249. // Filter to those without context
  2250. const collectionsWithoutContext: { name: string; pwd: string; doc_count: number }[] = [];
  2251. for (const coll of allCollections) {
  2252. // Check if collection has any context
  2253. if (!coll.context || Object.keys(coll.context).length === 0) {
  2254. // Get doc count from database
  2255. const stats = db.prepare(`
  2256. SELECT COUNT(d.id) as doc_count
  2257. FROM documents d
  2258. WHERE d.collection = ? AND d.active = 1
  2259. `).get(coll.name) as { doc_count: number } | null;
  2260. collectionsWithoutContext.push({
  2261. name: coll.name,
  2262. pwd: coll.path,
  2263. doc_count: stats?.doc_count || 0,
  2264. });
  2265. }
  2266. }
  2267. return collectionsWithoutContext.sort((a, b) => a.name.localeCompare(b.name));
  2268. }
  2269. /**
  2270. * Get top-level directories in a collection that don't have context.
  2271. * Useful for suggesting where context might be needed.
  2272. */
  2273. export function getTopLevelPathsWithoutContext(db: Database, collectionName: string): string[] {
  2274. // Get all paths in the collection from database
  2275. const paths = db.prepare(`
  2276. SELECT DISTINCT path FROM documents
  2277. WHERE collection = ? AND active = 1
  2278. `).all(collectionName) as { path: string }[];
  2279. // Get existing contexts for this collection from DB
  2280. const dbColl = getStoreCollection(db, collectionName);
  2281. if (!dbColl) return [];
  2282. const contextPrefixes = new Set<string>();
  2283. if (dbColl.context) {
  2284. for (const prefix of Object.keys(dbColl.context)) {
  2285. contextPrefixes.add(prefix);
  2286. }
  2287. }
  2288. // Extract top-level directories (first path component)
  2289. const topLevelDirs = new Set<string>();
  2290. for (const { path } of paths) {
  2291. const parts = path.split('/').filter(Boolean);
  2292. if (parts.length > 1) {
  2293. const dir = parts[0];
  2294. if (dir) topLevelDirs.add(dir);
  2295. }
  2296. }
  2297. // Filter out directories that already have context (exact or parent)
  2298. const missing: string[] = [];
  2299. for (const dir of topLevelDirs) {
  2300. let hasContext = false;
  2301. // Check if this dir or any parent has context
  2302. for (const prefix of contextPrefixes) {
  2303. if (prefix === '' || prefix === dir || dir.startsWith(prefix + '/')) {
  2304. hasContext = true;
  2305. break;
  2306. }
  2307. }
  2308. if (!hasContext) {
  2309. missing.push(dir);
  2310. }
  2311. }
  2312. return missing.sort();
  2313. }
  2314. // =============================================================================
  2315. // FTS Search
  2316. // =============================================================================
  2317. function sanitizeFTS5Term(term: string): string {
  2318. return term.replace(/[^\p{L}\p{N}']/gu, '').toLowerCase();
  2319. }
  2320. /**
  2321. * Parse lex query syntax into FTS5 query.
  2322. *
  2323. * Supports:
  2324. * - Quoted phrases: "exact phrase" → "exact phrase" (exact match)
  2325. * - Negation: -term or -"phrase" → uses FTS5 NOT operator
  2326. * - Plain terms: term → "term"* (prefix match)
  2327. *
  2328. * FTS5 NOT is a binary operator: `term1 NOT term2` means "match term1 but not term2".
  2329. * So `-term` only works when there are also positive terms.
  2330. *
  2331. * Examples:
  2332. * performance -sports → "performance"* NOT "sports"*
  2333. * "machine learning" → "machine learning"
  2334. */
  2335. function buildFTS5Query(query: string): string | null {
  2336. const positive: string[] = [];
  2337. const negative: string[] = [];
  2338. let i = 0;
  2339. const s = query.trim();
  2340. while (i < s.length) {
  2341. // Skip whitespace
  2342. while (i < s.length && /\s/.test(s[i]!)) i++;
  2343. if (i >= s.length) break;
  2344. // Check for negation prefix
  2345. const negated = s[i] === '-';
  2346. if (negated) i++;
  2347. // Check for quoted phrase
  2348. if (s[i] === '"') {
  2349. const start = i + 1;
  2350. i++;
  2351. while (i < s.length && s[i] !== '"') i++;
  2352. const phrase = s.slice(start, i).trim();
  2353. i++; // skip closing quote
  2354. if (phrase.length > 0) {
  2355. const sanitized = phrase.split(/\s+/).map(t => sanitizeFTS5Term(t)).filter(t => t).join(' ');
  2356. if (sanitized) {
  2357. const ftsPhrase = `"${sanitized}"`; // Exact phrase, no prefix match
  2358. if (negated) {
  2359. negative.push(ftsPhrase);
  2360. } else {
  2361. positive.push(ftsPhrase);
  2362. }
  2363. }
  2364. }
  2365. } else {
  2366. // Plain term (until whitespace or quote)
  2367. const start = i;
  2368. while (i < s.length && !/[\s"]/.test(s[i]!)) i++;
  2369. const term = s.slice(start, i);
  2370. const sanitized = sanitizeFTS5Term(term);
  2371. if (sanitized) {
  2372. const ftsTerm = `"${sanitized}"*`; // Prefix match
  2373. if (negated) {
  2374. negative.push(ftsTerm);
  2375. } else {
  2376. positive.push(ftsTerm);
  2377. }
  2378. }
  2379. }
  2380. }
  2381. if (positive.length === 0 && negative.length === 0) return null;
  2382. // If only negative terms, we can't search (FTS5 NOT is binary)
  2383. if (positive.length === 0) return null;
  2384. // Join positive terms with AND
  2385. let result = positive.join(' AND ');
  2386. // Add NOT clause for negative terms
  2387. for (const neg of negative) {
  2388. result = `${result} NOT ${neg}`;
  2389. }
  2390. return result;
  2391. }
  2392. /**
  2393. * Validate that a vec/hyde query doesn't use lex-only syntax.
  2394. * Returns error message if invalid, null if valid.
  2395. */
  2396. export function validateSemanticQuery(query: string): string | null {
  2397. // Check for negation syntax
  2398. if (/-\w/.test(query) || /-"/.test(query)) {
  2399. return 'Negation (-term) is not supported in vec/hyde queries. Use lex for exclusions.';
  2400. }
  2401. return null;
  2402. }
  2403. export function validateLexQuery(query: string): string | null {
  2404. if (/[\r\n]/.test(query)) {
  2405. return 'Lex queries must be a single line. Remove newline characters or split into separate lex: lines.';
  2406. }
  2407. const quoteCount = (query.match(/"/g) ?? []).length;
  2408. if (quoteCount % 2 === 1) {
  2409. return 'Lex query has an unmatched double quote ("). Add the closing quote or remove it.';
  2410. }
  2411. return null;
  2412. }
  2413. export function searchFTS(db: Database, query: string, limit: number = 20, collectionName?: string): SearchResult[] {
  2414. const ftsQuery = buildFTS5Query(query);
  2415. if (!ftsQuery) return [];
  2416. let sql = `
  2417. SELECT
  2418. 'qmd://' || d.collection || '/' || d.path as filepath,
  2419. d.collection || '/' || d.path as display_path,
  2420. d.title,
  2421. content.doc as body,
  2422. d.hash,
  2423. bm25(documents_fts, 10.0, 1.0) as bm25_score
  2424. FROM documents_fts f
  2425. JOIN documents d ON d.id = f.rowid
  2426. JOIN content ON content.hash = d.hash
  2427. WHERE documents_fts MATCH ? AND d.active = 1
  2428. `;
  2429. const params: (string | number)[] = [ftsQuery];
  2430. if (collectionName) {
  2431. sql += ` AND d.collection = ?`;
  2432. params.push(String(collectionName));
  2433. }
  2434. // bm25 lower is better; sort ascending.
  2435. sql += ` ORDER BY bm25_score ASC LIMIT ?`;
  2436. params.push(limit);
  2437. const rows = db.prepare(sql).all(...params) as { filepath: string; display_path: string; title: string; body: string; hash: string; bm25_score: number }[];
  2438. return rows.map(row => {
  2439. const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
  2440. // Convert bm25 (negative, lower is better) into a stable [0..1) score where higher is better.
  2441. // FTS5 BM25 scores are negative (e.g., -10 is strong, -2 is weak).
  2442. // |x| / (1 + |x|) maps: strong(-10)→0.91, medium(-2)→0.67, weak(-0.5)→0.33, none(0)→0.
  2443. // Monotonic and query-independent — no per-query normalization needed.
  2444. const score = Math.abs(row.bm25_score) / (1 + Math.abs(row.bm25_score));
  2445. return {
  2446. filepath: row.filepath,
  2447. displayPath: row.display_path,
  2448. title: row.title,
  2449. hash: row.hash,
  2450. docid: getDocid(row.hash),
  2451. collectionName,
  2452. modifiedAt: "", // Not available in FTS query
  2453. bodyLength: row.body.length,
  2454. body: row.body,
  2455. context: getContextForFile(db, row.filepath),
  2456. score,
  2457. source: "fts" as const,
  2458. };
  2459. });
  2460. }
  2461. // =============================================================================
  2462. // Vector Search
  2463. // =============================================================================
  2464. export async function searchVec(db: Database, query: string, model: string, limit: number = 20, collectionName?: string, session?: ILLMSession, precomputedEmbedding?: number[]): Promise<SearchResult[]> {
  2465. const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  2466. if (!tableExists) return [];
  2467. const embedding = precomputedEmbedding ?? await getEmbedding(query, model, true, session);
  2468. if (!embedding) return [];
  2469. // IMPORTANT: We use a two-step query approach here because sqlite-vec virtual tables
  2470. // hang indefinitely when combined with JOINs in the same query. Do NOT try to
  2471. // "optimize" this by combining into a single query with JOINs - it will break.
  2472. // See: https://github.com/tobi/qmd/pull/23
  2473. // Step 1: Get vector matches from sqlite-vec (no JOINs allowed)
  2474. const vecResults = db.prepare(`
  2475. SELECT hash_seq, distance
  2476. FROM vectors_vec
  2477. WHERE embedding MATCH ? AND k = ?
  2478. `).all(new Float32Array(embedding), limit * 3) as { hash_seq: string; distance: number }[];
  2479. if (vecResults.length === 0) return [];
  2480. // Step 2: Get chunk info and document data
  2481. const hashSeqs = vecResults.map(r => r.hash_seq);
  2482. const distanceMap = new Map(vecResults.map(r => [r.hash_seq, r.distance]));
  2483. // Build query for document lookup
  2484. const placeholders = hashSeqs.map(() => '?').join(',');
  2485. let docSql = `
  2486. SELECT
  2487. cv.hash || '_' || cv.seq as hash_seq,
  2488. cv.hash,
  2489. cv.pos,
  2490. 'qmd://' || d.collection || '/' || d.path as filepath,
  2491. d.collection || '/' || d.path as display_path,
  2492. d.title,
  2493. content.doc as body
  2494. FROM content_vectors cv
  2495. JOIN documents d ON d.hash = cv.hash AND d.active = 1
  2496. JOIN content ON content.hash = d.hash
  2497. WHERE cv.hash || '_' || cv.seq IN (${placeholders})
  2498. `;
  2499. const params: string[] = [...hashSeqs];
  2500. if (collectionName) {
  2501. docSql += ` AND d.collection = ?`;
  2502. params.push(collectionName);
  2503. }
  2504. const docRows = db.prepare(docSql).all(...params) as {
  2505. hash_seq: string; hash: string; pos: number; filepath: string;
  2506. display_path: string; title: string; body: string;
  2507. }[];
  2508. // Combine with distances and dedupe by filepath
  2509. const seen = new Map<string, { row: typeof docRows[0]; bestDist: number }>();
  2510. for (const row of docRows) {
  2511. const distance = distanceMap.get(row.hash_seq) ?? 1;
  2512. const existing = seen.get(row.filepath);
  2513. if (!existing || distance < existing.bestDist) {
  2514. seen.set(row.filepath, { row, bestDist: distance });
  2515. }
  2516. }
  2517. return Array.from(seen.values())
  2518. .sort((a, b) => a.bestDist - b.bestDist)
  2519. .slice(0, limit)
  2520. .map(({ row, bestDist }) => {
  2521. const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
  2522. return {
  2523. filepath: row.filepath,
  2524. displayPath: row.display_path,
  2525. title: row.title,
  2526. hash: row.hash,
  2527. docid: getDocid(row.hash),
  2528. collectionName,
  2529. modifiedAt: "", // Not available in vec query
  2530. bodyLength: row.body.length,
  2531. body: row.body,
  2532. context: getContextForFile(db, row.filepath),
  2533. score: 1 - bestDist, // Cosine similarity = 1 - cosine distance
  2534. source: "vec" as const,
  2535. chunkPos: row.pos,
  2536. };
  2537. });
  2538. }
  2539. // =============================================================================
  2540. // Embeddings
  2541. // =============================================================================
  2542. async function getEmbedding(text: string, model: string, isQuery: boolean, session?: ILLMSession, llmOverride?: LlamaCpp): Promise<number[] | null> {
  2543. // Format text using the appropriate prompt template
  2544. const formattedText = isQuery ? formatQueryForEmbedding(text, model) : formatDocForEmbedding(text, undefined, model);
  2545. const result = session
  2546. ? await session.embed(formattedText, { model, isQuery })
  2547. : await (llmOverride ?? getDefaultLlamaCpp()).embed(formattedText, { model, isQuery });
  2548. return result?.embedding || null;
  2549. }
  2550. /**
  2551. * Get all unique content hashes that need embeddings (from active documents).
  2552. * Returns hash, document body, and a sample path for display purposes.
  2553. */
  2554. export function getHashesForEmbedding(db: Database): { hash: string; body: string; path: string }[] {
  2555. return db.prepare(`
  2556. SELECT d.hash, c.doc as body, MIN(d.path) as path
  2557. FROM documents d
  2558. JOIN content c ON d.hash = c.hash
  2559. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  2560. WHERE d.active = 1 AND v.hash IS NULL
  2561. GROUP BY d.hash
  2562. `).all() as { hash: string; body: string; path: string }[];
  2563. }
  2564. /**
  2565. * Clear all embeddings from the database (force re-index).
  2566. * Deletes all rows from content_vectors and drops the vectors_vec table.
  2567. */
  2568. export function clearAllEmbeddings(db: Database): void {
  2569. db.exec(`DELETE FROM content_vectors`);
  2570. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  2571. }
  2572. /**
  2573. * Insert a single embedding into both content_vectors and vectors_vec tables.
  2574. * The hash_seq key is formatted as "hash_seq" for the vectors_vec table.
  2575. */
  2576. export function insertEmbedding(
  2577. db: Database,
  2578. hash: string,
  2579. seq: number,
  2580. pos: number,
  2581. embedding: Float32Array,
  2582. model: string,
  2583. embeddedAt: string
  2584. ): void {
  2585. const hashSeq = `${hash}_${seq}`;
  2586. const insertVecStmt = db.prepare(`INSERT OR REPLACE INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`);
  2587. const insertContentVectorStmt = db.prepare(`INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, ?, ?, ?, ?)`);
  2588. insertVecStmt.run(hashSeq, embedding);
  2589. insertContentVectorStmt.run(hash, seq, pos, model, embeddedAt);
  2590. }
  2591. // =============================================================================
  2592. // Query expansion
  2593. // =============================================================================
  2594. export async function expandQuery(query: string, model: string = DEFAULT_QUERY_MODEL, db: Database, intent?: string, llmOverride?: LlamaCpp): Promise<ExpandedQuery[]> {
  2595. // Check cache first — stored as JSON preserving types
  2596. const cacheKey = getCacheKey("expandQuery", { query, model, ...(intent && { intent }) });
  2597. const cached = getCachedResult(db, cacheKey);
  2598. if (cached) {
  2599. try {
  2600. const parsed = JSON.parse(cached) as any[];
  2601. // Migrate old cache format: { type, text } → { type, query }
  2602. if (parsed.length > 0 && parsed[0].query) {
  2603. return parsed as ExpandedQuery[];
  2604. } else if (parsed.length > 0 && parsed[0].text) {
  2605. return parsed.map((r: any) => ({ type: r.type, query: r.text }));
  2606. }
  2607. } catch {
  2608. // Old cache format (pre-typed, newline-separated text) — re-expand
  2609. }
  2610. }
  2611. const llm = llmOverride ?? getDefaultLlamaCpp();
  2612. // Note: LlamaCpp uses hardcoded model, model parameter is ignored
  2613. const results = await llm.expandQuery(query, { intent });
  2614. // Map Queryable[] → ExpandedQuery[] (same shape, decoupled from llm.ts internals).
  2615. // Filter out entries that duplicate the original query text.
  2616. const expanded: ExpandedQuery[] = results
  2617. .filter(r => r.text !== query)
  2618. .map(r => ({ type: r.type, query: r.text }));
  2619. if (expanded.length > 0) {
  2620. setCachedResult(db, cacheKey, JSON.stringify(expanded));
  2621. }
  2622. return expanded;
  2623. }
  2624. // =============================================================================
  2625. // Reranking
  2626. // =============================================================================
  2627. export async function rerank(query: string, documents: { file: string; text: string }[], model: string = DEFAULT_RERANK_MODEL, db: Database, intent?: string, llmOverride?: LlamaCpp): Promise<{ file: string; score: number }[]> {
  2628. // Prepend intent to rerank query so the reranker scores with domain context
  2629. const rerankQuery = intent ? `${intent}\n\n${query}` : query;
  2630. const cachedResults: Map<string, number> = new Map();
  2631. const uncachedDocsByChunk: Map<string, RerankDocument> = new Map();
  2632. // Check cache for each document
  2633. // Cache key includes chunk text — different queries can select different chunks
  2634. // from the same file, and the reranker score depends on which chunk was sent.
  2635. // File path is excluded from the new cache key because the reranker score
  2636. // depends on the chunk content, not where it came from.
  2637. for (const doc of documents) {
  2638. const cacheKey = getCacheKey("rerank", { query: rerankQuery, model, chunk: doc.text });
  2639. const legacyCacheKey = getCacheKey("rerank", { query, file: doc.file, model, chunk: doc.text });
  2640. const cached = getCachedResult(db, cacheKey) ?? getCachedResult(db, legacyCacheKey);
  2641. if (cached !== null) {
  2642. cachedResults.set(doc.text, parseFloat(cached));
  2643. } else {
  2644. uncachedDocsByChunk.set(doc.text, { file: doc.file, text: doc.text });
  2645. }
  2646. }
  2647. // Rerank uncached documents using LlamaCpp
  2648. if (uncachedDocsByChunk.size > 0) {
  2649. const llm = llmOverride ?? getDefaultLlamaCpp();
  2650. const uncachedDocs = [...uncachedDocsByChunk.values()];
  2651. const rerankResult = await llm.rerank(rerankQuery, uncachedDocs, { model });
  2652. // Cache results by chunk text so identical chunks across files are scored once.
  2653. const textByFile = new Map(uncachedDocs.map(d => [d.file, d.text]));
  2654. for (const result of rerankResult.results) {
  2655. const chunk = textByFile.get(result.file) || "";
  2656. const cacheKey = getCacheKey("rerank", { query: rerankQuery, model, chunk });
  2657. setCachedResult(db, cacheKey, result.score.toString());
  2658. cachedResults.set(chunk, result.score);
  2659. }
  2660. }
  2661. // Return all results sorted by score
  2662. return documents
  2663. .map(doc => ({ file: doc.file, score: cachedResults.get(doc.text) || 0 }))
  2664. .sort((a, b) => b.score - a.score);
  2665. }
  2666. // =============================================================================
  2667. // Reciprocal Rank Fusion
  2668. // =============================================================================
  2669. export function reciprocalRankFusion(
  2670. resultLists: RankedResult[][],
  2671. weights: number[] = [],
  2672. k: number = 60
  2673. ): RankedResult[] {
  2674. const scores = new Map<string, { result: RankedResult; rrfScore: number; topRank: number }>();
  2675. for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
  2676. const list = resultLists[listIdx];
  2677. if (!list) continue;
  2678. const weight = weights[listIdx] ?? 1.0;
  2679. for (let rank = 0; rank < list.length; rank++) {
  2680. const result = list[rank];
  2681. if (!result) continue;
  2682. const rrfContribution = weight / (k + rank + 1);
  2683. const existing = scores.get(result.file);
  2684. if (existing) {
  2685. existing.rrfScore += rrfContribution;
  2686. existing.topRank = Math.min(existing.topRank, rank);
  2687. } else {
  2688. scores.set(result.file, {
  2689. result,
  2690. rrfScore: rrfContribution,
  2691. topRank: rank,
  2692. });
  2693. }
  2694. }
  2695. }
  2696. // Top-rank bonus
  2697. for (const entry of scores.values()) {
  2698. if (entry.topRank === 0) {
  2699. entry.rrfScore += 0.05;
  2700. } else if (entry.topRank <= 2) {
  2701. entry.rrfScore += 0.02;
  2702. }
  2703. }
  2704. return Array.from(scores.values())
  2705. .sort((a, b) => b.rrfScore - a.rrfScore)
  2706. .map(e => ({ ...e.result, score: e.rrfScore }));
  2707. }
  2708. /**
  2709. * Build per-document RRF contribution traces for explain/debug output.
  2710. */
  2711. export function buildRrfTrace(
  2712. resultLists: RankedResult[][],
  2713. weights: number[] = [],
  2714. listMeta: RankedListMeta[] = [],
  2715. k: number = 60
  2716. ): Map<string, RRFScoreTrace> {
  2717. const traces = new Map<string, RRFScoreTrace>();
  2718. for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
  2719. const list = resultLists[listIdx];
  2720. if (!list) continue;
  2721. const weight = weights[listIdx] ?? 1.0;
  2722. const meta = listMeta[listIdx] ?? {
  2723. source: "fts",
  2724. queryType: "original",
  2725. query: "",
  2726. } as const;
  2727. for (let rank0 = 0; rank0 < list.length; rank0++) {
  2728. const result = list[rank0];
  2729. if (!result) continue;
  2730. const rank = rank0 + 1; // 1-indexed rank for explain output
  2731. const contribution = weight / (k + rank);
  2732. const existing = traces.get(result.file);
  2733. const detail: RRFContributionTrace = {
  2734. listIndex: listIdx,
  2735. source: meta.source,
  2736. queryType: meta.queryType,
  2737. query: meta.query,
  2738. rank,
  2739. weight,
  2740. backendScore: result.score,
  2741. rrfContribution: contribution,
  2742. };
  2743. if (existing) {
  2744. existing.baseScore += contribution;
  2745. existing.topRank = Math.min(existing.topRank, rank);
  2746. existing.contributions.push(detail);
  2747. } else {
  2748. traces.set(result.file, {
  2749. contributions: [detail],
  2750. baseScore: contribution,
  2751. topRank: rank,
  2752. topRankBonus: 0,
  2753. totalScore: 0,
  2754. });
  2755. }
  2756. }
  2757. }
  2758. for (const trace of traces.values()) {
  2759. let bonus = 0;
  2760. if (trace.topRank === 1) bonus = 0.05;
  2761. else if (trace.topRank <= 3) bonus = 0.02;
  2762. trace.topRankBonus = bonus;
  2763. trace.totalScore = trace.baseScore + bonus;
  2764. }
  2765. return traces;
  2766. }
  2767. // =============================================================================
  2768. // Document retrieval
  2769. // =============================================================================
  2770. type DbDocRow = {
  2771. virtual_path: string;
  2772. display_path: string;
  2773. title: string;
  2774. hash: string;
  2775. collection: string;
  2776. path: string;
  2777. modified_at: string;
  2778. body_length: number;
  2779. body?: string;
  2780. };
  2781. /**
  2782. * Find a document by filename/path, docid (#hash), or with fuzzy matching.
  2783. * Returns document metadata without body by default.
  2784. *
  2785. * Supports:
  2786. * - Virtual paths: qmd://collection/path/to/file.md
  2787. * - Absolute paths: /path/to/file.md
  2788. * - Relative paths: path/to/file.md
  2789. * - Short docid: #abc123 (first 6 chars of hash)
  2790. */
  2791. export function findDocument(db: Database, filename: string, options: { includeBody?: boolean } = {}): DocumentResult | DocumentNotFound {
  2792. let filepath = filename;
  2793. const colonMatch = filepath.match(/:(\d+)$/);
  2794. if (colonMatch) {
  2795. filepath = filepath.slice(0, -colonMatch[0].length);
  2796. }
  2797. // Check if this is a docid lookup (#abc123, abc123, "#abc123", "abc123", etc.)
  2798. if (isDocid(filepath)) {
  2799. const docidMatch = findDocumentByDocid(db, filepath);
  2800. if (docidMatch) {
  2801. filepath = docidMatch.filepath;
  2802. } else {
  2803. return { error: "not_found", query: filename, similarFiles: [] };
  2804. }
  2805. }
  2806. if (filepath.startsWith('~/')) {
  2807. filepath = homedir() + filepath.slice(1);
  2808. }
  2809. const bodyCol = options.includeBody ? `, content.doc as body` : ``;
  2810. // Build computed columns
  2811. // Note: absoluteFilepath is computed from YAML collections after query
  2812. const selectCols = `
  2813. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  2814. d.collection || '/' || d.path as display_path,
  2815. d.title,
  2816. d.hash,
  2817. d.collection,
  2818. d.modified_at,
  2819. LENGTH(content.doc) as body_length
  2820. ${bodyCol}
  2821. `;
  2822. // Try to match by virtual path first
  2823. let doc = db.prepare(`
  2824. SELECT ${selectCols}
  2825. FROM documents d
  2826. JOIN content ON content.hash = d.hash
  2827. WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
  2828. `).get(filepath) as DbDocRow | null;
  2829. // Try fuzzy match by virtual path
  2830. if (!doc) {
  2831. doc = db.prepare(`
  2832. SELECT ${selectCols}
  2833. FROM documents d
  2834. JOIN content ON content.hash = d.hash
  2835. WHERE 'qmd://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
  2836. LIMIT 1
  2837. `).get(`%${filepath}`) as DbDocRow | null;
  2838. }
  2839. // Try to match by absolute path (requires looking up collection paths from DB)
  2840. if (!doc && !filepath.startsWith('qmd://')) {
  2841. const collections = getStoreCollections(db);
  2842. for (const coll of collections) {
  2843. let relativePath: string | null = null;
  2844. // If filepath is absolute and starts with collection path, extract relative part
  2845. if (filepath.startsWith(coll.path + '/')) {
  2846. relativePath = filepath.slice(coll.path.length + 1);
  2847. }
  2848. // Otherwise treat filepath as relative to collection
  2849. else if (!filepath.startsWith('/')) {
  2850. relativePath = filepath;
  2851. }
  2852. if (relativePath) {
  2853. doc = db.prepare(`
  2854. SELECT ${selectCols}
  2855. FROM documents d
  2856. JOIN content ON content.hash = d.hash
  2857. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  2858. `).get(coll.name, relativePath) as DbDocRow | null;
  2859. if (doc) break;
  2860. }
  2861. }
  2862. }
  2863. if (!doc) {
  2864. const similar = findSimilarFiles(db, filepath, 5, 5);
  2865. return { error: "not_found", query: filename, similarFiles: similar };
  2866. }
  2867. // Get context using virtual path
  2868. const virtualPath = doc.virtual_path || `qmd://${doc.collection}/${doc.display_path}`;
  2869. const context = getContextForFile(db, virtualPath);
  2870. return {
  2871. filepath: virtualPath,
  2872. displayPath: doc.display_path,
  2873. title: doc.title,
  2874. context,
  2875. hash: doc.hash,
  2876. docid: getDocid(doc.hash),
  2877. collectionName: doc.collection,
  2878. modifiedAt: doc.modified_at,
  2879. bodyLength: doc.body_length,
  2880. ...(options.includeBody && doc.body !== undefined && { body: doc.body }),
  2881. };
  2882. }
  2883. /**
  2884. * Get the body content for a document
  2885. * Optionally slice by line range
  2886. */
  2887. export function getDocumentBody(db: Database, doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number): string | null {
  2888. const filepath = doc.filepath;
  2889. // Try to resolve document by filepath (absolute or virtual)
  2890. let row: { body: string } | null = null;
  2891. // Try virtual path first
  2892. if (filepath.startsWith('qmd://')) {
  2893. row = db.prepare(`
  2894. SELECT content.doc as body
  2895. FROM documents d
  2896. JOIN content ON content.hash = d.hash
  2897. WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
  2898. `).get(filepath) as { body: string } | null;
  2899. }
  2900. // Try absolute path by looking up in DB store_collections
  2901. if (!row) {
  2902. const collections = getStoreCollections(db);
  2903. for (const coll of collections) {
  2904. if (filepath.startsWith(coll.path + '/')) {
  2905. const relativePath = filepath.slice(coll.path.length + 1);
  2906. row = db.prepare(`
  2907. SELECT content.doc as body
  2908. FROM documents d
  2909. JOIN content ON content.hash = d.hash
  2910. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  2911. `).get(coll.name, relativePath) as { body: string } | null;
  2912. if (row) break;
  2913. }
  2914. }
  2915. }
  2916. if (!row) return null;
  2917. let body = row.body;
  2918. if (fromLine !== undefined || maxLines !== undefined) {
  2919. const lines = body.split('\n');
  2920. const start = (fromLine || 1) - 1;
  2921. const end = maxLines !== undefined ? start + maxLines : lines.length;
  2922. body = lines.slice(start, end).join('\n');
  2923. }
  2924. return body;
  2925. }
  2926. /**
  2927. * Find multiple documents by glob pattern or comma-separated list
  2928. * Returns documents without body by default (use getDocumentBody to load)
  2929. */
  2930. export function findDocuments(
  2931. db: Database,
  2932. pattern: string,
  2933. options: { includeBody?: boolean; maxBytes?: number } = {}
  2934. ): { docs: MultiGetResult[]; errors: string[] } {
  2935. const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
  2936. const errors: string[] = [];
  2937. const maxBytes = options.maxBytes ?? DEFAULT_MULTI_GET_MAX_BYTES;
  2938. const bodyCol = options.includeBody ? `, content.doc as body` : ``;
  2939. const selectCols = `
  2940. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  2941. d.collection || '/' || d.path as display_path,
  2942. d.title,
  2943. d.hash,
  2944. d.collection,
  2945. d.modified_at,
  2946. LENGTH(content.doc) as body_length
  2947. ${bodyCol}
  2948. `;
  2949. let fileRows: DbDocRow[];
  2950. if (isCommaSeparated) {
  2951. const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
  2952. fileRows = [];
  2953. for (const name of names) {
  2954. let doc = db.prepare(`
  2955. SELECT ${selectCols}
  2956. FROM documents d
  2957. JOIN content ON content.hash = d.hash
  2958. WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
  2959. `).get(name) as DbDocRow | null;
  2960. if (!doc) {
  2961. doc = db.prepare(`
  2962. SELECT ${selectCols}
  2963. FROM documents d
  2964. JOIN content ON content.hash = d.hash
  2965. WHERE 'qmd://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
  2966. LIMIT 1
  2967. `).get(`%${name}`) as DbDocRow | null;
  2968. }
  2969. if (doc) {
  2970. fileRows.push(doc);
  2971. } else {
  2972. const similar = findSimilarFiles(db, name, 5, 3);
  2973. let msg = `File not found: ${name}`;
  2974. if (similar.length > 0) {
  2975. msg += ` (did you mean: ${similar.join(', ')}?)`;
  2976. }
  2977. errors.push(msg);
  2978. }
  2979. }
  2980. } else {
  2981. // Glob pattern match
  2982. const matched = matchFilesByGlob(db, pattern);
  2983. if (matched.length === 0) {
  2984. errors.push(`No files matched pattern: ${pattern}`);
  2985. return { docs: [], errors };
  2986. }
  2987. const virtualPaths = matched.map(m => m.filepath);
  2988. const placeholders = virtualPaths.map(() => '?').join(',');
  2989. fileRows = db.prepare(`
  2990. SELECT ${selectCols}
  2991. FROM documents d
  2992. JOIN content ON content.hash = d.hash
  2993. WHERE 'qmd://' || d.collection || '/' || d.path IN (${placeholders}) AND d.active = 1
  2994. `).all(...virtualPaths) as DbDocRow[];
  2995. }
  2996. const results: MultiGetResult[] = [];
  2997. for (const row of fileRows) {
  2998. // Get context using virtual path
  2999. const virtualPath = row.virtual_path || `qmd://${row.collection}/${row.display_path}`;
  3000. const context = getContextForFile(db, virtualPath);
  3001. if (row.body_length > maxBytes) {
  3002. results.push({
  3003. doc: { filepath: virtualPath, displayPath: row.display_path },
  3004. skipped: true,
  3005. skipReason: `File too large (${Math.round(row.body_length / 1024)}KB > ${Math.round(maxBytes / 1024)}KB)`,
  3006. });
  3007. continue;
  3008. }
  3009. results.push({
  3010. doc: {
  3011. filepath: virtualPath,
  3012. displayPath: row.display_path,
  3013. title: row.title || row.display_path.split('/').pop() || row.display_path,
  3014. context,
  3015. hash: row.hash,
  3016. docid: getDocid(row.hash),
  3017. collectionName: row.collection,
  3018. modifiedAt: row.modified_at,
  3019. bodyLength: row.body_length,
  3020. ...(options.includeBody && row.body !== undefined && { body: row.body }),
  3021. },
  3022. skipped: false,
  3023. });
  3024. }
  3025. return { docs: results, errors };
  3026. }
  3027. // =============================================================================
  3028. // Status
  3029. // =============================================================================
  3030. export function getStatus(db: Database): IndexStatus {
  3031. // DB is source of truth for collections — config provides supplementary metadata
  3032. const dbCollections = db.prepare(`
  3033. SELECT
  3034. collection as name,
  3035. COUNT(*) as active_count,
  3036. MAX(modified_at) as last_doc_update
  3037. FROM documents
  3038. WHERE active = 1
  3039. GROUP BY collection
  3040. `).all() as { name: string; active_count: number; last_doc_update: string | null }[];
  3041. // Build a lookup from store_collections for path/pattern metadata
  3042. const storeCollections = getStoreCollections(db);
  3043. const configLookup = new Map(storeCollections.map(c => [c.name, { path: c.path, pattern: c.pattern }]));
  3044. const collections: CollectionInfo[] = dbCollections.map(row => {
  3045. const config = configLookup.get(row.name);
  3046. return {
  3047. name: row.name,
  3048. path: config?.path ?? null,
  3049. pattern: config?.pattern ?? null,
  3050. documents: row.active_count,
  3051. lastUpdated: row.last_doc_update || new Date().toISOString(),
  3052. };
  3053. });
  3054. // Sort by last update time (most recent first)
  3055. collections.sort((a, b) => {
  3056. if (!a.lastUpdated) return 1;
  3057. if (!b.lastUpdated) return -1;
  3058. return new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime();
  3059. });
  3060. const totalDocs = (db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 1`).get() as { c: number }).c;
  3061. const needsEmbedding = getHashesNeedingEmbedding(db);
  3062. const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  3063. return {
  3064. totalDocuments: totalDocs,
  3065. needsEmbedding,
  3066. hasVectorIndex: hasVectors,
  3067. collections,
  3068. };
  3069. }
  3070. // =============================================================================
  3071. // Snippet extraction
  3072. // =============================================================================
  3073. export type SnippetResult = {
  3074. line: number; // 1-indexed line number of best match
  3075. snippet: string; // The snippet text with diff-style header
  3076. linesBefore: number; // Lines in document before snippet
  3077. linesAfter: number; // Lines in document after snippet
  3078. snippetLines: number; // Number of lines in snippet
  3079. };
  3080. /** Weight for intent terms relative to query terms (1.0) in snippet scoring */
  3081. export const INTENT_WEIGHT_SNIPPET = 0.3;
  3082. /** Weight for intent terms relative to query terms (1.0) in chunk selection */
  3083. export const INTENT_WEIGHT_CHUNK = 0.5;
  3084. // Common stop words filtered from intent strings before tokenization.
  3085. // Seeded from finetune/reward.py KEY_TERM_STOPWORDS, extended with common
  3086. // 2-3 char function words so the length threshold can drop to >1 and let
  3087. // short domain terms (API, SQL, LLM, CPU, CDN, …) survive.
  3088. const INTENT_STOP_WORDS = new Set([
  3089. // 2-char function words
  3090. "am", "an", "as", "at", "be", "by", "do", "he", "if",
  3091. "in", "is", "it", "me", "my", "no", "of", "on", "or", "so",
  3092. "to", "up", "us", "we",
  3093. // 3-char function words
  3094. "all", "and", "any", "are", "but", "can", "did", "for", "get",
  3095. "has", "her", "him", "his", "how", "its", "let", "may", "not",
  3096. "our", "out", "the", "too", "was", "who", "why", "you",
  3097. // 4+ char common words
  3098. "also", "does", "find", "from", "have", "into", "more", "need",
  3099. "show", "some", "tell", "that", "them", "this", "want", "what",
  3100. "when", "will", "with", "your",
  3101. // Search-context noise
  3102. "about", "looking", "notes", "search", "where", "which",
  3103. ]);
  3104. /**
  3105. * Extract meaningful terms from an intent string, filtering stop words and punctuation.
  3106. * Uses Unicode-aware punctuation stripping so domain terms like "API" survive.
  3107. * Returns lowercase terms suitable for text matching.
  3108. */
  3109. export function extractIntentTerms(intent: string): string[] {
  3110. return intent.toLowerCase().split(/\s+/)
  3111. .map(t => t.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""))
  3112. .filter(t => t.length > 1 && !INTENT_STOP_WORDS.has(t));
  3113. }
  3114. export function extractSnippet(body: string, query: string, maxLen = 500, chunkPos?: number, chunkLen?: number, intent?: string): SnippetResult {
  3115. const totalLines = body.split('\n').length;
  3116. let searchBody = body;
  3117. let lineOffset = 0;
  3118. if (chunkPos && chunkPos > 0) {
  3119. // Search within the chunk region, with some padding for context
  3120. // Use provided chunkLen or fall back to max chunk size (covers variable-length chunks)
  3121. const searchLen = chunkLen || CHUNK_SIZE_CHARS;
  3122. const contextStart = Math.max(0, chunkPos - 100);
  3123. const contextEnd = Math.min(body.length, chunkPos + searchLen + 100);
  3124. searchBody = body.slice(contextStart, contextEnd);
  3125. if (contextStart > 0) {
  3126. lineOffset = body.slice(0, contextStart).split('\n').length - 1;
  3127. }
  3128. }
  3129. const lines = searchBody.split('\n');
  3130. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
  3131. const intentTerms = intent ? extractIntentTerms(intent) : [];
  3132. let bestLine = 0, bestScore = -1;
  3133. for (let i = 0; i < lines.length; i++) {
  3134. const lineLower = (lines[i] ?? "").toLowerCase();
  3135. let score = 0;
  3136. for (const term of queryTerms) {
  3137. if (lineLower.includes(term)) score += 1.0;
  3138. }
  3139. for (const term of intentTerms) {
  3140. if (lineLower.includes(term)) score += INTENT_WEIGHT_SNIPPET;
  3141. }
  3142. if (score > bestScore) {
  3143. bestScore = score;
  3144. bestLine = i;
  3145. }
  3146. }
  3147. const start = Math.max(0, bestLine - 1);
  3148. const end = Math.min(lines.length, bestLine + 3);
  3149. const snippetLines = lines.slice(start, end);
  3150. let snippetText = snippetLines.join('\n');
  3151. // If we focused on a chunk window and it produced an empty/whitespace-only snippet,
  3152. // fall back to a full-document snippet so we always show something useful.
  3153. if (chunkPos && chunkPos > 0 && snippetText.trim().length === 0) {
  3154. return extractSnippet(body, query, maxLen, undefined, undefined, intent);
  3155. }
  3156. if (snippetText.length > maxLen) snippetText = snippetText.substring(0, maxLen - 3) + "...";
  3157. const absoluteStart = lineOffset + start + 1; // 1-indexed
  3158. const snippetLineCount = snippetLines.length;
  3159. const linesBefore = absoluteStart - 1;
  3160. const linesAfter = totalLines - (absoluteStart + snippetLineCount - 1);
  3161. // Format with diff-style header: @@ -start,count @@ (linesBefore before, linesAfter after)
  3162. const header = `@@ -${absoluteStart},${snippetLineCount} @@ (${linesBefore} before, ${linesAfter} after)`;
  3163. const snippet = `${header}\n${snippetText}`;
  3164. return {
  3165. line: lineOffset + bestLine + 1,
  3166. snippet,
  3167. linesBefore,
  3168. linesAfter,
  3169. snippetLines: snippetLineCount,
  3170. };
  3171. }
  3172. // =============================================================================
  3173. // Shared helpers (used by both CLI and MCP)
  3174. // =============================================================================
  3175. /**
  3176. * Add line numbers to text content.
  3177. * Each line becomes: "{lineNum}: {content}"
  3178. */
  3179. export function addLineNumbers(text: string, startLine: number = 1): string {
  3180. const lines = text.split('\n');
  3181. return lines.map((line, i) => `${startLine + i}: ${line}`).join('\n');
  3182. }
  3183. // =============================================================================
  3184. // Shared search orchestration
  3185. //
  3186. // hybridQuery() and vectorSearchQuery() are standalone functions (not Store
  3187. // methods) because they are orchestration over primitives — same rationale as
  3188. // reciprocalRankFusion(). They take a Store as first argument so both CLI
  3189. // and MCP can share the identical pipeline.
  3190. // =============================================================================
  3191. /**
  3192. * Optional progress hooks for search orchestration.
  3193. * CLI wires these to stderr for user feedback; MCP leaves them unset.
  3194. */
  3195. export interface SearchHooks {
  3196. /** BM25 probe found strong signal — expansion will be skipped */
  3197. onStrongSignal?: (topScore: number) => void;
  3198. /** Query expansion starting */
  3199. onExpandStart?: () => void;
  3200. /** Query expansion complete. Empty array = strong signal skip. elapsedMs = time taken. */
  3201. onExpand?: (original: string, expanded: ExpandedQuery[], elapsedMs: number) => void;
  3202. /** Embedding starting (vec/hyde queries) */
  3203. onEmbedStart?: (count: number) => void;
  3204. /** Embedding complete */
  3205. onEmbedDone?: (elapsedMs: number) => void;
  3206. /** Reranking is about to start */
  3207. onRerankStart?: (chunkCount: number) => void;
  3208. /** Reranking finished */
  3209. onRerankDone?: (elapsedMs: number) => void;
  3210. }
  3211. export interface HybridQueryOptions {
  3212. collection?: string;
  3213. limit?: number; // default 10
  3214. minScore?: number; // default 0
  3215. candidateLimit?: number; // default RERANK_CANDIDATE_LIMIT
  3216. explain?: boolean; // include backend/RRF/rerank score traces
  3217. intent?: string; // domain intent hint for disambiguation
  3218. skipRerank?: boolean; // skip LLM reranking, use only RRF scores
  3219. hooks?: SearchHooks;
  3220. }
  3221. export interface HybridQueryResult {
  3222. file: string; // internal filepath (qmd://collection/path)
  3223. displayPath: string;
  3224. title: string;
  3225. body: string; // full document body (for snippet extraction)
  3226. bestChunk: string; // best chunk text
  3227. bestChunkPos: number; // char offset of best chunk in body
  3228. score: number; // blended score (full precision)
  3229. context: string | null; // user-set context
  3230. docid: string; // content hash prefix (6 chars)
  3231. explain?: HybridQueryExplain;
  3232. }
  3233. export type RankedListMeta = {
  3234. source: "fts" | "vec";
  3235. queryType: "original" | "lex" | "vec" | "hyde";
  3236. query: string;
  3237. };
  3238. /**
  3239. * Hybrid search: BM25 + vector + query expansion + RRF + chunked reranking.
  3240. *
  3241. * Pipeline:
  3242. * 1. BM25 probe → skip expansion if strong signal
  3243. * 2. expandQuery() → typed query variants (lex/vec/hyde)
  3244. * 3. Type-routed search: original→vector, lex→FTS, vec/hyde→vector
  3245. * 4. RRF fusion → slice to candidateLimit
  3246. * 5. chunkDocument() + keyword-best-chunk selection
  3247. * 6. rerank on chunks (NOT full bodies — O(tokens) trap)
  3248. * 7. Position-aware score blending (RRF rank × reranker score)
  3249. * 8. Dedup by file, filter by minScore, slice to limit
  3250. */
  3251. export async function hybridQuery(
  3252. store: Store,
  3253. query: string,
  3254. options?: HybridQueryOptions
  3255. ): Promise<HybridQueryResult[]> {
  3256. const limit = options?.limit ?? 10;
  3257. const minScore = options?.minScore ?? 0;
  3258. const candidateLimit = options?.candidateLimit ?? RERANK_CANDIDATE_LIMIT;
  3259. const collection = options?.collection;
  3260. const explain = options?.explain ?? false;
  3261. const intent = options?.intent;
  3262. const skipRerank = options?.skipRerank ?? false;
  3263. const hooks = options?.hooks;
  3264. const rankedLists: RankedResult[][] = [];
  3265. const rankedListMeta: RankedListMeta[] = [];
  3266. const docidMap = new Map<string, string>(); // filepath -> docid
  3267. const hasVectors = !!store.db.prepare(
  3268. `SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`
  3269. ).get();
  3270. // Step 1: BM25 probe — strong signal skips expensive LLM expansion
  3271. // When intent is provided, disable strong-signal bypass — the obvious BM25
  3272. // match may not be what the caller wants (e.g. "performance" with intent
  3273. // "web page load times" should NOT shortcut to a sports-performance doc).
  3274. // Pass collection directly into FTS query (filter at SQL level, not post-hoc)
  3275. const initialFts = store.searchFTS(query, 20, collection);
  3276. const topScore = initialFts[0]?.score ?? 0;
  3277. const secondScore = initialFts[1]?.score ?? 0;
  3278. const hasStrongSignal = !intent && initialFts.length > 0
  3279. && topScore >= STRONG_SIGNAL_MIN_SCORE
  3280. && (topScore - secondScore) >= STRONG_SIGNAL_MIN_GAP;
  3281. if (hasStrongSignal) hooks?.onStrongSignal?.(topScore);
  3282. // Step 2: Expand query (or skip if strong signal)
  3283. hooks?.onExpandStart?.();
  3284. const expandStart = Date.now();
  3285. const expanded = hasStrongSignal
  3286. ? []
  3287. : await store.expandQuery(query, undefined, intent);
  3288. hooks?.onExpand?.(query, expanded, Date.now() - expandStart);
  3289. // Seed with initial FTS results (avoid re-running original query FTS)
  3290. if (initialFts.length > 0) {
  3291. for (const r of initialFts) docidMap.set(r.filepath, r.docid);
  3292. rankedLists.push(initialFts.map(r => ({
  3293. file: r.filepath, displayPath: r.displayPath,
  3294. title: r.title, body: r.body || "", score: r.score,
  3295. })));
  3296. rankedListMeta.push({ source: "fts", queryType: "original", query });
  3297. }
  3298. // Step 3: Route searches by query type
  3299. //
  3300. // Strategy: run all FTS queries immediately (they're sync/instant), then
  3301. // batch-embed all vector queries in one embedBatch() call, then run
  3302. // sqlite-vec lookups with pre-computed embeddings.
  3303. // 3a: Run FTS for all lex expansions right away (no LLM needed)
  3304. for (const q of expanded) {
  3305. if (q.type === 'lex') {
  3306. const ftsResults = store.searchFTS(q.query, 20, collection);
  3307. if (ftsResults.length > 0) {
  3308. for (const r of ftsResults) docidMap.set(r.filepath, r.docid);
  3309. rankedLists.push(ftsResults.map(r => ({
  3310. file: r.filepath, displayPath: r.displayPath,
  3311. title: r.title, body: r.body || "", score: r.score,
  3312. })));
  3313. rankedListMeta.push({ source: "fts", queryType: "lex", query: q.query });
  3314. }
  3315. }
  3316. }
  3317. // 3b: Collect all texts that need vector search (original query + vec/hyde expansions)
  3318. if (hasVectors) {
  3319. const vecQueries: { text: string; queryType: "original" | "vec" | "hyde" }[] = [
  3320. { text: query, queryType: "original" },
  3321. ];
  3322. for (const q of expanded) {
  3323. if (q.type === 'vec' || q.type === 'hyde') {
  3324. vecQueries.push({ text: q.query, queryType: q.type });
  3325. }
  3326. }
  3327. // Batch embed all vector queries in a single call
  3328. const llm = getLlm(store);
  3329. const textsToEmbed = vecQueries.map(q => formatQueryForEmbedding(q.text));
  3330. hooks?.onEmbedStart?.(textsToEmbed.length);
  3331. const embedStart = Date.now();
  3332. const embeddings = await llm.embedBatch(textsToEmbed);
  3333. hooks?.onEmbedDone?.(Date.now() - embedStart);
  3334. // Run sqlite-vec lookups with pre-computed embeddings
  3335. for (let i = 0; i < vecQueries.length; i++) {
  3336. const embedding = embeddings[i]?.embedding;
  3337. if (!embedding) continue;
  3338. const vecResults = await store.searchVec(
  3339. vecQueries[i]!.text, DEFAULT_EMBED_MODEL, 20, collection,
  3340. undefined, embedding
  3341. );
  3342. if (vecResults.length > 0) {
  3343. for (const r of vecResults) docidMap.set(r.filepath, r.docid);
  3344. rankedLists.push(vecResults.map(r => ({
  3345. file: r.filepath, displayPath: r.displayPath,
  3346. title: r.title, body: r.body || "", score: r.score,
  3347. })));
  3348. rankedListMeta.push({
  3349. source: "vec",
  3350. queryType: vecQueries[i]!.queryType,
  3351. query: vecQueries[i]!.text,
  3352. });
  3353. }
  3354. }
  3355. }
  3356. // Step 4: RRF fusion — first 2 lists (original FTS + first vec) get 2x weight
  3357. const weights = rankedLists.map((_, i) => i < 2 ? 2.0 : 1.0);
  3358. const fused = reciprocalRankFusion(rankedLists, weights);
  3359. const rrfTraceByFile = explain ? buildRrfTrace(rankedLists, weights, rankedListMeta) : null;
  3360. const candidates = fused.slice(0, candidateLimit);
  3361. if (candidates.length === 0) return [];
  3362. // Step 5: Chunk documents, pick best chunk per doc for reranking.
  3363. // Reranking full bodies is O(tokens) — the critical perf lesson that motivated this refactor.
  3364. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 2);
  3365. const intentTerms = intent ? extractIntentTerms(intent) : [];
  3366. const docChunkMap = new Map<string, { chunks: { text: string; pos: number }[]; bestIdx: number }>();
  3367. for (const cand of candidates) {
  3368. const chunks = chunkDocument(cand.body);
  3369. if (chunks.length === 0) continue;
  3370. // Pick chunk with most keyword overlap (fallback: first chunk)
  3371. // Intent terms contribute at INTENT_WEIGHT_CHUNK (0.5) relative to query terms (1.0)
  3372. let bestIdx = 0;
  3373. let bestScore = -1;
  3374. for (let i = 0; i < chunks.length; i++) {
  3375. const chunkLower = chunks[i]!.text.toLowerCase();
  3376. let score = queryTerms.reduce((acc, term) => acc + (chunkLower.includes(term) ? 1 : 0), 0);
  3377. for (const term of intentTerms) {
  3378. if (chunkLower.includes(term)) score += INTENT_WEIGHT_CHUNK;
  3379. }
  3380. if (score > bestScore) { bestScore = score; bestIdx = i; }
  3381. }
  3382. docChunkMap.set(cand.file, { chunks, bestIdx });
  3383. }
  3384. if (skipRerank) {
  3385. // Skip LLM reranking — return candidates scored by RRF only
  3386. const seenFiles = new Set<string>();
  3387. return candidates
  3388. .map((cand, i) => {
  3389. const chunkInfo = docChunkMap.get(cand.file);
  3390. const bestIdx = chunkInfo?.bestIdx ?? 0;
  3391. const bestChunk = chunkInfo?.chunks[bestIdx]?.text || cand.body || "";
  3392. const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
  3393. const rrfRank = i + 1;
  3394. const rrfScore = 1 / rrfRank;
  3395. const trace = rrfTraceByFile?.get(cand.file);
  3396. const explainData: HybridQueryExplain | undefined = explain ? {
  3397. ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
  3398. vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
  3399. rrf: {
  3400. rank: rrfRank,
  3401. positionScore: rrfScore,
  3402. weight: 1.0,
  3403. baseScore: trace?.baseScore ?? 0,
  3404. topRankBonus: trace?.topRankBonus ?? 0,
  3405. totalScore: trace?.totalScore ?? 0,
  3406. contributions: trace?.contributions ?? [],
  3407. },
  3408. rerankScore: 0,
  3409. blendedScore: rrfScore,
  3410. } : undefined;
  3411. return {
  3412. file: cand.file,
  3413. displayPath: cand.displayPath,
  3414. title: cand.title,
  3415. body: cand.body,
  3416. bestChunk,
  3417. bestChunkPos,
  3418. score: rrfScore,
  3419. context: store.getContextForFile(cand.file),
  3420. docid: docidMap.get(cand.file) || "",
  3421. ...(explainData ? { explain: explainData } : {}),
  3422. };
  3423. })
  3424. .filter(r => {
  3425. if (seenFiles.has(r.file)) return false;
  3426. seenFiles.add(r.file);
  3427. return true;
  3428. })
  3429. .filter(r => r.score >= minScore)
  3430. .slice(0, limit);
  3431. }
  3432. // Step 6: Rerank chunks (NOT full bodies)
  3433. const chunksToRerank: { file: string; text: string }[] = [];
  3434. for (const cand of candidates) {
  3435. const chunkInfo = docChunkMap.get(cand.file);
  3436. if (chunkInfo) {
  3437. chunksToRerank.push({ file: cand.file, text: chunkInfo.chunks[chunkInfo.bestIdx]!.text });
  3438. }
  3439. }
  3440. hooks?.onRerankStart?.(chunksToRerank.length);
  3441. const rerankStart = Date.now();
  3442. const reranked = await store.rerank(query, chunksToRerank, undefined, intent);
  3443. hooks?.onRerankDone?.(Date.now() - rerankStart);
  3444. // Step 7: Blend RRF position score with reranker score
  3445. // Position-aware weights: top retrieval results get more protection from reranker disagreement
  3446. const candidateMap = new Map(candidates.map(c => [c.file, {
  3447. displayPath: c.displayPath, title: c.title, body: c.body,
  3448. }]));
  3449. const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1]));
  3450. const blended = reranked.map(r => {
  3451. const rrfRank = rrfRankMap.get(r.file) || candidateLimit;
  3452. let rrfWeight: number;
  3453. if (rrfRank <= 3) rrfWeight = 0.75;
  3454. else if (rrfRank <= 10) rrfWeight = 0.60;
  3455. else rrfWeight = 0.40;
  3456. const rrfScore = 1 / rrfRank;
  3457. const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
  3458. const candidate = candidateMap.get(r.file);
  3459. const chunkInfo = docChunkMap.get(r.file);
  3460. const bestIdx = chunkInfo?.bestIdx ?? 0;
  3461. const bestChunk = chunkInfo?.chunks[bestIdx]?.text || candidate?.body || "";
  3462. const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
  3463. const trace = rrfTraceByFile?.get(r.file);
  3464. const explainData: HybridQueryExplain | undefined = explain ? {
  3465. ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
  3466. vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
  3467. rrf: {
  3468. rank: rrfRank,
  3469. positionScore: rrfScore,
  3470. weight: rrfWeight,
  3471. baseScore: trace?.baseScore ?? 0,
  3472. topRankBonus: trace?.topRankBonus ?? 0,
  3473. totalScore: trace?.totalScore ?? 0,
  3474. contributions: trace?.contributions ?? [],
  3475. },
  3476. rerankScore: r.score,
  3477. blendedScore,
  3478. } : undefined;
  3479. return {
  3480. file: r.file,
  3481. displayPath: candidate?.displayPath || "",
  3482. title: candidate?.title || "",
  3483. body: candidate?.body || "",
  3484. bestChunk,
  3485. bestChunkPos,
  3486. score: blendedScore,
  3487. context: store.getContextForFile(r.file),
  3488. docid: docidMap.get(r.file) || "",
  3489. ...(explainData ? { explain: explainData } : {}),
  3490. };
  3491. }).sort((a, b) => b.score - a.score);
  3492. // Step 8: Dedup by file (safety net — prevents duplicate output)
  3493. const seenFiles = new Set<string>();
  3494. return blended
  3495. .filter(r => {
  3496. if (seenFiles.has(r.file)) return false;
  3497. seenFiles.add(r.file);
  3498. return true;
  3499. })
  3500. .filter(r => r.score >= minScore)
  3501. .slice(0, limit);
  3502. }
  3503. export interface VectorSearchOptions {
  3504. collection?: string;
  3505. limit?: number; // default 10
  3506. minScore?: number; // default 0.3
  3507. intent?: string; // domain intent hint for disambiguation
  3508. hooks?: Pick<SearchHooks, 'onExpand'>;
  3509. }
  3510. export interface VectorSearchResult {
  3511. file: string;
  3512. displayPath: string;
  3513. title: string;
  3514. body: string;
  3515. score: number;
  3516. context: string | null;
  3517. docid: string;
  3518. }
  3519. /**
  3520. * Vector-only semantic search with query expansion.
  3521. *
  3522. * Pipeline:
  3523. * 1. expandQuery() → typed variants, filter to vec/hyde only (lex irrelevant here)
  3524. * 2. searchVec() for original + vec/hyde variants (sequential — node-llama-cpp embed limitation)
  3525. * 3. Dedup by filepath (keep max score)
  3526. * 4. Sort by score descending, filter by minScore, slice to limit
  3527. */
  3528. export async function vectorSearchQuery(
  3529. store: Store,
  3530. query: string,
  3531. options?: VectorSearchOptions
  3532. ): Promise<VectorSearchResult[]> {
  3533. const limit = options?.limit ?? 10;
  3534. const minScore = options?.minScore ?? 0.3;
  3535. const collection = options?.collection;
  3536. const intent = options?.intent;
  3537. const hasVectors = !!store.db.prepare(
  3538. `SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`
  3539. ).get();
  3540. if (!hasVectors) return [];
  3541. // Expand query — filter to vec/hyde only (lex queries target FTS, not vector)
  3542. const expandStart = Date.now();
  3543. const allExpanded = await store.expandQuery(query, undefined, intent);
  3544. const vecExpanded = allExpanded.filter(q => q.type !== 'lex');
  3545. options?.hooks?.onExpand?.(query, vecExpanded, Date.now() - expandStart);
  3546. // Run original + vec/hyde expanded through vector, sequentially — concurrent embed() hangs
  3547. const queryTexts = [query, ...vecExpanded.map(q => q.query)];
  3548. const allResults = new Map<string, VectorSearchResult>();
  3549. for (const q of queryTexts) {
  3550. const vecResults = await store.searchVec(q, DEFAULT_EMBED_MODEL, limit, collection);
  3551. for (const r of vecResults) {
  3552. const existing = allResults.get(r.filepath);
  3553. if (!existing || r.score > existing.score) {
  3554. allResults.set(r.filepath, {
  3555. file: r.filepath,
  3556. displayPath: r.displayPath,
  3557. title: r.title,
  3558. body: r.body || "",
  3559. score: r.score,
  3560. context: store.getContextForFile(r.filepath),
  3561. docid: r.docid,
  3562. });
  3563. }
  3564. }
  3565. }
  3566. return Array.from(allResults.values())
  3567. .sort((a, b) => b.score - a.score)
  3568. .filter(r => r.score >= minScore)
  3569. .slice(0, limit);
  3570. }
  3571. // =============================================================================
  3572. // Structured search — pre-expanded queries from LLM
  3573. // =============================================================================
  3574. /**
  3575. * A single sub-search in a structured search request.
  3576. * Matches the format used in QMD training data.
  3577. */
  3578. export interface StructuredSearchOptions {
  3579. collections?: string[]; // Filter to specific collections (OR match)
  3580. limit?: number; // default 10
  3581. minScore?: number; // default 0
  3582. candidateLimit?: number; // default RERANK_CANDIDATE_LIMIT
  3583. explain?: boolean; // include backend/RRF/rerank score traces
  3584. /** Domain intent hint for disambiguation — steers reranking and chunk selection */
  3585. intent?: string;
  3586. /** Skip LLM reranking, use only RRF scores */
  3587. skipRerank?: boolean;
  3588. hooks?: SearchHooks;
  3589. }
  3590. /**
  3591. * Structured search: execute pre-expanded queries without LLM query expansion.
  3592. *
  3593. * Designed for LLM callers (MCP/HTTP) that generate their own query expansions.
  3594. * Skips the internal expandQuery() step — goes directly to:
  3595. *
  3596. * Pipeline:
  3597. * 1. Route searches: lex→FTS, vec/hyde→vector (batch embed)
  3598. * 2. RRF fusion across all result lists
  3599. * 3. Chunk documents + keyword-best-chunk selection
  3600. * 4. Rerank on chunks
  3601. * 5. Position-aware score blending
  3602. * 6. Dedup, filter, slice
  3603. *
  3604. * This is the recommended endpoint for capable LLMs — they can generate
  3605. * better query variations than our small local model, especially for
  3606. * domain-specific or nuanced queries.
  3607. */
  3608. export async function structuredSearch(
  3609. store: Store,
  3610. searches: ExpandedQuery[],
  3611. options?: StructuredSearchOptions
  3612. ): Promise<HybridQueryResult[]> {
  3613. const limit = options?.limit ?? 10;
  3614. const minScore = options?.minScore ?? 0;
  3615. const candidateLimit = options?.candidateLimit ?? RERANK_CANDIDATE_LIMIT;
  3616. const explain = options?.explain ?? false;
  3617. const intent = options?.intent;
  3618. const skipRerank = options?.skipRerank ?? false;
  3619. const hooks = options?.hooks;
  3620. const collections = options?.collections;
  3621. if (searches.length === 0) return [];
  3622. // Validate queries before executing
  3623. for (const search of searches) {
  3624. const location = search.line ? `Line ${search.line}` : 'Structured search';
  3625. if (/[\r\n]/.test(search.query)) {
  3626. throw new Error(`${location} (${search.type}): queries must be single-line. Remove newline characters.`);
  3627. }
  3628. if (search.type === 'lex') {
  3629. const error = validateLexQuery(search.query);
  3630. if (error) {
  3631. throw new Error(`${location} (lex): ${error}`);
  3632. }
  3633. } else if (search.type === 'vec' || search.type === 'hyde') {
  3634. const error = validateSemanticQuery(search.query);
  3635. if (error) {
  3636. throw new Error(`${location} (${search.type}): ${error}`);
  3637. }
  3638. }
  3639. }
  3640. const rankedLists: RankedResult[][] = [];
  3641. const rankedListMeta: RankedListMeta[] = [];
  3642. const docidMap = new Map<string, string>(); // filepath -> docid
  3643. const hasVectors = !!store.db.prepare(
  3644. `SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`
  3645. ).get();
  3646. // Helper to run search across collections (or all if undefined)
  3647. const collectionList = collections ?? [undefined]; // undefined = all collections
  3648. // Step 1: Run FTS for all lex searches (sync, instant)
  3649. for (const search of searches) {
  3650. if (search.type === 'lex') {
  3651. for (const coll of collectionList) {
  3652. const ftsResults = store.searchFTS(search.query, 20, coll);
  3653. if (ftsResults.length > 0) {
  3654. for (const r of ftsResults) docidMap.set(r.filepath, r.docid);
  3655. rankedLists.push(ftsResults.map(r => ({
  3656. file: r.filepath, displayPath: r.displayPath,
  3657. title: r.title, body: r.body || "", score: r.score,
  3658. })));
  3659. rankedListMeta.push({
  3660. source: "fts",
  3661. queryType: "lex",
  3662. query: search.query,
  3663. });
  3664. }
  3665. }
  3666. }
  3667. }
  3668. // Step 2: Batch embed and run vector searches for vec/hyde
  3669. if (hasVectors) {
  3670. const vecSearches = searches.filter(
  3671. (s): s is ExpandedQuery & { type: 'vec' | 'hyde' } =>
  3672. s.type === 'vec' || s.type === 'hyde'
  3673. );
  3674. if (vecSearches.length > 0) {
  3675. const llm = getLlm(store);
  3676. const textsToEmbed = vecSearches.map(s => formatQueryForEmbedding(s.query));
  3677. hooks?.onEmbedStart?.(textsToEmbed.length);
  3678. const embedStart = Date.now();
  3679. const embeddings = await llm.embedBatch(textsToEmbed);
  3680. hooks?.onEmbedDone?.(Date.now() - embedStart);
  3681. for (let i = 0; i < vecSearches.length; i++) {
  3682. const embedding = embeddings[i]?.embedding;
  3683. if (!embedding) continue;
  3684. for (const coll of collectionList) {
  3685. const vecResults = await store.searchVec(
  3686. vecSearches[i]!.query, DEFAULT_EMBED_MODEL, 20, coll,
  3687. undefined, embedding
  3688. );
  3689. if (vecResults.length > 0) {
  3690. for (const r of vecResults) docidMap.set(r.filepath, r.docid);
  3691. rankedLists.push(vecResults.map(r => ({
  3692. file: r.filepath, displayPath: r.displayPath,
  3693. title: r.title, body: r.body || "", score: r.score,
  3694. })));
  3695. rankedListMeta.push({
  3696. source: "vec",
  3697. queryType: vecSearches[i]!.type,
  3698. query: vecSearches[i]!.query,
  3699. });
  3700. }
  3701. }
  3702. }
  3703. }
  3704. }
  3705. if (rankedLists.length === 0) return [];
  3706. // Step 3: RRF fusion — first list gets 2x weight (assume caller ordered by importance)
  3707. const weights = rankedLists.map((_, i) => i === 0 ? 2.0 : 1.0);
  3708. const fused = reciprocalRankFusion(rankedLists, weights);
  3709. const rrfTraceByFile = explain ? buildRrfTrace(rankedLists, weights, rankedListMeta) : null;
  3710. const candidates = fused.slice(0, candidateLimit);
  3711. if (candidates.length === 0) return [];
  3712. hooks?.onExpand?.("", [], 0); // Signal no expansion (pre-expanded)
  3713. // Step 4: Chunk documents, pick best chunk per doc for reranking
  3714. // Use first lex query as the "query" for keyword matching, or first vec if no lex
  3715. const primaryQuery = searches.find(s => s.type === 'lex')?.query
  3716. || searches.find(s => s.type === 'vec')?.query
  3717. || searches[0]?.query || "";
  3718. const queryTerms = primaryQuery.toLowerCase().split(/\s+/).filter(t => t.length > 2);
  3719. const intentTerms = intent ? extractIntentTerms(intent) : [];
  3720. const docChunkMap = new Map<string, { chunks: { text: string; pos: number }[]; bestIdx: number }>();
  3721. for (const cand of candidates) {
  3722. const chunks = chunkDocument(cand.body);
  3723. if (chunks.length === 0) continue;
  3724. // Pick chunk with most keyword overlap
  3725. // Intent terms contribute at INTENT_WEIGHT_CHUNK (0.5) relative to query terms (1.0)
  3726. let bestIdx = 0;
  3727. let bestScore = -1;
  3728. for (let i = 0; i < chunks.length; i++) {
  3729. const chunkLower = chunks[i]!.text.toLowerCase();
  3730. let score = queryTerms.reduce((acc, term) => acc + (chunkLower.includes(term) ? 1 : 0), 0);
  3731. for (const term of intentTerms) {
  3732. if (chunkLower.includes(term)) score += INTENT_WEIGHT_CHUNK;
  3733. }
  3734. if (score > bestScore) { bestScore = score; bestIdx = i; }
  3735. }
  3736. docChunkMap.set(cand.file, { chunks, bestIdx });
  3737. }
  3738. if (skipRerank) {
  3739. // Skip LLM reranking — return candidates scored by RRF only
  3740. const seenFiles = new Set<string>();
  3741. return candidates
  3742. .map((cand, i) => {
  3743. const chunkInfo = docChunkMap.get(cand.file);
  3744. const bestIdx = chunkInfo?.bestIdx ?? 0;
  3745. const bestChunk = chunkInfo?.chunks[bestIdx]?.text || cand.body || "";
  3746. const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
  3747. const rrfRank = i + 1;
  3748. const rrfScore = 1 / rrfRank;
  3749. const trace = rrfTraceByFile?.get(cand.file);
  3750. const explainData: HybridQueryExplain | undefined = explain ? {
  3751. ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
  3752. vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
  3753. rrf: {
  3754. rank: rrfRank,
  3755. positionScore: rrfScore,
  3756. weight: 1.0,
  3757. baseScore: trace?.baseScore ?? 0,
  3758. topRankBonus: trace?.topRankBonus ?? 0,
  3759. totalScore: trace?.totalScore ?? 0,
  3760. contributions: trace?.contributions ?? [],
  3761. },
  3762. rerankScore: 0,
  3763. blendedScore: rrfScore,
  3764. } : undefined;
  3765. return {
  3766. file: cand.file,
  3767. displayPath: cand.displayPath,
  3768. title: cand.title,
  3769. body: cand.body,
  3770. bestChunk,
  3771. bestChunkPos,
  3772. score: rrfScore,
  3773. context: store.getContextForFile(cand.file),
  3774. docid: docidMap.get(cand.file) || "",
  3775. ...(explainData ? { explain: explainData } : {}),
  3776. };
  3777. })
  3778. .filter(r => {
  3779. if (seenFiles.has(r.file)) return false;
  3780. seenFiles.add(r.file);
  3781. return true;
  3782. })
  3783. .filter(r => r.score >= minScore)
  3784. .slice(0, limit);
  3785. }
  3786. // Step 5: Rerank chunks
  3787. const chunksToRerank: { file: string; text: string }[] = [];
  3788. for (const cand of candidates) {
  3789. const chunkInfo = docChunkMap.get(cand.file);
  3790. if (chunkInfo) {
  3791. chunksToRerank.push({ file: cand.file, text: chunkInfo.chunks[chunkInfo.bestIdx]!.text });
  3792. }
  3793. }
  3794. hooks?.onRerankStart?.(chunksToRerank.length);
  3795. const rerankStart2 = Date.now();
  3796. const reranked = await store.rerank(primaryQuery, chunksToRerank, undefined, intent);
  3797. hooks?.onRerankDone?.(Date.now() - rerankStart2);
  3798. // Step 6: Blend RRF position score with reranker score
  3799. const candidateMap = new Map(candidates.map(c => [c.file, {
  3800. displayPath: c.displayPath, title: c.title, body: c.body,
  3801. }]));
  3802. const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1]));
  3803. const blended = reranked.map(r => {
  3804. const rrfRank = rrfRankMap.get(r.file) || candidateLimit;
  3805. let rrfWeight: number;
  3806. if (rrfRank <= 3) rrfWeight = 0.75;
  3807. else if (rrfRank <= 10) rrfWeight = 0.60;
  3808. else rrfWeight = 0.40;
  3809. const rrfScore = 1 / rrfRank;
  3810. const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
  3811. const candidate = candidateMap.get(r.file);
  3812. const chunkInfo = docChunkMap.get(r.file);
  3813. const bestIdx = chunkInfo?.bestIdx ?? 0;
  3814. const bestChunk = chunkInfo?.chunks[bestIdx]?.text || candidate?.body || "";
  3815. const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
  3816. const trace = rrfTraceByFile?.get(r.file);
  3817. const explainData: HybridQueryExplain | undefined = explain ? {
  3818. ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
  3819. vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
  3820. rrf: {
  3821. rank: rrfRank,
  3822. positionScore: rrfScore,
  3823. weight: rrfWeight,
  3824. baseScore: trace?.baseScore ?? 0,
  3825. topRankBonus: trace?.topRankBonus ?? 0,
  3826. totalScore: trace?.totalScore ?? 0,
  3827. contributions: trace?.contributions ?? [],
  3828. },
  3829. rerankScore: r.score,
  3830. blendedScore,
  3831. } : undefined;
  3832. return {
  3833. file: r.file,
  3834. displayPath: candidate?.displayPath || "",
  3835. title: candidate?.title || "",
  3836. body: candidate?.body || "",
  3837. bestChunk,
  3838. bestChunkPos,
  3839. score: blendedScore,
  3840. context: store.getContextForFile(r.file),
  3841. docid: docidMap.get(r.file) || "",
  3842. ...(explainData ? { explain: explainData } : {}),
  3843. };
  3844. }).sort((a, b) => b.score - a.score);
  3845. // Step 7: Dedup by file
  3846. const seenFiles = new Set<string>();
  3847. return blended
  3848. .filter(r => {
  3849. if (seenFiles.has(r.file)) return false;
  3850. seenFiles.add(r.file);
  3851. return true;
  3852. })
  3853. .filter(r => r.score >= minScore)
  3854. .slice(0, limit);
  3855. }