store.test.ts 113 KB

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