store.test.ts 117 KB

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