store.js 169 KB

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