cli.test.ts 41 KB

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