store.ts 158 KB

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