store.js 167 KB

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