store.test.ts 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  1. /**
  2. * store.test.ts - Comprehensive unit tests for the QMD store module
  3. *
  4. * Run with: bun test store.test.ts
  5. *
  6. * Ollama is mocked - tests will fail if any real Ollama calls are made.
  7. */
  8. import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, mock, spyOn } from "bun:test";
  9. import { Database } from "bun:sqlite";
  10. import { unlink, mkdtemp, rmdir } from "node:fs/promises";
  11. import { tmpdir } from "node:os";
  12. import { join } from "node:path";
  13. import {
  14. createStore,
  15. getDefaultDbPath,
  16. homedir,
  17. resolve,
  18. getPwd,
  19. getRealPath,
  20. hashContent,
  21. extractTitle,
  22. formatQueryForEmbedding,
  23. formatDocForEmbedding,
  24. chunkDocument,
  25. reciprocalRankFusion,
  26. extractSnippet,
  27. getCacheKey,
  28. OLLAMA_URL,
  29. type Store,
  30. type DocumentResult,
  31. type SearchResult,
  32. type RankedResult,
  33. } from "./store.js";
  34. // =============================================================================
  35. // Ollama Mocking
  36. // =============================================================================
  37. // Track original fetch
  38. const originalFetch = globalThis.fetch;
  39. // Mock responses for different Ollama endpoints
  40. const mockOllamaResponses: Record<string, (body: unknown) => Response> = {
  41. "/api/embed": (body: unknown) => {
  42. // Return mock embeddings (768 dimensions)
  43. const embedding = Array(768).fill(0).map(() => Math.random());
  44. return new Response(JSON.stringify({ embeddings: [embedding] }), {
  45. status: 200,
  46. headers: { "Content-Type": "application/json" },
  47. });
  48. },
  49. "/api/generate": (body: unknown) => {
  50. const reqBody = body as { prompt?: string };
  51. // Check if this is a rerank request or query expansion
  52. if (reqBody.prompt?.includes("yes") || reqBody.prompt?.includes("no") || reqBody.prompt?.includes("Judge")) {
  53. // Rerank response
  54. return new Response(JSON.stringify({
  55. response: "yes",
  56. logprobs: [{ token: "yes", logprob: -0.1 }],
  57. }), {
  58. status: 200,
  59. headers: { "Content-Type": "application/json" },
  60. });
  61. } else {
  62. // Query expansion response
  63. return new Response(JSON.stringify({
  64. response: "expanded query variation 1\nexpanded query variation 2",
  65. }), {
  66. status: 200,
  67. headers: { "Content-Type": "application/json" },
  68. });
  69. }
  70. },
  71. "/api/show": () => {
  72. // Model exists
  73. return new Response(JSON.stringify({ modelfile: "exists" }), {
  74. status: 200,
  75. headers: { "Content-Type": "application/json" },
  76. });
  77. },
  78. };
  79. // Install mock fetch that intercepts Ollama calls
  80. function installOllamaMock(): void {
  81. globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
  82. const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
  83. // Check if this is an Ollama URL
  84. if (url.startsWith(OLLAMA_URL)) {
  85. const path = url.replace(OLLAMA_URL, "");
  86. const mockHandler = mockOllamaResponses[path];
  87. if (mockHandler) {
  88. const body = init?.body ? JSON.parse(init.body as string) : {};
  89. return mockHandler(body);
  90. }
  91. // Unknown Ollama endpoint - fail the test
  92. throw new Error(`TEST ERROR: Unmocked Ollama endpoint called: ${path}`);
  93. }
  94. // Non-Ollama URLs fail (we shouldn't be making other network calls in tests)
  95. throw new Error(`TEST ERROR: Unexpected network call to: ${url}`);
  96. };
  97. }
  98. // Restore original fetch
  99. function restoreOllamaMock(): void {
  100. globalThis.fetch = originalFetch;
  101. }
  102. // Install mock before all tests
  103. beforeAll(() => {
  104. installOllamaMock();
  105. });
  106. // Restore after all tests
  107. afterAll(() => {
  108. restoreOllamaMock();
  109. });
  110. // =============================================================================
  111. // Test Utilities
  112. // =============================================================================
  113. let testDir: string;
  114. let testDbPath: string;
  115. async function createTestStore(): Promise<Store> {
  116. testDbPath = join(testDir, `test-${Date.now()}-${Math.random().toString(36).slice(2)}.sqlite`);
  117. return createStore(testDbPath);
  118. }
  119. async function cleanupTestDb(store: Store): Promise<void> {
  120. store.close();
  121. try {
  122. await unlink(store.dbPath);
  123. } catch {
  124. // Ignore if file doesn't exist
  125. }
  126. }
  127. // Helper to insert a test document directly into the database
  128. async function insertTestDocument(
  129. db: Database,
  130. collectionId: number,
  131. opts: {
  132. name?: string;
  133. title?: string;
  134. hash?: string;
  135. displayPath?: string;
  136. body?: string;
  137. active?: number;
  138. }
  139. ): Promise<number> {
  140. const now = new Date().toISOString();
  141. const name = opts.name || "test-doc";
  142. const title = opts.title || "Test Document";
  143. const path = opts.displayPath || `test/${name}.md`;
  144. const body = opts.body || "# Test Document\n\nThis is test content.";
  145. const active = opts.active ?? 1;
  146. // Generate hash from body if not provided
  147. const hash = opts.hash || await hashContent(body);
  148. // Insert content (with OR IGNORE for deduplication)
  149. db.prepare(`
  150. INSERT OR IGNORE INTO content (hash, doc, created_at)
  151. VALUES (?, ?, ?)
  152. `).run(hash, body, now);
  153. // Insert document
  154. const result = db.prepare(`
  155. INSERT INTO documents (collection_id, path, title, hash, created_at, modified_at, active)
  156. VALUES (?, ?, ?, ?, ?, ?, ?)
  157. `).run(collectionId, path, title, hash, now, now, active);
  158. return Number(result.lastInsertRowid);
  159. }
  160. // Helper to create a test collection
  161. function createTestCollection(
  162. db: Database,
  163. options: { pwd?: string; glob?: string; name?: string } = {}
  164. ): number {
  165. const pwd = options.pwd || "/test/collection";
  166. const glob = options.glob || "**/*.md";
  167. const name = options.name || pwd.split('/').filter(Boolean).pop() || 'test';
  168. const now = new Date().toISOString();
  169. const result = db.prepare(`
  170. INSERT INTO collections (name, pwd, glob_pattern, created_at, updated_at)
  171. VALUES (?, ?, ?, ?, ?)
  172. `).run(name, pwd, glob, now, now);
  173. return Number(result.lastInsertRowid);
  174. }
  175. // Helper to add path context
  176. function addPathContext(db: Database, pathPrefix: string, context: string): void {
  177. const now = new Date().toISOString();
  178. db.prepare(`
  179. INSERT OR REPLACE INTO path_contexts (path_prefix, context, created_at)
  180. VALUES (?, ?, ?)
  181. `).run(pathPrefix, context, now);
  182. }
  183. // =============================================================================
  184. // Test Setup
  185. // =============================================================================
  186. beforeAll(async () => {
  187. testDir = await mkdtemp(join(tmpdir(), "qmd-test-"));
  188. });
  189. afterAll(async () => {
  190. try {
  191. // Clean up test directory
  192. const { readdir, unlink } = await import("node:fs/promises");
  193. const files = await readdir(testDir);
  194. for (const file of files) {
  195. await unlink(join(testDir, file));
  196. }
  197. await rmdir(testDir);
  198. } catch {
  199. // Ignore cleanup errors
  200. }
  201. });
  202. // =============================================================================
  203. // Path Utilities Tests
  204. // =============================================================================
  205. describe("Path Utilities", () => {
  206. test("homedir returns HOME environment variable", () => {
  207. const result = homedir();
  208. expect(result).toBe(Bun.env.HOME || "/tmp");
  209. });
  210. test("resolve handles absolute paths", () => {
  211. expect(resolve("/foo/bar")).toBe("/foo/bar");
  212. expect(resolve("/foo", "/bar")).toBe("/bar");
  213. });
  214. test("resolve handles relative paths", () => {
  215. const pwd = Bun.env.PWD || process.cwd();
  216. expect(resolve("foo")).toBe(`${pwd}/foo`);
  217. expect(resolve("foo", "bar")).toBe(`${pwd}/foo/bar`);
  218. });
  219. test("resolve normalizes . and ..", () => {
  220. expect(resolve("/foo/bar/./baz")).toBe("/foo/bar/baz");
  221. expect(resolve("/foo/bar/../baz")).toBe("/foo/baz");
  222. expect(resolve("/foo/bar/../../baz")).toBe("/baz");
  223. });
  224. test("getDefaultDbPath returns expected path structure", () => {
  225. const defaultPath = getDefaultDbPath();
  226. expect(defaultPath).toContain(".cache/qmd/index.sqlite");
  227. const customPath = getDefaultDbPath("custom");
  228. expect(customPath).toContain(".cache/qmd/custom.sqlite");
  229. });
  230. test("getPwd returns current working directory", () => {
  231. const pwd = getPwd();
  232. expect(pwd).toBeTruthy();
  233. expect(typeof pwd).toBe("string");
  234. });
  235. test("getRealPath resolves symlinks", () => {
  236. const result = getRealPath("/tmp");
  237. expect(result).toBeTruthy();
  238. // On macOS, /tmp is a symlink to /private/tmp
  239. expect(result === "/tmp" || result === "/private/tmp").toBe(true);
  240. });
  241. });
  242. // =============================================================================
  243. // Store Creation Tests
  244. // =============================================================================
  245. describe("Store Creation", () => {
  246. test("createStore creates a new store with default path", () => {
  247. const store = createStore();
  248. expect(store).toBeDefined();
  249. expect(store.db).toBeDefined();
  250. expect(store.dbPath).toContain(".cache/qmd/index.sqlite");
  251. store.close();
  252. });
  253. test("createStore creates a new store with custom path", async () => {
  254. const store = await createTestStore();
  255. expect(store.dbPath).toBe(testDbPath);
  256. expect(store.db).toBeInstanceOf(Database);
  257. await cleanupTestDb(store);
  258. });
  259. test("createStore initializes database schema", async () => {
  260. const store = await createTestStore();
  261. // Check tables exist
  262. const tables = store.db.prepare(`
  263. SELECT name FROM sqlite_master WHERE type='table' ORDER BY name
  264. `).all() as { name: string }[];
  265. const tableNames = tables.map(t => t.name);
  266. expect(tableNames).toContain("collections");
  267. expect(tableNames).toContain("documents");
  268. expect(tableNames).toContain("documents_fts");
  269. expect(tableNames).toContain("content_vectors");
  270. expect(tableNames).toContain("path_contexts");
  271. expect(tableNames).toContain("ollama_cache");
  272. await cleanupTestDb(store);
  273. });
  274. test("createStore sets WAL journal mode", async () => {
  275. const store = await createTestStore();
  276. const result = store.db.prepare("PRAGMA journal_mode").get() as { journal_mode: string };
  277. expect(result.journal_mode).toBe("wal");
  278. await cleanupTestDb(store);
  279. });
  280. test("store.close closes the database connection", async () => {
  281. const store = await createTestStore();
  282. store.close();
  283. // Attempting to use db after close should throw
  284. expect(() => store.db.prepare("SELECT 1").get()).toThrow();
  285. try {
  286. await unlink(testDbPath);
  287. } catch {}
  288. });
  289. });
  290. // =============================================================================
  291. // Document Hashing & Title Extraction Tests
  292. // =============================================================================
  293. describe("Document Helpers", () => {
  294. test("hashContent produces consistent SHA256 hashes", async () => {
  295. const content = "Hello, World!";
  296. const hash1 = await hashContent(content);
  297. const hash2 = await hashContent(content);
  298. expect(hash1).toBe(hash2);
  299. expect(hash1).toMatch(/^[a-f0-9]{64}$/);
  300. });
  301. test("hashContent produces different hashes for different content", async () => {
  302. const hash1 = await hashContent("Hello");
  303. const hash2 = await hashContent("World");
  304. expect(hash1).not.toBe(hash2);
  305. });
  306. test("extractTitle extracts H1 heading", () => {
  307. const content = "# My Title\n\nSome content here.";
  308. expect(extractTitle(content, "file.md")).toBe("My Title");
  309. });
  310. test("extractTitle extracts H2 heading if no H1", () => {
  311. const content = "## My Subtitle\n\nSome content here.";
  312. expect(extractTitle(content, "file.md")).toBe("My Subtitle");
  313. });
  314. test("extractTitle falls back to filename", () => {
  315. const content = "Just some plain text without headings.";
  316. expect(extractTitle(content, "my-document.md")).toBe("my-document");
  317. });
  318. test("extractTitle skips generic 'Notes' heading", () => {
  319. const content = "# Notes\n\n## Actual Title\n\nContent";
  320. expect(extractTitle(content, "file.md")).toBe("Actual Title");
  321. });
  322. test("extractTitle handles 📝 Notes heading", () => {
  323. const content = "# 📝 Notes\n\n## Meeting Summary\n\nContent";
  324. expect(extractTitle(content, "file.md")).toBe("Meeting Summary");
  325. });
  326. });
  327. // =============================================================================
  328. // Embedding Format Tests
  329. // =============================================================================
  330. describe("Embedding Formatting", () => {
  331. test("formatQueryForEmbedding adds search task prefix", () => {
  332. const formatted = formatQueryForEmbedding("how to deploy");
  333. expect(formatted).toBe("task: search result | query: how to deploy");
  334. });
  335. test("formatDocForEmbedding adds title and text prefix", () => {
  336. const formatted = formatDocForEmbedding("Some content", "My Title");
  337. expect(formatted).toBe("title: My Title | text: Some content");
  338. });
  339. test("formatDocForEmbedding handles missing title", () => {
  340. const formatted = formatDocForEmbedding("Some content");
  341. expect(formatted).toBe("title: none | text: Some content");
  342. });
  343. });
  344. // =============================================================================
  345. // Document Chunking Tests
  346. // =============================================================================
  347. describe("Document Chunking", () => {
  348. test("chunkDocument returns single chunk for small documents", () => {
  349. const content = "Small document content";
  350. const chunks = chunkDocument(content, 1000);
  351. expect(chunks).toHaveLength(1);
  352. expect(chunks[0].text).toBe(content);
  353. expect(chunks[0].pos).toBe(0);
  354. });
  355. test("chunkDocument splits large documents", () => {
  356. const content = "A".repeat(10000);
  357. const chunks = chunkDocument(content, 1000);
  358. expect(chunks.length).toBeGreaterThan(1);
  359. // All chunks should have correct positions
  360. for (let i = 0; i < chunks.length; i++) {
  361. expect(chunks[i].pos).toBeGreaterThanOrEqual(0);
  362. if (i > 0) {
  363. expect(chunks[i].pos).toBeGreaterThan(chunks[i - 1].pos);
  364. }
  365. }
  366. });
  367. test("chunkDocument prefers paragraph breaks", () => {
  368. const content = "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.".repeat(50);
  369. const chunks = chunkDocument(content, 500);
  370. // Chunks should end at paragraph breaks when possible
  371. for (const chunk of chunks.slice(0, -1)) {
  372. // Most chunks should end near a paragraph break
  373. const endsNearParagraph = chunk.text.endsWith("\n\n") ||
  374. chunk.text.endsWith(".") ||
  375. chunk.text.endsWith("\n");
  376. // This is a soft check - not all chunks can end at breaks
  377. }
  378. expect(chunks.length).toBeGreaterThan(1);
  379. });
  380. test("chunkDocument handles UTF-8 characters correctly", () => {
  381. const content = "こんにちは世界".repeat(500); // Japanese text
  382. const chunks = chunkDocument(content, 1000);
  383. // Should not split in the middle of a multi-byte character
  384. for (const chunk of chunks) {
  385. expect(() => new TextEncoder().encode(chunk.text)).not.toThrow();
  386. }
  387. });
  388. });
  389. // =============================================================================
  390. // Caching Tests
  391. // =============================================================================
  392. describe("Caching", () => {
  393. test("getCacheKey generates consistent keys", () => {
  394. const key1 = getCacheKey("http://example.com", { query: "test" });
  395. const key2 = getCacheKey("http://example.com", { query: "test" });
  396. expect(key1).toBe(key2);
  397. expect(key1).toMatch(/^[a-f0-9]{64}$/);
  398. });
  399. test("getCacheKey generates different keys for different inputs", () => {
  400. const key1 = getCacheKey("http://example.com", { query: "test1" });
  401. const key2 = getCacheKey("http://example.com", { query: "test2" });
  402. expect(key1).not.toBe(key2);
  403. });
  404. test("store cache operations work correctly", async () => {
  405. const store = await createTestStore();
  406. const key = "test-cache-key";
  407. const value = "cached result";
  408. // Initially empty
  409. expect(store.getCachedResult(key)).toBeNull();
  410. // Set cache
  411. store.setCachedResult(key, value);
  412. // Retrieve cache
  413. expect(store.getCachedResult(key)).toBe(value);
  414. // Clear cache
  415. store.clearCache();
  416. expect(store.getCachedResult(key)).toBeNull();
  417. await cleanupTestDb(store);
  418. });
  419. });
  420. // =============================================================================
  421. // Context Tests
  422. // =============================================================================
  423. describe("Path Context", () => {
  424. test("getContextForFile returns null when no context set", async () => {
  425. const store = await createTestStore();
  426. const context = store.getContextForFile("/some/random/path.md");
  427. expect(context).toBeNull();
  428. await cleanupTestDb(store);
  429. });
  430. test("getContextForFile returns matching context", async () => {
  431. const store = await createTestStore();
  432. addPathContext(store.db, "/test/docs", "Documentation files");
  433. const context = store.getContextForFile("/test/docs/readme.md");
  434. expect(context).toBe("Documentation files");
  435. await cleanupTestDb(store);
  436. });
  437. test("getContextForFile returns most specific context", async () => {
  438. const store = await createTestStore();
  439. addPathContext(store.db, "/test", "General test files");
  440. addPathContext(store.db, "/test/docs", "Documentation files");
  441. addPathContext(store.db, "/test/docs/api", "API documentation");
  442. expect(store.getContextForFile("/test/readme.md")).toBe("General test files");
  443. expect(store.getContextForFile("/test/docs/guide.md")).toBe("Documentation files");
  444. expect(store.getContextForFile("/test/docs/api/reference.md")).toBe("API documentation");
  445. await cleanupTestDb(store);
  446. });
  447. });
  448. // =============================================================================
  449. // Collection Tests
  450. // =============================================================================
  451. describe("Collections", () => {
  452. test("getCollectionIdByName finds collection by path suffix", async () => {
  453. const store = await createTestStore();
  454. const collectionId = createTestCollection(store.db, { pwd: "/home/user/projects/myapp", glob: "**/*.md" });
  455. const found = store.getCollectionIdByName("myapp");
  456. expect(found).toBe(collectionId);
  457. await cleanupTestDb(store);
  458. });
  459. test("getCollectionIdByName returns null for non-existent collection", async () => {
  460. const store = await createTestStore();
  461. const found = store.getCollectionIdByName("nonexistent");
  462. expect(found).toBeNull();
  463. await cleanupTestDb(store);
  464. });
  465. });
  466. // =============================================================================
  467. // FTS Search Tests
  468. // =============================================================================
  469. describe("FTS Search", () => {
  470. test("searchFTS returns empty array for no matches", async () => {
  471. const store = await createTestStore();
  472. const collectionId = createTestCollection(store.db);
  473. insertTestDocument(store.db, collectionId, {
  474. name: "doc1",
  475. body: "The quick brown fox jumps over the lazy dog",
  476. });
  477. const results = store.searchFTS("nonexistent-term-xyz", 10);
  478. expect(results).toHaveLength(0);
  479. await cleanupTestDb(store);
  480. });
  481. test("searchFTS finds documents by keyword", async () => {
  482. const store = await createTestStore();
  483. const collectionId = createTestCollection(store.db);
  484. insertTestDocument(store.db, collectionId, {
  485. name: "doc1",
  486. title: "Fox Document",
  487. body: "The quick brown fox jumps over the lazy dog",
  488. displayPath: "test/doc1.md",
  489. });
  490. const results = store.searchFTS("fox", 10);
  491. expect(results.length).toBeGreaterThan(0);
  492. expect(results[0].displayPath).toBe("test/doc1.md");
  493. expect(results[0].source).toBe("fts");
  494. await cleanupTestDb(store);
  495. });
  496. test("searchFTS ranks title matches higher", async () => {
  497. const store = await createTestStore();
  498. const collectionId = createTestCollection(store.db);
  499. // Document with "fox" in body only
  500. insertTestDocument(store.db, collectionId, {
  501. name: "body-match",
  502. title: "Some Other Title",
  503. body: "The fox is here in the body",
  504. displayPath: "test/body.md",
  505. });
  506. // Document with "fox" in title (via name field which is indexed)
  507. insertTestDocument(store.db, collectionId, {
  508. name: "fox",
  509. title: "Fox Title",
  510. body: "Different content without the animal",
  511. displayPath: "test/title.md",
  512. });
  513. const results = store.searchFTS("fox", 10);
  514. expect(results.length).toBe(2);
  515. // Title/name match should rank higher due to BM25 weights
  516. expect(results[0].displayPath).toBe("test/title.md");
  517. await cleanupTestDb(store);
  518. });
  519. test("searchFTS respects limit parameter", async () => {
  520. const store = await createTestStore();
  521. const collectionId = createTestCollection(store.db);
  522. // Insert 10 documents
  523. for (let i = 0; i < 10; i++) {
  524. insertTestDocument(store.db, collectionId, {
  525. name: `doc${i}`,
  526. body: "common keyword appears here",
  527. displayPath: `test/doc${i}.md`,
  528. });
  529. }
  530. const results = store.searchFTS("common keyword", 3);
  531. expect(results).toHaveLength(3);
  532. await cleanupTestDb(store);
  533. });
  534. test("searchFTS filters by collectionId", async () => {
  535. const store = await createTestStore();
  536. const collection1 = createTestCollection(store.db, { pwd: "/path/one", glob: "**/*.md" });
  537. const collection2 = createTestCollection(store.db, { pwd: "/path/two", glob: "**/*.md" });
  538. insertTestDocument(store.db, collection1, {
  539. name: "doc1",
  540. body: "searchable content",
  541. displayPath: "one/doc1.md",
  542. });
  543. insertTestDocument(store.db, collection2, {
  544. name: "doc2",
  545. body: "searchable content",
  546. displayPath: "two/doc2.md",
  547. });
  548. const allResults = store.searchFTS("searchable", 10);
  549. expect(allResults).toHaveLength(2);
  550. const filtered = store.searchFTS("searchable", 10, collection1);
  551. expect(filtered).toHaveLength(1);
  552. expect(filtered[0].displayPath).toBe("one/doc1.md");
  553. await cleanupTestDb(store);
  554. });
  555. test("searchFTS handles special characters in query", async () => {
  556. const store = await createTestStore();
  557. const collectionId = createTestCollection(store.db);
  558. insertTestDocument(store.db, collectionId, {
  559. name: "doc1",
  560. body: "Function with params: foo(bar, baz)",
  561. displayPath: "test/doc1.md",
  562. });
  563. // Should not throw on special characters
  564. const results = store.searchFTS("foo(bar)", 10);
  565. // Results may vary based on FTS5 handling
  566. expect(Array.isArray(results)).toBe(true);
  567. await cleanupTestDb(store);
  568. });
  569. test("searchFTS ignores inactive documents", async () => {
  570. const store = await createTestStore();
  571. const collectionId = createTestCollection(store.db);
  572. insertTestDocument(store.db, collectionId, {
  573. name: "active",
  574. body: "findme content",
  575. displayPath: "test/active.md",
  576. active: 1,
  577. });
  578. insertTestDocument(store.db, collectionId, {
  579. name: "inactive",
  580. body: "findme content",
  581. displayPath: "test/inactive.md",
  582. active: 0,
  583. });
  584. const results = store.searchFTS("findme", 10);
  585. expect(results).toHaveLength(1);
  586. expect(results[0].displayPath).toBe("test/active.md");
  587. await cleanupTestDb(store);
  588. });
  589. });
  590. // =============================================================================
  591. // Document Retrieval Tests
  592. // =============================================================================
  593. describe("Document Retrieval", () => {
  594. describe("findDocument", () => {
  595. test("findDocument finds by exact filepath", async () => {
  596. const store = await createTestStore();
  597. const collectionId = createTestCollection(store.db);
  598. insertTestDocument(store.db, collectionId, {
  599. name: "mydoc",
  600. title: "My Document",
  601. filepath: "/exact/path/mydoc.md",
  602. displayPath: "path/mydoc.md",
  603. body: "Document content here",
  604. });
  605. const result = store.findDocument("/exact/path/mydoc.md");
  606. expect("error" in result).toBe(false);
  607. if (!("error" in result)) {
  608. expect(result.title).toBe("My Document");
  609. expect(result.displayPath).toBe("path/mydoc.md");
  610. expect(result.body).toBeUndefined(); // body not included by default
  611. }
  612. await cleanupTestDb(store);
  613. });
  614. test("findDocument finds by display_path", async () => {
  615. const store = await createTestStore();
  616. const collectionId = createTestCollection(store.db);
  617. insertTestDocument(store.db, collectionId, {
  618. name: "mydoc",
  619. filepath: "/some/path/mydoc.md",
  620. displayPath: "docs/mydoc.md",
  621. });
  622. const result = store.findDocument("docs/mydoc.md");
  623. expect("error" in result).toBe(false);
  624. await cleanupTestDb(store);
  625. });
  626. test("findDocument finds by partial path match", async () => {
  627. const store = await createTestStore();
  628. const collectionId = createTestCollection(store.db);
  629. insertTestDocument(store.db, collectionId, {
  630. name: "mydoc",
  631. filepath: "/very/long/path/to/mydoc.md",
  632. displayPath: "path/to/mydoc.md",
  633. });
  634. const result = store.findDocument("mydoc.md");
  635. expect("error" in result).toBe(false);
  636. await cleanupTestDb(store);
  637. });
  638. test("findDocument includes body when requested", async () => {
  639. const store = await createTestStore();
  640. const collectionId = createTestCollection(store.db);
  641. insertTestDocument(store.db, collectionId, {
  642. name: "mydoc",
  643. filepath: "/path/mydoc.md",
  644. body: "The actual body content",
  645. });
  646. const result = store.findDocument("/path/mydoc.md", { includeBody: true });
  647. expect("error" in result).toBe(false);
  648. if (!("error" in result)) {
  649. expect(result.body).toBe("The actual body content");
  650. }
  651. await cleanupTestDb(store);
  652. });
  653. test("findDocument returns error with suggestions for not found", async () => {
  654. const store = await createTestStore();
  655. const collectionId = createTestCollection(store.db);
  656. insertTestDocument(store.db, collectionId, {
  657. name: "similar",
  658. filepath: "/path/similar.md",
  659. displayPath: "similar.md",
  660. });
  661. const result = store.findDocument("simlar.md"); // typo - 1 char diff
  662. expect("error" in result).toBe(true);
  663. if ("error" in result) {
  664. expect(result.error).toBe("not_found");
  665. // Levenshtein distance of 1 should be found with maxDistance 3
  666. expect(result.similarFiles.length).toBeGreaterThanOrEqual(0); // May or may not find depending on distance calc
  667. }
  668. await cleanupTestDb(store);
  669. });
  670. test("findDocument handles :line suffix", async () => {
  671. const store = await createTestStore();
  672. const collectionId = createTestCollection(store.db);
  673. insertTestDocument(store.db, collectionId, {
  674. name: "mydoc",
  675. filepath: "/path/mydoc.md",
  676. displayPath: "mydoc.md",
  677. });
  678. const result = store.findDocument("mydoc.md:100");
  679. expect("error" in result).toBe(false);
  680. await cleanupTestDb(store);
  681. });
  682. test("findDocument expands ~ to home directory", async () => {
  683. const store = await createTestStore();
  684. const collectionId = createTestCollection(store.db);
  685. const home = homedir();
  686. insertTestDocument(store.db, collectionId, {
  687. name: "mydoc",
  688. filepath: `${home}/docs/mydoc.md`,
  689. displayPath: "docs/mydoc.md",
  690. });
  691. const result = store.findDocument("~/docs/mydoc.md");
  692. expect("error" in result).toBe(false);
  693. await cleanupTestDb(store);
  694. });
  695. test("findDocument includes context from path_contexts", async () => {
  696. const store = await createTestStore();
  697. const collectionId = createTestCollection(store.db);
  698. addPathContext(store.db, "/path/docs", "Documentation");
  699. insertTestDocument(store.db, collectionId, {
  700. name: "mydoc",
  701. filepath: "/path/docs/mydoc.md",
  702. displayPath: "docs/mydoc.md",
  703. });
  704. const result = store.findDocument("/path/docs/mydoc.md");
  705. expect("error" in result).toBe(false);
  706. if (!("error" in result)) {
  707. expect(result.context).toBe("Documentation");
  708. }
  709. await cleanupTestDb(store);
  710. });
  711. });
  712. describe("getDocumentBody", () => {
  713. test("getDocumentBody returns full body", async () => {
  714. const store = await createTestStore();
  715. const collectionId = createTestCollection(store.db);
  716. insertTestDocument(store.db, collectionId, {
  717. name: "mydoc",
  718. filepath: "/path/mydoc.md",
  719. body: "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
  720. });
  721. const body = store.getDocumentBody({ filepath: "/path/mydoc.md" });
  722. expect(body).toBe("Line 1\nLine 2\nLine 3\nLine 4\nLine 5");
  723. await cleanupTestDb(store);
  724. });
  725. test("getDocumentBody supports line range", async () => {
  726. const store = await createTestStore();
  727. const collectionId = createTestCollection(store.db);
  728. insertTestDocument(store.db, collectionId, {
  729. name: "mydoc",
  730. filepath: "/path/mydoc.md",
  731. body: "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
  732. });
  733. const body = store.getDocumentBody({ filepath: "/path/mydoc.md" }, 2, 2);
  734. expect(body).toBe("Line 2\nLine 3");
  735. await cleanupTestDb(store);
  736. });
  737. test("getDocumentBody returns null for non-existent document", async () => {
  738. const store = await createTestStore();
  739. const body = store.getDocumentBody({ filepath: "/nonexistent.md" });
  740. expect(body).toBeNull();
  741. await cleanupTestDb(store);
  742. });
  743. });
  744. describe("findDocuments (multi-get)", () => {
  745. test("findDocuments finds by glob pattern", async () => {
  746. const store = await createTestStore();
  747. const collectionId = createTestCollection(store.db);
  748. insertTestDocument(store.db, collectionId, {
  749. name: "doc1",
  750. filepath: "/path/journals/2024-01.md",
  751. displayPath: "journals/2024-01.md",
  752. });
  753. insertTestDocument(store.db, collectionId, {
  754. name: "doc2",
  755. filepath: "/path/journals/2024-02.md",
  756. displayPath: "journals/2024-02.md",
  757. });
  758. insertTestDocument(store.db, collectionId, {
  759. name: "doc3",
  760. filepath: "/path/other/file.md",
  761. displayPath: "other/file.md",
  762. });
  763. const { docs, errors } = store.findDocuments("journals/2024-*.md");
  764. expect(errors).toHaveLength(0);
  765. expect(docs).toHaveLength(2);
  766. await cleanupTestDb(store);
  767. });
  768. test("findDocuments finds by comma-separated list", async () => {
  769. const store = await createTestStore();
  770. const collectionId = createTestCollection(store.db);
  771. insertTestDocument(store.db, collectionId, {
  772. name: "doc1",
  773. filepath: "/path/doc1.md",
  774. displayPath: "doc1.md",
  775. });
  776. insertTestDocument(store.db, collectionId, {
  777. name: "doc2",
  778. filepath: "/path/doc2.md",
  779. displayPath: "doc2.md",
  780. });
  781. const { docs, errors } = store.findDocuments("doc1.md, doc2.md");
  782. expect(errors).toHaveLength(0);
  783. expect(docs).toHaveLength(2);
  784. await cleanupTestDb(store);
  785. });
  786. test("findDocuments reports errors for not found files", async () => {
  787. const store = await createTestStore();
  788. const collectionId = createTestCollection(store.db);
  789. insertTestDocument(store.db, collectionId, {
  790. name: "doc1",
  791. filepath: "/path/doc1.md",
  792. displayPath: "doc1.md",
  793. });
  794. const { docs, errors } = store.findDocuments("doc1.md, nonexistent.md");
  795. expect(docs).toHaveLength(1);
  796. expect(errors).toHaveLength(1);
  797. expect(errors[0]).toContain("not found");
  798. await cleanupTestDb(store);
  799. });
  800. test("findDocuments skips large files", async () => {
  801. const store = await createTestStore();
  802. const collectionId = createTestCollection(store.db);
  803. insertTestDocument(store.db, collectionId, {
  804. name: "large",
  805. filepath: "/path/large.md",
  806. displayPath: "large.md",
  807. body: "x".repeat(20000), // 20KB
  808. });
  809. const { docs } = store.findDocuments("large.md", { maxBytes: 10000 });
  810. expect(docs).toHaveLength(1);
  811. expect(docs[0].skipped).toBe(true);
  812. if (docs[0].skipped) {
  813. expect(docs[0].skipReason).toContain("too large");
  814. }
  815. await cleanupTestDb(store);
  816. });
  817. test("findDocuments includes body when requested", async () => {
  818. const store = await createTestStore();
  819. const collectionId = createTestCollection(store.db);
  820. insertTestDocument(store.db, collectionId, {
  821. name: "doc1",
  822. filepath: "/path/doc1.md",
  823. displayPath: "doc1.md",
  824. body: "The content",
  825. });
  826. const { docs } = store.findDocuments("doc1.md", { includeBody: true });
  827. expect(docs[0].skipped).toBe(false);
  828. if (!docs[0].skipped) {
  829. expect(docs[0].doc.body).toBe("The content");
  830. }
  831. await cleanupTestDb(store);
  832. });
  833. });
  834. describe("Legacy getDocument", () => {
  835. test("getDocument returns document with body", async () => {
  836. const store = await createTestStore();
  837. const collectionId = createTestCollection(store.db);
  838. insertTestDocument(store.db, collectionId, {
  839. name: "mydoc",
  840. filepath: "/path/mydoc.md",
  841. body: "Document body",
  842. });
  843. const result = store.getDocument("/path/mydoc.md");
  844. expect("error" in result).toBe(false);
  845. if (!("error" in result)) {
  846. expect(result.body).toBe("Document body");
  847. }
  848. await cleanupTestDb(store);
  849. });
  850. test("getDocument supports line range from :line suffix", async () => {
  851. const store = await createTestStore();
  852. const collectionId = createTestCollection(store.db);
  853. insertTestDocument(store.db, collectionId, {
  854. name: "mydoc",
  855. filepath: "/path/mydoc.md",
  856. displayPath: "mydoc.md",
  857. body: "Line 1\nLine 2\nLine 3\nLine 4",
  858. });
  859. const result = store.getDocument("mydoc.md:2", undefined, 2);
  860. expect("error" in result).toBe(false);
  861. if (!("error" in result)) {
  862. expect(result.body).toBe("Line 2\nLine 3");
  863. }
  864. await cleanupTestDb(store);
  865. });
  866. });
  867. });
  868. // =============================================================================
  869. // Snippet Extraction Tests
  870. // =============================================================================
  871. describe("Snippet Extraction", () => {
  872. test("extractSnippet finds query terms", () => {
  873. const body = "First line.\nSecond line with keyword.\nThird line.\nFourth line.";
  874. const { line, snippet } = extractSnippet(body, "keyword", 500);
  875. expect(line).toBe(2); // Line 2 contains "keyword"
  876. expect(snippet).toContain("keyword");
  877. });
  878. test("extractSnippet includes context lines", () => {
  879. const body = "Line 1\nLine 2\nLine 3 has keyword\nLine 4\nLine 5";
  880. const { snippet } = extractSnippet(body, "keyword", 500);
  881. expect(snippet).toContain("Line 2"); // Context before
  882. expect(snippet).toContain("Line 3 has keyword");
  883. expect(snippet).toContain("Line 4"); // Context after
  884. });
  885. test("extractSnippet respects maxLen for content", () => {
  886. const body = "A".repeat(1000);
  887. const result = extractSnippet(body, "query", 100);
  888. // Snippet includes header + content, content should be truncated
  889. expect(result.snippet).toContain("@@"); // Has diff header
  890. expect(result.snippet).toContain("..."); // Content was truncated
  891. });
  892. test("extractSnippet uses chunkPos hint", () => {
  893. const body = "First section...\n".repeat(50) + "Target keyword here\n" + "More content...".repeat(50);
  894. const chunkPos = body.indexOf("Target keyword");
  895. const { snippet } = extractSnippet(body, "Target", 200, chunkPos);
  896. expect(snippet).toContain("Target keyword");
  897. });
  898. test("extractSnippet returns beginning when no match", () => {
  899. const body = "First line\nSecond line\nThird line";
  900. const { line, snippet } = extractSnippet(body, "nonexistent", 500);
  901. expect(line).toBe(1);
  902. expect(snippet).toContain("First line");
  903. });
  904. test("extractSnippet includes diff-style header", () => {
  905. const body = "Line 1\nLine 2\nLine 3 has keyword\nLine 4\nLine 5";
  906. const { snippet, linesBefore, linesAfter, snippetLines } = extractSnippet(body, "keyword", 500);
  907. // Header should show line position and context info
  908. expect(snippet).toMatch(/^@@ -\d+,\d+ @@ \(\d+ before, \d+ after\)/);
  909. expect(linesBefore).toBe(1); // Line 1 comes before
  910. expect(linesAfter).toBe(0); // Snippet includes to end (lines 2-5)
  911. expect(snippetLines).toBe(4); // Lines 2, 3, 4, 5
  912. });
  913. test("extractSnippet calculates linesBefore and linesAfter correctly", () => {
  914. const body = "L1\nL2\nL3\nL4 match\nL5\nL6\nL7\nL8\nL9\nL10";
  915. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "match", 500);
  916. expect(line).toBe(4); // "L4 match" is line 4
  917. expect(linesBefore).toBe(2); // L1, L2 before snippet (snippet starts at L3)
  918. expect(snippetLines).toBe(4); // L3, L4, L5, L6
  919. expect(linesAfter).toBe(4); // L7, L8, L9, L10 after snippet
  920. });
  921. test("extractSnippet header format matches diff style", () => {
  922. const body = "A\nB\nC keyword\nD\nE\nF\nG\nH";
  923. const { snippet } = extractSnippet(body, "keyword", 500);
  924. // Should start with @@ -line,count @@ (N before, M after)
  925. const headerMatch = snippet.match(/^@@ -(\d+),(\d+) @@ \((\d+) before, (\d+) after\)/);
  926. expect(headerMatch).not.toBeNull();
  927. const [, startLine, count, before, after] = headerMatch!;
  928. expect(parseInt(startLine)).toBe(2); // Snippet starts at line 2 (B)
  929. expect(parseInt(count)).toBe(4); // 4 lines: B, C keyword, D, E
  930. expect(parseInt(before)).toBe(1); // A is before
  931. expect(parseInt(after)).toBe(3); // F, G, H are after
  932. });
  933. test("extractSnippet at document start shows 0 before", () => {
  934. const body = "First line keyword\nSecond\nThird\nFourth\nFifth";
  935. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "keyword", 500);
  936. expect(line).toBe(1); // Keyword on first line
  937. expect(linesBefore).toBe(0); // Nothing before
  938. expect(snippetLines).toBe(3); // First, Second, Third (bestLine-1 to bestLine+3, clamped)
  939. expect(linesAfter).toBe(2); // Fourth, Fifth
  940. });
  941. test("extractSnippet at document end shows 0 after", () => {
  942. const body = "First\nSecond\nThird\nFourth\nFifth keyword";
  943. const { linesBefore, linesAfter, snippetLines, line } = extractSnippet(body, "keyword", 500);
  944. expect(line).toBe(5); // Keyword on last line
  945. expect(linesBefore).toBe(3); // First, Second, Third before snippet
  946. expect(snippetLines).toBe(2); // Fourth, Fifth keyword (bestLine-1 to bestLine+3, clamped)
  947. expect(linesAfter).toBe(0); // Nothing after
  948. });
  949. test("extractSnippet with single line document", () => {
  950. const body = "Single line with keyword";
  951. const { linesBefore, linesAfter, snippetLines, snippet } = extractSnippet(body, "keyword", 500);
  952. expect(linesBefore).toBe(0);
  953. expect(linesAfter).toBe(0);
  954. expect(snippetLines).toBe(1);
  955. expect(snippet).toContain("@@ -1,1 @@ (0 before, 0 after)");
  956. expect(snippet).toContain("Single line with keyword");
  957. });
  958. test("extractSnippet with chunkPos adjusts line numbers correctly", () => {
  959. // 50 lines of padding, then keyword, then more content
  960. const padding = "Padding line\n".repeat(50);
  961. const body = padding + "Target keyword here\nMore content\nEven more";
  962. const chunkPos = padding.length; // Position of "Target keyword"
  963. const { line, linesBefore, linesAfter } = extractSnippet(body, "keyword", 200, chunkPos);
  964. expect(line).toBe(51); // "Target keyword" is line 51
  965. expect(linesBefore).toBeGreaterThan(40); // Many lines before
  966. });
  967. });
  968. // =============================================================================
  969. // Reciprocal Rank Fusion Tests
  970. // =============================================================================
  971. describe("Reciprocal Rank Fusion", () => {
  972. const makeResult = (file: string, score: number): RankedResult => ({
  973. file,
  974. displayPath: file,
  975. title: file,
  976. body: "body",
  977. score,
  978. });
  979. test("RRF combines single list correctly", () => {
  980. const list1 = [
  981. makeResult("doc1", 0.9),
  982. makeResult("doc2", 0.8),
  983. makeResult("doc3", 0.7),
  984. ];
  985. const fused = reciprocalRankFusion([list1]);
  986. // Order should be preserved
  987. expect(fused[0].file).toBe("doc1");
  988. expect(fused[1].file).toBe("doc2");
  989. expect(fused[2].file).toBe("doc3");
  990. });
  991. test("RRF merges documents from multiple lists", () => {
  992. const list1 = [makeResult("doc1", 0.9), makeResult("doc2", 0.8)];
  993. const list2 = [makeResult("doc2", 0.95), makeResult("doc3", 0.85)];
  994. const fused = reciprocalRankFusion([list1, list2]);
  995. // doc2 appears in both lists, should have higher combined score
  996. expect(fused.find(r => r.file === "doc2")).toBeDefined();
  997. expect(fused.find(r => r.file === "doc1")).toBeDefined();
  998. expect(fused.find(r => r.file === "doc3")).toBeDefined();
  999. });
  1000. test("RRF respects weights", () => {
  1001. const list1 = [makeResult("doc1", 0.9)];
  1002. const list2 = [makeResult("doc2", 0.9)];
  1003. // Give double weight to list1
  1004. const fused = reciprocalRankFusion([list1, list2], [2.0, 1.0]);
  1005. // doc1 should rank higher due to weight
  1006. expect(fused[0].file).toBe("doc1");
  1007. });
  1008. test("RRF adds top-rank bonus", () => {
  1009. // doc1 is #1 in list1, doc2 is #2 in list1
  1010. const list1 = [makeResult("doc1", 0.9), makeResult("doc2", 0.8)];
  1011. const list2 = [makeResult("doc3", 0.85)];
  1012. const fused = reciprocalRankFusion([list1, list2]);
  1013. // doc1 should get +0.05 bonus for being #1
  1014. // doc2 should get +0.02 bonus for being #2-3
  1015. const doc1 = fused.find(r => r.file === "doc1");
  1016. const doc2 = fused.find(r => r.file === "doc2");
  1017. expect(doc1!.score).toBeGreaterThan(doc2!.score);
  1018. });
  1019. test("RRF handles empty lists", () => {
  1020. const fused = reciprocalRankFusion([[], []]);
  1021. expect(fused).toHaveLength(0);
  1022. });
  1023. test("RRF uses k parameter correctly", () => {
  1024. const list = [makeResult("doc1", 0.9)];
  1025. // With different k values, scores should differ
  1026. const fused60 = reciprocalRankFusion([list], [], 60);
  1027. const fused30 = reciprocalRankFusion([list], [], 30);
  1028. // Lower k = higher scores for top ranks
  1029. expect(fused30[0].score).toBeGreaterThan(fused60[0].score);
  1030. });
  1031. });
  1032. // =============================================================================
  1033. // Index Status Tests
  1034. // =============================================================================
  1035. describe("Index Status", () => {
  1036. test("getStatus returns correct structure", async () => {
  1037. const store = await createTestStore();
  1038. const status = store.getStatus();
  1039. expect(status).toHaveProperty("totalDocuments");
  1040. expect(status).toHaveProperty("needsEmbedding");
  1041. expect(status).toHaveProperty("hasVectorIndex");
  1042. expect(status).toHaveProperty("collections");
  1043. expect(Array.isArray(status.collections)).toBe(true);
  1044. await cleanupTestDb(store);
  1045. });
  1046. test("getStatus counts documents correctly", async () => {
  1047. const store = await createTestStore();
  1048. const collectionId = createTestCollection(store.db);
  1049. insertTestDocument(store.db, collectionId, { name: "doc1", active: 1 });
  1050. insertTestDocument(store.db, collectionId, { name: "doc2", active: 1 });
  1051. insertTestDocument(store.db, collectionId, { name: "doc3", active: 0 }); // inactive
  1052. const status = store.getStatus();
  1053. expect(status.totalDocuments).toBe(2); // Only active docs
  1054. await cleanupTestDb(store);
  1055. });
  1056. test("getStatus reports collection info", async () => {
  1057. const store = await createTestStore();
  1058. const collectionId = createTestCollection(store.db, { pwd: "/test/path", glob: "**/*.md" });
  1059. insertTestDocument(store.db, collectionId, { name: "doc1" });
  1060. const status = store.getStatus();
  1061. expect(status.collections).toHaveLength(1);
  1062. expect(status.collections[0].path).toBe("/test/path");
  1063. expect(status.collections[0].pattern).toBe("**/*.md");
  1064. expect(status.collections[0].documents).toBe(1);
  1065. await cleanupTestDb(store);
  1066. });
  1067. test("getHashesNeedingEmbedding counts correctly", async () => {
  1068. const store = await createTestStore();
  1069. const collectionId = createTestCollection(store.db);
  1070. // Add documents with different hashes
  1071. insertTestDocument(store.db, collectionId, { name: "doc1", hash: "hash1" });
  1072. insertTestDocument(store.db, collectionId, { name: "doc2", hash: "hash2" });
  1073. insertTestDocument(store.db, collectionId, { name: "doc3", hash: "hash1" }); // same hash as doc1
  1074. const needsEmbedding = store.getHashesNeedingEmbedding();
  1075. expect(needsEmbedding).toBe(2); // hash1 and hash2
  1076. await cleanupTestDb(store);
  1077. });
  1078. test("getIndexHealth returns health info", async () => {
  1079. const store = await createTestStore();
  1080. const collectionId = createTestCollection(store.db);
  1081. insertTestDocument(store.db, collectionId, { name: "doc1" });
  1082. const health = store.getIndexHealth();
  1083. expect(health).toHaveProperty("needsEmbedding");
  1084. expect(health).toHaveProperty("totalDocs");
  1085. expect(health).toHaveProperty("daysStale");
  1086. expect(health.totalDocs).toBe(1);
  1087. await cleanupTestDb(store);
  1088. });
  1089. });
  1090. // =============================================================================
  1091. // Fuzzy Matching Tests
  1092. // =============================================================================
  1093. describe("Fuzzy Matching", () => {
  1094. test("findSimilarFiles finds similar paths", async () => {
  1095. const store = await createTestStore();
  1096. const collectionId = createTestCollection(store.db);
  1097. insertTestDocument(store.db, collectionId, {
  1098. name: "readme",
  1099. displayPath: "docs/readme.md",
  1100. });
  1101. insertTestDocument(store.db, collectionId, {
  1102. name: "readmi",
  1103. displayPath: "docs/readmi.md", // typo
  1104. });
  1105. const similar = store.findSimilarFiles("docs/readme.md", 3, 5);
  1106. expect(similar).toContain("docs/readme.md");
  1107. await cleanupTestDb(store);
  1108. });
  1109. test("findSimilarFiles respects maxDistance", async () => {
  1110. const store = await createTestStore();
  1111. const collectionId = createTestCollection(store.db);
  1112. insertTestDocument(store.db, collectionId, {
  1113. name: "abc",
  1114. displayPath: "abc.md",
  1115. });
  1116. insertTestDocument(store.db, collectionId, {
  1117. name: "xyz",
  1118. displayPath: "xyz.md", // very different
  1119. });
  1120. const similar = store.findSimilarFiles("abc.md", 1, 5); // max distance 1
  1121. expect(similar).toContain("abc.md");
  1122. expect(similar).not.toContain("xyz.md");
  1123. await cleanupTestDb(store);
  1124. });
  1125. test("matchFilesByGlob matches patterns", async () => {
  1126. const store = await createTestStore();
  1127. const collectionId = createTestCollection(store.db);
  1128. insertTestDocument(store.db, collectionId, {
  1129. filepath: "/p/journals/2024-01.md",
  1130. displayPath: "journals/2024-01.md",
  1131. });
  1132. insertTestDocument(store.db, collectionId, {
  1133. filepath: "/p/journals/2024-02.md",
  1134. displayPath: "journals/2024-02.md",
  1135. });
  1136. insertTestDocument(store.db, collectionId, {
  1137. filepath: "/p/docs/readme.md",
  1138. displayPath: "docs/readme.md",
  1139. });
  1140. const matches = store.matchFilesByGlob("journals/*.md");
  1141. expect(matches).toHaveLength(2);
  1142. expect(matches.every(m => m.displayPath.startsWith("journals/"))).toBe(true);
  1143. await cleanupTestDb(store);
  1144. });
  1145. });
  1146. // =============================================================================
  1147. // Vector Table Tests
  1148. // =============================================================================
  1149. describe("Vector Table", () => {
  1150. test("ensureVecTable creates vector table", async () => {
  1151. const store = await createTestStore();
  1152. // Initially no vector table
  1153. let exists = store.db.prepare(`
  1154. SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1155. `).get();
  1156. expect(exists).toBeFalsy(); // null or undefined
  1157. // Create vector table
  1158. store.ensureVecTable(768);
  1159. exists = store.db.prepare(`
  1160. SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1161. `).get();
  1162. expect(exists).toBeTruthy();
  1163. await cleanupTestDb(store);
  1164. });
  1165. test("ensureVecTable recreates table if dimensions change", async () => {
  1166. const store = await createTestStore();
  1167. // Create with 768 dimensions
  1168. store.ensureVecTable(768);
  1169. // Check dimensions
  1170. let tableInfo = store.db.prepare(`
  1171. SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1172. `).get() as { sql: string };
  1173. expect(tableInfo.sql).toContain("float[768]");
  1174. // Recreate with different dimensions
  1175. store.ensureVecTable(1024);
  1176. tableInfo = store.db.prepare(`
  1177. SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  1178. `).get() as { sql: string };
  1179. expect(tableInfo.sql).toContain("float[1024]");
  1180. await cleanupTestDb(store);
  1181. });
  1182. });
  1183. // =============================================================================
  1184. // Integration Tests
  1185. // =============================================================================
  1186. describe("Integration", () => {
  1187. test("full document lifecycle: create, search, retrieve", async () => {
  1188. const store = await createTestStore();
  1189. const collectionId = createTestCollection(store.db, { pwd: "/test/notes", glob: "**/*.md" });
  1190. // Add context
  1191. addPathContext(store.db, "/test/notes", "Personal notes");
  1192. // Insert documents
  1193. insertTestDocument(store.db, collectionId, {
  1194. name: "meeting",
  1195. title: "Team Meeting Notes",
  1196. filepath: "/test/notes/meeting.md",
  1197. displayPath: "notes/meeting.md",
  1198. body: "# Team Meeting Notes\n\nDiscussed project timeline and deliverables.",
  1199. });
  1200. insertTestDocument(store.db, collectionId, {
  1201. name: "ideas",
  1202. title: "Project Ideas",
  1203. filepath: "/test/notes/ideas.md",
  1204. displayPath: "notes/ideas.md",
  1205. body: "# Project Ideas\n\nBrainstorming new features for the product.",
  1206. });
  1207. // Search
  1208. const searchResults = store.searchFTS("project", 10);
  1209. expect(searchResults.length).toBe(2);
  1210. // Status
  1211. const status = store.getStatus();
  1212. expect(status.totalDocuments).toBe(2);
  1213. expect(status.collections).toHaveLength(1);
  1214. // Retrieve single document
  1215. const doc = store.findDocument("notes/meeting.md", { includeBody: true });
  1216. expect("error" in doc).toBe(false);
  1217. if (!("error" in doc)) {
  1218. expect(doc.title).toBe("Team Meeting Notes");
  1219. expect(doc.context).toBe("Personal notes");
  1220. expect(doc.body).toContain("Team Meeting");
  1221. }
  1222. // Multi-get
  1223. const { docs, errors } = store.findDocuments("notes/*.md", { includeBody: true });
  1224. expect(errors).toHaveLength(0);
  1225. expect(docs).toHaveLength(2);
  1226. await cleanupTestDb(store);
  1227. });
  1228. test("multiple stores can operate independently", async () => {
  1229. const store1 = await createTestStore();
  1230. const store2 = await createTestStore();
  1231. const col1 = createTestCollection(store1.db, { pwd: "/store1", glob: "**/*.md" });
  1232. const col2 = createTestCollection(store2.db, { pwd: "/store2", glob: "**/*.md" });
  1233. insertTestDocument(store1.db, col1, {
  1234. name: "doc1",
  1235. body: "unique content for store1",
  1236. displayPath: "store1/doc.md",
  1237. });
  1238. insertTestDocument(store2.db, col2, {
  1239. name: "doc2",
  1240. body: "different content for store2",
  1241. displayPath: "store2/doc.md",
  1242. });
  1243. // Each store should only see its own documents
  1244. const results1 = store1.searchFTS("unique", 10);
  1245. const results2 = store2.searchFTS("different", 10);
  1246. expect(results1).toHaveLength(1);
  1247. expect(results1[0].displayPath).toBe("store1/doc.md");
  1248. expect(results2).toHaveLength(1);
  1249. expect(results2[0].displayPath).toBe("store2/doc.md");
  1250. // Cross-check: store1 shouldn't find store2's content
  1251. const cross1 = store1.searchFTS("different", 10);
  1252. const cross2 = store2.searchFTS("unique", 10);
  1253. expect(cross1).toHaveLength(0);
  1254. expect(cross2).toHaveLength(0);
  1255. await cleanupTestDb(store1);
  1256. await cleanupTestDb(store2);
  1257. });
  1258. });
  1259. // =============================================================================
  1260. // Legacy Compatibility Tests
  1261. // =============================================================================
  1262. describe("Legacy Compatibility", () => {
  1263. test("getMultipleDocuments returns files with body", async () => {
  1264. const store = await createTestStore();
  1265. const collectionId = createTestCollection(store.db);
  1266. insertTestDocument(store.db, collectionId, {
  1267. name: "doc1",
  1268. filepath: "/path/doc1.md",
  1269. displayPath: "doc1.md",
  1270. body: "Content 1",
  1271. });
  1272. insertTestDocument(store.db, collectionId, {
  1273. name: "doc2",
  1274. filepath: "/path/doc2.md",
  1275. displayPath: "doc2.md",
  1276. body: "Content 2",
  1277. });
  1278. const { files, errors } = store.getMultipleDocuments("*.md");
  1279. expect(errors).toHaveLength(0);
  1280. expect(files).toHaveLength(2);
  1281. expect(files[0].body).toBeTruthy();
  1282. expect(files[1].body).toBeTruthy();
  1283. await cleanupTestDb(store);
  1284. });
  1285. test("getMultipleDocuments truncates with maxLines", async () => {
  1286. const store = await createTestStore();
  1287. const collectionId = createTestCollection(store.db);
  1288. insertTestDocument(store.db, collectionId, {
  1289. name: "doc1",
  1290. filepath: "/path/doc1.md",
  1291. displayPath: "doc1.md",
  1292. body: "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
  1293. });
  1294. const { files } = store.getMultipleDocuments("doc1.md", 2);
  1295. expect(files).toHaveLength(1);
  1296. expect(files[0].skipped).toBe(false);
  1297. if (!files[0].skipped) {
  1298. expect(files[0].body).toBe("Line 1\nLine 2\n\n[... truncated 3 more lines]");
  1299. }
  1300. await cleanupTestDb(store);
  1301. });
  1302. test("getMultipleDocuments skips large files", async () => {
  1303. const store = await createTestStore();
  1304. const collectionId = createTestCollection(store.db);
  1305. insertTestDocument(store.db, collectionId, {
  1306. name: "large",
  1307. filepath: "/path/large.md",
  1308. displayPath: "large.md",
  1309. body: "x".repeat(15000),
  1310. });
  1311. const { files } = store.getMultipleDocuments("large.md", undefined, 10000);
  1312. expect(files).toHaveLength(1);
  1313. expect(files[0].skipped).toBe(true);
  1314. await cleanupTestDb(store);
  1315. });
  1316. });
  1317. // =============================================================================
  1318. // Ollama Integration Tests (using mocked Ollama)
  1319. // =============================================================================
  1320. describe("Ollama Integration (Mocked)", () => {
  1321. test("searchVec returns empty when no vector index", async () => {
  1322. const store = await createTestStore();
  1323. const collectionId = createTestCollection(store.db);
  1324. insertTestDocument(store.db, collectionId, {
  1325. name: "doc1",
  1326. body: "Some content",
  1327. });
  1328. // No vectors_vec table exists, should return empty
  1329. const results = await store.searchVec("query", "embeddinggemma", 10);
  1330. expect(results).toHaveLength(0);
  1331. await cleanupTestDb(store);
  1332. });
  1333. test("searchVec returns results when vector index exists", async () => {
  1334. const store = await createTestStore();
  1335. const collectionId = createTestCollection(store.db);
  1336. const hash = "testhash123";
  1337. insertTestDocument(store.db, collectionId, {
  1338. name: "doc1",
  1339. hash,
  1340. body: "Some content about testing",
  1341. filepath: "/test/doc1.md",
  1342. displayPath: "doc1.md",
  1343. });
  1344. // Create vector table and insert a vector
  1345. store.ensureVecTable(768);
  1346. const embedding = Array(768).fill(0).map(() => Math.random());
  1347. store.db.prepare(`INSERT INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, 0, 0, 'test', ?)`).run(hash, new Date().toISOString());
  1348. store.db.prepare(`INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`).run(`${hash}_0`, new Float32Array(embedding));
  1349. const results = await store.searchVec("test query", "embeddinggemma", 10);
  1350. expect(results).toHaveLength(1);
  1351. expect(results[0].displayPath).toBe("doc1.md");
  1352. expect(results[0].source).toBe("vec");
  1353. await cleanupTestDb(store);
  1354. });
  1355. test("expandQuery returns original plus expanded queries", async () => {
  1356. const store = await createTestStore();
  1357. const queries = await store.expandQuery("test query");
  1358. expect(queries).toContain("test query");
  1359. expect(queries[0]).toBe("test query");
  1360. // Mock returns 2 variations
  1361. expect(queries.length).toBeGreaterThanOrEqual(1);
  1362. await cleanupTestDb(store);
  1363. });
  1364. test("expandQuery caches results", async () => {
  1365. const store = await createTestStore();
  1366. // First call
  1367. const queries1 = await store.expandQuery("cached query test");
  1368. // Second call - should hit cache
  1369. const queries2 = await store.expandQuery("cached query test");
  1370. expect(queries1[0]).toBe(queries2[0]);
  1371. await cleanupTestDb(store);
  1372. });
  1373. test("rerank scores documents", async () => {
  1374. const store = await createTestStore();
  1375. const docs = [
  1376. { file: "doc1.md", text: "Relevant content about the topic" },
  1377. { file: "doc2.md", text: "Other content" },
  1378. ];
  1379. const results = await store.rerank("topic", docs);
  1380. expect(results).toHaveLength(2);
  1381. // Mock returns "yes" with high confidence
  1382. expect(results[0].score).toBeGreaterThan(0);
  1383. await cleanupTestDb(store);
  1384. });
  1385. test("rerank caches results", async () => {
  1386. const store = await createTestStore();
  1387. const docs = [{ file: "doc1.md", text: "Content for caching test" }];
  1388. // First call
  1389. await store.rerank("cache test query", docs);
  1390. // Second call - should hit cache
  1391. const results = await store.rerank("cache test query", docs);
  1392. expect(results).toHaveLength(1);
  1393. await cleanupTestDb(store);
  1394. });
  1395. });
  1396. // =============================================================================
  1397. // Edge Cases & Error Handling
  1398. // =============================================================================
  1399. describe("Edge Cases", () => {
  1400. test("handles empty database gracefully", async () => {
  1401. const store = await createTestStore();
  1402. const searchResults = store.searchFTS("anything", 10);
  1403. expect(searchResults).toHaveLength(0);
  1404. const status = store.getStatus();
  1405. expect(status.totalDocuments).toBe(0);
  1406. expect(status.collections).toHaveLength(0);
  1407. const doc = store.findDocument("nonexistent.md");
  1408. expect("error" in doc).toBe(true);
  1409. await cleanupTestDb(store);
  1410. });
  1411. test("handles very long document bodies", async () => {
  1412. const store = await createTestStore();
  1413. const collectionId = createTestCollection(store.db);
  1414. const longBody = "word ".repeat(100000); // ~600KB
  1415. insertTestDocument(store.db, collectionId, {
  1416. name: "long",
  1417. body: longBody,
  1418. displayPath: "long.md",
  1419. });
  1420. const results = store.searchFTS("word", 10);
  1421. expect(results).toHaveLength(1);
  1422. await cleanupTestDb(store);
  1423. });
  1424. test("handles unicode content correctly", async () => {
  1425. const store = await createTestStore();
  1426. const collectionId = createTestCollection(store.db);
  1427. insertTestDocument(store.db, collectionId, {
  1428. name: "unicode",
  1429. title: "日本語タイトル",
  1430. body: "# 日本語\n\n内容は日本語で書かれています。\n\nEmoji: 🎉🚀✨",
  1431. displayPath: "unicode.md",
  1432. });
  1433. // Should be searchable
  1434. const results = store.searchFTS("日本語", 10);
  1435. expect(results.length).toBeGreaterThan(0);
  1436. // Should retrieve correctly
  1437. const doc = store.findDocument("unicode.md", { includeBody: true });
  1438. expect("error" in doc).toBe(false);
  1439. if (!("error" in doc)) {
  1440. expect(doc.title).toBe("日本語タイトル");
  1441. expect(doc.body).toContain("🎉");
  1442. }
  1443. await cleanupTestDb(store);
  1444. });
  1445. test("handles documents with special characters in paths", async () => {
  1446. const store = await createTestStore();
  1447. const collectionId = createTestCollection(store.db);
  1448. insertTestDocument(store.db, collectionId, {
  1449. name: "special",
  1450. filepath: "/path/file with spaces.md",
  1451. displayPath: "file with spaces.md",
  1452. body: "Content",
  1453. });
  1454. const doc = store.findDocument("file with spaces.md");
  1455. expect("error" in doc).toBe(false);
  1456. await cleanupTestDb(store);
  1457. });
  1458. test("handles concurrent operations", async () => {
  1459. const store = await createTestStore();
  1460. const collectionId = createTestCollection(store.db);
  1461. // Insert multiple documents concurrently
  1462. const inserts = Array.from({ length: 10 }, (_, i) =>
  1463. Promise.resolve(insertTestDocument(store.db, collectionId, {
  1464. name: `concurrent${i}`,
  1465. body: `Content ${i} searchterm`,
  1466. displayPath: `concurrent${i}.md`,
  1467. }))
  1468. );
  1469. await Promise.all(inserts);
  1470. // All should be searchable
  1471. const results = store.searchFTS("searchterm", 20);
  1472. expect(results).toHaveLength(10);
  1473. await cleanupTestDb(store);
  1474. });
  1475. });
  1476. // =============================================================================
  1477. // Content-Addressable Storage Tests
  1478. // =============================================================================
  1479. describe("Content-Addressable Storage", () => {
  1480. test("same content gets same hash from multiple collections", async () => {
  1481. const store = await createTestStore();
  1482. // Create two collections
  1483. const collection1 = createTestCollection(store.db, { pwd: "/path/collection1" });
  1484. const collection2 = createTestCollection(store.db, { pwd: "/path/collection2" });
  1485. // Add same content to both collections
  1486. const content = "# Same Content\n\nThis is the same content in two places.";
  1487. const hash1 = await hashContent(content);
  1488. const doc1 = await insertTestDocument(store.db, collection1, {
  1489. name: "doc1",
  1490. body: content,
  1491. displayPath: "doc1.md",
  1492. });
  1493. const doc2 = await insertTestDocument(store.db, collection2, {
  1494. name: "doc2",
  1495. body: content,
  1496. displayPath: "doc2.md",
  1497. });
  1498. // Both should have the same hash
  1499. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  1500. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  1501. expect(hash1Db.hash).toBe(hash2Db.hash);
  1502. expect(hash1Db.hash).toBe(hash1);
  1503. // There should only be one entry in the content table
  1504. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(hash1) as { count: number };
  1505. expect(contentCount.count).toBe(1);
  1506. await cleanupTestDb(store);
  1507. });
  1508. test("removing one collection preserves content used by another", async () => {
  1509. const store = await createTestStore();
  1510. // Create two collections
  1511. const collection1 = createTestCollection(store.db, { pwd: "/path/collection1" });
  1512. const collection2 = createTestCollection(store.db, { pwd: "/path/collection2" });
  1513. // Add same content to both collections
  1514. const sharedContent = "# Shared Content\n\nThis is shared.";
  1515. const sharedHash = await hashContent(sharedContent);
  1516. await insertTestDocument(store.db, collection1, {
  1517. name: "shared1",
  1518. body: sharedContent,
  1519. displayPath: "shared1.md",
  1520. });
  1521. await insertTestDocument(store.db, collection2, {
  1522. name: "shared2",
  1523. body: sharedContent,
  1524. displayPath: "shared2.md",
  1525. });
  1526. // Add unique content to collection1
  1527. const uniqueContent = "# Unique Content\n\nThis is unique to collection1.";
  1528. const uniqueHash = await hashContent(uniqueContent);
  1529. await insertTestDocument(store.db, collection1, {
  1530. name: "unique",
  1531. body: uniqueContent,
  1532. displayPath: "unique.md",
  1533. });
  1534. // Verify both hashes exist in content table
  1535. const sharedExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  1536. const uniqueExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  1537. expect(sharedExists1).toBeTruthy();
  1538. expect(uniqueExists1).toBeTruthy();
  1539. // Remove collection1 (this should NOT remove shared content)
  1540. store.db.prepare(`DELETE FROM documents WHERE collection_id = ?`).run(collection1);
  1541. store.db.prepare(`DELETE FROM collections WHERE id = ?`).run(collection1);
  1542. // Clean up orphaned content (mimics what the CLI does)
  1543. store.db.prepare(`
  1544. DELETE FROM content
  1545. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  1546. `).run();
  1547. // Shared content should still exist (used by collection2)
  1548. const sharedExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  1549. expect(sharedExists2).toBeTruthy();
  1550. // Unique content should be removed (only used by collection1)
  1551. const uniqueExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  1552. expect(uniqueExists2).toBeFalsy();
  1553. await cleanupTestDb(store);
  1554. });
  1555. test("deduplicates content across many collections", async () => {
  1556. const store = await createTestStore();
  1557. const sharedContent = "# Common Header\n\nThis appears everywhere.";
  1558. const sharedHash = await hashContent(sharedContent);
  1559. // Create 5 collections with the same content
  1560. const collectionIds = [];
  1561. for (let i = 0; i < 5; i++) {
  1562. const collId = createTestCollection(store.db, { pwd: `/path/collection${i}` });
  1563. collectionIds.push(collId);
  1564. await insertTestDocument(store.db, collId, {
  1565. name: `doc${i}`,
  1566. body: sharedContent,
  1567. displayPath: `doc${i}.md`,
  1568. });
  1569. }
  1570. // Should have 5 documents
  1571. const docCount = store.db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number };
  1572. expect(docCount.count).toBe(5);
  1573. // But only 1 content entry
  1574. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(sharedHash) as { count: number };
  1575. expect(contentCount.count).toBe(1);
  1576. // All documents should point to the same hash
  1577. const hashes = store.db.prepare(`SELECT DISTINCT hash FROM documents WHERE active = 1`).all() as { hash: string }[];
  1578. expect(hashes).toHaveLength(1);
  1579. expect(hashes[0].hash).toBe(sharedHash);
  1580. await cleanupTestDb(store);
  1581. });
  1582. test("different content gets different hashes", async () => {
  1583. const store = await createTestStore();
  1584. const collectionId = createTestCollection(store.db);
  1585. const content1 = "# Content One";
  1586. const content2 = "# Content Two";
  1587. const hash1 = await hashContent(content1);
  1588. const hash2 = await hashContent(content2);
  1589. // Hashes should be different
  1590. expect(hash1).not.toBe(hash2);
  1591. const doc1 = await insertTestDocument(store.db, collectionId, {
  1592. name: "doc1",
  1593. body: content1,
  1594. displayPath: "doc1.md",
  1595. });
  1596. const doc2 = await insertTestDocument(store.db, collectionId, {
  1597. name: "doc2",
  1598. body: content2,
  1599. displayPath: "doc2.md",
  1600. });
  1601. // Both hashes should exist in content table
  1602. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  1603. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  1604. expect(hash1Db.hash).toBe(hash1);
  1605. expect(hash2Db.hash).toBe(hash2);
  1606. expect(hash1Db.hash).not.toBe(hash2Db.hash);
  1607. // Should have 2 entries in content table
  1608. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content`).get() as { count: number };
  1609. expect(contentCount.count).toBe(2);
  1610. await cleanupTestDb(store);
  1611. });
  1612. });