store.test.ts 116 KB

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