tool-edit.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. operation: "write",
  121. target: yield* Effect.promise(() => fs.realpath(target)),
  122. resource: "hello.txt",
  123. existed: true,
  124. replacements: 1,
  125. })
  126. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
  127. expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
  128. expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
  129. }),
  130. ),
  131. ),
  132. )
  133. },
  134. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  135. ),
  136. )
  137. it.live("accepts an absolute file path inside the active Location", () =>
  138. Effect.acquireUseRelease(
  139. Effect.promise(() => tmpdir()),
  140. (tmp) => {
  141. reset()
  142. const target = path.join(tmp.path, "absolute.txt")
  143. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  144. Effect.andThen(
  145. withTool(tmp.path, (registry) =>
  146. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  147. ),
  148. ),
  149. Effect.andThen((result) =>
  150. Effect.gen(function* () {
  151. expect(result.type).toBe("text")
  152. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  153. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  154. }),
  155. ),
  156. )
  157. },
  158. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  159. ),
  160. )
  161. it.live("approves an explicit external absolute path before edit", () =>
  162. Effect.acquireUseRelease(
  163. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  164. ([active, outside]) => {
  165. reset()
  166. const target = path.join(outside.path, "external.txt")
  167. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  168. Effect.andThen(
  169. withTool(active.path, (registry) =>
  170. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  171. ),
  172. ),
  173. Effect.andThen((result) =>
  174. Effect.gen(function* () {
  175. expect(result.type).toBe("text")
  176. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  177. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  178. expect(writes).toHaveLength(1)
  179. }),
  180. ),
  181. )
  182. },
  183. ([active, outside]) =>
  184. Effect.promise(() =>
  185. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  186. ),
  187. ),
  188. )
  189. it.live("does not write when external_directory or edit approval is denied", () =>
  190. Effect.acquireUseRelease(
  191. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  192. ([active, outside]) =>
  193. Effect.gen(function* () {
  194. const external = path.join(outside.path, "denied.txt")
  195. yield* Effect.promise(() => fs.writeFile(external, "before"))
  196. reset()
  197. denyAction = "external_directory"
  198. expect(
  199. yield* withTool(active.path, (registry) =>
  200. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  201. ),
  202. ).toEqual({
  203. type: "error",
  204. value: `Unable to edit ${external}`,
  205. })
  206. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  207. expect(reads).toBe(0)
  208. expect(writes).toEqual([])
  209. reset()
  210. denyAction = "edit"
  211. expect(
  212. yield* withTool(active.path, (registry) =>
  213. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  214. ),
  215. ).toEqual({
  216. type: "error",
  217. value: `Unable to edit ${external}`,
  218. })
  219. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  220. expect(reads).toBe(0)
  221. expect(writes).toEqual([])
  222. expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
  223. }),
  224. ([active, outside]) =>
  225. Effect.promise(() =>
  226. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  227. ),
  228. ),
  229. )
  230. it.live("denied edit reads no target content and does not disclose whether oldString matches", () =>
  231. Effect.acquireUseRelease(
  232. Effect.promise(() => tmpdir()),
  233. (tmp) => {
  234. reset()
  235. denyAction = "edit"
  236. const target = path.join(tmp.path, "secret.txt")
  237. return Effect.promise(() => fs.writeFile(target, "secret content")).pipe(
  238. Effect.andThen(
  239. withTool(tmp.path, (registry) =>
  240. Effect.gen(function* () {
  241. const matching = yield* executeTool(
  242. registry,
  243. call({ path: "secret.txt", oldString: "secret content", newString: "replacement" }),
  244. )
  245. const missing = yield* executeTool(
  246. registry,
  247. call({ path: "secret.txt", oldString: "not present", newString: "replacement" }),
  248. )
  249. expect(matching).toEqual({ type: "error", value: "Unable to edit secret.txt" })
  250. expect(missing).toEqual(matching)
  251. expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
  252. expect(reads).toBe(0)
  253. expect(writes).toEqual([])
  254. }),
  255. ),
  256. ),
  257. )
  258. },
  259. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  260. ),
  261. )
  262. it.live("rejects no-op, empty, missing, and ambiguous exact replacements", () =>
  263. Effect.acquireUseRelease(
  264. Effect.promise(() => tmpdir()),
  265. (tmp) => {
  266. reset()
  267. const target = path.join(tmp.path, "matches.txt")
  268. return Effect.promise(() => fs.writeFile(target, "same same")).pipe(
  269. Effect.andThen(
  270. withTool(tmp.path, (registry) =>
  271. Effect.gen(function* () {
  272. expect(
  273. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "same" })),
  274. ).toEqual({
  275. type: "error",
  276. value: "No changes to apply: oldString and newString are identical.",
  277. })
  278. expect(
  279. yield* executeTool(registry, call({ path: "matches.txt", oldString: "", newString: "after" })),
  280. ).toEqual({
  281. type: "error",
  282. value: "oldString must not be empty. Use write to create or overwrite a file.",
  283. })
  284. expect(
  285. yield* executeTool(registry, call({ path: "matches.txt", oldString: "missing", newString: "after" })),
  286. ).toEqual({
  287. type: "error",
  288. value:
  289. "Could not find oldString in the file. It must match exactly, including whitespace and indentation.",
  290. })
  291. expect(
  292. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "after" })),
  293. ).toEqual({
  294. type: "error",
  295. value:
  296. "Found multiple exact matches for oldString. Provide more surrounding context or set replaceAll to true.",
  297. })
  298. expect(writes).toEqual([])
  299. }),
  300. ),
  301. ),
  302. )
  303. },
  304. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  305. ),
  306. )
  307. it.live("replaces every exact occurrence when replaceAll is true", () =>
  308. Effect.acquireUseRelease(
  309. Effect.promise(() => tmpdir()),
  310. (tmp) => {
  311. reset()
  312. const target = path.join(tmp.path, "all.txt")
  313. return Effect.promise(() => fs.writeFile(target, "same same same")).pipe(
  314. Effect.andThen(
  315. withTool(tmp.path, (registry) =>
  316. settleTool(registry, call({ path: "all.txt", oldString: "same", newString: "after", replaceAll: true })),
  317. ),
  318. ),
  319. Effect.andThen((settled) =>
  320. Effect.gen(function* () {
  321. expect(settled.output?.structured).toMatchObject({ replacements: 3 })
  322. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after after after")
  323. expect(writes).toHaveLength(1)
  324. }),
  325. ),
  326. )
  327. },
  328. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  329. ),
  330. )
  331. it.live("preserves BOM and CRLF line endings", () =>
  332. Effect.acquireUseRelease(
  333. Effect.promise(() => tmpdir()),
  334. (tmp) => {
  335. reset()
  336. const target = path.join(tmp.path, "windows.txt")
  337. return Effect.promise(() => fs.writeFile(target, "\uFEFFbefore\r\nrest\r\n")).pipe(
  338. Effect.andThen(
  339. withTool(tmp.path, (registry) =>
  340. executeTool(registry, call({ path: "windows.txt", oldString: "before\nrest", newString: "after\nrest" })),
  341. ),
  342. ),
  343. Effect.andThen(() => Effect.promise(() => fs.readFile(target, "utf8"))),
  344. Effect.tap((content) => Effect.sync(() => expect(content).toBe("\uFEFFafter\r\nrest\r\n"))),
  345. )
  346. },
  347. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  348. ),
  349. )
  350. it.live("rejects an in-place content change after matching but before conditional commit", () =>
  351. Effect.acquireUseRelease(
  352. Effect.promise(() => tmpdir()),
  353. (tmp) => {
  354. reset()
  355. const target = path.join(tmp.path, "concurrent.txt")
  356. afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
  357. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  358. Effect.andThen(
  359. withTool(tmp.path, (registry) =>
  360. executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
  361. ),
  362. ),
  363. Effect.andThen((result) =>
  364. Effect.gen(function* () {
  365. expect(result).toEqual({
  366. type: "error",
  367. value: "File changed after permission approval. Read it again before editing.",
  368. })
  369. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
  370. expect(writes).toEqual([])
  371. }),
  372. ),
  373. )
  374. },
  375. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  376. ),
  377. )
  378. })
  379. test("keeps the locked edit schema, semantics docstring, and deferred TODOs visible", async () => {
  380. const source = (await fs.readFile(new URL("../src/tool/edit.ts", import.meta.url), "utf8")).replaceAll("\r\n", "\n")
  381. const definition = await Effect.runPromise(
  382. withTool(path.dirname(fileURLToPath(import.meta.url)), (registry) => toolDefinitions(registry)),
  383. )
  384. const schema = definition[0]?.inputSchema as { readonly properties?: Record<string, unknown> }
  385. expect(Object.keys(schema.properties ?? {}).sort()).toEqual(["newString", "oldString", "path", "replaceAll"])
  386. expect(source).toContain(
  387. "absolute external paths retain mutation capability through a separate\n * external_directory approval before edit approval.",
  388. )
  389. for (const todo of [
  390. "Port V1 fuzzy correction strategies only after exact-edit behavior is established: line-trimmed matching, block-anchor fallback, indentation correction, and similarity-threshold review.",
  391. "Add formatter integration after V2 formatter runtime exists.",
  392. "Publish watcher/file-edit events after V2 watcher integration exists.",
  393. "Add snapshots / undo after design exists.",
  394. "Add LSP notification and diagnostics after V2 LSP runtime exists.",
  395. ]) {
  396. expect(source).toContain(`TODO: ${todo}`)
  397. }
  398. })