fs-context.test.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. import { execFile as execFileCallback } from "node:child_process";
  2. import { EventEmitter } from "node:events";
  3. import {
  4. chmod,
  5. lstat,
  6. mkdir,
  7. mkdtemp,
  8. open,
  9. readdir,
  10. readFile,
  11. rm,
  12. stat,
  13. symlink,
  14. writeFile,
  15. } from "node:fs/promises";
  16. import { tmpdir } from "node:os";
  17. import { dirname, join } from "node:path";
  18. import { fileURLToPath } from "node:url";
  19. import { promisify } from "node:util";
  20. import { describe, expect, it, vi } from "vitest";
  21. import { READ_MAX_FILE_SIZE_BYTES } from "@zcode/contracts";
  22. import { createNodeContextSourceAdapter } from "../src/context/index.js";
  23. import {
  24. createNodeFileSystemAdapter,
  25. setRipgrepTimeoutMsForTests,
  26. setRipgrepWorkerFactoryForTests,
  27. } from "../src/fs/index.js";
  28. const execFile = promisify(execFileCallback);
  29. // Bugfix: 这些测试可能从仓库根或 apps/zcode-cli 子工程启动;fixture 路径必须绑定到当前测试文件位置。
  30. const TEST_DIR = dirname(fileURLToPath(import.meta.url));
  31. const GB2312_FIXTURE_PATH = join(TEST_DIR, "..", "..", "..", "tests", "gb2312.js");
  32. const GB2312_THIS_IS_BYTES = Buffer.from([0xd5, 0xe2, 0xca, 0xc7]);
  33. class HangingRipgrepWorker extends EventEmitter {
  34. terminated = false;
  35. terminate(): Promise<number> {
  36. this.terminated = true;
  37. queueMicrotask(() => {
  38. this.emit("exit", 1);
  39. });
  40. return Promise.resolve(1);
  41. }
  42. }
  43. describe("Node file and context adapters", () => {
  44. it("creates directory parents idempotently through FileSystemPort", async () => {
  45. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-directory-"));
  46. const path = join(dir, "nested", "memory");
  47. const fs = createNodeFileSystemAdapter();
  48. try {
  49. await expect(fs.createDirectory({ path })).resolves.toEqual({ path });
  50. await expect(fs.createDirectory({ path })).resolves.toEqual({ path });
  51. expect((await stat(path)).isDirectory()).toBe(true);
  52. } finally {
  53. await rm(dir, { force: true, recursive: true });
  54. }
  55. });
  56. it("reads and atomically writes text files through FileSystemPort", async () => {
  57. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-port-"));
  58. const path = join(dir, "nested", "file.txt");
  59. const fs = createNodeFileSystemAdapter();
  60. try {
  61. await fs.writeTextFile({
  62. path,
  63. content: "hello",
  64. createParents: true,
  65. atomic: true,
  66. });
  67. const read = await fs.readTextFile({ path });
  68. expect(read.content).toBe("hello");
  69. expect(read.revision?.id).toMatch(/^mtime:/);
  70. await fs.writeTextFile({
  71. path,
  72. content: "updated",
  73. expectedRevision: read.revision,
  74. });
  75. expect(await readFile(path, "utf8")).toBe("updated");
  76. await expect(fs.removeFile({ path })).resolves.toMatchObject({
  77. path,
  78. removed: true,
  79. });
  80. await expect(fs.removeFile({ path, missingOk: true })).resolves.toMatchObject({
  81. path,
  82. removed: false,
  83. });
  84. } finally {
  85. await rm(dir, { force: true, recursive: true });
  86. }
  87. });
  88. it.skipIf(process.platform === "win32")(
  89. "preserves executable permissions when atomically rewriting existing files",
  90. async () => {
  91. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-mode-"));
  92. const path = join(dir, "run.sh");
  93. const fs = createNodeFileSystemAdapter();
  94. try {
  95. await writeFile(path, "#!/usr/bin/env bash\necho old\n", "utf8");
  96. await chmod(path, 0o755);
  97. await fs.writeTextFile({
  98. path,
  99. content: "#!/usr/bin/env bash\necho new\n",
  100. atomic: true,
  101. });
  102. expect(await readFile(path, "utf8")).toBe("#!/usr/bin/env bash\necho new\n");
  103. expect((await stat(path)).mode & 0o777).toBe(0o755);
  104. } finally {
  105. await rm(dir, { force: true, recursive: true });
  106. }
  107. },
  108. );
  109. it.skipIf(process.platform === "win32")("rejects atomic writes through symlink targets", async () => {
  110. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-symlink-"));
  111. const targetPath = join(dir, "target.txt");
  112. const linkPath = join(dir, "link.txt");
  113. const fs = createNodeFileSystemAdapter();
  114. try {
  115. await writeFile(targetPath, "old", "utf8");
  116. await symlink(targetPath, linkPath);
  117. await expect(
  118. fs.writeTextFile({
  119. path: linkPath,
  120. content: "new",
  121. atomic: true,
  122. }),
  123. ).rejects.toMatchObject({
  124. code: "io_error",
  125. message: `Refusing to write through symlink: ${linkPath}. Resolve the symlink and pass the real target path explicitly.`,
  126. });
  127. expect(await readFile(targetPath, "utf8")).toBe("old");
  128. expect((await lstat(linkPath)).isSymbolicLink()).toBe(true);
  129. expect((await readdir(dir)).filter((entry) => entry.includes(".tmp."))).toEqual([]);
  130. } finally {
  131. await rm(dir, { force: true, recursive: true });
  132. }
  133. });
  134. it("normalizes CRLF reads and preserves requested CRLF writes", async () => {
  135. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-eol-"));
  136. const path = join(dir, "file.txt");
  137. const fs = createNodeFileSystemAdapter();
  138. try {
  139. await writeFile(path, "alpha\r\nbeta\r\n", "utf8");
  140. const read = await fs.readTextFile({ path });
  141. expect(read.content).toBe("alpha\nbeta\n");
  142. expect(read.lineEndings).toBe("CRLF");
  143. expect(read.encoding).toBe("utf8");
  144. await fs.writeTextFile({
  145. path,
  146. content: "alpha\ngamma\n",
  147. encoding: read.encoding,
  148. lineEndings: read.lineEndings,
  149. expectedRevision: read.revision,
  150. });
  151. expect(await readFile(path, "utf8")).toBe("alpha\r\ngamma\r\n");
  152. } finally {
  153. await rm(dir, { force: true, recursive: true });
  154. }
  155. });
  156. it("reads true line ranges from large files and rejects unbounded over-budget reads", async () => {
  157. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-range-"));
  158. const path = join(dir, "large.txt");
  159. const fs = createNodeFileSystemAdapter();
  160. const line = `${"x".repeat(120)}\n`;
  161. try {
  162. await writeFile(path, line.repeat(3000), "utf8");
  163. await expect(
  164. fs.readTextFileRange({
  165. path,
  166. maxBytes: READ_MAX_FILE_SIZE_BYTES,
  167. }),
  168. ).rejects.toMatchObject({
  169. code: "too_large",
  170. message: expect.stringContaining("maximum allowed size (256KB)"),
  171. });
  172. const read = await fs.readTextFileRange({
  173. path,
  174. offsetLine: 2500,
  175. limitLines: 2,
  176. });
  177. expect(read.content).toBe(`${"x".repeat(120)}\n${"x".repeat(120)}`);
  178. expect(read.startLine).toBe(2501);
  179. expect(read.lineCount).toBe(2);
  180. expect(read.totalLines).toBe(3001);
  181. expect(read.sizeBytes).toBeGreaterThan(READ_MAX_FILE_SIZE_BYTES);
  182. } finally {
  183. await rm(dir, { force: true, recursive: true });
  184. }
  185. });
  186. it("enforces the binary maxBytes contract without returning truncated content", async () => {
  187. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-binary-limit-"));
  188. const path = join(dir, "video.mp4");
  189. const fs = createNodeFileSystemAdapter();
  190. try {
  191. await writeFile(path, Buffer.from([1, 2, 3]));
  192. await expect(fs.readBinaryFile({ path, maxBytes: 2 })).rejects.toMatchObject({
  193. code: "too_large",
  194. });
  195. await expect(fs.readBinaryFile({ path, maxBytes: 3 })).resolves.toMatchObject({
  196. bytesRead: 3,
  197. sizeBytes: 3,
  198. });
  199. } finally {
  200. await rm(dir, { force: true, recursive: true });
  201. }
  202. });
  203. it("continues reading after a non-EOF short binary read", async () => {
  204. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-binary-short-read-"));
  205. const path = join(dir, "video.mp4");
  206. const fs = createNodeFileSystemAdapter();
  207. let readSpy: ReturnType<typeof vi.spyOn> | undefined;
  208. try {
  209. await writeFile(path, Buffer.from([1, 2, 3]));
  210. const probe = await open(path, "r");
  211. const fileHandlePrototype = Object.getPrototypeOf(probe) as {
  212. read: typeof probe.read;
  213. };
  214. const originalRead = fileHandlePrototype.read;
  215. await probe.close();
  216. let firstRead = true;
  217. readSpy = vi.spyOn(fileHandlePrototype, "read").mockImplementation(
  218. (async function (
  219. this: typeof probe,
  220. buffer: Buffer,
  221. offset: number,
  222. length: number,
  223. position: number | null,
  224. ) {
  225. const readLength = firstRead ? Math.min(1, length) : length;
  226. firstRead = false;
  227. return originalRead.call(this, buffer, offset, readLength, position);
  228. }) as never,
  229. );
  230. const read = await fs.readBinaryFile({ path, maxBytes: 3 });
  231. expect(read.content).toEqual(Buffer.from([1, 2, 3]));
  232. expect(read.bytesRead).toBe(3);
  233. } finally {
  234. readSpy?.mockRestore();
  235. await rm(dir, { force: true, recursive: true });
  236. }
  237. });
  238. it("detects UTF-16LE text files and keeps their line ending metadata", async () => {
  239. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-utf16-"));
  240. const path = join(dir, "file.txt");
  241. const fs = createNodeFileSystemAdapter();
  242. try {
  243. await writeFile(path, Buffer.from("\uFEFFalpha\r\nbeta\r\n", "utf16le"));
  244. const read = await fs.readTextFile({ path });
  245. expect(read.encoding).toBe("utf16le");
  246. expect(read.lineEndings).toBe("CRLF");
  247. expect(read.content).toBe("\uFEFFalpha\nbeta\n");
  248. await fs.writeTextFile({
  249. path,
  250. content: read.content.replace("beta", "gamma"),
  251. encoding: read.encoding,
  252. lineEndings: read.lineEndings,
  253. });
  254. expect((await readFile(path)).toString("utf16le")).toBe("\uFEFFalpha\r\ngamma\r\n");
  255. } finally {
  256. await rm(dir, { force: true, recursive: true });
  257. }
  258. });
  259. it("reads ranges from the GB2312 fixture as logical Unicode text", async () => {
  260. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-gb2312-read-"));
  261. const path = join(dir, "gb2312.js");
  262. const fs = createNodeFileSystemAdapter();
  263. try {
  264. await writeFile(path, await readFile(GB2312_FIXTURE_PATH));
  265. const read = await fs.readTextFile({ path });
  266. expect(read.encoding).toBe("gb2312");
  267. expect(read.content).toContain("// 这是一个变量");
  268. expect(read.content).toContain("// 你好");
  269. const range = await fs.readTextFileRange({
  270. path,
  271. offsetLine: 2,
  272. limitLines: 3,
  273. });
  274. expect(range.encoding).toBe("gb2312");
  275. expect(range.content).toBe("// 这是一个函数\nfunction go() {\n return 1");
  276. } finally {
  277. await rm(dir, { force: true, recursive: true });
  278. }
  279. });
  280. it("preserves GB2312 bytes when rewriting the fixture", async () => {
  281. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-gb2312-write-"));
  282. const path = join(dir, "gb2312.js");
  283. const fs = createNodeFileSystemAdapter();
  284. try {
  285. await writeFile(path, await readFile(GB2312_FIXTURE_PATH));
  286. const read = await fs.readTextFile({ path });
  287. await fs.writeTextFile({
  288. path,
  289. content: read.content.replace("return 1", "return 2"),
  290. encoding: read.encoding,
  291. lineEndings: read.lineEndings,
  292. expectedRevision: read.revision,
  293. });
  294. const raw = await readFile(path);
  295. expect(raw.includes(GB2312_THIS_IS_BYTES)).toBe(true);
  296. expect(raw.includes(Buffer.from("这是", "utf8"))).toBe(false);
  297. const reread = await fs.readTextFile({ path });
  298. expect(reread.encoding).toBe("gb2312");
  299. expect(reread.content).toContain("return 2");
  300. } finally {
  301. await rm(dir, { force: true, recursive: true });
  302. }
  303. });
  304. it("rejects unencodable GB2312 writes without modifying the file", async () => {
  305. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-gb2312-reject-"));
  306. const path = join(dir, "gb2312.js");
  307. const fs = createNodeFileSystemAdapter();
  308. try {
  309. const originalBytes = await readFile(GB2312_FIXTURE_PATH);
  310. await writeFile(path, originalBytes);
  311. const read = await fs.readTextFile({ path });
  312. await expect(
  313. fs.writeTextFile({
  314. path,
  315. content: `${read.content}\n// 🙂\n`,
  316. encoding: read.encoding,
  317. lineEndings: read.lineEndings,
  318. }),
  319. ).rejects.toMatchObject({
  320. code: "unsupported",
  321. });
  322. expect(await readFile(path)).toEqual(originalBytes);
  323. } finally {
  324. await rm(dir, { force: true, recursive: true });
  325. }
  326. });
  327. it("rejects relative file system adapter paths", async () => {
  328. const fs = createNodeFileSystemAdapter();
  329. await expect(fs.readTextFile({ path: "relative.txt" })).rejects.toMatchObject({
  330. code: "invalid_path",
  331. });
  332. await expect(
  333. fs.writeTextFile({
  334. path: "relative.txt",
  335. content: "nope",
  336. }),
  337. ).rejects.toMatchObject({
  338. code: "invalid_path",
  339. });
  340. });
  341. it("lists directory entries through FileSystemPort", async () => {
  342. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-list-"));
  343. const fs = createNodeFileSystemAdapter();
  344. try {
  345. await mkdir(join(dir, "src"));
  346. await writeFile(join(dir, "README.md"), "docs", "utf8");
  347. const listed = await fs.listDirectory({ path: dir });
  348. expect(listed.path).toBe(dir);
  349. expect(listed.numEntries).toBe(2);
  350. expect(listed.entries).toEqual([
  351. {
  352. kind: "file",
  353. name: "README.md",
  354. path: join(dir, "README.md"),
  355. },
  356. {
  357. kind: "directory",
  358. name: "src",
  359. path: join(dir, "src"),
  360. },
  361. ]);
  362. await expect(fs.listDirectory({ path: join(dir, "README.md") })).rejects.toMatchObject({
  363. code: "not_file",
  364. });
  365. } finally {
  366. await rm(dir, { force: true, recursive: true });
  367. }
  368. });
  369. it("searches files and text through FileSystemPort", async () => {
  370. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-search-"));
  371. const fs = createNodeFileSystemAdapter();
  372. try {
  373. await mkdir(join(dir, "src"), { recursive: true });
  374. await writeFile(join(dir, "src", "index.ts"), "export const answer = 42;\n");
  375. await writeFile(join(dir, "src", "index.test.ts"), "expect(answer).toBe(42);\n");
  376. await writeFile(join(dir, "README.md"), "# answer\n");
  377. const files = await fs.searchFiles({
  378. path: dir,
  379. pattern: "**/*.ts",
  380. maxResults: 10,
  381. });
  382. const grepFiles = await fs.searchText({
  383. path: dir,
  384. pattern: "answer",
  385. glob: "**/*.ts",
  386. });
  387. const grepContent = await fs.searchText({
  388. path: dir,
  389. pattern: "answer",
  390. outputMode: "content",
  391. headLimit: 1,
  392. });
  393. expect(files.files.map((path) => path.slice(dir.length + 1)).sort()).toEqual([
  394. "src/index.test.ts",
  395. "src/index.ts",
  396. ]);
  397. expect(grepFiles.files.map((path) => path.slice(dir.length + 1)).sort()).toEqual([
  398. "src/index.test.ts",
  399. "src/index.ts",
  400. ]);
  401. expect(grepFiles.numMatches).toBe(2);
  402. expect(grepContent.entries).toHaveLength(1);
  403. expect(grepContent.appliedLimit).toBe(1);
  404. expect(grepContent.truncated).toBe(true);
  405. } finally {
  406. await rm(dir, { force: true, recursive: true });
  407. }
  408. });
  409. it("searches text with bundled ripgrep semantics", async () => {
  410. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-ripgrep-"));
  411. const fs = createNodeFileSystemAdapter();
  412. try {
  413. await mkdir(join(dir, "src"), { recursive: true });
  414. await writeFile(
  415. join(dir, "src", "app.ts"),
  416. [
  417. "before",
  418. "Needle",
  419. "after",
  420. 'const option = "-flagged";',
  421. "start",
  422. "middle",
  423. "end",
  424. "",
  425. ].join("\n"),
  426. );
  427. await writeFile(join(dir, "src", "view.tsx"), "needle in tsx\n");
  428. await writeFile(join(dir, "src", "view.js"), "needle in js\n");
  429. await writeFile(join(dir, "README.md"), "Needle in docs\n");
  430. const counts = await fs.searchText({
  431. path: dir,
  432. pattern: "needle",
  433. outputMode: "count",
  434. ignoreCase: true,
  435. glob: "src/**/*",
  436. type: "ts",
  437. headLimit: 0,
  438. });
  439. const dashed = await fs.searchText({
  440. path: dir,
  441. pattern: "-flagged",
  442. outputMode: "content",
  443. glob: "**/*.ts",
  444. });
  445. const context = await fs.searchText({
  446. path: join(dir, "src", "app.ts"),
  447. pattern: "Needle",
  448. outputMode: "content",
  449. context: 1,
  450. });
  451. const onlyMatching = await fs.searchText({
  452. path: join(dir, "src", "app.ts"),
  453. pattern: "Needle",
  454. outputMode: "content",
  455. onlyMatching: true,
  456. });
  457. const multiline = await fs.searchText({
  458. path: join(dir, "src", "app.ts"),
  459. pattern: "start\nmiddle",
  460. outputMode: "content",
  461. multiline: true,
  462. });
  463. expect(counts.numMatches).toBe(2);
  464. expect(counts.entries.map((entry) => entry.path.slice(dir.length + 1)).sort()).toEqual([
  465. "src/app.ts",
  466. "src/view.tsx",
  467. ]);
  468. expect(dashed.numMatches).toBe(1);
  469. expect(dashed.entries[0]).toMatchObject({
  470. path: join(dir, "src", "app.ts"),
  471. lineNumber: 4,
  472. matched: true,
  473. });
  474. expect(context.entries.map((entry) => [entry.lineNumber, entry.text, entry.matched])).toEqual(
  475. [
  476. [1, "before", false],
  477. [2, "Needle", true],
  478. [3, "after", false],
  479. ],
  480. );
  481. expect(onlyMatching.entries.map((entry) => entry.text)).toEqual(["Needle"]);
  482. expect(multiline.numMatches).toBe(1);
  483. expect(multiline.entries[0]).toMatchObject({
  484. path: join(dir, "src", "app.ts"),
  485. lineNumber: 5,
  486. matched: true,
  487. });
  488. } finally {
  489. await rm(dir, { force: true, recursive: true });
  490. }
  491. });
  492. it("maps ripgrep regex failures to FileSystemPort invalid_pattern errors", async () => {
  493. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-ripgrep-error-"));
  494. const fs = createNodeFileSystemAdapter();
  495. try {
  496. await writeFile(join(dir, "file.txt"), "hello\n");
  497. await expect(
  498. fs.searchText({
  499. path: dir,
  500. pattern: "[",
  501. outputMode: "content",
  502. }),
  503. ).rejects.toMatchObject({
  504. code: "invalid_pattern",
  505. });
  506. } finally {
  507. await rm(dir, { force: true, recursive: true });
  508. }
  509. });
  510. it("ignores onlyMatching outside content mode in JavaScript grep fallback", async () => {
  511. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-grep-only-matching-"));
  512. const fs = createNodeFileSystemAdapter({ textSearchEngine: "javascript" });
  513. try {
  514. await writeFile(join(dir, "file.txt"), "foo foo\nfoo\n");
  515. const result = await fs.searchText({
  516. path: dir,
  517. pattern: "foo",
  518. outputMode: "count",
  519. onlyMatching: true,
  520. headLimit: 0,
  521. });
  522. expect(result.numMatches).toBe(2);
  523. expect(result.entries).toEqual([
  524. {
  525. path: join(dir, "file.txt"),
  526. count: 2,
  527. },
  528. ]);
  529. } finally {
  530. await rm(dir, { force: true, recursive: true });
  531. }
  532. });
  533. it("keeps context lines and match-line count for onlyMatching content", async () => {
  534. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-grep-only-matching-context-"));
  535. const engines = [
  536. createNodeFileSystemAdapter(),
  537. createNodeFileSystemAdapter({ textSearchEngine: "javascript" }),
  538. ];
  539. try {
  540. const path = join(dir, "file.txt");
  541. await writeFile(path, "before\nfoo foo\nafter\n");
  542. for (const fs of engines) {
  543. const result = await fs.searchText({
  544. path,
  545. pattern: "foo",
  546. outputMode: "content",
  547. onlyMatching: true,
  548. context: 1,
  549. headLimit: 0,
  550. });
  551. expect(result.numMatches).toBe(1);
  552. expect(result.entries.map((entry) => [entry.lineNumber, entry.text, entry.matched])).toEqual(
  553. [
  554. [1, "before", false],
  555. [2, "foo", true],
  556. [2, "foo", true],
  557. [3, "after", false],
  558. ],
  559. );
  560. }
  561. } finally {
  562. await rm(dir, { force: true, recursive: true });
  563. }
  564. });
  565. it("expands multiline onlyMatching content into line entries", async () => {
  566. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-grep-multiline-only-matching-"));
  567. const engines = [
  568. createNodeFileSystemAdapter(),
  569. createNodeFileSystemAdapter({ textSearchEngine: "javascript" }),
  570. ];
  571. const cases = [
  572. {
  573. content: "before\nstart\nmiddle\nend\n",
  574. pattern: "start\nmiddle",
  575. expected: [
  576. [2, "start", true],
  577. [3, "middle", true],
  578. ],
  579. },
  580. {
  581. content: "before\nstart\n\nend\n",
  582. pattern: "start\n\nend",
  583. expected: [
  584. [2, "start", true],
  585. [4, "end", true],
  586. ],
  587. },
  588. {
  589. content: "foo\rbar\r",
  590. pattern: "foo\rbar",
  591. expected: [[1, "foo\rbar", true]],
  592. },
  593. {
  594. content: "before\r\nfoo\r\nbar\r\nafter\r\n",
  595. pattern: "foo\r\nbar",
  596. expected: [
  597. [2, "foo", true],
  598. [3, "bar", true],
  599. ],
  600. },
  601. {
  602. content: "zero\nbefore\nstart\nmiddle\nafter\n",
  603. pattern: "start\nmiddle",
  604. context: 1,
  605. expected: [
  606. [2, "before", false],
  607. [3, "start", true],
  608. [4, "middle", true],
  609. [5, "after", false],
  610. ],
  611. },
  612. ] as const;
  613. try {
  614. for (const [index, testCase] of cases.entries()) {
  615. const path = join(dir, `file-${index}.txt`);
  616. await writeFile(path, testCase.content);
  617. for (const fs of engines) {
  618. const result = await fs.searchText({
  619. path,
  620. pattern: testCase.pattern,
  621. outputMode: "content",
  622. multiline: true,
  623. onlyMatching: true,
  624. context: testCase.context,
  625. headLimit: 0,
  626. });
  627. expect(result.numMatches).toBe(1);
  628. expect(
  629. result.entries.map((entry) => [entry.lineNumber, entry.text, entry.matched]),
  630. ).toEqual(testCase.expected);
  631. }
  632. }
  633. } finally {
  634. await rm(dir, { force: true, recursive: true });
  635. }
  636. });
  637. it("keeps zero-length onlyMatching entries aligned between ripgrep and fallback", async () => {
  638. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-grep-zero-only-matching-"));
  639. const engines = [
  640. createNodeFileSystemAdapter(),
  641. createNodeFileSystemAdapter({ textSearchEngine: "javascript" }),
  642. ];
  643. try {
  644. const path = join(dir, "file.txt");
  645. await writeFile(path, "foo\nbar\n");
  646. for (const fs of engines) {
  647. const result = await fs.searchText({
  648. path,
  649. pattern: "^",
  650. outputMode: "content",
  651. onlyMatching: true,
  652. headLimit: 0,
  653. });
  654. expect(result.numMatches).toBe(2);
  655. expect(result.entries.map((entry) => [entry.lineNumber, entry.text, entry.matched])).toEqual(
  656. [
  657. [1, "", true],
  658. [2, "", true],
  659. ],
  660. );
  661. }
  662. } finally {
  663. await rm(dir, { force: true, recursive: true });
  664. }
  665. });
  666. it("maps cancelled grep searches to FileSystemPort cancelled errors", async () => {
  667. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-grep-cancel-"));
  668. const fs = createNodeFileSystemAdapter({ textSearchEngine: "javascript" });
  669. const controller = new AbortController();
  670. try {
  671. await writeFile(join(dir, "file.txt"), "hello\n");
  672. controller.abort();
  673. await expect(
  674. fs.searchText(
  675. {
  676. path: dir,
  677. pattern: "hello",
  678. },
  679. { signal: controller.signal },
  680. ),
  681. ).rejects.toMatchObject({
  682. code: "cancelled",
  683. });
  684. } finally {
  685. await rm(dir, { force: true, recursive: true });
  686. }
  687. });
  688. it("terminates bundled ripgrep worker when grep search is cancelled", async () => {
  689. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-ripgrep-cancel-"));
  690. const fs = createNodeFileSystemAdapter();
  691. const controller = new AbortController();
  692. const worker = new HangingRipgrepWorker();
  693. let resolveStarted: () => void = () => undefined;
  694. const started = new Promise<void>((resolve) => {
  695. resolveStarted = resolve;
  696. });
  697. const restoreWorkerFactory = setRipgrepWorkerFactoryForTests(() => {
  698. resolveStarted();
  699. return worker;
  700. });
  701. try {
  702. await writeFile(join(dir, "file.txt"), "hello\n");
  703. const pending = fs.searchText(
  704. {
  705. path: dir,
  706. pattern: "hello",
  707. },
  708. { signal: controller.signal },
  709. );
  710. await started;
  711. controller.abort(new Error("user stopped"));
  712. await expect(pending).rejects.toMatchObject({
  713. code: "cancelled",
  714. });
  715. expect(worker.terminated).toBe(true);
  716. } finally {
  717. restoreWorkerFactory();
  718. await rm(dir, { force: true, recursive: true });
  719. }
  720. });
  721. it("terminates bundled ripgrep worker when grep search times out", async () => {
  722. const dir = await mkdtemp(join(tmpdir(), "zcode-fs-ripgrep-timeout-"));
  723. const fs = createNodeFileSystemAdapter();
  724. const worker = new HangingRipgrepWorker();
  725. let resolveStarted: () => void = () => undefined;
  726. const started = new Promise<void>((resolve) => {
  727. resolveStarted = resolve;
  728. });
  729. const restoreWorkerFactory = setRipgrepWorkerFactoryForTests(() => {
  730. resolveStarted();
  731. return worker;
  732. });
  733. const restoreTimeout = setRipgrepTimeoutMsForTests(10);
  734. try {
  735. await writeFile(join(dir, "file.txt"), "hello\n");
  736. const pending = fs.searchText({
  737. path: dir,
  738. pattern: "hello",
  739. });
  740. await started;
  741. await expect(pending).rejects.toMatchObject({
  742. code: "io_error",
  743. message: expect.stringContaining("timed out"),
  744. });
  745. expect(worker.terminated).toBe(true);
  746. } finally {
  747. restoreTimeout();
  748. restoreWorkerFactory();
  749. await rm(dir, { force: true, recursive: true });
  750. }
  751. });
  752. it("resolves context sources outside core", async () => {
  753. const dir = await mkdtemp(join(tmpdir(), "zcode-context-port-"));
  754. const adapter = createNodeContextSourceAdapter({ env: { HOME: dir, SHELL: "/bin/zsh" } });
  755. try {
  756. await writeFile(join(dir, "package.json"), JSON.stringify({ scripts: { test: "vitest" } }));
  757. await writeFile(join(dir, "pnpm-lock.yaml"), "");
  758. await writeFile(join(dir, "AGENTS.md"), "project instructions");
  759. await mkdir(join(dir, ".git"));
  760. const snapshot = await adapter.resolveContextSources({
  761. workingDirectory: dir,
  762. userInstructions: {
  763. workingDirectory: dir,
  764. },
  765. });
  766. expect(snapshot.envInfo.cwd).toBe(dir);
  767. expect(snapshot.envInfo.shell).toBe("zsh");
  768. expect(snapshot.envInfo.isGitRepository).toBe(false);
  769. expect(snapshot.userInstructions?.content).toBe("project instructions");
  770. expect(snapshot.projectContext).toMatchObject({
  771. type: "node",
  772. packageManager: "pnpm",
  773. scripts: { test: "vitest" },
  774. });
  775. } finally {
  776. await rm(dir, { force: true, recursive: true });
  777. }
  778. });
  779. it("uses the effective Bash shell display name when provided by runtime", async () => {
  780. const dir = await mkdtemp(join(tmpdir(), "zcode-context-shell-"));
  781. const adapter = createNodeContextSourceAdapter({ env: { HOME: dir, SHELL: "/bin/fish" } });
  782. try {
  783. const snapshot = await adapter.resolveContextSources({
  784. effectiveShellDisplayName: "zsh",
  785. workingDirectory: dir,
  786. });
  787. expect(snapshot.envInfo.shell).toBe("zsh");
  788. } finally {
  789. await rm(dir, { force: true, recursive: true });
  790. }
  791. });
  792. it("falls back to ~/.zcode/AGENTS.md when workspace AGENTS.md is absent", async () => {
  793. const home = await mkdtemp(join(tmpdir(), "zcode-context-home-"));
  794. const workspace = join(home, "workspace");
  795. const nestedCwd = join(workspace, "packages", "app");
  796. const adapter = createNodeContextSourceAdapter({
  797. env: { HOME: home, SHELL: "/bin/zsh" },
  798. });
  799. try {
  800. await mkdir(nestedCwd, { recursive: true });
  801. await mkdir(join(workspace, ".git"));
  802. await mkdir(join(home, ".zcode"), { recursive: true });
  803. await writeFile(join(home, ".zcode", "AGENTS.md"), "default user instructions");
  804. const fallbackSnapshot = await adapter.resolveContextSources({
  805. workingDirectory: nestedCwd,
  806. userInstructions: {
  807. workingDirectory: nestedCwd,
  808. },
  809. });
  810. expect(fallbackSnapshot.userInstructions?.filePath).toBe(join(home, ".zcode", "AGENTS.md"));
  811. expect(fallbackSnapshot.userInstructions?.content).toBe("default user instructions");
  812. expect(fallbackSnapshot.userInstructions?.sources).toEqual([
  813. expect.objectContaining({
  814. scope: "user",
  815. filePath: join(home, ".zcode", "AGENTS.md"),
  816. content: "default user instructions",
  817. }),
  818. ]);
  819. await writeFile(join(workspace, "AGENTS.md"), "project instructions");
  820. const projectSnapshot = await adapter.resolveContextSources({
  821. workingDirectory: nestedCwd,
  822. userInstructions: {
  823. workingDirectory: nestedCwd,
  824. },
  825. });
  826. expect(projectSnapshot.userInstructions?.filePath).toBe(join(workspace, "AGENTS.md"));
  827. expect(projectSnapshot.userInstructions?.content).toBe(
  828. "default user instructions\n\nproject instructions",
  829. );
  830. expect(projectSnapshot.userInstructions?.sources).toEqual([
  831. expect.objectContaining({
  832. scope: "user",
  833. filePath: join(home, ".zcode", "AGENTS.md"),
  834. content: "default user instructions",
  835. }),
  836. expect.objectContaining({
  837. scope: "workspace",
  838. filePath: join(workspace, "AGENTS.md"),
  839. content: "project instructions",
  840. }),
  841. ]);
  842. } finally {
  843. await rm(home, { force: true, recursive: true });
  844. }
  845. });
  846. it("uses USERPROFILE for default user instructions when HOME is absent", async () => {
  847. const home = await mkdtemp(join(tmpdir(), "zcode-context-userprofile-"));
  848. const workspace = join(home, "workspace");
  849. const adapter = createNodeContextSourceAdapter({
  850. env: { USERPROFILE: home, SHELL: "/bin/zsh" },
  851. });
  852. try {
  853. await mkdir(workspace, { recursive: true });
  854. await mkdir(join(workspace, ".git"));
  855. await mkdir(join(home, ".zcode"), { recursive: true });
  856. await writeFile(join(home, ".zcode", "AGENTS.md"), "userprofile instructions");
  857. const snapshot = await adapter.resolveContextSources({
  858. workingDirectory: workspace,
  859. userInstructions: {
  860. workingDirectory: workspace,
  861. },
  862. });
  863. expect(snapshot.userInstructions?.filePath).toBe(join(home, ".zcode", "AGENTS.md"));
  864. expect(snapshot.userInstructions?.content).toBe("userprofile instructions");
  865. } finally {
  866. await rm(home, { force: true, recursive: true });
  867. }
  868. });
  869. it("does not use the default AGENTS.md fallback for custom priority files", async () => {
  870. const home = await mkdtemp(join(tmpdir(), "zcode-context-priority-"));
  871. const workspace = join(home, "workspace");
  872. const adapter = createNodeContextSourceAdapter({
  873. env: { HOME: home, SHELL: "/bin/zsh" },
  874. });
  875. try {
  876. await mkdir(workspace, { recursive: true });
  877. await mkdir(join(workspace, ".git"));
  878. await mkdir(join(home, ".zcode"), { recursive: true });
  879. await writeFile(join(home, ".zcode", "AGENTS.md"), "default user instructions");
  880. const snapshot = await adapter.resolveContextSources({
  881. workingDirectory: workspace,
  882. userInstructions: {
  883. workingDirectory: workspace,
  884. priorityFiles: ["CUSTOM.md"],
  885. },
  886. });
  887. expect(snapshot.userInstructions).toBeUndefined();
  888. } finally {
  889. await rm(home, { force: true, recursive: true });
  890. }
  891. });
  892. it("captures a session-start git snapshot when the workspace is a repository", async () => {
  893. const dir = await mkdtemp(join(tmpdir(), "zcode-context-git-"));
  894. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  895. try {
  896. if (!(await hasGitCli())) {
  897. expect(true).toBe(true);
  898. return;
  899. }
  900. await runGit(dir, ["init"]);
  901. await runGit(dir, ["checkout", "-B", "main"]);
  902. await runGit(dir, ["config", "user.name", "ZCode Tester"]);
  903. await runGit(dir, ["config", "user.email", "tester@example.com"]);
  904. await writeFile(join(dir, "tracked.txt"), "first\n");
  905. await runGit(dir, ["add", "tracked.txt"]);
  906. await runGit(dir, ["commit", "-m", "first commit"]);
  907. await writeFile(join(dir, "tracked.txt"), "first\nsecond\n");
  908. await runGit(dir, ["add", "tracked.txt"]);
  909. await runGit(dir, ["commit", "-m", "second commit"]);
  910. await writeFile(join(dir, "tracked.txt"), "dirty\n");
  911. await writeFile(join(dir, "untracked.txt"), "new file\n");
  912. const snapshot = await adapter.resolveContextSources({
  913. workingDirectory: dir,
  914. });
  915. expect(snapshot.envInfo.shell).toBe("zsh");
  916. expect(snapshot.envInfo.isGitRepository).toBe(true);
  917. expect(snapshot.envInfo.gitBranch).toBe("main");
  918. expect(snapshot.envInfo.gitMainBranch).toBe("main");
  919. expect(snapshot.envInfo.gitUser).toBe("ZCode Tester");
  920. expect(snapshot.envInfo.gitStatus).toBe("dirty");
  921. expect(snapshot.envInfo.gitStatusLines).toEqual(
  922. expect.arrayContaining(["M tracked.txt", "?? untracked.txt"]),
  923. );
  924. expect(snapshot.envInfo.recentCommits?.length).toBe(2);
  925. expect(snapshot.envInfo.recentCommits?.[0]).toContain("second commit");
  926. expect(snapshot.envInfo.recentCommits?.[1]).toContain("first commit");
  927. } finally {
  928. await rm(dir, { force: true, recursive: true });
  929. }
  930. });
  931. it("keeps git status entries until the 2k character boundary", async () => {
  932. const dir = await mkdtemp(join(tmpdir(), "zcode-context-git-large-"));
  933. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  934. try {
  935. if (!(await hasGitCli())) {
  936. expect(true).toBe(true);
  937. return;
  938. }
  939. await runGit(dir, ["init"]);
  940. await runGit(dir, ["checkout", "-B", "main"]);
  941. for (let index = 0; index < 30; index += 1) {
  942. await writeFile(join(dir, `file-${String(index).padStart(3, "0")}.txt`), "dirty\n");
  943. }
  944. const snapshot = await adapter.resolveContextSources({
  945. workingDirectory: dir,
  946. });
  947. const statusLines = snapshot.envInfo.gitStatusLines ?? [];
  948. expect(snapshot.envInfo.gitStatus).toBe("dirty");
  949. expect(statusLines).toHaveLength(30);
  950. expect(statusLines[0]).toBe("?? file-000.txt");
  951. expect(statusLines[19]).toBe("?? file-019.txt");
  952. expect(statusLines[29]).toBe("?? file-029.txt");
  953. expect(statusLines.join("\n")).not.toContain("git status truncated after 20 entries");
  954. } finally {
  955. await rm(dir, { force: true, recursive: true });
  956. }
  957. });
  958. it("truncates git status by 2k characters with the truncation prompt text", async () => {
  959. const dir = await mkdtemp(join(tmpdir(), "zcode-context-git-2k-"));
  960. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  961. try {
  962. if (!(await hasGitCli())) {
  963. expect(true).toBe(true);
  964. return;
  965. }
  966. await runGit(dir, ["init"]);
  967. await runGit(dir, ["checkout", "-B", "main"]);
  968. for (let index = 0; index < 100; index += 1) {
  969. await writeFile(
  970. join(dir, `file-${String(index).padStart(3, "0")}-${"x".repeat(32)}.txt`),
  971. "dirty\n",
  972. );
  973. }
  974. const snapshot = await adapter.resolveContextSources({
  975. workingDirectory: dir,
  976. });
  977. const statusText = (snapshot.envInfo.gitStatusLines ?? []).join("\n");
  978. expect(snapshot.envInfo.gitStatus).toBe("dirty");
  979. expect(statusText).toContain("... (truncated because it exceeds 2k characters.");
  980. expect(statusText).toContain('run "git status" using Bash');
  981. expect(statusText).not.toContain("git status truncated after 20 entries");
  982. expect(statusText.length).toBeGreaterThan(2000);
  983. } finally {
  984. await rm(dir, { force: true, recursive: true });
  985. }
  986. });
  987. it("uses the main branch fallback when origin HEAD is unavailable", async () => {
  988. const dir = await mkdtemp(join(tmpdir(), "zcode-context-git-main-fallback-"));
  989. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  990. try {
  991. if (!(await hasGitCli())) {
  992. expect(true).toBe(true);
  993. return;
  994. }
  995. await runGit(dir, ["init"]);
  996. await runGit(dir, ["checkout", "-B", "feature-only"]);
  997. await runGit(dir, ["config", "user.name", "ZCode Tester"]);
  998. await runGit(dir, ["config", "user.email", "tester@example.com"]);
  999. await writeFile(join(dir, "tracked.txt"), "first\n");
  1000. await runGit(dir, ["add", "tracked.txt"]);
  1001. await runGit(dir, ["commit", "-m", "first commit"]);
  1002. const snapshot = await adapter.resolveContextSources({
  1003. workingDirectory: dir,
  1004. });
  1005. expect(snapshot.envInfo.gitBranch).toBe("feature-only");
  1006. expect(snapshot.envInfo.gitMainBranch).toBe("main");
  1007. } finally {
  1008. await rm(dir, { force: true, recursive: true });
  1009. }
  1010. });
  1011. it("reports HEAD as the current branch in detached checkout", async () => {
  1012. const dir = await mkdtemp(join(tmpdir(), "zcode-context-git-detached-"));
  1013. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  1014. try {
  1015. if (!(await hasGitCli())) {
  1016. expect(true).toBe(true);
  1017. return;
  1018. }
  1019. await runGit(dir, ["init"]);
  1020. await runGit(dir, ["checkout", "-B", "main"]);
  1021. await runGit(dir, ["config", "user.name", "ZCode Tester"]);
  1022. await runGit(dir, ["config", "user.email", "tester@example.com"]);
  1023. await writeFile(join(dir, "tracked.txt"), "first\n");
  1024. await runGit(dir, ["add", "tracked.txt"]);
  1025. await runGit(dir, ["commit", "-m", "first commit"]);
  1026. await runGit(dir, ["checkout", "--detach", "HEAD"]);
  1027. const snapshot = await adapter.resolveContextSources({
  1028. workingDirectory: dir,
  1029. });
  1030. expect(snapshot.envInfo.gitBranch).toBe("HEAD");
  1031. } finally {
  1032. await rm(dir, { force: true, recursive: true });
  1033. }
  1034. });
  1035. });
  1036. async function hasGitCli(): Promise<boolean> {
  1037. try {
  1038. await execFile("git", ["--version"], {
  1039. encoding: "utf8",
  1040. windowsHide: true,
  1041. });
  1042. return true;
  1043. } catch {
  1044. return false;
  1045. }
  1046. }
  1047. async function runGit(cwd: string, args: string[]): Promise<void> {
  1048. await execFile("git", args, {
  1049. cwd,
  1050. encoding: "utf8",
  1051. windowsHide: true,
  1052. });
  1053. }