store.js 160 KB

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