fileService.test.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
  2. import { homedir, tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. createFileService,
  7. FileExistenceCache,
  8. isSkippableWorkspaceFileListError,
  9. } from "../src/file/fileService.js";
  10. import { setDataBaseDir } from "../src/paths.js";
  11. import {
  12. unpackWorkspaceFileEntries,
  13. } from "@zcode/shared/workspaceFileEntriesCodec";
  14. import type { IFileService } from "../src/file/file.js";
  15. // 分块拉全量(测试语义等价旧单次 listWorkspaceFiles)。
  16. async function readAllPacked(service: IFileService, rootPath: string): Promise<string> {
  17. const total = await service.listWorkspaceFilesLength({ rootPath });
  18. let packed = "";
  19. for (let offset = 0; offset < total; offset += 1000) {
  20. packed += await service.listWorkspaceFilesRange({ rootPath, offset, length: 1000 });
  21. }
  22. return packed;
  23. }
  24. const tempDirs: string[] = [];
  25. function makeTempDir(prefix: string): string {
  26. const dir = mkdtempSync(join(tmpdir(), prefix));
  27. tempDirs.push(dir);
  28. return dir;
  29. }
  30. afterEach(() => {
  31. setDataBaseDir(null);
  32. while (tempDirs.length > 0) {
  33. const dir = tempDirs.pop();
  34. if (dir) {
  35. rmSync(dir, { recursive: true, force: true });
  36. }
  37. }
  38. });
  39. describe("FileExistenceCache", () => {
  40. it("写入新条目前主动删除所有过期条目", () => {
  41. const now = vi.spyOn(Date, "now").mockReturnValue(1_000);
  42. const cache = new FileExistenceCache();
  43. try {
  44. cache.set("expired-a.pdf", true);
  45. cache.set("expired-b.pdf", false);
  46. expect(cache.size).toBe(2);
  47. now.mockReturnValue(61_001);
  48. cache.set("fresh.pdf", true);
  49. expect(cache.size).toBe(1);
  50. expect(cache.get("expired-a.pdf")).toBeUndefined();
  51. expect(cache.get("expired-b.pdf")).toBeUndefined();
  52. expect(cache.get("fresh.pdf")).toBe(true);
  53. } finally {
  54. now.mockRestore();
  55. }
  56. });
  57. it("最多保留 100 条并按 LRU 淘汰", () => {
  58. const cache = new FileExistenceCache();
  59. for (let index = 0; index < 100; index += 1) {
  60. cache.set(`file-${index}.pdf`, false);
  61. }
  62. expect(cache.get("file-0.pdf")).toBe(false);
  63. cache.set("file-100.pdf", true);
  64. expect(cache.size).toBe(100);
  65. expect(cache.get("file-0.pdf")).toBe(false);
  66. expect(cache.get("file-1.pdf")).toBeUndefined();
  67. expect(cache.get("file-100.pdf")).toBe(true);
  68. });
  69. });
  70. describe("fileService", () => {
  71. // ── readdir ──────────────────────────────────────────────────────
  72. describe("readdir", () => {
  73. it("lists directory entries, filters hidden files, sorts directories first then alphabetically", async () => {
  74. const rootPath = makeTempDir("zcode-readdir-");
  75. mkdirSync(join(rootPath, "src"));
  76. mkdirSync(join(rootPath, "assets"));
  77. mkdirSync(join(rootPath, ".hidden-dir"));
  78. writeFileSync(join(rootPath, "readme.md"), "# Hello");
  79. writeFileSync(join(rootPath, "package.json"), "{}");
  80. writeFileSync(join(rootPath, ".gitignore"), "node_modules");
  81. const service = createFileService();
  82. const entries = await service.readdir({ path: rootPath });
  83. expect(entries).toEqual([
  84. {
  85. name: "assets",
  86. path: join(rootPath, "assets"),
  87. type: "directory",
  88. isSymbolicLink: false,
  89. },
  90. {
  91. name: "src",
  92. path: join(rootPath, "src"),
  93. type: "directory",
  94. isSymbolicLink: false,
  95. },
  96. {
  97. name: "package.json",
  98. path: join(rootPath, "package.json"),
  99. type: "file",
  100. isSymbolicLink: false,
  101. },
  102. {
  103. name: "readme.md",
  104. path: join(rootPath, "readme.md"),
  105. type: "file",
  106. isSymbolicLink: false,
  107. },
  108. ]);
  109. });
  110. it("includes hidden files when requested", async () => {
  111. const rootPath = makeTempDir("zcode-readdir-hidden-");
  112. mkdirSync(join(rootPath, ".github"));
  113. mkdirSync(join(rootPath, "src"));
  114. writeFileSync(join(rootPath, ".gitignore"), "node_modules");
  115. writeFileSync(join(rootPath, "readme.md"), "# Hello");
  116. const service = createFileService();
  117. const entries = await service.readdir({ path: rootPath, includeHidden: true });
  118. expect(entries).toEqual([
  119. {
  120. name: ".github",
  121. path: join(rootPath, ".github"),
  122. type: "directory",
  123. isSymbolicLink: false,
  124. },
  125. {
  126. name: "src",
  127. path: join(rootPath, "src"),
  128. type: "directory",
  129. isSymbolicLink: false,
  130. },
  131. {
  132. name: ".gitignore",
  133. path: join(rootPath, ".gitignore"),
  134. type: "file",
  135. isSymbolicLink: false,
  136. },
  137. {
  138. name: "readme.md",
  139. path: join(rootPath, "readme.md"),
  140. type: "file",
  141. isSymbolicLink: false,
  142. },
  143. ]);
  144. });
  145. it("classifies symlinks to directories as directories", async () => {
  146. const rootPath = makeTempDir("zcode-readdir-symlink-dir-");
  147. const targetPath = join(rootPath, "target");
  148. const linkPath = join(rootPath, "linked-dir");
  149. mkdirSync(targetPath);
  150. symlinkSync(targetPath, linkPath, process.platform === "win32" ? "junction" : "dir");
  151. const service = createFileService();
  152. const entries = await service.readdir({ path: rootPath });
  153. expect(entries).toContainEqual({
  154. name: "linked-dir",
  155. path: linkPath,
  156. type: "directory",
  157. isSymbolicLink: true,
  158. });
  159. });
  160. it("marks symlink metadata for directory entries", async () => {
  161. const rootPath = makeTempDir("zcode-readdir-symlink-meta-");
  162. const targetPath = join(rootPath, "target");
  163. const linkPath = join(rootPath, "linked-dir");
  164. mkdirSync(targetPath);
  165. symlinkSync(targetPath, linkPath, process.platform === "win32" ? "junction" : "dir");
  166. const service = createFileService();
  167. const entries = await service.readdir({ path: rootPath });
  168. expect(entries).toEqual(
  169. expect.arrayContaining([
  170. expect.objectContaining({
  171. name: "target",
  172. type: "directory",
  173. isSymbolicLink: false,
  174. }),
  175. expect.objectContaining({
  176. name: "linked-dir",
  177. type: "directory",
  178. isSymbolicLink: true,
  179. }),
  180. ]),
  181. );
  182. });
  183. it("returns empty array for an empty directory", async () => {
  184. const rootPath = makeTempDir("zcode-readdir-empty-");
  185. const service = createFileService();
  186. const entries = await service.readdir({ path: rootPath });
  187. expect(entries).toEqual([]);
  188. });
  189. });
  190. // ── stat ─────────────────────────────────────────────────────────
  191. describe("stat", () => {
  192. it("distinguishes files from directories", async () => {
  193. const rootPath = makeTempDir("zcode-stat-");
  194. const filePath = join(rootPath, "readme.md");
  195. writeFileSync(filePath, "# Hello");
  196. const service = createFileService();
  197. await expect(service.stat({ path: rootPath })).resolves.toEqual({
  198. path: rootPath,
  199. type: "directory",
  200. });
  201. await expect(service.stat({ path: filePath })).resolves.toEqual({
  202. path: filePath,
  203. type: "file",
  204. size: 7,
  205. mtimeMs: expect.any(Number),
  206. });
  207. });
  208. });
  209. describe("checkFilesExist", () => {
  210. it("并发返回文件存在性并把目录和缺失路径判为不可预览", async () => {
  211. const rootPath = makeTempDir("zcode-file-exists-");
  212. const filePath = join(rootPath, "report.pdf");
  213. const directoryPath = join(rootPath, "docs");
  214. const missingPath = join(rootPath, "missing.pdf");
  215. writeFileSync(filePath, "pdf");
  216. mkdirSync(directoryPath);
  217. await expect(
  218. createFileService().checkFilesExist({
  219. paths: [filePath, directoryPath, missingPath],
  220. }),
  221. ).resolves.toEqual([
  222. { path: filePath, exists: true },
  223. { path: directoryPath, exists: false },
  224. { path: missingPath, exists: false },
  225. ]);
  226. });
  227. it("正负结果缓存一分钟,过期后重新读取文件状态", async () => {
  228. const now = vi.spyOn(Date, "now").mockReturnValue(1_000);
  229. const rootPath = makeTempDir("zcode-file-exists-cache-");
  230. const filePath = join(rootPath, "later.pdf");
  231. const service = createFileService();
  232. await expect(service.checkFilesExist({ paths: [filePath] })).resolves.toEqual([
  233. { path: filePath, exists: false },
  234. ]);
  235. writeFileSync(filePath, "created");
  236. now.mockReturnValue(60_999);
  237. await expect(service.checkFilesExist({ paths: [filePath] })).resolves.toEqual([
  238. { path: filePath, exists: false },
  239. ]);
  240. now.mockReturnValue(61_001);
  241. await expect(service.checkFilesExist({ paths: [filePath] })).resolves.toEqual([
  242. { path: filePath, exists: true },
  243. ]);
  244. now.mockRestore();
  245. });
  246. it("拒绝超过单批 15 个路径", async () => {
  247. const service = createFileService();
  248. await expect(
  249. service.checkFilesExist({
  250. paths: Array.from({ length: 16 }, (_, index) => `/tmp/file-${index}.pdf`),
  251. }),
  252. ).rejects.toThrow("15");
  253. });
  254. });
  255. // ── ensureConversationWorkspace ──────────────────────────────────
  256. describe("ensureConversationWorkspace", () => {
  257. it("creates the managed conversation workspace under the configured data root", async () => {
  258. const dataBaseDir = makeTempDir("zcode-conversation-workspace-");
  259. setDataBaseDir(dataBaseDir);
  260. const service = createFileService();
  261. const workspacePath = join(dataBaseDir, ".zcode", "workspace", "default");
  262. await expect(service.ensureConversationWorkspace()).resolves.toEqual({
  263. path: workspacePath,
  264. created: true,
  265. workspacePurpose: "conversation",
  266. });
  267. await expect(service.ensureConversationWorkspace()).resolves.toEqual({
  268. path: workspacePath,
  269. created: false,
  270. workspacePurpose: "conversation",
  271. });
  272. await expect(service.stat({ path: workspacePath })).resolves.toEqual({
  273. path: workspacePath,
  274. type: "directory",
  275. });
  276. });
  277. it("rejects a file collision without returning a half-created workspace", async () => {
  278. const dataBaseDir = makeTempDir("zcode-conversation-workspace-file-");
  279. setDataBaseDir(dataBaseDir);
  280. const workspaceRoot = join(dataBaseDir, ".zcode", "workspace");
  281. mkdirSync(workspaceRoot, { recursive: true });
  282. writeFileSync(join(workspaceRoot, "default"), "not a directory");
  283. await expect(createFileService().ensureConversationWorkspace()).rejects.toThrow(
  284. "Workspace path is not a directory",
  285. );
  286. });
  287. });
  288. // ── createScratchWorkspace ───────────────────────────────────────
  289. describe("createScratchWorkspace", () => {
  290. const scratchRoot = join(homedir(), "ZCodeProject");
  291. const testWorkspaceName = `zcode-file-service-test-${Date.now()}`;
  292. const testWorkspacePath = join(scratchRoot, testWorkspaceName);
  293. afterEach(() => {
  294. rmSync(testWorkspacePath, { recursive: true, force: true });
  295. rmSync(`${testWorkspacePath}-file`, { force: true });
  296. });
  297. it("creates a missing scratch workspace directory", async () => {
  298. const service = createFileService();
  299. await expect(service.createScratchWorkspace({ name: testWorkspaceName })).resolves.toEqual({
  300. path: testWorkspacePath,
  301. });
  302. await expect(service.stat({ path: testWorkspacePath })).resolves.toEqual({
  303. path: testWorkspacePath,
  304. type: "directory",
  305. });
  306. await expect(
  307. service.readdir({ path: testWorkspacePath, includeHidden: true }),
  308. ).resolves.toEqual([]);
  309. });
  310. it("succeeds idempotently when the directory already exists", async () => {
  311. mkdirSync(testWorkspacePath, { recursive: true });
  312. const service = createFileService();
  313. await expect(service.createScratchWorkspace({ name: testWorkspaceName })).resolves.toEqual({
  314. path: testWorkspacePath,
  315. });
  316. });
  317. it("throws when the target path conflicts with a file", async () => {
  318. const fileWorkspaceName = `${testWorkspaceName}-file`;
  319. const fileWorkspacePath = `${testWorkspacePath}-file`;
  320. mkdirSync(scratchRoot, { recursive: true });
  321. writeFileSync(fileWorkspacePath, "not a directory");
  322. const service = createFileService();
  323. await expect(service.createScratchWorkspace({ name: fileWorkspaceName })).rejects.toThrow();
  324. });
  325. });
  326. // ── readTextFile ─────────────────────────────────────────────────
  327. describe("readTextFile", () => {
  328. it("reads full content of a small text file", async () => {
  329. const rootPath = makeTempDir("zcode-readtext-");
  330. const filePath = join(rootPath, "hello.txt");
  331. writeFileSync(filePath, "Hello, world!");
  332. const service = createFileService();
  333. const result = await service.readTextFile({ path: filePath });
  334. expect(result.content).toBe("Hello, world!");
  335. expect(result.offset).toBe(0);
  336. expect(result.bytesRead).toBe(13);
  337. expect(result.totalBytes).toBe(13);
  338. expect(result.truncated).toBe(false);
  339. expect(result.isBinary).toBe(false);
  340. });
  341. it("returns empty content when offset exceeds file size", async () => {
  342. const rootPath = makeTempDir("zcode-readtext-offset-");
  343. const filePath = join(rootPath, "small.txt");
  344. writeFileSync(filePath, "abc");
  345. const service = createFileService();
  346. const result = await service.readTextFile({ path: filePath, offset: 100 });
  347. expect(result.content).toBe("");
  348. expect(result.bytesRead).toBe(0);
  349. expect(result.totalBytes).toBe(3);
  350. expect(result.truncated).toBe(false);
  351. expect(result.isBinary).toBe(false);
  352. });
  353. it("reads a slice with offset and length", async () => {
  354. const rootPath = makeTempDir("zcode-readtext-slice-");
  355. const filePath = join(rootPath, "data.txt");
  356. writeFileSync(filePath, "abcdefghij");
  357. const service = createFileService();
  358. const result = await service.readTextFile({ path: filePath, offset: 3, length: 4 });
  359. expect(result.content).toBe("defg");
  360. expect(result.offset).toBe(3);
  361. expect(result.bytesRead).toBe(4);
  362. expect(result.totalBytes).toBe(10);
  363. // 偏移量3 + 读取4字节 = 7,文件总大小10,还有剩余
  364. expect(result.truncated).toBe(true);
  365. });
  366. it("detects binary files and returns empty content", async () => {
  367. const rootPath = makeTempDir("zcode-readtext-binary-");
  368. const filePath = join(rootPath, "image.bin");
  369. // 构造含大量 null 字节的二进制内容
  370. const binaryContent = Buffer.alloc(64, 0);
  371. writeFileSync(filePath, binaryContent);
  372. const service = createFileService();
  373. const result = await service.readTextFile({ path: filePath });
  374. expect(result.content).toBe("");
  375. expect(result.isBinary).toBe(true);
  376. expect(result.totalBytes).toBe(64);
  377. });
  378. it("truncates when file is larger than default read size", async () => {
  379. const rootPath = makeTempDir("zcode-readtext-large-");
  380. const filePath = join(rootPath, "large.txt");
  381. // 默认读取上限 128KB,写入 256KB 的内容
  382. const largeContent = "x".repeat(256 * 1024);
  383. writeFileSync(filePath, largeContent);
  384. const service = createFileService();
  385. const result = await service.readTextFile({ path: filePath });
  386. expect(result.bytesRead).toBe(128 * 1024);
  387. expect(result.totalBytes).toBe(256 * 1024);
  388. expect(result.truncated).toBe(true);
  389. expect(result.isBinary).toBe(false);
  390. });
  391. it("clamps length to MAX_TEXT_READ_BYTES (256KB)", async () => {
  392. const rootPath = makeTempDir("zcode-readtext-clamp-");
  393. const filePath = join(rootPath, "huge.txt");
  394. const content = "y".repeat(512 * 1024);
  395. writeFileSync(filePath, content);
  396. const service = createFileService();
  397. // 请求读取 512KB,应被截断到 256KB
  398. const result = await service.readTextFile({ path: filePath, length: 512 * 1024 });
  399. expect(result.bytesRead).toBe(256 * 1024);
  400. expect(result.truncated).toBe(true);
  401. });
  402. it("throws when path is not a file", async () => {
  403. const rootPath = makeTempDir("zcode-readtext-dir-");
  404. const service = createFileService();
  405. await expect(service.readTextFile({ path: rootPath })).rejects.toThrow(/not a file/);
  406. });
  407. });
  408. // ── readFileRange ────────────────────────────────────────────────
  409. describe("readFileRange", () => {
  410. it("reads raw bytes at the requested offset", async () => {
  411. const rootPath = makeTempDir("zcode-readrange-");
  412. const filePath = join(rootPath, "doc.pdf");
  413. writeFileSync(filePath, Buffer.from([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]));
  414. const service = createFileService();
  415. const result = await service.readFileRange({ path: filePath, offset: 2, length: 4 });
  416. expect(result).toBeInstanceOf(Uint8Array);
  417. expect(Array.from(result)).toEqual([0x44, 0x46, 0x2d, 0x31]);
  418. });
  419. it("returns a short array when the range crosses EOF", async () => {
  420. const rootPath = makeTempDir("zcode-readrange-eof-");
  421. const filePath = join(rootPath, "doc.pdf");
  422. writeFileSync(filePath, Buffer.alloc(10, 7));
  423. const service = createFileService();
  424. const result = await service.readFileRange({ path: filePath, offset: 6, length: 64 });
  425. expect(result.length).toBe(4);
  426. });
  427. it("returns an empty array when offset exceeds file size", async () => {
  428. const rootPath = makeTempDir("zcode-readrange-offset-");
  429. const filePath = join(rootPath, "doc.pdf");
  430. writeFileSync(filePath, Buffer.alloc(3, 1));
  431. const service = createFileService();
  432. const result = await service.readFileRange({ path: filePath, offset: 100, length: 8 });
  433. expect(result.length).toBe(0);
  434. });
  435. it("clamps length to MAX_BINARY_READ_BYTES (1MB)", async () => {
  436. const rootPath = makeTempDir("zcode-readrange-clamp-");
  437. const filePath = join(rootPath, "large.pdf");
  438. writeFileSync(filePath, Buffer.alloc(1536 * 1024, 2));
  439. const service = createFileService();
  440. const result = await service.readFileRange({
  441. path: filePath,
  442. offset: 0,
  443. length: 2 * 1024 * 1024,
  444. });
  445. expect(result.length).toBe(1024 * 1024);
  446. });
  447. it("throws when path is not a file", async () => {
  448. const rootPath = makeTempDir("zcode-readrange-dir-");
  449. const service = createFileService();
  450. await expect(service.readFileRange({ path: rootPath, offset: 0, length: 8 })).rejects.toThrow(
  451. /not a file/,
  452. );
  453. });
  454. });
  455. // ── readMediaPreview ────────────────────────────────────────────
  456. describe("readMediaPreview", () => {
  457. it("reads image files as base64 previews with inferred media type", async () => {
  458. const rootPath = makeTempDir("zcode-readmedia-");
  459. const filePath = join(rootPath, "preview.png");
  460. writeFileSync(filePath, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
  461. const service = createFileService();
  462. const result = await service.readMediaPreview({ path: filePath });
  463. expect(result).toEqual({
  464. path: filePath,
  465. mediaType: "image/png",
  466. dataBase64: Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString("base64"),
  467. totalBytes: 4,
  468. });
  469. });
  470. it("rejects media previews that exceed the configured size limit", async () => {
  471. const rootPath = makeTempDir("zcode-readmedia-large-");
  472. const filePath = join(rootPath, "large.png");
  473. writeFileSync(filePath, Buffer.alloc(32, 1));
  474. const service = createFileService();
  475. await expect(service.readMediaPreview({ path: filePath, maxBytes: 16 })).rejects.toThrow(
  476. /too large/,
  477. );
  478. });
  479. it.each([
  480. ["clip.mp4", "video/mp4"],
  481. ["clip.mov", "video/quicktime"],
  482. ["clip.webm", "video/webm"],
  483. ["clip.m4v", "video/x-m4v"],
  484. ["song.mp3", "audio/mpeg"],
  485. ["song.wav", "audio/wav"],
  486. ["song.m4a", "audio/mp4"],
  487. ["song.ogg", "audio/ogg"],
  488. ["song.opus", "audio/opus"],
  489. ["song.flac", "audio/flac"],
  490. ["song.weba", "audio/webm"],
  491. ])("infers %s as %s", async (filename, mediaType) => {
  492. const rootPath = makeTempDir("zcode-readmedia-format-");
  493. const filePath = join(rootPath, filename);
  494. writeFileSync(filePath, Buffer.from([1, 2, 3]));
  495. const result = await createFileService().readMediaPreview({ path: filePath });
  496. expect(result.mediaType).toBe(mediaType);
  497. });
  498. });
  499. // ── readBinaryPreview ───────────────────────────────────────────
  500. describe("readBinaryPreview", () => {
  501. it("reads bounded binary files as base64 previews", async () => {
  502. const rootPath = makeTempDir("zcode-readbinary-");
  503. const filePath = join(rootPath, "workbook.xlsx");
  504. const content = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
  505. writeFileSync(filePath, content);
  506. const service = createFileService();
  507. const result = await service.readBinaryPreview({ path: filePath });
  508. expect(result).toEqual({
  509. path: filePath,
  510. dataBase64: content.toString("base64"),
  511. totalBytes: content.byteLength,
  512. });
  513. });
  514. it("rejects binary previews before reading files above the configured limit", async () => {
  515. const rootPath = makeTempDir("zcode-readbinary-large-");
  516. const filePath = join(rootPath, "large.docx");
  517. writeFileSync(filePath, Buffer.alloc(32, 1));
  518. const service = createFileService();
  519. await expect(service.readBinaryPreview({ path: filePath, maxBytes: 16 })).rejects.toThrow(
  520. /too large/,
  521. );
  522. });
  523. it("clamps custom binary preview limits to the 25 MB hard limit", async () => {
  524. const rootPath = makeTempDir("zcode-readbinary-hard-limit-");
  525. const filePath = join(rootPath, "oversized.xlsx");
  526. writeFileSync(filePath, Buffer.alloc(25 * 1024 * 1024 + 1, 1));
  527. const service = createFileService();
  528. await expect(
  529. service.readBinaryPreview({
  530. path: filePath,
  531. maxBytes: Number.MAX_SAFE_INTEGER,
  532. }),
  533. ).rejects.toThrow(/too large/);
  534. });
  535. it("rejects directories", async () => {
  536. const rootPath = makeTempDir("zcode-readbinary-dir-");
  537. const service = createFileService();
  538. await expect(service.readBinaryPreview({ path: rootPath })).rejects.toThrow(/not a file/);
  539. });
  540. });
  541. // ── listWorkspaceFiles ───────────────────────────────────────────
  542. describe("listWorkspaceFiles", () => {
  543. it("classifies unreadable or disappearing directories as skippable mention index errors", () => {
  544. for (const code of ["EACCES", "EPERM", "ENOENT"]) {
  545. expect(isSkippableWorkspaceFileListError({ code })).toBe(true);
  546. }
  547. expect(isSkippableWorkspaceFileListError({ code: "EIO" })).toBe(false);
  548. expect(isSkippableWorkspaceFileListError(new Error("boom"))).toBe(false);
  549. });
  550. it("traverses hidden directories while keeping default excluded directories pruned", async () => {
  551. const rootPath = makeTempDir("zcode-file-service-");
  552. mkdirSync(join(rootPath, "src"));
  553. mkdirSync(join(rootPath, "node_modules"));
  554. mkdirSync(join(rootPath, ".git"));
  555. mkdirSync(join(rootPath, ".github", "workflows"), { recursive: true });
  556. writeFileSync(join(rootPath, "package.json"), "{}");
  557. writeFileSync(join(rootPath, ".gitignore"), "dist/\n");
  558. writeFileSync(join(rootPath, ".env"), "SECRET=123");
  559. writeFileSync(join(rootPath, ".env.local"), "SECRET=456");
  560. writeFileSync(join(rootPath, "src", "index.ts"), "export {};");
  561. writeFileSync(join(rootPath, "node_modules", "ignore-me.js"), "");
  562. writeFileSync(join(rootPath, ".git", "HEAD"), "ref: refs/heads/main");
  563. writeFileSync(join(rootPath, ".github", "workflows", "release.yml"), "name: release");
  564. const service = createFileService();
  565. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  566. expect(entries).toEqual([
  567. {
  568. name: "src",
  569. path: join(rootPath, "src"),
  570. relativePath: "src",
  571. type: "directory",
  572. },
  573. {
  574. name: "release.yml",
  575. path: join(rootPath, ".github", "workflows", "release.yml"),
  576. relativePath: ".github/workflows/release.yml",
  577. type: "file",
  578. },
  579. {
  580. name: ".gitignore",
  581. path: join(rootPath, ".gitignore"),
  582. relativePath: ".gitignore",
  583. type: "file",
  584. },
  585. {
  586. name: "package.json",
  587. path: join(rootPath, "package.json"),
  588. relativePath: "package.json",
  589. type: "file",
  590. },
  591. {
  592. name: "index.ts",
  593. path: join(rootPath, "src", "index.ts"),
  594. relativePath: "src/index.ts",
  595. type: "file",
  596. },
  597. ]);
  598. });
  599. it("skips common generated cache and dependency directories across ecosystems", async () => {
  600. const rootPath = makeTempDir("zcode-file-service-generated-dirs-");
  601. const skippedDirectories = [
  602. ["__pycache__", "module.cpython-312.pyc"],
  603. ["coverage", "lcov.info"],
  604. ["htmlcov", "index.html"],
  605. ["lcov-report", "index.html"],
  606. ["bower_components", "dependency.js"],
  607. ["jspm_packages", "dependency.js"],
  608. ["Pods", "Manifest.lock"],
  609. ["CMakeFiles", "compiler_depend.make"],
  610. ["cmake-build-debug", "CMakeCache.txt"],
  611. ["bazel-out", "artifact.o"],
  612. ["DerivedData", "Build.db"],
  613. ["storybook-static", "iframe.html"],
  614. ["playwright-report", "index.html"],
  615. ["test-results", "trace.zip"],
  616. ["allure-results", "result.json"],
  617. ["allure-report", "index.html"],
  618. ["cdk.out", "manifest.json"],
  619. ["eggs", "package.egg"],
  620. ["pip-wheel-metadata", "metadata.json"],
  621. ["wheels", "package.whl"],
  622. ["package.egg-info", "PKG-INFO"],
  623. ["package.dist-info", "METADATA"],
  624. ];
  625. mkdirSync(join(rootPath, "src"));
  626. writeFileSync(join(rootPath, "src", "index.ts"), "export {};");
  627. for (const [directoryName, fileName] of skippedDirectories) {
  628. mkdirSync(join(rootPath, directoryName), { recursive: true });
  629. writeFileSync(join(rootPath, directoryName, fileName), "");
  630. }
  631. const service = createFileService();
  632. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  633. expect(entries).toEqual([
  634. {
  635. name: "src",
  636. path: join(rootPath, "src"),
  637. relativePath: "src",
  638. type: "directory",
  639. },
  640. {
  641. name: "index.ts",
  642. path: join(rootPath, "src", "index.ts"),
  643. relativePath: "src/index.ts",
  644. type: "file",
  645. },
  646. ]);
  647. });
  648. it("skips standalone compiled and cache file artifacts", async () => {
  649. const rootPath = makeTempDir("zcode-file-service-generated-files-");
  650. const skippedFileNames = [
  651. "module.pyc",
  652. "module.pyo",
  653. "Main.class",
  654. "object.o",
  655. "library.obj",
  656. "archive.a",
  657. "library.lib",
  658. "addon.node",
  659. "library.so",
  660. "library.dylib",
  661. "library.dll",
  662. "program.exe",
  663. "program.pdb",
  664. "coverage.gcda",
  665. "coverage.profraw",
  666. "coverage.out",
  667. "lcov.info",
  668. "package.jar",
  669. "package.war",
  670. "package.aar",
  671. "package.nupkg",
  672. "package.gem",
  673. "module.beam",
  674. "module.hi",
  675. "library.rlib",
  676. "tsconfig.tsbuildinfo",
  677. ];
  678. writeFileSync(join(rootPath, "src.ts"), "export {};");
  679. for (const fileName of skippedFileNames) {
  680. writeFileSync(join(rootPath, fileName), "");
  681. }
  682. const service = createFileService();
  683. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  684. expect(entries.map((entry) => entry.relativePath)).toEqual(["src.ts"]);
  685. });
  686. it("keeps user-maintained directories and distributable assets searchable", async () => {
  687. const rootPath = makeTempDir("zcode-file-service-user-maintained-");
  688. const includedDirectories = [
  689. "vendor",
  690. "env",
  691. "dist",
  692. "build",
  693. "out",
  694. "target",
  695. "bin",
  696. "obj",
  697. "classes",
  698. "_build",
  699. "deps",
  700. "dist-newstyle",
  701. "renv",
  702. ];
  703. for (const directoryName of includedDirectories) {
  704. mkdirSync(join(rootPath, directoryName));
  705. writeFileSync(join(rootPath, directoryName, "kept.txt"), "");
  706. }
  707. for (const fileName of ["bundle.js.map", "app.min.js", "style.min.css"]) {
  708. writeFileSync(join(rootPath, fileName), "");
  709. }
  710. const service = createFileService();
  711. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  712. const relativePaths = entries.map((entry) => entry.relativePath);
  713. for (const directoryName of includedDirectories) {
  714. expect(relativePaths).toContain(directoryName);
  715. expect(relativePaths).toContain(`${directoryName}/kept.txt`);
  716. }
  717. expect(relativePaths).toEqual(
  718. expect.arrayContaining(["bundle.js.map", "app.min.js", "style.min.css"]),
  719. );
  720. });
  721. it("classifies directory symlinks before filtering without traversing them", async () => {
  722. const rootPath = makeTempDir("zcode-file-service-symlink-");
  723. const targetPath = makeTempDir("zcode-file-service-symlink-target-");
  724. const linkPath = join(rootPath, "linked-dir");
  725. writeFileSync(join(targetPath, "outside.ts"), "");
  726. symlinkSync(targetPath, linkPath, process.platform === "win32" ? "junction" : "dir");
  727. const evaluatedTypes: string[] = [];
  728. const service = createFileService({
  729. workspaceFileSearchFilter: {
  730. evaluate: (entry) => {
  731. evaluatedTypes.push(entry.type);
  732. return { include: true, traverse: true };
  733. },
  734. },
  735. });
  736. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  737. expect(evaluatedTypes).toEqual(["directory"]);
  738. expect(entries).toEqual([
  739. {
  740. name: "linked-dir",
  741. path: linkPath,
  742. relativePath: "linked-dir",
  743. type: "directory",
  744. },
  745. ]);
  746. });
  747. it("uses an injected filter as a complete replacement for the default filter", async () => {
  748. const rootPath = makeTempDir("zcode-file-service-custom-filter-");
  749. mkdirSync(join(rootPath, "node_modules"));
  750. writeFileSync(join(rootPath, "node_modules", "package.js"), "");
  751. writeFileSync(join(rootPath, ".env"), "SECRET=123");
  752. // 预置空 .zcodeignore 隔离掉 ignore 规则层:本用例专测"注入 filter 完整替换内置过滤"
  753. // 的旧契约;.zcodeignore 剪枝行为由独立用例覆盖。
  754. writeFileSync(join(rootPath, ".zcodeignore"), "\n");
  755. const service = createFileService({
  756. workspaceFileSearchFilter: {
  757. evaluate: (entry) => ({
  758. include: true,
  759. traverse: entry.type === "directory",
  760. }),
  761. },
  762. });
  763. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  764. expect(entries.map((entry) => entry.relativePath)).toEqual([
  765. "node_modules",
  766. ".env",
  767. "node_modules/package.js",
  768. ]);
  769. });
  770. it("allows an injected filter to exclude every entry", async () => {
  771. const rootPath = makeTempDir("zcode-file-service-exclude-filter-");
  772. mkdirSync(join(rootPath, "src"));
  773. writeFileSync(join(rootPath, "src", "index.ts"), "");
  774. const service = createFileService({
  775. workspaceFileSearchFilter: {
  776. evaluate: () => ({ include: false, traverse: false }),
  777. },
  778. });
  779. expect(unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath)).toEqual([]);
  780. });
  781. it("returns empty array when hidden directory descendants and env files provide no candidates", async () => {
  782. const rootPath = makeTempDir("zcode-file-service-hidden-");
  783. mkdirSync(join(rootPath, ".vscode"));
  784. writeFileSync(join(rootPath, ".env"), "SECRET=123");
  785. const service = createFileService();
  786. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  787. expect(entries).toEqual([]);
  788. });
  789. it("sorts results by relativePath", async () => {
  790. const rootPath = makeTempDir("zcode-file-service-sort-");
  791. mkdirSync(join(rootPath, "b"));
  792. mkdirSync(join(rootPath, "a"));
  793. writeFileSync(join(rootPath, "b", "z.ts"), "");
  794. writeFileSync(join(rootPath, "a", "x.ts"), "");
  795. writeFileSync(join(rootPath, "root.ts"), "");
  796. const service = createFileService();
  797. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  798. const relativePaths = entries.map((e) => e.relativePath);
  799. expect(relativePaths).toEqual(["a", "b", "a/x.ts", "b/z.ts", "root.ts"]);
  800. });
  801. // .zcodeignore 单一真相源(spec 2026-09-15 增补):目录排除的唯一规则来源。
  802. describe(".zcodeignore", () => {
  803. it("prunes gitignored build directories like obj and bin (ZCT-2096811705629528064)", async () => {
  804. const rootPath = makeTempDir("zcode-file-service-dotnet-");
  805. writeFileSync(join(rootPath, ".gitignore"), "obj/\nbin/\n");
  806. mkdirSync(join(rootPath, "obj", "Debug"), { recursive: true });
  807. mkdirSync(join(rootPath, "bin", "Release"), { recursive: true });
  808. mkdirSync(join(rootPath, "src"));
  809. writeFileSync(join(rootPath, "obj", "Debug", "fake.pdb"), "");
  810. writeFileSync(join(rootPath, "obj", "Debug", "marker.cs"), "");
  811. writeFileSync(join(rootPath, "bin", "Release", "app.dll"), "");
  812. writeFileSync(join(rootPath, "src", "Program.cs"), "");
  813. const service = createFileService();
  814. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  815. // 自动创建暂时停用,内存中的 gitignore + 默认规则仍剪枝 obj/bin。
  816. expect(entries.map((e) => e.relativePath)).toEqual([
  817. "src",
  818. ".gitignore",
  819. "src/Program.cs",
  820. ]);
  821. // 规则文件自身是工具配置,不进入候选。
  822. expect(existsSync(join(rootPath, ".zcodeignore"))).toBe(false);
  823. });
  824. it("uses .gitignore plus builtin defaults without creating .zcodeignore", async () => {
  825. const rootPath = makeTempDir("zcode-file-service-create-");
  826. writeFileSync(join(rootPath, ".gitignore"), "dist/\n");
  827. mkdirSync(join(rootPath, "node_modules", "pkg"), { recursive: true });
  828. mkdirSync(join(rootPath, "dist"));
  829. writeFileSync(join(rootPath, "node_modules", "pkg", "index.js"), "");
  830. writeFileSync(join(rootPath, "dist", "bundle.js"), "");
  831. const service = createFileService();
  832. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  833. // .gitignore 未声明 node_modules:内存默认段仍剪枝(行为兼容)。
  834. expect(entries.map((e) => e.relativePath)).toEqual([".gitignore"]);
  835. expect(existsSync(join(rootPath, ".zcodeignore"))).toBe(false);
  836. });
  837. it("dedupes builtin defaults against gitignore rules on creation", async () => {
  838. const rootPath = makeTempDir("zcode-file-service-create-dedupe-");
  839. // .gitignore 声明了 node_modules/(含尾斜杠差异写法各测一条)。
  840. writeFileSync(join(rootPath, ".gitignore"), "node_modules/\ncoverage\n");
  841. mkdirSync(join(rootPath, "node_modules"));
  842. writeFileSync(join(rootPath, "node_modules", "x.js"), "");
  843. writeFileSync(join(rootPath, "keep.ts"), "");
  844. const service = createFileService();
  845. const preview = await service.readWorkspaceFileSearchIgnore({ rootPath });
  846. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: preview.content });
  847. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  848. // 去重:gitignore 区已有 node_modules/ 与 coverage,默认段不再重复写这两条
  849. // ——文件中每条规则最多一份,删除 gitignore 区那一行即完全放开。
  850. const created = readFileSync(join(rootPath, ".zcodeignore"), "utf8");
  851. expect(created.match(/^node_modules\/$/gm)).toHaveLength(1);
  852. expect(created.match(/^coverage\/?$/gm)).toHaveLength(1);
  853. // 剪枝仍然生效(gitignore 区那条在起作用);.gitignore 自身保持可搜。
  854. expect(entries.map((e) => e.relativePath)).toEqual([".gitignore", "keep.ts"]);
  855. });
  856. it("uses builtin defaults without creating .zcodeignore when no .gitignore exists", async () => {
  857. const rootPath = makeTempDir("zcode-file-service-create-no-gitignore-");
  858. mkdirSync(join(rootPath, "node_modules"));
  859. writeFileSync(join(rootPath, "node_modules", "x.js"), "");
  860. writeFileSync(join(rootPath, "keep.ts"), "");
  861. const service = createFileService();
  862. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  863. expect(entries.map((e) => e.relativePath)).toEqual(["keep.ts"]);
  864. expect(existsSync(join(rootPath, ".zcodeignore"))).toBe(false);
  865. });
  866. it("honors gitignore semantics: negation, anchored patterns and directory suffix", async () => {
  867. const rootPath = makeTempDir("zcode-file-service-semantics-");
  868. mkdirSync(join(rootPath, "logs"));
  869. mkdirSync(join(rootPath, "sub", "build"), { recursive: true });
  870. mkdirSync(join(rootPath, "build"));
  871. writeFileSync(
  872. join(rootPath, ".zcodeignore"),
  873. ["logs/*", "!logs/keep.log", "/build", "*.tmp"].join("\n"),
  874. );
  875. writeFileSync(join(rootPath, "logs", "keep.log"), "");
  876. writeFileSync(join(rootPath, "logs", "drop.log"), "");
  877. writeFileSync(join(rootPath, "build", "root-only.txt"), "");
  878. writeFileSync(join(rootPath, "sub", "build", "nested.txt"), "");
  879. writeFileSync(join(rootPath, "scratch.tmp"), "");
  880. writeFileSync(join(rootPath, "main.ts"), "");
  881. const service = createFileService();
  882. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  883. // ! 反选恢复 logs/keep.log;anchored /build 只剪根 build,sub/build 保留;*.tmp 排除文件。
  884. // logs/* 不排除 logs 目录自身(git 语义:只匹配其下内容)。
  885. expect(entries.map((e) => e.relativePath)).toEqual([
  886. "logs",
  887. "sub",
  888. "sub/build",
  889. "logs/keep.log",
  890. "main.ts",
  891. "sub/build/nested.txt",
  892. ]);
  893. });
  894. it("lets users re-include builtin defaults by editing .zcodeignore (single source of truth)", async () => {
  895. const rootPath = makeTempDir("zcode-file-service-reinclude-");
  896. mkdirSync(join(rootPath, "node_modules", "pkg"), { recursive: true });
  897. writeFileSync(join(rootPath, "node_modules", "pkg", "index.js"), "");
  898. // 用户显式反选内置默认排除:node_modules 必须恢复为可搜(无代码级并集)。
  899. writeFileSync(join(rootPath, ".zcodeignore"), "!node_modules/\n");
  900. const service = createFileService();
  901. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  902. expect(entries.map((e) => e.relativePath)).toEqual([
  903. "node_modules",
  904. "node_modules/pkg",
  905. "node_modules/pkg/index.js",
  906. ]);
  907. });
  908. it("reads and writes the ignore file via service RPC methods", async () => {
  909. const rootPath = makeTempDir("zcode-file-service-rpc-");
  910. writeFileSync(join(rootPath, ".gitignore"), "out/\n");
  911. const service = createFileService();
  912. const initial = await service.readWorkspaceFileSearchIgnore({ rootPath });
  913. // 尚未落盘:预览初始内容(gitignore 拷贝 + 默认段)。
  914. expect(initial.source).toBe("template");
  915. expect(initial.content).toContain("out/");
  916. expect(existsSync(join(rootPath, ".zcodeignore"))).toBe(false);
  917. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: "custom/\n" });
  918. const afterWrite = await service.readWorkspaceFileSearchIgnore({ rootPath });
  919. expect(afterWrite.source).toBe("file");
  920. expect(afterWrite.content).toBe("custom/\n");
  921. mkdirSync(join(rootPath, "custom"));
  922. writeFileSync(join(rootPath, "custom", "x.txt"), "");
  923. writeFileSync(join(rootPath, "ok.txt"), "");
  924. const entries = unpackWorkspaceFileEntries(await readAllPacked(service, rootPath), rootPath);
  925. // custom/ 被写入的规则剪枝;.gitignore 本身保持可搜(现有行为)。
  926. expect(entries.map((e) => e.relativePath)).toEqual([".gitignore", "ok.txt"]);
  927. });
  928. it("syncs only the gitignore section while keeping defaults and custom rules", async () => {
  929. const rootPath = makeTempDir("zcode-file-service-section-sync-");
  930. writeFileSync(join(rootPath, ".gitignore"), "out/\n");
  931. const service = createFileService();
  932. const initial = await service.readWorkspaceFileSearchIgnore({ rootPath });
  933. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: initial.content });
  934. // 用户在默认段里删掉 node_modules/(放开),并在自定义区追加自己的规则。
  935. const edited = initial.content
  936. .replace("node_modules/\n", "")
  937. .concat("my-private-assets/\n");
  938. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: edited });
  939. // .gitignore 更新后同步:只重写 gitignore 区。
  940. writeFileSync(join(rootPath, ".gitignore"), "out/\nnewdir/\n");
  941. const synced = await service.applyWorkspaceFileSearchIgnoreTransform({
  942. rootPath,
  943. transform: "sync-gitignore",
  944. });
  945. expect(synced.content).toContain("newdir/");
  946. // 默认段的用户修改(node_modules 放开)与自定义规则都必须保留。
  947. expect(synced.content).not.toContain("node_modules/");
  948. expect(synced.content).toContain("my-private-assets/");
  949. });
  950. it("resets only the defaults section while keeping gitignore and custom rules", async () => {
  951. const rootPath = makeTempDir("zcode-file-service-section-reset-");
  952. writeFileSync(join(rootPath, ".gitignore"), "out/\n");
  953. const service = createFileService();
  954. const initial = await service.readWorkspaceFileSearchIgnore({ rootPath });
  955. const edited = initial.content
  956. .replace("node_modules/\n", "")
  957. .concat("my-private-assets/\n");
  958. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: edited });
  959. const reset = await service.applyWorkspaceFileSearchIgnoreTransform({
  960. rootPath,
  961. transform: "reset-defaults",
  962. });
  963. // 默认段恢复出厂(node_modules/ 回来了)。
  964. expect(reset.content).toContain("node_modules/");
  965. // gitignore 区与自定义区原样保留。
  966. expect(reset.content).toContain("out/");
  967. expect(reset.content).toContain("my-private-assets/");
  968. });
  969. it("reset re-adds builtin rule after it was removed from .gitignore", async () => {
  970. const rootPath = makeTempDir("zcode-file-service-reset-readd-");
  971. // 创建时 gitignore 声明了 node_modules/ → 默认段去重未写入。
  972. writeFileSync(join(rootPath, ".gitignore"), "node_modules/\n");
  973. const service = createFileService();
  974. const initial = await service.readWorkspaceFileSearchIgnore({ rootPath });
  975. expect(initial.content.match(/^node_modules\/$/gm)).toHaveLength(1);
  976. // 用户从 .gitignore 删掉该行后恢复默认:默认段按新 gitignore 重算,补回兜底。
  977. writeFileSync(join(rootPath, ".gitignore"), "");
  978. await service.writeWorkspaceFileSearchIgnore({ rootPath, content: initial.content });
  979. const reset = await service.applyWorkspaceFileSearchIgnoreTransform({
  980. rootPath,
  981. transform: "reset-defaults",
  982. });
  983. expect(reset.content.match(/^node_modules\/$/gm)).toHaveLength(1);
  984. });
  985. it("falls back to full template rebuild when section markers are missing", async () => {
  986. const rootPath = makeTempDir("zcode-file-service-section-fallback-");
  987. writeFileSync(join(rootPath, ".gitignore"), "out/\n");
  988. // 用户删掉了分区标记(旧格式/手动清理),无法结构化定位分区。
  989. writeFileSync(join(rootPath, ".zcodeignore"), "legacy-rules/\n");
  990. const service = createFileService();
  991. const synced = await service.applyWorkspaceFileSearchIgnoreTransform({
  992. rootPath,
  993. transform: "sync-gitignore",
  994. });
  995. // 退化为整体初始内容重建(含新标记),并在 MR/文档中说明标记行不可删。
  996. expect(synced.content).toContain("out/");
  997. expect(synced.content).toContain("node_modules/");
  998. expect(synced.content).not.toContain("legacy-rules/");
  999. });
  1000. });
  1001. });
  1002. });