cli.test.ts 42 KB

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