store.test.ts 116 KB

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