cli.test.ts 40 KB

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