fs-context.test.ts 43 KB

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