edit-tool-contract.test.ts 35 KB

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