tool-edit.test.ts 16 KB

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