cli.test.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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. // Collection Ignore Patterns
  672. // =============================================================================
  673. describe("collection ignore patterns", () => {
  674. let localDbPath: string;
  675. let localConfigDir: string;
  676. let ignoreTestDir: string;
  677. beforeAll(async () => {
  678. const env = await createIsolatedTestEnv("ignore-patterns");
  679. localDbPath = env.dbPath;
  680. localConfigDir = env.configDir;
  681. // Create directory structure with subdirectories to ignore
  682. ignoreTestDir = join(testDir, "ignore-fixtures");
  683. await mkdir(join(ignoreTestDir, "notes"), { recursive: true });
  684. await mkdir(join(ignoreTestDir, "sessions"), { recursive: true });
  685. await mkdir(join(ignoreTestDir, "sessions", "2026-03"), { recursive: true });
  686. await mkdir(join(ignoreTestDir, "archive"), { recursive: true });
  687. // Files that should be indexed
  688. await writeFile(join(ignoreTestDir, "readme.md"), "# Main readme\nThis should be indexed.");
  689. await writeFile(join(ignoreTestDir, "notes", "note1.md"), "# Note 1\nThis is a personal note.");
  690. // Files that should be ignored
  691. await writeFile(join(ignoreTestDir, "sessions", "session1.md"), "# Session 1\nThis session should be ignored.");
  692. await writeFile(join(ignoreTestDir, "sessions", "2026-03", "session2.md"), "# Session 2\nNested session should also be ignored.");
  693. await writeFile(join(ignoreTestDir, "archive", "old.md"), "# Old stuff\nThis archive file should be ignored.");
  694. });
  695. test("ignore patterns exclude matching files from indexing", async () => {
  696. // Write YAML config with ignore patterns
  697. await writeFile(
  698. join(localConfigDir, "index.yml"),
  699. `collections:
  700. ignoretst:
  701. path: ${ignoreTestDir}
  702. pattern: "**/*.md"
  703. ignore:
  704. - "sessions/**"
  705. - "archive/**"
  706. `
  707. );
  708. const { stdout, exitCode } = await runQmd(["update"], {
  709. cwd: ignoreTestDir,
  710. dbPath: localDbPath,
  711. configDir: localConfigDir,
  712. });
  713. expect(exitCode).toBe(0);
  714. // Should index 2 files (readme.md + notes/note1.md), not 5
  715. expect(stdout).toContain("2 new");
  716. });
  717. test("ignored files are not searchable", async () => {
  718. const { stdout, exitCode } = await runQmd(["search", "session", "-n", "10"], {
  719. cwd: ignoreTestDir,
  720. dbPath: localDbPath,
  721. configDir: localConfigDir,
  722. });
  723. // Should find no results since sessions/ was ignored
  724. if (exitCode === 0) {
  725. expect(stdout).not.toContain("session1");
  726. expect(stdout).not.toContain("session2");
  727. }
  728. });
  729. test("non-ignored files are searchable", async () => {
  730. const { stdout, exitCode } = await runQmd(["search", "personal note", "-n", "10"], {
  731. cwd: ignoreTestDir,
  732. dbPath: localDbPath,
  733. configDir: localConfigDir,
  734. });
  735. expect(exitCode).toBe(0);
  736. expect(stdout).toContain("note1");
  737. });
  738. test("status shows ignore patterns", async () => {
  739. const { stdout, exitCode } = await runQmd(["collection", "list"], {
  740. cwd: ignoreTestDir,
  741. dbPath: localDbPath,
  742. configDir: localConfigDir,
  743. });
  744. expect(exitCode).toBe(0);
  745. expect(stdout).toContain("Ignore:");
  746. expect(stdout).toContain("sessions/**");
  747. expect(stdout).toContain("archive/**");
  748. });
  749. test("collection without ignore indexes all files", async () => {
  750. // Create a second collection without ignore
  751. const env2 = await createIsolatedTestEnv("no-ignore");
  752. await writeFile(
  753. join(env2.configDir, "index.yml"),
  754. `collections:
  755. allfiles:
  756. path: ${ignoreTestDir}
  757. pattern: "**/*.md"
  758. `
  759. );
  760. const { stdout, exitCode } = await runQmd(["update"], {
  761. cwd: ignoreTestDir,
  762. dbPath: env2.dbPath,
  763. configDir: env2.configDir,
  764. });
  765. expect(exitCode).toBe(0);
  766. // Should index all 5 files
  767. expect(stdout).toContain("5 new");
  768. });
  769. });
  770. // =============================================================================
  771. // Output Format Tests - qmd:// URIs, context, and docid
  772. // =============================================================================
  773. describe("search output formats", () => {
  774. let localDbPath: string;
  775. let localConfigDir: string;
  776. const collName = "fixtures";
  777. beforeAll(async () => {
  778. const env = await createIsolatedTestEnv("output-format");
  779. localDbPath = env.dbPath;
  780. localConfigDir = env.configDir;
  781. // Add collection
  782. const { exitCode, stderr } = await runQmd(
  783. ["collection", "add", fixturesDir, "--name", collName],
  784. { dbPath: localDbPath, configDir: localConfigDir }
  785. );
  786. if (exitCode !== 0) console.error("collection add failed:", stderr);
  787. expect(exitCode).toBe(0);
  788. // Add context
  789. await runQmd(["context", "add", `qmd://${collName}/`, "Test fixtures for QMD"], { dbPath: localDbPath, configDir: localConfigDir });
  790. });
  791. test("search --json includes qmd:// path, docid, and context", async () => {
  792. const { stdout, exitCode } = await runQmd(["search", "test", "--json", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  793. expect(exitCode).toBe(0);
  794. const results = JSON.parse(stdout);
  795. expect(results.length).toBeGreaterThan(0);
  796. const result = results[0];
  797. expect(result.file).toMatch(new RegExp(`^qmd://${collName}/`));
  798. expect(result.docid).toMatch(/^#[a-f0-9]{6}$/);
  799. expect(result.context).toBe("Test fixtures for QMD");
  800. // Ensure no full filesystem paths
  801. expect(result.file).not.toMatch(/^\/Users\//);
  802. expect(result.file).not.toMatch(/^\/home\//);
  803. });
  804. test("search --files includes qmd:// path, docid, and context", async () => {
  805. const { stdout, exitCode } = await runQmd(["search", "test", "--files", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  806. expect(exitCode).toBe(0);
  807. // Format: #docid,score,qmd://collection/path,"context"
  808. expect(stdout).toMatch(new RegExp(`^#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`, "m"));
  809. expect(stdout).toContain("Test fixtures for QMD");
  810. // Ensure no full filesystem paths
  811. expect(stdout).not.toMatch(/\/Users\//);
  812. expect(stdout).not.toMatch(/\/home\//);
  813. });
  814. test("search --csv includes qmd:// path, docid, and context", async () => {
  815. const { stdout, exitCode } = await runQmd(["search", "test", "--csv", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  816. expect(exitCode).toBe(0);
  817. // Header should include context
  818. expect(stdout).toMatch(/^docid,score,file,title,context,line,snippet$/m);
  819. // Data rows should have qmd:// paths and context
  820. expect(stdout).toMatch(new RegExp(`#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`));
  821. expect(stdout).toContain("Test fixtures for QMD");
  822. // Ensure no full filesystem paths
  823. expect(stdout).not.toMatch(/\/Users\//);
  824. expect(stdout).not.toMatch(/\/home\//);
  825. });
  826. test("search --md includes docid and context", async () => {
  827. const { stdout, exitCode } = await runQmd(["search", "test", "--md", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  828. expect(exitCode).toBe(0);
  829. expect(stdout).toMatch(/\*\*docid:\*\* `#[a-f0-9]{6}`/);
  830. expect(stdout).toContain("**context:** Test fixtures for QMD");
  831. });
  832. test("search --xml includes qmd:// path, docid, and context", async () => {
  833. const { stdout, exitCode } = await runQmd(["search", "test", "--xml", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  834. expect(exitCode).toBe(0);
  835. expect(stdout).toMatch(new RegExp(`<file docid="#[a-f0-9]{6}" name="qmd://${collName}/`));
  836. expect(stdout).toContain('context="Test fixtures for QMD"');
  837. // Ensure no full filesystem paths
  838. expect(stdout).not.toMatch(/\/Users\//);
  839. expect(stdout).not.toMatch(/\/home\//);
  840. });
  841. test("search default CLI format includes qmd:// path, docid, and context", async () => {
  842. const { stdout, exitCode } = await runQmd(["search", "test", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  843. expect(exitCode).toBe(0);
  844. // First line should have qmd:// path and docid
  845. expect(stdout).toMatch(new RegExp(`^qmd://${collName}/.*#[a-f0-9]{6}`, "m"));
  846. expect(stdout).toContain("Context: Test fixtures for QMD");
  847. // Ensure no full filesystem paths
  848. expect(stdout).not.toMatch(/\/Users\//);
  849. expect(stdout).not.toMatch(/\/home\//);
  850. });
  851. });
  852. // =============================================================================
  853. // Get Command Path Normalization Tests
  854. // =============================================================================
  855. describe("get command path normalization", () => {
  856. let localDbPath: string;
  857. let localConfigDir: string;
  858. const collName = "fixtures";
  859. beforeAll(async () => {
  860. const env = await createIsolatedTestEnv("get-paths");
  861. localDbPath = env.dbPath;
  862. localConfigDir = env.configDir;
  863. const { exitCode, stderr } = await runQmd(
  864. ["collection", "add", fixturesDir, "--name", collName],
  865. { dbPath: localDbPath, configDir: localConfigDir }
  866. );
  867. if (exitCode !== 0) console.error("collection add failed:", stderr);
  868. expect(exitCode).toBe(0);
  869. });
  870. test("get with qmd://collection/path format", async () => {
  871. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  872. expect(exitCode).toBe(0);
  873. expect(stdout).toContain("Test Document 1");
  874. });
  875. test("get with collection/path format (no scheme)", async () => {
  876. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  877. expect(exitCode).toBe(0);
  878. expect(stdout).toContain("Test Document 1");
  879. });
  880. test("get with //collection/path format", async () => {
  881. const { stdout, exitCode } = await runQmd(["get", `//${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  882. expect(exitCode).toBe(0);
  883. expect(stdout).toContain("Test Document 1");
  884. });
  885. test("get with qmd:////collection/path format (extra slashes)", async () => {
  886. const { stdout, exitCode } = await runQmd(["get", `qmd:////${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  887. expect(exitCode).toBe(0);
  888. expect(stdout).toContain("Test Document 1");
  889. });
  890. test("get with path:line format", async () => {
  891. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  892. expect(exitCode).toBe(0);
  893. // Should start from line 3, not line 1
  894. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  895. });
  896. test("get with qmd://path:line format", async () => {
  897. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  898. expect(exitCode).toBe(0);
  899. // Should start from line 3, not line 1
  900. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  901. });
  902. });
  903. // =============================================================================
  904. // Status and Collection List - No Full Paths
  905. // =============================================================================
  906. describe("status and collection list hide filesystem paths", () => {
  907. let localDbPath: string;
  908. let localConfigDir: string;
  909. const collName = "fixtures";
  910. beforeAll(async () => {
  911. const env = await createIsolatedTestEnv("status-paths");
  912. localDbPath = env.dbPath;
  913. localConfigDir = env.configDir;
  914. const { exitCode, stderr } = await runQmd(
  915. ["collection", "add", fixturesDir, "--name", collName],
  916. { dbPath: localDbPath, configDir: localConfigDir }
  917. );
  918. if (exitCode !== 0) console.error("collection add failed:", stderr);
  919. expect(exitCode).toBe(0);
  920. });
  921. test("status does not show full filesystem paths", async () => {
  922. const { stdout, exitCode } = await runQmd(["status"], { dbPath: localDbPath, configDir: localConfigDir });
  923. expect(exitCode).toBe(0);
  924. // Should show qmd:// URIs
  925. expect(stdout).toContain(`qmd://${collName}/`);
  926. // Should NOT show full filesystem paths (except for the index location which is ok)
  927. const lines = stdout.split('\n').filter(l => !l.includes('Index:'));
  928. const pathLines = lines.filter(l => l.includes('/Users/') || l.includes('/home/') || l.includes('/tmp/'));
  929. expect(pathLines.length).toBe(0);
  930. });
  931. test("collection list does not show full filesystem paths", async () => {
  932. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath, configDir: localConfigDir });
  933. expect(exitCode).toBe(0);
  934. // Should show qmd:// URIs
  935. expect(stdout).toContain(`qmd://${collName}/`);
  936. // Should NOT show Path: lines with filesystem paths
  937. expect(stdout).not.toMatch(/Path:\s+\//);
  938. });
  939. });
  940. // =============================================================================
  941. // MCP HTTP Daemon Lifecycle
  942. // =============================================================================
  943. describe("mcp http daemon", () => {
  944. let daemonTestDir: string;
  945. let daemonCacheDir: string; // XDG_CACHE_HOME value (the qmd/ subdir is created automatically)
  946. let daemonDbPath: string;
  947. let daemonConfigDir: string;
  948. // Track spawned PIDs for cleanup
  949. const spawnedPids: number[] = [];
  950. /** Get path to PID file inside the test cache dir */
  951. function pidPath(): string {
  952. return join(daemonCacheDir, "qmd", "mcp.pid");
  953. }
  954. /** Run qmd with test-isolated env (cache, db, config) */
  955. async function runDaemonQmd(
  956. args: string[],
  957. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  958. return runQmd(args, {
  959. dbPath: daemonDbPath,
  960. configDir: daemonConfigDir,
  961. env: { XDG_CACHE_HOME: daemonCacheDir },
  962. });
  963. }
  964. /** Spawn a foreground HTTP server (non-blocking) and return the process */
  965. function spawnHttpServer(port: number): import("child_process").ChildProcess {
  966. const proc = spawn(tsxBin, [qmdScript, "mcp", "--http", "--port", String(port)], {
  967. cwd: fixturesDir,
  968. env: {
  969. ...process.env,
  970. INDEX_PATH: daemonDbPath,
  971. QMD_CONFIG_DIR: daemonConfigDir,
  972. },
  973. stdio: ["ignore", "pipe", "pipe"],
  974. });
  975. if (proc.pid) spawnedPids.push(proc.pid);
  976. return proc;
  977. }
  978. /** Wait for HTTP server to become ready */
  979. async function waitForServer(port: number, timeoutMs = 5000): Promise<boolean> {
  980. const deadline = Date.now() + timeoutMs;
  981. while (Date.now() < deadline) {
  982. try {
  983. const res = await fetch(`http://localhost:${port}/health`);
  984. if (res.ok) return true;
  985. } catch { /* not ready yet */ }
  986. await sleep(200);
  987. }
  988. return false;
  989. }
  990. /** Pick a random high port unlikely to conflict */
  991. function randomPort(): number {
  992. return 10000 + Math.floor(Math.random() * 50000);
  993. }
  994. beforeAll(async () => {
  995. daemonTestDir = await mkdtemp(join(tmpdir(), "qmd-daemon-test-"));
  996. daemonCacheDir = join(daemonTestDir, "cache");
  997. daemonDbPath = join(daemonTestDir, "test.sqlite");
  998. daemonConfigDir = join(daemonTestDir, "config");
  999. await mkdir(join(daemonCacheDir, "qmd"), { recursive: true });
  1000. await mkdir(daemonConfigDir, { recursive: true });
  1001. await writeFile(join(daemonConfigDir, "index.yml"), "collections: {}\n");
  1002. });
  1003. afterAll(async () => {
  1004. // Kill any leftover spawned processes
  1005. for (const pid of spawnedPids) {
  1006. try { process.kill(pid, "SIGTERM"); } catch { /* already dead */ }
  1007. }
  1008. // Also clean up via PID file if present
  1009. try {
  1010. const pf = pidPath();
  1011. if (existsSync(pf)) {
  1012. const pid = parseInt(readFileSync(pf, "utf-8").trim());
  1013. try { process.kill(pid, "SIGTERM"); } catch {}
  1014. unlinkSync(pf);
  1015. }
  1016. } catch {}
  1017. await rm(daemonTestDir, { recursive: true, force: true });
  1018. });
  1019. // -------------------------------------------------------------------------
  1020. // Foreground HTTP
  1021. // -------------------------------------------------------------------------
  1022. test("foreground HTTP server starts and responds to health check", async () => {
  1023. const port = randomPort();
  1024. const proc = spawnHttpServer(port);
  1025. try {
  1026. const ready = await waitForServer(port);
  1027. expect(ready).toBe(true);
  1028. const res = await fetch(`http://localhost:${port}/health`);
  1029. expect(res.status).toBe(200);
  1030. const body = await res.json();
  1031. expect(body.status).toBe("ok");
  1032. } finally {
  1033. proc.kill("SIGTERM");
  1034. await new Promise(r => proc.on("close", r));
  1035. }
  1036. });
  1037. // -------------------------------------------------------------------------
  1038. // Daemon lifecycle
  1039. // -------------------------------------------------------------------------
  1040. test("--daemon writes PID file and starts server", async () => {
  1041. const port = randomPort();
  1042. const { stdout, exitCode } = await runDaemonQmd([
  1043. "mcp", "--http", "--daemon", "--port", String(port),
  1044. ]);
  1045. expect(exitCode).toBe(0);
  1046. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1047. // PID file should exist
  1048. expect(existsSync(pidPath())).toBe(true);
  1049. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1050. spawnedPids.push(pid);
  1051. // Server should be reachable
  1052. const ready = await waitForServer(port);
  1053. expect(ready).toBe(true);
  1054. // Clean up
  1055. process.kill(pid, "SIGTERM");
  1056. await sleep(500);
  1057. try { unlinkSync(pidPath()); } catch {}
  1058. });
  1059. test("stop kills daemon and removes PID file", async () => {
  1060. const port = randomPort();
  1061. // Start daemon
  1062. const { exitCode: startCode } = await runDaemonQmd([
  1063. "mcp", "--http", "--daemon", "--port", String(port),
  1064. ]);
  1065. expect(startCode).toBe(0);
  1066. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1067. spawnedPids.push(pid);
  1068. await waitForServer(port);
  1069. // Stop it
  1070. const { stdout: stopOut, exitCode: stopCode } = await runDaemonQmd(["mcp", "stop"]);
  1071. expect(stopCode).toBe(0);
  1072. expect(stopOut).toContain("Stopped");
  1073. // PID file should be gone
  1074. expect(existsSync(pidPath())).toBe(false);
  1075. // Process should be dead
  1076. await sleep(500);
  1077. expect(() => process.kill(pid, 0)).toThrow();
  1078. });
  1079. test("stop handles dead PID gracefully (cleans stale file)", async () => {
  1080. // Write a PID file pointing to a dead process
  1081. writeFileSync(pidPath(), "999999999");
  1082. const { stdout, exitCode } = await runDaemonQmd(["mcp", "stop"]);
  1083. expect(exitCode).toBe(0);
  1084. expect(stdout).toContain("stale");
  1085. // PID file should be cleaned up
  1086. expect(existsSync(pidPath())).toBe(false);
  1087. });
  1088. test("--daemon rejects if already running", async () => {
  1089. const port = randomPort();
  1090. // Start first daemon
  1091. const { exitCode: firstCode } = await runDaemonQmd([
  1092. "mcp", "--http", "--daemon", "--port", String(port),
  1093. ]);
  1094. expect(firstCode).toBe(0);
  1095. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1096. spawnedPids.push(pid);
  1097. await waitForServer(port);
  1098. // Try to start second daemon — should fail
  1099. const { stderr, exitCode } = await runDaemonQmd([
  1100. "mcp", "--http", "--daemon", "--port", String(port + 1),
  1101. ]);
  1102. expect(exitCode).toBe(1);
  1103. expect(stderr).toContain("Already running");
  1104. // Clean up first daemon
  1105. process.kill(pid, "SIGTERM");
  1106. await sleep(500);
  1107. try { unlinkSync(pidPath()); } catch {}
  1108. });
  1109. test("--daemon cleans stale PID file and starts fresh", async () => {
  1110. // Write a stale PID file
  1111. writeFileSync(pidPath(), "999999999");
  1112. const port = randomPort();
  1113. const { exitCode, stdout } = await runDaemonQmd([
  1114. "mcp", "--http", "--daemon", "--port", String(port),
  1115. ]);
  1116. expect(exitCode).toBe(0);
  1117. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1118. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1119. spawnedPids.push(pid);
  1120. expect(pid).not.toBe(999999999);
  1121. // Clean up
  1122. const ready = await waitForServer(port);
  1123. expect(ready).toBe(true);
  1124. process.kill(pid, "SIGTERM");
  1125. await sleep(500);
  1126. try { unlinkSync(pidPath()); } catch {}
  1127. });
  1128. });