store.test.ts 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276
  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. // =============================================================================
  2297. // Content-Addressable Storage Tests
  2298. // =============================================================================
  2299. describe("Content-Addressable Storage", () => {
  2300. test("same content gets same hash from multiple collections", async () => {
  2301. const store = await createTestStore();
  2302. // Create two collections
  2303. const collection1 = await createTestCollection({ pwd: "/path/collection1", name: "collection1" });
  2304. const collection2 = await createTestCollection({ pwd: "/path/collection2", name: "collection2" });
  2305. // Add same content to both collections
  2306. const content = "# Same Content\n\nThis is the same content in two places.";
  2307. const hash1 = await hashContent(content);
  2308. const doc1 = await insertTestDocument(store.db, collection1, {
  2309. name: "doc1",
  2310. body: content,
  2311. displayPath: "doc1.md",
  2312. });
  2313. const doc2 = await insertTestDocument(store.db, collection2, {
  2314. name: "doc2",
  2315. body: content,
  2316. displayPath: "doc2.md",
  2317. });
  2318. // Both should have the same hash
  2319. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  2320. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  2321. expect(hash1Db.hash).toBe(hash2Db.hash);
  2322. expect(hash1Db.hash).toBe(hash1);
  2323. // There should only be one entry in the content table
  2324. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(hash1) as { count: number };
  2325. expect(contentCount.count).toBe(1);
  2326. await cleanupTestDb(store);
  2327. });
  2328. test("removing one collection preserves content used by another", async () => {
  2329. const store = await createTestStore();
  2330. // Create two collections
  2331. const collection1 = await createTestCollection({ pwd: "/path/collection1", name: "collection1" });
  2332. const collection2 = await createTestCollection({ pwd: "/path/collection2", name: "collection2" });
  2333. // Add same content to both collections
  2334. const sharedContent = "# Shared Content\n\nThis is shared.";
  2335. const sharedHash = await hashContent(sharedContent);
  2336. await insertTestDocument(store.db, collection1, {
  2337. name: "shared1",
  2338. body: sharedContent,
  2339. displayPath: "shared1.md",
  2340. });
  2341. await insertTestDocument(store.db, collection2, {
  2342. name: "shared2",
  2343. body: sharedContent,
  2344. displayPath: "shared2.md",
  2345. });
  2346. // Add unique content to collection1
  2347. const uniqueContent = "# Unique Content\n\nThis is unique to collection1.";
  2348. const uniqueHash = await hashContent(uniqueContent);
  2349. await insertTestDocument(store.db, collection1, {
  2350. name: "unique",
  2351. body: uniqueContent,
  2352. displayPath: "unique.md",
  2353. });
  2354. // Verify both hashes exist in content table
  2355. const sharedExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  2356. const uniqueExists1 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  2357. expect(sharedExists1).toBeTruthy();
  2358. expect(uniqueExists1).toBeTruthy();
  2359. // Remove collection1 documents (collections are in YAML now)
  2360. store.db.prepare(`DELETE FROM documents WHERE collection = ?`).run(collection1);
  2361. // Clean up orphaned content (mimics what the CLI does)
  2362. store.db.prepare(`
  2363. DELETE FROM content
  2364. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  2365. `).run();
  2366. // Shared content should still exist (used by collection2)
  2367. const sharedExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(sharedHash);
  2368. expect(sharedExists2).toBeTruthy();
  2369. // Unique content should be removed (only used by collection1)
  2370. const uniqueExists2 = store.db.prepare(`SELECT hash FROM content WHERE hash = ?`).get(uniqueHash);
  2371. expect(uniqueExists2).toBeFalsy();
  2372. await cleanupTestDb(store);
  2373. });
  2374. test("deduplicates content across many collections", async () => {
  2375. const store = await createTestStore();
  2376. const sharedContent = "# Common Header\n\nThis appears everywhere.";
  2377. const sharedHash = await hashContent(sharedContent);
  2378. // Create 5 collections with the same content
  2379. const collectionNames = [];
  2380. for (let i = 0; i < 5; i++) {
  2381. const collName = await createTestCollection({ pwd: `/path/collection${i}`, name: `collection${i}` });
  2382. collectionNames.push(collName);
  2383. await insertTestDocument(store.db, collName, {
  2384. name: `doc${i}`,
  2385. body: sharedContent,
  2386. displayPath: `doc${i}.md`,
  2387. });
  2388. }
  2389. // Should have 5 documents
  2390. const docCount = store.db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number };
  2391. expect(docCount.count).toBe(5);
  2392. // But only 1 content entry
  2393. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content WHERE hash = ?`).get(sharedHash) as { count: number };
  2394. expect(contentCount.count).toBe(1);
  2395. // All documents should point to the same hash
  2396. const hashes = store.db.prepare(`SELECT DISTINCT hash FROM documents WHERE active = 1`).all() as { hash: string }[];
  2397. expect(hashes).toHaveLength(1);
  2398. expect(hashes[0]!.hash).toBe(sharedHash);
  2399. await cleanupTestDb(store);
  2400. });
  2401. test("different content gets different hashes", async () => {
  2402. const store = await createTestStore();
  2403. const collectionName = await createTestCollection();
  2404. const content1 = "# Content One";
  2405. const content2 = "# Content Two";
  2406. const hash1 = await hashContent(content1);
  2407. const hash2 = await hashContent(content2);
  2408. // Hashes should be different
  2409. expect(hash1).not.toBe(hash2);
  2410. const doc1 = await insertTestDocument(store.db, collectionName, {
  2411. name: "doc1",
  2412. body: content1,
  2413. displayPath: "doc1.md",
  2414. });
  2415. const doc2 = await insertTestDocument(store.db, collectionName, {
  2416. name: "doc2",
  2417. body: content2,
  2418. displayPath: "doc2.md",
  2419. });
  2420. // Both hashes should exist in content table
  2421. const hash1Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc1) as { hash: string };
  2422. const hash2Db = store.db.prepare(`SELECT hash FROM documents WHERE id = ?`).get(doc2) as { hash: string };
  2423. expect(hash1Db.hash).toBe(hash1);
  2424. expect(hash2Db.hash).toBe(hash2);
  2425. expect(hash1Db.hash).not.toBe(hash2Db.hash);
  2426. // Should have 2 entries in content table
  2427. const contentCount = store.db.prepare(`SELECT COUNT(*) as count FROM content`).get() as { count: number };
  2428. expect(contentCount.count).toBe(2);
  2429. await cleanupTestDb(store);
  2430. });
  2431. test("re-indexing a previously deactivated path reactivates instead of violating UNIQUE", async () => {
  2432. const store = await createTestStore();
  2433. const collectionName = await createTestCollection();
  2434. const now = new Date().toISOString();
  2435. const oldContent = "# First Version";
  2436. const oldHash = await hashContent(oldContent);
  2437. store.insertContent(oldHash, oldContent, now);
  2438. store.insertDocument(collectionName, "docs/foo.md", "foo", oldHash, now, now);
  2439. // Simulate file removal during update pass.
  2440. store.deactivateDocument(collectionName, "docs/foo.md");
  2441. expect(store.findActiveDocument(collectionName, "docs/foo.md")).toBeNull();
  2442. // Simulate file coming back in a later update pass.
  2443. const newContent = "# Second Version";
  2444. const newHash = await hashContent(newContent);
  2445. store.insertContent(newHash, newContent, now);
  2446. expect(() => {
  2447. store.insertDocument(collectionName, "docs/foo.md", "foo", newHash, now, now);
  2448. }).not.toThrow();
  2449. const rows = store.db.prepare(`
  2450. SELECT id, hash, active FROM documents
  2451. WHERE collection = ? AND path = ?
  2452. `).all(collectionName, "docs/foo.md") as { id: number; hash: string; active: number }[];
  2453. expect(rows).toHaveLength(1);
  2454. expect(rows[0]!.active).toBe(1);
  2455. expect(rows[0]!.hash).toBe(newHash);
  2456. await cleanupTestDb(store);
  2457. });
  2458. });
  2459. // =============================================================================
  2460. // Virtual Path Normalization Tests
  2461. // =============================================================================
  2462. describe("normalizeVirtualPath", () => {
  2463. test("already normalized qmd:// path passes through", () => {
  2464. expect(normalizeVirtualPath("qmd://collection/path.md")).toBe("qmd://collection/path.md");
  2465. expect(normalizeVirtualPath("qmd://journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2466. });
  2467. test("handles //collection/path format (missing qmd: prefix)", () => {
  2468. expect(normalizeVirtualPath("//collection/path.md")).toBe("qmd://collection/path.md");
  2469. expect(normalizeVirtualPath("//journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2470. });
  2471. test("handles qmd:// with extra slashes", () => {
  2472. expect(normalizeVirtualPath("qmd:////collection/path.md")).toBe("qmd://collection/path.md");
  2473. expect(normalizeVirtualPath("qmd:///journals/2025-01-01.md")).toBe("qmd://journals/2025-01-01.md");
  2474. expect(normalizeVirtualPath("qmd:///////archive/file.md")).toBe("qmd://archive/file.md");
  2475. });
  2476. test("handles collection root paths", () => {
  2477. expect(normalizeVirtualPath("qmd://collection/")).toBe("qmd://collection/");
  2478. expect(normalizeVirtualPath("qmd://collection")).toBe("qmd://collection");
  2479. expect(normalizeVirtualPath("//collection/")).toBe("qmd://collection/");
  2480. });
  2481. test("preserves bare collection/path format (not auto-converted)", () => {
  2482. // Bare paths without qmd:// or // prefix are NOT converted
  2483. // (could be relative filesystem paths)
  2484. expect(normalizeVirtualPath("collection/path.md")).toBe("collection/path.md");
  2485. expect(normalizeVirtualPath("journals/2025-01-01.md")).toBe("journals/2025-01-01.md");
  2486. });
  2487. test("preserves absolute filesystem paths", () => {
  2488. expect(normalizeVirtualPath("/Users/test/file.md")).toBe("/Users/test/file.md");
  2489. expect(normalizeVirtualPath("/absolute/path/file.md")).toBe("/absolute/path/file.md");
  2490. });
  2491. test("preserves home-relative paths", () => {
  2492. expect(normalizeVirtualPath("~/Documents/file.md")).toBe("~/Documents/file.md");
  2493. });
  2494. test("preserves docid format", () => {
  2495. expect(normalizeVirtualPath("#abc123")).toBe("#abc123");
  2496. expect(normalizeVirtualPath("#def456")).toBe("#def456");
  2497. });
  2498. test("handles whitespace trimming", () => {
  2499. expect(normalizeVirtualPath(" qmd://collection/path.md ")).toBe("qmd://collection/path.md");
  2500. expect(normalizeVirtualPath(" //collection/path.md ")).toBe("qmd://collection/path.md");
  2501. });
  2502. });
  2503. describe("isVirtualPath", () => {
  2504. test("recognizes qmd:// paths", () => {
  2505. expect(isVirtualPath("qmd://collection/path.md")).toBe(true);
  2506. expect(isVirtualPath("qmd://journals/2025-01-01.md")).toBe(true);
  2507. expect(isVirtualPath("qmd://collection")).toBe(true);
  2508. });
  2509. test("recognizes //collection/path format", () => {
  2510. expect(isVirtualPath("//collection/path.md")).toBe(true);
  2511. expect(isVirtualPath("//journals/2025-01-01.md")).toBe(true);
  2512. });
  2513. test("does not auto-recognize bare collection/path format", () => {
  2514. // Bare paths could be relative filesystem paths, so not auto-detected as virtual
  2515. expect(isVirtualPath("collection/path.md")).toBe(false);
  2516. expect(isVirtualPath("journals/2025-01-01.md")).toBe(false);
  2517. expect(isVirtualPath("archive/subfolder/file.md")).toBe(false);
  2518. });
  2519. test("rejects docid format", () => {
  2520. expect(isVirtualPath("#abc123")).toBe(false);
  2521. expect(isVirtualPath("#def456")).toBe(false);
  2522. });
  2523. test("rejects absolute filesystem paths", () => {
  2524. expect(isVirtualPath("/Users/test/file.md")).toBe(false);
  2525. expect(isVirtualPath("/absolute/path/file.md")).toBe(false);
  2526. });
  2527. test("rejects home-relative paths", () => {
  2528. expect(isVirtualPath("~/Documents/file.md")).toBe(false);
  2529. expect(isVirtualPath("~/notes/journal.md")).toBe(false);
  2530. });
  2531. test("rejects paths without slashes", () => {
  2532. expect(isVirtualPath("file.md")).toBe(false);
  2533. expect(isVirtualPath("document")).toBe(false);
  2534. });
  2535. });
  2536. describe("parseVirtualPath", () => {
  2537. test("parses standard qmd:// paths", () => {
  2538. expect(parseVirtualPath("qmd://collection/path.md")).toEqual({
  2539. collectionName: "collection",
  2540. path: "path.md",
  2541. });
  2542. expect(parseVirtualPath("qmd://journals/2025-01-01.md")).toEqual({
  2543. collectionName: "journals",
  2544. path: "2025-01-01.md",
  2545. });
  2546. });
  2547. test("parses paths with nested directories", () => {
  2548. expect(parseVirtualPath("qmd://archive/subfolder/file.md")).toEqual({
  2549. collectionName: "archive",
  2550. path: "subfolder/file.md",
  2551. });
  2552. });
  2553. test("parses collection root paths", () => {
  2554. expect(parseVirtualPath("qmd://collection/")).toEqual({
  2555. collectionName: "collection",
  2556. path: "",
  2557. });
  2558. expect(parseVirtualPath("qmd://collection")).toEqual({
  2559. collectionName: "collection",
  2560. path: "",
  2561. });
  2562. });
  2563. test("parses //collection/path format (normalizes first)", () => {
  2564. expect(parseVirtualPath("//collection/path.md")).toEqual({
  2565. collectionName: "collection",
  2566. path: "path.md",
  2567. });
  2568. });
  2569. test("parses qmd:// with extra slashes (normalizes first)", () => {
  2570. expect(parseVirtualPath("qmd:////collection/path.md")).toEqual({
  2571. collectionName: "collection",
  2572. path: "path.md",
  2573. });
  2574. });
  2575. test("parses qmd:// paths with index query parameters", () => {
  2576. expect(parseVirtualPath("qmd://collection/path.md?index=docs-v2")).toEqual({
  2577. collectionName: "collection",
  2578. path: "path.md",
  2579. indexName: "docs-v2",
  2580. });
  2581. });
  2582. test("returns null for non-virtual paths", () => {
  2583. expect(parseVirtualPath("/absolute/path.md")).toBe(null);
  2584. expect(parseVirtualPath("~/home/path.md")).toBe(null);
  2585. expect(parseVirtualPath("#docid")).toBe(null);
  2586. expect(parseVirtualPath("file.md")).toBe(null);
  2587. // Bare collection/path is not recognized as virtual
  2588. expect(parseVirtualPath("collection/path.md")).toBe(null);
  2589. });
  2590. });
  2591. // =============================================================================
  2592. // Docid Functions
  2593. // =============================================================================
  2594. describe("normalizeDocid", () => {
  2595. test("strips leading # from docid", () => {
  2596. expect(normalizeDocid("#abc123")).toBe("abc123");
  2597. expect(normalizeDocid("#def456")).toBe("def456");
  2598. });
  2599. test("returns bare hex unchanged", () => {
  2600. expect(normalizeDocid("abc123")).toBe("abc123");
  2601. expect(normalizeDocid("def456")).toBe("def456");
  2602. });
  2603. test("strips surrounding double quotes", () => {
  2604. expect(normalizeDocid('"#abc123"')).toBe("abc123");
  2605. expect(normalizeDocid('"abc123"')).toBe("abc123");
  2606. });
  2607. test("strips surrounding single quotes", () => {
  2608. expect(normalizeDocid("'#abc123'")).toBe("abc123");
  2609. expect(normalizeDocid("'abc123'")).toBe("abc123");
  2610. });
  2611. test("handles quoted docid without #", () => {
  2612. expect(normalizeDocid('"def456"')).toBe("def456");
  2613. expect(normalizeDocid("'def456'")).toBe("def456");
  2614. });
  2615. test("handles whitespace", () => {
  2616. expect(normalizeDocid(" #abc123 ")).toBe("abc123");
  2617. expect(normalizeDocid(" abc123 ")).toBe("abc123");
  2618. });
  2619. test("handles uppercase hex", () => {
  2620. expect(normalizeDocid("#ABC123")).toBe("ABC123");
  2621. expect(normalizeDocid('"ABC123"')).toBe("ABC123");
  2622. });
  2623. test("does not strip mismatched quotes", () => {
  2624. expect(normalizeDocid('"abc123\'')).toBe('"abc123\'');
  2625. expect(normalizeDocid("'abc123\"")).toBe("'abc123\"");
  2626. });
  2627. });
  2628. describe("isDocid", () => {
  2629. test("accepts #hash format", () => {
  2630. expect(isDocid("#abc123")).toBe(true);
  2631. expect(isDocid("#def456")).toBe(true);
  2632. expect(isDocid("#ABCDEF")).toBe(true);
  2633. });
  2634. test("accepts bare 6-char hex", () => {
  2635. expect(isDocid("abc123")).toBe(true);
  2636. expect(isDocid("def456")).toBe(true);
  2637. expect(isDocid("ABCDEF")).toBe(true);
  2638. });
  2639. test("accepts longer hex strings", () => {
  2640. expect(isDocid("abc123def456")).toBe(true);
  2641. expect(isDocid("#abc123def456")).toBe(true);
  2642. });
  2643. test("accepts double-quoted docids", () => {
  2644. expect(isDocid('"#abc123"')).toBe(true);
  2645. expect(isDocid('"abc123"')).toBe(true);
  2646. });
  2647. test("accepts single-quoted docids", () => {
  2648. expect(isDocid("'#abc123'")).toBe(true);
  2649. expect(isDocid("'abc123'")).toBe(true);
  2650. });
  2651. test("rejects non-hex strings", () => {
  2652. expect(isDocid("ghijkl")).toBe(false);
  2653. expect(isDocid("#ghijkl")).toBe(false);
  2654. expect(isDocid("abc12g")).toBe(false);
  2655. });
  2656. test("rejects strings shorter than 6 chars", () => {
  2657. expect(isDocid("abc12")).toBe(false);
  2658. expect(isDocid("#abc1")).toBe(false);
  2659. expect(isDocid("'abc'")).toBe(false);
  2660. });
  2661. test("rejects empty strings", () => {
  2662. expect(isDocid("")).toBe(false);
  2663. expect(isDocid("#")).toBe(false);
  2664. expect(isDocid('""')).toBe(false);
  2665. });
  2666. test("rejects file paths", () => {
  2667. expect(isDocid("/path/to/file.md")).toBe(false);
  2668. expect(isDocid("path/to/file.md")).toBe(false);
  2669. expect(isDocid("qmd://collection/file.md")).toBe(false);
  2670. });
  2671. test("rejects paths that look like hex with extensions", () => {
  2672. expect(isDocid("abc123.md")).toBe(false);
  2673. });
  2674. });