cli.test.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. /**
  2. * CLI Integration Tests
  3. *
  4. * Tests all qmd CLI commands using a temporary test database via INDEX_PATH.
  5. * These tests spawn actual qmd processes to verify end-to-end functionality.
  6. */
  7. import { describe, test, expect, beforeAll, afterAll, beforeEach } from "vitest";
  8. import { mkdtemp, rm, writeFile, mkdir } from "fs/promises";
  9. import { existsSync, lstatSync, readFileSync, symlinkSync, writeFileSync, unlinkSync } from "fs";
  10. import { tmpdir } from "os";
  11. import { join, dirname } from "path";
  12. import { fileURLToPath } from "url";
  13. import { spawn } from "child_process";
  14. import { setTimeout as sleep } from "timers/promises";
  15. import { buildEditorUri, termLink } from "../src/cli/qmd.ts";
  16. // Test fixtures directory and database path
  17. let testDir: string;
  18. let testDbPath: string;
  19. let testConfigDir: string;
  20. let fixturesDir: string;
  21. let testCounter = 0; // Unique counter for each test run
  22. // Get the directory where this test file lives
  23. const thisDir = dirname(fileURLToPath(import.meta.url));
  24. const projectRoot = join(thisDir, "..");
  25. const qmdScript = join(projectRoot, "src", "cli", "qmd.ts");
  26. // Resolve tsx binary from project's node_modules (not cwd-dependent)
  27. const tsxBin = (() => {
  28. const candidate = join(projectRoot, "node_modules", ".bin", "tsx");
  29. if (existsSync(candidate)) {
  30. return candidate;
  31. }
  32. return join(process.cwd(), "node_modules", ".bin", "tsx");
  33. })();
  34. // Helper to run qmd command with test database
  35. async function runQmd(
  36. args: string[],
  37. options: { cwd?: string; env?: Record<string, string>; dbPath?: string; configDir?: string } = {}
  38. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  39. const workingDir = options.cwd || fixturesDir;
  40. const dbPath = options.dbPath || testDbPath;
  41. const configDir = options.configDir || testConfigDir;
  42. const proc = spawn(tsxBin, [qmdScript, ...args], {
  43. cwd: workingDir,
  44. env: {
  45. ...process.env,
  46. INDEX_PATH: dbPath,
  47. QMD_CONFIG_DIR: configDir, // Use test config directory
  48. PWD: workingDir, // Must explicitly set PWD since getPwd() checks this
  49. ...options.env,
  50. },
  51. stdio: ["ignore", "pipe", "pipe"],
  52. });
  53. const stdoutPromise = new Promise<string>((resolve, reject) => {
  54. let data = "";
  55. proc.stdout?.on("data", (chunk: Buffer) => { data += chunk.toString(); });
  56. proc.once("error", reject);
  57. proc.stdout?.once("end", () => resolve(data));
  58. });
  59. const stderrPromise = new Promise<string>((resolve, reject) => {
  60. let data = "";
  61. proc.stderr?.on("data", (chunk: Buffer) => { data += chunk.toString(); });
  62. proc.once("error", reject);
  63. proc.stderr?.once("end", () => resolve(data));
  64. });
  65. const exitCode = await new Promise<number>((resolve, reject) => {
  66. proc.once("error", reject);
  67. proc.on("close", (code) => resolve(code ?? 1));
  68. });
  69. const stdout = await stdoutPromise;
  70. const stderr = await stderrPromise;
  71. return { stdout, stderr, exitCode };
  72. }
  73. // Get a fresh database path for isolated tests
  74. function getFreshDbPath(): string {
  75. testCounter++;
  76. return join(testDir, `test-${testCounter}.sqlite`);
  77. }
  78. // Create an isolated test environment (db + config dir)
  79. async function createIsolatedTestEnv(prefix: string): Promise<{ dbPath: string; configDir: string }> {
  80. testCounter++;
  81. const dbPath = join(testDir, `${prefix}-${testCounter}.sqlite`);
  82. const configDir = join(testDir, `${prefix}-config-${testCounter}`);
  83. await mkdir(configDir, { recursive: true });
  84. await writeFile(join(configDir, "index.yml"), "collections: {}\n");
  85. return { dbPath, configDir };
  86. }
  87. // Setup test fixtures
  88. beforeAll(async () => {
  89. // Create temp directory structure
  90. testDir = await mkdtemp(join(tmpdir(), "qmd-test-"));
  91. testDbPath = join(testDir, "test.sqlite");
  92. testConfigDir = join(testDir, "config");
  93. fixturesDir = join(testDir, "fixtures");
  94. await mkdir(testConfigDir, { recursive: true });
  95. await mkdir(fixturesDir, { recursive: true });
  96. await mkdir(join(fixturesDir, "notes"), { recursive: true });
  97. await mkdir(join(fixturesDir, "docs"), { recursive: true });
  98. // Create empty YAML config for tests
  99. await writeFile(
  100. join(testConfigDir, "index.yml"),
  101. "collections: {}\n"
  102. );
  103. // Create test markdown files
  104. await writeFile(
  105. join(fixturesDir, "README.md"),
  106. `# Test Project
  107. This is a test project for QMD CLI testing.
  108. ## Features
  109. - Full-text search with BM25
  110. - Vector similarity search
  111. - Hybrid search with reranking
  112. `
  113. );
  114. await writeFile(
  115. join(fixturesDir, "notes", "meeting.md"),
  116. `# Team Meeting Notes
  117. Date: 2024-01-15
  118. ## Attendees
  119. - Alice
  120. - Bob
  121. - Charlie
  122. ## Discussion Topics
  123. - Project timeline review
  124. - Resource allocation
  125. - Technical debt prioritization
  126. ## Action Items
  127. 1. Alice to update documentation
  128. 2. Bob to fix authentication bug
  129. 3. Charlie to review pull requests
  130. `
  131. );
  132. await writeFile(
  133. join(fixturesDir, "notes", "ideas.md"),
  134. `# Product Ideas
  135. ## Feature Requests
  136. - Dark mode support
  137. - Keyboard shortcuts
  138. - Export to PDF
  139. ## Technical Improvements
  140. - Improve search performance
  141. - Add caching layer
  142. - Optimize database queries
  143. `
  144. );
  145. await writeFile(
  146. join(fixturesDir, "docs", "api.md"),
  147. `# API Documentation
  148. ## Endpoints
  149. ### GET /search
  150. Search for documents.
  151. Parameters:
  152. - q: Search query (required)
  153. - limit: Max results (default: 10)
  154. ### GET /document/:id
  155. Retrieve a specific document.
  156. ### POST /index
  157. Index new documents.
  158. `
  159. );
  160. // Create test files for path normalization tests
  161. await writeFile(
  162. join(fixturesDir, "test1.md"),
  163. `# Test Document 1
  164. This is the first test document.
  165. It has multiple lines for testing line numbers.
  166. Line 6 is here.
  167. Line 7 is here.
  168. `
  169. );
  170. await writeFile(
  171. join(fixturesDir, "test2.md"),
  172. `# Test Document 2
  173. This is the second test document.
  174. `
  175. );
  176. });
  177. // Cleanup after all tests
  178. afterAll(async () => {
  179. if (testDir) {
  180. await rm(testDir, { recursive: true, force: true });
  181. }
  182. });
  183. // Reset YAML config before each test to ensure isolation
  184. beforeEach(async () => {
  185. // Reset to empty collections config
  186. await writeFile(
  187. join(testConfigDir, "index.yml"),
  188. "collections: {}\n"
  189. );
  190. });
  191. describe("CLI Help", () => {
  192. test("shows help with --help flag", async () => {
  193. const { stdout, exitCode } = await runQmd(["--help"]);
  194. expect(exitCode).toBe(0);
  195. expect(stdout).toContain("Usage:");
  196. expect(stdout).toContain("qmd collection add");
  197. expect(stdout).toContain("qmd search");
  198. expect(stdout).toContain("qmd skill show/install");
  199. });
  200. test("shows help with no arguments", async () => {
  201. const { stdout, exitCode } = await runQmd([]);
  202. expect(exitCode).toBe(1);
  203. expect(stdout).toContain("Usage:");
  204. });
  205. });
  206. describe("CLI Embed", () => {
  207. test("rejects invalid --max-docs-per-batch", async () => {
  208. const { stderr, exitCode } = await runQmd(["embed", "--max-docs-per-batch", "0"]);
  209. expect(exitCode).toBe(1);
  210. expect(stderr).toContain("maxDocsPerBatch");
  211. });
  212. test("rejects invalid --max-batch-mb", async () => {
  213. const { stderr, exitCode } = await runQmd(["embed", "--max-batch-mb", "0"]);
  214. expect(exitCode).toBe(1);
  215. expect(stderr).toContain("maxBatchBytes");
  216. });
  217. // i-ofojj7dy — collection-filter ergonomics for embed
  218. test("embed <unknown-collection> exits non-zero with available list", async () => {
  219. const { dbPath, configDir } = await createIsolatedTestEnv("embed-unknown");
  220. const aDir = join(testDir, `embed-unknown-a-${Date.now()}`);
  221. await mkdir(aDir, { recursive: true });
  222. await writeFile(join(aDir, "e.md"), "# E");
  223. expect((await runQmd(["collection", "add", aDir, "--name", "embed-real"], { dbPath, configDir })).exitCode).toBe(0);
  224. const { stderr, exitCode } = await runQmd(["embed", "embed-ghost"], { dbPath, configDir });
  225. expect(exitCode).toBe(1);
  226. expect(stderr).toContain("Collection not found");
  227. expect(stderr).toContain("embed-ghost");
  228. expect(stderr).toContain("embed-real");
  229. });
  230. test("embed <collection> --force rejects the conflict", async () => {
  231. const { dbPath, configDir } = await createIsolatedTestEnv("embed-force-conflict");
  232. const aDir = join(testDir, `embed-force-conflict-a-${Date.now()}`);
  233. await mkdir(aDir, { recursive: true });
  234. await writeFile(join(aDir, "f.md"), "# F");
  235. expect((await runQmd(["collection", "add", aDir, "--name", "ef-a"], { dbPath, configDir })).exitCode).toBe(0);
  236. const { stderr, exitCode } = await runQmd(["embed", "ef-a", "--force"], { dbPath, configDir });
  237. expect(exitCode).toBe(1);
  238. expect(stderr).toContain("--force cannot be combined with a positional collection name");
  239. });
  240. test("embed --all + positional name is a conflict error", async () => {
  241. const { dbPath, configDir } = await createIsolatedTestEnv("embed-all-conflict");
  242. const aDir = join(testDir, `embed-all-conflict-a-${Date.now()}`);
  243. await mkdir(aDir, { recursive: true });
  244. await writeFile(join(aDir, "g.md"), "# G");
  245. expect((await runQmd(["collection", "add", aDir, "--name", "eac-a"], { dbPath, configDir })).exitCode).toBe(0);
  246. const { stderr, exitCode } = await runQmd(["embed", "eac-a", "--all"], { dbPath, configDir });
  247. expect(exitCode).toBe(1);
  248. expect(stderr).toContain("Conflicting arguments");
  249. });
  250. });
  251. describe("CLI Skill Commands", () => {
  252. test("shows embedded skill with --skill alias", async () => {
  253. const { stdout, exitCode } = await runQmd(["--skill"]);
  254. expect(exitCode).toBe(0);
  255. expect(stdout).toContain("QMD Skill (embedded)");
  256. expect(stdout).toContain("name: qmd");
  257. expect(stdout).toContain("allowed-tools: Bash(qmd:*), mcp__qmd__*");
  258. });
  259. test("shows skill help with -h", async () => {
  260. const { stdout, exitCode } = await runQmd(["skill", "-h"]);
  261. expect(exitCode).toBe(0);
  262. expect(stdout).toContain("Usage: qmd skill <show|install> [options]");
  263. expect(stdout).toContain("install");
  264. expect(stdout).toContain("--global");
  265. });
  266. test("installs the skill into the current project", async () => {
  267. const projectDir = join(testDir, "skill-project");
  268. await mkdir(projectDir, { recursive: true });
  269. const { stdout, exitCode } = await runQmd(["skill", "install"], { cwd: projectDir });
  270. expect(exitCode).toBe(0);
  271. const skillDir = join(projectDir, ".agents", "skills", "qmd");
  272. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  273. expect(readFileSync(join(skillDir, "references", "mcp-setup.md"), "utf-8")).toContain("Claude Code");
  274. expect(existsSync(join(projectDir, ".claude", "skills", "qmd"))).toBe(false);
  275. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  276. expect(stdout).toContain("Tip: create a Claude symlink manually");
  277. });
  278. test("installs globally and creates the Claude symlink with --yes", async () => {
  279. const fakeHome = join(testDir, "skill-home");
  280. await mkdir(fakeHome, { recursive: true });
  281. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  282. env: { HOME: fakeHome },
  283. });
  284. expect(exitCode).toBe(0);
  285. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  286. const claudeLink = join(fakeHome, ".claude", "skills", "qmd");
  287. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  288. expect(lstatSync(claudeLink).isSymbolicLink()).toBe(true);
  289. expect(readFileSync(join(claudeLink, "SKILL.md"), "utf-8")).toContain("name: qmd");
  290. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  291. expect(stdout).toContain(`✓ Linked Claude skill at ${claudeLink}`);
  292. });
  293. test("skips Claude qmd symlink when .claude/skills already points to .agents/skills", async () => {
  294. const fakeHome = join(testDir, "skill-home-shared");
  295. await mkdir(join(fakeHome, ".agents"), { recursive: true });
  296. await mkdir(join(fakeHome, ".claude"), { recursive: true });
  297. symlinkSync(join(fakeHome, ".agents", "skills"), join(fakeHome, ".claude", "skills"), "dir");
  298. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  299. env: { HOME: fakeHome },
  300. });
  301. expect(exitCode).toBe(0);
  302. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  303. expect(lstatSync(skillDir).isSymbolicLink()).toBe(false);
  304. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  305. expect(stdout).toContain(`✓ Claude already sees the skill via ${join(fakeHome, ".claude", "skills")}`);
  306. });
  307. test("refuses to overwrite an existing install without --force", async () => {
  308. const projectDir = join(testDir, "skill-project-force");
  309. await mkdir(projectDir, { recursive: true });
  310. const first = await runQmd(["skill", "install"], { cwd: projectDir });
  311. expect(first.exitCode).toBe(0);
  312. const second = await runQmd(["skill", "install"], { cwd: projectDir });
  313. expect(second.exitCode).toBe(1);
  314. expect(second.stderr).toContain("Skill already exists");
  315. expect(second.stderr).toContain("--force");
  316. });
  317. });
  318. describe("CLI Add Command", () => {
  319. test("adds files from current directory", async () => {
  320. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  321. expect(exitCode).toBe(0);
  322. expect(stdout).toContain("Collection:");
  323. expect(stdout).toContain("Indexed:");
  324. });
  325. test("adds files with custom glob pattern", async () => {
  326. const { stdout, stderr, exitCode } = await runQmd(["collection", "add", ".", "--mask", "notes/*.md"]);
  327. if (exitCode !== 0) {
  328. console.error("Command failed:", stderr);
  329. }
  330. expect(exitCode).toBe(0);
  331. expect(stdout).toContain("Collection:");
  332. // Should find meeting.md and ideas.md in notes/
  333. expect(stdout).toContain("notes/*.md");
  334. });
  335. test("can recreate collection with remove and add", async () => {
  336. // First add
  337. await runQmd(["collection", "add", "."]);
  338. // Remove it
  339. await runQmd(["collection", "remove", "fixtures"]);
  340. // Re-add
  341. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  342. expect(exitCode).toBe(0);
  343. expect(stdout).toContain("Collection 'fixtures' created successfully");
  344. });
  345. });
  346. describe("CLI Status Command", () => {
  347. beforeEach(async () => {
  348. // Ensure we have indexed files
  349. await runQmd(["collection", "add", "."]);
  350. });
  351. test("shows index status", async () => {
  352. const { stdout, exitCode } = await runQmd(["status"]);
  353. expect(exitCode).toBe(0);
  354. // Should show collection info
  355. expect(stdout).toContain("Collection");
  356. });
  357. });
  358. describe("CLI Search Command", () => {
  359. beforeEach(async () => {
  360. // Ensure we have indexed files
  361. await runQmd(["collection", "add", "."]);
  362. });
  363. test("searches for documents with BM25", async () => {
  364. const { stdout, exitCode } = await runQmd(["search", "meeting"]);
  365. expect(exitCode).toBe(0);
  366. // Should find meeting.md
  367. expect(stdout.toLowerCase()).toContain("meeting");
  368. });
  369. test("searches with limit option", async () => {
  370. const { stdout, exitCode } = await runQmd(["search", "-n", "1", "test"]);
  371. expect(exitCode).toBe(0);
  372. });
  373. test("searches with all results option", async () => {
  374. const { stdout, exitCode } = await runQmd(["search", "--all", "the"]);
  375. expect(exitCode).toBe(0);
  376. });
  377. test("returns no results message for non-matching query", async () => {
  378. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123"]);
  379. expect(exitCode).toBe(0);
  380. expect(stdout).toContain("No results");
  381. });
  382. test("returns empty JSON array for non-matching query with --json", async () => {
  383. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--json"]);
  384. expect(exitCode).toBe(0);
  385. expect(JSON.parse(stdout)).toEqual([]);
  386. });
  387. test("returns CSV header only for non-matching query with --csv", async () => {
  388. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--csv"]);
  389. expect(exitCode).toBe(0);
  390. expect(stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  391. });
  392. test("returns empty XML container for non-matching query with --xml", async () => {
  393. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--xml"]);
  394. expect(exitCode).toBe(0);
  395. expect(stdout.trim()).toBe("<results></results>");
  396. });
  397. test("returns empty output for non-matching query with --md", async () => {
  398. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--md"]);
  399. expect(exitCode).toBe(0);
  400. expect(stdout.trim()).toBe("");
  401. });
  402. test("returns empty output for non-matching query with --files", async () => {
  403. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--files"]);
  404. expect(exitCode).toBe(0);
  405. expect(stdout.trim()).toBe("");
  406. });
  407. test("returns min-score threshold message for default CLI output", async () => {
  408. const { stdout, exitCode } = await runQmd(["search", "test", "--min-score", "2"]);
  409. expect(exitCode).toBe(0);
  410. expect(stdout).toContain("No results found above minimum score threshold.");
  411. });
  412. test("returns format-safe empty output when --min-score filters all results", async () => {
  413. const json = await runQmd(["search", "test", "--json", "--min-score", "2"]);
  414. expect(json.exitCode).toBe(0);
  415. expect(JSON.parse(json.stdout)).toEqual([]);
  416. const csv = await runQmd(["search", "test", "--csv", "--min-score", "2"]);
  417. expect(csv.exitCode).toBe(0);
  418. expect(csv.stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  419. const xml = await runQmd(["search", "test", "--xml", "--min-score", "2"]);
  420. expect(xml.exitCode).toBe(0);
  421. expect(xml.stdout.trim()).toBe("<results></results>");
  422. const md = await runQmd(["search", "test", "--md", "--min-score", "2"]);
  423. expect(md.exitCode).toBe(0);
  424. expect(md.stdout.trim()).toBe("");
  425. const files = await runQmd(["search", "test", "--files", "--min-score", "2"]);
  426. expect(files.exitCode).toBe(0);
  427. expect(files.stdout.trim()).toBe("");
  428. });
  429. test("requires query argument", async () => {
  430. const { stdout, stderr, exitCode } = await runQmd(["search"]);
  431. expect(exitCode).toBe(1);
  432. // Error message goes to stderr
  433. expect(stderr).toContain("Usage:");
  434. });
  435. });
  436. describe("CLI Get Command", () => {
  437. beforeEach(async () => {
  438. // Ensure we have indexed files
  439. await runQmd(["collection", "add", "."]);
  440. });
  441. test("retrieves document content by path", async () => {
  442. const { stdout, exitCode } = await runQmd(["get", "README.md"]);
  443. expect(exitCode).toBe(0);
  444. expect(stdout).toContain("Test Project");
  445. });
  446. test("retrieves document from subdirectory", async () => {
  447. const { stdout, exitCode } = await runQmd(["get", "notes/meeting.md"]);
  448. expect(exitCode).toBe(0);
  449. expect(stdout).toContain("Team Meeting");
  450. });
  451. test("handles non-existent file", async () => {
  452. const { stdout, exitCode } = await runQmd(["get", "nonexistent.md"]);
  453. // Should indicate file not found
  454. expect(exitCode).toBe(1);
  455. });
  456. });
  457. describe("CLI Multi-Get Command", () => {
  458. let localDbPath: string;
  459. beforeEach(async () => {
  460. // Use fresh database for each test
  461. localDbPath = getFreshDbPath();
  462. // Ensure we have indexed files
  463. const addResult = await runQmd(["collection", "add", ".", "--name", "fixtures"], { dbPath: localDbPath });
  464. if (addResult.exitCode !== 0) {
  465. throw new Error(`Failed to add collection: ${addResult.stderr}`);
  466. }
  467. });
  468. test("retrieves multiple documents by pattern", async () => {
  469. // Test glob pattern matching
  470. const { stdout, stderr, exitCode } = await runQmd(["multi-get", "notes/*.md"], { dbPath: localDbPath });
  471. expect(exitCode).toBe(0);
  472. // Should contain content from both notes files
  473. expect(stdout).toContain("Meeting");
  474. expect(stdout).toContain("Ideas");
  475. });
  476. test("retrieves documents by comma-separated paths", async () => {
  477. const { stdout, exitCode } = await runQmd([
  478. "multi-get",
  479. "README.md,notes/meeting.md",
  480. ], { dbPath: localDbPath });
  481. expect(exitCode).toBe(0);
  482. expect(stdout).toContain("Test Project");
  483. expect(stdout).toContain("Team Meeting");
  484. });
  485. });
  486. describe("CLI Update Command", () => {
  487. let localDbPath: string;
  488. beforeEach(async () => {
  489. // Use a fresh database for this test suite
  490. localDbPath = getFreshDbPath();
  491. // Ensure we have indexed files
  492. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  493. });
  494. test("updates all collections", async () => {
  495. const { stdout, exitCode } = await runQmd(["update"], { dbPath: localDbPath });
  496. expect(exitCode).toBe(0);
  497. expect(stdout).toContain("Updating");
  498. });
  499. // i-ofojj7dy — collection-filter ergonomics
  500. test("update <collection> filters to a single collection", async () => {
  501. const { dbPath, configDir } = await createIsolatedTestEnv("update-filter");
  502. // Two collections in one config; each gets its own fixture dir
  503. const aDir = join(testDir, `update-filter-a-${Date.now()}`);
  504. const bDir = join(testDir, `update-filter-b-${Date.now()}`);
  505. await mkdir(aDir, { recursive: true });
  506. await mkdir(bDir, { recursive: true });
  507. await writeFile(join(aDir, "x.md"), "# X");
  508. await writeFile(join(bDir, "y.md"), "# Y");
  509. expect((await runQmd(["collection", "add", aDir, "--name", "filter-a"], { dbPath, configDir })).exitCode).toBe(0);
  510. expect((await runQmd(["collection", "add", bDir, "--name", "filter-b"], { dbPath, configDir })).exitCode).toBe(0);
  511. const { stdout, exitCode } = await runQmd(["update", "filter-a"], { dbPath, configDir });
  512. expect(exitCode).toBe(0);
  513. expect(stdout).toContain("Updating 1 collection(s)");
  514. expect(stdout).toContain("filter-a");
  515. expect(stdout).not.toContain("filter-b");
  516. });
  517. test("update <unknown-collection> exits non-zero with available list", async () => {
  518. const { dbPath, configDir } = await createIsolatedTestEnv("update-unknown");
  519. const aDir = join(testDir, `update-unknown-a-${Date.now()}`);
  520. await mkdir(aDir, { recursive: true });
  521. await writeFile(join(aDir, "z.md"), "# Z");
  522. expect((await runQmd(["collection", "add", aDir, "--name", "real-name"], { dbPath, configDir })).exitCode).toBe(0);
  523. const { stderr, exitCode } = await runQmd(["update", "ghost-collection"], { dbPath, configDir });
  524. expect(exitCode).toBe(1);
  525. expect(stderr).toContain("Collection not found");
  526. expect(stderr).toContain("ghost-collection");
  527. expect(stderr).toContain("real-name");
  528. });
  529. test("update --all behaves like update with no args (full-fleet)", async () => {
  530. const { dbPath, configDir } = await createIsolatedTestEnv("update-all");
  531. const aDir = join(testDir, `update-all-a-${Date.now()}`);
  532. const bDir = join(testDir, `update-all-b-${Date.now()}`);
  533. await mkdir(aDir, { recursive: true });
  534. await mkdir(bDir, { recursive: true });
  535. await writeFile(join(aDir, "u.md"), "# U");
  536. await writeFile(join(bDir, "v.md"), "# V");
  537. expect((await runQmd(["collection", "add", aDir, "--name", "all-a"], { dbPath, configDir })).exitCode).toBe(0);
  538. expect((await runQmd(["collection", "add", bDir, "--name", "all-b"], { dbPath, configDir })).exitCode).toBe(0);
  539. const { stdout, exitCode } = await runQmd(["update", "--all"], { dbPath, configDir });
  540. expect(exitCode).toBe(0);
  541. expect(stdout).toContain("Updating 2 collection(s)");
  542. expect(stdout).toContain("all-a");
  543. expect(stdout).toContain("all-b");
  544. });
  545. test("update --all + positional name is a conflict error", async () => {
  546. const { dbPath, configDir } = await createIsolatedTestEnv("update-conflict");
  547. const aDir = join(testDir, `update-conflict-a-${Date.now()}`);
  548. await mkdir(aDir, { recursive: true });
  549. await writeFile(join(aDir, "c.md"), "# C");
  550. expect((await runQmd(["collection", "add", aDir, "--name", "conflict-a"], { dbPath, configDir })).exitCode).toBe(0);
  551. const { stderr, exitCode } = await runQmd(["update", "conflict-a", "--all"], { dbPath, configDir });
  552. expect(exitCode).toBe(1);
  553. expect(stderr).toContain("Conflicting arguments");
  554. });
  555. test("deactivates stale docs when collection has zero matching files", async () => {
  556. const { dbPath, configDir } = await createIsolatedTestEnv("update-empty");
  557. const collectionDir = join(testDir, `update-empty-${Date.now()}`);
  558. await mkdir(collectionDir, { recursive: true });
  559. const docPath = join(collectionDir, "only.md");
  560. const token = `stale-proof-${Date.now()}`;
  561. await writeFile(
  562. docPath,
  563. `---
  564. date: 2026-03-06
  565. ---
  566. # Empty Collection Deactivation
  567. ${token}
  568. `
  569. );
  570. const add = await runQmd(
  571. ["collection", "add", collectionDir, "--name", "empty-check"],
  572. { dbPath, configDir }
  573. );
  574. expect(add.exitCode).toBe(0);
  575. const before = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  576. expect(before.exitCode).toBe(0);
  577. expect(before.stdout).toContain(token);
  578. unlinkSync(docPath);
  579. const update = await runQmd(["update"], { dbPath, configDir });
  580. expect(update.exitCode).toBe(0);
  581. expect(update.stdout).toContain("0 new, 0 updated, 0 unchanged, 1 removed");
  582. const after = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  583. expect(after.exitCode).toBe(1);
  584. });
  585. });
  586. describe("CLI Add-Context Command", () => {
  587. let localDbPath: string;
  588. let localConfigDir: string;
  589. const collName = "fixtures";
  590. beforeAll(async () => {
  591. const env = await createIsolatedTestEnv("context-cmd");
  592. localDbPath = env.dbPath;
  593. localConfigDir = env.configDir;
  594. // Add collection with known name
  595. const { exitCode, stderr } = await runQmd(
  596. ["collection", "add", fixturesDir, "--name", collName],
  597. { dbPath: localDbPath, configDir: localConfigDir }
  598. );
  599. if (exitCode !== 0) console.error("collection add failed:", stderr);
  600. expect(exitCode).toBe(0);
  601. });
  602. test("adds context to a path", async () => {
  603. // Add context to the collection root using virtual path
  604. const { stdout, exitCode } = await runQmd([
  605. "context",
  606. "add",
  607. `qmd://${collName}/`,
  608. "Personal notes and meeting logs",
  609. ], { dbPath: localDbPath, configDir: localConfigDir });
  610. expect(exitCode).toBe(0);
  611. expect(stdout).toContain("✓ Added context");
  612. });
  613. test("requires path and text arguments", async () => {
  614. const { stderr, exitCode } = await runQmd(["context", "add"], { dbPath: localDbPath, configDir: localConfigDir });
  615. expect(exitCode).toBe(1);
  616. // Error message goes to stderr
  617. expect(stderr).toContain("Usage:");
  618. });
  619. });
  620. describe("CLI Cleanup Command", () => {
  621. beforeEach(async () => {
  622. // Ensure we have indexed files
  623. await runQmd(["collection", "add", "."]);
  624. });
  625. test("cleans up orphaned entries", async () => {
  626. const { stdout, exitCode } = await runQmd(["cleanup"]);
  627. expect(exitCode).toBe(0);
  628. });
  629. });
  630. describe("CLI Error Handling", () => {
  631. test("handles unknown command", async () => {
  632. const { stderr, exitCode } = await runQmd(["unknowncommand"]);
  633. expect(exitCode).toBe(1);
  634. // Should indicate unknown command
  635. expect(stderr).toContain("Unknown command");
  636. });
  637. test("uses INDEX_PATH environment variable", async () => {
  638. // Verify the test DB path is being used by creating a separate index
  639. const customDbPath = join(testDir, "custom.sqlite");
  640. const { exitCode } = await runQmd(["collection", "add", "."], {
  641. env: { INDEX_PATH: customDbPath },
  642. });
  643. expect(exitCode).toBe(0);
  644. // The custom database should exist
  645. expect(existsSync(customDbPath)).toBe(true);
  646. });
  647. });
  648. describe("CLI Output Formats", () => {
  649. beforeEach(async () => {
  650. await runQmd(["collection", "add", "."]);
  651. });
  652. test("search with --json flag outputs JSON", async () => {
  653. const { stdout, exitCode } = await runQmd(["search", "--json", "test"]);
  654. expect(exitCode).toBe(0);
  655. // Should be valid JSON
  656. const parsed = JSON.parse(stdout);
  657. expect(Array.isArray(parsed)).toBe(true);
  658. });
  659. test("search with --files flag outputs file paths", async () => {
  660. const { stdout, exitCode } = await runQmd(["search", "--files", "meeting"]);
  661. expect(exitCode).toBe(0);
  662. expect(stdout).toContain(".md");
  663. });
  664. test("search output includes snippets by default", async () => {
  665. const { stdout, exitCode } = await runQmd(["search", "API"]);
  666. expect(exitCode).toBe(0);
  667. // If results found, should have snippet content
  668. if (!stdout.includes("No results")) {
  669. expect(stdout.toLowerCase()).toContain("api");
  670. }
  671. });
  672. });
  673. describe("CLI Search with Collection Filter", () => {
  674. let localDbPath: string;
  675. beforeEach(async () => {
  676. // Use a fresh database for this test suite
  677. localDbPath = getFreshDbPath();
  678. // Create multiple collections with explicit names
  679. await runQmd(["collection", "add", ".", "--name", "notes", "--mask", "notes/*.md"], { dbPath: localDbPath });
  680. await runQmd(["collection", "add", ".", "--name", "docs", "--mask", "docs/*.md"], { dbPath: localDbPath });
  681. });
  682. test("filters search by collection name", async () => {
  683. const { stdout, stderr, exitCode } = await runQmd([
  684. "search",
  685. "-c",
  686. "notes",
  687. "meeting",
  688. ], { dbPath: localDbPath });
  689. if (exitCode !== 0) {
  690. console.log("Collection filter search failed:");
  691. console.log("stdout:", stdout);
  692. console.log("stderr:", stderr);
  693. }
  694. expect(exitCode).toBe(0);
  695. });
  696. });
  697. describe("CLI Context Management", () => {
  698. let localDbPath: string;
  699. beforeEach(async () => {
  700. // Use a fresh database for this test suite
  701. localDbPath = getFreshDbPath();
  702. // Index some files first
  703. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  704. });
  705. test("add global context with /", async () => {
  706. const { stdout, exitCode } = await runQmd([
  707. "context",
  708. "add",
  709. "/",
  710. "Global system context",
  711. ], { dbPath: localDbPath });
  712. expect(exitCode).toBe(0);
  713. expect(stdout).toContain("✓ Set global context");
  714. expect(stdout).toContain("Global system context");
  715. });
  716. test("list contexts", async () => {
  717. // Add a global context first
  718. await runQmd([
  719. "context",
  720. "add",
  721. "/",
  722. "Test context",
  723. ], { dbPath: localDbPath });
  724. const { stdout, exitCode } = await runQmd([
  725. "context",
  726. "list",
  727. ], { dbPath: localDbPath });
  728. expect(exitCode).toBe(0);
  729. expect(stdout).toContain("Configured Contexts");
  730. expect(stdout).toContain("Test context");
  731. });
  732. test("add context to virtual path", async () => {
  733. // Collection name should be "fixtures" (basename of the fixtures directory)
  734. const { stdout, exitCode } = await runQmd([
  735. "context",
  736. "add",
  737. "qmd://fixtures/notes",
  738. "Context for notes subdirectory",
  739. ], { dbPath: localDbPath });
  740. expect(exitCode).toBe(0);
  741. expect(stdout).toContain("✓ Added context for: qmd://fixtures/notes");
  742. });
  743. test("remove global context", async () => {
  744. // Add a global context first
  745. await runQmd([
  746. "context",
  747. "add",
  748. "/",
  749. "Global context to remove",
  750. ], { dbPath: localDbPath });
  751. const { stdout, exitCode } = await runQmd([
  752. "context",
  753. "rm",
  754. "/",
  755. ], { dbPath: localDbPath });
  756. expect(exitCode).toBe(0);
  757. expect(stdout).toContain("✓ Removed");
  758. });
  759. test("remove virtual path context", async () => {
  760. // Add a context first
  761. await runQmd([
  762. "context",
  763. "add",
  764. "qmd://fixtures/notes",
  765. "Context to remove",
  766. ], { dbPath: localDbPath });
  767. const { stdout, exitCode } = await runQmd([
  768. "context",
  769. "rm",
  770. "qmd://fixtures/notes",
  771. ], { dbPath: localDbPath });
  772. expect(exitCode).toBe(0);
  773. expect(stdout).toContain("✓ Removed context for: qmd://fixtures/notes");
  774. });
  775. test("fails to remove non-existent context", async () => {
  776. const { stdout, stderr, exitCode } = await runQmd([
  777. "context",
  778. "rm",
  779. "qmd://nonexistent/path",
  780. ], { dbPath: localDbPath });
  781. expect(exitCode).toBe(1);
  782. expect(stderr || stdout).toContain("not found");
  783. });
  784. });
  785. describe("CLI ls Command", () => {
  786. let localDbPath: string;
  787. beforeEach(async () => {
  788. // Use a fresh database for this test suite
  789. localDbPath = getFreshDbPath();
  790. // Index some files first
  791. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  792. });
  793. test("lists all collections", async () => {
  794. const { stdout, exitCode } = await runQmd(["ls"], { dbPath: localDbPath });
  795. expect(exitCode).toBe(0);
  796. expect(stdout).toContain("Collections:");
  797. expect(stdout).toContain("qmd://fixtures/");
  798. });
  799. test("lists files in a collection", async () => {
  800. const { stdout, exitCode } = await runQmd(["ls", "fixtures"], { dbPath: localDbPath });
  801. expect(exitCode).toBe(0);
  802. // handelize converts to lowercase
  803. expect(stdout).toContain("qmd://fixtures/readme.md");
  804. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  805. });
  806. test("lists files with path prefix", async () => {
  807. const { stdout, exitCode } = await runQmd(["ls", "fixtures/notes"], { dbPath: localDbPath });
  808. expect(exitCode).toBe(0);
  809. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  810. expect(stdout).toContain("qmd://fixtures/notes/ideas.md");
  811. // Should not include files outside the prefix (handelize converts to lowercase)
  812. expect(stdout).not.toContain("qmd://fixtures/readme.md");
  813. });
  814. test("lists files with virtual path", async () => {
  815. const { stdout, exitCode } = await runQmd(["ls", "qmd://fixtures/docs"], { dbPath: localDbPath });
  816. expect(exitCode).toBe(0);
  817. expect(stdout).toContain("qmd://fixtures/docs/api.md");
  818. });
  819. test("handles non-existent collection", async () => {
  820. const { stderr, exitCode } = await runQmd(["ls", "nonexistent"], { dbPath: localDbPath });
  821. expect(exitCode).toBe(1);
  822. expect(stderr).toContain("Collection not found");
  823. });
  824. });
  825. describe("CLI Collection Commands", () => {
  826. let localDbPath: string;
  827. beforeEach(async () => {
  828. // Use a fresh database for this test suite
  829. localDbPath = getFreshDbPath();
  830. // Index some files first to create a collection
  831. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  832. });
  833. test("lists collections", async () => {
  834. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  835. expect(exitCode).toBe(0);
  836. expect(stdout).toContain("Collections");
  837. expect(stdout).toContain("fixtures");
  838. expect(stdout).toContain("qmd://fixtures/");
  839. expect(stdout).toContain("Pattern:");
  840. expect(stdout).toContain("Files:");
  841. });
  842. test("removes a collection", async () => {
  843. // First verify the collection exists
  844. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  845. expect(listBefore).toContain("fixtures");
  846. // Remove it
  847. const { stdout, exitCode } = await runQmd(["collection", "remove", "fixtures"], { dbPath: localDbPath });
  848. expect(exitCode).toBe(0);
  849. expect(stdout).toContain("✓ Removed collection 'fixtures'");
  850. expect(stdout).toContain("Deleted");
  851. // Verify it's gone
  852. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  853. expect(listAfter).not.toContain("fixtures");
  854. });
  855. test("handles removing non-existent collection", async () => {
  856. const { stderr, exitCode } = await runQmd(["collection", "remove", "nonexistent"], { dbPath: localDbPath });
  857. expect(exitCode).toBe(1);
  858. expect(stderr).toContain("Collection not found");
  859. });
  860. test("handles missing remove argument", async () => {
  861. const { stderr, exitCode } = await runQmd(["collection", "remove"], { dbPath: localDbPath });
  862. expect(exitCode).toBe(1);
  863. expect(stderr).toContain("Usage:");
  864. });
  865. test("handles unknown subcommand", async () => {
  866. const { stderr, exitCode } = await runQmd(["collection", "invalid"], { dbPath: localDbPath });
  867. expect(exitCode).toBe(1);
  868. expect(stderr).toContain("Unknown subcommand");
  869. });
  870. test("renames a collection", async () => {
  871. // First verify the collection exists
  872. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  873. expect(listBefore).toContain("qmd://fixtures/");
  874. // Rename it
  875. const { stdout, exitCode } = await runQmd(["collection", "rename", "fixtures", "my-fixtures"], { dbPath: localDbPath });
  876. expect(exitCode).toBe(0);
  877. expect(stdout).toContain("✓ Renamed collection 'fixtures' to 'my-fixtures'");
  878. expect(stdout).toContain("qmd://fixtures/");
  879. expect(stdout).toContain("qmd://my-fixtures/");
  880. // Verify the new name exists and old name is gone
  881. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  882. expect(listAfter).toContain("qmd://my-fixtures/");
  883. expect(listAfter).not.toContain("qmd://fixtures/"); // Old collection should not appear
  884. });
  885. test("handles renaming non-existent collection", async () => {
  886. const { stderr, exitCode } = await runQmd(["collection", "rename", "nonexistent", "newname"], { dbPath: localDbPath });
  887. expect(exitCode).toBe(1);
  888. expect(stderr).toContain("Collection not found");
  889. });
  890. test("handles renaming to existing collection name", async () => {
  891. // Create a second collection in a temp directory
  892. const tempDir = await mkdtemp(join(tmpdir(), "qmd-second-"));
  893. await writeFile(join(tempDir, "test.md"), "# Test");
  894. const addResult = await runQmd(["collection", "add", tempDir, "--name", "second"], { dbPath: localDbPath });
  895. if (addResult.exitCode !== 0) {
  896. console.error("Failed to add second collection:", addResult.stderr);
  897. }
  898. expect(addResult.exitCode).toBe(0);
  899. // Verify both collections exist
  900. const { stdout: listBoth } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  901. expect(listBoth).toContain("qmd://fixtures/");
  902. expect(listBoth).toContain("qmd://second/");
  903. // Try to rename fixtures to second (which already exists)
  904. const { stderr, exitCode } = await runQmd(["collection", "rename", "fixtures", "second"], { dbPath: localDbPath });
  905. expect(exitCode).toBe(1);
  906. expect(stderr).toContain("Collection name already exists");
  907. });
  908. test("handles missing rename arguments", async () => {
  909. const { stderr: stderr1, exitCode: exitCode1 } = await runQmd(["collection", "rename"], { dbPath: localDbPath });
  910. expect(exitCode1).toBe(1);
  911. expect(stderr1).toContain("Usage:");
  912. const { stderr: stderr2, exitCode: exitCode2 } = await runQmd(["collection", "rename", "fixtures"], { dbPath: localDbPath });
  913. expect(exitCode2).toBe(1);
  914. expect(stderr2).toContain("Usage:");
  915. });
  916. });
  917. // =============================================================================
  918. // Collection Ignore Patterns
  919. // =============================================================================
  920. describe("collection ignore patterns", () => {
  921. let localDbPath: string;
  922. let localConfigDir: string;
  923. let ignoreTestDir: string;
  924. beforeAll(async () => {
  925. const env = await createIsolatedTestEnv("ignore-patterns");
  926. localDbPath = env.dbPath;
  927. localConfigDir = env.configDir;
  928. // Create directory structure with subdirectories to ignore
  929. ignoreTestDir = join(testDir, "ignore-fixtures");
  930. await mkdir(join(ignoreTestDir, "notes"), { recursive: true });
  931. await mkdir(join(ignoreTestDir, "sessions"), { recursive: true });
  932. await mkdir(join(ignoreTestDir, "sessions", "2026-03"), { recursive: true });
  933. await mkdir(join(ignoreTestDir, "archive"), { recursive: true });
  934. // Files that should be indexed
  935. await writeFile(join(ignoreTestDir, "readme.md"), "# Main readme\nThis should be indexed.");
  936. await writeFile(join(ignoreTestDir, "notes", "note1.md"), "# Note 1\nThis is a personal note.");
  937. // Files that should be ignored
  938. await writeFile(join(ignoreTestDir, "sessions", "session1.md"), "# Session 1\nThis session should be ignored.");
  939. await writeFile(join(ignoreTestDir, "sessions", "2026-03", "session2.md"), "# Session 2\nNested session should also be ignored.");
  940. await writeFile(join(ignoreTestDir, "archive", "old.md"), "# Old stuff\nThis archive file should be ignored.");
  941. });
  942. test("ignore patterns exclude matching files from indexing", async () => {
  943. // Write YAML config with ignore patterns
  944. await writeFile(
  945. join(localConfigDir, "index.yml"),
  946. `collections:
  947. ignoretst:
  948. path: ${ignoreTestDir}
  949. pattern: "**/*.md"
  950. ignore:
  951. - "sessions/**"
  952. - "archive/**"
  953. `
  954. );
  955. const { stdout, exitCode } = await runQmd(["update"], {
  956. cwd: ignoreTestDir,
  957. dbPath: localDbPath,
  958. configDir: localConfigDir,
  959. });
  960. expect(exitCode).toBe(0);
  961. // Should index 2 files (readme.md + notes/note1.md), not 5
  962. expect(stdout).toContain("2 new");
  963. });
  964. test("ignored files are not searchable", async () => {
  965. const { stdout, exitCode } = await runQmd(["search", "session", "-n", "10"], {
  966. cwd: ignoreTestDir,
  967. dbPath: localDbPath,
  968. configDir: localConfigDir,
  969. });
  970. // Should find no results since sessions/ was ignored
  971. if (exitCode === 0) {
  972. expect(stdout).not.toContain("session1");
  973. expect(stdout).not.toContain("session2");
  974. }
  975. });
  976. test("non-ignored files are searchable", async () => {
  977. const { stdout, exitCode } = await runQmd(["search", "personal note", "-n", "10"], {
  978. cwd: ignoreTestDir,
  979. dbPath: localDbPath,
  980. configDir: localConfigDir,
  981. });
  982. expect(exitCode).toBe(0);
  983. expect(stdout).toContain("note1");
  984. });
  985. test("status shows ignore patterns", async () => {
  986. const { stdout, exitCode } = await runQmd(["collection", "list"], {
  987. cwd: ignoreTestDir,
  988. dbPath: localDbPath,
  989. configDir: localConfigDir,
  990. });
  991. expect(exitCode).toBe(0);
  992. expect(stdout).toContain("Ignore:");
  993. expect(stdout).toContain("sessions/**");
  994. expect(stdout).toContain("archive/**");
  995. });
  996. test("collection without ignore indexes all files", async () => {
  997. // Create a second collection without ignore
  998. const env2 = await createIsolatedTestEnv("no-ignore");
  999. await writeFile(
  1000. join(env2.configDir, "index.yml"),
  1001. `collections:
  1002. allfiles:
  1003. path: ${ignoreTestDir}
  1004. pattern: "**/*.md"
  1005. `
  1006. );
  1007. const { stdout, exitCode } = await runQmd(["update"], {
  1008. cwd: ignoreTestDir,
  1009. dbPath: env2.dbPath,
  1010. configDir: env2.configDir,
  1011. });
  1012. expect(exitCode).toBe(0);
  1013. // Should index all 5 files
  1014. expect(stdout).toContain("5 new");
  1015. });
  1016. });
  1017. // =============================================================================
  1018. // Output Format Tests - qmd:// URIs, context, and docid
  1019. // =============================================================================
  1020. describe("search output formats", () => {
  1021. let localDbPath: string;
  1022. let localConfigDir: string;
  1023. const collName = "fixtures";
  1024. beforeAll(async () => {
  1025. const env = await createIsolatedTestEnv("output-format");
  1026. localDbPath = env.dbPath;
  1027. localConfigDir = env.configDir;
  1028. // Add collection
  1029. const { exitCode, stderr } = await runQmd(
  1030. ["collection", "add", fixturesDir, "--name", collName],
  1031. { dbPath: localDbPath, configDir: localConfigDir }
  1032. );
  1033. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1034. expect(exitCode).toBe(0);
  1035. // Add context
  1036. await runQmd(["context", "add", `qmd://${collName}/`, "Test fixtures for QMD"], { dbPath: localDbPath, configDir: localConfigDir });
  1037. });
  1038. test("search --json includes qmd:// path, docid, and context", async () => {
  1039. const { stdout, exitCode } = await runQmd(["search", "test", "--json", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1040. expect(exitCode).toBe(0);
  1041. const results = JSON.parse(stdout);
  1042. expect(results.length).toBeGreaterThan(0);
  1043. const result = results[0];
  1044. expect(result.file).toMatch(new RegExp(`^qmd://${collName}/`));
  1045. expect(result.docid).toMatch(/^#[a-f0-9]{6}$/);
  1046. expect(result.context).toBe("Test fixtures for QMD");
  1047. // Ensure no full filesystem paths
  1048. expect(result.file).not.toMatch(/^\/Users\//);
  1049. expect(result.file).not.toMatch(/^\/home\//);
  1050. });
  1051. test("search --files includes qmd:// path, docid, and context", async () => {
  1052. const { stdout, exitCode } = await runQmd(["search", "test", "--files", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1053. expect(exitCode).toBe(0);
  1054. // Format: #docid,score,qmd://collection/path,"context"
  1055. expect(stdout).toMatch(new RegExp(`^#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`, "m"));
  1056. expect(stdout).toContain("Test fixtures for QMD");
  1057. // Ensure no full filesystem paths
  1058. expect(stdout).not.toMatch(/\/Users\//);
  1059. expect(stdout).not.toMatch(/\/home\//);
  1060. });
  1061. test("search --csv includes qmd:// path, docid, and context", async () => {
  1062. const { stdout, exitCode } = await runQmd(["search", "test", "--csv", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1063. expect(exitCode).toBe(0);
  1064. // Header should include context
  1065. expect(stdout).toMatch(/^docid,score,file,title,context,line,snippet$/m);
  1066. // Data rows should have qmd:// paths and context
  1067. expect(stdout).toMatch(new RegExp(`#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`));
  1068. expect(stdout).toContain("Test fixtures for QMD");
  1069. // Ensure no full filesystem paths
  1070. expect(stdout).not.toMatch(/\/Users\//);
  1071. expect(stdout).not.toMatch(/\/home\//);
  1072. });
  1073. test("search --md includes docid and context", async () => {
  1074. const { stdout, exitCode } = await runQmd(["search", "test", "--md", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1075. expect(exitCode).toBe(0);
  1076. expect(stdout).toMatch(/\*\*docid:\*\* `#[a-f0-9]{6}`/);
  1077. expect(stdout).toContain("**context:** Test fixtures for QMD");
  1078. });
  1079. test("search --xml includes qmd:// path, docid, and context", async () => {
  1080. const { stdout, exitCode } = await runQmd(["search", "test", "--xml", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1081. expect(exitCode).toBe(0);
  1082. expect(stdout).toMatch(new RegExp(`<file docid="#[a-f0-9]{6}" name="qmd://${collName}/`));
  1083. expect(stdout).toContain('context="Test fixtures for QMD"');
  1084. // Ensure no full filesystem paths
  1085. expect(stdout).not.toMatch(/\/Users\//);
  1086. expect(stdout).not.toMatch(/\/home\//);
  1087. });
  1088. test("search default CLI format includes plain qmd:// path, docid, and context in non-TTY mode", async () => {
  1089. const { stdout, exitCode } = await runQmd(["search", "test", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1090. expect(exitCode).toBe(0);
  1091. // runQmd uses piped stdio, so stdout is non-TTY and should not contain OSC 8 links.
  1092. expect(stdout).toMatch(new RegExp(`^qmd://${collName}/.*#[a-f0-9]{6}`, "m"));
  1093. expect(stdout).toContain("Context: Test fixtures for QMD");
  1094. expect(stdout).not.toContain("\x1b]8;;");
  1095. // Ensure no full filesystem paths
  1096. expect(stdout).not.toMatch(/\/Users\//);
  1097. expect(stdout).not.toMatch(/\/home\//);
  1098. });
  1099. });
  1100. describe("editor URI templates", () => {
  1101. test("buildEditorUri expands path, line, and col placeholders", () => {
  1102. const uri = buildEditorUri(
  1103. "vscode://file/{path}:{line}:{col}",
  1104. "/tmp/my notes/readme.md",
  1105. 42,
  1106. 1,
  1107. );
  1108. expect(uri).toBe("vscode://file//tmp/my%20notes/readme.md:42:1");
  1109. });
  1110. test("buildEditorUri supports {column} alias", () => {
  1111. const uri = buildEditorUri(
  1112. "cursor://file/{path}:{line}:{column}",
  1113. "/tmp/docs/api.md",
  1114. 7,
  1115. 3,
  1116. );
  1117. expect(uri).toBe("cursor://file//tmp/docs/api.md:7:3");
  1118. });
  1119. test("termLink returns plain text when stdout is not a TTY", () => {
  1120. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", false);
  1121. expect(linked).toBe("docs/api.md:12");
  1122. });
  1123. test("termLink emits OSC 8 hyperlinks when stdout is a TTY", () => {
  1124. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", true);
  1125. expect(linked).toBe("\x1b]8;;vscode://file//tmp/docs/api.md:12:1\x07docs/api.md:12\x1b]8;;\x07");
  1126. });
  1127. });
  1128. // =============================================================================
  1129. // Get Command Path Normalization Tests
  1130. // =============================================================================
  1131. describe("get command path normalization", () => {
  1132. let localDbPath: string;
  1133. let localConfigDir: string;
  1134. const collName = "fixtures";
  1135. beforeAll(async () => {
  1136. const env = await createIsolatedTestEnv("get-paths");
  1137. localDbPath = env.dbPath;
  1138. localConfigDir = env.configDir;
  1139. const { exitCode, stderr } = await runQmd(
  1140. ["collection", "add", fixturesDir, "--name", collName],
  1141. { dbPath: localDbPath, configDir: localConfigDir }
  1142. );
  1143. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1144. expect(exitCode).toBe(0);
  1145. });
  1146. test("get with qmd://collection/path format", async () => {
  1147. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1148. expect(exitCode).toBe(0);
  1149. expect(stdout).toContain("Test Document 1");
  1150. });
  1151. test("get with collection/path format (no scheme)", async () => {
  1152. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1153. expect(exitCode).toBe(0);
  1154. expect(stdout).toContain("Test Document 1");
  1155. });
  1156. test("get with //collection/path format", async () => {
  1157. const { stdout, exitCode } = await runQmd(["get", `//${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1158. expect(exitCode).toBe(0);
  1159. expect(stdout).toContain("Test Document 1");
  1160. });
  1161. test("get with qmd:////collection/path format (extra slashes)", async () => {
  1162. const { stdout, exitCode } = await runQmd(["get", `qmd:////${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1163. expect(exitCode).toBe(0);
  1164. expect(stdout).toContain("Test Document 1");
  1165. });
  1166. test("get with path:line format", async () => {
  1167. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1168. expect(exitCode).toBe(0);
  1169. // Should start from line 3, not line 1
  1170. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1171. });
  1172. test("get with qmd://path:line format", async () => {
  1173. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1174. expect(exitCode).toBe(0);
  1175. // Should start from line 3, not line 1
  1176. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1177. });
  1178. });
  1179. // =============================================================================
  1180. // Status and Collection List - No Full Paths
  1181. // =============================================================================
  1182. describe("status and collection list hide filesystem paths", () => {
  1183. let localDbPath: string;
  1184. let localConfigDir: string;
  1185. const collName = "fixtures";
  1186. beforeAll(async () => {
  1187. const env = await createIsolatedTestEnv("status-paths");
  1188. localDbPath = env.dbPath;
  1189. localConfigDir = env.configDir;
  1190. const { exitCode, stderr } = await runQmd(
  1191. ["collection", "add", fixturesDir, "--name", collName],
  1192. { dbPath: localDbPath, configDir: localConfigDir }
  1193. );
  1194. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1195. expect(exitCode).toBe(0);
  1196. });
  1197. test("status does not show full filesystem paths", async () => {
  1198. const { stdout, exitCode } = await runQmd(["status"], { dbPath: localDbPath, configDir: localConfigDir });
  1199. expect(exitCode).toBe(0);
  1200. // Should show qmd:// URIs
  1201. expect(stdout).toContain(`qmd://${collName}/`);
  1202. // Should NOT show full filesystem paths (except for the index location which is ok)
  1203. const lines = stdout.split('\n').filter(l => !l.includes('Index:'));
  1204. const pathLines = lines.filter(l => l.includes('/Users/') || l.includes('/home/') || l.includes('/tmp/'));
  1205. expect(pathLines.length).toBe(0);
  1206. });
  1207. test("collection list does not show full filesystem paths", async () => {
  1208. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath, configDir: localConfigDir });
  1209. expect(exitCode).toBe(0);
  1210. // Should show qmd:// URIs
  1211. expect(stdout).toContain(`qmd://${collName}/`);
  1212. // Should NOT show Path: lines with filesystem paths
  1213. expect(stdout).not.toMatch(/Path:\s+\//);
  1214. });
  1215. });
  1216. // =============================================================================
  1217. // MCP HTTP Daemon Lifecycle
  1218. // =============================================================================
  1219. describe("mcp http daemon", () => {
  1220. let daemonTestDir: string;
  1221. let daemonCacheDir: string; // XDG_CACHE_HOME value (the qmd/ subdir is created automatically)
  1222. let daemonDbPath: string;
  1223. let daemonConfigDir: string;
  1224. // Track spawned PIDs for cleanup
  1225. const spawnedPids: number[] = [];
  1226. /** Get path to PID file inside the test cache dir */
  1227. function pidPath(): string {
  1228. return join(daemonCacheDir, "qmd", "mcp.pid");
  1229. }
  1230. /** Run qmd with test-isolated env (cache, db, config) */
  1231. async function runDaemonQmd(
  1232. args: string[],
  1233. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  1234. return runQmd(args, {
  1235. dbPath: daemonDbPath,
  1236. configDir: daemonConfigDir,
  1237. env: { XDG_CACHE_HOME: daemonCacheDir },
  1238. });
  1239. }
  1240. /** Spawn a foreground HTTP server (non-blocking) and return the process */
  1241. function spawnHttpServer(port: number): import("child_process").ChildProcess {
  1242. const proc = spawn(tsxBin, [qmdScript, "mcp", "--http", "--port", String(port)], {
  1243. cwd: fixturesDir,
  1244. env: {
  1245. ...process.env,
  1246. INDEX_PATH: daemonDbPath,
  1247. QMD_CONFIG_DIR: daemonConfigDir,
  1248. },
  1249. stdio: ["ignore", "pipe", "pipe"],
  1250. });
  1251. if (proc.pid) spawnedPids.push(proc.pid);
  1252. return proc;
  1253. }
  1254. /** Wait for HTTP server to become ready */
  1255. async function waitForServer(port: number, timeoutMs = 5000): Promise<boolean> {
  1256. const deadline = Date.now() + timeoutMs;
  1257. while (Date.now() < deadline) {
  1258. try {
  1259. const res = await fetch(`http://localhost:${port}/health`);
  1260. if (res.ok) return true;
  1261. } catch { /* not ready yet */ }
  1262. await sleep(200);
  1263. }
  1264. return false;
  1265. }
  1266. /** Pick a random high port unlikely to conflict */
  1267. function randomPort(): number {
  1268. return 10000 + Math.floor(Math.random() * 50000);
  1269. }
  1270. beforeAll(async () => {
  1271. daemonTestDir = await mkdtemp(join(tmpdir(), "qmd-daemon-test-"));
  1272. daemonCacheDir = join(daemonTestDir, "cache");
  1273. daemonDbPath = join(daemonTestDir, "test.sqlite");
  1274. daemonConfigDir = join(daemonTestDir, "config");
  1275. await mkdir(join(daemonCacheDir, "qmd"), { recursive: true });
  1276. await mkdir(daemonConfigDir, { recursive: true });
  1277. await writeFile(join(daemonConfigDir, "index.yml"), "collections: {}\n");
  1278. });
  1279. afterAll(async () => {
  1280. // Kill any leftover spawned processes
  1281. for (const pid of spawnedPids) {
  1282. try { process.kill(pid, "SIGTERM"); } catch { /* already dead */ }
  1283. }
  1284. // Also clean up via PID file if present
  1285. try {
  1286. const pf = pidPath();
  1287. if (existsSync(pf)) {
  1288. const pid = parseInt(readFileSync(pf, "utf-8").trim());
  1289. try { process.kill(pid, "SIGTERM"); } catch {}
  1290. unlinkSync(pf);
  1291. }
  1292. } catch {}
  1293. await rm(daemonTestDir, { recursive: true, force: true });
  1294. });
  1295. // -------------------------------------------------------------------------
  1296. // Foreground HTTP
  1297. // -------------------------------------------------------------------------
  1298. test("foreground HTTP server starts and responds to health check", async () => {
  1299. const port = randomPort();
  1300. const proc = spawnHttpServer(port);
  1301. try {
  1302. const ready = await waitForServer(port);
  1303. expect(ready).toBe(true);
  1304. const res = await fetch(`http://localhost:${port}/health`);
  1305. expect(res.status).toBe(200);
  1306. const body = await res.json();
  1307. expect(body.status).toBe("ok");
  1308. } finally {
  1309. proc.kill("SIGTERM");
  1310. await new Promise(r => proc.on("close", r));
  1311. }
  1312. });
  1313. // -------------------------------------------------------------------------
  1314. // Daemon lifecycle
  1315. // -------------------------------------------------------------------------
  1316. test("--daemon writes PID file and starts server", async () => {
  1317. const port = randomPort();
  1318. const { stdout, exitCode } = await runDaemonQmd([
  1319. "mcp", "--http", "--daemon", "--port", String(port),
  1320. ]);
  1321. expect(exitCode).toBe(0);
  1322. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1323. // PID file should exist
  1324. expect(existsSync(pidPath())).toBe(true);
  1325. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1326. spawnedPids.push(pid);
  1327. // Server should be reachable
  1328. const ready = await waitForServer(port);
  1329. expect(ready).toBe(true);
  1330. // Clean up
  1331. process.kill(pid, "SIGTERM");
  1332. await sleep(500);
  1333. try { unlinkSync(pidPath()); } catch {}
  1334. });
  1335. test("stop kills daemon and removes PID file", async () => {
  1336. const port = randomPort();
  1337. // Start daemon
  1338. const { exitCode: startCode } = await runDaemonQmd([
  1339. "mcp", "--http", "--daemon", "--port", String(port),
  1340. ]);
  1341. expect(startCode).toBe(0);
  1342. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1343. spawnedPids.push(pid);
  1344. await waitForServer(port);
  1345. // Stop it
  1346. const { stdout: stopOut, exitCode: stopCode } = await runDaemonQmd(["mcp", "stop"]);
  1347. expect(stopCode).toBe(0);
  1348. expect(stopOut).toContain("Stopped");
  1349. // PID file should be gone
  1350. expect(existsSync(pidPath())).toBe(false);
  1351. // Process should be dead
  1352. await sleep(500);
  1353. expect(() => process.kill(pid, 0)).toThrow();
  1354. });
  1355. test("stop handles dead PID gracefully (cleans stale file)", async () => {
  1356. // Write a PID file pointing to a dead process
  1357. writeFileSync(pidPath(), "999999999");
  1358. const { stdout, exitCode } = await runDaemonQmd(["mcp", "stop"]);
  1359. expect(exitCode).toBe(0);
  1360. expect(stdout).toContain("stale");
  1361. // PID file should be cleaned up
  1362. expect(existsSync(pidPath())).toBe(false);
  1363. });
  1364. test("--daemon rejects if already running", async () => {
  1365. const port = randomPort();
  1366. // Start first daemon
  1367. const { exitCode: firstCode } = await runDaemonQmd([
  1368. "mcp", "--http", "--daemon", "--port", String(port),
  1369. ]);
  1370. expect(firstCode).toBe(0);
  1371. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1372. spawnedPids.push(pid);
  1373. await waitForServer(port);
  1374. // Try to start second daemon — should fail
  1375. const { stderr, exitCode } = await runDaemonQmd([
  1376. "mcp", "--http", "--daemon", "--port", String(port + 1),
  1377. ]);
  1378. expect(exitCode).toBe(1);
  1379. expect(stderr).toContain("Already running");
  1380. // Clean up first daemon
  1381. process.kill(pid, "SIGTERM");
  1382. await sleep(500);
  1383. try { unlinkSync(pidPath()); } catch {}
  1384. });
  1385. test("--daemon cleans stale PID file and starts fresh", async () => {
  1386. // Write a stale PID file
  1387. writeFileSync(pidPath(), "999999999");
  1388. const port = randomPort();
  1389. const { exitCode, stdout } = await runDaemonQmd([
  1390. "mcp", "--http", "--daemon", "--port", String(port),
  1391. ]);
  1392. expect(exitCode).toBe(0);
  1393. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1394. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1395. spawnedPids.push(pid);
  1396. expect(pid).not.toBe(999999999);
  1397. // Clean up
  1398. const ready = await waitForServer(port);
  1399. expect(ready).toBe(true);
  1400. process.kill(pid, "SIGTERM");
  1401. await sleep(500);
  1402. try { unlinkSync(pidPath()); } catch {}
  1403. });
  1404. });