store.ts 122 KB

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