cli.test.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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. });
  218. describe("CLI Skill Commands", () => {
  219. test("shows embedded skill with --skill alias", async () => {
  220. const { stdout, exitCode } = await runQmd(["--skill"]);
  221. expect(exitCode).toBe(0);
  222. expect(stdout).toContain("QMD Skill (embedded)");
  223. expect(stdout).toContain("name: qmd");
  224. expect(stdout).toContain("allowed-tools: Bash(qmd:*), mcp__qmd__*");
  225. });
  226. test("shows skill help with -h", async () => {
  227. const { stdout, exitCode } = await runQmd(["skill", "-h"]);
  228. expect(exitCode).toBe(0);
  229. expect(stdout).toContain("Usage: qmd skill <show|install> [options]");
  230. expect(stdout).toContain("install");
  231. expect(stdout).toContain("--global");
  232. });
  233. test("installs the skill into the current project", async () => {
  234. const projectDir = join(testDir, "skill-project");
  235. await mkdir(projectDir, { recursive: true });
  236. const { stdout, exitCode } = await runQmd(["skill", "install"], { cwd: projectDir });
  237. expect(exitCode).toBe(0);
  238. const skillDir = join(projectDir, ".agents", "skills", "qmd");
  239. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  240. expect(readFileSync(join(skillDir, "references", "mcp-setup.md"), "utf-8")).toContain("Claude Code");
  241. expect(existsSync(join(projectDir, ".claude", "skills", "qmd"))).toBe(false);
  242. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  243. expect(stdout).toContain("Tip: create a Claude symlink manually");
  244. });
  245. test("installs globally and creates the Claude symlink with --yes", async () => {
  246. const fakeHome = join(testDir, "skill-home");
  247. await mkdir(fakeHome, { recursive: true });
  248. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  249. env: { HOME: fakeHome },
  250. });
  251. expect(exitCode).toBe(0);
  252. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  253. const claudeLink = join(fakeHome, ".claude", "skills", "qmd");
  254. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  255. expect(lstatSync(claudeLink).isSymbolicLink()).toBe(true);
  256. expect(readFileSync(join(claudeLink, "SKILL.md"), "utf-8")).toContain("name: qmd");
  257. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  258. expect(stdout).toContain(`✓ Linked Claude skill at ${claudeLink}`);
  259. });
  260. test("skips Claude qmd symlink when .claude/skills already points to .agents/skills", async () => {
  261. const fakeHome = join(testDir, "skill-home-shared");
  262. await mkdir(join(fakeHome, ".agents"), { recursive: true });
  263. await mkdir(join(fakeHome, ".claude"), { recursive: true });
  264. symlinkSync(join(fakeHome, ".agents", "skills"), join(fakeHome, ".claude", "skills"), "dir");
  265. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  266. env: { HOME: fakeHome },
  267. });
  268. expect(exitCode).toBe(0);
  269. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  270. expect(lstatSync(skillDir).isSymbolicLink()).toBe(false);
  271. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  272. expect(stdout).toContain(`✓ Claude already sees the skill via ${join(fakeHome, ".claude", "skills")}`);
  273. });
  274. test("refuses to overwrite an existing install without --force", async () => {
  275. const projectDir = join(testDir, "skill-project-force");
  276. await mkdir(projectDir, { recursive: true });
  277. const first = await runQmd(["skill", "install"], { cwd: projectDir });
  278. expect(first.exitCode).toBe(0);
  279. const second = await runQmd(["skill", "install"], { cwd: projectDir });
  280. expect(second.exitCode).toBe(1);
  281. expect(second.stderr).toContain("Skill already exists");
  282. expect(second.stderr).toContain("--force");
  283. });
  284. });
  285. describe("CLI Add Command", () => {
  286. test("adds files from current directory", async () => {
  287. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  288. expect(exitCode).toBe(0);
  289. expect(stdout).toContain("Collection:");
  290. expect(stdout).toContain("Indexed:");
  291. });
  292. test("adds files with custom glob pattern", async () => {
  293. const { stdout, stderr, exitCode } = await runQmd(["collection", "add", ".", "--mask", "notes/*.md"]);
  294. if (exitCode !== 0) {
  295. console.error("Command failed:", stderr);
  296. }
  297. expect(exitCode).toBe(0);
  298. expect(stdout).toContain("Collection:");
  299. // Should find meeting.md and ideas.md in notes/
  300. expect(stdout).toContain("notes/*.md");
  301. });
  302. test("can recreate collection with remove and add", async () => {
  303. // First add
  304. await runQmd(["collection", "add", "."]);
  305. // Remove it
  306. await runQmd(["collection", "remove", "fixtures"]);
  307. // Re-add
  308. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  309. expect(exitCode).toBe(0);
  310. expect(stdout).toContain("Collection 'fixtures' created successfully");
  311. });
  312. });
  313. describe("CLI Status Command", () => {
  314. beforeEach(async () => {
  315. // Ensure we have indexed files
  316. await runQmd(["collection", "add", "."]);
  317. });
  318. test("shows index status", async () => {
  319. const { stdout, exitCode } = await runQmd(["status"]);
  320. expect(exitCode).toBe(0);
  321. // Should show collection info
  322. expect(stdout).toContain("Collection");
  323. });
  324. });
  325. describe("CLI Search Command", () => {
  326. beforeEach(async () => {
  327. // Ensure we have indexed files
  328. await runQmd(["collection", "add", "."]);
  329. });
  330. test("searches for documents with BM25", async () => {
  331. const { stdout, exitCode } = await runQmd(["search", "meeting"]);
  332. expect(exitCode).toBe(0);
  333. // Should find meeting.md
  334. expect(stdout.toLowerCase()).toContain("meeting");
  335. });
  336. test("searches with limit option", async () => {
  337. const { stdout, exitCode } = await runQmd(["search", "-n", "1", "test"]);
  338. expect(exitCode).toBe(0);
  339. });
  340. test("searches with all results option", async () => {
  341. const { stdout, exitCode } = await runQmd(["search", "--all", "the"]);
  342. expect(exitCode).toBe(0);
  343. });
  344. test("returns no results message for non-matching query", async () => {
  345. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123"]);
  346. expect(exitCode).toBe(0);
  347. expect(stdout).toContain("No results");
  348. });
  349. test("returns empty JSON array for non-matching query with --json", async () => {
  350. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--json"]);
  351. expect(exitCode).toBe(0);
  352. expect(JSON.parse(stdout)).toEqual([]);
  353. });
  354. test("returns CSV header only for non-matching query with --csv", async () => {
  355. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--csv"]);
  356. expect(exitCode).toBe(0);
  357. expect(stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  358. });
  359. test("returns empty XML container for non-matching query with --xml", async () => {
  360. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--xml"]);
  361. expect(exitCode).toBe(0);
  362. expect(stdout.trim()).toBe("<results></results>");
  363. });
  364. test("returns empty output for non-matching query with --md", async () => {
  365. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--md"]);
  366. expect(exitCode).toBe(0);
  367. expect(stdout.trim()).toBe("");
  368. });
  369. test("returns empty output for non-matching query with --files", async () => {
  370. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--files"]);
  371. expect(exitCode).toBe(0);
  372. expect(stdout.trim()).toBe("");
  373. });
  374. test("returns min-score threshold message for default CLI output", async () => {
  375. const { stdout, exitCode } = await runQmd(["search", "test", "--min-score", "2"]);
  376. expect(exitCode).toBe(0);
  377. expect(stdout).toContain("No results found above minimum score threshold.");
  378. });
  379. test("returns format-safe empty output when --min-score filters all results", async () => {
  380. const json = await runQmd(["search", "test", "--json", "--min-score", "2"]);
  381. expect(json.exitCode).toBe(0);
  382. expect(JSON.parse(json.stdout)).toEqual([]);
  383. const csv = await runQmd(["search", "test", "--csv", "--min-score", "2"]);
  384. expect(csv.exitCode).toBe(0);
  385. expect(csv.stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  386. const xml = await runQmd(["search", "test", "--xml", "--min-score", "2"]);
  387. expect(xml.exitCode).toBe(0);
  388. expect(xml.stdout.trim()).toBe("<results></results>");
  389. const md = await runQmd(["search", "test", "--md", "--min-score", "2"]);
  390. expect(md.exitCode).toBe(0);
  391. expect(md.stdout.trim()).toBe("");
  392. const files = await runQmd(["search", "test", "--files", "--min-score", "2"]);
  393. expect(files.exitCode).toBe(0);
  394. expect(files.stdout.trim()).toBe("");
  395. });
  396. test("requires query argument", async () => {
  397. const { stdout, stderr, exitCode } = await runQmd(["search"]);
  398. expect(exitCode).toBe(1);
  399. // Error message goes to stderr
  400. expect(stderr).toContain("Usage:");
  401. });
  402. });
  403. describe("CLI Get Command", () => {
  404. beforeEach(async () => {
  405. // Ensure we have indexed files
  406. await runQmd(["collection", "add", "."]);
  407. });
  408. test("retrieves document content by path", async () => {
  409. const { stdout, exitCode } = await runQmd(["get", "README.md"]);
  410. expect(exitCode).toBe(0);
  411. expect(stdout).toContain("Test Project");
  412. });
  413. test("retrieves document from subdirectory", async () => {
  414. const { stdout, exitCode } = await runQmd(["get", "notes/meeting.md"]);
  415. expect(exitCode).toBe(0);
  416. expect(stdout).toContain("Team Meeting");
  417. });
  418. test("handles non-existent file", async () => {
  419. const { stdout, exitCode } = await runQmd(["get", "nonexistent.md"]);
  420. // Should indicate file not found
  421. expect(exitCode).toBe(1);
  422. });
  423. });
  424. describe("CLI Multi-Get Command", () => {
  425. let localDbPath: string;
  426. beforeEach(async () => {
  427. // Use fresh database for each test
  428. localDbPath = getFreshDbPath();
  429. // Ensure we have indexed files
  430. const addResult = await runQmd(["collection", "add", ".", "--name", "fixtures"], { dbPath: localDbPath });
  431. if (addResult.exitCode !== 0) {
  432. throw new Error(`Failed to add collection: ${addResult.stderr}`);
  433. }
  434. });
  435. test("retrieves multiple documents by pattern", async () => {
  436. // Test glob pattern matching
  437. const { stdout, stderr, exitCode } = await runQmd(["multi-get", "notes/*.md"], { dbPath: localDbPath });
  438. expect(exitCode).toBe(0);
  439. // Should contain content from both notes files
  440. expect(stdout).toContain("Meeting");
  441. expect(stdout).toContain("Ideas");
  442. });
  443. test("retrieves documents by comma-separated paths", async () => {
  444. const { stdout, exitCode } = await runQmd([
  445. "multi-get",
  446. "README.md,notes/meeting.md",
  447. ], { dbPath: localDbPath });
  448. expect(exitCode).toBe(0);
  449. expect(stdout).toContain("Test Project");
  450. expect(stdout).toContain("Team Meeting");
  451. });
  452. });
  453. describe("CLI Update Command", () => {
  454. let localDbPath: string;
  455. beforeEach(async () => {
  456. // Use a fresh database for this test suite
  457. localDbPath = getFreshDbPath();
  458. // Ensure we have indexed files
  459. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  460. });
  461. test("updates all collections", async () => {
  462. const { stdout, exitCode } = await runQmd(["update"], { dbPath: localDbPath });
  463. expect(exitCode).toBe(0);
  464. expect(stdout).toContain("Updating");
  465. });
  466. test("deactivates stale docs when collection has zero matching files", async () => {
  467. const { dbPath, configDir } = await createIsolatedTestEnv("update-empty");
  468. const collectionDir = join(testDir, `update-empty-${Date.now()}`);
  469. await mkdir(collectionDir, { recursive: true });
  470. const docPath = join(collectionDir, "only.md");
  471. const token = `stale-proof-${Date.now()}`;
  472. await writeFile(
  473. docPath,
  474. `---
  475. date: 2026-03-06
  476. ---
  477. # Empty Collection Deactivation
  478. ${token}
  479. `
  480. );
  481. const add = await runQmd(
  482. ["collection", "add", collectionDir, "--name", "empty-check"],
  483. { dbPath, configDir }
  484. );
  485. expect(add.exitCode).toBe(0);
  486. const before = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  487. expect(before.exitCode).toBe(0);
  488. expect(before.stdout).toContain(token);
  489. unlinkSync(docPath);
  490. const update = await runQmd(["update"], { dbPath, configDir });
  491. expect(update.exitCode).toBe(0);
  492. expect(update.stdout).toContain("0 new, 0 updated, 0 unchanged, 1 removed");
  493. const after = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  494. expect(after.exitCode).toBe(1);
  495. });
  496. });
  497. describe("CLI Add-Context Command", () => {
  498. let localDbPath: string;
  499. let localConfigDir: string;
  500. const collName = "fixtures";
  501. beforeAll(async () => {
  502. const env = await createIsolatedTestEnv("context-cmd");
  503. localDbPath = env.dbPath;
  504. localConfigDir = env.configDir;
  505. // Add collection with known name
  506. const { exitCode, stderr } = await runQmd(
  507. ["collection", "add", fixturesDir, "--name", collName],
  508. { dbPath: localDbPath, configDir: localConfigDir }
  509. );
  510. if (exitCode !== 0) console.error("collection add failed:", stderr);
  511. expect(exitCode).toBe(0);
  512. });
  513. test("adds context to a path", async () => {
  514. // Add context to the collection root using virtual path
  515. const { stdout, exitCode } = await runQmd([
  516. "context",
  517. "add",
  518. `qmd://${collName}/`,
  519. "Personal notes and meeting logs",
  520. ], { dbPath: localDbPath, configDir: localConfigDir });
  521. expect(exitCode).toBe(0);
  522. expect(stdout).toContain("✓ Added context");
  523. });
  524. test("requires path and text arguments", async () => {
  525. const { stderr, exitCode } = await runQmd(["context", "add"], { dbPath: localDbPath, configDir: localConfigDir });
  526. expect(exitCode).toBe(1);
  527. // Error message goes to stderr
  528. expect(stderr).toContain("Usage:");
  529. });
  530. });
  531. describe("CLI Cleanup Command", () => {
  532. beforeEach(async () => {
  533. // Ensure we have indexed files
  534. await runQmd(["collection", "add", "."]);
  535. });
  536. test("cleans up orphaned entries", async () => {
  537. const { stdout, exitCode } = await runQmd(["cleanup"]);
  538. expect(exitCode).toBe(0);
  539. });
  540. });
  541. describe("CLI Error Handling", () => {
  542. test("handles unknown command", async () => {
  543. const { stderr, exitCode } = await runQmd(["unknowncommand"]);
  544. expect(exitCode).toBe(1);
  545. // Should indicate unknown command
  546. expect(stderr).toContain("Unknown command");
  547. });
  548. test("uses INDEX_PATH environment variable", async () => {
  549. // Verify the test DB path is being used by creating a separate index
  550. const customDbPath = join(testDir, "custom.sqlite");
  551. const { exitCode } = await runQmd(["collection", "add", "."], {
  552. env: { INDEX_PATH: customDbPath },
  553. });
  554. expect(exitCode).toBe(0);
  555. // The custom database should exist
  556. expect(existsSync(customDbPath)).toBe(true);
  557. });
  558. });
  559. describe("CLI Output Formats", () => {
  560. beforeEach(async () => {
  561. await runQmd(["collection", "add", "."]);
  562. });
  563. test("search with --json flag outputs JSON", async () => {
  564. const { stdout, exitCode } = await runQmd(["search", "--json", "test"]);
  565. expect(exitCode).toBe(0);
  566. // Should be valid JSON
  567. const parsed = JSON.parse(stdout);
  568. expect(Array.isArray(parsed)).toBe(true);
  569. });
  570. test("search with --files flag outputs file paths", async () => {
  571. const { stdout, exitCode } = await runQmd(["search", "--files", "meeting"]);
  572. expect(exitCode).toBe(0);
  573. expect(stdout).toContain(".md");
  574. });
  575. test("search output includes snippets by default", async () => {
  576. const { stdout, exitCode } = await runQmd(["search", "API"]);
  577. expect(exitCode).toBe(0);
  578. // If results found, should have snippet content
  579. if (!stdout.includes("No results")) {
  580. expect(stdout.toLowerCase()).toContain("api");
  581. }
  582. });
  583. });
  584. describe("CLI Search with Collection Filter", () => {
  585. let localDbPath: string;
  586. beforeEach(async () => {
  587. // Use a fresh database for this test suite
  588. localDbPath = getFreshDbPath();
  589. // Create multiple collections with explicit names
  590. await runQmd(["collection", "add", ".", "--name", "notes", "--mask", "notes/*.md"], { dbPath: localDbPath });
  591. await runQmd(["collection", "add", ".", "--name", "docs", "--mask", "docs/*.md"], { dbPath: localDbPath });
  592. });
  593. test("filters search by collection name", async () => {
  594. const { stdout, stderr, exitCode } = await runQmd([
  595. "search",
  596. "-c",
  597. "notes",
  598. "meeting",
  599. ], { dbPath: localDbPath });
  600. if (exitCode !== 0) {
  601. console.log("Collection filter search failed:");
  602. console.log("stdout:", stdout);
  603. console.log("stderr:", stderr);
  604. }
  605. expect(exitCode).toBe(0);
  606. });
  607. });
  608. describe("CLI Context Management", () => {
  609. let localDbPath: string;
  610. beforeEach(async () => {
  611. // Use a fresh database for this test suite
  612. localDbPath = getFreshDbPath();
  613. // Index some files first
  614. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  615. });
  616. test("add global context with /", async () => {
  617. const { stdout, exitCode } = await runQmd([
  618. "context",
  619. "add",
  620. "/",
  621. "Global system context",
  622. ], { dbPath: localDbPath });
  623. expect(exitCode).toBe(0);
  624. expect(stdout).toContain("✓ Set global context");
  625. expect(stdout).toContain("Global system context");
  626. });
  627. test("list contexts", async () => {
  628. // Add a global context first
  629. await runQmd([
  630. "context",
  631. "add",
  632. "/",
  633. "Test context",
  634. ], { dbPath: localDbPath });
  635. const { stdout, exitCode } = await runQmd([
  636. "context",
  637. "list",
  638. ], { dbPath: localDbPath });
  639. expect(exitCode).toBe(0);
  640. expect(stdout).toContain("Configured Contexts");
  641. expect(stdout).toContain("Test context");
  642. });
  643. test("add context to virtual path", async () => {
  644. // Collection name should be "fixtures" (basename of the fixtures directory)
  645. const { stdout, exitCode } = await runQmd([
  646. "context",
  647. "add",
  648. "qmd://fixtures/notes",
  649. "Context for notes subdirectory",
  650. ], { dbPath: localDbPath });
  651. expect(exitCode).toBe(0);
  652. expect(stdout).toContain("✓ Added context for: qmd://fixtures/notes");
  653. });
  654. test("remove global context", async () => {
  655. // Add a global context first
  656. await runQmd([
  657. "context",
  658. "add",
  659. "/",
  660. "Global context to remove",
  661. ], { dbPath: localDbPath });
  662. const { stdout, exitCode } = await runQmd([
  663. "context",
  664. "rm",
  665. "/",
  666. ], { dbPath: localDbPath });
  667. expect(exitCode).toBe(0);
  668. expect(stdout).toContain("✓ Removed");
  669. });
  670. test("remove virtual path context", async () => {
  671. // Add a context first
  672. await runQmd([
  673. "context",
  674. "add",
  675. "qmd://fixtures/notes",
  676. "Context to remove",
  677. ], { dbPath: localDbPath });
  678. const { stdout, exitCode } = await runQmd([
  679. "context",
  680. "rm",
  681. "qmd://fixtures/notes",
  682. ], { dbPath: localDbPath });
  683. expect(exitCode).toBe(0);
  684. expect(stdout).toContain("✓ Removed context for: qmd://fixtures/notes");
  685. });
  686. test("fails to remove non-existent context", async () => {
  687. const { stdout, stderr, exitCode } = await runQmd([
  688. "context",
  689. "rm",
  690. "qmd://nonexistent/path",
  691. ], { dbPath: localDbPath });
  692. expect(exitCode).toBe(1);
  693. expect(stderr || stdout).toContain("not found");
  694. });
  695. });
  696. describe("CLI ls Command", () => {
  697. let localDbPath: string;
  698. beforeEach(async () => {
  699. // Use a fresh database for this test suite
  700. localDbPath = getFreshDbPath();
  701. // Index some files first
  702. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  703. });
  704. test("lists all collections", async () => {
  705. const { stdout, exitCode } = await runQmd(["ls"], { dbPath: localDbPath });
  706. expect(exitCode).toBe(0);
  707. expect(stdout).toContain("Collections:");
  708. expect(stdout).toContain("qmd://fixtures/");
  709. });
  710. test("lists files in a collection", async () => {
  711. const { stdout, exitCode } = await runQmd(["ls", "fixtures"], { dbPath: localDbPath });
  712. expect(exitCode).toBe(0);
  713. // handelize preserves original case
  714. expect(stdout).toContain("qmd://fixtures/README.md");
  715. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  716. });
  717. test("lists files with path prefix", async () => {
  718. const { stdout, exitCode } = await runQmd(["ls", "fixtures/notes"], { dbPath: localDbPath });
  719. expect(exitCode).toBe(0);
  720. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  721. expect(stdout).toContain("qmd://fixtures/notes/ideas.md");
  722. // Should not include files outside the prefix (case preserved)
  723. expect(stdout).not.toContain("qmd://fixtures/README.md");
  724. });
  725. test("lists files with virtual path", async () => {
  726. const { stdout, exitCode } = await runQmd(["ls", "qmd://fixtures/docs"], { dbPath: localDbPath });
  727. expect(exitCode).toBe(0);
  728. expect(stdout).toContain("qmd://fixtures/docs/api.md");
  729. });
  730. test("handles non-existent collection", async () => {
  731. const { stderr, exitCode } = await runQmd(["ls", "nonexistent"], { dbPath: localDbPath });
  732. expect(exitCode).toBe(1);
  733. expect(stderr).toContain("Collection not found");
  734. });
  735. });
  736. describe("CLI Collection Commands", () => {
  737. let localDbPath: string;
  738. beforeEach(async () => {
  739. // Use a fresh database for this test suite
  740. localDbPath = getFreshDbPath();
  741. // Index some files first to create a collection
  742. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  743. });
  744. test("lists collections", async () => {
  745. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  746. expect(exitCode).toBe(0);
  747. expect(stdout).toContain("Collections");
  748. expect(stdout).toContain("fixtures");
  749. expect(stdout).toContain("qmd://fixtures/");
  750. expect(stdout).toContain("Pattern:");
  751. expect(stdout).toContain("Files:");
  752. });
  753. test("removes a collection", async () => {
  754. // First verify the collection exists
  755. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  756. expect(listBefore).toContain("fixtures");
  757. // Remove it
  758. const { stdout, exitCode } = await runQmd(["collection", "remove", "fixtures"], { dbPath: localDbPath });
  759. expect(exitCode).toBe(0);
  760. expect(stdout).toContain("✓ Removed collection 'fixtures'");
  761. expect(stdout).toContain("Deleted");
  762. // Verify it's gone
  763. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  764. expect(listAfter).not.toContain("fixtures");
  765. });
  766. test("handles removing non-existent collection", async () => {
  767. const { stderr, exitCode } = await runQmd(["collection", "remove", "nonexistent"], { dbPath: localDbPath });
  768. expect(exitCode).toBe(1);
  769. expect(stderr).toContain("Collection not found");
  770. });
  771. test("handles missing remove argument", async () => {
  772. const { stderr, exitCode } = await runQmd(["collection", "remove"], { dbPath: localDbPath });
  773. expect(exitCode).toBe(1);
  774. expect(stderr).toContain("Usage:");
  775. });
  776. test("handles unknown subcommand", async () => {
  777. const { stderr, exitCode } = await runQmd(["collection", "invalid"], { dbPath: localDbPath });
  778. expect(exitCode).toBe(1);
  779. expect(stderr).toContain("Unknown subcommand");
  780. });
  781. test("renames a collection", async () => {
  782. // First verify the collection exists
  783. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  784. expect(listBefore).toContain("qmd://fixtures/");
  785. // Rename it
  786. const { stdout, exitCode } = await runQmd(["collection", "rename", "fixtures", "my-fixtures"], { dbPath: localDbPath });
  787. expect(exitCode).toBe(0);
  788. expect(stdout).toContain("✓ Renamed collection 'fixtures' to 'my-fixtures'");
  789. expect(stdout).toContain("qmd://fixtures/");
  790. expect(stdout).toContain("qmd://my-fixtures/");
  791. // Verify the new name exists and old name is gone
  792. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  793. expect(listAfter).toContain("qmd://my-fixtures/");
  794. expect(listAfter).not.toContain("qmd://fixtures/"); // Old collection should not appear
  795. });
  796. test("handles renaming non-existent collection", async () => {
  797. const { stderr, exitCode } = await runQmd(["collection", "rename", "nonexistent", "newname"], { dbPath: localDbPath });
  798. expect(exitCode).toBe(1);
  799. expect(stderr).toContain("Collection not found");
  800. });
  801. test("handles renaming to existing collection name", async () => {
  802. // Create a second collection in a temp directory
  803. const tempDir = await mkdtemp(join(tmpdir(), "qmd-second-"));
  804. await writeFile(join(tempDir, "test.md"), "# Test");
  805. const addResult = await runQmd(["collection", "add", tempDir, "--name", "second"], { dbPath: localDbPath });
  806. if (addResult.exitCode !== 0) {
  807. console.error("Failed to add second collection:", addResult.stderr);
  808. }
  809. expect(addResult.exitCode).toBe(0);
  810. // Verify both collections exist
  811. const { stdout: listBoth } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  812. expect(listBoth).toContain("qmd://fixtures/");
  813. expect(listBoth).toContain("qmd://second/");
  814. // Try to rename fixtures to second (which already exists)
  815. const { stderr, exitCode } = await runQmd(["collection", "rename", "fixtures", "second"], { dbPath: localDbPath });
  816. expect(exitCode).toBe(1);
  817. expect(stderr).toContain("Collection name already exists");
  818. });
  819. test("handles missing rename arguments", async () => {
  820. const { stderr: stderr1, exitCode: exitCode1 } = await runQmd(["collection", "rename"], { dbPath: localDbPath });
  821. expect(exitCode1).toBe(1);
  822. expect(stderr1).toContain("Usage:");
  823. const { stderr: stderr2, exitCode: exitCode2 } = await runQmd(["collection", "rename", "fixtures"], { dbPath: localDbPath });
  824. expect(exitCode2).toBe(1);
  825. expect(stderr2).toContain("Usage:");
  826. });
  827. });
  828. // =============================================================================
  829. // Collection Ignore Patterns
  830. // =============================================================================
  831. describe("collection ignore patterns", () => {
  832. let localDbPath: string;
  833. let localConfigDir: string;
  834. let ignoreTestDir: string;
  835. beforeAll(async () => {
  836. const env = await createIsolatedTestEnv("ignore-patterns");
  837. localDbPath = env.dbPath;
  838. localConfigDir = env.configDir;
  839. // Create directory structure with subdirectories to ignore
  840. ignoreTestDir = join(testDir, "ignore-fixtures");
  841. await mkdir(join(ignoreTestDir, "notes"), { recursive: true });
  842. await mkdir(join(ignoreTestDir, "sessions"), { recursive: true });
  843. await mkdir(join(ignoreTestDir, "sessions", "2026-03"), { recursive: true });
  844. await mkdir(join(ignoreTestDir, "archive"), { recursive: true });
  845. // Files that should be indexed
  846. await writeFile(join(ignoreTestDir, "readme.md"), "# Main readme\nThis should be indexed.");
  847. await writeFile(join(ignoreTestDir, "notes", "note1.md"), "# Note 1\nThis is a personal note.");
  848. // Files that should be ignored
  849. await writeFile(join(ignoreTestDir, "sessions", "session1.md"), "# Session 1\nThis session should be ignored.");
  850. await writeFile(join(ignoreTestDir, "sessions", "2026-03", "session2.md"), "# Session 2\nNested session should also be ignored.");
  851. await writeFile(join(ignoreTestDir, "archive", "old.md"), "# Old stuff\nThis archive file should be ignored.");
  852. });
  853. test("ignore patterns exclude matching files from indexing", async () => {
  854. // Write YAML config with ignore patterns
  855. await writeFile(
  856. join(localConfigDir, "index.yml"),
  857. `collections:
  858. ignoretst:
  859. path: ${ignoreTestDir}
  860. pattern: "**/*.md"
  861. ignore:
  862. - "sessions/**"
  863. - "archive/**"
  864. `
  865. );
  866. const { stdout, exitCode } = await runQmd(["update"], {
  867. cwd: ignoreTestDir,
  868. dbPath: localDbPath,
  869. configDir: localConfigDir,
  870. });
  871. expect(exitCode).toBe(0);
  872. // Should index 2 files (readme.md + notes/note1.md), not 5
  873. expect(stdout).toContain("2 new");
  874. });
  875. test("ignored files are not searchable", async () => {
  876. const { stdout, exitCode } = await runQmd(["search", "session", "-n", "10"], {
  877. cwd: ignoreTestDir,
  878. dbPath: localDbPath,
  879. configDir: localConfigDir,
  880. });
  881. // Should find no results since sessions/ was ignored
  882. if (exitCode === 0) {
  883. expect(stdout).not.toContain("session1");
  884. expect(stdout).not.toContain("session2");
  885. }
  886. });
  887. test("non-ignored files are searchable", async () => {
  888. const { stdout, exitCode } = await runQmd(["search", "personal note", "-n", "10"], {
  889. cwd: ignoreTestDir,
  890. dbPath: localDbPath,
  891. configDir: localConfigDir,
  892. });
  893. expect(exitCode).toBe(0);
  894. expect(stdout).toContain("note1");
  895. });
  896. test("status shows ignore patterns", async () => {
  897. const { stdout, exitCode } = await runQmd(["collection", "list"], {
  898. cwd: ignoreTestDir,
  899. dbPath: localDbPath,
  900. configDir: localConfigDir,
  901. });
  902. expect(exitCode).toBe(0);
  903. expect(stdout).toContain("Ignore:");
  904. expect(stdout).toContain("sessions/**");
  905. expect(stdout).toContain("archive/**");
  906. });
  907. test("collection without ignore indexes all files", async () => {
  908. // Create a second collection without ignore
  909. const env2 = await createIsolatedTestEnv("no-ignore");
  910. await writeFile(
  911. join(env2.configDir, "index.yml"),
  912. `collections:
  913. allfiles:
  914. path: ${ignoreTestDir}
  915. pattern: "**/*.md"
  916. `
  917. );
  918. const { stdout, exitCode } = await runQmd(["update"], {
  919. cwd: ignoreTestDir,
  920. dbPath: env2.dbPath,
  921. configDir: env2.configDir,
  922. });
  923. expect(exitCode).toBe(0);
  924. // Should index all 5 files
  925. expect(stdout).toContain("5 new");
  926. });
  927. });
  928. // =============================================================================
  929. // Output Format Tests - qmd:// URIs, context, and docid
  930. // =============================================================================
  931. describe("search output formats", () => {
  932. let localDbPath: string;
  933. let localConfigDir: string;
  934. const collName = "fixtures";
  935. beforeAll(async () => {
  936. const env = await createIsolatedTestEnv("output-format");
  937. localDbPath = env.dbPath;
  938. localConfigDir = env.configDir;
  939. // Add collection
  940. const { exitCode, stderr } = await runQmd(
  941. ["collection", "add", fixturesDir, "--name", collName],
  942. { dbPath: localDbPath, configDir: localConfigDir }
  943. );
  944. if (exitCode !== 0) console.error("collection add failed:", stderr);
  945. expect(exitCode).toBe(0);
  946. // Add context
  947. await runQmd(["context", "add", `qmd://${collName}/`, "Test fixtures for QMD"], { dbPath: localDbPath, configDir: localConfigDir });
  948. });
  949. test("search --json includes qmd:// path, docid, and context", async () => {
  950. const { stdout, exitCode } = await runQmd(["search", "test", "--json", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  951. expect(exitCode).toBe(0);
  952. const results = JSON.parse(stdout);
  953. expect(results.length).toBeGreaterThan(0);
  954. const result = results[0];
  955. expect(result.file).toMatch(new RegExp(`^qmd://${collName}/`));
  956. expect(result.docid).toMatch(/^#[a-f0-9]{6}$/);
  957. expect(result.context).toBe("Test fixtures for QMD");
  958. // Ensure no full filesystem paths
  959. expect(result.file).not.toMatch(/^\/Users\//);
  960. expect(result.file).not.toMatch(/^\/home\//);
  961. });
  962. test("search --files includes qmd:// path, docid, and context", async () => {
  963. const { stdout, exitCode } = await runQmd(["search", "test", "--files", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  964. expect(exitCode).toBe(0);
  965. // Format: #docid,score,qmd://collection/path,"context"
  966. expect(stdout).toMatch(new RegExp(`^#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`, "m"));
  967. expect(stdout).toContain("Test fixtures for QMD");
  968. // Ensure no full filesystem paths
  969. expect(stdout).not.toMatch(/\/Users\//);
  970. expect(stdout).not.toMatch(/\/home\//);
  971. });
  972. test("search --csv includes qmd:// path, docid, and context", async () => {
  973. const { stdout, exitCode } = await runQmd(["search", "test", "--csv", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  974. expect(exitCode).toBe(0);
  975. // Header should include context
  976. expect(stdout).toMatch(/^docid,score,file,title,context,line,snippet$/m);
  977. // Data rows should have qmd:// paths and context
  978. expect(stdout).toMatch(new RegExp(`#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`));
  979. expect(stdout).toContain("Test fixtures for QMD");
  980. // Ensure no full filesystem paths
  981. expect(stdout).not.toMatch(/\/Users\//);
  982. expect(stdout).not.toMatch(/\/home\//);
  983. });
  984. test("search --md includes docid and context", async () => {
  985. const { stdout, exitCode } = await runQmd(["search", "test", "--md", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  986. expect(exitCode).toBe(0);
  987. expect(stdout).toMatch(/\*\*docid:\*\* `#[a-f0-9]{6}`/);
  988. expect(stdout).toContain("**context:** Test fixtures for QMD");
  989. });
  990. test("search --xml includes qmd:// path, docid, and context", async () => {
  991. const { stdout, exitCode } = await runQmd(["search", "test", "--xml", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  992. expect(exitCode).toBe(0);
  993. expect(stdout).toMatch(new RegExp(`<file docid="#[a-f0-9]{6}" name="qmd://${collName}/`));
  994. expect(stdout).toContain('context="Test fixtures for QMD"');
  995. // Ensure no full filesystem paths
  996. expect(stdout).not.toMatch(/\/Users\//);
  997. expect(stdout).not.toMatch(/\/home\//);
  998. });
  999. test("search default CLI format includes plain qmd:// path, docid, and context in non-TTY mode", async () => {
  1000. const { stdout, exitCode } = await runQmd(["search", "test", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1001. expect(exitCode).toBe(0);
  1002. // runQmd uses piped stdio, so stdout is non-TTY and should not contain OSC 8 links.
  1003. expect(stdout).toMatch(new RegExp(`^qmd://${collName}/.*#[a-f0-9]{6}`, "m"));
  1004. expect(stdout).toContain("Context: Test fixtures for QMD");
  1005. expect(stdout).not.toContain("\x1b]8;;");
  1006. // Ensure no full filesystem paths
  1007. expect(stdout).not.toMatch(/\/Users\//);
  1008. expect(stdout).not.toMatch(/\/home\//);
  1009. });
  1010. });
  1011. describe("editor URI templates", () => {
  1012. test("buildEditorUri expands path, line, and col placeholders", () => {
  1013. const uri = buildEditorUri(
  1014. "vscode://file/{path}:{line}:{col}",
  1015. "/tmp/my notes/readme.md",
  1016. 42,
  1017. 1,
  1018. );
  1019. expect(uri).toBe("vscode://file//tmp/my%20notes/readme.md:42:1");
  1020. });
  1021. test("buildEditorUri supports {column} alias", () => {
  1022. const uri = buildEditorUri(
  1023. "cursor://file/{path}:{line}:{column}",
  1024. "/tmp/docs/api.md",
  1025. 7,
  1026. 3,
  1027. );
  1028. expect(uri).toBe("cursor://file//tmp/docs/api.md:7:3");
  1029. });
  1030. test("termLink returns plain text when stdout is not a TTY", () => {
  1031. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", false);
  1032. expect(linked).toBe("docs/api.md:12");
  1033. });
  1034. test("termLink emits OSC 8 hyperlinks when stdout is a TTY", () => {
  1035. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", true);
  1036. expect(linked).toBe("\x1b]8;;vscode://file//tmp/docs/api.md:12:1\x07docs/api.md:12\x1b]8;;\x07");
  1037. });
  1038. });
  1039. // =============================================================================
  1040. // Get Command Path Normalization Tests
  1041. // =============================================================================
  1042. describe("get command path normalization", () => {
  1043. let localDbPath: string;
  1044. let localConfigDir: string;
  1045. const collName = "fixtures";
  1046. beforeAll(async () => {
  1047. const env = await createIsolatedTestEnv("get-paths");
  1048. localDbPath = env.dbPath;
  1049. localConfigDir = env.configDir;
  1050. const { exitCode, stderr } = await runQmd(
  1051. ["collection", "add", fixturesDir, "--name", collName],
  1052. { dbPath: localDbPath, configDir: localConfigDir }
  1053. );
  1054. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1055. expect(exitCode).toBe(0);
  1056. });
  1057. test("get with qmd://collection/path format", async () => {
  1058. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1059. expect(exitCode).toBe(0);
  1060. expect(stdout).toContain("Test Document 1");
  1061. });
  1062. test("get with collection/path format (no scheme)", async () => {
  1063. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1064. expect(exitCode).toBe(0);
  1065. expect(stdout).toContain("Test Document 1");
  1066. });
  1067. test("get with //collection/path format", async () => {
  1068. const { stdout, exitCode } = await runQmd(["get", `//${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1069. expect(exitCode).toBe(0);
  1070. expect(stdout).toContain("Test Document 1");
  1071. });
  1072. test("get with qmd:////collection/path format (extra slashes)", async () => {
  1073. const { stdout, exitCode } = await runQmd(["get", `qmd:////${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1074. expect(exitCode).toBe(0);
  1075. expect(stdout).toContain("Test Document 1");
  1076. });
  1077. test("get with path:line format", async () => {
  1078. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1079. expect(exitCode).toBe(0);
  1080. // Should start from line 3, not line 1
  1081. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1082. });
  1083. test("get with qmd://path:line format", async () => {
  1084. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1085. expect(exitCode).toBe(0);
  1086. // Should start from line 3, not line 1
  1087. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1088. });
  1089. });
  1090. // =============================================================================
  1091. // Status and Collection List - No Full Paths
  1092. // =============================================================================
  1093. describe("status and collection list hide filesystem paths", () => {
  1094. let localDbPath: string;
  1095. let localConfigDir: string;
  1096. const collName = "fixtures";
  1097. beforeAll(async () => {
  1098. const env = await createIsolatedTestEnv("status-paths");
  1099. localDbPath = env.dbPath;
  1100. localConfigDir = env.configDir;
  1101. const { exitCode, stderr } = await runQmd(
  1102. ["collection", "add", fixturesDir, "--name", collName],
  1103. { dbPath: localDbPath, configDir: localConfigDir }
  1104. );
  1105. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1106. expect(exitCode).toBe(0);
  1107. });
  1108. test("status does not show full filesystem paths", async () => {
  1109. const { stdout, exitCode } = await runQmd(["status"], { dbPath: localDbPath, configDir: localConfigDir });
  1110. expect(exitCode).toBe(0);
  1111. // Should show qmd:// URIs
  1112. expect(stdout).toContain(`qmd://${collName}/`);
  1113. // Should NOT show full filesystem paths (except for the index location which is ok)
  1114. const lines = stdout.split('\n').filter(l => !l.includes('Index:'));
  1115. const pathLines = lines.filter(l => l.includes('/Users/') || l.includes('/home/') || l.includes('/tmp/'));
  1116. expect(pathLines.length).toBe(0);
  1117. });
  1118. test("collection list does not show full filesystem paths", async () => {
  1119. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath, configDir: localConfigDir });
  1120. expect(exitCode).toBe(0);
  1121. // Should show qmd:// URIs
  1122. expect(stdout).toContain(`qmd://${collName}/`);
  1123. // Should NOT show Path: lines with filesystem paths
  1124. expect(stdout).not.toMatch(/Path:\s+\//);
  1125. });
  1126. });
  1127. // =============================================================================
  1128. // MCP HTTP Daemon Lifecycle
  1129. // =============================================================================
  1130. describe("mcp http daemon", () => {
  1131. let daemonTestDir: string;
  1132. let daemonCacheDir: string; // XDG_CACHE_HOME value (the qmd/ subdir is created automatically)
  1133. let daemonDbPath: string;
  1134. let daemonConfigDir: string;
  1135. // Track spawned PIDs for cleanup
  1136. const spawnedPids: number[] = [];
  1137. /** Get path to PID file inside the test cache dir */
  1138. function pidPath(): string {
  1139. return join(daemonCacheDir, "qmd", "mcp.pid");
  1140. }
  1141. /** Run qmd with test-isolated env (cache, db, config) */
  1142. async function runDaemonQmd(
  1143. args: string[],
  1144. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  1145. return runQmd(args, {
  1146. dbPath: daemonDbPath,
  1147. configDir: daemonConfigDir,
  1148. env: { XDG_CACHE_HOME: daemonCacheDir },
  1149. });
  1150. }
  1151. /** Spawn a foreground HTTP server (non-blocking) and return the process */
  1152. function spawnHttpServer(port: number): import("child_process").ChildProcess {
  1153. const proc = spawn(tsxBin, [qmdScript, "mcp", "--http", "--port", String(port)], {
  1154. cwd: fixturesDir,
  1155. env: {
  1156. ...process.env,
  1157. INDEX_PATH: daemonDbPath,
  1158. QMD_CONFIG_DIR: daemonConfigDir,
  1159. },
  1160. stdio: ["ignore", "pipe", "pipe"],
  1161. });
  1162. if (proc.pid) spawnedPids.push(proc.pid);
  1163. return proc;
  1164. }
  1165. /** Wait for HTTP server to become ready */
  1166. async function waitForServer(port: number, timeoutMs = 5000): Promise<boolean> {
  1167. const deadline = Date.now() + timeoutMs;
  1168. while (Date.now() < deadline) {
  1169. try {
  1170. const res = await fetch(`http://localhost:${port}/health`);
  1171. if (res.ok) return true;
  1172. } catch { /* not ready yet */ }
  1173. await sleep(200);
  1174. }
  1175. return false;
  1176. }
  1177. /** Pick a random high port unlikely to conflict */
  1178. function randomPort(): number {
  1179. return 10000 + Math.floor(Math.random() * 50000);
  1180. }
  1181. beforeAll(async () => {
  1182. daemonTestDir = await mkdtemp(join(tmpdir(), "qmd-daemon-test-"));
  1183. daemonCacheDir = join(daemonTestDir, "cache");
  1184. daemonDbPath = join(daemonTestDir, "test.sqlite");
  1185. daemonConfigDir = join(daemonTestDir, "config");
  1186. await mkdir(join(daemonCacheDir, "qmd"), { recursive: true });
  1187. await mkdir(daemonConfigDir, { recursive: true });
  1188. await writeFile(join(daemonConfigDir, "index.yml"), "collections: {}\n");
  1189. });
  1190. afterAll(async () => {
  1191. // Kill any leftover spawned processes
  1192. for (const pid of spawnedPids) {
  1193. try { process.kill(pid, "SIGTERM"); } catch { /* already dead */ }
  1194. }
  1195. // Also clean up via PID file if present
  1196. try {
  1197. const pf = pidPath();
  1198. if (existsSync(pf)) {
  1199. const pid = parseInt(readFileSync(pf, "utf-8").trim());
  1200. try { process.kill(pid, "SIGTERM"); } catch {}
  1201. unlinkSync(pf);
  1202. }
  1203. } catch {}
  1204. await rm(daemonTestDir, { recursive: true, force: true });
  1205. });
  1206. // -------------------------------------------------------------------------
  1207. // Foreground HTTP
  1208. // -------------------------------------------------------------------------
  1209. test("foreground HTTP server starts and responds to health check", async () => {
  1210. const port = randomPort();
  1211. const proc = spawnHttpServer(port);
  1212. try {
  1213. const ready = await waitForServer(port);
  1214. expect(ready).toBe(true);
  1215. const res = await fetch(`http://localhost:${port}/health`);
  1216. expect(res.status).toBe(200);
  1217. const body = await res.json();
  1218. expect(body.status).toBe("ok");
  1219. } finally {
  1220. proc.kill("SIGTERM");
  1221. await new Promise(r => proc.on("close", r));
  1222. }
  1223. });
  1224. // -------------------------------------------------------------------------
  1225. // Daemon lifecycle
  1226. // -------------------------------------------------------------------------
  1227. test("--daemon writes PID file and starts server", async () => {
  1228. const port = randomPort();
  1229. const { stdout, exitCode } = await runDaemonQmd([
  1230. "mcp", "--http", "--daemon", "--port", String(port),
  1231. ]);
  1232. expect(exitCode).toBe(0);
  1233. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1234. // PID file should exist
  1235. expect(existsSync(pidPath())).toBe(true);
  1236. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1237. spawnedPids.push(pid);
  1238. // Server should be reachable
  1239. const ready = await waitForServer(port);
  1240. expect(ready).toBe(true);
  1241. // Clean up
  1242. process.kill(pid, "SIGTERM");
  1243. await sleep(500);
  1244. try { unlinkSync(pidPath()); } catch {}
  1245. });
  1246. test("stop kills daemon and removes PID file", async () => {
  1247. const port = randomPort();
  1248. // Start daemon
  1249. const { exitCode: startCode } = await runDaemonQmd([
  1250. "mcp", "--http", "--daemon", "--port", String(port),
  1251. ]);
  1252. expect(startCode).toBe(0);
  1253. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1254. spawnedPids.push(pid);
  1255. await waitForServer(port);
  1256. // Stop it
  1257. const { stdout: stopOut, exitCode: stopCode } = await runDaemonQmd(["mcp", "stop"]);
  1258. expect(stopCode).toBe(0);
  1259. expect(stopOut).toContain("Stopped");
  1260. // PID file should be gone
  1261. expect(existsSync(pidPath())).toBe(false);
  1262. // Process should be dead
  1263. await sleep(500);
  1264. expect(() => process.kill(pid, 0)).toThrow();
  1265. });
  1266. test("stop handles dead PID gracefully (cleans stale file)", async () => {
  1267. // Write a PID file pointing to a dead process
  1268. writeFileSync(pidPath(), "999999999");
  1269. const { stdout, exitCode } = await runDaemonQmd(["mcp", "stop"]);
  1270. expect(exitCode).toBe(0);
  1271. expect(stdout).toContain("stale");
  1272. // PID file should be cleaned up
  1273. expect(existsSync(pidPath())).toBe(false);
  1274. });
  1275. test("--daemon rejects if already running", async () => {
  1276. const port = randomPort();
  1277. // Start first daemon
  1278. const { exitCode: firstCode } = await runDaemonQmd([
  1279. "mcp", "--http", "--daemon", "--port", String(port),
  1280. ]);
  1281. expect(firstCode).toBe(0);
  1282. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1283. spawnedPids.push(pid);
  1284. await waitForServer(port);
  1285. // Try to start second daemon — should fail
  1286. const { stderr, exitCode } = await runDaemonQmd([
  1287. "mcp", "--http", "--daemon", "--port", String(port + 1),
  1288. ]);
  1289. expect(exitCode).toBe(1);
  1290. expect(stderr).toContain("Already running");
  1291. // Clean up first daemon
  1292. process.kill(pid, "SIGTERM");
  1293. await sleep(500);
  1294. try { unlinkSync(pidPath()); } catch {}
  1295. });
  1296. test("--daemon cleans stale PID file and starts fresh", async () => {
  1297. // Write a stale PID file
  1298. writeFileSync(pidPath(), "999999999");
  1299. const port = randomPort();
  1300. const { exitCode, stdout } = await runDaemonQmd([
  1301. "mcp", "--http", "--daemon", "--port", String(port),
  1302. ]);
  1303. expect(exitCode).toBe(0);
  1304. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1305. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1306. spawnedPids.push(pid);
  1307. expect(pid).not.toBe(999999999);
  1308. // Clean up
  1309. const ready = await waitForServer(port);
  1310. expect(ready).toBe(true);
  1311. process.kill(pid, "SIGTERM");
  1312. await sleep(500);
  1313. try { unlinkSync(pidPath()); } catch {}
  1314. });
  1315. });