store.ts 151 KB

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