store.test.ts 108 KB

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