cli.test.ts 40 KB

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