cli.test.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  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, termLink } 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. // i-ofojj7dy — collection-filter ergonomics for embed
  218. test("embed <unknown-collection> exits non-zero with available list", async () => {
  219. const { dbPath, configDir } = await createIsolatedTestEnv("embed-unknown");
  220. const aDir = join(testDir, `embed-unknown-a-${Date.now()}`);
  221. await mkdir(aDir, { recursive: true });
  222. await writeFile(join(aDir, "e.md"), "# E");
  223. expect((await runQmd(["collection", "add", aDir, "--name", "embed-real"], { dbPath, configDir })).exitCode).toBe(0);
  224. const { stderr, exitCode } = await runQmd(["embed", "embed-ghost"], { dbPath, configDir });
  225. expect(exitCode).toBe(1);
  226. expect(stderr).toContain("Collection not found");
  227. expect(stderr).toContain("embed-ghost");
  228. expect(stderr).toContain("embed-real");
  229. });
  230. test("embed <collection> --force rejects the conflict", async () => {
  231. const { dbPath, configDir } = await createIsolatedTestEnv("embed-force-conflict");
  232. const aDir = join(testDir, `embed-force-conflict-a-${Date.now()}`);
  233. await mkdir(aDir, { recursive: true });
  234. await writeFile(join(aDir, "f.md"), "# F");
  235. expect((await runQmd(["collection", "add", aDir, "--name", "ef-a"], { dbPath, configDir })).exitCode).toBe(0);
  236. const { stderr, exitCode } = await runQmd(["embed", "ef-a", "--force"], { dbPath, configDir });
  237. expect(exitCode).toBe(1);
  238. expect(stderr).toContain("--force cannot be combined with a positional collection name");
  239. });
  240. test("embed --all + positional name is a conflict error", async () => {
  241. const { dbPath, configDir } = await createIsolatedTestEnv("embed-all-conflict");
  242. const aDir = join(testDir, `embed-all-conflict-a-${Date.now()}`);
  243. await mkdir(aDir, { recursive: true });
  244. await writeFile(join(aDir, "g.md"), "# G");
  245. expect((await runQmd(["collection", "add", aDir, "--name", "eac-a"], { dbPath, configDir })).exitCode).toBe(0);
  246. const { stderr, exitCode } = await runQmd(["embed", "eac-a", "--all"], { dbPath, configDir });
  247. expect(exitCode).toBe(1);
  248. expect(stderr).toContain("Conflicting arguments");
  249. });
  250. });
  251. describe("CLI Skill Commands", () => {
  252. test("shows embedded skill with --skill alias", async () => {
  253. const { stdout, exitCode } = await runQmd(["--skill"]);
  254. expect(exitCode).toBe(0);
  255. expect(stdout).toContain("QMD Skill (embedded)");
  256. expect(stdout).toContain("name: qmd");
  257. expect(stdout).toContain("allowed-tools: Bash(qmd:*), mcp__qmd__*");
  258. });
  259. test("shows skill help with -h", async () => {
  260. const { stdout, exitCode } = await runQmd(["skill", "-h"]);
  261. expect(exitCode).toBe(0);
  262. expect(stdout).toContain("Usage: qmd skill <show|install> [options]");
  263. expect(stdout).toContain("install");
  264. expect(stdout).toContain("--global");
  265. });
  266. test("installs the skill into the current project", async () => {
  267. const projectDir = join(testDir, "skill-project");
  268. await mkdir(projectDir, { recursive: true });
  269. const { stdout, exitCode } = await runQmd(["skill", "install"], { cwd: projectDir });
  270. expect(exitCode).toBe(0);
  271. const skillDir = join(projectDir, ".agents", "skills", "qmd");
  272. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  273. expect(readFileSync(join(skillDir, "references", "mcp-setup.md"), "utf-8")).toContain("Claude Code");
  274. expect(existsSync(join(projectDir, ".claude", "skills", "qmd"))).toBe(false);
  275. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  276. expect(stdout).toContain("Tip: create a Claude symlink manually");
  277. });
  278. test("installs globally and creates the Claude symlink with --yes", async () => {
  279. const fakeHome = join(testDir, "skill-home");
  280. await mkdir(fakeHome, { recursive: true });
  281. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  282. env: { HOME: fakeHome },
  283. });
  284. expect(exitCode).toBe(0);
  285. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  286. const claudeLink = join(fakeHome, ".claude", "skills", "qmd");
  287. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  288. expect(lstatSync(claudeLink).isSymbolicLink()).toBe(true);
  289. expect(readFileSync(join(claudeLink, "SKILL.md"), "utf-8")).toContain("name: qmd");
  290. expect(stdout).toContain(`✓ Installed QMD skill to ${skillDir}`);
  291. expect(stdout).toContain(`✓ Linked Claude skill at ${claudeLink}`);
  292. });
  293. test("skips Claude qmd symlink when .claude/skills already points to .agents/skills", async () => {
  294. const fakeHome = join(testDir, "skill-home-shared");
  295. await mkdir(join(fakeHome, ".agents"), { recursive: true });
  296. await mkdir(join(fakeHome, ".claude"), { recursive: true });
  297. symlinkSync(join(fakeHome, ".agents", "skills"), join(fakeHome, ".claude", "skills"), "dir");
  298. const { stdout, exitCode } = await runQmd(["skill", "install", "--global", "--yes"], {
  299. env: { HOME: fakeHome },
  300. });
  301. expect(exitCode).toBe(0);
  302. const skillDir = join(fakeHome, ".agents", "skills", "qmd");
  303. expect(lstatSync(skillDir).isSymbolicLink()).toBe(false);
  304. expect(readFileSync(join(skillDir, "SKILL.md"), "utf-8")).toContain("name: qmd");
  305. expect(stdout).toContain(`✓ Claude already sees the skill via ${join(fakeHome, ".claude", "skills")}`);
  306. });
  307. test("refuses to overwrite an existing install without --force", async () => {
  308. const projectDir = join(testDir, "skill-project-force");
  309. await mkdir(projectDir, { recursive: true });
  310. const first = await runQmd(["skill", "install"], { cwd: projectDir });
  311. expect(first.exitCode).toBe(0);
  312. const second = await runQmd(["skill", "install"], { cwd: projectDir });
  313. expect(second.exitCode).toBe(1);
  314. expect(second.stderr).toContain("Skill already exists");
  315. expect(second.stderr).toContain("--force");
  316. });
  317. });
  318. describe("CLI Add Command", () => {
  319. test("adds files from current directory", async () => {
  320. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  321. expect(exitCode).toBe(0);
  322. expect(stdout).toContain("Collection:");
  323. expect(stdout).toContain("Indexed:");
  324. });
  325. test("adds files with custom glob pattern", async () => {
  326. const { stdout, stderr, exitCode } = await runQmd(["collection", "add", ".", "--mask", "notes/*.md"]);
  327. if (exitCode !== 0) {
  328. console.error("Command failed:", stderr);
  329. }
  330. expect(exitCode).toBe(0);
  331. expect(stdout).toContain("Collection:");
  332. // Should find meeting.md and ideas.md in notes/
  333. expect(stdout).toContain("notes/*.md");
  334. });
  335. test("can recreate collection with remove and add", async () => {
  336. // First add
  337. await runQmd(["collection", "add", "."]);
  338. // Remove it
  339. await runQmd(["collection", "remove", "fixtures"]);
  340. // Re-add
  341. const { stdout, exitCode } = await runQmd(["collection", "add", "."]);
  342. expect(exitCode).toBe(0);
  343. expect(stdout).toContain("Collection 'fixtures' created successfully");
  344. });
  345. });
  346. describe("CLI Status Command", () => {
  347. beforeEach(async () => {
  348. // Ensure we have indexed files
  349. await runQmd(["collection", "add", "."]);
  350. });
  351. test("shows index status", async () => {
  352. const { stdout, exitCode } = await runQmd(["status"]);
  353. expect(exitCode).toBe(0);
  354. // Should show collection info
  355. expect(stdout).toContain("Collection");
  356. });
  357. });
  358. describe("CLI Search Command", () => {
  359. beforeEach(async () => {
  360. // Ensure we have indexed files
  361. await runQmd(["collection", "add", "."]);
  362. });
  363. test("searches for documents with BM25", async () => {
  364. const { stdout, exitCode } = await runQmd(["search", "meeting"]);
  365. expect(exitCode).toBe(0);
  366. // Should find meeting.md
  367. expect(stdout.toLowerCase()).toContain("meeting");
  368. });
  369. test("searches with limit option", async () => {
  370. const { stdout, exitCode } = await runQmd(["search", "-n", "1", "test"]);
  371. expect(exitCode).toBe(0);
  372. });
  373. test("searches with all results option", async () => {
  374. const { stdout, exitCode } = await runQmd(["search", "--all", "the"]);
  375. expect(exitCode).toBe(0);
  376. });
  377. test("returns no results message for non-matching query", async () => {
  378. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123"]);
  379. expect(exitCode).toBe(0);
  380. expect(stdout).toContain("No results");
  381. });
  382. test("returns empty JSON array for non-matching query with --json", async () => {
  383. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--json"]);
  384. expect(exitCode).toBe(0);
  385. expect(JSON.parse(stdout)).toEqual([]);
  386. });
  387. test("returns CSV header only for non-matching query with --csv", async () => {
  388. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--csv"]);
  389. expect(exitCode).toBe(0);
  390. expect(stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  391. });
  392. test("returns empty XML container for non-matching query with --xml", async () => {
  393. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--xml"]);
  394. expect(exitCode).toBe(0);
  395. expect(stdout.trim()).toBe("<results></results>");
  396. });
  397. test("returns empty output for non-matching query with --md", async () => {
  398. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--md"]);
  399. expect(exitCode).toBe(0);
  400. expect(stdout.trim()).toBe("");
  401. });
  402. test("returns empty output for non-matching query with --files", async () => {
  403. const { stdout, exitCode } = await runQmd(["search", "xyznonexistent123", "--files"]);
  404. expect(exitCode).toBe(0);
  405. expect(stdout.trim()).toBe("");
  406. });
  407. test("returns min-score threshold message for default CLI output", async () => {
  408. const { stdout, exitCode } = await runQmd(["search", "test", "--min-score", "2"]);
  409. expect(exitCode).toBe(0);
  410. expect(stdout).toContain("No results found above minimum score threshold.");
  411. });
  412. test("returns format-safe empty output when --min-score filters all results", async () => {
  413. const json = await runQmd(["search", "test", "--json", "--min-score", "2"]);
  414. expect(json.exitCode).toBe(0);
  415. expect(JSON.parse(json.stdout)).toEqual([]);
  416. const csv = await runQmd(["search", "test", "--csv", "--min-score", "2"]);
  417. expect(csv.exitCode).toBe(0);
  418. expect(csv.stdout.trim()).toBe("docid,score,file,title,context,line,snippet");
  419. const xml = await runQmd(["search", "test", "--xml", "--min-score", "2"]);
  420. expect(xml.exitCode).toBe(0);
  421. expect(xml.stdout.trim()).toBe("<results></results>");
  422. const md = await runQmd(["search", "test", "--md", "--min-score", "2"]);
  423. expect(md.exitCode).toBe(0);
  424. expect(md.stdout.trim()).toBe("");
  425. const files = await runQmd(["search", "test", "--files", "--min-score", "2"]);
  426. expect(files.exitCode).toBe(0);
  427. expect(files.stdout.trim()).toBe("");
  428. });
  429. test("requires query argument", async () => {
  430. const { stdout, stderr, exitCode } = await runQmd(["search"]);
  431. expect(exitCode).toBe(1);
  432. // Error message goes to stderr
  433. expect(stderr).toContain("Usage:");
  434. });
  435. });
  436. describe("CLI Get Command", () => {
  437. beforeEach(async () => {
  438. // Ensure we have indexed files
  439. await runQmd(["collection", "add", "."]);
  440. });
  441. test("retrieves document content by path", async () => {
  442. const { stdout, exitCode } = await runQmd(["get", "README.md"]);
  443. expect(exitCode).toBe(0);
  444. expect(stdout).toContain("Test Project");
  445. });
  446. test("retrieves document from subdirectory", async () => {
  447. const { stdout, exitCode } = await runQmd(["get", "notes/meeting.md"]);
  448. expect(exitCode).toBe(0);
  449. expect(stdout).toContain("Team Meeting");
  450. });
  451. test("handles non-existent file", async () => {
  452. const { stdout, exitCode } = await runQmd(["get", "nonexistent.md"]);
  453. // Should indicate file not found
  454. expect(exitCode).toBe(1);
  455. });
  456. });
  457. describe("CLI Multi-Get Command", () => {
  458. let localDbPath: string;
  459. beforeEach(async () => {
  460. // Use fresh database for each test
  461. localDbPath = getFreshDbPath();
  462. // Ensure we have indexed files
  463. const addResult = await runQmd(["collection", "add", ".", "--name", "fixtures"], { dbPath: localDbPath });
  464. if (addResult.exitCode !== 0) {
  465. throw new Error(`Failed to add collection: ${addResult.stderr}`);
  466. }
  467. });
  468. test("retrieves multiple documents by pattern", async () => {
  469. // Test glob pattern matching
  470. const { stdout, stderr, exitCode } = await runQmd(["multi-get", "notes/*.md"], { dbPath: localDbPath });
  471. expect(exitCode).toBe(0);
  472. // Should contain content from both notes files
  473. expect(stdout).toContain("Meeting");
  474. expect(stdout).toContain("Ideas");
  475. });
  476. test("retrieves documents by comma-separated paths", async () => {
  477. const { stdout, exitCode } = await runQmd([
  478. "multi-get",
  479. "README.md,notes/meeting.md",
  480. ], { dbPath: localDbPath });
  481. expect(exitCode).toBe(0);
  482. expect(stdout).toContain("Test Project");
  483. expect(stdout).toContain("Team Meeting");
  484. });
  485. });
  486. describe("CLI Update Command", () => {
  487. let localDbPath: string;
  488. beforeEach(async () => {
  489. // Use a fresh database for this test suite
  490. localDbPath = getFreshDbPath();
  491. // Ensure we have indexed files
  492. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  493. });
  494. test("updates all collections", async () => {
  495. const { stdout, exitCode } = await runQmd(["update"], { dbPath: localDbPath });
  496. expect(exitCode).toBe(0);
  497. expect(stdout).toContain("Updating");
  498. });
  499. // i-ofojj7dy — collection-filter ergonomics
  500. test("update <collection> filters to a single collection", async () => {
  501. const { dbPath, configDir } = await createIsolatedTestEnv("update-filter");
  502. // Two collections in one config; each gets its own fixture dir
  503. const aDir = join(testDir, `update-filter-a-${Date.now()}`);
  504. const bDir = join(testDir, `update-filter-b-${Date.now()}`);
  505. await mkdir(aDir, { recursive: true });
  506. await mkdir(bDir, { recursive: true });
  507. await writeFile(join(aDir, "x.md"), "# X");
  508. await writeFile(join(bDir, "y.md"), "# Y");
  509. expect((await runQmd(["collection", "add", aDir, "--name", "filter-a"], { dbPath, configDir })).exitCode).toBe(0);
  510. expect((await runQmd(["collection", "add", bDir, "--name", "filter-b"], { dbPath, configDir })).exitCode).toBe(0);
  511. const { stdout, exitCode } = await runQmd(["update", "filter-a"], { dbPath, configDir });
  512. expect(exitCode).toBe(0);
  513. expect(stdout).toContain("Updating 1 collection(s)");
  514. expect(stdout).toContain("filter-a");
  515. expect(stdout).not.toContain("filter-b");
  516. });
  517. test("update <unknown-collection> exits non-zero with available list", async () => {
  518. const { dbPath, configDir } = await createIsolatedTestEnv("update-unknown");
  519. const aDir = join(testDir, `update-unknown-a-${Date.now()}`);
  520. await mkdir(aDir, { recursive: true });
  521. await writeFile(join(aDir, "z.md"), "# Z");
  522. expect((await runQmd(["collection", "add", aDir, "--name", "real-name"], { dbPath, configDir })).exitCode).toBe(0);
  523. const { stderr, exitCode } = await runQmd(["update", "ghost-collection"], { dbPath, configDir });
  524. expect(exitCode).toBe(1);
  525. expect(stderr).toContain("Collection not found");
  526. expect(stderr).toContain("ghost-collection");
  527. expect(stderr).toContain("real-name");
  528. });
  529. test("update --all behaves like update with no args (full-fleet)", async () => {
  530. const { dbPath, configDir } = await createIsolatedTestEnv("update-all");
  531. const aDir = join(testDir, `update-all-a-${Date.now()}`);
  532. const bDir = join(testDir, `update-all-b-${Date.now()}`);
  533. await mkdir(aDir, { recursive: true });
  534. await mkdir(bDir, { recursive: true });
  535. await writeFile(join(aDir, "u.md"), "# U");
  536. await writeFile(join(bDir, "v.md"), "# V");
  537. expect((await runQmd(["collection", "add", aDir, "--name", "all-a"], { dbPath, configDir })).exitCode).toBe(0);
  538. expect((await runQmd(["collection", "add", bDir, "--name", "all-b"], { dbPath, configDir })).exitCode).toBe(0);
  539. const { stdout, exitCode } = await runQmd(["update", "--all"], { dbPath, configDir });
  540. expect(exitCode).toBe(0);
  541. expect(stdout).toContain("Updating 2 collection(s)");
  542. expect(stdout).toContain("all-a");
  543. expect(stdout).toContain("all-b");
  544. });
  545. test("update --all + positional name is a conflict error", async () => {
  546. const { dbPath, configDir } = await createIsolatedTestEnv("update-conflict");
  547. const aDir = join(testDir, `update-conflict-a-${Date.now()}`);
  548. await mkdir(aDir, { recursive: true });
  549. await writeFile(join(aDir, "c.md"), "# C");
  550. expect((await runQmd(["collection", "add", aDir, "--name", "conflict-a"], { dbPath, configDir })).exitCode).toBe(0);
  551. const { stderr, exitCode } = await runQmd(["update", "conflict-a", "--all"], { dbPath, configDir });
  552. expect(exitCode).toBe(1);
  553. expect(stderr).toContain("Conflicting arguments");
  554. });
  555. test("deactivates stale docs when collection has zero matching files", async () => {
  556. const { dbPath, configDir } = await createIsolatedTestEnv("update-empty");
  557. const collectionDir = join(testDir, `update-empty-${Date.now()}`);
  558. await mkdir(collectionDir, { recursive: true });
  559. const docPath = join(collectionDir, "only.md");
  560. const token = `stale-proof-${Date.now()}`;
  561. await writeFile(
  562. docPath,
  563. `---
  564. date: 2026-03-06
  565. ---
  566. # Empty Collection Deactivation
  567. ${token}
  568. `
  569. );
  570. const add = await runQmd(
  571. ["collection", "add", collectionDir, "--name", "empty-check"],
  572. { dbPath, configDir }
  573. );
  574. expect(add.exitCode).toBe(0);
  575. const before = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  576. expect(before.exitCode).toBe(0);
  577. expect(before.stdout).toContain(token);
  578. unlinkSync(docPath);
  579. const update = await runQmd(["update"], { dbPath, configDir });
  580. expect(update.exitCode).toBe(0);
  581. expect(update.stdout).toContain("0 new, 0 updated, 0 unchanged, 1 removed");
  582. const after = await runQmd(["get", "qmd://empty-check/only.md"], { dbPath, configDir });
  583. expect(after.exitCode).toBe(1);
  584. });
  585. });
  586. describe("CLI Add-Context Command", () => {
  587. let localDbPath: string;
  588. let localConfigDir: string;
  589. const collName = "fixtures";
  590. beforeAll(async () => {
  591. const env = await createIsolatedTestEnv("context-cmd");
  592. localDbPath = env.dbPath;
  593. localConfigDir = env.configDir;
  594. // Add collection with known name
  595. const { exitCode, stderr } = await runQmd(
  596. ["collection", "add", fixturesDir, "--name", collName],
  597. { dbPath: localDbPath, configDir: localConfigDir }
  598. );
  599. if (exitCode !== 0) console.error("collection add failed:", stderr);
  600. expect(exitCode).toBe(0);
  601. });
  602. test("adds context to a path", async () => {
  603. // Add context to the collection root using virtual path
  604. const { stdout, exitCode } = await runQmd([
  605. "context",
  606. "add",
  607. `qmd://${collName}/`,
  608. "Personal notes and meeting logs",
  609. ], { dbPath: localDbPath, configDir: localConfigDir });
  610. expect(exitCode).toBe(0);
  611. expect(stdout).toContain("✓ Added context");
  612. });
  613. test("requires path and text arguments", async () => {
  614. const { stderr, exitCode } = await runQmd(["context", "add"], { dbPath: localDbPath, configDir: localConfigDir });
  615. expect(exitCode).toBe(1);
  616. // Error message goes to stderr
  617. expect(stderr).toContain("Usage:");
  618. });
  619. });
  620. describe("CLI Cleanup Command", () => {
  621. beforeEach(async () => {
  622. // Ensure we have indexed files
  623. await runQmd(["collection", "add", "."]);
  624. });
  625. test("cleans up orphaned entries", async () => {
  626. const { stdout, exitCode } = await runQmd(["cleanup"]);
  627. expect(exitCode).toBe(0);
  628. });
  629. test("cleanup --no-vacuum prunes without vacuuming", async () => {
  630. const { stdout, exitCode } = await runQmd(["cleanup", "--no-vacuum"]);
  631. expect(exitCode).toBe(0);
  632. expect(stdout).toContain("Skipped VACUUM");
  633. expect(stdout).not.toContain("Database vacuumed");
  634. });
  635. });
  636. describe("CLI Error Handling", () => {
  637. test("handles unknown command", async () => {
  638. const { stderr, exitCode } = await runQmd(["unknowncommand"]);
  639. expect(exitCode).toBe(1);
  640. // Should indicate unknown command
  641. expect(stderr).toContain("Unknown command");
  642. });
  643. test("uses INDEX_PATH environment variable", async () => {
  644. // Verify the test DB path is being used by creating a separate index
  645. const customDbPath = join(testDir, "custom.sqlite");
  646. const { exitCode } = await runQmd(["collection", "add", "."], {
  647. env: { INDEX_PATH: customDbPath },
  648. });
  649. expect(exitCode).toBe(0);
  650. // The custom database should exist
  651. expect(existsSync(customDbPath)).toBe(true);
  652. });
  653. });
  654. describe("CLI Output Formats", () => {
  655. beforeEach(async () => {
  656. await runQmd(["collection", "add", "."]);
  657. });
  658. test("search with --json flag outputs JSON", async () => {
  659. const { stdout, exitCode } = await runQmd(["search", "--json", "test"]);
  660. expect(exitCode).toBe(0);
  661. // Should be valid JSON
  662. const parsed = JSON.parse(stdout);
  663. expect(Array.isArray(parsed)).toBe(true);
  664. });
  665. test("search with --files flag outputs file paths", async () => {
  666. const { stdout, exitCode } = await runQmd(["search", "--files", "meeting"]);
  667. expect(exitCode).toBe(0);
  668. expect(stdout).toContain(".md");
  669. });
  670. test("search output includes snippets by default", async () => {
  671. const { stdout, exitCode } = await runQmd(["search", "API"]);
  672. expect(exitCode).toBe(0);
  673. // If results found, should have snippet content
  674. if (!stdout.includes("No results")) {
  675. expect(stdout.toLowerCase()).toContain("api");
  676. }
  677. });
  678. });
  679. describe("CLI Search with Collection Filter", () => {
  680. let localDbPath: string;
  681. beforeEach(async () => {
  682. // Use a fresh database for this test suite
  683. localDbPath = getFreshDbPath();
  684. // Create multiple collections with explicit names
  685. await runQmd(["collection", "add", ".", "--name", "notes", "--mask", "notes/*.md"], { dbPath: localDbPath });
  686. await runQmd(["collection", "add", ".", "--name", "docs", "--mask", "docs/*.md"], { dbPath: localDbPath });
  687. });
  688. test("filters search by collection name", async () => {
  689. const { stdout, stderr, exitCode } = await runQmd([
  690. "search",
  691. "-c",
  692. "notes",
  693. "meeting",
  694. ], { dbPath: localDbPath });
  695. if (exitCode !== 0) {
  696. console.log("Collection filter search failed:");
  697. console.log("stdout:", stdout);
  698. console.log("stderr:", stderr);
  699. }
  700. expect(exitCode).toBe(0);
  701. });
  702. });
  703. describe("CLI Context Management", () => {
  704. let localDbPath: string;
  705. beforeEach(async () => {
  706. // Use a fresh database for this test suite
  707. localDbPath = getFreshDbPath();
  708. // Index some files first
  709. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  710. });
  711. test("add global context with /", async () => {
  712. const { stdout, exitCode } = await runQmd([
  713. "context",
  714. "add",
  715. "/",
  716. "Global system context",
  717. ], { dbPath: localDbPath });
  718. expect(exitCode).toBe(0);
  719. expect(stdout).toContain("✓ Set global context");
  720. expect(stdout).toContain("Global system context");
  721. });
  722. test("list contexts", async () => {
  723. // Add a global context first
  724. await runQmd([
  725. "context",
  726. "add",
  727. "/",
  728. "Test context",
  729. ], { dbPath: localDbPath });
  730. const { stdout, exitCode } = await runQmd([
  731. "context",
  732. "list",
  733. ], { dbPath: localDbPath });
  734. expect(exitCode).toBe(0);
  735. expect(stdout).toContain("Configured Contexts");
  736. expect(stdout).toContain("Test context");
  737. });
  738. test("add context to virtual path", async () => {
  739. // Collection name should be "fixtures" (basename of the fixtures directory)
  740. const { stdout, exitCode } = await runQmd([
  741. "context",
  742. "add",
  743. "qmd://fixtures/notes",
  744. "Context for notes subdirectory",
  745. ], { dbPath: localDbPath });
  746. expect(exitCode).toBe(0);
  747. expect(stdout).toContain("✓ Added context for: qmd://fixtures/notes");
  748. });
  749. test("remove global context", async () => {
  750. // Add a global context first
  751. await runQmd([
  752. "context",
  753. "add",
  754. "/",
  755. "Global context to remove",
  756. ], { dbPath: localDbPath });
  757. const { stdout, exitCode } = await runQmd([
  758. "context",
  759. "rm",
  760. "/",
  761. ], { dbPath: localDbPath });
  762. expect(exitCode).toBe(0);
  763. expect(stdout).toContain("✓ Removed");
  764. });
  765. test("remove virtual path context", async () => {
  766. // Add a context first
  767. await runQmd([
  768. "context",
  769. "add",
  770. "qmd://fixtures/notes",
  771. "Context to remove",
  772. ], { dbPath: localDbPath });
  773. const { stdout, exitCode } = await runQmd([
  774. "context",
  775. "rm",
  776. "qmd://fixtures/notes",
  777. ], { dbPath: localDbPath });
  778. expect(exitCode).toBe(0);
  779. expect(stdout).toContain("✓ Removed context for: qmd://fixtures/notes");
  780. });
  781. test("fails to remove non-existent context", async () => {
  782. const { stdout, stderr, exitCode } = await runQmd([
  783. "context",
  784. "rm",
  785. "qmd://nonexistent/path",
  786. ], { dbPath: localDbPath });
  787. expect(exitCode).toBe(1);
  788. expect(stderr || stdout).toContain("not found");
  789. });
  790. });
  791. describe("CLI ls Command", () => {
  792. let localDbPath: string;
  793. beforeEach(async () => {
  794. // Use a fresh database for this test suite
  795. localDbPath = getFreshDbPath();
  796. // Index some files first
  797. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  798. });
  799. test("lists all collections", async () => {
  800. const { stdout, exitCode } = await runQmd(["ls"], { dbPath: localDbPath });
  801. expect(exitCode).toBe(0);
  802. expect(stdout).toContain("Collections:");
  803. expect(stdout).toContain("qmd://fixtures/");
  804. });
  805. test("lists files in a collection", async () => {
  806. const { stdout, exitCode } = await runQmd(["ls", "fixtures"], { dbPath: localDbPath });
  807. expect(exitCode).toBe(0);
  808. // handelize converts to lowercase
  809. expect(stdout).toContain("qmd://fixtures/readme.md");
  810. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  811. });
  812. test("lists files with path prefix", async () => {
  813. const { stdout, exitCode } = await runQmd(["ls", "fixtures/notes"], { dbPath: localDbPath });
  814. expect(exitCode).toBe(0);
  815. expect(stdout).toContain("qmd://fixtures/notes/meeting.md");
  816. expect(stdout).toContain("qmd://fixtures/notes/ideas.md");
  817. // Should not include files outside the prefix (handelize converts to lowercase)
  818. expect(stdout).not.toContain("qmd://fixtures/readme.md");
  819. });
  820. test("lists files with virtual path", async () => {
  821. const { stdout, exitCode } = await runQmd(["ls", "qmd://fixtures/docs"], { dbPath: localDbPath });
  822. expect(exitCode).toBe(0);
  823. expect(stdout).toContain("qmd://fixtures/docs/api.md");
  824. });
  825. test("handles non-existent collection", async () => {
  826. const { stderr, exitCode } = await runQmd(["ls", "nonexistent"], { dbPath: localDbPath });
  827. expect(exitCode).toBe(1);
  828. expect(stderr).toContain("Collection not found");
  829. });
  830. });
  831. describe("CLI Collection Commands", () => {
  832. let localDbPath: string;
  833. beforeEach(async () => {
  834. // Use a fresh database for this test suite
  835. localDbPath = getFreshDbPath();
  836. // Index some files first to create a collection
  837. await runQmd(["collection", "add", "."], { dbPath: localDbPath });
  838. });
  839. test("lists collections", async () => {
  840. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  841. expect(exitCode).toBe(0);
  842. expect(stdout).toContain("Collections");
  843. expect(stdout).toContain("fixtures");
  844. expect(stdout).toContain("qmd://fixtures/");
  845. expect(stdout).toContain("Pattern:");
  846. expect(stdout).toContain("Files:");
  847. });
  848. test("removes a collection", async () => {
  849. // First verify the collection exists
  850. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  851. expect(listBefore).toContain("fixtures");
  852. // Remove it
  853. const { stdout, exitCode } = await runQmd(["collection", "remove", "fixtures"], { dbPath: localDbPath });
  854. expect(exitCode).toBe(0);
  855. expect(stdout).toContain("✓ Removed collection 'fixtures'");
  856. expect(stdout).toContain("Deleted");
  857. // Verify it's gone
  858. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  859. expect(listAfter).not.toContain("fixtures");
  860. });
  861. test("handles removing non-existent collection", async () => {
  862. const { stderr, exitCode } = await runQmd(["collection", "remove", "nonexistent"], { dbPath: localDbPath });
  863. expect(exitCode).toBe(1);
  864. expect(stderr).toContain("Collection not found");
  865. });
  866. test("handles missing remove argument", async () => {
  867. const { stderr, exitCode } = await runQmd(["collection", "remove"], { dbPath: localDbPath });
  868. expect(exitCode).toBe(1);
  869. expect(stderr).toContain("Usage:");
  870. });
  871. test("handles unknown subcommand", async () => {
  872. const { stderr, exitCode } = await runQmd(["collection", "invalid"], { dbPath: localDbPath });
  873. expect(exitCode).toBe(1);
  874. expect(stderr).toContain("Unknown subcommand");
  875. });
  876. test("renames a collection", async () => {
  877. // First verify the collection exists
  878. const { stdout: listBefore } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  879. expect(listBefore).toContain("qmd://fixtures/");
  880. // Rename it
  881. const { stdout, exitCode } = await runQmd(["collection", "rename", "fixtures", "my-fixtures"], { dbPath: localDbPath });
  882. expect(exitCode).toBe(0);
  883. expect(stdout).toContain("✓ Renamed collection 'fixtures' to 'my-fixtures'");
  884. expect(stdout).toContain("qmd://fixtures/");
  885. expect(stdout).toContain("qmd://my-fixtures/");
  886. // Verify the new name exists and old name is gone
  887. const { stdout: listAfter } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  888. expect(listAfter).toContain("qmd://my-fixtures/");
  889. expect(listAfter).not.toContain("qmd://fixtures/"); // Old collection should not appear
  890. });
  891. test("handles renaming non-existent collection", async () => {
  892. const { stderr, exitCode } = await runQmd(["collection", "rename", "nonexistent", "newname"], { dbPath: localDbPath });
  893. expect(exitCode).toBe(1);
  894. expect(stderr).toContain("Collection not found");
  895. });
  896. test("handles renaming to existing collection name", async () => {
  897. // Create a second collection in a temp directory
  898. const tempDir = await mkdtemp(join(tmpdir(), "qmd-second-"));
  899. await writeFile(join(tempDir, "test.md"), "# Test");
  900. const addResult = await runQmd(["collection", "add", tempDir, "--name", "second"], { dbPath: localDbPath });
  901. if (addResult.exitCode !== 0) {
  902. console.error("Failed to add second collection:", addResult.stderr);
  903. }
  904. expect(addResult.exitCode).toBe(0);
  905. // Verify both collections exist
  906. const { stdout: listBoth } = await runQmd(["collection", "list"], { dbPath: localDbPath });
  907. expect(listBoth).toContain("qmd://fixtures/");
  908. expect(listBoth).toContain("qmd://second/");
  909. // Try to rename fixtures to second (which already exists)
  910. const { stderr, exitCode } = await runQmd(["collection", "rename", "fixtures", "second"], { dbPath: localDbPath });
  911. expect(exitCode).toBe(1);
  912. expect(stderr).toContain("Collection name already exists");
  913. });
  914. test("handles missing rename arguments", async () => {
  915. const { stderr: stderr1, exitCode: exitCode1 } = await runQmd(["collection", "rename"], { dbPath: localDbPath });
  916. expect(exitCode1).toBe(1);
  917. expect(stderr1).toContain("Usage:");
  918. const { stderr: stderr2, exitCode: exitCode2 } = await runQmd(["collection", "rename", "fixtures"], { dbPath: localDbPath });
  919. expect(exitCode2).toBe(1);
  920. expect(stderr2).toContain("Usage:");
  921. });
  922. });
  923. // =============================================================================
  924. // Collection Ignore Patterns
  925. // =============================================================================
  926. describe("collection ignore patterns", () => {
  927. let localDbPath: string;
  928. let localConfigDir: string;
  929. let ignoreTestDir: string;
  930. beforeAll(async () => {
  931. const env = await createIsolatedTestEnv("ignore-patterns");
  932. localDbPath = env.dbPath;
  933. localConfigDir = env.configDir;
  934. // Create directory structure with subdirectories to ignore
  935. ignoreTestDir = join(testDir, "ignore-fixtures");
  936. await mkdir(join(ignoreTestDir, "notes"), { recursive: true });
  937. await mkdir(join(ignoreTestDir, "sessions"), { recursive: true });
  938. await mkdir(join(ignoreTestDir, "sessions", "2026-03"), { recursive: true });
  939. await mkdir(join(ignoreTestDir, "archive"), { recursive: true });
  940. // Files that should be indexed
  941. await writeFile(join(ignoreTestDir, "readme.md"), "# Main readme\nThis should be indexed.");
  942. await writeFile(join(ignoreTestDir, "notes", "note1.md"), "# Note 1\nThis is a personal note.");
  943. // Files that should be ignored
  944. await writeFile(join(ignoreTestDir, "sessions", "session1.md"), "# Session 1\nThis session should be ignored.");
  945. await writeFile(join(ignoreTestDir, "sessions", "2026-03", "session2.md"), "# Session 2\nNested session should also be ignored.");
  946. await writeFile(join(ignoreTestDir, "archive", "old.md"), "# Old stuff\nThis archive file should be ignored.");
  947. });
  948. test("ignore patterns exclude matching files from indexing", async () => {
  949. // Write YAML config with ignore patterns
  950. await writeFile(
  951. join(localConfigDir, "index.yml"),
  952. `collections:
  953. ignoretst:
  954. path: ${ignoreTestDir}
  955. pattern: "**/*.md"
  956. ignore:
  957. - "sessions/**"
  958. - "archive/**"
  959. `
  960. );
  961. const { stdout, exitCode } = await runQmd(["update"], {
  962. cwd: ignoreTestDir,
  963. dbPath: localDbPath,
  964. configDir: localConfigDir,
  965. });
  966. expect(exitCode).toBe(0);
  967. // Should index 2 files (readme.md + notes/note1.md), not 5
  968. expect(stdout).toContain("2 new");
  969. });
  970. test("ignored files are not searchable", async () => {
  971. const { stdout, exitCode } = await runQmd(["search", "session", "-n", "10"], {
  972. cwd: ignoreTestDir,
  973. dbPath: localDbPath,
  974. configDir: localConfigDir,
  975. });
  976. // Should find no results since sessions/ was ignored
  977. if (exitCode === 0) {
  978. expect(stdout).not.toContain("session1");
  979. expect(stdout).not.toContain("session2");
  980. }
  981. });
  982. test("non-ignored files are searchable", async () => {
  983. const { stdout, exitCode } = await runQmd(["search", "personal note", "-n", "10"], {
  984. cwd: ignoreTestDir,
  985. dbPath: localDbPath,
  986. configDir: localConfigDir,
  987. });
  988. expect(exitCode).toBe(0);
  989. expect(stdout).toContain("note1");
  990. });
  991. test("status shows ignore patterns", async () => {
  992. const { stdout, exitCode } = await runQmd(["collection", "list"], {
  993. cwd: ignoreTestDir,
  994. dbPath: localDbPath,
  995. configDir: localConfigDir,
  996. });
  997. expect(exitCode).toBe(0);
  998. expect(stdout).toContain("Ignore:");
  999. expect(stdout).toContain("sessions/**");
  1000. expect(stdout).toContain("archive/**");
  1001. });
  1002. test("collection without ignore indexes all files", async () => {
  1003. // Create a second collection without ignore
  1004. const env2 = await createIsolatedTestEnv("no-ignore");
  1005. await writeFile(
  1006. join(env2.configDir, "index.yml"),
  1007. `collections:
  1008. allfiles:
  1009. path: ${ignoreTestDir}
  1010. pattern: "**/*.md"
  1011. `
  1012. );
  1013. const { stdout, exitCode } = await runQmd(["update"], {
  1014. cwd: ignoreTestDir,
  1015. dbPath: env2.dbPath,
  1016. configDir: env2.configDir,
  1017. });
  1018. expect(exitCode).toBe(0);
  1019. // Should index all 5 files
  1020. expect(stdout).toContain("5 new");
  1021. });
  1022. });
  1023. // =============================================================================
  1024. // Output Format Tests - qmd:// URIs, context, and docid
  1025. // =============================================================================
  1026. describe("search output formats", () => {
  1027. let localDbPath: string;
  1028. let localConfigDir: string;
  1029. const collName = "fixtures";
  1030. beforeAll(async () => {
  1031. const env = await createIsolatedTestEnv("output-format");
  1032. localDbPath = env.dbPath;
  1033. localConfigDir = env.configDir;
  1034. // Add collection
  1035. const { exitCode, stderr } = await runQmd(
  1036. ["collection", "add", fixturesDir, "--name", collName],
  1037. { dbPath: localDbPath, configDir: localConfigDir }
  1038. );
  1039. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1040. expect(exitCode).toBe(0);
  1041. // Add context
  1042. await runQmd(["context", "add", `qmd://${collName}/`, "Test fixtures for QMD"], { dbPath: localDbPath, configDir: localConfigDir });
  1043. });
  1044. test("search --json includes qmd:// path, docid, and context", async () => {
  1045. const { stdout, exitCode } = await runQmd(["search", "test", "--json", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1046. expect(exitCode).toBe(0);
  1047. const results = JSON.parse(stdout);
  1048. expect(results.length).toBeGreaterThan(0);
  1049. const result = results[0];
  1050. expect(result.file).toMatch(new RegExp(`^qmd://${collName}/`));
  1051. expect(result.docid).toMatch(/^#[a-f0-9]{6}$/);
  1052. expect(result.context).toBe("Test fixtures for QMD");
  1053. // Ensure no full filesystem paths
  1054. expect(result.file).not.toMatch(/^\/Users\//);
  1055. expect(result.file).not.toMatch(/^\/home\//);
  1056. });
  1057. test("search --files includes qmd:// path, docid, and context", async () => {
  1058. const { stdout, exitCode } = await runQmd(["search", "test", "--files", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1059. expect(exitCode).toBe(0);
  1060. // Format: #docid,score,qmd://collection/path,"context"
  1061. expect(stdout).toMatch(new RegExp(`^#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`, "m"));
  1062. expect(stdout).toContain("Test fixtures for QMD");
  1063. // Ensure no full filesystem paths
  1064. expect(stdout).not.toMatch(/\/Users\//);
  1065. expect(stdout).not.toMatch(/\/home\//);
  1066. });
  1067. test("search --csv includes qmd:// path, docid, and context", async () => {
  1068. const { stdout, exitCode } = await runQmd(["search", "test", "--csv", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1069. expect(exitCode).toBe(0);
  1070. // Header should include context
  1071. expect(stdout).toMatch(/^docid,score,file,title,context,line,snippet$/m);
  1072. // Data rows should have qmd:// paths and context
  1073. expect(stdout).toMatch(new RegExp(`#[a-f0-9]{6},[\\d.]+,qmd://${collName}/`));
  1074. expect(stdout).toContain("Test fixtures for QMD");
  1075. // Ensure no full filesystem paths
  1076. expect(stdout).not.toMatch(/\/Users\//);
  1077. expect(stdout).not.toMatch(/\/home\//);
  1078. });
  1079. test("search --md includes docid and context", async () => {
  1080. const { stdout, exitCode } = await runQmd(["search", "test", "--md", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1081. expect(exitCode).toBe(0);
  1082. expect(stdout).toMatch(/\*\*docid:\*\* `#[a-f0-9]{6}`/);
  1083. expect(stdout).toContain("**context:** Test fixtures for QMD");
  1084. });
  1085. test("search --xml includes qmd:// path, docid, and context", async () => {
  1086. const { stdout, exitCode } = await runQmd(["search", "test", "--xml", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1087. expect(exitCode).toBe(0);
  1088. expect(stdout).toMatch(new RegExp(`<file docid="#[a-f0-9]{6}" name="qmd://${collName}/`));
  1089. expect(stdout).toContain('context="Test fixtures for QMD"');
  1090. // Ensure no full filesystem paths
  1091. expect(stdout).not.toMatch(/\/Users\//);
  1092. expect(stdout).not.toMatch(/\/home\//);
  1093. });
  1094. test("search default CLI format includes plain qmd:// path, docid, and context in non-TTY mode", async () => {
  1095. const { stdout, exitCode } = await runQmd(["search", "test", "-n", "1"], { dbPath: localDbPath, configDir: localConfigDir });
  1096. expect(exitCode).toBe(0);
  1097. // runQmd uses piped stdio, so stdout is non-TTY and should not contain OSC 8 links.
  1098. expect(stdout).toMatch(new RegExp(`^qmd://${collName}/.*#[a-f0-9]{6}`, "m"));
  1099. expect(stdout).toContain("Context: Test fixtures for QMD");
  1100. expect(stdout).not.toContain("\x1b]8;;");
  1101. // Ensure no full filesystem paths
  1102. expect(stdout).not.toMatch(/\/Users\//);
  1103. expect(stdout).not.toMatch(/\/home\//);
  1104. });
  1105. });
  1106. describe("editor URI templates", () => {
  1107. test("buildEditorUri expands path, line, and col placeholders", () => {
  1108. const uri = buildEditorUri(
  1109. "vscode://file/{path}:{line}:{col}",
  1110. "/tmp/my notes/readme.md",
  1111. 42,
  1112. 1,
  1113. );
  1114. expect(uri).toBe("vscode://file//tmp/my%20notes/readme.md:42:1");
  1115. });
  1116. test("buildEditorUri supports {column} alias", () => {
  1117. const uri = buildEditorUri(
  1118. "cursor://file/{path}:{line}:{column}",
  1119. "/tmp/docs/api.md",
  1120. 7,
  1121. 3,
  1122. );
  1123. expect(uri).toBe("cursor://file//tmp/docs/api.md:7:3");
  1124. });
  1125. test("termLink returns plain text when stdout is not a TTY", () => {
  1126. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", false);
  1127. expect(linked).toBe("docs/api.md:12");
  1128. });
  1129. test("termLink emits OSC 8 hyperlinks when stdout is a TTY", () => {
  1130. const linked = termLink("docs/api.md:12", "vscode://file//tmp/docs/api.md:12:1", true);
  1131. expect(linked).toBe("\x1b]8;;vscode://file//tmp/docs/api.md:12:1\x07docs/api.md:12\x1b]8;;\x07");
  1132. });
  1133. });
  1134. // =============================================================================
  1135. // Get Command Path Normalization Tests
  1136. // =============================================================================
  1137. describe("get command path normalization", () => {
  1138. let localDbPath: string;
  1139. let localConfigDir: string;
  1140. const collName = "fixtures";
  1141. beforeAll(async () => {
  1142. const env = await createIsolatedTestEnv("get-paths");
  1143. localDbPath = env.dbPath;
  1144. localConfigDir = env.configDir;
  1145. const { exitCode, stderr } = await runQmd(
  1146. ["collection", "add", fixturesDir, "--name", collName],
  1147. { dbPath: localDbPath, configDir: localConfigDir }
  1148. );
  1149. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1150. expect(exitCode).toBe(0);
  1151. });
  1152. test("get with qmd://collection/path format", async () => {
  1153. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1154. expect(exitCode).toBe(0);
  1155. expect(stdout).toContain("Test Document 1");
  1156. });
  1157. test("get with collection/path format (no scheme)", async () => {
  1158. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1159. expect(exitCode).toBe(0);
  1160. expect(stdout).toContain("Test Document 1");
  1161. });
  1162. test("get with //collection/path format", async () => {
  1163. const { stdout, exitCode } = await runQmd(["get", `//${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1164. expect(exitCode).toBe(0);
  1165. expect(stdout).toContain("Test Document 1");
  1166. });
  1167. test("get with qmd:////collection/path format (extra slashes)", async () => {
  1168. const { stdout, exitCode } = await runQmd(["get", `qmd:////${collName}/test1.md`, "-l", "3"], { dbPath: localDbPath, configDir: localConfigDir });
  1169. expect(exitCode).toBe(0);
  1170. expect(stdout).toContain("Test Document 1");
  1171. });
  1172. test("get with path:line format", async () => {
  1173. const { stdout, exitCode } = await runQmd(["get", `${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1174. expect(exitCode).toBe(0);
  1175. // Should start from line 3, not line 1
  1176. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1177. });
  1178. test("get with qmd://path:line format", async () => {
  1179. const { stdout, exitCode } = await runQmd(["get", `qmd://${collName}/test1.md:3`, "-l", "2"], { dbPath: localDbPath, configDir: localConfigDir });
  1180. expect(exitCode).toBe(0);
  1181. // Should start from line 3, not line 1
  1182. expect(stdout).not.toMatch(/^# Test Document 1$/m);
  1183. });
  1184. });
  1185. // =============================================================================
  1186. // Status and Collection List - No Full Paths
  1187. // =============================================================================
  1188. describe("status and collection list hide filesystem paths", () => {
  1189. let localDbPath: string;
  1190. let localConfigDir: string;
  1191. const collName = "fixtures";
  1192. beforeAll(async () => {
  1193. const env = await createIsolatedTestEnv("status-paths");
  1194. localDbPath = env.dbPath;
  1195. localConfigDir = env.configDir;
  1196. const { exitCode, stderr } = await runQmd(
  1197. ["collection", "add", fixturesDir, "--name", collName],
  1198. { dbPath: localDbPath, configDir: localConfigDir }
  1199. );
  1200. if (exitCode !== 0) console.error("collection add failed:", stderr);
  1201. expect(exitCode).toBe(0);
  1202. });
  1203. test("status does not show full filesystem paths", async () => {
  1204. const { stdout, exitCode } = await runQmd(["status"], { dbPath: localDbPath, configDir: localConfigDir });
  1205. expect(exitCode).toBe(0);
  1206. // Should show qmd:// URIs
  1207. expect(stdout).toContain(`qmd://${collName}/`);
  1208. // Should NOT show full filesystem paths (except for the index location which is ok)
  1209. const lines = stdout.split('\n').filter(l => !l.includes('Index:'));
  1210. const pathLines = lines.filter(l => l.includes('/Users/') || l.includes('/home/') || l.includes('/tmp/'));
  1211. expect(pathLines.length).toBe(0);
  1212. });
  1213. test("collection list does not show full filesystem paths", async () => {
  1214. const { stdout, exitCode } = await runQmd(["collection", "list"], { dbPath: localDbPath, configDir: localConfigDir });
  1215. expect(exitCode).toBe(0);
  1216. // Should show qmd:// URIs
  1217. expect(stdout).toContain(`qmd://${collName}/`);
  1218. // Should NOT show Path: lines with filesystem paths
  1219. expect(stdout).not.toMatch(/Path:\s+\//);
  1220. });
  1221. });
  1222. // =============================================================================
  1223. // MCP HTTP Daemon Lifecycle
  1224. // =============================================================================
  1225. describe("mcp http daemon", () => {
  1226. let daemonTestDir: string;
  1227. let daemonCacheDir: string; // XDG_CACHE_HOME value (the qmd/ subdir is created automatically)
  1228. let daemonDbPath: string;
  1229. let daemonConfigDir: string;
  1230. // Track spawned PIDs for cleanup
  1231. const spawnedPids: number[] = [];
  1232. /** Get path to PID file inside the test cache dir */
  1233. function pidPath(): string {
  1234. return join(daemonCacheDir, "qmd", "mcp.pid");
  1235. }
  1236. /** Run qmd with test-isolated env (cache, db, config) */
  1237. async function runDaemonQmd(
  1238. args: string[],
  1239. ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  1240. return runQmd(args, {
  1241. dbPath: daemonDbPath,
  1242. configDir: daemonConfigDir,
  1243. env: { XDG_CACHE_HOME: daemonCacheDir },
  1244. });
  1245. }
  1246. /** Spawn a foreground HTTP server (non-blocking) and return the process */
  1247. function spawnHttpServer(port: number): import("child_process").ChildProcess {
  1248. const proc = spawn(tsxBin, [qmdScript, "mcp", "--http", "--port", String(port)], {
  1249. cwd: fixturesDir,
  1250. env: {
  1251. ...process.env,
  1252. INDEX_PATH: daemonDbPath,
  1253. QMD_CONFIG_DIR: daemonConfigDir,
  1254. },
  1255. stdio: ["ignore", "pipe", "pipe"],
  1256. });
  1257. if (proc.pid) spawnedPids.push(proc.pid);
  1258. return proc;
  1259. }
  1260. /** Wait for HTTP server to become ready */
  1261. async function waitForServer(port: number, timeoutMs = 5000): Promise<boolean> {
  1262. const deadline = Date.now() + timeoutMs;
  1263. while (Date.now() < deadline) {
  1264. try {
  1265. const res = await fetch(`http://localhost:${port}/health`);
  1266. if (res.ok) return true;
  1267. } catch { /* not ready yet */ }
  1268. await sleep(200);
  1269. }
  1270. return false;
  1271. }
  1272. /** Pick a random high port unlikely to conflict */
  1273. function randomPort(): number {
  1274. return 10000 + Math.floor(Math.random() * 50000);
  1275. }
  1276. beforeAll(async () => {
  1277. daemonTestDir = await mkdtemp(join(tmpdir(), "qmd-daemon-test-"));
  1278. daemonCacheDir = join(daemonTestDir, "cache");
  1279. daemonDbPath = join(daemonTestDir, "test.sqlite");
  1280. daemonConfigDir = join(daemonTestDir, "config");
  1281. await mkdir(join(daemonCacheDir, "qmd"), { recursive: true });
  1282. await mkdir(daemonConfigDir, { recursive: true });
  1283. await writeFile(join(daemonConfigDir, "index.yml"), "collections: {}\n");
  1284. });
  1285. afterAll(async () => {
  1286. // Kill any leftover spawned processes
  1287. for (const pid of spawnedPids) {
  1288. try { process.kill(pid, "SIGTERM"); } catch { /* already dead */ }
  1289. }
  1290. // Also clean up via PID file if present
  1291. try {
  1292. const pf = pidPath();
  1293. if (existsSync(pf)) {
  1294. const pid = parseInt(readFileSync(pf, "utf-8").trim());
  1295. try { process.kill(pid, "SIGTERM"); } catch {}
  1296. unlinkSync(pf);
  1297. }
  1298. } catch {}
  1299. await rm(daemonTestDir, { recursive: true, force: true });
  1300. });
  1301. // -------------------------------------------------------------------------
  1302. // Foreground HTTP
  1303. // -------------------------------------------------------------------------
  1304. test("foreground HTTP server starts and responds to health check", async () => {
  1305. const port = randomPort();
  1306. const proc = spawnHttpServer(port);
  1307. try {
  1308. const ready = await waitForServer(port);
  1309. expect(ready).toBe(true);
  1310. const res = await fetch(`http://localhost:${port}/health`);
  1311. expect(res.status).toBe(200);
  1312. const body = await res.json();
  1313. expect(body.status).toBe("ok");
  1314. } finally {
  1315. proc.kill("SIGTERM");
  1316. await new Promise(r => proc.on("close", r));
  1317. }
  1318. });
  1319. // -------------------------------------------------------------------------
  1320. // Daemon lifecycle
  1321. // -------------------------------------------------------------------------
  1322. test("--daemon writes PID file and starts server", async () => {
  1323. const port = randomPort();
  1324. const { stdout, exitCode } = await runDaemonQmd([
  1325. "mcp", "--http", "--daemon", "--port", String(port),
  1326. ]);
  1327. expect(exitCode).toBe(0);
  1328. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1329. // PID file should exist
  1330. expect(existsSync(pidPath())).toBe(true);
  1331. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1332. spawnedPids.push(pid);
  1333. // Server should be reachable
  1334. const ready = await waitForServer(port);
  1335. expect(ready).toBe(true);
  1336. // Clean up
  1337. process.kill(pid, "SIGTERM");
  1338. await sleep(500);
  1339. try { unlinkSync(pidPath()); } catch {}
  1340. });
  1341. test("stop kills daemon and removes PID file", async () => {
  1342. const port = randomPort();
  1343. // Start daemon
  1344. const { exitCode: startCode } = await runDaemonQmd([
  1345. "mcp", "--http", "--daemon", "--port", String(port),
  1346. ]);
  1347. expect(startCode).toBe(0);
  1348. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1349. spawnedPids.push(pid);
  1350. await waitForServer(port);
  1351. // Stop it
  1352. const { stdout: stopOut, exitCode: stopCode } = await runDaemonQmd(["mcp", "stop"]);
  1353. expect(stopCode).toBe(0);
  1354. expect(stopOut).toContain("Stopped");
  1355. // PID file should be gone
  1356. expect(existsSync(pidPath())).toBe(false);
  1357. // Process should be dead
  1358. await sleep(500);
  1359. expect(() => process.kill(pid, 0)).toThrow();
  1360. });
  1361. test("stop handles dead PID gracefully (cleans stale file)", async () => {
  1362. // Write a PID file pointing to a dead process
  1363. writeFileSync(pidPath(), "999999999");
  1364. const { stdout, exitCode } = await runDaemonQmd(["mcp", "stop"]);
  1365. expect(exitCode).toBe(0);
  1366. expect(stdout).toContain("stale");
  1367. // PID file should be cleaned up
  1368. expect(existsSync(pidPath())).toBe(false);
  1369. });
  1370. test("--daemon rejects if already running", async () => {
  1371. const port = randomPort();
  1372. // Start first daemon
  1373. const { exitCode: firstCode } = await runDaemonQmd([
  1374. "mcp", "--http", "--daemon", "--port", String(port),
  1375. ]);
  1376. expect(firstCode).toBe(0);
  1377. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1378. spawnedPids.push(pid);
  1379. await waitForServer(port);
  1380. // Try to start second daemon — should fail
  1381. const { stderr, exitCode } = await runDaemonQmd([
  1382. "mcp", "--http", "--daemon", "--port", String(port + 1),
  1383. ]);
  1384. expect(exitCode).toBe(1);
  1385. expect(stderr).toContain("Already running");
  1386. // Clean up first daemon
  1387. process.kill(pid, "SIGTERM");
  1388. await sleep(500);
  1389. try { unlinkSync(pidPath()); } catch {}
  1390. });
  1391. test("--daemon cleans stale PID file and starts fresh", async () => {
  1392. // Write a stale PID file
  1393. writeFileSync(pidPath(), "999999999");
  1394. const port = randomPort();
  1395. const { exitCode, stdout } = await runDaemonQmd([
  1396. "mcp", "--http", "--daemon", "--port", String(port),
  1397. ]);
  1398. expect(exitCode).toBe(0);
  1399. expect(stdout).toContain(`http://localhost:${port}/mcp`);
  1400. const pid = parseInt(readFileSync(pidPath(), "utf-8").trim());
  1401. spawnedPids.push(pid);
  1402. expect(pid).not.toBe(999999999);
  1403. // Clean up
  1404. const ready = await waitForServer(port);
  1405. expect(ready).toBe(true);
  1406. process.kill(pid, "SIGTERM");
  1407. await sleep(500);
  1408. try { unlinkSync(pidPath()); } catch {}
  1409. });
  1410. });