tool-edit.test.ts 18 KB

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