edit-tool-contract.test.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import {
  6. createFileSystemError,
  7. type FileSystemLineEndings,
  8. type FileSystemPort,
  9. type FileSystemReadTextRangeResult,
  10. type FileSystemReadTextResult,
  11. type FileSystemRevision,
  12. type FileSystemSearchFilesResult,
  13. type FileSystemSearchTextResult,
  14. type FileSystemStatResult,
  15. type FileSystemWriteTextRequest,
  16. type PermissionRuleset,
  17. } from "@zcode/contracts";
  18. import { EditInputSchema, EditOutputSchema } from "@zcode/contracts";
  19. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  20. import {
  21. createErrorResult,
  22. createToolHandlerFailureError,
  23. isToolHandlerFailure,
  24. } from "../src/tool/executor/errors.js";
  25. import { editHandler, editToolEntry } from "../src/tool/handlers/edit.js";
  26. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  27. import type {
  28. ExecutableToolCall,
  29. ReadFileStateMap,
  30. ToolExecutionContext,
  31. } from "../src/tool/types.js";
  32. let tmpDir: string;
  33. beforeEach(async () => {
  34. tmpDir = await mkdtemp(join(tmpdir(), "zcode-edit-contract-"));
  35. });
  36. afterEach(async () => {
  37. await rm(tmpDir, { recursive: true, force: true });
  38. });
  39. describe("Edit tool contract", () => {
  40. it("updates an existing file and maps the success result for the model", async () => {
  41. const file = join(tmpDir, "existing.txt");
  42. const fs = createMemoryFileSystem({ [file]: "old line\nkept line\n" });
  43. const context = contextWith(fs, {
  44. readFileState: createReadFileState(file, "old line\nkept line\n"),
  45. });
  46. const statSpy = vi.spyOn(fs, "stat");
  47. const readSpy = vi.spyOn(fs, "readTextFile");
  48. const writeSpy = vi.spyOn(fs, "writeTextFile");
  49. const output = await editHandler(
  50. { file_path: file, old_string: "old line", new_string: "new line" },
  51. context,
  52. );
  53. expect(fs.files.get(file)).toBe("new line\nkept line\n");
  54. expect(output).toMatchObject({
  55. filePath: file,
  56. oldString: "old line",
  57. newString: "new line",
  58. originalFile: "old line\nkept line\n",
  59. userModified: false,
  60. replaceAll: false,
  61. });
  62. expect(editToolEntry.formatModelContent?.(output)).toBe(
  63. `The file ${file} has been updated successfully. (file state is current in your context — no need to Read it back)`,
  64. );
  65. expect(statSpy).toHaveBeenCalledTimes(1);
  66. expect(readSpy).toHaveBeenCalledTimes(1);
  67. expect(writeSpy).toHaveBeenCalledTimes(1);
  68. });
  69. it("replaces all matches when replace_all is true", async () => {
  70. const file = join(tmpDir, "replace-all.txt");
  71. const fs = createMemoryFileSystem({ [file]: "foo\nfoo\nkeep\n" });
  72. const context = contextWith(fs, {
  73. readFileState: createReadFileState(file, "foo\nfoo\nkeep\n"),
  74. });
  75. const output = await editHandler(
  76. { file_path: file, old_string: "foo", new_string: "bar", replace_all: true },
  77. context,
  78. );
  79. expect(fs.files.get(file)).toBe("bar\nbar\nkeep\n");
  80. expect(editToolEntry.formatModelContent?.(output)).toBe(
  81. `The file ${file} has been updated. All occurrences were successfully replaced. (file state is current in your context — no need to Read it back)`,
  82. );
  83. });
  84. it("writes dollar replacement tokens literally", async () => {
  85. const file = join(tmpDir, "dollar-tokens.txt");
  86. const fs = createMemoryFileSystem({ [file]: "first TOKEN\nsecond TOKEN\n" });
  87. const context = contextWith(fs, {
  88. readFileState: createReadFileState(file, "first TOKEN\nsecond TOKEN\n"),
  89. });
  90. const output = await editHandler(
  91. { file_path: file, old_string: "first TOKEN", new_string: "first $$ and $&" },
  92. context,
  93. );
  94. expect(fs.files.get(file)).toBe("first $$ and $&\nsecond TOKEN\n");
  95. expect(output.newString).toBe("first $$ and $&");
  96. });
  97. it("creates a missing file from empty old_string but still maps it as an update", async () => {
  98. const file = join(tmpDir, "generated", "created.txt");
  99. const fs = createMemoryFileSystem({});
  100. const output = await editHandler(
  101. { file_path: file, old_string: "", new_string: "created\ncontent\n" },
  102. contextWith(fs),
  103. );
  104. expect(fs.files.get(file)).toBe("created\ncontent\n");
  105. expect(output).toMatchObject({ oldString: "", originalFile: "" });
  106. expect(editToolEntry.formatModelContent?.(output)).toBe(
  107. `The file ${file} has been updated successfully. (file state is current in your context — no need to Read it back)`,
  108. );
  109. });
  110. it("fills an existing empty file with empty old_string after it has been read", async () => {
  111. const file = join(tmpDir, "empty-existing.txt");
  112. const fs = createMemoryFileSystem({ [file]: "" });
  113. const context = contextWith(fs, { readFileState: createReadFileState(file, "") });
  114. const output = await editHandler(
  115. { file_path: file, old_string: "", new_string: "filled\n" },
  116. context,
  117. );
  118. expect(fs.files.get(file)).toBe("filled\n");
  119. expect(output).toMatchObject({ oldString: "", originalFile: "" });
  120. });
  121. it("preserves the input relative path in output and model content", async () => {
  122. const file = join(tmpDir, "relative.txt");
  123. const fs = createMemoryFileSystem({ [file]: "relative old\n" });
  124. const context = contextWith(fs, {
  125. readFileState: createReadFileState(file, "relative old\n"),
  126. workingDirectory: tmpDir,
  127. workspaceRoot: tmpDir,
  128. });
  129. const output = await editHandler(
  130. { file_path: "relative.txt", old_string: "relative old", new_string: "relative new" },
  131. context,
  132. );
  133. expect(fs.files.get(file)).toBe("relative new\n");
  134. expect(output.filePath).toBe("relative.txt");
  135. expect(editToolEntry.formatModelContent?.(output)).toBe(
  136. "The file relative.txt has been updated successfully. (file state is current in your context — no need to Read it back)",
  137. );
  138. });
  139. it("accepts a normalized read-state key when the stored display path differs", async () => {
  140. const file = join(tmpDir, "existing-normalized-key.txt");
  141. const fs = createMemoryFileSystem({ [file]: "original\n" });
  142. const revision = revisionFor(file, "original\n");
  143. const readFileState: ReadFileStateMap = new Map([
  144. [
  145. createReadFileStatePathKey(file),
  146. {
  147. path: `${tmpDir}/nested/../existing-normalized-key.txt`,
  148. content: "original\n",
  149. offset: 1,
  150. limit: undefined,
  151. isPartialView: false,
  152. readAt: new Date(),
  153. revisionId: revision.id,
  154. mtimeMs: revision.mtimeMs,
  155. sizeBytes: revision.sizeBytes,
  156. },
  157. ],
  158. ]);
  159. const context = contextWith(fs, { readFileState });
  160. const output = await editHandler(
  161. { file_path: file, old_string: "original", new_string: "modified-by-edit" },
  162. context,
  163. );
  164. expect(output).toMatchObject({
  165. filePath: file,
  166. oldString: "original",
  167. newString: "modified-by-edit",
  168. originalFile: "original\n",
  169. });
  170. expect(fs.files.get(file)).toBe("modified-by-edit\n");
  171. });
  172. it("preserves CRLF on disk while using LF-normalized content internally", async () => {
  173. const file = join(tmpDir, "line-endings.txt");
  174. const fs = createMemoryFileSystem({ [file]: "first\r\nsecond\r\n" });
  175. const context = contextWith(fs, {
  176. readFileState: createReadFileState(file, "first\nsecond\n"),
  177. });
  178. const output = await editHandler(
  179. { file_path: file, old_string: "second", new_string: "changed" },
  180. context,
  181. );
  182. expect(fs.files.get(file)).toBe("first\r\nchanged\r\n");
  183. expect(output.originalFile).toBe("first\nsecond\n");
  184. });
  185. it("deleting a line removes the following newline when old_string omits it", async () => {
  186. const file = join(tmpDir, "delete-line.txt");
  187. const fs = createMemoryFileSystem({ [file]: "keep\nremove\nlast\n" });
  188. const context = contextWith(fs, {
  189. readFileState: createReadFileState(file, "keep\nremove\nlast\n"),
  190. });
  191. await editHandler({ file_path: file, old_string: "remove", new_string: "" }, context);
  192. expect(fs.files.get(file)).toBe("keep\nlast\n");
  193. });
  194. it("matches straight quotes against curly quotes and preserves the file quote style", async () => {
  195. const file = join(tmpDir, "quotes.txt");
  196. const fs = createMemoryFileSystem({ [file]: "const msg = “hello”\n" });
  197. const context = contextWith(fs, {
  198. readFileState: createReadFileState(file, "const msg = “hello”\n"),
  199. });
  200. const output = await editHandler(
  201. { file_path: file, old_string: '"hello"', new_string: '"bye"' },
  202. context,
  203. );
  204. expect(output.oldString).toBe("“hello”");
  205. expect(output.newString).toBe("“bye”");
  206. expect(fs.files.get(file)).toBe("const msg = “bye”\n");
  207. });
  208. it("uses the latest user-modified model text and no legacy freshness suffix", () => {
  209. const content = editToolEntry.formatModelContent?.({
  210. filePath: "/work/user-modified.txt",
  211. oldString: "before",
  212. newString: "after",
  213. originalFile: "before\n",
  214. structuredPatch: [],
  215. userModified: true,
  216. replaceAll: false,
  217. });
  218. expect(content).toBe(
  219. "The file /work/user-modified.txt has been updated successfully. The user modified your proposed changes before accepting them. .",
  220. );
  221. });
  222. it("rejects no-op edits before filesystem access", async () => {
  223. await expect(
  224. editHandler(
  225. { file_path: join(tmpDir, "anything.txt"), old_string: "same", new_string: "same" },
  226. contextWith(createMemoryFileSystem({})),
  227. ),
  228. ).resolves.toEqual({
  229. result: false,
  230. errorCode: 1,
  231. message: "No changes to make: old_string and new_string are exactly the same.",
  232. });
  233. });
  234. it("returns a tool-owned error for an empty file path", async () => {
  235. const fs = createMemoryFileSystem({});
  236. const statSpy = vi.spyOn(fs, "stat");
  237. const toolCall: ExecutableToolCall = {
  238. id: "tool_empty_edit_path",
  239. input: {
  240. file_path: "",
  241. old_string: "before",
  242. new_string: "after",
  243. },
  244. name: "Edit",
  245. };
  246. const failure = await editHandler(toolCall.input, contextWith(fs));
  247. expect(failure).toEqual({
  248. result: false,
  249. errorCode: 13,
  250. message: "Tool path must not be empty",
  251. });
  252. expect(statSpy).not.toHaveBeenCalled();
  253. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  254. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  255. expect(result.error).toMatchObject({
  256. code: "13",
  257. message: "Tool path must not be empty",
  258. });
  259. expect(result.modelContent).toBe(
  260. "<tool_use_error>Tool path must not be empty</tool_use_error>",
  261. );
  262. });
  263. it("wraps a tool-owned code + message only for the model", async () => {
  264. const toolCall: ExecutableToolCall = {
  265. id: "tool_test",
  266. input: {
  267. file_path: "/work/noop.txt",
  268. old_string: "same",
  269. new_string: "same",
  270. },
  271. name: "Edit",
  272. };
  273. const failure = await editHandler(toolCall.input, contextWith(createMemoryFileSystem({})));
  274. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  275. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  276. expect(result.error?.message).toBe(
  277. "No changes to make: old_string and new_string are exactly the same.",
  278. );
  279. expect(result.modelContent).toBe(
  280. "<tool_use_error>No changes to make: old_string and new_string are exactly the same.</tool_use_error>",
  281. );
  282. });
  283. it("preserves raw multiline Edit error text in model-facing tool_result content", async () => {
  284. const file = join(tmpDir, "missing-string.txt");
  285. const oldString = "first line\nsecond line\n" + "x".repeat(520);
  286. const fs = createMemoryFileSystem({ [file]: "available content" });
  287. const toolCall: ExecutableToolCall = {
  288. id: "tool_test",
  289. input: {
  290. file_path: file,
  291. old_string: oldString,
  292. new_string: "replacement",
  293. },
  294. name: "Edit",
  295. };
  296. const rawMessage =
  297. "String to replace not found in file.\nString: first line\nsecond line\n" + "x".repeat(520);
  298. const failure = await editHandler(
  299. toolCall.input,
  300. contextWith(fs, {
  301. readFileState: createReadFileState(file, "available content"),
  302. }),
  303. );
  304. expect(failure).toEqual({
  305. result: false,
  306. errorCode: 8,
  307. message: rawMessage,
  308. });
  309. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  310. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  311. expect(result.error?.message).not.toBe(rawMessage);
  312. expect(result.modelContent).toBe(`<tool_use_error>${rawMessage}</tool_use_error>`);
  313. });
  314. it("does not misclassify unexpected Edit exceptions as tool-owned failures", () => {
  315. const result = createErrorResult(
  316. {
  317. id: "tool_edit_race",
  318. input: {
  319. file_path: "/work/race.txt",
  320. old_string: "before",
  321. new_string: "after",
  322. },
  323. name: "Edit",
  324. },
  325. new Error("File write failed"),
  326. );
  327. expect(result.error?.message).toBe("File write failed");
  328. expect(result.modelContent).toBeUndefined();
  329. });
  330. it("returns missing-file messages with cwd and similar filename suggestions", async () => {
  331. const existing = join(tmpDir, "component.ts");
  332. const missing = join(tmpDir, "component.js");
  333. const fs = createMemoryFileSystem({ [existing]: "export const value = 1\n" });
  334. await expect(
  335. editHandler(
  336. { file_path: missing, old_string: "value", new_string: "renamed" },
  337. contextWith(fs),
  338. ),
  339. ).resolves.toMatchObject({
  340. result: false,
  341. errorCode: 4,
  342. message: `File does not exist. Note: your current working directory is ${tmpDir}. Did you mean component.ts?`,
  343. });
  344. });
  345. it("rejects empty old_string for an existing nonempty file", async () => {
  346. const file = join(tmpDir, "nonempty.txt");
  347. const fs = createMemoryFileSystem({ [file]: "already here" });
  348. await expect(
  349. editHandler({ file_path: file, old_string: "", new_string: "replacement" }, contextWith(fs)),
  350. ).resolves.toMatchObject({
  351. result: false,
  352. errorCode: 3,
  353. message: "Cannot create new file - file already exists.",
  354. });
  355. });
  356. it("rejects notebooks and points to a shell command or script", async () => {
  357. const file = join(tmpDir, "notebook.ipynb");
  358. const fs = createMemoryFileSystem({ [file]: '{"cells":[]}' });
  359. const context = contextWith(fs, { readFileState: createReadFileState(file, '{"cells":[]}') });
  360. await expect(
  361. editHandler({ file_path: file, old_string: "cells", new_string: "metadata" }, context),
  362. ).resolves.toMatchObject({
  363. result: false,
  364. errorCode: 5,
  365. message:
  366. "File is a Jupyter Notebook. Edit does not change .ipynb files; change the notebook JSON with a shell command or script instead.",
  367. });
  368. });
  369. it("requires existing nonempty files to be read before editing", async () => {
  370. const file = join(tmpDir, "unread.txt");
  371. const fs = createMemoryFileSystem({ [file]: "old content" });
  372. await expect(
  373. editHandler(
  374. { file_path: file, old_string: "old", new_string: "new" },
  375. contextWith(fs, { readFileState: new Map() }),
  376. ),
  377. ).resolves.toMatchObject({
  378. result: false,
  379. errorCode: 6,
  380. message: "File has not been read yet. Read it first before writing to it.",
  381. });
  382. });
  383. it("rejects token-truncated partial views even when the file is unchanged", async () => {
  384. const file = join(tmpDir, "partial-view.txt");
  385. const fs = createMemoryFileSystem({ [file]: "line one\nline two\n" });
  386. const context = contextWith(fs, {
  387. readFileState: createReadFileState(file, "line one", {
  388. isPartialView: true,
  389. limit: 1,
  390. revisionContent: "line one\nline two\n",
  391. }),
  392. });
  393. await expect(
  394. editHandler({ file_path: file, old_string: "line two", new_string: "line 2" }, context),
  395. ).resolves.toMatchObject({
  396. result: false,
  397. errorCode: 6,
  398. message: "File has not been read yet. Read it first before writing to it.",
  399. });
  400. });
  401. it("uses the latest same-file range read state after an older full read becomes stale", async () => {
  402. const file = join(tmpDir, "latest-range.txt");
  403. const fs = createMemoryFileSystem({ [file]: "line one\nline two\n" });
  404. fs.setMtime(file, 3);
  405. const readFileState = createReadFileState(file, "outdated\nline two\n", {
  406. mtimeMs: 1,
  407. readAt: new Date(1),
  408. });
  409. const latestRevision = revisionFor(file, "line one\nline two\n", 3);
  410. readFileState.set(createReadFileStatePathKey(file), {
  411. path: file,
  412. content: "line two",
  413. offset: 2,
  414. limit: 1,
  415. isPartialView: false,
  416. readAt: new Date(2),
  417. revisionId: latestRevision.id,
  418. mtimeMs: latestRevision.mtimeMs,
  419. sizeBytes: latestRevision.sizeBytes,
  420. });
  421. await expect(
  422. editHandler(
  423. { file_path: file, old_string: "line two", new_string: "line 2" },
  424. contextWith(fs, { readFileState }),
  425. ),
  426. ).resolves.toMatchObject({ filePath: file });
  427. expect(fs.files.get(file)).toBe("line one\nline 2\n");
  428. });
  429. it("allows sub-millisecond mtime drift for partial read freshness", async () => {
  430. const file = join(tmpDir, "mtime-sub-ms-partial.txt");
  431. const fs = createMemoryFileSystem({ [file]: "target content" });
  432. fs.setMtime(file, 1000.8);
  433. const context = contextWith(fs, {
  434. readFileState: createReadFileState(file, "target", {
  435. limit: 1,
  436. mtimeMs: 1000.2,
  437. offset: 1,
  438. revisionContent: "target content",
  439. }),
  440. });
  441. await expect(
  442. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  443. ).resolves.toMatchObject({ filePath: file });
  444. expect(fs.files.get(file)).toBe("updated content");
  445. });
  446. it("rejects range reads when normalized mtime advances", async () => {
  447. const file = join(tmpDir, "mtime-advanced-range.txt");
  448. const fs = createMemoryFileSystem({ [file]: "target content" });
  449. fs.setMtime(file, 1001);
  450. const context = contextWith(fs, {
  451. readFileState: createReadFileState(file, "target", {
  452. limit: 1,
  453. mtimeMs: 1000.9,
  454. revisionContent: "target content",
  455. }),
  456. });
  457. await expect(
  458. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  459. ).resolves.toMatchObject({
  460. result: false,
  461. errorCode: 7,
  462. message:
  463. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  464. });
  465. });
  466. it("rejects range reads when file size changes inside the same millisecond", async () => {
  467. const file = join(tmpDir, "size-changed-range.txt");
  468. const fs = createMemoryFileSystem({ [file]: "target content" });
  469. fs.files.set(file, "target content!");
  470. fs.setMtime(file, 1000.8);
  471. const context = contextWith(fs, {
  472. readFileState: createReadFileState(file, "target", {
  473. limit: 1,
  474. mtimeMs: 1000.2,
  475. revisionContent: "target content",
  476. }),
  477. });
  478. await expect(
  479. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  480. ).resolves.toMatchObject({
  481. result: false,
  482. errorCode: 7,
  483. message:
  484. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  485. });
  486. });
  487. it("rejects stale edits when content changed after the cached read", async () => {
  488. const file = join(tmpDir, "stale.txt");
  489. const fs = createMemoryFileSystem({ [file]: "old content" });
  490. const context = contextWith(fs, { readFileState: createReadFileState(file, "old content") });
  491. fs.files.set(file, "old content changed elsewhere");
  492. fs.touch(file);
  493. await expect(
  494. editHandler({ file_path: file, old_string: "old", new_string: "new" }, context),
  495. ).resolves.toMatchObject({
  496. result: false,
  497. errorCode: 7,
  498. message:
  499. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  500. });
  501. });
  502. it("allows mtime-only changes for offset-1 full reads but rejects later range stale fallbacks", async () => {
  503. const fullReadFile = join(tmpDir, "mtime-only.txt");
  504. const offsetOneReadFile = join(tmpDir, "mtime-offset-one.txt");
  505. const offsetRangeReadFile = join(tmpDir, "mtime-offset-range.txt");
  506. const fs = createMemoryFileSystem({
  507. [fullReadFile]: "target content",
  508. [offsetOneReadFile]: "target content",
  509. [offsetRangeReadFile]: "target content",
  510. });
  511. const fullContext = contextWith(fs, {
  512. readFileState: createReadFileState(fullReadFile, "target content", { mtimeMs: 1 }),
  513. });
  514. fs.setMtime(fullReadFile, 2);
  515. await expect(
  516. editHandler(
  517. { file_path: fullReadFile, old_string: "target", new_string: "updated" },
  518. fullContext,
  519. ),
  520. ).resolves.toMatchObject({ filePath: fullReadFile });
  521. const offsetOneContext = contextWith(fs, {
  522. readFileState: createReadFileState(offsetOneReadFile, "target content", {
  523. offset: 1,
  524. mtimeMs: 1,
  525. }),
  526. });
  527. fs.setMtime(offsetOneReadFile, 2);
  528. await expect(
  529. editHandler(
  530. { file_path: offsetOneReadFile, old_string: "target", new_string: "updated" },
  531. offsetOneContext,
  532. ),
  533. ).resolves.toMatchObject({ filePath: offsetOneReadFile });
  534. const offsetRangeContext = contextWith(fs, {
  535. readFileState: createReadFileState(offsetRangeReadFile, "target content", {
  536. offset: 2,
  537. mtimeMs: 1,
  538. }),
  539. });
  540. fs.setMtime(offsetRangeReadFile, 2);
  541. await expect(
  542. editHandler(
  543. { file_path: offsetRangeReadFile, old_string: "target", new_string: "updated" },
  544. offsetRangeContext,
  545. ),
  546. ).resolves.toMatchObject({
  547. result: false,
  548. errorCode: 7,
  549. message:
  550. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  551. });
  552. });
  553. it("returns old_string not found and ambiguous-match messages", async () => {
  554. const missingFile = join(tmpDir, "missing-string.txt");
  555. const ambiguousFile = join(tmpDir, "ambiguous.txt");
  556. const fs = createMemoryFileSystem({
  557. [missingFile]: "available content",
  558. [ambiguousFile]: "name\nname\n",
  559. });
  560. await expect(
  561. editHandler(
  562. { file_path: missingFile, old_string: "not present", new_string: "replacement" },
  563. contextWith(fs, { readFileState: createReadFileState(missingFile, "available content") }),
  564. ),
  565. ).resolves.toMatchObject({
  566. result: false,
  567. errorCode: 8,
  568. message: "String to replace not found in file.\nString: not present",
  569. });
  570. await expect(
  571. editHandler(
  572. { file_path: ambiguousFile, old_string: "name", new_string: "label" },
  573. contextWith(fs, { readFileState: createReadFileState(ambiguousFile, "name\nname\n") }),
  574. ),
  575. ).resolves.toMatchObject({
  576. result: false,
  577. errorCode: 9,
  578. message:
  579. "Found 2 matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: name",
  580. });
  581. });
  582. it("matches unicode escape old_string against decoded file content", async () => {
  583. const file = join(tmpDir, "unicode-escape.txt");
  584. const fs = createMemoryFileSystem({ [file]: "<tag>value</tag>\n" });
  585. const output = await editHandler(
  586. { file_path: file, old_string: "\\u003Ctag\\u003E", new_string: "<node>" },
  587. contextWith(fs, { readFileState: createReadFileState(file, "<tag>value</tag>\n") }),
  588. );
  589. expect(output.oldString).toBe("<tag>");
  590. expect(fs.files.get(file)).toBe("<node>value</tag>\n");
  591. });
  592. it("adds Edit performance attribution with patch matching statistics", async () => {
  593. const file = join(tmpDir, "perf-edit.txt");
  594. const fs = createMemoryFileSystem({ [file]: "alpha\nbeta\n" });
  595. const byteLength = Buffer.byteLength;
  596. let newContentByteCountCalls = 0;
  597. const byteLengthSpy = vi.spyOn(Buffer, "byteLength").mockImplementation((value, encoding) => {
  598. if (value === "alpha\ngamma\n" && encoding === "utf8") {
  599. newContentByteCountCalls += 1;
  600. }
  601. return byteLength(value, encoding);
  602. });
  603. try {
  604. const output = await editHandler(
  605. { file_path: file, old_string: "beta", new_string: "gamma" },
  606. contextWith(fs, { readFileState: createReadFileState(file, "alpha\nbeta\n") }),
  607. );
  608. expect(output).toMatchObject({
  609. filePath: file,
  610. perf: {
  611. detail: {
  612. kind: "patch",
  613. filesystem: {
  614. readMs: expect.any(Number),
  615. writeMs: expect.any(Number),
  616. fileCount: 1,
  617. totalBytes: byteLength("alpha\ngamma\n", "utf8"),
  618. maxFileBytes: byteLength("alpha\ngamma\n", "utf8"),
  619. workspaceKind: "local",
  620. },
  621. patch: {
  622. matchMs: expect.any(Number),
  623. hunkCount: 1,
  624. matchAttempts: 1,
  625. },
  626. },
  627. },
  628. });
  629. // 内存 FS 写入和 revision 计算会读取新内容大小;这里约束 perf 字段只额外计算一次。
  630. expect(newContentByteCountCalls).toBe(4);
  631. expect(JSON.stringify((output as any).perf)).not.toContain(file);
  632. expect(JSON.stringify((output as any).perf)).not.toContain("gamma");
  633. } finally {
  634. byteLengthSpy.mockRestore();
  635. }
  636. });
  637. it("rejects files larger than the edit limit before reading them", async () => {
  638. const file = join(tmpDir, "huge.txt");
  639. const fs = createMemoryFileSystem({ [file]: "old" });
  640. fs.sizes.set(file, 1024 * 1024 * 1024 + 1);
  641. await expect(
  642. editHandler({ file_path: file, old_string: "old", new_string: "new" }, contextWith(fs)),
  643. ).resolves.toMatchObject({
  644. result: false,
  645. errorCode: 10,
  646. // 只比上限大一点时,格式化后同为 1GB,括号里写字节数。
  647. message: "File is too large to edit (1073741825 bytes). Maximum editable file size is 1GB.",
  648. });
  649. fs.sizes.set(file, 1536 * 1024 * 1024);
  650. await expect(
  651. editHandler({ file_path: file, old_string: "old", new_string: "new" }, contextWith(fs)),
  652. ).resolves.toMatchObject({
  653. errorCode: 10,
  654. message: "File is too large to edit (1.5GB). Maximum editable file size is 1GB.",
  655. });
  656. });
  657. it("explains an undecodable file instead of returning the raw file-system error", async () => {
  658. const file = join(tmpDir, "legacy.txt");
  659. const fs = createMemoryFileSystem({ [file]: "old" });
  660. fs.readTextFile = async (request) => {
  661. throw createFileSystemError({
  662. code: "unsupported",
  663. path: request.path,
  664. message: `Unsupported or binary text encoding: ${request.path}`,
  665. });
  666. };
  667. await expect(
  668. editHandler({ file_path: file, old_string: "old", new_string: "new" }, contextWith(fs)),
  669. ).resolves.toEqual({
  670. result: false,
  671. errorCode: 15,
  672. message:
  673. "File is not valid UTF-8 or a supported legacy encoding (GB2312, GBK, GB18030), or it is binary. Edit and Write never convert a file's encoding on their own, so nothing was written. If the file is text, make the change with a shell command that reads and writes it in its own encoding (iconv, or PowerShell Get-Content/Set-Content -Encoding), or ask the user whether to convert it to UTF-8 first. To replace the whole file with new UTF-8 text anyway, delete it first, then Write it.",
  674. });
  675. expect(fs.files.get(file)).toBe("old");
  676. });
  677. it("adds the escape note only when old_string has a \\uXXXX escape", async () => {
  678. const file = join(tmpDir, "escape-note.txt");
  679. const fs = createMemoryFileSystem({ [file]: "plain text" });
  680. const context = contextWith(fs, { readFileState: createReadFileState(file, "plain text") });
  681. await expect(
  682. editHandler({ file_path: file, old_string: "caf\\u00e9 menu", new_string: "x" }, context),
  683. ).resolves.toMatchObject({
  684. errorCode: 8,
  685. message:
  686. "String to replace not found in file.\nString: caf\\u00e9 menu\n(note: Edit also tried swapping \\uXXXX escapes and their characters; neither form matched, so the mismatch is likely elsewhere in old_string. Re-read the file and copy the exact surrounding text.)",
  687. });
  688. // 匹配器不会把字符换成 \uXXXX 再找,只有非 ASCII 字符时不加这句。
  689. await expect(
  690. editHandler({ file_path: file, old_string: "café menu", new_string: "x" }, context),
  691. ).resolves.toMatchObject({
  692. errorCode: 8,
  693. message: "String to replace not found in file.\nString: café menu",
  694. });
  695. });
  696. it("coerces semantic boolean strings for replace_all and requires originalFile to be a string", async () => {
  697. expect(
  698. EditInputSchema.parse({
  699. file_path: "/tmp/example.txt",
  700. old_string: "old",
  701. new_string: "new",
  702. replace_all: "false",
  703. }),
  704. ).toMatchObject({ replace_all: false });
  705. const file = join(tmpDir, "string-true.txt");
  706. const fs = createMemoryFileSystem({ [file]: "foo\nfoo\n" });
  707. const output = await editHandler(
  708. { file_path: file, old_string: "foo", new_string: "bar", replace_all: "true" },
  709. contextWith(fs, { readFileState: createReadFileState(file, "foo\nfoo\n") }),
  710. );
  711. expect(fs.files.get(file)).toBe("bar\nbar\n");
  712. expect(typeof output.originalFile).toBe("string");
  713. expect(() =>
  714. EditOutputSchema.parse({
  715. filePath: file,
  716. oldString: "old",
  717. newString: "new",
  718. originalFile: null,
  719. structuredPatch: [],
  720. userModified: false,
  721. replaceAll: false,
  722. }),
  723. ).toThrow();
  724. });
  725. it("honors Edit deny rules before filesystem access", () => {
  726. const service = new PermissionService(defaultPermissionConfig);
  727. const file = join(tmpDir, "blocked", "secret.txt");
  728. const projectRules: PermissionRuleset = {
  729. version: 1,
  730. deny: [
  731. {
  732. toolName: "Edit",
  733. ruleContent: `${tmpDir}/blocked/*`,
  734. },
  735. ],
  736. };
  737. const decision = service.checkPermission(
  738. {
  739. input: {
  740. file_path: file,
  741. old_string: "secret",
  742. new_string: "redacted",
  743. },
  744. mode: "edit",
  745. riskLevel: editToolEntry.metadata.riskLevel,
  746. toolName: "Edit",
  747. },
  748. {
  749. ...editToolEntry.metadata,
  750. permission: editToolEntry.permission,
  751. },
  752. projectRules,
  753. );
  754. expect(decision).toMatchObject({
  755. allowed: false,
  756. decision: "deny",
  757. });
  758. });
  759. });
  760. function contextWith(
  761. fileSystemPort: MemoryFileSystem,
  762. options: {
  763. readFileState?: ReadFileStateMap;
  764. workingDirectory?: string;
  765. workspaceRoot?: string;
  766. } = {},
  767. ): ToolExecutionContext {
  768. return {
  769. toolCallId: "tool_test",
  770. traceId: "trace_test",
  771. spanId: "span_test",
  772. abortSignal: new AbortController().signal,
  773. fileSystemPort,
  774. readFileState: options.readFileState,
  775. workingDirectory: options.workingDirectory ?? tmpDir,
  776. workspaceRoot: options.workspaceRoot ?? tmpDir,
  777. sessionId: "sess_test",
  778. turnId: "turn_test",
  779. };
  780. }
  781. function createReadFileState(
  782. filePath: string,
  783. content: string,
  784. options: {
  785. isPartialView?: boolean;
  786. limit?: number;
  787. mtimeMs?: number;
  788. offset?: number;
  789. readAt?: Date;
  790. revisionContent?: string;
  791. } = {},
  792. ): ReadFileStateMap {
  793. const revisionContent = options.revisionContent ?? content;
  794. return new Map([
  795. [
  796. createReadFileStatePathKey(filePath),
  797. {
  798. path: filePath,
  799. content,
  800. offset: options.offset,
  801. limit: options.limit,
  802. isPartialView: options.isPartialView ?? false,
  803. readAt: options.readAt ?? new Date(),
  804. revisionId: revisionFor(filePath, revisionContent, options.mtimeMs ?? 1).id,
  805. mtimeMs: options.mtimeMs ?? 1,
  806. sizeBytes: Buffer.byteLength(revisionContent, "utf8"),
  807. },
  808. ],
  809. ]);
  810. }
  811. interface MemoryFileSystem extends FileSystemPort {
  812. files: Map<string, string>;
  813. lastWrite?: FileSystemWriteTextRequest;
  814. sizes: Map<string, number>;
  815. mtimes: Map<string, number>;
  816. setMtime(path: string, mtimeMs: number): void;
  817. touch(path: string): void;
  818. }
  819. function createMemoryFileSystem(initial: Record<string, string>): MemoryFileSystem {
  820. const files = new Map(Object.entries(initial));
  821. const sizes = new Map<string, number>();
  822. const mtimes = new Map<string, number>();
  823. const fs: MemoryFileSystem = {
  824. files,
  825. sizes,
  826. mtimes,
  827. setMtime(path, mtimeMs) {
  828. mtimes.set(path, mtimeMs);
  829. },
  830. touch(path) {
  831. mtimes.set(path, (mtimes.get(path) ?? 1) + 1);
  832. },
  833. async stat(request): Promise<FileSystemStatResult> {
  834. const content = files.get(request.path);
  835. if (content === undefined) throw missingFile(request.path);
  836. const mtimeMs = mtimes.get(request.path) ?? 1;
  837. return {
  838. kind: "file",
  839. path: request.path,
  840. revision: revisionFor(request.path, content, mtimeMs),
  841. sizeBytes: sizes.get(request.path) ?? Buffer.byteLength(content, "utf8"),
  842. mtimeMs,
  843. };
  844. },
  845. async readTextFile(request): Promise<FileSystemReadTextResult> {
  846. const content = readTextOrThrow(request.path, files);
  847. const mtimeMs = mtimes.get(request.path) ?? 1;
  848. return {
  849. bytesRead: Buffer.byteLength(content, "utf8"),
  850. content: normalizeLineEndings(content),
  851. encoding: request.encoding ?? "utf8",
  852. lineEndings: detectLineEndings(content),
  853. path: request.path,
  854. revision: revisionFor(request.path, content, mtimeMs),
  855. sizeBytes: sizes.get(request.path) ?? Buffer.byteLength(content, "utf8"),
  856. truncated: false,
  857. };
  858. },
  859. async readBinaryFile(request) {
  860. const content = readTextOrThrow(request.path, files);
  861. const buffer = Buffer.from(content, "utf8");
  862. return {
  863. bytesRead: buffer.byteLength,
  864. content: buffer,
  865. path: request.path,
  866. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  867. sizeBytes: buffer.byteLength,
  868. };
  869. },
  870. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  871. const content = readTextOrThrow(request.path, files);
  872. const normalized = normalizeLineEndings(content);
  873. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  874. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  875. const limitLines =
  876. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  877. const selected =
  878. limitLines === undefined
  879. ? lines.slice(offsetLine)
  880. : lines.slice(offsetLine, offsetLine + limitLines);
  881. return {
  882. bytesRead: Buffer.byteLength(content, "utf8"),
  883. content: selected.join("\n"),
  884. encoding: request.encoding ?? "utf8",
  885. lineCount: selected.length,
  886. lineEndings: detectLineEndings(content),
  887. path: request.path,
  888. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  889. sizeBytes: Buffer.byteLength(content, "utf8"),
  890. startLine: offsetLine + 1,
  891. totalLines: lines.length,
  892. truncated: false,
  893. };
  894. },
  895. async writeTextFile(request) {
  896. const content = applyLineEndings(request.content, request.lineEndings);
  897. fs.lastWrite = request;
  898. files.set(request.path, content);
  899. fs.touch(request.path);
  900. return {
  901. bytesWritten: Buffer.byteLength(content, "utf8"),
  902. path: request.path,
  903. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  904. };
  905. },
  906. async removeFile(request) {
  907. const removed = files.delete(request.path);
  908. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  909. return { path: request.path, removed };
  910. },
  911. async listDirectory(request) {
  912. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  913. const entries = Array.from(files.keys())
  914. .filter((path) => path.startsWith(prefix))
  915. .map((path) => ({
  916. kind: "file" as const,
  917. name: path.slice(prefix.length),
  918. path,
  919. }));
  920. return { durationMs: 0, entries, numEntries: entries.length, path: request.path };
  921. },
  922. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  923. return {
  924. durationMs: 0,
  925. files: [],
  926. numFiles: 0,
  927. path: request.path,
  928. pattern: request.pattern,
  929. truncated: false,
  930. };
  931. },
  932. async searchText(request): Promise<FileSystemSearchTextResult> {
  933. return {
  934. durationMs: 0,
  935. entries: [],
  936. files: [],
  937. mode: request.outputMode ?? "files_with_matches",
  938. numMatches: 0,
  939. path: request.path,
  940. pattern: request.pattern,
  941. truncated: false,
  942. };
  943. },
  944. };
  945. return fs;
  946. }
  947. function readTextOrThrow(path: string, files: Map<string, string>): string {
  948. const content = files.get(path);
  949. if (content === undefined) throw missingFile(path);
  950. return content;
  951. }
  952. function missingFile(path: string): Error {
  953. return createFileSystemError({ code: "not_found", message: `missing: ${path}`, path });
  954. }
  955. function normalizeLineEndings(content: string): string {
  956. return content.replaceAll("\r\n", "\n");
  957. }
  958. function applyLineEndings(content: string, lineEndings: FileSystemLineEndings | undefined): string {
  959. if (lineEndings !== "CRLF") return content;
  960. return content.replaceAll("\r\n", "\n").split("\n").join("\r\n");
  961. }
  962. function detectLineEndings(content: string): "LF" | "CRLF" {
  963. let crlfCount = 0;
  964. let lfCount = 0;
  965. for (let index = 0; index < content.length; index += 1) {
  966. if (content[index] !== "\n") continue;
  967. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  968. else lfCount += 1;
  969. }
  970. return crlfCount > lfCount ? "CRLF" : "LF";
  971. }
  972. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  973. return {
  974. id: `rev:${path}:${content.length}:${Buffer.byteLength(content, "utf8")}:${mtimeMs}`,
  975. mtimeMs,
  976. sizeBytes: Buffer.byteLength(content, "utf8"),
  977. };
  978. }