tool-edit.test.ts 17 KB

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