cli.test.ts 60 KB

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