store.test.ts 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434
  1. /**
  2. * store.test.ts - Comprehensive unit tests for the QMD store module
  3. *
  4. * Run with: bun test store.test.ts
  5. *
  6. * LLM operations use LlamaCpp with local GGUF models (node-llama-cpp).
  7. */
  8. import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from "vitest";
  9. import { openDatabase, loadSqliteVec } from "../src/db.js";
  10. import type { Database } from "../src/db.js";
  11. import { unlink, mkdtemp, rmdir, writeFile } from "node:fs/promises";
  12. import { tmpdir } from "node:os";
  13. import { join } from "node:path";
  14. import YAML from "yaml";
  15. import * as llmModule from "../src/llm.js";
  16. import { disposeDefaultLlamaCpp, setDefaultLlamaCpp } from "../src/llm.js";
  17. import {
  18. createStore,
  19. verifySqliteVecLoaded,
  20. getDefaultDbPath,
  21. homedir,
  22. resolve,
  23. getPwd,
  24. getRealPath,
  25. hashContent,
  26. extractTitle,
  27. formatQueryForEmbedding,
  28. formatDocForEmbedding,
  29. chunkDocument,
  30. chunkDocumentByTokens,
  31. chunkDocumentAsync,
  32. chunkDocumentWithBreakPoints,
  33. mergeBreakPoints,
  34. scanBreakPoints,
  35. findCodeFences,
  36. isInsideCodeFence,
  37. findBestCutoff,
  38. type BreakPoint,
  39. type CodeFenceRegion,
  40. reciprocalRankFusion,
  41. extractSnippet,
  42. getCacheKey,
  43. handelize,
  44. normalizeVirtualPath,
  45. isVirtualPath,
  46. parseVirtualPath,
  47. normalizeDocid,
  48. isDocid,
  49. syncConfigToDb,
  50. STRONG_SIGNAL_MIN_SCORE,
  51. STRONG_SIGNAL_MIN_GAP,
  52. generateEmbeddings,
  53. type Store,
  54. type DocumentResult,
  55. type SearchResult,
  56. type RankedResult,
  57. } from "../src/store.js";
  58. import type { CollectionConfig } from "../src/collections.js";
  59. // =============================================================================
  60. // LlamaCpp Setup
  61. // =============================================================================
  62. // Note: LlamaCpp uses node-llama-cpp for local GGUF model inference.
  63. // No HTTP mocking needed - tests use real LlamaCpp calls for integration tests.
  64. // =============================================================================
  65. // Test Utilities
  66. // =============================================================================
  67. let testDir: string;
  68. let testDbPath: string;
  69. let testConfigDir: string;
  70. let currentTestStore: Store | null = null;
  71. async function createTestStore(): Promise<Store> {
  72. testDbPath = join(testDir, `test-${Date.now()}-${Math.random().toString(36).slice(2)}.sqlite`);
  73. // Set up test config directory
  74. const configPrefix = join(testDir, `config-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  75. testConfigDir = await mkdtemp(configPrefix);
  76. // Set environment variable to use test config
  77. process.env.QMD_CONFIG_DIR = testConfigDir;
  78. // Create empty YAML config
  79. const emptyConfig: CollectionConfig = { collections: {} };
  80. await writeFile(
  81. join(testConfigDir, "index.yml"),
  82. YAML.stringify(emptyConfig)
  83. );
  84. const store = createStore(testDbPath);
  85. currentTestStore = store;
  86. return store;
  87. }
  88. async function cleanupTestDb(store: Store): Promise<void> {
  89. currentTestStore = null;
  90. store.close();
  91. try {
  92. await unlink(store.dbPath);
  93. } catch {
  94. // Ignore if file doesn't exist
  95. }
  96. // Clean up test config directory
  97. try {
  98. const { readdir, unlink: unlinkFile, rmdir: rmdirAsync } = await import("node:fs/promises");
  99. const files = await readdir(testConfigDir);
  100. for (const file of files) {
  101. await unlinkFile(join(testConfigDir, file));
  102. }
  103. await rmdirAsync(testConfigDir);
  104. } catch {
  105. // Ignore cleanup errors
  106. }
  107. // Clear environment variable
  108. delete process.env.QMD_CONFIG_DIR;
  109. }
  110. // Helper to insert a test document directly into the database
  111. async function insertTestDocument(
  112. db: Database,
  113. collectionName: string,
  114. opts: {
  115. name?: string;
  116. title?: string;
  117. hash?: string;
  118. displayPath?: string;
  119. filepath?: string;
  120. body?: string;
  121. active?: number;
  122. }
  123. ): Promise<number> {
  124. const now = new Date().toISOString();
  125. const name = opts.name || "test-doc";
  126. const title = opts.title || "Test Document";
  127. // Use displayPath if provided, otherwise filepath's basename, otherwise default
  128. let path: string;
  129. if (opts.displayPath) {
  130. path = opts.displayPath;
  131. } else if (opts.filepath) {
  132. // Extract relative path from filepath by removing collection path
  133. // For tests, assume filepath is either relative or we want the whole path as the document path
  134. path = opts.filepath.startsWith('/') ? opts.filepath : opts.filepath;
  135. } else {
  136. path = `test/${name}.md`;
  137. }
  138. const body = opts.body || "# Test Document\n\nThis is test content.";
  139. const active = opts.active ?? 1;
  140. // Generate hash from body if not provided
  141. const hash = opts.hash || await hashContent(body);
  142. // Insert content (with OR IGNORE for deduplication)
  143. db.prepare(`
  144. INSERT OR IGNORE INTO content (hash, doc, created_at)
  145. VALUES (?, ?, ?)
  146. `).run(hash, body, now);
  147. // Insert document
  148. const result = db.prepare(`
  149. INSERT INTO documents (collection, path, title, hash, created_at, modified_at, active)
  150. VALUES (?, ?, ?, ?, ?, ?, ?)
  151. `).run(collectionName, path, title, hash, now, now, active);
  152. return Number(result.lastInsertRowid);
  153. }
  154. /** Sync YAML config file to SQLite store_collections in the current test store */
  155. async function syncTestConfig(): Promise<void> {
  156. if (!currentTestStore) return;
  157. const configPath = join(testConfigDir, "index.yml");
  158. const { readFile } = await import("node:fs/promises");
  159. const content = await readFile(configPath, "utf-8");
  160. const config = YAML.parse(content) as CollectionConfig;
  161. // Clear config hash to force re-sync
  162. currentTestStore.db.prepare(`DELETE FROM store_config WHERE key = 'config_hash'`).run();
  163. syncConfigToDb(currentTestStore.db, config);
  164. }
  165. // Helper to create a test collection in YAML config
  166. async function createTestCollection(
  167. options: { pwd?: string; glob?: string; name?: string } = {}
  168. ): Promise<string> {
  169. const pwd = options.pwd || "/test/collection";
  170. const glob = options.glob || "**/*.md";
  171. const name = options.name || pwd.split('/').filter(Boolean).pop() || 'test';
  172. // Read current config
  173. const configPath = join(testConfigDir, "index.yml");
  174. const { readFile } = await import("node:fs/promises");
  175. const content = await readFile(configPath, "utf-8");
  176. const config = YAML.parse(content) as CollectionConfig;
  177. // Add collection
  178. config.collections[name] = {
  179. path: pwd,
  180. pattern: glob,
  181. };
  182. // Write back
  183. await writeFile(configPath, YAML.stringify(config));
  184. await syncTestConfig();
  185. return name;
  186. }
  187. // Helper to add path context in YAML config
  188. async function addPathContext(collectionName: string, pathPrefix: string, contextText: string): Promise<void> {
  189. // Read current config
  190. const configPath = join(testConfigDir, "index.yml");
  191. const { readFile } = await import("node:fs/promises");
  192. const content = await readFile(configPath, "utf-8");
  193. const config = YAML.parse(content) as CollectionConfig;
  194. // Add context to collection
  195. if (!config.collections[collectionName]) {
  196. throw new Error(`Collection ${collectionName} not found`);
  197. }
  198. if (!config.collections[collectionName].context) {
  199. config.collections[collectionName].context = {};
  200. }
  201. config.collections[collectionName].context![pathPrefix] = contextText;
  202. // Write back
  203. await writeFile(configPath, YAML.stringify(config));
  204. await syncTestConfig();
  205. }
  206. // Helper to add global context in YAML config
  207. async function addGlobalContext(contextText: string): Promise<void> {
  208. const configPath = join(testConfigDir, "index.yml");
  209. const { readFile } = await import("node:fs/promises");
  210. const content = await readFile(configPath, "utf-8");
  211. const config = YAML.parse(content) as CollectionConfig;
  212. config.global_context = contextText;
  213. await writeFile(configPath, YAML.stringify(config));
  214. await syncTestConfig();
  215. }
  216. // =============================================================================
  217. // Test Setup
  218. // =============================================================================
  219. beforeAll(async () => {
  220. testDir = await mkdtemp(join(tmpdir(), "qmd-test-"));
  221. });
  222. afterAll(async () => {
  223. // Ensure native resources are released to avoid ggml-metal asserts on process exit.
  224. await disposeDefaultLlamaCpp();
  225. try {
  226. // Clean up test directory
  227. const { readdir, unlink } = await import("node:fs/promises");
  228. const files = await readdir(testDir);
  229. for (const file of files) {
  230. await unlink(join(testDir, file));
  231. }
  232. await rmdir(testDir);
  233. } catch {
  234. // Ignore cleanup errors
  235. }
  236. });
  237. // =============================================================================
  238. // Path Utilities Tests
  239. // =============================================================================
  240. describe("Path Utilities", () => {
  241. test("homedir returns HOME environment variable", () => {
  242. const result = homedir();
  243. expect(result).toBe(process.env.HOME || "/tmp");
  244. });
  245. test("resolve handles absolute paths", () => {
  246. expect(resolve("/foo/bar")).toBe("/foo/bar");
  247. expect(resolve("/foo", "/bar")).toBe("/bar");
  248. });
  249. test("resolve handles relative paths", () => {
  250. const pwd = process.env.PWD || process.cwd();
  251. expect(resolve("foo")).toBe(`${pwd}/foo`);
  252. expect(resolve("foo", "bar")).toBe(`${pwd}/foo/bar`);
  253. });
  254. test("resolve normalizes . and ..", () => {
  255. expect(resolve("/foo/bar/./baz")).toBe("/foo/bar/baz");
  256. expect(resolve("/foo/bar/../baz")).toBe("/foo/baz");
  257. expect(resolve("/foo/bar/../../baz")).toBe("/baz");
  258. });
  259. test("getDefaultDbPath throws in test mode without INDEX_PATH", () => {
  260. // In test mode, getDefaultDbPath should throw to prevent accidental writes to global index
  261. // This is intentional safety behavior
  262. const originalIndexPath = process.env.INDEX_PATH;
  263. delete process.env.INDEX_PATH;
  264. expect(() => getDefaultDbPath()).toThrow("Database path not set");
  265. // Restore
  266. if (originalIndexPath) process.env.INDEX_PATH = originalIndexPath;
  267. });
  268. test("getDefaultDbPath uses INDEX_PATH when set", () => {
  269. const originalIndexPath = process.env.INDEX_PATH;
  270. process.env.INDEX_PATH = "/tmp/test-index.sqlite";
  271. expect(getDefaultDbPath()).toBe("/tmp/test-index.sqlite");
  272. expect(getDefaultDbPath("custom")).toBe("/tmp/test-index.sqlite"); // INDEX_PATH overrides name
  273. // Restore
  274. if (originalIndexPath) {
  275. process.env.INDEX_PATH = originalIndexPath;
  276. } else {
  277. delete process.env.INDEX_PATH;
  278. }
  279. });
  280. test("getPwd returns current working directory", () => {
  281. const pwd = getPwd();
  282. expect(pwd).toBeTruthy();
  283. expect(typeof pwd).toBe("string");
  284. });
  285. test("getRealPath resolves symlinks", () => {
  286. const result = getRealPath("/tmp");
  287. expect(result).toBeTruthy();
  288. // On macOS, /tmp is a symlink to /private/tmp
  289. expect(result === "/tmp" || result === "/private/tmp").toBe(true);
  290. });
  291. });
  292. // =============================================================================
  293. // Handelize Tests - path normalization for token-friendly filenames
  294. // =============================================================================
  295. describe("handelize", () => {
  296. test("converts to lowercase", () => {
  297. expect(handelize("README.md")).toBe("readme.md");
  298. expect(handelize("MyFile.MD")).toBe("myfile.md");
  299. });
  300. test("preserves folder structure", () => {
  301. expect(handelize("a/b/c/d.md")).toBe("a/b/c/d.md");
  302. expect(handelize("docs/api/README.md")).toBe("docs/api/readme.md");
  303. });
  304. test("replaces non-word characters with dash", () => {
  305. expect(handelize("hello world.md")).toBe("hello-world.md");
  306. expect(handelize("file (1).md")).toBe("file-1.md");
  307. expect(handelize("foo@bar#baz.md")).toBe("foo-bar-baz.md");
  308. });
  309. test("collapses multiple special chars into single dash", () => {
  310. expect(handelize("hello world.md")).toBe("hello-world.md");
  311. expect(handelize("foo---bar.md")).toBe("foo-bar.md");
  312. expect(handelize("a - b.md")).toBe("a-b.md");
  313. });
  314. test("removes leading and trailing dashes from segments", () => {
  315. expect(handelize("-hello-.md")).toBe("hello.md");
  316. expect(handelize("--test--.md")).toBe("test.md");
  317. expect(handelize("a/-b-/c.md")).toBe("a/b/c.md");
  318. });
  319. test("converts triple underscore to folder separator", () => {
  320. expect(handelize("foo___bar.md")).toBe("foo/bar.md");
  321. expect(handelize("notes___2025___january.md")).toBe("notes/2025/january.md");
  322. expect(handelize("a/b___c/d.md")).toBe("a/b/c/d.md");
  323. });
  324. test("handles complex real-world meeting notes", () => {
  325. // Example: "Money Movement Licensing Review - 2025/11/19 10:25 EST - Notes by Gemini.md"
  326. const complexName = "Money Movement Licensing Review - 2025/11/19 10:25 EST - Notes by Gemini.md";
  327. const result = handelize(complexName);
  328. expect(result).toBe("money-movement-licensing-review-2025-11-19-10-25-est-notes-by-gemini.md");
  329. expect(result).not.toContain(" ");
  330. expect(result).not.toContain("/");
  331. expect(result).not.toContain(":");
  332. });
  333. test("handles unicode characters", () => {
  334. // Pure unicode filenames are now supported (fixes GitHub issue #10)
  335. expect(handelize("日本語.md")).toBe("日本語.md");
  336. expect(handelize("Зоны и проекты.md")).toBe("зоны-и-проекты.md");
  337. // Mixed unicode/ascii preserves both
  338. expect(handelize("café-notes.md")).toBe("café-notes.md");
  339. expect(handelize("naïve.md")).toBe("naïve.md");
  340. expect(handelize("日本語-notes.md")).toBe("日本語-notes.md");
  341. });
  342. test("handles dates and times in filenames", () => {
  343. expect(handelize("meeting-2025-01-15.md")).toBe("meeting-2025-01-15.md");
  344. expect(handelize("notes 2025/01/15.md")).toBe("notes-2025/01/15.md");
  345. expect(handelize("call_10:30_AM.md")).toBe("call-10-30-am.md");
  346. });
  347. test("handles special project naming patterns", () => {
  348. expect(handelize("PROJECT_ABC_v2.0.md")).toBe("project-abc-v2-0.md");
  349. expect(handelize("[WIP] Feature Request.md")).toBe("wip-feature-request.md");
  350. expect(handelize("(DRAFT) Proposal v1.md")).toBe("draft-proposal-v1.md");
  351. });
  352. test("handles symbol-only route filenames", () => {
  353. expect(handelize("routes/api/auth/$.ts")).toBe("routes/api/auth/$.ts");
  354. expect(handelize("app/routes/$id.tsx")).toBe("app/routes/$id.tsx");
  355. });
  356. test("filters out empty segments", () => {
  357. expect(handelize("a//b/c.md")).toBe("a/b/c.md");
  358. expect(handelize("/a/b/")).toBe("a/b");
  359. expect(handelize("///test///")).toBe("test");
  360. });
  361. test("throws error for invalid inputs", () => {
  362. expect(() => handelize("")).toThrow("path cannot be empty");
  363. expect(() => handelize(" ")).toThrow("path cannot be empty");
  364. expect(() => handelize(".md")).toThrow("no valid filename content");
  365. expect(() => handelize("...")).toThrow("no valid filename content");
  366. expect(() => handelize("___")).toThrow("no valid filename content");
  367. });
  368. test("handles minimal valid inputs", () => {
  369. expect(handelize("a")).toBe("a");
  370. expect(handelize("1")).toBe("1");
  371. expect(handelize("a.md")).toBe("a.md");
  372. });
  373. });
  374. // =============================================================================
  375. // Store Creation Tests
  376. // =============================================================================
  377. describe("Store Creation", () => {
  378. test("createStore throws without explicit path in test mode", () => {
  379. // In test mode, createStore without path should throw to prevent accidental writes
  380. const originalIndexPath = process.env.INDEX_PATH;
  381. delete process.env.INDEX_PATH;
  382. expect(() => createStore()).toThrow("Database path not set");
  383. // Restore
  384. if (originalIndexPath) process.env.INDEX_PATH = originalIndexPath;
  385. });
  386. test("createStore creates a new store with custom path", async () => {
  387. const store = await createTestStore();
  388. expect(store.dbPath).toBe(testDbPath);
  389. expect(store.db).toBeDefined();
  390. expect(typeof store.db.exec).toBe("function");
  391. await cleanupTestDb(store);
  392. });
  393. test("createStore initializes database schema", async () => {
  394. const store = await createTestStore();
  395. // Check tables exist
  396. const tables = store.db.prepare(`
  397. SELECT name FROM sqlite_master WHERE type='table' ORDER BY name
  398. `).all() as { name: string }[];
  399. const tableNames = tables.map(t => t.name);
  400. expect(tableNames).toContain("documents");
  401. expect(tableNames).toContain("documents_fts");
  402. expect(tableNames).toContain("content_vectors");
  403. expect(tableNames).toContain("llm_cache");
  404. // Note: path_contexts table removed in favor of YAML-based context storage
  405. await cleanupTestDb(store);
  406. });
  407. test("createStore sets WAL journal mode", async () => {
  408. const store = await createTestStore();
  409. const result = store.db.prepare("PRAGMA journal_mode").get() as { journal_mode: string };
  410. expect(result.journal_mode).toBe("wal");
  411. await cleanupTestDb(store);
  412. });
  413. test("verifySqliteVecLoaded throws when sqlite-vec is not loaded", () => {
  414. const db = openDatabase(":memory:");
  415. try {
  416. expect(() => verifySqliteVecLoaded(db)).toThrow("sqlite-vec extension is unavailable");
  417. } finally {
  418. db.close();
  419. }
  420. });
  421. test("verifySqliteVecLoaded succeeds when sqlite-vec is loaded", () => {
  422. const db = openDatabase(":memory:");
  423. try {
  424. loadSqliteVec(db);
  425. expect(() => verifySqliteVecLoaded(db)).not.toThrow();
  426. } finally {
  427. db.close();
  428. }
  429. });
  430. test("store.close closes the database connection", async () => {
  431. const store = await createTestStore();
  432. store.close();
  433. // Attempting to use db after close should throw
  434. expect(() => store.db.prepare("SELECT 1").get()).toThrow();
  435. try {
  436. await unlink(testDbPath);
  437. } catch {}
  438. });
  439. });
  440. // =============================================================================
  441. // Document Hashing & Title Extraction Tests
  442. // =============================================================================
  443. describe("Document Helpers", () => {
  444. test("hashContent produces consistent SHA256 hashes", async () => {
  445. const content = "Hello, World!";
  446. const hash1 = await hashContent(content);
  447. const hash2 = await hashContent(content);
  448. expect(hash1).toBe(hash2);
  449. expect(hash1).toMatch(/^[a-f0-9]{64}$/);
  450. });
  451. test("hashContent produces different hashes for different content", async () => {
  452. const hash1 = await hashContent("Hello");
  453. const hash2 = await hashContent("World");
  454. expect(hash1).not.toBe(hash2);
  455. });
  456. test("extractTitle extracts H1 heading", () => {
  457. const content = "# My Title\n\nSome content here.";
  458. expect(extractTitle(content, "file.md")).toBe("My Title");
  459. });
  460. test("extractTitle extracts H2 heading if no H1", () => {
  461. const content = "## My Subtitle\n\nSome content here.";
  462. expect(extractTitle(content, "file.md")).toBe("My Subtitle");
  463. });
  464. test("extractTitle falls back to filename", () => {
  465. const content = "Just some plain text without headings.";
  466. expect(extractTitle(content, "my-document.md")).toBe("my-document");
  467. });
  468. test("extractTitle skips generic 'Notes' heading", () => {
  469. const content = "# Notes\n\n## Actual Title\n\nContent";
  470. expect(extractTitle(content, "file.md")).toBe("Actual Title");
  471. });
  472. test("extractTitle handles 📝 Notes heading", () => {
  473. const content = "# 📝 Notes\n\n## Meeting Summary\n\nContent";
  474. expect(extractTitle(content, "file.md")).toBe("Meeting Summary");
  475. });
  476. });
  477. // =============================================================================
  478. // Embedding Format Tests
  479. // =============================================================================
  480. describe("Embedding Formatting", () => {
  481. test("formatQueryForEmbedding adds search task prefix", () => {
  482. const formatted = formatQueryForEmbedding("how to deploy");
  483. expect(formatted).toBe("task: search result | query: how to deploy");
  484. });
  485. test("formatDocForEmbedding adds title and text prefix", () => {
  486. const formatted = formatDocForEmbedding("Some content", "My Title");
  487. expect(formatted).toBe("title: My Title | text: Some content");
  488. });
  489. test("formatDocForEmbedding handles missing title", () => {
  490. const formatted = formatDocForEmbedding("Some content");
  491. expect(formatted).toBe("title: none | text: Some content");
  492. });
  493. });
  494. // =============================================================================
  495. // Document Chunking Tests
  496. // =============================================================================
  497. describe("Document Chunking", () => {
  498. test("chunkDocument returns single chunk for small documents", () => {
  499. const content = "Small document content";
  500. const chunks = chunkDocument(content, 1000, 0);
  501. expect(chunks).toHaveLength(1);
  502. expect(chunks[0]!.text).toBe(content);
  503. expect(chunks[0]!.pos).toBe(0);
  504. });
  505. test("chunkDocument splits large documents", () => {
  506. const content = "A".repeat(10000);
  507. const chunks = chunkDocument(content, 1000, 0);
  508. expect(chunks.length).toBeGreaterThan(1);
  509. // All chunks should have correct positions
  510. for (let i = 0; i < chunks.length; i++) {
  511. expect(chunks[i]!.pos).toBeGreaterThanOrEqual(0);
  512. if (i > 0) {
  513. expect(chunks[i]!.pos).toBeGreaterThan(chunks[i - 1]!.pos);
  514. }
  515. }
  516. });
  517. test("chunkDocument with overlap creates overlapping chunks", () => {
  518. const content = "A".repeat(3000);
  519. const chunks = chunkDocument(content, 1000, 150); // 15% overlap
  520. expect(chunks.length).toBeGreaterThan(1);
  521. // With overlap, positions should be closer together than without
  522. // Each new chunk starts 150 chars before where the previous one ended
  523. for (let i = 1; i < chunks.length; i++) {
  524. const prevEnd = chunks[i - 1]!.pos + chunks[i - 1]!.text.length;
  525. const currentStart = chunks[i]!.pos;
  526. // Current chunk should start before the previous chunk ended (overlap)
  527. expect(currentStart).toBeLessThan(prevEnd);
  528. // But should still make forward progress
  529. expect(currentStart).toBeGreaterThan(chunks[i - 1]!.pos);
  530. }
  531. });
  532. test("chunkDocument prefers paragraph breaks", () => {
  533. const content = "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.".repeat(50);
  534. const chunks = chunkDocument(content, 500, 0);
  535. // Chunks should end at paragraph breaks when possible
  536. for (const chunk of chunks.slice(0, -1)) {
  537. // Most chunks should end near a paragraph break
  538. const endsNearParagraph = chunk.text.endsWith("\n\n") ||
  539. chunk.text.endsWith(".") ||
  540. chunk.text.endsWith("\n");
  541. // This is a soft check - not all chunks can end at breaks
  542. }
  543. expect(chunks.length).toBeGreaterThan(1);
  544. });
  545. test("chunkDocument handles UTF-8 characters correctly", () => {
  546. const content = "こんにちは世界".repeat(500); // Japanese text
  547. const chunks = chunkDocument(content, 1000, 0);
  548. // Should not split in the middle of a multi-byte character
  549. for (const chunk of chunks) {
  550. expect(() => new TextEncoder().encode(chunk.text)).not.toThrow();
  551. }
  552. });
  553. test("chunkDocument with default params uses 900-token chunks", () => {
  554. // Default is CHUNK_SIZE_CHARS (3600 chars) with CHUNK_OVERLAP_CHARS (540 chars)
  555. const content = "Word ".repeat(2500); // ~12500 chars
  556. const chunks = chunkDocument(content);
  557. expect(chunks.length).toBeGreaterThan(1);
  558. // Each chunk should be around 3600 chars (except last)
  559. expect(chunks[0]!.text.length).toBeGreaterThan(2800);
  560. expect(chunks[0]!.text.length).toBeLessThanOrEqual(3600);
  561. });
  562. });
  563. describe.skipIf(!!process.env.CI)("Token-based Chunking", () => {
  564. test("chunkDocumentByTokens returns single chunk for small documents", async () => {
  565. const content = "This is a small document.";
  566. const chunks = await chunkDocumentByTokens(content, 900, 135);
  567. expect(chunks).toHaveLength(1);
  568. expect(chunks[0]!.text).toBe(content);
  569. expect(chunks[0]!.pos).toBe(0);
  570. expect(chunks[0]!.tokens).toBeGreaterThan(0);
  571. expect(chunks[0]!.tokens).toBeLessThan(900);
  572. });
  573. test("chunkDocumentByTokens splits large documents", async () => {
  574. // Create a document that's definitely more than 900 tokens
  575. const content = "The quick brown fox jumps over the lazy dog. ".repeat(250);
  576. const chunks = await chunkDocumentByTokens(content, 900, 135);
  577. expect(chunks.length).toBeGreaterThan(1);
  578. // Each chunk should have ~900 tokens or less
  579. for (const chunk of chunks) {
  580. expect(chunk.tokens).toBeLessThanOrEqual(950); // Allow slight overage
  581. expect(chunk.tokens).toBeGreaterThan(0);
  582. }
  583. // Chunks should have correct positions
  584. for (let i = 0; i < chunks.length; i++) {
  585. expect(chunks[i]!.pos).toBeGreaterThanOrEqual(0);
  586. if (i > 0) {
  587. expect(chunks[i]!.pos).toBeGreaterThan(chunks[i - 1]!.pos);
  588. }
  589. }
  590. });
  591. test("chunkDocumentByTokens creates overlapping chunks", async () => {
  592. const content = "Word ".repeat(500); // ~500 tokens
  593. const chunks = await chunkDocumentByTokens(content, 200, 30); // 15% overlap
  594. expect(chunks.length).toBeGreaterThan(1);
  595. // With overlap, consecutive chunks should have overlapping positions
  596. for (let i = 1; i < chunks.length; i++) {
  597. const prevEnd = chunks[i - 1]!.pos + chunks[i - 1]!.text.length;
  598. const currentStart = chunks[i]!.pos;
  599. // Current chunk should start before the previous chunk ended (overlap)
  600. expect(currentStart).toBeLessThan(prevEnd);
  601. }
  602. });
  603. test("chunkDocumentByTokens returns actual token counts", async () => {
  604. const content = "Hello world, this is a test.";
  605. const chunks = await chunkDocumentByTokens(content);
  606. expect(chunks).toHaveLength(1);
  607. // The token count should be reasonable (not 0, not equal to char count)
  608. expect(chunks[0]!.tokens).toBeGreaterThan(0);
  609. expect(chunks[0]!.tokens).toBeLessThan(content.length); // Tokens < chars for English
  610. });
  611. });
  612. // =============================================================================
  613. // Smart Chunking - Break Point Detection Tests
  614. // =============================================================================
  615. describe("scanBreakPoints", () => {
  616. test("detects h1 headings", () => {
  617. const text = "Intro\n# Heading 1\nMore text";
  618. const breaks = scanBreakPoints(text);
  619. const h1 = breaks.find(b => b.type === 'h1');
  620. expect(h1).toBeDefined();
  621. expect(h1!.score).toBe(100);
  622. expect(h1!.pos).toBe(5); // position of \n#
  623. });
  624. test("detects multiple heading levels", () => {
  625. const text = "Text\n# H1\n## H2\n### H3\nMore";
  626. const breaks = scanBreakPoints(text);
  627. const h1 = breaks.find(b => b.type === 'h1');
  628. const h2 = breaks.find(b => b.type === 'h2');
  629. const h3 = breaks.find(b => b.type === 'h3');
  630. expect(h1).toBeDefined();
  631. expect(h2).toBeDefined();
  632. expect(h3).toBeDefined();
  633. expect(h1!.score).toBe(100);
  634. expect(h2!.score).toBe(90);
  635. expect(h3!.score).toBe(80);
  636. });
  637. test("detects code blocks", () => {
  638. const text = "Before\n```js\ncode\n```\nAfter";
  639. const breaks = scanBreakPoints(text);
  640. const codeBlocks = breaks.filter(b => b.type === 'codeblock');
  641. expect(codeBlocks.length).toBe(2); // opening and closing
  642. expect(codeBlocks[0]!.score).toBe(80);
  643. });
  644. test("detects horizontal rules", () => {
  645. const text = "Text\n---\nMore text";
  646. const breaks = scanBreakPoints(text);
  647. const hr = breaks.find(b => b.type === 'hr');
  648. expect(hr).toBeDefined();
  649. expect(hr!.score).toBe(60);
  650. });
  651. test("detects blank lines (paragraph boundaries)", () => {
  652. const text = "First paragraph.\n\nSecond paragraph.";
  653. const breaks = scanBreakPoints(text);
  654. const blank = breaks.find(b => b.type === 'blank');
  655. expect(blank).toBeDefined();
  656. expect(blank!.score).toBe(20);
  657. });
  658. test("detects list items", () => {
  659. const text = "Intro\n- Item 1\n- Item 2\n1. Numbered";
  660. const breaks = scanBreakPoints(text);
  661. const lists = breaks.filter(b => b.type === 'list');
  662. const numLists = breaks.filter(b => b.type === 'numlist');
  663. expect(lists.length).toBe(2);
  664. expect(numLists.length).toBe(1);
  665. expect(lists[0]!.score).toBe(5);
  666. expect(numLists[0]!.score).toBe(5);
  667. });
  668. test("detects newlines as fallback", () => {
  669. const text = "Line 1\nLine 2\nLine 3";
  670. const breaks = scanBreakPoints(text);
  671. const newlines = breaks.filter(b => b.type === 'newline');
  672. expect(newlines.length).toBe(2);
  673. expect(newlines[0]!.score).toBe(1);
  674. });
  675. test("returns breaks sorted by position", () => {
  676. const text = "A\n# B\n\nC\n## D";
  677. const breaks = scanBreakPoints(text);
  678. for (let i = 1; i < breaks.length; i++) {
  679. expect(breaks[i]!.pos).toBeGreaterThan(breaks[i-1]!.pos);
  680. }
  681. });
  682. test("higher-scoring pattern wins at same position", () => {
  683. // \n# matches both newline (score 1) and h1 (score 100)
  684. const text = "Text\n# Heading";
  685. const breaks = scanBreakPoints(text);
  686. const atPos = breaks.filter(b => b.pos === 4);
  687. expect(atPos.length).toBe(1);
  688. expect(atPos[0]!.type).toBe('h1');
  689. expect(atPos[0]!.score).toBe(100);
  690. });
  691. });
  692. describe("findCodeFences", () => {
  693. test("finds single code fence", () => {
  694. const text = "Before\n```js\ncode here\n```\nAfter";
  695. const fences = findCodeFences(text);
  696. expect(fences.length).toBe(1);
  697. expect(fences[0]!.start).toBe(6); // position of first \n```
  698. // End is position after the closing \n``` (which is at position 22, length 4)
  699. expect(fences[0]!.end).toBe(26);
  700. });
  701. test("finds multiple code fences", () => {
  702. const text = "Intro\n```\nblock1\n```\nMiddle\n```\nblock2\n```\nEnd";
  703. const fences = findCodeFences(text);
  704. expect(fences.length).toBe(2);
  705. });
  706. test("handles unclosed code fence", () => {
  707. const text = "Before\n```\nunclosed code block";
  708. const fences = findCodeFences(text);
  709. expect(fences.length).toBe(1);
  710. expect(fences[0]!.end).toBe(text.length); // extends to end of document
  711. });
  712. test("returns empty array for no code fences", () => {
  713. const text = "No code fences here";
  714. const fences = findCodeFences(text);
  715. expect(fences.length).toBe(0);
  716. });
  717. });
  718. describe("isInsideCodeFence", () => {
  719. test("returns true for position inside fence", () => {
  720. const fences: CodeFenceRegion[] = [{ start: 10, end: 30 }];
  721. expect(isInsideCodeFence(15, fences)).toBe(true);
  722. expect(isInsideCodeFence(20, fences)).toBe(true);
  723. });
  724. test("returns false for position outside fence", () => {
  725. const fences: CodeFenceRegion[] = [{ start: 10, end: 30 }];
  726. expect(isInsideCodeFence(5, fences)).toBe(false);
  727. expect(isInsideCodeFence(35, fences)).toBe(false);
  728. });
  729. test("returns false for position at fence boundaries", () => {
  730. const fences: CodeFenceRegion[] = [{ start: 10, end: 30 }];
  731. expect(isInsideCodeFence(10, fences)).toBe(false); // at start
  732. expect(isInsideCodeFence(30, fences)).toBe(false); // at end
  733. });
  734. test("handles multiple fences", () => {
  735. const fences: CodeFenceRegion[] = [
  736. { start: 10, end: 30 },
  737. { start: 50, end: 70 }
  738. ];
  739. expect(isInsideCodeFence(20, fences)).toBe(true);
  740. expect(isInsideCodeFence(60, fences)).toBe(true);
  741. expect(isInsideCodeFence(40, fences)).toBe(false);
  742. });
  743. });
  744. describe("findBestCutoff", () => {
  745. test("prefers higher-scoring break points", () => {
  746. const breakPoints: BreakPoint[] = [
  747. { pos: 100, score: 1, type: 'newline' },
  748. { pos: 150, score: 100, type: 'h1' },
  749. { pos: 180, score: 20, type: 'blank' },
  750. ];
  751. // Target is 200, window is 100 (so 100-200 is valid)
  752. const cutoff = findBestCutoff(breakPoints, 200, 100, 0.7);
  753. expect(cutoff).toBe(150); // h1 wins due to high score
  754. });
  755. test("h2 at window edge beats blank at target (squared decay)", () => {
  756. const breakPoints: BreakPoint[] = [
  757. { pos: 100, score: 90, type: 'h2' }, // at window edge
  758. { pos: 195, score: 20, type: 'blank' }, // close to target
  759. ];
  760. // Target is 200, window is 100
  761. // With squared decay:
  762. // h2 at 100: dist=100, normalized=1.0, mult=1-1*0.7=0.3, final=90*0.3=27
  763. // blank at 195: dist=5, normalized=0.05, mult=1-0.0025*0.7=0.998, final=20*0.998=19.97
  764. const cutoff = findBestCutoff(breakPoints, 200, 100, 0.7);
  765. expect(cutoff).toBe(100); // h2 wins even at edge!
  766. });
  767. test("high score easily overcomes distance", () => {
  768. const breakPoints: BreakPoint[] = [
  769. { pos: 150, score: 100, type: 'h1' }, // h1 at middle
  770. { pos: 195, score: 1, type: 'newline' }, // newline near target
  771. ];
  772. // Target is 200, window is 100
  773. // h1 at 150: dist=50, normalized=0.5, mult=1-0.25*0.7=0.825, final=82.5
  774. // newline at 195: dist=5, mult=0.998, final=0.998
  775. const cutoff = findBestCutoff(breakPoints, 200, 100, 0.7);
  776. expect(cutoff).toBe(150); // h1 wins easily
  777. });
  778. test("returns target position when no breaks in window", () => {
  779. const breakPoints: BreakPoint[] = [
  780. { pos: 10, score: 100, type: 'h1' }, // too far before window
  781. ];
  782. const cutoff = findBestCutoff(breakPoints, 200, 100, 0.7);
  783. expect(cutoff).toBe(200);
  784. });
  785. test("skips break points inside code fences", () => {
  786. const breakPoints: BreakPoint[] = [
  787. { pos: 150, score: 100, type: 'h1' }, // inside fence
  788. { pos: 180, score: 20, type: 'blank' }, // outside fence
  789. ];
  790. const codeFences: CodeFenceRegion[] = [{ start: 140, end: 160 }];
  791. const cutoff = findBestCutoff(breakPoints, 200, 100, 0.7, codeFences);
  792. expect(cutoff).toBe(180); // blank wins since h1 is inside fence
  793. });
  794. test("handles empty break points array", () => {
  795. const cutoff = findBestCutoff([], 200, 100, 0.7);
  796. expect(cutoff).toBe(200);
  797. });
  798. });
  799. describe("Smart Chunking Integration", () => {
  800. test("chunkDocument prefers headings over arbitrary breaks", () => {
  801. // Create content where the heading falls within the search window
  802. // We want the heading at ~1700 chars so it's in the window for a 2000 char target
  803. const section1 = "Introduction text here. ".repeat(70); // ~1680 chars
  804. const section2 = "Main content text here. ".repeat(50); // ~1150 chars
  805. const content = `${section1}\n# Main Section\n${section2}`;
  806. // With 2000 char chunks and 800 char window (searches 1200-2000)
  807. // Heading is at ~1680 which is in window
  808. const chunks = chunkDocument(content, 2000, 0, 800);
  809. const headingPos = content.indexOf('\n# Main Section');
  810. // First chunk should end at the heading (best break point in window)
  811. expect(chunks.length).toBeGreaterThanOrEqual(2);
  812. expect(chunks[0]!.text.length).toBe(headingPos);
  813. });
  814. test("chunkDocument does not split inside code blocks", () => {
  815. const beforeCode = "Some intro text. ".repeat(30); // ~480 chars
  816. const codeBlock = "```typescript\n" + "const x = 1;\n".repeat(100) + "```\n";
  817. const afterCode = "More text after code. ".repeat(30);
  818. const content = beforeCode + codeBlock + afterCode;
  819. const chunks = chunkDocument(content, 1000, 0, 400);
  820. // Check that no chunk starts in the middle of a code block
  821. for (const chunk of chunks) {
  822. const hasOpenFence = (chunk.text.match(/\n```/g) || []).length;
  823. // If we have an odd number of fence markers, we're splitting inside a block
  824. // (unless it's the last chunk with unclosed fence)
  825. if (hasOpenFence % 2 === 1 && !chunk.text.endsWith('```\n')) {
  826. // This is acceptable only if it's an unclosed fence at document end
  827. const isLastChunk = chunks.indexOf(chunk) === chunks.length - 1;
  828. if (!isLastChunk) {
  829. // Not the last chunk, so this would be a split inside code - check it's not common
  830. // Actually this test is more about smoke testing - we just verify it runs
  831. }
  832. }
  833. }
  834. expect(chunks.length).toBeGreaterThan(1);
  835. });
  836. test("chunkDocument handles markdown with mixed elements", () => {
  837. const content = `# Introduction
  838. This is the introduction paragraph with some text.
  839. ## Section 1
  840. Some content in section 1.
  841. - List item 1
  842. - List item 2
  843. - List item 3
  844. ## Section 2
  845. \`\`\`javascript
  846. function hello() {
  847. console.log("Hello");
  848. }
  849. \`\`\`
  850. More text after the code block.
  851. ---
  852. ## Section 3
  853. Final section content.
  854. `.repeat(10);
  855. const chunks = chunkDocument(content, 500, 75, 200);
  856. // Should produce multiple chunks
  857. expect(chunks.length).toBeGreaterThan(5);
  858. // All chunks should be valid strings
  859. for (const chunk of chunks) {
  860. expect(typeof chunk.text).toBe('string');
  861. expect(chunk.text.length).toBeGreaterThan(0);
  862. expect(chunk.pos).toBeGreaterThanOrEqual(0);
  863. }
  864. });
  865. });
  866. // =============================================================================
  867. // AST-Aware Chunking Integration Tests
  868. // =============================================================================
  869. describe("mergeBreakPoints", () => {
  870. test("merges two sets of break points keeping highest score at each position", () => {
  871. const regexPoints: BreakPoint[] = [
  872. { pos: 10, score: 20, type: "blank" },
  873. { pos: 50, score: 1, type: "newline" },
  874. ];
  875. const astPoints: BreakPoint[] = [
  876. { pos: 10, score: 90, type: "ast:func" },
  877. { pos: 100, score: 100, type: "ast:class" },
  878. ];
  879. const merged = mergeBreakPoints(regexPoints, astPoints);
  880. expect(merged).toHaveLength(3);
  881. // pos 10: AST score (90) wins over regex (20)
  882. const at10 = merged.find(p => p.pos === 10);
  883. expect(at10?.score).toBe(90);
  884. expect(at10?.type).toBe("ast:func");
  885. // pos 50: only regex
  886. expect(merged.find(p => p.pos === 50)?.score).toBe(1);
  887. // pos 100: only AST
  888. expect(merged.find(p => p.pos === 100)?.score).toBe(100);
  889. });
  890. test("returns sorted by position", () => {
  891. const a: BreakPoint[] = [{ pos: 100, score: 10, type: "a" }];
  892. const b: BreakPoint[] = [{ pos: 5, score: 20, type: "b" }];
  893. const merged = mergeBreakPoints(a, b);
  894. expect(merged[0]!.pos).toBe(5);
  895. expect(merged[1]!.pos).toBe(100);
  896. });
  897. });
  898. describe("chunkDocumentWithBreakPoints", () => {
  899. test("produces same output as chunkDocument for same input", () => {
  900. const content = "a".repeat(5000) + "\n\n" + "b".repeat(5000);
  901. const breakPoints = scanBreakPoints(content);
  902. const codeFences = findCodeFences(content);
  903. const chunksOriginal = chunkDocument(content);
  904. const chunksNew = chunkDocumentWithBreakPoints(content, breakPoints, codeFences);
  905. expect(chunksNew.length).toBe(chunksOriginal.length);
  906. for (let i = 0; i < chunksNew.length; i++) {
  907. expect(chunksNew[i]!.text).toBe(chunksOriginal[i]!.text);
  908. expect(chunksNew[i]!.pos).toBe(chunksOriginal[i]!.pos);
  909. }
  910. });
  911. });
  912. describe("AST-aware chunkDocumentAsync", () => {
  913. const TS_CODE = `import { Database } from './db';
  914. export class AuthService {
  915. constructor(private db: Database) {}
  916. async authenticate(user: User, token: string): Promise<boolean> {
  917. const session = await this.db.findSession(token);
  918. return session?.userId === user.id;
  919. }
  920. validateToken(token: string): boolean {
  921. return token.length === 64;
  922. }
  923. }
  924. export function hashPassword(password: string): string {
  925. return crypto.createHash('sha256').update(password).digest('hex');
  926. }
  927. `.repeat(10); // Repeat to make it large enough to trigger chunking
  928. test("returns chunks for code files with AST strategy", async () => {
  929. const chunks = await chunkDocumentAsync(TS_CODE, undefined, undefined, undefined, "auth.ts", "auto");
  930. expect(chunks.length).toBeGreaterThan(0);
  931. // Each chunk should have text and pos
  932. for (const chunk of chunks) {
  933. expect(typeof chunk.text).toBe("string");
  934. expect(chunk.text.length).toBeGreaterThan(0);
  935. expect(chunk.pos).toBeGreaterThanOrEqual(0);
  936. }
  937. });
  938. test("regex strategy produces same output as chunkDocument for code files", async () => {
  939. const asyncChunks = await chunkDocumentAsync(TS_CODE, undefined, undefined, undefined, "auth.ts", "regex");
  940. const syncChunks = chunkDocument(TS_CODE);
  941. expect(asyncChunks.length).toBe(syncChunks.length);
  942. for (let i = 0; i < asyncChunks.length; i++) {
  943. expect(asyncChunks[i]!.text).toBe(syncChunks[i]!.text);
  944. expect(asyncChunks[i]!.pos).toBe(syncChunks[i]!.pos);
  945. }
  946. });
  947. test("markdown files are unchanged in auto mode", async () => {
  948. const mdContent = ("# Heading\n\n" + "Some text. ".repeat(200) + "\n\n").repeat(10);
  949. const asyncChunks = await chunkDocumentAsync(mdContent, undefined, undefined, undefined, "readme.md", "auto");
  950. const syncChunks = chunkDocument(mdContent);
  951. expect(asyncChunks.length).toBe(syncChunks.length);
  952. for (let i = 0; i < asyncChunks.length; i++) {
  953. expect(asyncChunks[i]!.text).toBe(syncChunks[i]!.text);
  954. }
  955. });
  956. test("no filepath falls back to regex-only", async () => {
  957. const asyncChunks = await chunkDocumentAsync(TS_CODE, undefined, undefined, undefined, undefined, "auto");
  958. const syncChunks = chunkDocument(TS_CODE);
  959. expect(asyncChunks.length).toBe(syncChunks.length);
  960. for (let i = 0; i < asyncChunks.length; i++) {
  961. expect(asyncChunks[i]!.text).toBe(syncChunks[i]!.text);
  962. }
  963. });
  964. });
  965. // =============================================================================
  966. // Caching Tests
  967. // =============================================================================
  968. describe("Caching", () => {
  969. test("getCacheKey generates consistent keys", () => {
  970. const key1 = getCacheKey("http://example.com", { query: "test" });
  971. const key2 = getCacheKey("http://example.com", { query: "test" });
  972. expect(key1).toBe(key2);
  973. expect(key1).toMatch(/^[a-f0-9]{64}$/);
  974. });
  975. test("getCacheKey generates different keys for different inputs", () => {
  976. const key1 = getCacheKey("http://example.com", { query: "test1" });
  977. const key2 = getCacheKey("http://example.com", { query: "test2" });
  978. expect(key1).not.toBe(key2);
  979. });
  980. test("store cache operations work correctly", async () => {
  981. const store = await createTestStore();
  982. const key = "test-cache-key";
  983. const value = "cached result";
  984. // Initially empty
  985. expect(store.getCachedResult(key)).toBeNull();
  986. // Set cache
  987. store.setCachedResult(key, value);
  988. // Retrieve cache
  989. expect(store.getCachedResult(key)).toBe(value);
  990. // Clear cache
  991. store.clearCache();
  992. expect(store.getCachedResult(key)).toBeNull();
  993. await cleanupTestDb(store);
  994. });
  995. });
  996. // =============================================================================
  997. // Context Tests
  998. // =============================================================================
  999. describe("Path Context", () => {
  1000. test("getContextForFile returns null when no context set", async () => {
  1001. const store = await createTestStore();
  1002. const context = store.getContextForFile("/some/random/path.md");
  1003. expect(context).toBeNull();
  1004. await cleanupTestDb(store);
  1005. });
  1006. test("getContextForFile returns matching context", async () => {
  1007. const store = await createTestStore();
  1008. const collectionName = await createTestCollection({ pwd: "/test/collection", glob: "**/*.md" });
  1009. await addPathContext(collectionName, "/docs", "Documentation files");
  1010. // Insert a document so getContextForFile can find it
  1011. await insertTestDocument(store.db, collectionName, {
  1012. name: "readme",
  1013. displayPath: "docs/readme.md",
  1014. });
  1015. const context = store.getContextForFile("/test/collection/docs/readme.md");
  1016. expect(context).toBe("Documentation files");
  1017. await cleanupTestDb(store);
  1018. });
  1019. test("getContextForFile returns all matching contexts", async () => {
  1020. const store = await createTestStore();
  1021. const collectionName = await createTestCollection({ pwd: "/test/collection", glob: "**/*.md" });
  1022. await addPathContext(collectionName, "/", "General test files");
  1023. await addPathContext(collectionName, "/docs", "Documentation files");
  1024. await addPathContext(collectionName, "/docs/api", "API documentation");
  1025. // Insert documents so getContextForFile can find them
  1026. await insertTestDocument(store.db, collectionName, {
  1027. name: "readme",
  1028. displayPath: "readme.md",
  1029. });
  1030. await insertTestDocument(store.db, collectionName, {
  1031. name: "guide",
  1032. displayPath: "docs/guide.md",
  1033. });
  1034. await insertTestDocument(store.db, collectionName, {
  1035. name: "reference",
  1036. displayPath: "docs/api/reference.md",
  1037. });
  1038. // Context now returns ALL matching contexts joined with \n\n
  1039. expect(store.getContextForFile("/test/collection/readme.md")).toBe("General test files");
  1040. expect(store.getContextForFile("/test/collection/docs/guide.md")).toBe("General test files\n\nDocumentation files");
  1041. expect(store.getContextForFile("/test/collection/docs/api/reference.md")).toBe("General test files\n\nDocumentation files\n\nAPI documentation");
  1042. await cleanupTestDb(store);
  1043. });
  1044. });
  1045. // =============================================================================
  1046. // Collection Tests
  1047. // =============================================================================
  1048. describe("Collections", () => {
  1049. test("collections are managed via YAML config", async () => {
  1050. const store = await createTestStore();
  1051. const collectionName = await createTestCollection({ pwd: "/home/user/projects/myapp", glob: "**/*.md" });
  1052. // Collections are now in YAML, not in the database
  1053. expect(collectionName).toBe("myapp");
  1054. await cleanupTestDb(store);
  1055. });
  1056. });
  1057. // =============================================================================
  1058. // FTS Search Tests
  1059. // =============================================================================
  1060. describe("FTS Search", () => {
  1061. test("searchFTS returns empty array for no matches", async () => {
  1062. const store = await createTestStore();
  1063. const collectionName = await createTestCollection();
  1064. await insertTestDocument(store.db, collectionName, {
  1065. name: "doc1",
  1066. body: "The quick brown fox jumps over the lazy dog",
  1067. });
  1068. const results = store.searchFTS("nonexistent-term-xyz", 10);
  1069. expect(results).toHaveLength(0);
  1070. await cleanupTestDb(store);
  1071. });
  1072. test("searchFTS finds documents by keyword", async () => {
  1073. const store = await createTestStore();
  1074. const collectionName = await createTestCollection();
  1075. await insertTestDocument(store.db, collectionName, {
  1076. name: "doc1",
  1077. title: "Fox Document",
  1078. body: "The quick brown fox jumps over the lazy dog",
  1079. displayPath: "test/doc1.md",
  1080. });
  1081. const results = store.searchFTS("fox", 10);
  1082. expect(results.length).toBeGreaterThan(0);
  1083. expect(results[0]!.displayPath).toBe(`${collectionName}/test/doc1.md`);
  1084. expect(results[0]!.filepath).toBe(`qmd://${collectionName}/test/doc1.md`);
  1085. expect(results[0]!.source).toBe("fts");
  1086. await cleanupTestDb(store);
  1087. });
  1088. test("searchFTS ranks title matches higher", async () => {
  1089. const store = await createTestStore();
  1090. const collectionName = await createTestCollection();
  1091. // Document with "fox" in body only
  1092. await insertTestDocument(store.db, collectionName, {
  1093. name: "body-match",
  1094. title: "Some Other Title",
  1095. body: "The fox is here in the body",
  1096. displayPath: "test/body.md",
  1097. });
  1098. // Document with "fox" in title (via name field which is indexed)
  1099. await insertTestDocument(store.db, collectionName, {
  1100. name: "fox",
  1101. title: "Fox Title",
  1102. body: "Different content without the animal fox",
  1103. displayPath: "test/title.md",
  1104. });
  1105. const results = store.searchFTS("fox", 10);
  1106. // Both documents contain "fox" in the body now, so we should get 2 results
  1107. expect(results.length).toBe(2);
  1108. // Title/name match should rank higher due to BM25 weights
  1109. expect(results[0]!.displayPath).toBe(`${collectionName}/test/title.md`);
  1110. await cleanupTestDb(store);
  1111. });
  1112. test("searchFTS title boost outweighs higher body frequency", async () => {
  1113. const store = await createTestStore();
  1114. const collectionName = await createTestCollection();
  1115. // Document with "quantum" mentioned in a longer body but NOT in the title
  1116. await insertTestDocument(store.db, collectionName, {
  1117. name: "body-only",
  1118. title: "General Science Notes",
  1119. body: "This research paper discusses quantum mechanics and the quantum model of computation. The quantum approach offers improvements over classical methods.",
  1120. displayPath: "test/body-only.md",
  1121. });
  1122. // Document with "quantum" in the title but a shorter body mention
  1123. await insertTestDocument(store.db, collectionName, {
  1124. name: "title-match",
  1125. title: "Quantum Computing Overview",
  1126. body: "An introduction to the fundamentals of this emerging computing paradigm.",
  1127. displayPath: "test/title-match.md",
  1128. });
  1129. const results = store.searchFTS("quantum", 10);
  1130. expect(results.length).toBe(2);
  1131. // Title-match doc should rank higher due to BM25 column weights boosting title
  1132. expect(results[0]!.displayPath).toBe(`${collectionName}/test/title-match.md`);
  1133. await cleanupTestDb(store);
  1134. });
  1135. test("searchFTS respects limit parameter", async () => {
  1136. const store = await createTestStore();
  1137. const collectionName = await createTestCollection();
  1138. // Insert 10 documents
  1139. for (let i = 0; i < 10; i++) {
  1140. await insertTestDocument(store.db, collectionName, {
  1141. name: `doc${i}`,
  1142. body: "common keyword appears here",
  1143. displayPath: `test/doc${i}.md`,
  1144. });
  1145. }
  1146. const results = store.searchFTS("common keyword", 3);
  1147. expect(results).toHaveLength(3);
  1148. await cleanupTestDb(store);
  1149. });
  1150. test("searchFTS filters by collection name", async () => {
  1151. const store = await createTestStore();
  1152. const collection1 = await createTestCollection({ pwd: "/path/one", glob: "**/*.md", name: "one" });
  1153. const collection2 = await createTestCollection({ pwd: "/path/two", glob: "**/*.md", name: "two" });
  1154. await insertTestDocument(store.db, collection1, {
  1155. name: "doc1",
  1156. body: "searchable content",
  1157. displayPath: "doc1.md",
  1158. });
  1159. await insertTestDocument(store.db, collection2, {
  1160. name: "doc2",
  1161. body: "searchable content",
  1162. displayPath: "doc2.md",
  1163. });
  1164. const allResults = store.searchFTS("searchable", 10);
  1165. expect(allResults).toHaveLength(2);
  1166. // Filter by collection name
  1167. const filtered = store.searchFTS("searchable", 10, collection1);
  1168. expect(filtered).toHaveLength(1);
  1169. expect(filtered[0]!.displayPath).toBe(`${collection1}/doc1.md`);
  1170. await cleanupTestDb(store);
  1171. });
  1172. test("searchFTS handles special characters in query", async () => {
  1173. const store = await createTestStore();
  1174. const collectionName = await createTestCollection();
  1175. await insertTestDocument(store.db, collectionName, {
  1176. name: "doc1",
  1177. body: "Function with params: foo(bar, baz)",
  1178. displayPath: "test/doc1.md",
  1179. });
  1180. // Should not throw on special characters
  1181. const results = store.searchFTS("foo(bar)", 10);
  1182. // Results may vary based on FTS5 handling
  1183. expect(Array.isArray(results)).toBe(true);
  1184. await cleanupTestDb(store);
  1185. });
  1186. // BM25 IDF requires corpus depth — helper adds non-matching docs so term frequency
  1187. // differentiation produces meaningful scores (2-doc corpus has near-zero IDF).
  1188. async function addNoiseDocuments(db: Database, collectionName: string, count = 8) {
  1189. for (let i = 0; i < count; i++) {
  1190. await insertTestDocument(db, collectionName, {
  1191. name: `noise${i}`,
  1192. title: `Unrelated Topic ${i}`,
  1193. body: `This document discusses completely different subjects like gardening and cooking ${i}`,
  1194. displayPath: `test/noise${i}.md`,
  1195. });
  1196. }
  1197. }
  1198. test("searchFTS scores: stronger BM25 match → higher normalized score", async () => {
  1199. const store = await createTestStore();
  1200. const collectionName = await createTestCollection();
  1201. await addNoiseDocuments(store.db, collectionName);
  1202. // "alpha" appears in title (10x weight) + body → strong BM25
  1203. await insertTestDocument(store.db, collectionName, {
  1204. name: "strong",
  1205. title: "Alpha Guide",
  1206. body: "This is the definitive alpha reference with alpha details and more alpha info",
  1207. displayPath: "test/strong.md",
  1208. });
  1209. // "alpha" appears once in body only → weaker BM25
  1210. await insertTestDocument(store.db, collectionName, {
  1211. name: "weak",
  1212. title: "General Notes",
  1213. body: "Some notes that mention alpha in passing among other topics and keywords",
  1214. displayPath: "test/weak.md",
  1215. });
  1216. const results = store.searchFTS("alpha", 10);
  1217. expect(results.length).toBe(2);
  1218. // Verify score direction: stronger match (title + body) should score HIGHER
  1219. const strongResult = results.find(r => r.displayPath.includes("strong"))!;
  1220. const weakResult = results.find(r => r.displayPath.includes("weak"))!;
  1221. expect(strongResult.score).toBeGreaterThan(weakResult.score);
  1222. // Verify scores are in valid (0, 1) range
  1223. for (const r of results) {
  1224. expect(r.score).toBeGreaterThan(0);
  1225. expect(r.score).toBeLessThan(1);
  1226. }
  1227. await cleanupTestDb(store);
  1228. });
  1229. test("searchFTS scores: minScore filter keeps strong matches, drops weak", async () => {
  1230. const store = await createTestStore();
  1231. const collectionName = await createTestCollection();
  1232. await addNoiseDocuments(store.db, collectionName);
  1233. // Strong match: keyword in title (10x weight) + repeated in body
  1234. await insertTestDocument(store.db, collectionName, {
  1235. name: "strong",
  1236. title: "Kubernetes Deployment",
  1237. body: "Kubernetes deployment strategies for kubernetes clusters using kubernetes operators",
  1238. displayPath: "test/strong.md",
  1239. });
  1240. // Weak match: keyword appears once in body only
  1241. await insertTestDocument(store.db, collectionName, {
  1242. name: "weak",
  1243. title: "Random Notes",
  1244. body: "Various topics including a brief kubernetes mention among many other unrelated things",
  1245. displayPath: "test/weak.md",
  1246. });
  1247. const allResults = store.searchFTS("kubernetes", 10);
  1248. expect(allResults.length).toBe(2);
  1249. // With a minScore threshold, strong match should survive, weak should be filterable
  1250. const strongScore = allResults.find(r => r.displayPath.includes("strong"))!.score;
  1251. const weakScore = allResults.find(r => r.displayPath.includes("weak"))!.score;
  1252. // Find a threshold between them
  1253. const threshold = (strongScore + weakScore) / 2;
  1254. const filtered = allResults.filter(r => r.score >= threshold);
  1255. // Strong match survives the filter, weak does not
  1256. expect(filtered.length).toBe(1);
  1257. expect(filtered[0]!.displayPath).toContain("strong");
  1258. await cleanupTestDb(store);
  1259. });
  1260. test("searchFTS ignores inactive documents", async () => {
  1261. const store = await createTestStore();
  1262. const collectionName = await createTestCollection();
  1263. await insertTestDocument(store.db, collectionName, {
  1264. name: "active",
  1265. body: "findme content",
  1266. displayPath: "test/active.md",
  1267. active: 1,
  1268. });
  1269. await insertTestDocument(store.db, collectionName, {
  1270. name: "inactive",
  1271. body: "findme content",
  1272. displayPath: "test/inactive.md",
  1273. active: 0,
  1274. });
  1275. const results = store.searchFTS("findme", 10);
  1276. expect(results).toHaveLength(1);
  1277. expect(results[0]!.displayPath).toBe(`${collectionName}/test/active.md`);
  1278. expect(results[0]!.filepath).toBe(`qmd://${collectionName}/test/active.md`);
  1279. await cleanupTestDb(store);
  1280. });
  1281. test("searchFTS scores: strong signal detection works with correct normalization", async () => {
  1282. const store = await createTestStore();
  1283. const collectionName = await createTestCollection();
  1284. // BM25 IDF needs meaningful corpus depth for strong signal to fire.
  1285. // 50 noise docs give IDF ≈ log(50/2) ≈ 3.2 — enough for scores above 0.85.
  1286. await addNoiseDocuments(store.db, collectionName, 50);
  1287. // Dominant: keyword in filepath (10x BM25 weight column) + title + body
  1288. await insertTestDocument(store.db, collectionName, {
  1289. name: "dominant",
  1290. title: "Zephyr Configuration Guide",
  1291. body: "Complete zephyr configuration guide. Zephyr setup instructions for zephyr deployment.",
  1292. displayPath: "zephyr/zephyr-guide.md",
  1293. });
  1294. // Weak: keyword once in body only, longer doc dilutes TF
  1295. await insertTestDocument(store.db, collectionName, {
  1296. name: "weak",
  1297. title: "General Notes",
  1298. body: "Various topics covering many areas of technology and design. " +
  1299. "One of them might relate to zephyr but mostly about other things entirely. " +
  1300. "Additional content about databases, networking, security, performance, " +
  1301. "monitoring, deployment, testing, and documentation practices.",
  1302. displayPath: "notes/misc.md",
  1303. });
  1304. const results = store.searchFTS("zephyr", 10);
  1305. expect(results.length).toBe(2);
  1306. const topScore = results[0]!.score;
  1307. const secondScore = results[1]!.score;
  1308. // With correct normalization: strong match should be well above threshold
  1309. expect(topScore).toBeGreaterThanOrEqual(STRONG_SIGNAL_MIN_SCORE);
  1310. // Gap should exceed threshold when there's a dominant match
  1311. const gap = topScore - secondScore;
  1312. expect(gap).toBeGreaterThanOrEqual(STRONG_SIGNAL_MIN_GAP);
  1313. // Full strong signal check should pass (this was dead code before the fix)
  1314. const hasStrongSignal = topScore >= STRONG_SIGNAL_MIN_SCORE && gap >= STRONG_SIGNAL_MIN_GAP;
  1315. expect(hasStrongSignal).toBe(true);
  1316. await cleanupTestDb(store);
  1317. });
  1318. });
  1319. // =============================================================================
  1320. // Document Retrieval Tests
  1321. // =============================================================================
  1322. describe("Document Retrieval", () => {
  1323. describe("findDocument", () => {
  1324. test("findDocument finds by exact filepath", async () => {
  1325. const store = await createTestStore();
  1326. const collectionName = await createTestCollection({ pwd: "/exact/path", glob: "**/*.md" });
  1327. await insertTestDocument(store.db, collectionName, {
  1328. name: "mydoc",
  1329. title: "My Document",
  1330. displayPath: "mydoc.md",
  1331. body: "Document content here",
  1332. });
  1333. const result = store.findDocument("/exact/path/mydoc.md");
  1334. expect("error" in result).toBe(false);
  1335. if (!("error" in result)) {
  1336. expect(result.title).toBe("My Document");
  1337. expect(result.displayPath).toBe(`${collectionName}/mydoc.md`);
  1338. expect(result.filepath).toBe(`qmd://${collectionName}/mydoc.md`);
  1339. expect(result.body).toBeUndefined(); // body not included by default
  1340. }
  1341. await cleanupTestDb(store);
  1342. });
  1343. test("findDocument finds by display_path", async () => {
  1344. const store = await createTestStore();
  1345. const collectionName = await createTestCollection({ pwd: "/some/path", glob: "**/*.md" });
  1346. await insertTestDocument(store.db, collectionName, {
  1347. name: "mydoc",
  1348. displayPath: "docs/mydoc.md",
  1349. });
  1350. const result = store.findDocument("docs/mydoc.md");
  1351. expect("error" in result).toBe(false);
  1352. await cleanupTestDb(store);
  1353. });
  1354. test("findDocument finds by partial path match", async () => {
  1355. const store = await createTestStore();
  1356. const collectionName = await createTestCollection({ pwd: "/very/long/path/to", glob: "**/*.md" });
  1357. await insertTestDocument(store.db, collectionName, {
  1358. name: "mydoc",
  1359. displayPath: "mydoc.md",
  1360. });
  1361. const result = store.findDocument("mydoc.md");
  1362. expect("error" in result).toBe(false);
  1363. await cleanupTestDb(store);
  1364. });
  1365. test("findDocument includes body when requested", async () => {
  1366. const store = await createTestStore();
  1367. const collectionName = await createTestCollection({ pwd: "/path", glob: "**/*.md" });
  1368. await insertTestDocument(store.db, collectionName, {
  1369. name: "mydoc",
  1370. displayPath: "mydoc.md",
  1371. body: "The actual body content",
  1372. });
  1373. const result = store.findDocument("/path/mydoc.md", { includeBody: true });
  1374. expect("error" in result).toBe(false);
  1375. if (!("error" in result)) {
  1376. expect(result.body).toBe("The actual body content");
  1377. }
  1378. await cleanupTestDb(store);
  1379. });
  1380. test("findDocument returns error with suggestions for not found", async () => {
  1381. const store = await createTestStore();
  1382. const collectionName = await createTestCollection();
  1383. await insertTestDocument(store.db, collectionName, {
  1384. name: "similar",
  1385. filepath: "/path/similar.md",
  1386. displayPath: "similar.md",
  1387. });
  1388. const result = store.findDocument("simlar.md"); // typo - 1 char diff
  1389. expect("error" in result).toBe(true);
  1390. if ("error" in result) {
  1391. expect(result.error).toBe("not_found");
  1392. // Levenshtein distance of 1 should be found with maxDistance 3
  1393. expect(result.similarFiles.length).toBeGreaterThanOrEqual(0); // May or may not find depending on distance calc
  1394. }
  1395. await cleanupTestDb(store);
  1396. });
  1397. test("findDocument handles :line suffix", async () => {
  1398. const store = await createTestStore();
  1399. const collectionName = await createTestCollection();
  1400. await insertTestDocument(store.db, collectionName, {
  1401. name: "mydoc",
  1402. filepath: "/path/mydoc.md",
  1403. displayPath: "mydoc.md",
  1404. });
  1405. const result = store.findDocument("mydoc.md:100");
  1406. expect("error" in result).toBe(false);
  1407. await cleanupTestDb(store);
  1408. });
  1409. test("findDocument expands ~ to home directory", async () => {
  1410. const store = await createTestStore();
  1411. const home = homedir();
  1412. const collectionName = await createTestCollection({ pwd: home, name: "home" });
  1413. await insertTestDocument(store.db, collectionName, {
  1414. name: "mydoc",
  1415. filepath: `${home}/docs/mydoc.md`,
  1416. displayPath: "docs/mydoc.md",
  1417. });
  1418. const result = store.findDocument("~/docs/mydoc.md");
  1419. expect("error" in result).toBe(false);
  1420. await cleanupTestDb(store);
  1421. });
  1422. test("findDocument includes context from path_contexts", async () => {
  1423. const store = await createTestStore();
  1424. const collectionName = await createTestCollection({ pwd: "/path" });
  1425. await addPathContext(collectionName, "docs", "Documentation");
  1426. await insertTestDocument(store.db, collectionName, {
  1427. name: "mydoc",
  1428. displayPath: "docs/mydoc.md",
  1429. });
  1430. const result = store.findDocument("/path/docs/mydoc.md");
  1431. expect("error" in result).toBe(false);
  1432. if (!("error" in result)) {
  1433. expect(result.context).toBe("Documentation");
  1434. }
  1435. await cleanupTestDb(store);
  1436. });
  1437. test("findDocument includes hierarchical contexts (global + collection + path)", async () => {
  1438. const store = await createTestStore();
  1439. const collectionName = await createTestCollection({ pwd: "/archive", name: "archive" });
  1440. // Add global context
  1441. await addGlobalContext("Global context for all documents");
  1442. // Add collection root context
  1443. await addPathContext(collectionName, "/", "Archive collection context");
  1444. // Add path-specific contexts at different levels
  1445. await addPathContext(collectionName, "/podcasts", "Podcast episodes");
  1446. await addPathContext(collectionName, "/podcasts/external", "External podcast interviews");
  1447. // Insert document in nested path
  1448. await insertTestDocument(store.db, collectionName, {
  1449. name: "interview",
  1450. displayPath: "podcasts/external/2024-jan-interview.md",
  1451. });
  1452. const result = store.findDocument("/archive/podcasts/external/2024-jan-interview.md");
  1453. expect("error" in result).toBe(false);
  1454. if (!("error" in result)) {
  1455. // Should have all contexts joined with double newlines
  1456. expect(result.context).toBe(
  1457. "Global context for all documents\n\n" +
  1458. "Archive collection context\n\n" +
  1459. "Podcast episodes\n\n" +
  1460. "External podcast interviews"
  1461. );
  1462. }
  1463. await cleanupTestDb(store);
  1464. });
  1465. });
  1466. describe("getDocumentBody", () => {
  1467. test("getDocumentBody returns full body", async () => {
  1468. const store = await createTestStore();
  1469. const collectionName = await createTestCollection({ pwd: "/path" });
  1470. await insertTestDocument(store.db, collectionName, {
  1471. name: "mydoc",
  1472. displayPath: "mydoc.md",
  1473. body: "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
  1474. });
  1475. const body = store.getDocumentBody({ filepath: "/path/mydoc.md" });
  1476. expect(body).toBe("Line 1\nLine 2\nLine 3\nLine 4\nLine 5");
  1477. await cleanupTestDb(store);
  1478. });
  1479. test("getDocumentBody supports line range", async () => {
  1480. const store = await createTestStore();
  1481. const collectionName = await createTestCollection({ pwd: "/path" });
  1482. await insertTestDocument(store.db, collectionName, {
  1483. name: "mydoc",
  1484. displayPath: "mydoc.md",
  1485. body: "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
  1486. });
  1487. const body = store.getDocumentBody({ filepath: "/path/mydoc.md" }, 2, 2);
  1488. expect(body).toBe("Line 2\nLine 3");
  1489. await cleanupTestDb(store);
  1490. });
  1491. test("getDocumentBody returns null for non-existent document", async () => {
  1492. const store = await createTestStore();
  1493. const body = store.getDocumentBody({ filepath: "/nonexistent.md" });
  1494. expect(body).toBeNull();
  1495. await cleanupTestDb(store);
  1496. });
  1497. });
  1498. describe("findDocuments (multi-get)", () => {
  1499. test("findDocuments finds by glob pattern", async () => {
  1500. const store = await createTestStore();
  1501. const collectionName = await createTestCollection();
  1502. await insertTestDocument(store.db, collectionName, {
  1503. name: "doc1",
  1504. filepath: "/path/journals/2024-01.md",
  1505. displayPath: "journals/2024-01.md",
  1506. });
  1507. await insertTestDocument(store.db, collectionName, {
  1508. name: "doc2",
  1509. filepath: "/path/journals/2024-02.md",
  1510. displayPath: "journals/2024-02.md",
  1511. });
  1512. await insertTestDocument(store.db, collectionName, {
  1513. name: "doc3",
  1514. filepath: "/path/other/file.md",
  1515. displayPath: "other/file.md",
  1516. });
  1517. const { docs, errors } = store.findDocuments("journals/2024-*.md");
  1518. expect(errors).toHaveLength(0);
  1519. expect(docs).toHaveLength(2);
  1520. await cleanupTestDb(store);
  1521. });
  1522. test("findDocuments finds by comma-separated list", async () => {
  1523. const store = await createTestStore();
  1524. const collectionName = await createTestCollection();
  1525. await insertTestDocument(store.db, collectionName, {
  1526. name: "doc1",
  1527. filepath: "/path/doc1.md",
  1528. displayPath: "doc1.md",
  1529. });
  1530. await insertTestDocument(store.db, collectionName, {
  1531. name: "doc2",
  1532. filepath: "/path/doc2.md",
  1533. displayPath: "doc2.md",
  1534. });
  1535. const { docs, errors } = store.findDocuments("doc1.md, doc2.md");
  1536. expect(errors).toHaveLength(0);
  1537. expect(docs).toHaveLength(2);
  1538. await cleanupTestDb(store);
  1539. });
  1540. test("findDocuments reports errors for not found files", async () => {
  1541. const store = await createTestStore();
  1542. const collectionName = await createTestCollection();
  1543. await insertTestDocument(store.db, collectionName, {
  1544. name: "doc1",
  1545. filepath: "/path/doc1.md",
  1546. displayPath: "doc1.md",
  1547. });
  1548. const { docs, errors } = store.findDocuments("doc1.md, nonexistent.md");
  1549. expect(docs).toHaveLength(1);
  1550. expect(errors).toHaveLength(1);
  1551. expect(errors[0]).toContain("not found");
  1552. await cleanupTestDb(store);
  1553. });
  1554. test("findDocuments skips large files", async () => {
  1555. const store = await createTestStore();
  1556. const collectionName = await createTestCollection();
  1557. await insertTestDocument(store.db, collectionName, {
  1558. name: "large",
  1559. filepath: "/path/large.md",
  1560. displayPath: "large.md",
  1561. body: "x".repeat(20000), // 20KB
  1562. });
  1563. const { docs } = store.findDocuments("large.md", { maxBytes: 10000 });
  1564. expect(docs).toHaveLength(1);
  1565. expect(docs[0]!.skipped).toBe(true);
  1566. if (docs[0]!.skipped) {
  1567. expect((docs[0] as { skipped: true; skipReason: string }).skipReason).toContain("too large");
  1568. }
  1569. await cleanupTestDb(store);
  1570. });
  1571. test("findDocuments includes body when requested", async () => {
  1572. const store = await createTestStore();
  1573. const collectionName = await createTestCollection();
  1574. await insertTestDocument(store.db, collectionName, {
  1575. name: "doc1",
  1576. filepath: "/path/doc1.md",
  1577. displayPath: "doc1.md",
  1578. body: "The content",
  1579. });
  1580. const { docs } = store.findDocuments("doc1.md", { includeBody: true });
  1581. expect(docs[0]!.skipped).toBe(false);
  1582. if (!docs[0]!.skipped) {
  1583. expect((docs[0] as { doc: { body: string }; skipped: false }).doc.body).toBe("The content");
  1584. }
  1585. await cleanupTestDb(store);
  1586. });
  1587. test("findDocuments supports brace expansion patterns", async () => {
  1588. const store = await createTestStore();
  1589. const collectionName = await createTestCollection();
  1590. await insertTestDocument(store.db, collectionName, {
  1591. name: "doc1",
  1592. filepath: "/path/doc1.md",
  1593. displayPath: "doc1.md",
  1594. });
  1595. await insertTestDocument(store.db, collectionName, {
  1596. name: "doc2",
  1597. filepath: "/path/doc2.md",
  1598. displayPath: "doc2.md",
  1599. });
  1600. await insertTestDocument(store.db, collectionName, {
  1601. name: "doc3",
  1602. filepath: "/path/doc3.md",
  1603. displayPath: "doc3.md",
  1604. });
  1605. const { docs, errors } = store.findDocuments("{doc1,doc2}.md");
  1606. expect(errors).toHaveLength(0);
  1607. expect(docs).toHaveLength(2);
  1608. await cleanupTestDb(store);
  1609. });
  1610. test("findDocuments supports brace expansion with collection prefix", async () => {
  1611. const store = await createTestStore();
  1612. const collectionName = await createTestCollection();
  1613. await insertTestDocument(store.db, collectionName, {
  1614. name: "readme",
  1615. filepath: "/path/readme.md",
  1616. displayPath: "readme.md",
  1617. });
  1618. await insertTestDocument(store.db, collectionName, {
  1619. name: "changelog",
  1620. filepath: "/path/changelog.md",
  1621. displayPath: "changelog.md",
  1622. });
  1623. const { docs, errors } = store.findDocuments(`${collectionName}/{readme,changelog}.md`);
  1624. expect(errors).toHaveLength(0);
  1625. expect(docs).toHaveLength(2);
  1626. await cleanupTestDb(store);
  1627. });
  1628. });
  1629. });
  1630. // =============================================================================
  1631. // Snippet Extraction Tests
  1632. // =============================================================================
  1633. describe("Snippet Extraction", () => {
  1634. test("extractSnippet finds query terms", () => {
  1635. const body = "First line.\nSecond line with keyword.\nThird line.\nFourth line.";
  1636. const { line, snippet } = extractSnippet(body, "keyword", 500);
  1637. expect(line).toBe(2); // Line 2 contains "keyword"
  1638. expect(snippet).toContain("keyword");
  1639. });
  1640. test("extractSnippet includes context lines", () => {
  1641. const body = "Line 1\nLine 2\nLine 3 has keyword\nLine 4\nLine 5";
  1642. const { snippet } = extractSnippet(body, "keyword", 500);
  1643. expect(snippet).toContain("Line 2"); // Context before
  1644. expect(snippet).toContain("Line 3 has keyword");
  1645. expect(snippet).toContain("Line 4"); // Context after
  1646. });
  1647. test("extractSnippet respects maxLen for content", () => {
  1648. const body = "A".repeat(1000);
  1649. const result = extractSnippet(body, "query", 100);
  1650. // Snippet includes header + content, content should be truncated
  1651. expect(result.snippet).toContain("@@"); // Has diff header
  1652. expect(result.snippet).toContain("..."); // Content was truncated
  1653. });
  1654. test("extractSnippet uses chunkPos hint", () => {
  1655. const body = "First section...\n".repeat(50) + "Target keyword here\n" + "More content...".repeat(50);
  1656. const chunkPos = body.indexOf("Target keyword");
  1657. const { snippet } = extractSnippet(body, "Target", 200, chunkPos);
  1658. expect(snippet).toContain("Target keyword");
  1659. });
  1660. test("extractSnippet returns beginning when no match", () => {
  1661. const body = "First line\nSecond line\nThird line";
  1662. const { line, snippet } = extractSnippet(body, "nonexistent", 500);
  1663. expect(line).toBe(1);
  1664. expect(snippet).toContain("First line");
  1665. });
  1666. test("extractSnippet includes diff-style header", () => {
  1667. const body = "Line 1\nLine 2\nLine 3 has keyword\nLine 4\nLine 5";
  1668. const { snippet, linesBefore, linesAfter, snippetLines } = extractSnippet(body, "keyword", 500);
  1669. // Header should show line position and context info
  1670. expect(snippet).toMatch(/^@@ -\d+,\d+ @@ \(\d+ before, \d+ after\)/);
  1671. expect(linesBefore).toBe(1); // Line 1 comes before
  1672. expect(linesAfter).toBe(0); // Snippet includes to end (lines 2-5)
  1673. expect(snippetLines).toBe(4); // Lines 2, 3, 4, 5
  1674. });
  1675. test("extractSnippet calculates linesBefore and linesAfter correctly", () => {
  1676. const body = "L1\nL2\nL3\nL4 match\nL5\nL6\nL7\nL8\nL9\nL10";
  1677. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "match", 500);
  1678. expect(line).toBe(4); // "L4 match" is line 4
  1679. expect(linesBefore).toBe(2); // L1, L2 before snippet (snippet starts at L3)
  1680. expect(snippetLines).toBe(4); // L3, L4, L5, L6
  1681. expect(linesAfter).toBe(4); // L7, L8, L9, L10 after snippet
  1682. });
  1683. test("extractSnippet header format matches diff style", () => {
  1684. const body = "A\nB\nC keyword\nD\nE\nF\nG\nH";
  1685. const { snippet } = extractSnippet(body, "keyword", 500);
  1686. // Should start with @@ -line,count @@ (N before, M after)
  1687. const headerMatch = snippet.match(/^@@ -(\d+),(\d+) @@ \((\d+) before, (\d+) after\)/);
  1688. expect(headerMatch).not.toBeNull();
  1689. const [, startLine, count, before, after] = headerMatch!;
  1690. expect(parseInt(startLine!)).toBe(2); // Snippet starts at line 2 (B)
  1691. expect(parseInt(count!)).toBe(4); // 4 lines: B, C keyword, D, E
  1692. expect(parseInt(before!)).toBe(1); // A is before
  1693. expect(parseInt(after!)).toBe(3); // F, G, H are after
  1694. });
  1695. test("extractSnippet at document start shows 0 before", () => {
  1696. const body = "First line keyword\nSecond\nThird\nFourth\nFifth";
  1697. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "keyword", 500);
  1698. expect(line).toBe(1); // Keyword on first line
  1699. expect(linesBefore).toBe(0); // Nothing before
  1700. expect(snippetLines).toBe(3); // First, Second, Third (bestLine-1 to bestLine+3, clamped)
  1701. expect(linesAfter).toBe(2); // Fourth, Fifth
  1702. });
  1703. test("extractSnippet at document end shows 0 after", () => {
  1704. const body = "First\nSecond\nThird\nFourth\nFifth keyword";
  1705. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "keyword", 500);
  1706. expect(line).toBe(5); // Keyword on last line
  1707. expect(linesBefore).toBe(3); // First, Second, Third before snippet
  1708. expect(snippetLines).toBe(2); // Fourth, Fifth keyword (bestLine-1 to bestLine+3, clamped)
  1709. expect(linesAfter).toBe(0); // Nothing after
  1710. });
  1711. test("extractSnippet with single line document", () => {
  1712. const body = "Single line with keyword";
  1713. const { linesBefore, linesAfter, snippetLines, snippet } = extractSnippet(body, "keyword", 500);
  1714. expect(linesBefore).toBe(0);
  1715. expect(linesAfter).toBe(0);
  1716. expect(snippetLines).toBe(1);
  1717. expect(snippet).toContain("@@ -1,1 @@ (0 before, 0 after)");
  1718. expect(snippet).toContain("Single line with keyword");
  1719. });
  1720. test("extractSnippet with chunkPos adjusts line numbers correctly", () => {
  1721. // 50 lines of padding, then keyword, then more content
  1722. const padding = "Padding line\n".repeat(50);
  1723. const body = padding + "Target keyword here\nMore content\nEven more";
  1724. const chunkPos = padding.length; // Position of "Target keyword"
  1725. const { line, linesBefore, linesAfter } = extractSnippet(body, "keyword", 200, chunkPos);
  1726. expect(line).toBe(51); // "Target keyword" is line 51
  1727. expect(linesBefore).toBeGreaterThan(40); // Many lines before
  1728. });
  1729. });
  1730. // =============================================================================
  1731. // Reciprocal Rank Fusion Tests
  1732. // =============================================================================
  1733. describe("Reciprocal Rank Fusion", () => {
  1734. const makeResult = (file: string, score: number): RankedResult => ({
  1735. file,
  1736. displayPath: file,
  1737. title: file,
  1738. body: "body",
  1739. score,
  1740. });
  1741. test("RRF combines single list correctly", () => {
  1742. const list1 = [
  1743. makeResult("doc1", 0.9),
  1744. makeResult("doc2", 0.8),
  1745. makeResult("doc3", 0.7),
  1746. ];
  1747. const fused = reciprocalRankFusion([list1]);
  1748. // Order should be preserved
  1749. expect(fused[0]!.file).toBe("doc1");
  1750. expect(fused[1]!.file).toBe("doc2");
  1751. expect(fused[2]!.file).toBe("doc3");
  1752. });
  1753. test("RRF merges documents from multiple lists", () => {
  1754. const list1 = [makeResult("doc1", 0.9), makeResult("doc2", 0.8)];
  1755. const list2 = [makeResult("doc2", 0.95), makeResult("doc3", 0.85)];
  1756. const fused = reciprocalRankFusion([list1, list2]);
  1757. // doc2 appears in both lists, should have higher combined score
  1758. expect(fused.find(r => r.file === "doc2")).toBeDefined();
  1759. expect(fused.find(r => r.file === "doc1")).toBeDefined();
  1760. expect(fused.find(r => r.file === "doc3")).toBeDefined();
  1761. });
  1762. test("RRF respects weights", () => {
  1763. const list1 = [makeResult("doc1", 0.9)];
  1764. const list2 = [makeResult("doc2", 0.9)];
  1765. // Give double weight to list1
  1766. const fused = reciprocalRankFusion([list1, list2], [2.0, 1.0]);
  1767. // doc1 should rank higher due to weight
  1768. expect(fused[0]!.file).toBe("doc1");
  1769. });
  1770. test("RRF adds top-rank bonus", () => {
  1771. // doc1 is #1 in list1, doc2 is #2 in list1
  1772. const list1 = [makeResult("doc1", 0.9), makeResult("doc2", 0.8)];
  1773. const list2 = [makeResult("doc3", 0.85)];
  1774. const fused = reciprocalRankFusion([list1, list2]);
  1775. // doc1 should get +0.05 bonus for being #1
  1776. // doc2 should get +0.02 bonus for being #2-3
  1777. const doc1 = fused.find(r => r.file === "doc1");
  1778. const doc2 = fused.find(r => r.file === "doc2");
  1779. expect(doc1!.score).toBeGreaterThan(doc2!.score);
  1780. });
  1781. test("RRF handles empty lists", () => {
  1782. const fused = reciprocalRankFusion([[], []]);
  1783. expect(fused).toHaveLength(0);
  1784. });
  1785. test("RRF uses k parameter correctly", () => {
  1786. const list = [makeResult("doc1", 0.9)];
  1787. // With different k values, scores should differ
  1788. const fused60 = reciprocalRankFusion([list], [], 60);
  1789. const fused30 = reciprocalRankFusion([list], [], 30);
  1790. // Lower k = higher scores for top ranks
  1791. expect(fused30[0]!.score).toBeGreaterThan(fused60[0]!.score);
  1792. });
  1793. });
  1794. // =============================================================================
  1795. // Index Status Tests
  1796. // =============================================================================
  1797. describe("Index Status", () => {
  1798. test("getStatus returns correct structure", async () => {
  1799. const store = await createTestStore();
  1800. const status = store.getStatus();
  1801. expect(status).toHaveProperty("totalDocuments");
  1802. expect(status).toHaveProperty("needsEmbedding");
  1803. expect(status).toHaveProperty("hasVectorIndex");
  1804. expect(status).toHaveProperty("collections");
  1805. expect(Array.isArray(status.collections)).toBe(true);
  1806. await cleanupTestDb(store);
  1807. });
  1808. test("getStatus counts documents correctly", async () => {
  1809. const store = await createTestStore();
  1810. const collectionName = await createTestCollection();
  1811. await insertTestDocument(store.db, collectionName, { name: "doc1", active: 1 });
  1812. await insertTestDocument(store.db, collectionName, { name: "doc2", active: 1 });
  1813. await insertTestDocument(store.db, collectionName, { name: "doc3", active: 0 }); // inactive
  1814. const status = store.getStatus();
  1815. expect(status.totalDocuments).toBe(2); // Only active docs
  1816. await cleanupTestDb(store);
  1817. });
  1818. test("getStatus reports collection info", async () => {
  1819. const store = await createTestStore();
  1820. const collectionName = await createTestCollection({ pwd: "/test/path", glob: "**/*.md" });
  1821. await insertTestDocument(store.db, collectionName, { name: "doc1" });
  1822. const status = store.getStatus();
  1823. expect(status.collections.length).toBeGreaterThanOrEqual(1);
  1824. const col = status.collections.find(c => c.name === collectionName);
  1825. expect(col).toBeDefined();
  1826. expect(col?.path).toBe("/test/path");
  1827. expect(col?.pattern).toBe("**/*.md");
  1828. expect(col?.documents).toBe(1);
  1829. await cleanupTestDb(store);
  1830. });
  1831. test("getHashesNeedingEmbedding counts correctly", async () => {
  1832. const store = await createTestStore();
  1833. const collectionName = await createTestCollection();
  1834. // Add documents with different hashes
  1835. await insertTestDocument(store.db, collectionName, { name: "doc1", hash: "hash1" });
  1836. await insertTestDocument(store.db, collectionName, { name: "doc2", hash: "hash2" });
  1837. await insertTestDocument(store.db, collectionName, { name: "doc3", hash: "hash1" }); // same hash as doc1
  1838. const needsEmbedding = store.getHashesNeedingEmbedding();
  1839. expect(needsEmbedding).toBe(2); // hash1 and hash2
  1840. await cleanupTestDb(store);
  1841. });
  1842. test("getIndexHealth returns health info", async () => {
  1843. const store = await createTestStore();
  1844. const collectionName = await createTestCollection();
  1845. await insertTestDocument(store.db, collectionName, { name: "doc1" });
  1846. const health = store.getIndexHealth();
  1847. expect(health).toHaveProperty("needsEmbedding");
  1848. expect(health).toHaveProperty("totalDocs");
  1849. expect(health).toHaveProperty("daysStale");
  1850. expect(health.totalDocs).toBe(1);
  1851. await cleanupTestDb(store);
  1852. });
  1853. });
  1854. // =============================================================================
  1855. // Fuzzy Matching Tests
  1856. // =============================================================================
  1857. describe("Fuzzy Matching", () => {
  1858. test("findSimilarFiles finds similar paths", async () => {
  1859. const store = await createTestStore();
  1860. const collectionName = await createTestCollection();
  1861. await insertTestDocument(store.db, collectionName, {
  1862. name: "readme",
  1863. displayPath: "docs/readme.md",
  1864. });
  1865. await insertTestDocument(store.db, collectionName, {
  1866. name: "readmi",
  1867. displayPath: "docs/readmi.md", // typo
  1868. });
  1869. const similar = store.findSimilarFiles("docs/readme.md", 3, 5);
  1870. expect(similar).toContain("docs/readme.md");
  1871. await cleanupTestDb(store);
  1872. });
  1873. test("findSimilarFiles respects maxDistance", async () => {
  1874. const store = await createTestStore();
  1875. const collectionName = await createTestCollection();
  1876. await insertTestDocument(store.db, collectionName, {
  1877. name: "abc",
  1878. displayPath: "abc.md",
  1879. });
  1880. await insertTestDocument(store.db, collectionName, {
  1881. name: "xyz",
  1882. displayPath: "xyz.md", // very different
  1883. });
  1884. const similar = store.findSimilarFiles("abc.md", 1, 5); // max distance 1
  1885. expect(similar).toContain("abc.md");
  1886. expect(similar).not.toContain("xyz.md");
  1887. await cleanupTestDb(store);
  1888. });
  1889. test("matchFilesByGlob matches patterns", async () => {
  1890. const store = await createTestStore();
  1891. const collectionName = await createTestCollection();
  1892. await insertTestDocument(store.db, collectionName, {
  1893. filepath: "/p/journals/2024-01.md",
  1894. displayPath: "journals/2024-01.md",
  1895. });
  1896. await insertTestDocument(store.db, collectionName, {
  1897. filepath: "/p/journals/2024-02.md",
  1898. displayPath: "journals/2024-02.md",
  1899. });
  1900. await insertTestDocument(store.db, collectionName, {
  1901. filepath: "/p/docs/readme.md",
  1902. displayPath: "docs/readme.md",
  1903. });
  1904. const matches = store.matchFilesByGlob("journals/*.md");
  1905. expect(matches).toHaveLength(2);
  1906. expect(matches.every(m => m.displayPath.startsWith("journals/"))).toBe(true);
  1907. await cleanupTestDb(store);
  1908. });
  1909. test("matchFilesByGlob matches collection/path patterns", async () => {
  1910. const store = await createTestStore();
  1911. const collectionName = await createTestCollection();
  1912. await insertTestDocument(store.db, collectionName, {
  1913. filepath: "/p/readme.md",
  1914. displayPath: "readme.md",
  1915. });
  1916. await insertTestDocument(store.db, collectionName, {
  1917. filepath: "/p/changelog.md",
  1918. displayPath: "changelog.md",
  1919. });
  1920. const matches = store.matchFilesByGlob(`${collectionName}/*.md`);
  1921. expect(matches).toHaveLength(2);
  1922. await cleanupTestDb(store);
  1923. });
  1924. test("matchFilesByGlob matches brace expansion", async () => {
  1925. const store = await createTestStore();
  1926. const collectionName = await createTestCollection();
  1927. await insertTestDocument(store.db, collectionName, {
  1928. filepath: "/p/readme.md",
  1929. displayPath: "readme.md",
  1930. });
  1931. await insertTestDocument(store.db, collectionName, {
  1932. filepath: "/p/changelog.md",
  1933. displayPath: "changelog.md",
  1934. });
  1935. await insertTestDocument(store.db, collectionName, {
  1936. filepath: "/p/license.md",
  1937. displayPath: "license.md",
  1938. });
  1939. const matches = store.matchFilesByGlob(`${collectionName}/{readme,changelog}.md`);
  1940. expect(matches).toHaveLength(2);
  1941. await cleanupTestDb(store);
  1942. });
  1943. });
  1944. // =============================================================================
  1945. // Vector Table Tests
  1946. // =============================================================================
  1947. describe("Vector Table", () => {
  1948. test("ensureVecTable creates vector table", async () => {
  1949. const store = await createTestStore();
  1950. // Initially no vector table
  1951. let exists = store.db.prepare(`
  1952. SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1953. `).get();
  1954. expect(exists).toBeFalsy(); // null or undefined
  1955. // Create vector table
  1956. store.ensureVecTable(768);
  1957. exists = store.db.prepare(`
  1958. SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1959. `).get();
  1960. expect(exists).toBeTruthy();
  1961. await cleanupTestDb(store);
  1962. });
  1963. test("ensureVecTable throws on dimension mismatch instead of silently rebuilding", async () => {
  1964. const store = await createTestStore();
  1965. // Create with 768 dimensions
  1966. store.ensureVecTable(768);
  1967. // Check dimensions
  1968. const tableInfo = store.db.prepare(`
  1969. SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1970. `).get() as { sql: string };
  1971. expect(tableInfo.sql).toContain("float[768]");
  1972. // Attempting to use a different dimension should throw (not silently drop data)
  1973. expect(() => store.ensureVecTable(1024)).toThrow(/dimension mismatch/i);
  1974. // Original table should still exist untouched
  1975. const tableInfoAfter = store.db.prepare(`
  1976. SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1977. `).get() as { sql: string };
  1978. expect(tableInfoAfter.sql).toContain("float[768]");
  1979. await cleanupTestDb(store);
  1980. });
  1981. });
  1982. // =============================================================================
  1983. // Integration Tests
  1984. // =============================================================================
  1985. describe("Integration", () => {
  1986. test("full document lifecycle: create, search, retrieve", async () => {
  1987. const store = await createTestStore();
  1988. const collectionName = await createTestCollection({ pwd: "/test/notes", glob: "**/*.md" });
  1989. // Add context - use "/" for collection root
  1990. await addPathContext(collectionName, "/", "Personal notes");
  1991. // Insert documents
  1992. await insertTestDocument(store.db, collectionName, {
  1993. name: "meeting",
  1994. title: "Team Meeting Notes",
  1995. filepath: "/test/notes/meeting.md",
  1996. displayPath: "notes/meeting.md",
  1997. body: "# Team Meeting Notes\n\nDiscussed project timeline and deliverables.",
  1998. });
  1999. await insertTestDocument(store.db, collectionName, {
  2000. name: "ideas",
  2001. title: "Project Ideas",
  2002. filepath: "/test/notes/ideas.md",
  2003. displayPath: "notes/ideas.md",
  2004. body: "# Project Ideas\n\nBrainstorming new features for the product.",
  2005. });
  2006. // Search
  2007. const searchResults = store.searchFTS("project", 10);
  2008. expect(searchResults.length).toBe(2);
  2009. // Status - SKIPPED: getStatus() has bug (queries non-existent collections table)
  2010. // const status = store.getStatus();
  2011. // expect(status.totalDocuments).toBe(2);
  2012. // expect(status.collections).toHaveLength(1);
  2013. // Retrieve single document
  2014. const doc = store.findDocument("notes/meeting.md", { includeBody: true });
  2015. expect("error" in doc).toBe(false);
  2016. if (!("error" in doc)) {
  2017. expect(doc.title).toBe("Team Meeting Notes");
  2018. expect(doc.context).toBe("Personal notes");
  2019. expect(doc.body).toContain("Team Meeting");
  2020. }
  2021. // Multi-get
  2022. const { docs, errors } = store.findDocuments("notes/*.md", { includeBody: true });
  2023. expect(errors).toHaveLength(0);
  2024. expect(docs).toHaveLength(2);
  2025. await cleanupTestDb(store);
  2026. });
  2027. test("multiple stores can operate independently", async () => {
  2028. const store1 = await createTestStore();
  2029. const store2 = await createTestStore();
  2030. const col1 = await createTestCollection({ pwd: "/store1", glob: "**/*.md", name: "store1" });
  2031. const col2 = await createTestCollection({ pwd: "/store2", glob: "**/*.md", name: "store2" });
  2032. await insertTestDocument(store1.db, col1, {
  2033. name: "doc1",
  2034. body: "unique content for store1",
  2035. displayPath: "doc.md",
  2036. });
  2037. await insertTestDocument(store2.db, col2, {
  2038. name: "doc2",
  2039. body: "different content for store2",
  2040. displayPath: "doc.md",
  2041. });
  2042. // Each store should only see its own documents
  2043. const results1 = store1.searchFTS("unique", 10);
  2044. const results2 = store2.searchFTS("different", 10);
  2045. expect(results1).toHaveLength(1);
  2046. expect(results1[0]!.displayPath).toBe("store1/doc.md");
  2047. expect(results1[0]!.filepath).toBe("qmd://store1/doc.md");
  2048. expect(results2).toHaveLength(1);
  2049. expect(results2[0]!.displayPath).toBe("store2/doc.md");
  2050. expect(results2[0]!.filepath).toBe("qmd://store2/doc.md");
  2051. // Cross-check: store1 shouldn't find store2's content
  2052. const cross1 = store1.searchFTS("different", 10);
  2053. const cross2 = store2.searchFTS("unique", 10);
  2054. expect(cross1).toHaveLength(0);
  2055. expect(cross2).toHaveLength(0);
  2056. await cleanupTestDb(store1);
  2057. await cleanupTestDb(store2);
  2058. });
  2059. });
  2060. // =============================================================================
  2061. // LlamaCpp Integration Tests (using real local models)
  2062. // =============================================================================
  2063. describe.skipIf(!!process.env.CI)("LlamaCpp Integration", () => {
  2064. test("searchVec returns empty when no vector index", async () => {
  2065. const store = await createTestStore();
  2066. const collectionName = await createTestCollection();
  2067. await insertTestDocument(store.db, collectionName, {
  2068. name: "doc1",
  2069. body: "Some content",
  2070. });
  2071. // No vectors_vec table exists, should return empty
  2072. const results = await store.searchVec("query", "embeddinggemma", 10);
  2073. expect(results).toHaveLength(0);
  2074. await cleanupTestDb(store);
  2075. });
  2076. test("searchVec returns results when vector index exists", async () => {
  2077. const store = await createTestStore();
  2078. const collectionName = await createTestCollection();
  2079. const hash = "testhash123";
  2080. await insertTestDocument(store.db, collectionName, {
  2081. name: "doc1",
  2082. hash,
  2083. body: "Some content about testing",
  2084. filepath: "/test/doc1.md",
  2085. displayPath: "doc1.md",
  2086. });
  2087. // Create vector table and insert a vector
  2088. store.ensureVecTable(768);
  2089. const embedding = Array(768).fill(0).map(() => Math.random());
  2090. store.db.prepare(`INSERT INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, 0, 0, 'test', ?)`).run(hash, new Date().toISOString());
  2091. store.db.prepare(`INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`).run(`${hash}_0`, new Float32Array(embedding));
  2092. const results = await store.searchVec("test query", "embeddinggemma", 10);
  2093. expect(results).toHaveLength(1);
  2094. expect(results[0]!.displayPath).toBe(`${collectionName}/doc1.md`);
  2095. expect(results[0]!.filepath).toBe(`qmd://${collectionName}/doc1.md`);
  2096. expect(results[0]!.source).toBe("vec");
  2097. await cleanupTestDb(store);
  2098. });
  2099. test("searchVec filters by collection name", async () => {
  2100. const store = await createTestStore();
  2101. const collection1 = await createTestCollection({ name: "coll1", pwd: "/test/coll1" });
  2102. const collection2 = await createTestCollection({ name: "coll2", pwd: "/test/coll2" });
  2103. const hash1 = "hash1abc";
  2104. const hash2 = "hash2xyz";
  2105. await insertTestDocument(store.db, collection1, {
  2106. name: "doc1",
  2107. hash: hash1,
  2108. body: "Content in collection one",
  2109. });
  2110. await insertTestDocument(store.db, collection2, {
  2111. name: "doc2",
  2112. hash: hash2,
  2113. body: "Content in collection two",
  2114. });
  2115. // Create vectors_vec table with correct dimensions (768 for embeddinggemma)
  2116. store.ensureVecTable(768);
  2117. const embedding1 = Array(768).fill(0).map(() => Math.random());
  2118. const embedding2 = Array(768).fill(0).map(() => Math.random());
  2119. store.db.prepare(`INSERT INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, 0, 0, 'test', ?)`).run(hash1, new Date().toISOString());
  2120. store.db.prepare(`INSERT INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, 0, 0, 'test', ?)`).run(hash2, new Date().toISOString());
  2121. store.db.prepare(`INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`).run(`${hash1}_0`, new Float32Array(embedding1));
  2122. store.db.prepare(`INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`).run(`${hash2}_0`, new Float32Array(embedding2));
  2123. // Search without filter - should return both
  2124. const allResults = await store.searchVec("content", "embeddinggemma", 10);
  2125. expect(allResults).toHaveLength(2);
  2126. // Search with collection filter - should return only from collection1
  2127. const filtered = await store.searchVec("content", "embeddinggemma", 10, collection1);
  2128. expect(filtered).toHaveLength(1);
  2129. expect(filtered[0]!.collectionName).toBe(collection1);
  2130. await cleanupTestDb(store);
  2131. });
  2132. // Regression test for https://github.com/tobi/qmd/pull/23
  2133. // sqlite-vec virtual tables hang when combined with JOINs in the same query.
  2134. // The fix uses a two-step approach: vector query first, then separate JOINs.
  2135. test("searchVec uses two-step query to avoid sqlite-vec JOIN hang", async () => {
  2136. const store = await createTestStore();
  2137. const collectionName = await createTestCollection();
  2138. const hash = "regression_test_hash";
  2139. await insertTestDocument(store.db, collectionName, {
  2140. name: "regression-doc",
  2141. hash,
  2142. body: "Test content for vector search regression",
  2143. filepath: "/test/regression.md",
  2144. displayPath: "regression.md",
  2145. });
  2146. // Create vector table and insert a test vector
  2147. store.ensureVecTable(768);
  2148. const embedding = Array(768).fill(0).map(() => Math.random());
  2149. store.db.prepare(`INSERT INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, 0, 0, 'test', ?)`).run(hash, new Date().toISOString());
  2150. store.db.prepare(`INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`).run(`${hash}_0`, new Float32Array(embedding));
  2151. // This should complete quickly (not hang) due to the two-step fix
  2152. // The old code with JOINs in the sqlite-vec query would hang indefinitely
  2153. const startTime = Date.now();
  2154. const results = await store.searchVec("test content", "embeddinggemma", 5);
  2155. const elapsed = Date.now() - startTime;
  2156. // If the query took more than 5 seconds, something is wrong
  2157. // (the hang bug would cause it to never return at all)
  2158. expect(elapsed).toBeLessThan(5000);
  2159. expect(results.length).toBeGreaterThan(0);
  2160. await cleanupTestDb(store);
  2161. });
  2162. test("expandQuery returns typed expansions (no original query)", async () => {
  2163. const store = await createTestStore();
  2164. const expanded = await store.expandQuery("test query");
  2165. // Returns ExpandedQuery[] — typed results from LLM, excluding original
  2166. expect(expanded.length).toBeGreaterThanOrEqual(1);
  2167. for (const q of expanded) {
  2168. expect(['lex', 'vec', 'hyde']).toContain(q.type);
  2169. expect(q.query.length).toBeGreaterThan(0);
  2170. expect(q.query).not.toBe("test query"); // original excluded
  2171. }
  2172. await cleanupTestDb(store);
  2173. }, 30000);
  2174. test("expandQuery caches results as JSON with types", async () => {
  2175. const store = await createTestStore();
  2176. // First call — hits LLM
  2177. const queries1 = await store.expandQuery("cached query test");
  2178. // Second call — hits cache
  2179. const queries2 = await store.expandQuery("cached query test");
  2180. // Cache should preserve full typed structure
  2181. expect(queries1).toEqual(queries2);
  2182. expect(queries2[0]?.type).toBeDefined();
  2183. await cleanupTestDb(store);
  2184. }, 30000);
  2185. test("rerank scores documents", async () => {
  2186. const store = await createTestStore();
  2187. const docs = [
  2188. { file: "doc1.md", text: "Relevant content about the topic" },
  2189. { file: "doc2.md", text: "Other content" },
  2190. ];
  2191. const results = await store.rerank("topic", docs);
  2192. expect(results).toHaveLength(2);
  2193. // LlamaCpp reranker returns relevance scores
  2194. expect(results[0]!.score).toBeGreaterThan(0);
  2195. await cleanupTestDb(store);
  2196. });
  2197. test("rerank caches results", async () => {
  2198. const store = await createTestStore();
  2199. const docs = [{ file: "doc1.md", text: "Content for caching test" }];
  2200. // First call
  2201. await store.rerank("cache test query", docs);
  2202. // Second call - should hit cache
  2203. const results = await store.rerank("cache test query", docs);
  2204. expect(results).toHaveLength(1);
  2205. await cleanupTestDb(store);
  2206. });
  2207. test("rerank deduplicates identical chunks across files", async () => {
  2208. const store = await createTestStore();
  2209. const rerankSpy = vi.fn(async (_query: string, docs: { file: string; text: string }[]) => ({
  2210. results: docs.map((doc, index) => ({
  2211. file: doc.file,
  2212. score: 1 - index * 0.1,
  2213. index,
  2214. })),
  2215. model: "mock-reranker",
  2216. }));
  2217. const llmSpy = vi.spyOn(llmModule, "getDefaultLlamaCpp").mockReturnValue({
  2218. rerank: rerankSpy,
  2219. } as any);
  2220. try {
  2221. const docs = [
  2222. { file: "doc1.md", text: "Shared chunk text" },
  2223. { file: "doc2.md", text: "Shared chunk text" },
  2224. ];
  2225. const first = await store.rerank("shared", docs);
  2226. const second = await store.rerank("shared", docs);
  2227. expect(first).toHaveLength(2);
  2228. expect(second).toHaveLength(2);
  2229. expect(rerankSpy).toHaveBeenCalledTimes(1);
  2230. expect(rerankSpy.mock.calls[0]?.[1]).toEqual([{ file: "doc2.md", text: "Shared chunk text" }]);
  2231. } finally {
  2232. llmSpy.mockRestore();
  2233. await cleanupTestDb(store);
  2234. }
  2235. });
  2236. });
  2237. // =============================================================================
  2238. // Edge Cases & Error Handling
  2239. // =============================================================================
  2240. describe("Edge Cases", () => {
  2241. test("handles empty database gracefully", async () => {
  2242. const store = await createTestStore();
  2243. const searchResults = store.searchFTS("anything", 10);
  2244. expect(searchResults).toHaveLength(0);
  2245. // SKIPPED: getStatus() has bug (queries non-existent collections table)
  2246. // const status = store.getStatus();
  2247. // expect(status.totalDocuments).toBe(0);
  2248. // expect(status.collections).toHaveLength(0);
  2249. const doc = store.findDocument("nonexistent.md");
  2250. expect("error" in doc).toBe(true);
  2251. await cleanupTestDb(store);
  2252. });
  2253. test("handles very long document bodies", async () => {
  2254. const store = await createTestStore();
  2255. const collectionName = await createTestCollection();
  2256. const longBody = "word ".repeat(100000); // ~600KB
  2257. await insertTestDocument(store.db, collectionName, {
  2258. name: "long",
  2259. body: longBody,
  2260. displayPath: "long.md",
  2261. });
  2262. const results = store.searchFTS("word", 10);
  2263. expect(results).toHaveLength(1);
  2264. await cleanupTestDb(store);
  2265. });
  2266. test("handles unicode content correctly", async () => {
  2267. const store = await createTestStore();
  2268. const collectionName = await createTestCollection();
  2269. await insertTestDocument(store.db, collectionName, {
  2270. name: "unicode",
  2271. title: "日本語タイトル",
  2272. body: "# 日本語\n\n内容は日本語で書かれています。\n\nEmoji: 🎉🚀✨",
  2273. displayPath: "unicode.md",
  2274. });
  2275. // Should be searchable
  2276. const results = store.searchFTS("日本語", 10);
  2277. expect(results.length).toBeGreaterThan(0);
  2278. // Should retrieve correctly
  2279. const doc = store.findDocument("unicode.md", { includeBody: true });
  2280. expect("error" in doc).toBe(false);
  2281. if (!("error" in doc)) {
  2282. expect(doc.title).toBe("日本語タイトル");
  2283. expect(doc.body).toContain("🎉");
  2284. }
  2285. await cleanupTestDb(store);
  2286. });
  2287. test("handles documents with special characters in paths", async () => {
  2288. const store = await createTestStore();
  2289. const collectionName = await createTestCollection();
  2290. await insertTestDocument(store.db, collectionName, {
  2291. name: "special",
  2292. filepath: "/path/file with spaces.md",
  2293. displayPath: "file with spaces.md",
  2294. body: "Content",
  2295. });
  2296. const doc = store.findDocument("file with spaces.md");
  2297. expect("error" in doc).toBe(false);
  2298. await cleanupTestDb(store);
  2299. });
  2300. test("handles concurrent operations", async () => {
  2301. const store = await createTestStore();
  2302. const collectionName = await createTestCollection();
  2303. // Insert multiple documents concurrently
  2304. const inserts = Array.from({ length: 10 }, (_, i) =>
  2305. insertTestDocument(store.db, collectionName, {
  2306. name: `concurrent${i}`,
  2307. body: `Content ${i} searchterm`,
  2308. displayPath: `concurrent${i}.md`,
  2309. })
  2310. );
  2311. await Promise.all(inserts);
  2312. // All should be searchable
  2313. const results = store.searchFTS("searchterm", 20);
  2314. expect(results).toHaveLength(10);
  2315. await cleanupTestDb(store);
  2316. });
  2317. });
  2318. describe("Embedding batching", () => {
  2319. function createFakeTokenizer() {
  2320. return {
  2321. async tokenize(text: string) {
  2322. return new Array(Math.max(1, Math.ceil(text.length / 16))).fill(1);
  2323. },
  2324. };
  2325. }
  2326. function createFakeEmbedLlm() {
  2327. const embedBatchCalls: string[][] = [];
  2328. const embedCalls: { text: string; options?: { model?: string } }[] = [];
  2329. const embedBatchModelCalls: ({ model?: string } | undefined)[] = [];
  2330. return {
  2331. embedBatchCalls,
  2332. embedCalls,
  2333. embedBatchModelCalls,
  2334. async embed(text: string, options?: { model?: string }) {
  2335. embedCalls.push({ text, options });
  2336. return { embedding: [0.1, 0.2, 0.3], model: "fake-embed" };
  2337. },
  2338. async embedBatch(texts: string[], options?: { model?: string }) {
  2339. embedBatchCalls.push([...texts]);
  2340. embedBatchModelCalls.push(options);
  2341. return texts.map((_text, index) => ({
  2342. embedding: [index + 1, index + 2, index + 3],
  2343. model: "fake-embed",
  2344. }));
  2345. },
  2346. };
  2347. }
  2348. test("generateEmbeddings flushes batches when maxDocsPerBatch is reached", async () => {
  2349. const store = await createTestStore();
  2350. const db = store.db;
  2351. const fakeLlm = createFakeEmbedLlm();
  2352. setDefaultLlamaCpp(createFakeTokenizer() as any);
  2353. store.llm = fakeLlm as any;
  2354. try {
  2355. await insertTestDocument(db, "docs", { name: "one", body: "# One\n\nAlpha" });
  2356. await insertTestDocument(db, "docs", { name: "two", body: "# Two\n\nBeta" });
  2357. await insertTestDocument(db, "docs", { name: "three", body: "# Three\n\nGamma" });
  2358. const result = await generateEmbeddings(store, {
  2359. maxDocsPerBatch: 1,
  2360. maxBatchBytes: 1024 * 1024,
  2361. });
  2362. expect(fakeLlm.embedBatchCalls).toHaveLength(3);
  2363. expect(fakeLlm.embedBatchCalls.map(call => call.length)).toEqual([1, 1, 1]);
  2364. expect(result.docsProcessed).toBe(3);
  2365. expect(result.chunksEmbedded).toBe(3);
  2366. expect(db.prepare(`SELECT COUNT(*) as count FROM content_vectors`).get()).toEqual({ count: 3 });
  2367. } finally {
  2368. setDefaultLlamaCpp(null);
  2369. await cleanupTestDb(store);
  2370. }
  2371. });
  2372. test("generateEmbeddings flushes batches when maxBatchBytes is reached", async () => {
  2373. const store = await createTestStore();
  2374. const db = store.db;
  2375. const fakeLlm = createFakeEmbedLlm();
  2376. setDefaultLlamaCpp(createFakeTokenizer() as any);
  2377. store.llm = fakeLlm as any;
  2378. const docOne = "# One\n\n" + "A".repeat(36);
  2379. const docTwo = "# Two\n\n" + "B".repeat(36);
  2380. const docThree = "# Three\n\n" + "C".repeat(36);
  2381. const batchLimit = new TextEncoder().encode(docOne).length
  2382. + new TextEncoder().encode(docTwo).length
  2383. + 1;
  2384. try {
  2385. await insertTestDocument(db, "docs", { name: "a-one", body: docOne });
  2386. await insertTestDocument(db, "docs", { name: "b-two", body: docTwo });
  2387. await insertTestDocument(db, "docs", { name: "c-three", body: docThree });
  2388. const result = await generateEmbeddings(store, {
  2389. maxDocsPerBatch: 64,
  2390. maxBatchBytes: batchLimit,
  2391. });
  2392. expect(fakeLlm.embedBatchCalls).toHaveLength(2);
  2393. expect(fakeLlm.embedBatchCalls.map(call => call.length)).toEqual([2, 1]);
  2394. expect(result.docsProcessed).toBe(3);
  2395. expect(result.chunksEmbedded).toBe(3);
  2396. } finally {
  2397. setDefaultLlamaCpp(null);
  2398. await cleanupTestDb(store);
  2399. }
  2400. });
  2401. test("generateEmbeddings passes the selected model through to embed calls and metadata", async () => {
  2402. const store = await createTestStore();
  2403. const db = store.db;
  2404. const fakeLlm = createFakeEmbedLlm();
  2405. const model = "hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf";
  2406. setDefaultLlamaCpp(createFakeTokenizer() as any);
  2407. store.llm = fakeLlm as any;
  2408. try {
  2409. await insertTestDocument(db, "docs", { name: "one", body: "# One\n\nAlpha" });
  2410. const result = await generateEmbeddings(store, { model });
  2411. expect(result.chunksEmbedded).toBe(1);
  2412. expect(fakeLlm.embedCalls[0]?.options?.model).toBe(model);
  2413. expect(fakeLlm.embedBatchModelCalls).toEqual([{ model }]);
  2414. expect(db.prepare(`SELECT DISTINCT model FROM content_vectors`).all()).toEqual([{ model }]);
  2415. } finally {
  2416. setDefaultLlamaCpp(null);
  2417. await cleanupTestDb(store);
  2418. }
  2419. });
  2420. test("generateEmbeddings rejects invalid batch limits", async () => {
  2421. const store = await createTestStore();
  2422. try {
  2423. await expect(generateEmbeddings(store, { maxDocsPerBatch: 0 })).rejects.toThrow(
  2424. "maxDocsPerBatch"
  2425. );
  2426. await expect(generateEmbeddings(store, { maxBatchBytes: 0 })).rejects.toThrow(
  2427. "maxBatchBytes"
  2428. );
  2429. } finally {
  2430. setDefaultLlamaCpp(null);
  2431. await cleanupTestDb(store);
  2432. }
  2433. });
  2434. });
  2435. // =============================================================================
  2436. // Content-Addressable Storage Tests
  2437. // =============================================================================
  2438. describe("Content-Addressable Storage", () => {
  2439. test("same content gets same hash from multiple collections", async () => {
  2440. const store = await createTestStore();
  2441. // Create two collections
  2442. const collection1 = await createTestCollection({ pwd: "/path/collection1", name: "collection1" });
  2443. const collection2 = await createTestCollection({ pwd: "/path/collection2", name: "collection2" });
  2444. // Add same content to both collections
  2445. const content = "# Same Content\n\nThis is the same content in two places.";
  2446. const hash1 = await hashContent(content);
  2447. const doc1 = await insertTestDocument(store.db, collection1, {
  2448. name: "doc1",
  2449. body: content,
  2450. displayPath: "doc1.md",
  2451. });
  2452. const doc2 = await insertTestDocument(store.db, collection2, {
  2453. name: "doc2",
  2454. body: content,
  2455. displayPath: "doc2.md",
  2456. });
  2457. // Both should have the same hash
  2458. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  2459. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  2460. expect(hash1Db.hash).toBe(hash2Db.hash);
  2461. expect(hash1Db.hash).toBe(hash1);
  2462. // There should only be one entry in the content table
  2463. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(hash1) as { count: number };
  2464. expect(contentCount.count).toBe(1);
  2465. await cleanupTestDb(store);
  2466. });
  2467. test("removing one collection preserves content used by another", async () => {
  2468. const store = await createTestStore();
  2469. // Create two collections
  2470. const collection1 = await createTestCollection({ pwd: "/path/collection1", name: "collection1" });
  2471. const collection2 = await createTestCollection({ pwd: "/path/collection2", name: "collection2" });
  2472. // Add same content to both collections
  2473. const sharedContent = "# Shared Content\n\nThis is shared.";
  2474. const sharedHash = await hashContent(sharedContent);
  2475. await insertTestDocument(store.db, collection1, {
  2476. name: "shared1",
  2477. body: sharedContent,
  2478. displayPath: "shared1.md",
  2479. });
  2480. await insertTestDocument(store.db, collection2, {
  2481. name: "shared2",
  2482. body: sharedContent,
  2483. displayPath: "shared2.md",
  2484. });
  2485. // Add unique content to collection1
  2486. const uniqueContent = "# Unique Content\n\nThis is unique to collection1.";
  2487. const uniqueHash = await hashContent(uniqueContent);
  2488. await insertTestDocument(store.db, collection1, {
  2489. name: "unique",
  2490. body: uniqueContent,
  2491. displayPath: "unique.md",
  2492. });
  2493. // Verify both hashes exist in content table
  2494. const sharedExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  2495. const uniqueExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  2496. expect(sharedExists1).toBeTruthy();
  2497. expect(uniqueExists1).toBeTruthy();
  2498. // Remove collection1 documents (collections are in YAML now)
  2499. store.db.prepare(`DELETE FROM documents WHERE collection = ?`).run(collection1);
  2500. // Clean up orphaned content (mimics what the CLI does)
  2501. store.db.prepare(`
  2502. DELETE FROM content
  2503. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  2504. `).run();
  2505. // Shared content should still exist (used by collection2)
  2506. const sharedExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  2507. expect(sharedExists2).toBeTruthy();
  2508. // Unique content should be removed (only used by collection1)
  2509. const uniqueExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  2510. expect(uniqueExists2).toBeFalsy();
  2511. await cleanupTestDb(store);
  2512. });
  2513. test("deduplicates content across many collections", async () => {
  2514. const store = await createTestStore();
  2515. const sharedContent = "# Common Header\n\nThis appears everywhere.";
  2516. const sharedHash = await hashContent(sharedContent);
  2517. // Create 5 collections with the same content
  2518. const collectionNames = [];
  2519. for (let i = 0; i < 5; i++) {
  2520. const collName = await createTestCollection({ pwd: `/path/collection${i}`, name: `collection${i}` });
  2521. collectionNames.push(collName);
  2522. await insertTestDocument(store.db, collName, {
  2523. name: `doc${i}`,
  2524. body: sharedContent,
  2525. displayPath: `doc${i}.md`,
  2526. });
  2527. }
  2528. // Should have 5 documents
  2529. const docCount = store.db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number };
  2530. expect(docCount.count).toBe(5);
  2531. // But only 1 content entry
  2532. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(sharedHash) as { count: number };
  2533. expect(contentCount.count).toBe(1);
  2534. // All documents should point to the same hash
  2535. const hashes = store.db.prepare(`SELECT DISTINCT hash FROM documents WHERE active = 1`).all() as { hash: string }[];
  2536. expect(hashes).toHaveLength(1);
  2537. expect(hashes[0]!.hash).toBe(sharedHash);
  2538. await cleanupTestDb(store);
  2539. });
  2540. test("different content gets different hashes", async () => {
  2541. const store = await createTestStore();
  2542. const collectionName = await createTestCollection();
  2543. const content1 = "# Content One";
  2544. const content2 = "# Content Two";
  2545. const hash1 = await hashContent(content1);
  2546. const hash2 = await hashContent(content2);
  2547. // Hashes should be different
  2548. expect(hash1).not.toBe(hash2);
  2549. const doc1 = await insertTestDocument(store.db, collectionName, {
  2550. name: "doc1",
  2551. body: content1,
  2552. displayPath: "doc1.md",
  2553. });
  2554. const doc2 = await insertTestDocument(store.db, collectionName, {
  2555. name: "doc2",
  2556. body: content2,
  2557. displayPath: "doc2.md",
  2558. });
  2559. // Both hashes should exist in content table
  2560. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  2561. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  2562. expect(hash1Db.hash).toBe(hash1);
  2563. expect(hash2Db.hash).toBe(hash2);
  2564. expect(hash1Db.hash).not.toBe(hash2Db.hash);
  2565. // Should have 2 entries in content table
  2566. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content`).get() as { count: number };
  2567. expect(contentCount.count).toBe(2);
  2568. await cleanupTestDb(store);
  2569. });
  2570. test("re-indexing a previously deactivated path reactivates instead of violating UNIQUE", async () => {
  2571. const store = await createTestStore();
  2572. const collectionName = await createTestCollection();
  2573. const now = new Date().toISOString();
  2574. const oldContent = "# First Version";
  2575. const oldHash = await hashContent(oldContent);
  2576. store.insertContent(oldHash, oldContent, now);
  2577. store.insertDocument(collectionName, "docs/foo.md", "foo", oldHash, now, now);
  2578. // Simulate file removal during update pass.
  2579. store.deactivateDocument(collectionName, "docs/foo.md");
  2580. expect(store.findActiveDocument(collectionName, "docs/foo.md")).toBeNull();
  2581. // Simulate file coming back in a later update pass.
  2582. const newContent = "# Second Version";
  2583. const newHash = await hashContent(newContent);
  2584. store.insertContent(newHash, newContent, now);
  2585. expect(() => {
  2586. store.insertDocument(collectionName, "docs/foo.md", "foo", newHash, now, now);
  2587. }).not.toThrow();
  2588. const rows = store.db.prepare(`
  2589. SELECT id, hash, active FROM documents
  2590. WHERE collection = ? AND path = ?
  2591. `).all(collectionName, "docs/foo.md") as { id: number; hash: string; active: number }[];
  2592. expect(rows).toHaveLength(1);
  2593. expect(rows[0]!.active).toBe(1);
  2594. expect(rows[0]!.hash).toBe(newHash);
  2595. await cleanupTestDb(store);
  2596. });
  2597. });
  2598. // =============================================================================
  2599. // Virtual Path Normalization Tests
  2600. // =============================================================================
  2601. describe("normalizeVirtualPath", () => {
  2602. test("already normalized qmd:// path passes through", () => {
  2603. expect(normalizeVirtualPath("qmd://collection/path.md")).toBe("qmd://collection/path.md");
  2604. expect(normalizeVirtualPath("qmd://journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2605. });
  2606. test("handles //collection/path format (missing qmd: prefix)", () => {
  2607. expect(normalizeVirtualPath("//collection/path.md")).toBe("qmd://collection/path.md");
  2608. expect(normalizeVirtualPath("//journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2609. });
  2610. test("handles qmd:// with extra slashes", () => {
  2611. expect(normalizeVirtualPath("qmd:////collection/path.md")).toBe("qmd://collection/path.md");
  2612. expect(normalizeVirtualPath("qmd:///journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2613. expect(normalizeVirtualPath("qmd:///////archive/file.md")).toBe("qmd://archive/file.md");
  2614. });
  2615. test("handles collection root paths", () => {
  2616. expect(normalizeVirtualPath("qmd://collection/")).toBe("qmd://collection/");
  2617. expect(normalizeVirtualPath("qmd://collection")).toBe("qmd://collection");
  2618. expect(normalizeVirtualPath("//collection/")).toBe("qmd://collection/");
  2619. });
  2620. test("preserves bare collection/path format (not auto-converted)", () => {
  2621. // Bare paths without qmd:// or // prefix are NOT converted
  2622. // (could be relative filesystem paths)
  2623. expect(normalizeVirtualPath("collection/path.md")).toBe("collection/path.md");
  2624. expect(normalizeVirtualPath("journals/2025-01-01.md")).toBe("journals/2025-01-01.md");
  2625. });
  2626. test("preserves absolute filesystem paths", () => {
  2627. expect(normalizeVirtualPath("/Users/test/file.md")).toBe("/Users/test/file.md");
  2628. expect(normalizeVirtualPath("/absolute/path/file.md")).toBe("/absolute/path/file.md");
  2629. });
  2630. test("preserves home-relative paths", () => {
  2631. expect(normalizeVirtualPath("~/Documents/file.md")).toBe("~/Documents/file.md");
  2632. });
  2633. test("preserves docid format", () => {
  2634. expect(normalizeVirtualPath("#abc123")).toBe("#abc123");
  2635. expect(normalizeVirtualPath("#def456")).toBe("#def456");
  2636. });
  2637. test("handles whitespace trimming", () => {
  2638. expect(normalizeVirtualPath(" qmd://collection/path.md ")).toBe("qmd://collection/path.md");
  2639. expect(normalizeVirtualPath(" //collection/path.md ")).toBe("qmd://collection/path.md");
  2640. });
  2641. });
  2642. describe("isVirtualPath", () => {
  2643. test("recognizes qmd:// paths", () => {
  2644. expect(isVirtualPath("qmd://collection/path.md")).toBe(true);
  2645. expect(isVirtualPath("qmd://journals/2025-01-01.md")).toBe(true);
  2646. expect(isVirtualPath("qmd://collection")).toBe(true);
  2647. });
  2648. test("recognizes //collection/path format", () => {
  2649. expect(isVirtualPath("//collection/path.md")).toBe(true);
  2650. expect(isVirtualPath("//journals/2025-01-01.md")).toBe(true);
  2651. });
  2652. test("does not auto-recognize bare collection/path format", () => {
  2653. // Bare paths could be relative filesystem paths, so not auto-detected as virtual
  2654. expect(isVirtualPath("collection/path.md")).toBe(false);
  2655. expect(isVirtualPath("journals/2025-01-01.md")).toBe(false);
  2656. expect(isVirtualPath("archive/subfolder/file.md")).toBe(false);
  2657. });
  2658. test("rejects docid format", () => {
  2659. expect(isVirtualPath("#abc123")).toBe(false);
  2660. expect(isVirtualPath("#def456")).toBe(false);
  2661. });
  2662. test("rejects absolute filesystem paths", () => {
  2663. expect(isVirtualPath("/Users/test/file.md")).toBe(false);
  2664. expect(isVirtualPath("/absolute/path/file.md")).toBe(false);
  2665. });
  2666. test("rejects home-relative paths", () => {
  2667. expect(isVirtualPath("~/Documents/file.md")).toBe(false);
  2668. expect(isVirtualPath("~/notes/journal.md")).toBe(false);
  2669. });
  2670. test("rejects paths without slashes", () => {
  2671. expect(isVirtualPath("file.md")).toBe(false);
  2672. expect(isVirtualPath("document")).toBe(false);
  2673. });
  2674. });
  2675. describe("parseVirtualPath", () => {
  2676. test("parses standard qmd:// paths", () => {
  2677. expect(parseVirtualPath("qmd://collection/path.md")).toEqual({
  2678. collectionName: "collection",
  2679. path: "path.md",
  2680. });
  2681. expect(parseVirtualPath("qmd://journals/2025-01-01.md")).toEqual({
  2682. collectionName: "journals",
  2683. path: "2025-01-01.md",
  2684. });
  2685. });
  2686. test("parses paths with nested directories", () => {
  2687. expect(parseVirtualPath("qmd://archive/subfolder/file.md")).toEqual({
  2688. collectionName: "archive",
  2689. path: "subfolder/file.md",
  2690. });
  2691. });
  2692. test("parses collection root paths", () => {
  2693. expect(parseVirtualPath("qmd://collection/")).toEqual({
  2694. collectionName: "collection",
  2695. path: "",
  2696. });
  2697. expect(parseVirtualPath("qmd://collection")).toEqual({
  2698. collectionName: "collection",
  2699. path: "",
  2700. });
  2701. });
  2702. test("parses //collection/path format (normalizes first)", () => {
  2703. expect(parseVirtualPath("//collection/path.md")).toEqual({
  2704. collectionName: "collection",
  2705. path: "path.md",
  2706. });
  2707. });
  2708. test("parses qmd:// with extra slashes (normalizes first)", () => {
  2709. expect(parseVirtualPath("qmd:////collection/path.md")).toEqual({
  2710. collectionName: "collection",
  2711. path: "path.md",
  2712. });
  2713. });
  2714. test("returns null for non-virtual paths", () => {
  2715. expect(parseVirtualPath("/absolute/path.md")).toBe(null);
  2716. expect(parseVirtualPath("~/home/path.md")).toBe(null);
  2717. expect(parseVirtualPath("#docid")).toBe(null);
  2718. expect(parseVirtualPath("file.md")).toBe(null);
  2719. // Bare collection/path is not recognized as virtual
  2720. expect(parseVirtualPath("collection/path.md")).toBe(null);
  2721. });
  2722. });
  2723. // =============================================================================
  2724. // Docid Functions
  2725. // =============================================================================
  2726. describe("normalizeDocid", () => {
  2727. test("strips leading # from docid", () => {
  2728. expect(normalizeDocid("#abc123")).toBe("abc123");
  2729. expect(normalizeDocid("#def456")).toBe("def456");
  2730. });
  2731. test("returns bare hex unchanged", () => {
  2732. expect(normalizeDocid("abc123")).toBe("abc123");
  2733. expect(normalizeDocid("def456")).toBe("def456");
  2734. });
  2735. test("strips surrounding double quotes", () => {
  2736. expect(normalizeDocid('"#abc123"')).toBe("abc123");
  2737. expect(normalizeDocid('"abc123"')).toBe("abc123");
  2738. });
  2739. test("strips surrounding single quotes", () => {
  2740. expect(normalizeDocid("'#abc123'")).toBe("abc123");
  2741. expect(normalizeDocid("'abc123'")).toBe("abc123");
  2742. });
  2743. test("handles quoted docid without #", () => {
  2744. expect(normalizeDocid('"def456"')).toBe("def456");
  2745. expect(normalizeDocid("'def456'")).toBe("def456");
  2746. });
  2747. test("handles whitespace", () => {
  2748. expect(normalizeDocid(" #abc123 ")).toBe("abc123");
  2749. expect(normalizeDocid(" abc123 ")).toBe("abc123");
  2750. });
  2751. test("handles uppercase hex", () => {
  2752. expect(normalizeDocid("#ABC123")).toBe("ABC123");
  2753. expect(normalizeDocid('"ABC123"')).toBe("ABC123");
  2754. });
  2755. test("does not strip mismatched quotes", () => {
  2756. expect(normalizeDocid('"abc123\'')).toBe('"abc123\'');
  2757. expect(normalizeDocid("'abc123\"")).toBe("'abc123\"");
  2758. });
  2759. });
  2760. describe("isDocid", () => {
  2761. test("accepts #hash format", () => {
  2762. expect(isDocid("#abc123")).toBe(true);
  2763. expect(isDocid("#def456")).toBe(true);
  2764. expect(isDocid("#ABCDEF")).toBe(true);
  2765. });
  2766. test("accepts bare 6-char hex", () => {
  2767. expect(isDocid("abc123")).toBe(true);
  2768. expect(isDocid("def456")).toBe(true);
  2769. expect(isDocid("ABCDEF")).toBe(true);
  2770. });
  2771. test("accepts longer hex strings", () => {
  2772. expect(isDocid("abc123def456")).toBe(true);
  2773. expect(isDocid("#abc123def456")).toBe(true);
  2774. });
  2775. test("accepts double-quoted docids", () => {
  2776. expect(isDocid('"#abc123"')).toBe(true);
  2777. expect(isDocid('"abc123"')).toBe(true);
  2778. });
  2779. test("accepts single-quoted docids", () => {
  2780. expect(isDocid("'#abc123'")).toBe(true);
  2781. expect(isDocid("'abc123'")).toBe(true);
  2782. });
  2783. test("rejects non-hex strings", () => {
  2784. expect(isDocid("ghijkl")).toBe(false);
  2785. expect(isDocid("#ghijkl")).toBe(false);
  2786. expect(isDocid("abc12g")).toBe(false);
  2787. });
  2788. test("rejects strings shorter than 6 chars", () => {
  2789. expect(isDocid("abc12")).toBe(false);
  2790. expect(isDocid("#abc1")).toBe(false);
  2791. expect(isDocid("'abc'")).toBe(false);
  2792. });
  2793. test("rejects empty strings", () => {
  2794. expect(isDocid("")).toBe(false);
  2795. expect(isDocid("#")).toBe(false);
  2796. expect(isDocid('""')).toBe(false);
  2797. });
  2798. test("rejects file paths", () => {
  2799. expect(isDocid("/path/to/file.md")).toBe(false);
  2800. expect(isDocid("path/to/file.md")).toBe(false);
  2801. expect(isDocid("qmd://collection/file.md")).toBe(false);
  2802. });
  2803. test("rejects paths that look like hex with extensions", () => {
  2804. expect(isDocid("abc123.md")).toBe(false);
  2805. });
  2806. });