cli.test.ts 48 KB

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