cli.test.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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", "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. });
  386. describe("CLI Add-Context Command", () => {
  387. let localDbPath: string;
  388. let localConfigDir: string;
  389. const collName = "fixtures";
  390. beforeAll(async () => {
  391. const env = await createIsolatedTestEnv("context-cmd");
  392. localDbPath = env.dbPath;
  393. localConfigDir = env.configDir;
  394. // Add collection with known name
  395. const { exitCode, stderr } = await runQmd(
  396. ["collection", "add", fixturesDir, "--name", collName],
  397. { dbPath: localDbPath, configDir: localConfigDir }
  398. );
  399. if (exitCode !== 0) console.error("collection add failed:", stderr);
  400. expect(exitCode).toBe(0);
  401. });
  402. test("adds context to a path", async () => {
  403. // Add context to the collection root using virtual path
  404. const { stdout, exitCode } = await runQmd([
  405. "context",
  406. "add",
  407. `qmd://${collName}/`,
  408. "Personal notes and meeting logs",
  409. ], { dbPath: localDbPath, configDir: localConfigDir });
  410. expect(exitCode).toBe(0);
  411. expect(stdout).toContain("✓ Added context");
  412. });
  413. test("requires path and text arguments", async () => {
  414. const { stderr, exitCode } = await runQmd(["context", "add"], { dbPath: localDbPath, configDir: localConfigDir });
  415. expect(exitCode).toBe(1);
  416. // Error message goes to stderr
  417. expect(stderr).toContain("Usage:");
  418. });
  419. });
  420. describe("CLI Cleanup Command", () => {
  421. beforeEach(async () => {
  422. // Ensure we have indexed files
  423. await runQmd(["collection", "add", "."]);
  424. });
  425. test("cleans up orphaned entries", async () => {
  426. const { stdout, exitCode } = await runQmd(["cleanup"]);
  427. expect(exitCode).toBe(0);
  428. });
  429. });
  430. describe("CLI Error Handling", () => {
  431. test("handles unknown command", async () => {
  432. const { stderr, exitCode } = await runQmd(["unknowncommand"]);
  433. expect(exitCode).toBe(1);
  434. // Should indicate unknown command
  435. expect(stderr).toContain("Unknown command");
  436. });
  437. test("uses INDEX_PATH environment variable", async () => {
  438. // Verify the test DB path is being used by creating a separate index
  439. const customDbPath = join(testDir, "custom.sqlite");
  440. const { exitCode } = await runQmd(["collection", "add", "."], {
  441. env: { INDEX_PATH: customDbPath },
  442. });
  443. expect(exitCode).toBe(0);
  444. // The custom database should exist
  445. expect(existsSync(customDbPath)).toBe(true);
  446. });
  447. });
  448. describe("CLI Output Formats", () => {
  449. beforeEach(async () => {
  450. await runQmd(["collection", "add", "."]);
  451. });
  452. test("search with --json flag outputs JSON", async () => {
  453. const { stdout, exitCode } = await runQmd(["search", "--json", "test"]);
  454. expect(exitCode).toBe(0);
  455. // Should be valid JSON
  456. const parsed = JSON.parse(stdout);
  457. expect(Array.isArray(parsed)).toBe(true);
  458. });
  459. test("search with --files flag outputs file paths", async () => {
  460. const { stdout, exitCode } = await runQmd(["search", "--files", "meeting"]);
  461. expect(exitCode).toBe(0);
  462. expect(stdout).toContain(".md");
  463. });
  464. test("search output includes snippets by default", async () => {
  465. const { stdout, exitCode } = await runQmd(["search", "API"]);
  466. expect(exitCode).toBe(0);
  467. // If results found, should have snippet content
  468. if (!stdout.includes("No results")) {
  469. expect(stdout.toLowerCase()).toContain("api");
  470. }
  471. });
  472. });
  473. describe("CLI Search with Collection Filter", () => {
  474. let localDbPath: string;
  475. beforeEach(async () => {
  476. // Use a fresh database for this test suite
  477. localDbPath = getFreshDbPath();
  478. // Create multiple collections with explicit names
  479. await runQmd(["collection", "add", ".", "--name", "notes", "--mask", "notes/*.md"], { dbPath: localDbPath });
  480. await runQmd(["collection", "add", ".", "--name", "docs", "--mask", "docs/*.md"], { dbPath: localDbPath });
  481. });
  482. test("filters search by collection name", async () => {
  483. const { stdout, stderr, exitCode } = await runQmd([
  484. "search",
  485. "-c",
  486. "notes",
  487. "meeting",
  488. ], { dbPath: localDbPath });
  489. if (exitCode !== 0) {
  490. console.log("Collection filter search failed:");
  491. console.log("stdout:", stdout);
  492. console.log("stderr:", stderr);
  493. }
  494. expect(exitCode).toBe(0);
  495. });
  496. });
  497. describe("CLI Context Management", () => {
  498. let localDbPath: string;
  499. beforeEach(async () => {
  500. // Use a fresh database for this test suite
  501. localDbPath = getFreshDbPath();
  502. // Index some files first
  503. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  504. });
  505. test("add global context with /", async () => {
  506. const { stdout, exitCode } = await runQmd([
  507. "context",
  508. "add",
  509. "/",
  510. "Global system context",
  511. ], { dbPath: localDbPath });
  512. expect(exitCode).toBe(0);
  513. expect(stdout).toContain("✓ Set global context");
  514. expect(stdout).toContain("Global system context");
  515. });
  516. test("list contexts", async () => {
  517. // Add a global context first
  518. await runQmd([
  519. "context",
  520. "add",
  521. "/",
  522. "Test context",
  523. ], { dbPath: localDbPath });
  524. const { stdout, exitCode } = await runQmd([
  525. "context",
  526. "list",
  527. ], { dbPath: localDbPath });
  528. expect(exitCode).toBe(0);
  529. expect(stdout).toContain("Configured Contexts");
  530. expect(stdout).toContain("Test context");
  531. });
  532. test("add context to virtual path", async () => {
  533. // Collection name should be "fixtures" (basename of the fixtures directory)
  534. const { stdout, exitCode } = await runQmd([
  535. "context",
  536. "add",
  537. "qmd://fixtures/notes",
  538. "Context for notes subdirectory",
  539. ], { dbPath: localDbPath });
  540. expect(exitCode).toBe(0);
  541. expect(stdout).toContain("✓ Added context for: qmd://fixtures/notes");
  542. });
  543. test("remove global context", async () => {
  544. // Add a global context first
  545. await runQmd([
  546. "context",
  547. "add",
  548. "/",
  549. "Global context to remove",
  550. ], { dbPath: localDbPath });
  551. const { stdout, exitCode } = await runQmd([
  552. "context",
  553. "rm",
  554. "/",
  555. ], { dbPath: localDbPath });
  556. expect(exitCode).toBe(0);
  557. expect(stdout).toContain("✓ Removed");
  558. });
  559. test("remove virtual path context", async () => {
  560. // Add a context first
  561. await runQmd([
  562. "context",
  563. "add",
  564. "qmd://fixtures/notes",
  565. "Context to remove",
  566. ], { dbPath: localDbPath });
  567. const { stdout, exitCode } = await runQmd([
  568. "context",
  569. "rm",
  570. "qmd://fixtures/notes",
  571. ], { dbPath: localDbPath });
  572. expect(exitCode).toBe(0);
  573. expect(stdout).toContain("✓ Removed context for: qmd://fixtures/notes");
  574. });
  575. test("fails to remove non-existent context", async () => {
  576. const { stdout, stderr, exitCode } = await runQmd([
  577. "context",
  578. "rm",
  579. "qmd://nonexistent/path",
  580. ], { dbPath: localDbPath });
  581. expect(exitCode).toBe(1);
  582. expect(stderr || stdout).toContain("not found");
  583. });
  584. });
  585. describe("CLI ls Command", () => {
  586. let localDbPath: string;
  587. beforeEach(async () => {
  588. // Use a fresh database for this test suite
  589. localDbPath = getFreshDbPath();
  590. // Index some files first
  591. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  592. });
  593. test("lists all collections", async () => {
  594. const { stdout, exitCode } = await runQmd(["ls"], { dbPath: localDbPath });
  595. expect(exitCode).toBe(0);
  596. expect(stdout).toContain("Collections:");
  597. expect(stdout).toContain("qmd://fixtures/");
  598. });
  599. test("lists files in a collection", async () => {
  600. const { stdout, exitCode } = await runQmd(["ls", "fixtures"], { dbPath: localDbPath });
  601. expect(exitCode).toBe(0);
  602. // handelize converts to lowercase
  603. expect(stdout).toContain("qmd://fixtures/readme.md");
  604. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  605. });
  606. test("lists files with path prefix", async () => {
  607. const { stdout, exitCode } = await runQmd(["ls", "fixtures/notes"], { dbPath: localDbPath });
  608. expect(exitCode).toBe(0);
  609. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  610. expect(stdout).toContain("qmd://fixtures/notes/ideas.md");
  611. // Should not include files outside the prefix (handelize converts to lowercase)
  612. expect(stdout).not.toContain("qmd://fixtures/readme.md");
  613. });
  614. test("lists files with virtual path", async () => {
  615. const { stdout, exitCode } = await runQmd(["ls", "qmd://fixtures/docs"], { dbPath: localDbPath });
  616. expect(exitCode).toBe(0);
  617. expect(stdout).toContain("qmd://fixtures/docs/api.md");
  618. });
  619. test("handles non-existent collection", async () => {
  620. const { stderr, exitCode } = await runQmd(["ls", "nonexistent"], { dbPath: localDbPath });
  621. expect(exitCode).toBe(1);
  622. expect(stderr).toContain("Collection not found");
  623. });
  624. });
  625. describe("CLI Collection Commands", () => {
  626. let localDbPath: string;
  627. beforeEach(async () => {
  628. // Use a fresh database for this test suite
  629. localDbPath = getFreshDbPath();
  630. // Index some files first to create a collection
  631. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  632. });
  633. test("lists collections", async () => {
  634. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  635. expect(exitCode).toBe(0);
  636. expect(stdout).toContain("Collections");
  637. expect(stdout).toContain("fixtures");
  638. expect(stdout).toContain("qmd://fixtures/");
  639. expect(stdout).toContain("Pattern:");
  640. expect(stdout).toContain("Files:");
  641. });
  642. test("removes a collection", async () => {
  643. // First verify the collection exists
  644. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  645. expect(listBefore).toContain("fixtures");
  646. // Remove it
  647. const { stdout, exitCode } = await runQmd(["collection", "remove", "fixtures"], { dbPath: localDbPath });
  648. expect(exitCode).toBe(0);
  649. expect(stdout).toContain("✓ Removed collection 'fixtures'");
  650. expect(stdout).toContain("Deleted");
  651. // Verify it's gone
  652. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  653. expect(listAfter).not.toContain("fixtures");
  654. });
  655. test("handles removing non-existent collection", async () => {
  656. const { stderr, exitCode } = await runQmd(["collection", "remove", "nonexistent"], { dbPath: localDbPath });
  657. expect(exitCode).toBe(1);
  658. expect(stderr).toContain("Collection not found");
  659. });
  660. test("handles missing remove argument", async () => {
  661. const { stderr, exitCode } = await runQmd(["collection", "remove"], { dbPath: localDbPath });
  662. expect(exitCode).toBe(1);
  663. expect(stderr).toContain("Usage:");
  664. });
  665. test("handles unknown subcommand", async () => {
  666. const { stderr, exitCode } = await runQmd(["collection", "invalid"], { dbPath: localDbPath });
  667. expect(exitCode).toBe(1);
  668. expect(stderr).toContain("Unknown subcommand");
  669. });
  670. test("renames a collection", async () => {
  671. // First verify the collection exists
  672. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  673. expect(listBefore).toContain("qmd://fixtures/");
  674. // Rename it
  675. const { stdout, exitCode } = await runQmd(["collection", "rename", "fixtures", "my-fixtures"], { dbPath: localDbPath });
  676. expect(exitCode).toBe(0);
  677. expect(stdout).toContain("✓ Renamed collection 'fixtures' to 'my-fixtures'");
  678. expect(stdout).toContain("qmd://fixtures/");
  679. expect(stdout).toContain("qmd://my-fixtures/");
  680. // Verify the new name exists and old name is gone
  681. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  682. expect(listAfter).toContain("qmd://my-fixtures/");
  683. expect(listAfter).not.toContain("qmd://fixtures/"); // Old collection should not appear
  684. });
  685. test("handles renaming non-existent collection", async () => {
  686. const { stderr, exitCode } = await runQmd(["collection", "rename", "nonexistent", "newname"], { dbPath: localDbPath });
  687. expect(exitCode).toBe(1);
  688. expect(stderr).toContain("Collection not found");
  689. });
  690. test("handles renaming to existing collection name", async () => {
  691. // Create a second collection in a temp directory
  692. const tempDir = await mkdtemp(join(tmpdir(), "qmd-second-"));
  693. await writeFile(join(tempDir, "test.md"), "# Test");
  694. const addResult = await runQmd(["collection", "add", tempDir, "--name", "second"], { dbPath: localDbPath });
  695. if (addResult.exitCode !== 0) {
  696. console.error("Failed to add second collection:", addResult.stderr);
  697. }
  698. expect(addResult.exitCode).toBe(0);
  699. // Verify both collections exist
  700. const { stdout: listBoth } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  701. expect(listBoth).toContain("qmd://fixtures/");
  702. expect(listBoth).toContain("qmd://second/");
  703. // Try to rename fixtures to second (which already exists)
  704. const { stderr, exitCode } = await runQmd(["collection", "rename", "fixtures", "second"], { dbPath: localDbPath });
  705. expect(exitCode).toBe(1);
  706. expect(stderr).toContain("Collection name already exists");
  707. });
  708. test("handles missing rename arguments", async () => {
  709. const { stderr: stderr1, exitCode: exitCode1 } = await runQmd(["collection", "rename"], { dbPath: localDbPath });
  710. expect(exitCode1).toBe(1);
  711. expect(stderr1).toContain("Usage:");
  712. const { stderr: stderr2, exitCode: exitCode2 } = await runQmd(["collection", "rename", "fixtures"], { dbPath: localDbPath });
  713. expect(exitCode2).toBe(1);
  714. expect(stderr2).toContain("Usage:");
  715. });
  716. });
  717. // =============================================================================
  718. // Output Format Tests - qmd:// URIs, context, and docid
  719. // =============================================================================
  720. describe("search output formats", () => {
  721. let localDbPath: string;
  722. let localConfigDir: string;
  723. const collName = "fixtures";
  724. beforeAll(async () => {
  725. const env = await createIsolatedTestEnv("output-format");
  726. localDbPath = env.dbPath;
  727. localConfigDir = env.configDir;
  728. // Add collection
  729. const { exitCode, stderr } = await runQmd(
  730. ["collection", "add", fixturesDir, "--name", collName],
  731. { dbPath: localDbPath, configDir: localConfigDir }
  732. );
  733. if (exitCode !== 0) console.error("collection add failed:", stderr);
  734. expect(exitCode).toBe(0);
  735. // Add context
  736. await runQmd(["context", "add", `qmd://${collName}/`, "Test fixtures for QMD"], { dbPath: localDbPath, configDir: localConfigDir });
  737. });
  738. test("search --json includes qmd:// path, docid, and context", async () => {
  739. const { stdout, exitCode } = await runQmd(["search", "test", "--json", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  740. expect(exitCode).toBe(0);
  741. const results = JSON.parse(stdout);
  742. expect(results.length).toBeGreaterThan(0);
  743. const result = results[0];
  744. expect(result.file).toMatch(new RegExp(`^qmd://${collName}/`));
  745. expect(result.docid).toMatch(/^#[a-f0-9]{6}$/);
  746. expect(result.context).toBe("Test fixtures for QMD");
  747. // Ensure no full filesystem paths
  748. expect(result.file).not.toMatch(/^\/Users\//);
  749. expect(result.file).not.toMatch(/^\/home\//);
  750. });
  751. test("search --files includes qmd:// path, docid, and context", async () => {
  752. const { stdout, exitCode } = await runQmd(["search", "test", "--files", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  753. expect(exitCode).toBe(0);
  754. // Format: #docid,score,qmd://collection/path,"context"
  755. expect(stdout).toMatch(new RegExp(`^#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`, "m"));
  756. expect(stdout).toContain("Test fixtures for QMD");
  757. // Ensure no full filesystem paths
  758. expect(stdout).not.toMatch(/\/Users\//);
  759. expect(stdout).not.toMatch(/\/home\//);
  760. });
  761. test("search --csv includes qmd:// path, docid, and context", async () => {
  762. const { stdout, exitCode } = await runQmd(["search", "test", "--csv", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  763. expect(exitCode).toBe(0);
  764. // Header should include context
  765. expect(stdout).toMatch(/^docid,score,file,title,context,line,snippet$/m);
  766. // Data rows should have qmd:// paths and context
  767. expect(stdout).toMatch(new RegExp(`#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`));
  768. expect(stdout).toContain("Test fixtures for QMD");
  769. // Ensure no full filesystem paths
  770. expect(stdout).not.toMatch(/\/Users\//);
  771. expect(stdout).not.toMatch(/\/home\//);
  772. });
  773. test("search --md includes docid and context", async () => {
  774. const { stdout, exitCode } = await runQmd(["search", "test", "--md", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  775. expect(exitCode).toBe(0);
  776. expect(stdout).toMatch(/\*\*docid:\*\* `#[a-f0-9]{6}`/);
  777. expect(stdout).toContain("**context:** Test fixtures for QMD");
  778. });
  779. test("search --xml includes qmd:// path, docid, and context", async () => {
  780. const { stdout, exitCode } = await runQmd(["search", "test", "--xml", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  781. expect(exitCode).toBe(0);
  782. expect(stdout).toMatch(new RegExp(`<file docid="#[a-f0-9]{6}" name="qmd://${collName}/`));
  783. expect(stdout).toContain('context="Test fixtures for QMD"');
  784. // Ensure no full filesystem paths
  785. expect(stdout).not.toMatch(/\/Users\//);
  786. expect(stdout).not.toMatch(/\/home\//);
  787. });
  788. test("search default CLI format includes qmd:// path, docid, and context", async () => {
  789. const { stdout, exitCode } = await runQmd(["search", "test", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  790. expect(exitCode).toBe(0);
  791. // First line should have qmd:// path and docid
  792. expect(stdout).toMatch(new RegExp(`^qmd://${collName}/.*#[a-f0-9]{6}`, "m"));
  793. expect(stdout).toContain("Context: Test fixtures for QMD");
  794. // Ensure no full filesystem paths
  795. expect(stdout).not.toMatch(/\/Users\//);
  796. expect(stdout).not.toMatch(/\/home\//);
  797. });
  798. });
  799. // =============================================================================
  800. // Get Command Path Normalization Tests
  801. // =============================================================================
  802. describe("get command path normalization", () => {
  803. let localDbPath: string;
  804. let localConfigDir: string;
  805. const collName = "fixtures";
  806. beforeAll(async () => {
  807. const env = await createIsolatedTestEnv("get-paths");
  808. localDbPath = env.dbPath;
  809. localConfigDir = env.configDir;
  810. const { exitCode, stderr } = await runQmd(
  811. ["collection", "add", fixturesDir, "--name", collName],
  812. { dbPath: localDbPath, configDir: localConfigDir }
  813. );
  814. if (exitCode !== 0) console.error("collection add failed:", stderr);
  815. expect(exitCode).toBe(0);
  816. });
  817. test("get with qmd://collection/path format", async () => {
  818. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  819. expect(exitCode).toBe(0);
  820. expect(stdout).toContain("Test Document 1");
  821. });
  822. test("get with collection/path format (no scheme)", async () => {
  823. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  824. expect(exitCode).toBe(0);
  825. expect(stdout).toContain("Test Document 1");
  826. });
  827. test("get with //collection/path format", async () => {
  828. const { stdout, exitCode } = await runQmd(["get", `//${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  829. expect(exitCode).toBe(0);
  830. expect(stdout).toContain("Test Document 1");
  831. });
  832. test("get with qmd:////collection/path format (extra slashes)", async () => {
  833. const { stdout, exitCode } = await runQmd(["get", `qmd:////${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  834. expect(exitCode).toBe(0);
  835. expect(stdout).toContain("Test Document 1");
  836. });
  837. test("get with path:line format", async () => {
  838. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  839. expect(exitCode).toBe(0);
  840. // Should start from line 3, not line 1
  841. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  842. });
  843. test("get with qmd://path:line format", async () => {
  844. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  845. expect(exitCode).toBe(0);
  846. // Should start from line 3, not line 1
  847. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  848. });
  849. });
  850. // =============================================================================
  851. // Status and Collection List - No Full Paths
  852. // =============================================================================
  853. describe("status and collection list hide filesystem paths", () => {
  854. let localDbPath: string;
  855. let localConfigDir: string;
  856. const collName = "fixtures";
  857. beforeAll(async () => {
  858. const env = await createIsolatedTestEnv("status-paths");
  859. localDbPath = env.dbPath;
  860. localConfigDir = env.configDir;
  861. const { exitCode, stderr } = await runQmd(
  862. ["collection", "add", fixturesDir, "--name", collName],
  863. { dbPath: localDbPath, configDir: localConfigDir }
  864. );
  865. if (exitCode !== 0) console.error("collection add failed:", stderr);
  866. expect(exitCode).toBe(0);
  867. });
  868. test("status does not show full filesystem paths", async () => {
  869. const { stdout, exitCode } = await runQmd(["status"], { dbPath: localDbPath, configDir: localConfigDir });
  870. expect(exitCode).toBe(0);
  871. // Should show qmd:// URIs
  872. expect(stdout).toContain(`qmd://${collName}/`);
  873. // Should NOT show full filesystem paths (except for the index location which is ok)
  874. const lines = stdout.split('\n').filter(l => !l.includes('Index:'));
  875. const pathLines = lines.filter(l => l.includes('/Users/') || l.includes('/home/') || l.includes('/tmp/'));
  876. expect(pathLines.length).toBe(0);
  877. });
  878. test("collection list does not show full filesystem paths", async () => {
  879. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath, configDir: localConfigDir });
  880. expect(exitCode).toBe(0);
  881. // Should show qmd:// URIs
  882. expect(stdout).toContain(`qmd://${collName}/`);
  883. // Should NOT show Path: lines with filesystem paths
  884. expect(stdout).not.toMatch(/Path:\s+\//);
  885. });
  886. });
  887. // =============================================================================
  888. // MCP HTTP Daemon Lifecycle
  889. // =============================================================================
  890. describe("mcp http daemon", () => {
  891. let daemonTestDir: string;
  892. let daemonCacheDir: string; // XDG_CACHE_HOME value (the qmd/ subdir is created automatically)
  893. let daemonDbPath: string;
  894. let daemonConfigDir: string;
  895. // Track spawned PIDs for cleanup
  896. const spawnedPids: number[] = [];
  897. /** Get path to PID file inside the test cache dir */
  898. function pidPath(): string {
  899. return join(daemonCacheDir, "qmd", "mcp.pid");
  900. }
  901. /** Run qmd with test-isolated env (cache, db, config) */
  902. async function runDaemonQmd(
  903. args: string[],
  904. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  905. return runQmd(args, {
  906. dbPath: daemonDbPath,
  907. configDir: daemonConfigDir,
  908. env: { XDG_CACHE_HOME: daemonCacheDir },
  909. });
  910. }
  911. /** Spawn a foreground HTTP server (non-blocking) and return the process */
  912. function spawnHttpServer(port: number): import("child_process").ChildProcess {
  913. const proc = spawn(tsxBin, [qmdScript, "mcp", "--http", "--port", String(port)], {
  914. cwd: fixturesDir,
  915. env: {
  916. ...process.env,
  917. INDEX_PATH: daemonDbPath,
  918. QMD_CONFIG_DIR: daemonConfigDir,
  919. },
  920. stdio: ["ignore", "pipe", "pipe"],
  921. });
  922. if (proc.pid) spawnedPids.push(proc.pid);
  923. return proc;
  924. }
  925. /** Wait for HTTP server to become ready */
  926. async function waitForServer(port: number, timeoutMs = 5000): Promise<boolean> {
  927. const deadline = Date.now() + timeoutMs;
  928. while (Date.now() < deadline) {
  929. try {
  930. const res = await fetch(`http://localhost:${port}/health`);
  931. if (res.ok) return true;
  932. } catch { /* not ready yet */ }
  933. await sleep(200);
  934. }
  935. return false;
  936. }
  937. /** Pick a random high port unlikely to conflict */
  938. function randomPort(): number {
  939. return 10000 + Math.floor(Math.random() * 50000);
  940. }
  941. beforeAll(async () => {
  942. daemonTestDir = await mkdtemp(join(tmpdir(), "qmd-daemon-test-"));
  943. daemonCacheDir = join(daemonTestDir, "cache");
  944. daemonDbPath = join(daemonTestDir, "test.sqlite");
  945. daemonConfigDir = join(daemonTestDir, "config");
  946. await mkdir(join(daemonCacheDir, "qmd"), { recursive: true });
  947. await mkdir(daemonConfigDir, { recursive: true });
  948. await writeFile(join(daemonConfigDir, "index.yml"), "collections: {}\n");
  949. });
  950. afterAll(async () => {
  951. // Kill any leftover spawned processes
  952. for (const pid of spawnedPids) {
  953. try { process.kill(pid, "SIGTERM"); } catch { /* already dead */ }
  954. }
  955. // Also clean up via PID file if present
  956. try {
  957. const pf = pidPath();
  958. if (existsSync(pf)) {
  959. const pid = parseInt(readFileSync(pf, "utf-8").trim());
  960. try { process.kill(pid, "SIGTERM"); } catch {}
  961. unlinkSync(pf);
  962. }
  963. } catch {}
  964. await rm(daemonTestDir, { recursive: true, force: true });
  965. });
  966. // -------------------------------------------------------------------------
  967. // Foreground HTTP
  968. // -------------------------------------------------------------------------
  969. test("foreground HTTP server starts and responds to health check", async () => {
  970. const port = randomPort();
  971. const proc = spawnHttpServer(port);
  972. try {
  973. const ready = await waitForServer(port);
  974. expect(ready).toBe(true);
  975. const res = await fetch(`http://localhost:${port}/health`);
  976. expect(res.status).toBe(200);
  977. const body = await res.json();
  978. expect(body.status).toBe("ok");
  979. } finally {
  980. proc.kill("SIGTERM");
  981. await new Promise(r => proc.on("close", r));
  982. }
  983. });
  984. // -------------------------------------------------------------------------
  985. // Daemon lifecycle
  986. // -------------------------------------------------------------------------
  987. test("--daemon writes PID file and starts server", async () => {
  988. const port = randomPort();
  989. const { stdout, exitCode } = await runDaemonQmd([
  990. "mcp", "--http", "--daemon", "--port", String(port),
  991. ]);
  992. expect(exitCode).toBe(0);
  993. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  994. // PID file should exist
  995. expect(existsSync(pidPath())).toBe(true);
  996. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  997. spawnedPids.push(pid);
  998. // Server should be reachable
  999. const ready = await waitForServer(port);
  1000. expect(ready).toBe(true);
  1001. // Clean up
  1002. process.kill(pid, "SIGTERM");
  1003. await sleep(500);
  1004. try { unlinkSync(pidPath()); } catch {}
  1005. });
  1006. test("stop kills daemon and removes PID file", async () => {
  1007. const port = randomPort();
  1008. // Start daemon
  1009. const { exitCode: startCode } = await runDaemonQmd([
  1010. "mcp", "--http", "--daemon", "--port", String(port),
  1011. ]);
  1012. expect(startCode).toBe(0);
  1013. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1014. spawnedPids.push(pid);
  1015. await waitForServer(port);
  1016. // Stop it
  1017. const { stdout: stopOut, exitCode: stopCode } = await runDaemonQmd(["mcp", "stop"]);
  1018. expect(stopCode).toBe(0);
  1019. expect(stopOut).toContain("Stopped");
  1020. // PID file should be gone
  1021. expect(existsSync(pidPath())).toBe(false);
  1022. // Process should be dead
  1023. await sleep(500);
  1024. expect(() => process.kill(pid, 0)).toThrow();
  1025. });
  1026. test("stop handles dead PID gracefully (cleans stale file)", async () => {
  1027. // Write a PID file pointing to a dead process
  1028. writeFileSync(pidPath(), "999999999");
  1029. const { stdout, exitCode } = await runDaemonQmd(["mcp", "stop"]);
  1030. expect(exitCode).toBe(0);
  1031. expect(stdout).toContain("stale");
  1032. // PID file should be cleaned up
  1033. expect(existsSync(pidPath())).toBe(false);
  1034. });
  1035. test("--daemon rejects if already running", async () => {
  1036. const port = randomPort();
  1037. // Start first daemon
  1038. const { exitCode: firstCode } = await runDaemonQmd([
  1039. "mcp", "--http", "--daemon", "--port", String(port),
  1040. ]);
  1041. expect(firstCode).toBe(0);
  1042. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1043. spawnedPids.push(pid);
  1044. await waitForServer(port);
  1045. // Try to start second daemon — should fail
  1046. const { stderr, exitCode } = await runDaemonQmd([
  1047. "mcp", "--http", "--daemon", "--port", String(port + 1),
  1048. ]);
  1049. expect(exitCode).toBe(1);
  1050. expect(stderr).toContain("Already running");
  1051. // Clean up first daemon
  1052. process.kill(pid, "SIGTERM");
  1053. await sleep(500);
  1054. try { unlinkSync(pidPath()); } catch {}
  1055. });
  1056. test("--daemon cleans stale PID file and starts fresh", async () => {
  1057. // Write a stale PID file
  1058. writeFileSync(pidPath(), "999999999");
  1059. const port = randomPort();
  1060. const { exitCode, stdout } = await runDaemonQmd([
  1061. "mcp", "--http", "--daemon", "--port", String(port),
  1062. ]);
  1063. expect(exitCode).toBe(0);
  1064. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1065. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1066. spawnedPids.push(pid);
  1067. expect(pid).not.toBe(999999999);
  1068. // Clean up
  1069. const ready = await waitForServer(port);
  1070. expect(ready).toBe(true);
  1071. process.kill(pid, "SIGTERM");
  1072. await sleep(500);
  1073. try { unlinkSync(pidPath()); } catch {}
  1074. });
  1075. });