cli.test.ts 53 KB

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