store.js 145 KB

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