store.ts 160 KB

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