cli.test.ts 45 KB

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