tool-edit.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { fileURLToPath } from "url"
  4. import { describe, expect, test } from "bun:test"
  5. import { Effect, Layer } from "effect"
  6. import { FileMutation } from "@opencode-ai/core/file-mutation"
  7. import { FSUtil } from "@opencode-ai/core/fs-util"
  8. import { Location } from "@opencode-ai/core/location"
  9. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  10. import { PermissionV2 } from "@opencode-ai/core/permission"
  11. import { AbsolutePath } from "@opencode-ai/core/schema"
  12. import { SessionV2 } from "@opencode-ai/core/session"
  13. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  14. import { EditTool } from "@opencode-ai/core/tool/edit"
  15. import { location } from "./fixture/location"
  16. import { tmpdir } from "./fixture/tmpdir"
  17. import { testEffect } from "./lib/effect"
  18. import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool"
  19. const sessionID = SessionV2.ID.make("ses_edit_tool_test")
  20. const assertions: PermissionV2.AssertInput[] = []
  21. const writes: string[] = []
  22. let reads = 0
  23. let denyAction: string | undefined
  24. let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
  25. const permission = Layer.succeed(
  26. PermissionV2.Service,
  27. PermissionV2.Service.of({
  28. assert: (input) =>
  29. Effect.sync(() => assertions.push(input)).pipe(
  30. Effect.andThen(
  31. input.action === denyAction ? Effect.fail(new PermissionV2.DeniedError({ rules: [] })) : Effect.void,
  32. ),
  33. ),
  34. ask: () => Effect.die("unused"),
  35. reply: () => Effect.die("unused"),
  36. get: () => Effect.die("unused"),
  37. forSession: () => Effect.die("unused"),
  38. list: () => Effect.die("unused"),
  39. }),
  40. )
  41. const reset = () => {
  42. assertions.length = 0
  43. writes.length = 0
  44. reads = 0
  45. denyAction = undefined
  46. afterRead = () => Effect.void
  47. }
  48. const filesystem = Layer.effect(
  49. FSUtil.Service,
  50. Effect.gen(function* () {
  51. const fs = yield* FSUtil.Service
  52. return FSUtil.Service.of({
  53. ...fs,
  54. readFile: (target) =>
  55. fs
  56. .readFile(target)
  57. .pipe(
  58. Effect.tap((content) =>
  59. Effect.sync(() => reads++).pipe(Effect.andThen(Effect.suspend(() => afterRead(target, content)))),
  60. ),
  61. ),
  62. writeWithDirs: (target, content, mode) =>
  63. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeWithDirs(target, content, mode))),
  64. writeFile: (target, content, options) =>
  65. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeFile(target, content, options))),
  66. writeFileString: (target, content, options) =>
  67. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeFileString(target, content, options))),
  68. })
  69. }),
  70. ).pipe(Layer.provide(FSUtil.defaultLayer))
  71. const withTool = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) => {
  72. const activeLocation = Layer.succeed(
  73. Location.Service,
  74. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  75. )
  76. const resolution = LocationMutation.layer.pipe(Layer.provide(filesystem), Layer.provide(activeLocation))
  77. const mutation = FileMutation.layer.pipe(Layer.provide(filesystem))
  78. const registry = ToolRegistry.defaultLayer.pipe(Layer.provide(permission))
  79. const edit = EditTool.layer.pipe(
  80. Layer.provide(registry),
  81. Layer.provide(permission),
  82. Layer.provide(resolution),
  83. Layer.provide(mutation),
  84. Layer.provide(filesystem),
  85. )
  86. return Effect.gen(function* () {
  87. return yield* body(yield* ToolRegistry.Service)
  88. }).pipe(Effect.provide(Layer.mergeAll(registry, resolution, mutation, edit)))
  89. }
  90. const call = (input: typeof EditTool.Input.Type, id = "call-edit") => ({
  91. sessionID,
  92. ...toolIdentity,
  93. call: { type: "tool-call" as const, id, name: "edit", input },
  94. })
  95. const it = testEffect(Layer.empty)
  96. describe("EditTool", () => {
  97. it.live("registers and replaces relative exact text through FileMutation once", () =>
  98. Effect.acquireUseRelease(
  99. Effect.promise(() => tmpdir()),
  100. (tmp) => {
  101. reset()
  102. const target = path.join(tmp.path, "hello.txt")
  103. return Effect.promise(() => fs.writeFile(target, "before\nrest\n")).pipe(
  104. Effect.andThen(
  105. withTool(tmp.path, (registry) =>
  106. Effect.gen(function* () {
  107. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["edit"])
  108. expect(yield* toolDefinitions(registry, [{ action: "edit", resource: "*", effect: "deny" }])).toEqual(
  109. [],
  110. )
  111. const settled = yield* settleTool(
  112. registry,
  113. call({ path: "hello.txt", oldString: "before", newString: "after" }),
  114. )
  115. expect(settled.result).toEqual({
  116. type: "text",
  117. value: "Edited file successfully: hello.txt\nReplacements: 1\n```diff\n-before\n+after\n```",
  118. })
  119. expect(settled.output?.structured).toEqual({
  120. replacements: 1,
  121. files: [
  122. {
  123. file: "hello.txt",
  124. status: "modified",
  125. additions: 1,
  126. deletions: 1,
  127. patch: expect.stringContaining("-before\n+after"),
  128. },
  129. ],
  130. })
  131. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
  132. expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
  133. expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
  134. }),
  135. ),
  136. ),
  137. )
  138. },
  139. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  140. ),
  141. )
  142. it.live("accepts an absolute file path inside the active Location", () =>
  143. Effect.acquireUseRelease(
  144. Effect.promise(() => tmpdir()),
  145. (tmp) => {
  146. reset()
  147. const target = path.join(tmp.path, "absolute.txt")
  148. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  149. Effect.andThen(
  150. withTool(tmp.path, (registry) =>
  151. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  152. ),
  153. ),
  154. Effect.andThen((result) =>
  155. Effect.gen(function* () {
  156. expect(result.type).toBe("text")
  157. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  158. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  159. }),
  160. ),
  161. )
  162. },
  163. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  164. ),
  165. )
  166. it.live("approves an explicit external absolute path before edit", () =>
  167. Effect.acquireUseRelease(
  168. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  169. ([active, outside]) => {
  170. reset()
  171. const target = path.join(outside.path, "external.txt")
  172. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  173. Effect.andThen(
  174. withTool(active.path, (registry) =>
  175. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  176. ),
  177. ),
  178. Effect.andThen((result) =>
  179. Effect.gen(function* () {
  180. expect(result.type).toBe("text")
  181. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  182. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  183. expect(writes).toHaveLength(1)
  184. }),
  185. ),
  186. )
  187. },
  188. ([active, outside]) =>
  189. Effect.promise(() =>
  190. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  191. ),
  192. ),
  193. )
  194. it.live("does not write when external_directory or edit approval is denied", () =>
  195. Effect.acquireUseRelease(
  196. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  197. ([active, outside]) =>
  198. Effect.gen(function* () {
  199. const external = path.join(outside.path, "denied.txt")
  200. yield* Effect.promise(() => fs.writeFile(external, "before"))
  201. reset()
  202. denyAction = "external_directory"
  203. expect(
  204. yield* withTool(active.path, (registry) =>
  205. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  206. ),
  207. ).toEqual({
  208. type: "error",
  209. value: `Unable to edit ${external}`,
  210. })
  211. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  212. expect(reads).toBe(0)
  213. expect(writes).toEqual([])
  214. reset()
  215. denyAction = "edit"
  216. expect(
  217. yield* withTool(active.path, (registry) =>
  218. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  219. ),
  220. ).toEqual({
  221. type: "error",
  222. value: `Unable to edit ${external}`,
  223. })
  224. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  225. expect(reads).toBe(0)
  226. expect(writes).toEqual([])
  227. expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
  228. }),
  229. ([active, outside]) =>
  230. Effect.promise(() =>
  231. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  232. ),
  233. ),
  234. )
  235. it.live("denied edit reads no target content and does not disclose whether oldString matches", () =>
  236. Effect.acquireUseRelease(
  237. Effect.promise(() => tmpdir()),
  238. (tmp) => {
  239. reset()
  240. denyAction = "edit"
  241. const target = path.join(tmp.path, "secret.txt")
  242. return Effect.promise(() => fs.writeFile(target, "secret content")).pipe(
  243. Effect.andThen(
  244. withTool(tmp.path, (registry) =>
  245. Effect.gen(function* () {
  246. const matching = yield* executeTool(
  247. registry,
  248. call({ path: "secret.txt", oldString: "secret content", newString: "replacement" }),
  249. )
  250. const missing = yield* executeTool(
  251. registry,
  252. call({ path: "secret.txt", oldString: "not present", newString: "replacement" }),
  253. )
  254. expect(matching).toEqual({ type: "error", value: "Unable to edit secret.txt" })
  255. expect(missing).toEqual(matching)
  256. expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
  257. expect(reads).toBe(0)
  258. expect(writes).toEqual([])
  259. }),
  260. ),
  261. ),
  262. )
  263. },
  264. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  265. ),
  266. )
  267. it.live("rejects no-op, empty, missing, and ambiguous exact replacements", () =>
  268. Effect.acquireUseRelease(
  269. Effect.promise(() => tmpdir()),
  270. (tmp) => {
  271. reset()
  272. const target = path.join(tmp.path, "matches.txt")
  273. return Effect.promise(() => fs.writeFile(target, "same same")).pipe(
  274. Effect.andThen(
  275. withTool(tmp.path, (registry) =>
  276. Effect.gen(function* () {
  277. expect(
  278. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "same" })),
  279. ).toEqual({
  280. type: "error",
  281. value: "No changes to apply: oldString and newString are identical.",
  282. })
  283. expect(
  284. yield* executeTool(registry, call({ path: "matches.txt", oldString: "", newString: "after" })),
  285. ).toEqual({
  286. type: "error",
  287. value: "oldString must not be empty. Use write to create or overwrite a file.",
  288. })
  289. expect(
  290. yield* executeTool(registry, call({ path: "matches.txt", oldString: "missing", newString: "after" })),
  291. ).toEqual({
  292. type: "error",
  293. value:
  294. "Could not find oldString in the file. It must match exactly, including whitespace and indentation.",
  295. })
  296. expect(
  297. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "after" })),
  298. ).toEqual({
  299. type: "error",
  300. value:
  301. "Found multiple exact matches for oldString. Provide more surrounding context or set replaceAll to true.",
  302. })
  303. expect(writes).toEqual([])
  304. }),
  305. ),
  306. ),
  307. )
  308. },
  309. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  310. ),
  311. )
  312. it.live("replaces every exact occurrence when replaceAll is true", () =>
  313. Effect.acquireUseRelease(
  314. Effect.promise(() => tmpdir()),
  315. (tmp) => {
  316. reset()
  317. const target = path.join(tmp.path, "all.txt")
  318. return Effect.promise(() => fs.writeFile(target, "same same same")).pipe(
  319. Effect.andThen(
  320. withTool(tmp.path, (registry) =>
  321. settleTool(registry, call({ path: "all.txt", oldString: "same", newString: "after", replaceAll: true })),
  322. ),
  323. ),
  324. Effect.andThen((settled) =>
  325. Effect.gen(function* () {
  326. expect(settled.output?.structured).toMatchObject({ replacements: 3 })
  327. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after after after")
  328. expect(writes).toHaveLength(1)
  329. }),
  330. ),
  331. )
  332. },
  333. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  334. ),
  335. )
  336. it.live("preserves BOM and CRLF line endings", () =>
  337. Effect.acquireUseRelease(
  338. Effect.promise(() => tmpdir()),
  339. (tmp) => {
  340. reset()
  341. const target = path.join(tmp.path, "windows.txt")
  342. return Effect.promise(() => fs.writeFile(target, "\uFEFFbefore\r\nrest\r\n")).pipe(
  343. Effect.andThen(
  344. withTool(tmp.path, (registry) =>
  345. executeTool(registry, call({ path: "windows.txt", oldString: "before\nrest", newString: "after\nrest" })),
  346. ),
  347. ),
  348. Effect.andThen(() => Effect.promise(() => fs.readFile(target, "utf8"))),
  349. Effect.tap((content) => Effect.sync(() => expect(content).toBe("\uFEFFafter\r\nrest\r\n"))),
  350. )
  351. },
  352. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  353. ),
  354. )
  355. it.live("rejects an in-place content change after matching but before conditional commit", () =>
  356. Effect.acquireUseRelease(
  357. Effect.promise(() => tmpdir()),
  358. (tmp) => {
  359. reset()
  360. const target = path.join(tmp.path, "concurrent.txt")
  361. afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
  362. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  363. Effect.andThen(
  364. withTool(tmp.path, (registry) =>
  365. executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
  366. ),
  367. ),
  368. Effect.andThen((result) =>
  369. Effect.gen(function* () {
  370. expect(result).toEqual({
  371. type: "error",
  372. value: "File changed after permission approval. Read it again before editing.",
  373. })
  374. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
  375. expect(writes).toEqual([])
  376. }),
  377. ),
  378. )
  379. },
  380. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  381. ),
  382. )
  383. })
  384. test("keeps the locked edit schema, semantics docstring, and deferred TODOs visible", async () => {
  385. const source = (await fs.readFile(new URL("../src/tool/edit.ts", import.meta.url), "utf8")).replaceAll("\r\n", "\n")
  386. const definition = await Effect.runPromise(
  387. withTool(path.dirname(fileURLToPath(import.meta.url)), (registry) => toolDefinitions(registry)),
  388. )
  389. const schema = definition[0]?.inputSchema as { readonly properties?: Record<string, unknown> }
  390. expect(Object.keys(schema.properties ?? {}).sort()).toEqual(["newString", "oldString", "path", "replaceAll"])
  391. expect(source).toContain(
  392. "absolute external paths retain mutation capability through a separate\n * external_directory approval before edit approval.",
  393. )
  394. for (const todo of [
  395. "Port V1 fuzzy correction strategies only after exact-edit behavior is established: line-trimmed matching, block-anchor fallback, indentation correction, and similarity-threshold review.",
  396. "Add formatter integration after V2 formatter runtime exists.",
  397. "Publish watcher/file-edit events after V2 watcher integration exists.",
  398. "Add snapshots / undo after design exists.",
  399. "Add LSP notification and diagnostics after V2 LSP runtime exists.",
  400. ]) {
  401. expect(source).toContain(`TODO: ${todo}`)
  402. }
  403. })