tool-edit.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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/util/effect/layer-node"
  8. import { FileMutation } from "@opencode-ai/core/file-mutation"
  9. import { FSUtil } from "@opencode-ai/util/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/util/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("edits an external symlink target with only its in-location permission", () =>
  192. Effect.acquireUseRelease(
  193. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  194. ([active, outside]) => {
  195. reset()
  196. if (process.platform === "win32") return Effect.void
  197. const target = path.join(outside.path, "external.txt")
  198. const link = path.join(active.path, "link.txt")
  199. return Effect.promise(async () => {
  200. await fs.writeFile(target, "before")
  201. await fs.symlink(target, link)
  202. }).pipe(
  203. Effect.andThen(
  204. withTool(active.path, (registry) =>
  205. executeTool(registry, call({ path: "link.txt", oldString: "before", newString: "after" })),
  206. ),
  207. ),
  208. Effect.andThen((result) =>
  209. Effect.sync(() => {
  210. expect(result.type).toBe("text")
  211. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  212. expect(assertions[0]?.resources).toEqual(["link.txt"])
  213. }),
  214. ),
  215. Effect.andThen(Effect.promise(() => fs.readFile(target, "utf8"))),
  216. Effect.tap((content) => Effect.sync(() => expect(content).toBe("after"))),
  217. )
  218. },
  219. ([active, outside]) =>
  220. Effect.promise(() =>
  221. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  222. ),
  223. ),
  224. )
  225. it.live("approves an explicit external absolute path before edit", () =>
  226. Effect.acquireUseRelease(
  227. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  228. ([active, outside]) => {
  229. reset()
  230. const target = path.join(outside.path, "external.txt")
  231. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  232. Effect.andThen(
  233. withTool(active.path, (registry) =>
  234. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  235. ),
  236. ),
  237. Effect.andThen((result) =>
  238. Effect.gen(function* () {
  239. expect(result.type).toBe("text")
  240. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  241. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  242. expect(writes).toHaveLength(1)
  243. }),
  244. ),
  245. )
  246. },
  247. ([active, outside]) =>
  248. Effect.promise(() =>
  249. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  250. ),
  251. ),
  252. )
  253. it.live("does not write when external_directory or edit approval is denied", () =>
  254. Effect.acquireUseRelease(
  255. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  256. ([active, outside]) =>
  257. Effect.gen(function* () {
  258. const external = path.join(outside.path, "denied.txt")
  259. yield* Effect.promise(() => fs.writeFile(external, "before"))
  260. reset()
  261. denyAction = "external_directory"
  262. expect(
  263. yield* withTool(active.path, (registry) =>
  264. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  265. ),
  266. ).toEqual({
  267. type: "error",
  268. value: `Unable to edit ${external}`,
  269. })
  270. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  271. expect(reads).toBe(0)
  272. expect(writes).toEqual([])
  273. reset()
  274. denyAction = "edit"
  275. expect(
  276. yield* withTool(active.path, (registry) =>
  277. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  278. ),
  279. ).toEqual({
  280. type: "error",
  281. value: `Unable to edit ${external}`,
  282. })
  283. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  284. expect(reads).toBe(0)
  285. expect(writes).toEqual([])
  286. expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
  287. }),
  288. ([active, outside]) =>
  289. Effect.promise(() =>
  290. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  291. ),
  292. ),
  293. )
  294. it.live("denied edit reads no target content and does not disclose whether oldString matches", () =>
  295. Effect.acquireUseRelease(
  296. Effect.promise(() => tmpdir()),
  297. (tmp) => {
  298. reset()
  299. denyAction = "edit"
  300. const target = path.join(tmp.path, "secret.txt")
  301. return Effect.promise(() => fs.writeFile(target, "secret content")).pipe(
  302. Effect.andThen(
  303. withTool(tmp.path, (registry) =>
  304. Effect.gen(function* () {
  305. const matching = yield* executeTool(
  306. registry,
  307. call({ path: "secret.txt", oldString: "secret content", newString: "replacement" }),
  308. )
  309. const missing = yield* executeTool(
  310. registry,
  311. call({ path: "secret.txt", oldString: "not present", newString: "replacement" }),
  312. )
  313. expect(matching).toEqual({ type: "error", value: "Unable to edit secret.txt" })
  314. expect(missing).toEqual(matching)
  315. expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
  316. expect(reads).toBe(0)
  317. expect(writes).toEqual([])
  318. }),
  319. ),
  320. ),
  321. )
  322. },
  323. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  324. ),
  325. )
  326. it.live("rejects no-op, empty, missing, and ambiguous exact replacements", () =>
  327. Effect.acquireUseRelease(
  328. Effect.promise(() => tmpdir()),
  329. (tmp) => {
  330. reset()
  331. const target = path.join(tmp.path, "matches.txt")
  332. return Effect.promise(() => fs.writeFile(target, "same same")).pipe(
  333. Effect.andThen(
  334. withTool(tmp.path, (registry) =>
  335. Effect.gen(function* () {
  336. expect(
  337. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "same" })),
  338. ).toEqual({
  339. type: "error",
  340. value: "No changes to apply: oldString and newString are identical.",
  341. })
  342. expect(
  343. yield* executeTool(registry, call({ path: "matches.txt", oldString: "", newString: "after" })),
  344. ).toEqual({
  345. type: "error",
  346. value: "oldString must not be empty. Use write to create or overwrite a file.",
  347. })
  348. expect(
  349. yield* executeTool(registry, call({ path: "matches.txt", oldString: "missing", newString: "after" })),
  350. ).toEqual({
  351. type: "error",
  352. value:
  353. "Could not find oldString in the file. It must match exactly, including whitespace and indentation.",
  354. })
  355. expect(
  356. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "after" })),
  357. ).toEqual({
  358. type: "error",
  359. value:
  360. "Found multiple exact matches for oldString. Provide more surrounding context or set replaceAll to true.",
  361. })
  362. expect(writes).toEqual([])
  363. }),
  364. ),
  365. ),
  366. )
  367. },
  368. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  369. ),
  370. )
  371. it.live("replaces every exact occurrence when replaceAll is true", () =>
  372. Effect.acquireUseRelease(
  373. Effect.promise(() => tmpdir()),
  374. (tmp) => {
  375. reset()
  376. const target = path.join(tmp.path, "all.txt")
  377. return Effect.promise(() => fs.writeFile(target, "same same same")).pipe(
  378. Effect.andThen(
  379. withTool(tmp.path, (registry) =>
  380. settleTool(registry, call({ path: "all.txt", oldString: "same", newString: "after", replaceAll: true })),
  381. ),
  382. ),
  383. Effect.andThen((settled) =>
  384. Effect.gen(function* () {
  385. expect(settled.output?.structured).toMatchObject({ replacements: 3 })
  386. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after after after")
  387. expect(writes).toHaveLength(1)
  388. }),
  389. ),
  390. )
  391. },
  392. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  393. ),
  394. )
  395. it.live("preserves BOM and CRLF line endings", () =>
  396. Effect.acquireUseRelease(
  397. Effect.promise(() => tmpdir()),
  398. (tmp) => {
  399. reset()
  400. const target = path.join(tmp.path, "windows.txt")
  401. return Effect.promise(() => fs.writeFile(target, "\uFEFFbefore\r\nrest\r\n")).pipe(
  402. Effect.andThen(
  403. withTool(tmp.path, (registry) =>
  404. executeTool(registry, call({ path: "windows.txt", oldString: "before\nrest", newString: "after\nrest" })),
  405. ),
  406. ),
  407. Effect.andThen(() => Effect.promise(() => fs.readFile(target, "utf8"))),
  408. Effect.tap((content) => Effect.sync(() => expect(content).toBe("\uFEFFafter\r\nrest\r\n"))),
  409. )
  410. },
  411. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  412. ),
  413. )
  414. it.live("rejects an in-place content change after matching but before conditional commit", () =>
  415. Effect.acquireUseRelease(
  416. Effect.promise(() => tmpdir()),
  417. (tmp) => {
  418. reset()
  419. const target = path.join(tmp.path, "concurrent.txt")
  420. afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
  421. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  422. Effect.andThen(
  423. withTool(tmp.path, (registry) =>
  424. executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
  425. ),
  426. ),
  427. Effect.andThen((result) =>
  428. Effect.gen(function* () {
  429. expect(result).toEqual({
  430. type: "error",
  431. value: "File changed after permission approval. Read it again before editing.",
  432. })
  433. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
  434. expect(writes).toEqual([])
  435. }),
  436. ),
  437. )
  438. },
  439. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  440. ),
  441. )
  442. })
  443. test("keeps the locked edit schema, semantics docstring, and deferred TODOs visible", async () => {
  444. const source = (await fs.readFile(new URL("../src/tool/edit.ts", import.meta.url), "utf8")).replaceAll("\r\n", "\n")
  445. const definition = await Effect.runPromise(
  446. withTool(path.dirname(fileURLToPath(import.meta.url)), (registry) => toolDefinitions(registry)),
  447. )
  448. const schema = definition[0]?.inputSchema as { readonly properties?: Record<string, unknown> }
  449. expect(Object.keys(schema.properties ?? {}).sort()).toEqual(["newString", "oldString", "path", "replaceAll"])
  450. expect(source).toContain(
  451. "absolute external paths retain mutation capability through a separate\n * external_directory approval before edit approval.",
  452. )
  453. for (const todo of [
  454. "Port V1 fuzzy correction strategies only after exact-edit behavior is established: line-trimmed matching, block-anchor fallback, indentation correction, and similarity-threshold review.",
  455. "Add formatter integration after V2 formatter runtime exists.",
  456. "Publish watcher/file-edit events after V2 watcher integration exists.",
  457. "Add snapshots / undo after design exists.",
  458. "Add LSP notification and diagnostics after V2 LSP runtime exists.",
  459. ]) {
  460. expect(source).toContain(`TODO: ${todo}`)
  461. }
  462. })