tool-edit.test.ts 16 KB

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