store.test.ts 106 KB

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