edit-tool-contract.test.ts 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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 { createReadFileStateKey } 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. createReadFileStateKey(file, 1, undefined),
  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. expect(content).not.toContain("file state is current in your context");
  222. expect(content).not.toContain("no need to Read it back");
  223. });
  224. it("rejects no-op edits before filesystem access", async () => {
  225. await expect(
  226. editHandler(
  227. { file_path: join(tmpDir, "anything.txt"), old_string: "same", new_string: "same" },
  228. contextWith(createMemoryFileSystem({})),
  229. ),
  230. ).resolves.toEqual({
  231. result: false,
  232. errorCode: 1,
  233. message: "No changes to make: old_string and new_string are exactly the same.",
  234. });
  235. });
  236. it("returns a tool-owned error for an empty file path", async () => {
  237. const fs = createMemoryFileSystem({});
  238. const statSpy = vi.spyOn(fs, "stat");
  239. const toolCall: ExecutableToolCall = {
  240. id: "tool_empty_edit_path",
  241. input: {
  242. file_path: "",
  243. old_string: "before",
  244. new_string: "after",
  245. },
  246. name: "Edit",
  247. };
  248. const failure = await editHandler(toolCall.input, contextWith(fs));
  249. expect(failure).toEqual({
  250. result: false,
  251. errorCode: 13,
  252. message: "Tool path must not be empty",
  253. });
  254. expect(statSpy).not.toHaveBeenCalled();
  255. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  256. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  257. expect(result.error).toMatchObject({
  258. code: "13",
  259. message: "Tool path must not be empty",
  260. });
  261. expect(result.modelContent).toBe(
  262. "<tool_use_error>Tool path must not be empty</tool_use_error>",
  263. );
  264. });
  265. it("wraps a tool-owned code + message only for the model", async () => {
  266. const toolCall: ExecutableToolCall = {
  267. id: "tool_test",
  268. input: {
  269. file_path: "/work/noop.txt",
  270. old_string: "same",
  271. new_string: "same",
  272. },
  273. name: "Edit",
  274. };
  275. const failure = await editHandler(toolCall.input, contextWith(createMemoryFileSystem({})));
  276. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  277. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  278. expect(result.error?.message).toBe(
  279. "No changes to make: old_string and new_string are exactly the same.",
  280. );
  281. expect(result.modelContent).toBe(
  282. "<tool_use_error>No changes to make: old_string and new_string are exactly the same.</tool_use_error>",
  283. );
  284. });
  285. it("preserves raw multiline Edit error text in model-facing tool_result content", async () => {
  286. const file = join(tmpDir, "missing-string.txt");
  287. const oldString = "first line\nsecond line\n" + "x".repeat(520);
  288. const fs = createMemoryFileSystem({ [file]: "available content" });
  289. const toolCall: ExecutableToolCall = {
  290. id: "tool_test",
  291. input: {
  292. file_path: file,
  293. old_string: oldString,
  294. new_string: "replacement",
  295. },
  296. name: "Edit",
  297. };
  298. const rawMessage =
  299. "String to replace not found in file.\nString: first line\nsecond line\n" + "x".repeat(520);
  300. const failure = await editHandler(
  301. toolCall.input,
  302. contextWith(fs, {
  303. readFileState: createReadFileState(file, "available content"),
  304. }),
  305. );
  306. expect(failure).toEqual({
  307. result: false,
  308. errorCode: 8,
  309. message: rawMessage,
  310. });
  311. if (!isToolHandlerFailure(failure)) throw new Error("Expected Edit handler to fail");
  312. const result = createErrorResult(toolCall, createToolHandlerFailureError(toolCall, failure));
  313. expect(result.error?.message).not.toBe(rawMessage);
  314. expect(result.modelContent).toBe(`<tool_use_error>${rawMessage}</tool_use_error>`);
  315. });
  316. it("does not misclassify unexpected Edit exceptions as tool-owned failures", () => {
  317. const result = createErrorResult(
  318. {
  319. id: "tool_edit_race",
  320. input: {
  321. file_path: "/work/race.txt",
  322. old_string: "before",
  323. new_string: "after",
  324. },
  325. name: "Edit",
  326. },
  327. new Error("File write failed"),
  328. );
  329. expect(result.error?.message).toBe("File write failed");
  330. expect(result.modelContent).toBeUndefined();
  331. });
  332. it("returns missing-file messages with cwd and similar filename suggestions", async () => {
  333. const existing = join(tmpDir, "component.ts");
  334. const missing = join(tmpDir, "component.js");
  335. const fs = createMemoryFileSystem({ [existing]: "export const value = 1\n" });
  336. await expect(
  337. editHandler(
  338. { file_path: missing, old_string: "value", new_string: "renamed" },
  339. contextWith(fs),
  340. ),
  341. ).resolves.toMatchObject({
  342. result: false,
  343. errorCode: 4,
  344. message: `File does not exist. Note: your current working directory is ${tmpDir}. Did you mean component.ts?`,
  345. });
  346. });
  347. it("rejects empty old_string for an existing nonempty file", async () => {
  348. const file = join(tmpDir, "nonempty.txt");
  349. const fs = createMemoryFileSystem({ [file]: "already here" });
  350. await expect(
  351. editHandler({ file_path: file, old_string: "", new_string: "replacement" }, contextWith(fs)),
  352. ).resolves.toMatchObject({
  353. result: false,
  354. errorCode: 3,
  355. message: "Cannot create new file - file already exists.",
  356. });
  357. });
  358. it("rejects notebooks in favor of NotebookEdit", async () => {
  359. const file = join(tmpDir, "notebook.ipynb");
  360. const fs = createMemoryFileSystem({ [file]: '{"cells":[]}' });
  361. const context = contextWith(fs, { readFileState: createReadFileState(file, '{"cells":[]}') });
  362. await expect(
  363. editHandler({ file_path: file, old_string: "cells", new_string: "metadata" }, context),
  364. ).resolves.toMatchObject({
  365. result: false,
  366. errorCode: 5,
  367. message: "File is a Jupyter Notebook. Use the NotebookEdit to edit this file.",
  368. });
  369. });
  370. it("requires existing nonempty files to be read before editing", async () => {
  371. const file = join(tmpDir, "unread.txt");
  372. const fs = createMemoryFileSystem({ [file]: "old content" });
  373. await expect(
  374. editHandler(
  375. { file_path: file, old_string: "old", new_string: "new" },
  376. contextWith(fs, { readFileState: new Map() }),
  377. ),
  378. ).resolves.toMatchObject({
  379. result: false,
  380. errorCode: 6,
  381. message: "File has not been read yet. Read it first before writing to it.",
  382. });
  383. });
  384. it("rejects token-truncated partial views even when the file is unchanged", async () => {
  385. const file = join(tmpDir, "partial-view.txt");
  386. const fs = createMemoryFileSystem({ [file]: "line one\nline two\n" });
  387. const context = contextWith(fs, {
  388. readFileState: createReadFileState(file, "line one", {
  389. isPartialView: true,
  390. limit: 1,
  391. revisionContent: "line one\nline two\n",
  392. }),
  393. });
  394. await expect(
  395. editHandler({ file_path: file, old_string: "line two", new_string: "line 2" }, context),
  396. ).resolves.toMatchObject({
  397. result: false,
  398. errorCode: 6,
  399. message: "File has not been read yet. Read it first before writing to it.",
  400. });
  401. });
  402. it("uses the latest same-file range read state after an older full read becomes stale", async () => {
  403. const file = join(tmpDir, "latest-range.txt");
  404. const fs = createMemoryFileSystem({ [file]: "line one\nline two\n" });
  405. fs.setMtime(file, 3);
  406. const readFileState = createReadFileState(file, "outdated\nline two\n", {
  407. mtimeMs: 1,
  408. readAt: new Date(1),
  409. });
  410. const latestRevision = revisionFor(file, "line one\nline two\n", 3);
  411. readFileState.set(createReadFileStateKey(file, 2, 1), {
  412. path: file,
  413. content: "line two",
  414. offset: 2,
  415. limit: 1,
  416. isPartialView: false,
  417. readAt: new Date(2),
  418. revisionId: latestRevision.id,
  419. mtimeMs: latestRevision.mtimeMs,
  420. sizeBytes: latestRevision.sizeBytes,
  421. });
  422. await expect(
  423. editHandler(
  424. { file_path: file, old_string: "line two", new_string: "line 2" },
  425. contextWith(fs, { readFileState }),
  426. ),
  427. ).resolves.toMatchObject({ filePath: file });
  428. expect(fs.files.get(file)).toBe("line one\nline 2\n");
  429. });
  430. it("allows sub-millisecond mtime drift for partial read freshness", async () => {
  431. const file = join(tmpDir, "mtime-sub-ms-partial.txt");
  432. const fs = createMemoryFileSystem({ [file]: "target content" });
  433. fs.setMtime(file, 1000.8);
  434. const context = contextWith(fs, {
  435. readFileState: createReadFileState(file, "target", {
  436. limit: 1,
  437. mtimeMs: 1000.2,
  438. offset: 1,
  439. revisionContent: "target content",
  440. }),
  441. });
  442. await expect(
  443. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  444. ).resolves.toMatchObject({ filePath: file });
  445. expect(fs.files.get(file)).toBe("updated content");
  446. });
  447. it("rejects range reads when normalized mtime advances", async () => {
  448. const file = join(tmpDir, "mtime-advanced-range.txt");
  449. const fs = createMemoryFileSystem({ [file]: "target content" });
  450. fs.setMtime(file, 1001);
  451. const context = contextWith(fs, {
  452. readFileState: createReadFileState(file, "target", {
  453. limit: 1,
  454. mtimeMs: 1000.9,
  455. revisionContent: "target content",
  456. }),
  457. });
  458. await expect(
  459. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  460. ).resolves.toMatchObject({
  461. result: false,
  462. errorCode: 7,
  463. message:
  464. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  465. });
  466. });
  467. it("rejects range reads when file size changes inside the same millisecond", async () => {
  468. const file = join(tmpDir, "size-changed-range.txt");
  469. const fs = createMemoryFileSystem({ [file]: "target content" });
  470. fs.files.set(file, "target content!");
  471. fs.setMtime(file, 1000.8);
  472. const context = contextWith(fs, {
  473. readFileState: createReadFileState(file, "target", {
  474. limit: 1,
  475. mtimeMs: 1000.2,
  476. revisionContent: "target content",
  477. }),
  478. });
  479. await expect(
  480. editHandler({ file_path: file, old_string: "target", new_string: "updated" }, context),
  481. ).resolves.toMatchObject({
  482. result: false,
  483. errorCode: 7,
  484. message:
  485. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  486. });
  487. });
  488. it("rejects stale edits when content changed after the cached read", async () => {
  489. const file = join(tmpDir, "stale.txt");
  490. const fs = createMemoryFileSystem({ [file]: "old content" });
  491. const context = contextWith(fs, { readFileState: createReadFileState(file, "old content") });
  492. fs.files.set(file, "old content changed elsewhere");
  493. fs.touch(file);
  494. await expect(
  495. editHandler({ file_path: file, old_string: "old", new_string: "new" }, context),
  496. ).resolves.toMatchObject({
  497. result: false,
  498. errorCode: 7,
  499. message:
  500. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  501. });
  502. });
  503. it("allows mtime-only changes for offset-1 full reads but rejects later range stale fallbacks", async () => {
  504. const fullReadFile = join(tmpDir, "mtime-only.txt");
  505. const offsetOneReadFile = join(tmpDir, "mtime-offset-one.txt");
  506. const offsetRangeReadFile = join(tmpDir, "mtime-offset-range.txt");
  507. const fs = createMemoryFileSystem({
  508. [fullReadFile]: "target content",
  509. [offsetOneReadFile]: "target content",
  510. [offsetRangeReadFile]: "target content",
  511. });
  512. const fullContext = contextWith(fs, {
  513. readFileState: createReadFileState(fullReadFile, "target content", { mtimeMs: 1 }),
  514. });
  515. fs.setMtime(fullReadFile, 2);
  516. await expect(
  517. editHandler(
  518. { file_path: fullReadFile, old_string: "target", new_string: "updated" },
  519. fullContext,
  520. ),
  521. ).resolves.toMatchObject({ filePath: fullReadFile });
  522. const offsetOneContext = contextWith(fs, {
  523. readFileState: createReadFileState(offsetOneReadFile, "target content", {
  524. offset: 1,
  525. mtimeMs: 1,
  526. }),
  527. });
  528. fs.setMtime(offsetOneReadFile, 2);
  529. await expect(
  530. editHandler(
  531. { file_path: offsetOneReadFile, old_string: "target", new_string: "updated" },
  532. offsetOneContext,
  533. ),
  534. ).resolves.toMatchObject({ filePath: offsetOneReadFile });
  535. const offsetRangeContext = contextWith(fs, {
  536. readFileState: createReadFileState(offsetRangeReadFile, "target content", {
  537. offset: 2,
  538. mtimeMs: 1,
  539. }),
  540. });
  541. fs.setMtime(offsetRangeReadFile, 2);
  542. await expect(
  543. editHandler(
  544. { file_path: offsetRangeReadFile, old_string: "target", new_string: "updated" },
  545. offsetRangeContext,
  546. ),
  547. ).resolves.toMatchObject({
  548. result: false,
  549. errorCode: 7,
  550. message:
  551. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  552. });
  553. });
  554. it("returns old_string not found and ambiguous-match messages", async () => {
  555. const missingFile = join(tmpDir, "missing-string.txt");
  556. const ambiguousFile = join(tmpDir, "ambiguous.txt");
  557. const fs = createMemoryFileSystem({
  558. [missingFile]: "available content",
  559. [ambiguousFile]: "name\nname\n",
  560. });
  561. await expect(
  562. editHandler(
  563. { file_path: missingFile, old_string: "not present", new_string: "replacement" },
  564. contextWith(fs, { readFileState: createReadFileState(missingFile, "available content") }),
  565. ),
  566. ).resolves.toMatchObject({
  567. result: false,
  568. errorCode: 8,
  569. message: "String to replace not found in file.\nString: not present",
  570. });
  571. await expect(
  572. editHandler(
  573. { file_path: ambiguousFile, old_string: "name", new_string: "label" },
  574. contextWith(fs, { readFileState: createReadFileState(ambiguousFile, "name\nname\n") }),
  575. ),
  576. ).resolves.toMatchObject({
  577. result: false,
  578. errorCode: 9,
  579. message:
  580. "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",
  581. });
  582. });
  583. it("matches unicode escape old_string against decoded file content", async () => {
  584. const file = join(tmpDir, "unicode-escape.txt");
  585. const fs = createMemoryFileSystem({ [file]: "<tag>value</tag>\n" });
  586. const output = await editHandler(
  587. { file_path: file, old_string: "\\u003Ctag\\u003E", new_string: "<node>" },
  588. contextWith(fs, { readFileState: createReadFileState(file, "<tag>value</tag>\n") }),
  589. );
  590. expect(output.oldString).toBe("<tag>");
  591. expect(fs.files.get(file)).toBe("<node>value</tag>\n");
  592. });
  593. it("adds Edit performance attribution with patch matching statistics", async () => {
  594. const file = join(tmpDir, "perf-edit.txt");
  595. const fs = createMemoryFileSystem({ [file]: "alpha\nbeta\n" });
  596. const byteLength = Buffer.byteLength;
  597. let newContentByteCountCalls = 0;
  598. const byteLengthSpy = vi.spyOn(Buffer, "byteLength").mockImplementation((value, encoding) => {
  599. if (value === "alpha\ngamma\n" && encoding === "utf8") {
  600. newContentByteCountCalls += 1;
  601. }
  602. return byteLength(value, encoding);
  603. });
  604. try {
  605. const output = await editHandler(
  606. { file_path: file, old_string: "beta", new_string: "gamma" },
  607. contextWith(fs, { readFileState: createReadFileState(file, "alpha\nbeta\n") }),
  608. );
  609. expect(output).toMatchObject({
  610. filePath: file,
  611. perf: {
  612. detail: {
  613. kind: "patch",
  614. filesystem: {
  615. readMs: expect.any(Number),
  616. writeMs: expect.any(Number),
  617. fileCount: 1,
  618. totalBytes: byteLength("alpha\ngamma\n", "utf8"),
  619. maxFileBytes: byteLength("alpha\ngamma\n", "utf8"),
  620. workspaceKind: "local",
  621. },
  622. patch: {
  623. matchMs: expect.any(Number),
  624. hunkCount: 1,
  625. matchAttempts: 1,
  626. },
  627. },
  628. },
  629. });
  630. // 内存 FS 写入和 revision 计算会读取新内容大小;这里约束 perf 字段只额外计算一次。
  631. expect(newContentByteCountCalls).toBe(4);
  632. expect(JSON.stringify((output as any).perf)).not.toContain(file);
  633. expect(JSON.stringify((output as any).perf)).not.toContain("gamma");
  634. } finally {
  635. byteLengthSpy.mockRestore();
  636. }
  637. });
  638. it("rejects files larger than the edit limit before reading them", async () => {
  639. const file = join(tmpDir, "huge.txt");
  640. const fs = createMemoryFileSystem({ [file]: "old" });
  641. fs.sizes.set(file, 1024 * 1024 * 1024 + 1);
  642. await expect(
  643. editHandler({ file_path: file, old_string: "old", new_string: "new" }, contextWith(fs)),
  644. ).resolves.toMatchObject({
  645. result: false,
  646. errorCode: 10,
  647. message: "File is too large to edit (1GB). Maximum editable file size is 1GB.",
  648. });
  649. });
  650. it("coerces semantic boolean strings for replace_all and requires originalFile to be a string", async () => {
  651. expect(
  652. EditInputSchema.parse({
  653. file_path: "/tmp/example.txt",
  654. old_string: "old",
  655. new_string: "new",
  656. replace_all: "false",
  657. }),
  658. ).toMatchObject({ replace_all: false });
  659. const file = join(tmpDir, "string-true.txt");
  660. const fs = createMemoryFileSystem({ [file]: "foo\nfoo\n" });
  661. const output = await editHandler(
  662. { file_path: file, old_string: "foo", new_string: "bar", replace_all: "true" },
  663. contextWith(fs, { readFileState: createReadFileState(file, "foo\nfoo\n") }),
  664. );
  665. expect(fs.files.get(file)).toBe("bar\nbar\n");
  666. expect(typeof output.originalFile).toBe("string");
  667. expect(() =>
  668. EditOutputSchema.parse({
  669. filePath: file,
  670. oldString: "old",
  671. newString: "new",
  672. originalFile: null,
  673. structuredPatch: [],
  674. userModified: false,
  675. replaceAll: false,
  676. }),
  677. ).toThrow();
  678. });
  679. it("honors Edit deny rules before filesystem access", () => {
  680. const service = new PermissionService(defaultPermissionConfig);
  681. const file = join(tmpDir, "blocked", "secret.txt");
  682. const projectRules: PermissionRuleset = {
  683. version: 1,
  684. deny: [
  685. {
  686. toolName: "Edit",
  687. ruleContent: `${tmpDir}/blocked/*`,
  688. },
  689. ],
  690. };
  691. const decision = service.checkPermission(
  692. {
  693. input: {
  694. file_path: file,
  695. old_string: "secret",
  696. new_string: "redacted",
  697. },
  698. mode: "edit",
  699. riskLevel: editToolEntry.metadata.riskLevel,
  700. toolName: "Edit",
  701. },
  702. {
  703. ...editToolEntry.metadata,
  704. permission: editToolEntry.permission,
  705. },
  706. projectRules,
  707. );
  708. expect(decision).toMatchObject({
  709. allowed: false,
  710. decision: "deny",
  711. });
  712. });
  713. });
  714. function contextWith(
  715. fileSystemPort: MemoryFileSystem,
  716. options: {
  717. readFileState?: ReadFileStateMap;
  718. workingDirectory?: string;
  719. workspaceRoot?: string;
  720. } = {},
  721. ): ToolExecutionContext {
  722. return {
  723. toolCallId: "tool_test",
  724. traceId: "trace_test",
  725. spanId: "span_test",
  726. abortSignal: new AbortController().signal,
  727. fileSystemPort,
  728. readFileState: options.readFileState,
  729. workingDirectory: options.workingDirectory ?? tmpDir,
  730. workspaceRoot: options.workspaceRoot ?? tmpDir,
  731. sessionId: "sess_test",
  732. turnId: "turn_test",
  733. };
  734. }
  735. function createReadFileState(
  736. filePath: string,
  737. content: string,
  738. options: {
  739. isPartialView?: boolean;
  740. limit?: number;
  741. mtimeMs?: number;
  742. offset?: number;
  743. readAt?: Date;
  744. revisionContent?: string;
  745. } = {},
  746. ): ReadFileStateMap {
  747. const revisionContent = options.revisionContent ?? content;
  748. return new Map([
  749. [
  750. [
  751. filePath,
  752. String(options.offset ?? 1),
  753. options.limit === undefined ? "" : String(options.limit),
  754. ].join("\0"),
  755. {
  756. path: filePath,
  757. content,
  758. offset: options.offset,
  759. limit: options.limit,
  760. isPartialView: options.isPartialView ?? false,
  761. readAt: options.readAt ?? new Date(),
  762. revisionId: revisionFor(filePath, revisionContent, options.mtimeMs ?? 1).id,
  763. mtimeMs: options.mtimeMs ?? 1,
  764. sizeBytes: Buffer.byteLength(revisionContent, "utf8"),
  765. },
  766. ],
  767. ]);
  768. }
  769. interface MemoryFileSystem extends FileSystemPort {
  770. files: Map<string, string>;
  771. lastWrite?: FileSystemWriteTextRequest;
  772. sizes: Map<string, number>;
  773. mtimes: Map<string, number>;
  774. setMtime(path: string, mtimeMs: number): void;
  775. touch(path: string): void;
  776. }
  777. function createMemoryFileSystem(initial: Record<string, string>): MemoryFileSystem {
  778. const files = new Map(Object.entries(initial));
  779. const sizes = new Map<string, number>();
  780. const mtimes = new Map<string, number>();
  781. const fs: MemoryFileSystem = {
  782. files,
  783. sizes,
  784. mtimes,
  785. setMtime(path, mtimeMs) {
  786. mtimes.set(path, mtimeMs);
  787. },
  788. touch(path) {
  789. mtimes.set(path, (mtimes.get(path) ?? 1) + 1);
  790. },
  791. async stat(request): Promise<FileSystemStatResult> {
  792. const content = files.get(request.path);
  793. if (content === undefined) throw missingFile(request.path);
  794. const mtimeMs = mtimes.get(request.path) ?? 1;
  795. return {
  796. kind: "file",
  797. path: request.path,
  798. revision: revisionFor(request.path, content, mtimeMs),
  799. sizeBytes: sizes.get(request.path) ?? Buffer.byteLength(content, "utf8"),
  800. mtimeMs,
  801. };
  802. },
  803. async readTextFile(request): Promise<FileSystemReadTextResult> {
  804. const content = readTextOrThrow(request.path, files);
  805. const mtimeMs = mtimes.get(request.path) ?? 1;
  806. return {
  807. bytesRead: Buffer.byteLength(content, "utf8"),
  808. content: normalizeLineEndings(content),
  809. encoding: request.encoding ?? "utf8",
  810. lineEndings: detectLineEndings(content),
  811. path: request.path,
  812. revision: revisionFor(request.path, content, mtimeMs),
  813. sizeBytes: sizes.get(request.path) ?? Buffer.byteLength(content, "utf8"),
  814. truncated: false,
  815. };
  816. },
  817. async readBinaryFile(request) {
  818. const content = readTextOrThrow(request.path, files);
  819. const buffer = Buffer.from(content, "utf8");
  820. return {
  821. bytesRead: buffer.byteLength,
  822. content: buffer,
  823. path: request.path,
  824. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  825. sizeBytes: buffer.byteLength,
  826. };
  827. },
  828. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  829. const content = readTextOrThrow(request.path, files);
  830. const normalized = normalizeLineEndings(content);
  831. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  832. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  833. const limitLines =
  834. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  835. const selected =
  836. limitLines === undefined
  837. ? lines.slice(offsetLine)
  838. : lines.slice(offsetLine, offsetLine + limitLines);
  839. return {
  840. bytesRead: Buffer.byteLength(content, "utf8"),
  841. content: selected.join("\n"),
  842. encoding: request.encoding ?? "utf8",
  843. lineCount: selected.length,
  844. lineEndings: detectLineEndings(content),
  845. path: request.path,
  846. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  847. sizeBytes: Buffer.byteLength(content, "utf8"),
  848. startLine: offsetLine + 1,
  849. totalLines: lines.length,
  850. truncated: false,
  851. };
  852. },
  853. async writeTextFile(request) {
  854. const content = applyLineEndings(request.content, request.lineEndings);
  855. fs.lastWrite = request;
  856. files.set(request.path, content);
  857. fs.touch(request.path);
  858. return {
  859. bytesWritten: Buffer.byteLength(content, "utf8"),
  860. path: request.path,
  861. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  862. };
  863. },
  864. async removeFile(request) {
  865. const removed = files.delete(request.path);
  866. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  867. return { path: request.path, removed };
  868. },
  869. async listDirectory(request) {
  870. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  871. const entries = Array.from(files.keys())
  872. .filter((path) => path.startsWith(prefix))
  873. .map((path) => ({
  874. kind: "file" as const,
  875. name: path.slice(prefix.length),
  876. path,
  877. }));
  878. return { durationMs: 0, entries, numEntries: entries.length, path: request.path };
  879. },
  880. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  881. return {
  882. durationMs: 0,
  883. files: [],
  884. numFiles: 0,
  885. path: request.path,
  886. pattern: request.pattern,
  887. truncated: false,
  888. };
  889. },
  890. async searchText(request): Promise<FileSystemSearchTextResult> {
  891. return {
  892. durationMs: 0,
  893. entries: [],
  894. files: [],
  895. mode: request.outputMode ?? "files_with_matches",
  896. numMatches: 0,
  897. path: request.path,
  898. pattern: request.pattern,
  899. truncated: false,
  900. };
  901. },
  902. };
  903. return fs;
  904. }
  905. function readTextOrThrow(path: string, files: Map<string, string>): string {
  906. const content = files.get(path);
  907. if (content === undefined) throw missingFile(path);
  908. return content;
  909. }
  910. function missingFile(path: string): Error {
  911. return createFileSystemError({ code: "not_found", message: `missing: ${path}`, path });
  912. }
  913. function normalizeLineEndings(content: string): string {
  914. return content.replaceAll("\r\n", "\n");
  915. }
  916. function applyLineEndings(content: string, lineEndings: FileSystemLineEndings | undefined): string {
  917. if (lineEndings !== "CRLF") return content;
  918. return content.replaceAll("\r\n", "\n").split("\n").join("\r\n");
  919. }
  920. function detectLineEndings(content: string): "LF" | "CRLF" {
  921. let crlfCount = 0;
  922. let lfCount = 0;
  923. for (let index = 0; index < content.length; index += 1) {
  924. if (content[index] !== "\n") continue;
  925. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  926. else lfCount += 1;
  927. }
  928. return crlfCount > lfCount ? "CRLF" : "LF";
  929. }
  930. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  931. return {
  932. id: `rev:${path}:${content.length}:${Buffer.byteLength(content, "utf8")}:${mtimeMs}`,
  933. mtimeMs,
  934. sizeBytes: Buffer.byteLength(content, "utf8"),
  935. };
  936. }