tool-patch.test.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Exit, Layer, Schema } from "effect"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  7. import { FSUtil } from "@opencode-ai/util/fs-util"
  8. import { Location } from "@opencode-ai/core/location"
  9. import { PermissionV2 } from "@opencode-ai/core/permission"
  10. import { AbsolutePath } from "@opencode-ai/core/schema"
  11. import { SessionV2 } from "@opencode-ai/core/session"
  12. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  13. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  14. import { PatchTool } from "@opencode-ai/core/tool/patch"
  15. import { location } from "./fixture/location"
  16. import { tmpdir } from "./fixture/tmpdir"
  17. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  18. import { testEffect } from "./lib/effect"
  19. import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool"
  20. const patchToolNode = makeLocationNode({
  21. name: "test/patch-tool-plugin",
  22. layer: Layer.effectDiscard(registerToolPlugin(PatchTool.Plugin)),
  23. deps: [ToolRegistry.toolsNode, FSUtil.node, Location.node, PermissionV2.node],
  24. })
  25. const sessionID = SessionV2.ID.make("ses_patch_tool_test")
  26. const assertions: PermissionV2.AssertInput[] = []
  27. let denyAction: string | undefined
  28. let failRemoveTarget: string | undefined
  29. let readsBeforeEditApproval = 0
  30. let editApproved = false
  31. let afterEditApproval = (): Effect.Effect<void> => Effect.void
  32. const permission = Layer.succeed(
  33. PermissionV2.Service,
  34. PermissionV2.Service.of({
  35. assert: (input) =>
  36. Effect.sync(() => {
  37. assertions.push(input)
  38. if (input.action === "edit") editApproved = true
  39. }).pipe(
  40. Effect.andThen(input.action === "edit" ? Effect.suspend(afterEditApproval) : Effect.void),
  41. Effect.andThen(
  42. input.action === denyAction
  43. ? Effect.fail(
  44. new PermissionV2.BlockedError({
  45. rules: [],
  46. permission: input.action,
  47. resources: input.resources,
  48. }),
  49. )
  50. : Effect.void,
  51. ),
  52. ),
  53. ask: () => Effect.die("unused"),
  54. reply: () => Effect.die("unused"),
  55. get: () => Effect.die("unused"),
  56. forSession: () => Effect.die("unused"),
  57. list: () => Effect.die("unused"),
  58. }),
  59. )
  60. const reset = () => {
  61. assertions.length = 0
  62. denyAction = undefined
  63. failRemoveTarget = undefined
  64. readsBeforeEditApproval = 0
  65. editApproved = false
  66. afterEditApproval = () => Effect.void
  67. }
  68. const filesystem = Layer.effect(
  69. FSUtil.Service,
  70. Effect.gen(function* () {
  71. const fs = yield* FSUtil.Service
  72. return FSUtil.Service.of({
  73. ...fs,
  74. readFile: (target) =>
  75. Effect.sync(() => {
  76. if (!editApproved) readsBeforeEditApproval++
  77. }).pipe(Effect.andThen(fs.readFile(target))),
  78. remove: (target, options) => {
  79. if (failRemoveTarget && path.basename(target) === failRemoveTarget) return Effect.die("forced remove failure")
  80. return fs.remove(target, options)
  81. },
  82. })
  83. }),
  84. ).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
  85. const withTool = <A, E, R>(
  86. directory: string,
  87. body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>,
  88. projectDirectory = directory,
  89. ) => {
  90. const activeLocation = Layer.succeed(
  91. Location.Service,
  92. Location.Service.of(
  93. location(
  94. { directory: AbsolutePath.make(directory) },
  95. { projectDirectory: AbsolutePath.make(projectDirectory) },
  96. ),
  97. ),
  98. )
  99. return Effect.gen(function* () {
  100. return yield* body(yield* ToolRegistry.Service)
  101. }).pipe(
  102. Effect.provide(
  103. AppNodeBuilder.build(
  104. LayerNode.group([
  105. ToolRegistry.node,
  106. ToolRegistry.toolsNode,
  107. patchToolNode,
  108. ]),
  109. [
  110. [FSUtil.node, filesystem],
  111. [Location.node, activeLocation],
  112. [PermissionV2.node, permission],
  113. [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
  114. ],
  115. ),
  116. ),
  117. )
  118. }
  119. const call = (patchText: string, id = "call-patch") => ({
  120. sessionID,
  121. ...toolIdentity,
  122. call: { type: "tool-call" as const, id, name: "patch", input: { patchText } },
  123. })
  124. const exists = (target: string) =>
  125. Effect.promise(() =>
  126. fs.stat(target).then(
  127. () => true,
  128. () => false,
  129. ),
  130. )
  131. const it = testEffect(Layer.empty)
  132. const withTempTool = <A, E, R>(body: (directory: string, registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) =>
  133. Effect.acquireUseRelease(
  134. Effect.promise(() => tmpdir()),
  135. (tmp) => {
  136. reset()
  137. return withTool(tmp.path, (registry) => body(tmp.path, registry))
  138. },
  139. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  140. )
  141. describe("PatchTool", () => {
  142. it.live("registers and sequentially applies add, update, and delete hunks", () =>
  143. Effect.acquireUseRelease(
  144. Effect.promise(() => tmpdir()),
  145. (tmp) => {
  146. reset()
  147. const update = path.join(tmp.path, "update.txt")
  148. const remove = path.join(tmp.path, "remove.txt")
  149. return Effect.promise(() =>
  150. Promise.all([fs.writeFile(update, "before\n"), fs.writeFile(remove, "remove\n")]),
  151. ).pipe(
  152. Effect.andThen(
  153. withTool(tmp.path, (registry) =>
  154. Effect.gen(function* () {
  155. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch"])
  156. const settled = yield* settleTool(
  157. registry,
  158. call(
  159. "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Update File: update.txt\n@@\n-before\n+after\n*** Delete File: remove.txt\n*** End Patch",
  160. ),
  161. )
  162. expect(settled.result).toEqual({
  163. type: "text",
  164. value: "Success. Updated the following files:\nA nested/new.txt\nM update.txt\nD remove.txt",
  165. })
  166. if (process.platform === "win32") expect(settled.result.value).not.toContain("\\")
  167. expect(settled.output?.structured).toMatchObject({
  168. applied: [
  169. { type: "add", resource: "nested/new.txt" },
  170. { type: "update", resource: "update.txt" },
  171. { type: "delete", resource: "remove.txt" },
  172. ],
  173. files: [
  174. {
  175. file: "nested/new.txt",
  176. status: "added",
  177. additions: 1,
  178. deletions: 0,
  179. patch: expect.stringContaining("+created"),
  180. },
  181. {
  182. file: "update.txt",
  183. status: "modified",
  184. additions: 1,
  185. deletions: 1,
  186. patch: expect.stringContaining("-before\n+after"),
  187. },
  188. {
  189. file: "remove.txt",
  190. status: "deleted",
  191. additions: 0,
  192. deletions: 2,
  193. patch: expect.stringContaining("-remove"),
  194. },
  195. ],
  196. })
  197. expect(assertions).toMatchObject([
  198. {
  199. sessionID,
  200. action: "edit",
  201. resources: ["nested/new.txt", "update.txt", "remove.txt"],
  202. save: ["*"],
  203. metadata: {
  204. filepath: "nested/new.txt, update.txt, remove.txt",
  205. diff: expect.stringContaining("Index:"),
  206. files: expect.any(Array),
  207. },
  208. },
  209. ])
  210. expect(readsBeforeEditApproval).toBe(2)
  211. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe(
  212. "created\n",
  213. )
  214. expect(yield* Effect.promise(() => fs.readFile(update, "utf8"))).toBe("after\n")
  215. expect(yield* exists(remove)).toBe(false)
  216. }),
  217. ),
  218. ),
  219. )
  220. },
  221. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  222. ),
  223. )
  224. it.live("moves and updates a file", () =>
  225. Effect.acquireUseRelease(
  226. Effect.promise(() => tmpdir()),
  227. (tmp) => {
  228. reset()
  229. const source = path.join(tmp.path, "old.txt")
  230. return Effect.promise(() => fs.writeFile(source, "before\n")).pipe(
  231. Effect.andThen(
  232. withTool(tmp.path, (registry) =>
  233. Effect.gen(function* () {
  234. expect(
  235. yield* executeTool(
  236. registry,
  237. call(
  238. "*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: old.txt\n*** Move to: moved.txt\n@@\n-before\n+after\n*** End Patch",
  239. ),
  240. ),
  241. ).toEqual({
  242. type: "text",
  243. value: "Success. Updated the following files:\nA created.txt\nM moved.txt",
  244. })
  245. expect(yield* exists(source)).toBe(false)
  246. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "moved.txt"), "utf8"))).toBe(
  247. "after\n",
  248. )
  249. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "created.txt"), "utf8"))).toBe(
  250. "created\n",
  251. )
  252. }),
  253. ),
  254. ),
  255. )
  256. },
  257. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  258. ),
  259. )
  260. it.live("moves a file over an existing destination", () =>
  261. Effect.acquireUseRelease(
  262. Effect.promise(() => tmpdir()),
  263. (tmp) => {
  264. reset()
  265. const source = path.join(tmp.path, "old.txt")
  266. const destination = path.join(tmp.path, "nested", "moved.txt")
  267. return Effect.promise(() =>
  268. Promise.all([
  269. fs.writeFile(source, "before\n"),
  270. fs.mkdir(path.dirname(destination), { recursive: true }).then(() => fs.writeFile(destination, "existing\n")),
  271. ]),
  272. ).pipe(
  273. Effect.andThen(
  274. withTool(tmp.path, (registry) =>
  275. Effect.gen(function* () {
  276. expect(
  277. yield* executeTool(
  278. registry,
  279. call(
  280. "*** Begin Patch\n*** Update File: old.txt\n*** Move to: nested/moved.txt\n@@\n-before\n+after\n*** End Patch",
  281. ),
  282. ),
  283. ).toMatchObject({ type: "text" })
  284. expect(yield* exists(source)).toBe(false)
  285. expect(yield* Effect.promise(() => fs.readFile(destination, "utf8"))).toBe("after\n")
  286. }),
  287. ),
  288. ),
  289. )
  290. },
  291. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  292. ),
  293. )
  294. it.live("moves a symlink without deleting its target", () =>
  295. withTempTool((directory, registry) =>
  296. Effect.gen(function* () {
  297. if (process.platform === "win32") return
  298. const target = path.join(directory, "target.txt")
  299. const source = path.join(directory, "link.txt")
  300. const moved = path.join(directory, "moved.txt")
  301. yield* Effect.promise(() => fs.writeFile(target, "before\n"))
  302. yield* Effect.promise(() => fs.symlink(target, source))
  303. yield* executeTool(
  304. registry,
  305. call(
  306. "*** Begin Patch\n*** Update File: link.txt\n*** Move to: moved.txt\n@@\n-before\n+after\n*** End Patch",
  307. ),
  308. )
  309. expect(yield* exists(source)).toBe(false)
  310. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("before\n")
  311. expect(yield* Effect.promise(() => fs.readFile(moved, "utf8"))).toBe("after\n")
  312. }),
  313. ),
  314. )
  315. it.live("includes move file info in structured output", () =>
  316. withTempTool((directory, registry) =>
  317. Effect.gen(function* () {
  318. const source = path.join(directory, "old", "name.txt")
  319. yield* Effect.promise(() => fs.mkdir(path.dirname(source), { recursive: true }))
  320. yield* Effect.promise(() => fs.writeFile(source, "old content\n"))
  321. const settled = yield* settleTool(
  322. registry,
  323. call(
  324. "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch",
  325. ),
  326. )
  327. expect(settled.output?.structured).toMatchObject({
  328. applied: [{ type: "update", resource: "renamed/dir/name.txt" }],
  329. files: [
  330. {
  331. file: "renamed/dir/name.txt",
  332. status: "modified",
  333. patch: expect.stringContaining("-old content\n+new content"),
  334. },
  335. ],
  336. })
  337. }),
  338. ),
  339. )
  340. it.live("includes the move destination in edit permission resources", () =>
  341. withTempTool((directory, registry) =>
  342. Effect.gen(function* () {
  343. const source = path.join(directory, "old", "name.txt")
  344. yield* Effect.promise(() => fs.mkdir(path.dirname(source), { recursive: true }))
  345. yield* Effect.promise(() => fs.writeFile(source, "old content\n"))
  346. yield* executeTool(
  347. registry,
  348. call(
  349. "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch",
  350. ),
  351. )
  352. expect(assertions).toMatchObject([
  353. {
  354. action: "edit",
  355. resources: ["old/name.txt", "renamed/dir/name.txt"],
  356. },
  357. ])
  358. }),
  359. ),
  360. )
  361. it.live("inserts lines with an insert-only hunk", () =>
  362. withTempTool((directory, registry) =>
  363. Effect.gen(function* () {
  364. const target = path.join(directory, "insert-only.txt")
  365. yield* Effect.promise(() => fs.writeFile(target, "alpha\nomega\n"))
  366. yield* executeTool(
  367. registry,
  368. call("*** Begin Patch\n*** Update File: insert-only.txt\n@@\n alpha\n+beta\n omega\n*** End Patch"),
  369. )
  370. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("alpha\nbeta\nomega\n")
  371. }),
  372. ),
  373. )
  374. it.live("updates an empty file", () =>
  375. withTempTool((directory, registry) =>
  376. Effect.gen(function* () {
  377. const target = path.join(directory, "empty.txt")
  378. yield* Effect.promise(() => fs.writeFile(target, ""))
  379. yield* executeTool(registry, call("*** Begin Patch\n*** Update File: empty.txt\n@@\n+First line\n*** End Patch"))
  380. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("First line\n")
  381. }),
  382. ),
  383. )
  384. it.live("rejects deleting a directory", () =>
  385. withTempTool((directory, registry) =>
  386. Effect.gen(function* () {
  387. yield* Effect.promise(() => fs.mkdir(path.join(directory, "dir")))
  388. expect(
  389. yield* executeTool(registry, call("*** Begin Patch\n*** Delete File: dir\n*** End Patch")),
  390. ).toMatchObject({ type: "error" })
  391. expect(yield* exists(path.join(directory, "dir"))).toBe(true)
  392. }),
  393. ),
  394. )
  395. it.live("supports an end-of-file anchor", () =>
  396. withTempTool((directory, registry) =>
  397. Effect.gen(function* () {
  398. const target = path.join(directory, "tail.txt")
  399. yield* Effect.promise(() => fs.writeFile(target, "first\nsecond"))
  400. yield* executeTool(
  401. registry,
  402. call(
  403. "*** Begin Patch\n*** Update File: tail.txt\n@@\n first\n-second\n+second updated\n*** End of File\n*** End Patch",
  404. ),
  405. )
  406. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("first\nsecond updated\n")
  407. }),
  408. ),
  409. )
  410. it.live("applies an end-of-file chunk to the final duplicate", () =>
  411. withTempTool((directory, registry) =>
  412. Effect.gen(function* () {
  413. const target = path.join(directory, "duplicates.txt")
  414. yield* Effect.promise(() => fs.writeFile(target, "marker\nend\nmiddle\nmarker\nend\n"))
  415. yield* executeTool(
  416. registry,
  417. call(
  418. "*** Begin Patch\n*** Update File: duplicates.txt\n@@\n-marker\n-end\n+marker changed\n+end\n*** End of File\n*** End Patch",
  419. ),
  420. )
  421. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe(
  422. "marker\nend\nmiddle\nmarker changed\nend\n",
  423. )
  424. }),
  425. ),
  426. )
  427. it.live("rejects a missing second chunk context", () =>
  428. withTempTool((directory, registry) =>
  429. Effect.gen(function* () {
  430. const target = path.join(directory, "two-chunks.txt")
  431. yield* Effect.promise(() => fs.writeFile(target, "a\nb\nc\nd\n"))
  432. expect(
  433. yield* executeTool(
  434. registry,
  435. call(
  436. "*** Begin Patch\n*** Update File: two-chunks.txt\n@@\n-b\n+B\n\n-d\n+D\n*** End Patch",
  437. ),
  438. ),
  439. ).toMatchObject({ type: "error" })
  440. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("a\nb\nc\nd\n")
  441. }),
  442. ),
  443. )
  444. it.live("requires patchText", () =>
  445. withTempTool((_directory, registry) =>
  446. Effect.gen(function* () {
  447. expect(yield* executeTool(registry, call(""))).toEqual({ type: "error", value: "patchText is required" })
  448. }),
  449. ),
  450. )
  451. it.live("rejects invalid patch format", () =>
  452. withTempTool((_directory, registry) =>
  453. Effect.gen(function* () {
  454. expect(yield* executeTool(registry, call("invalid patch"))).toEqual({
  455. type: "error",
  456. value: "patch verification failed: The first line of the patch must be '*** Begin Patch'",
  457. })
  458. expect(yield* executeTool(registry, call("*** Begin Patch\n*** Add File: foo\n+hello"))).toEqual({
  459. type: "error",
  460. value: "patch verification failed: The last line of the patch must be '*** End Patch'",
  461. })
  462. }),
  463. ),
  464. )
  465. it.live("rejects an empty patch", () =>
  466. withTempTool((_directory, registry) =>
  467. Effect.gen(function* () {
  468. expect(yield* executeTool(registry, call("*** Begin Patch\n*** End Patch"))).toEqual({
  469. type: "error",
  470. value: "patch rejected: empty patch",
  471. })
  472. }),
  473. ),
  474. )
  475. it.live("rejects an invalid hunk header", () =>
  476. withTempTool((_directory, registry) =>
  477. Effect.gen(function* () {
  478. expect(
  479. yield* executeTool(
  480. registry,
  481. call("*** Begin Patch\n*** Frobnicate File: foo\n*** End Patch"),
  482. ),
  483. ).toEqual({
  484. type: "error",
  485. value:
  486. "patch verification failed: Invalid hunk at line 2: '*** Frobnicate File: foo' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'",
  487. })
  488. }),
  489. ),
  490. )
  491. it.live("applies multiple hunks to one file", () =>
  492. withTempTool((directory, registry) =>
  493. Effect.gen(function* () {
  494. const target = path.join(directory, "multi.txt")
  495. yield* Effect.promise(() => fs.writeFile(target, "a\nb\nc\nd\n"))
  496. yield* executeTool(
  497. registry,
  498. call("*** Begin Patch\n*** Update File: multi.txt\n@@\n-b\n+B\n@@\n-d\n+D\n*** End Patch"),
  499. )
  500. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("a\nB\nc\nD\n")
  501. }),
  502. ),
  503. )
  504. it.live("applies successive update operations to one file", () =>
  505. withTempTool((directory, registry) =>
  506. Effect.gen(function* () {
  507. const target = path.join(directory, "successive.txt")
  508. yield* Effect.promise(() => fs.writeFile(target, "a\nb\n"))
  509. yield* executeTool(
  510. registry,
  511. call(
  512. "*** Begin Patch\n*** Update File: successive.txt\n@@\n-a\n+A\n*** Update File: successive.txt\n@@\n-b\n+B\n*** End Patch",
  513. ),
  514. )
  515. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("A\nB\n")
  516. }),
  517. ),
  518. )
  519. it.live("does not invent a first-line diff for BOM files", () =>
  520. withTempTool((directory, registry) =>
  521. Effect.gen(function* () {
  522. const bom = "\uFEFF"
  523. const target = path.join(directory, "example.cs")
  524. yield* Effect.promise(() => fs.writeFile(target, `${bom}using System;\n\nclass Test {}\n`))
  525. const settled = yield* settleTool(
  526. registry,
  527. call(
  528. "*** Begin Patch\n*** Update File: example.cs\n@@\n class Test {}\n+class Next {}\n*** End Patch",
  529. ),
  530. )
  531. const output = Schema.decodeUnknownSync(PatchTool.Output)(settled.output?.structured)
  532. expect(output.files[0]?.patch).not.toContain(bom)
  533. expect(output.files[0]?.patch).not.toContain("-using System;")
  534. expect(output.files[0]?.patch).not.toContain("+using System;")
  535. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe(
  536. `${bom}using System;\n\nclass Test {}\nclass Next {}\n`,
  537. )
  538. }),
  539. ),
  540. )
  541. it.live("appends a trailing newline on update", () =>
  542. withTempTool((directory, registry) =>
  543. Effect.gen(function* () {
  544. const target = path.join(directory, "no-newline.txt")
  545. yield* Effect.promise(() => fs.writeFile(target, "no newline at end"))
  546. yield* executeTool(
  547. registry,
  548. call(
  549. "*** Begin Patch\n*** Update File: no-newline.txt\n@@\n-no newline at end\n+first line\n+second line\n*** End Patch",
  550. ),
  551. )
  552. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("first line\nsecond line\n")
  553. }),
  554. ),
  555. )
  556. it.live("disambiguates change context with an @@ header", () =>
  557. withTempTool((directory, registry) =>
  558. Effect.gen(function* () {
  559. const target = path.join(directory, "context.txt")
  560. yield* Effect.promise(() => fs.writeFile(target, "fn a\nx=10\ny=2\nfn b\nx=10\ny=20\n"))
  561. yield* executeTool(
  562. registry,
  563. call("*** Begin Patch\n*** Update File: context.txt\n@@ fn b\n-x=10\n+x=11\n*** End Patch"),
  564. )
  565. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe(
  566. "fn a\nx=10\ny=2\nfn b\nx=11\ny=20\n",
  567. )
  568. }),
  569. ),
  570. )
  571. it.live("parses a heredoc-wrapped patch", () =>
  572. withTempTool((directory, registry) =>
  573. Effect.gen(function* () {
  574. yield* executeTool(
  575. registry,
  576. call("cat <<'EOF'\n*** Begin Patch\n*** Add File: heredoc.txt\n+with cat\n*** End Patch\nEOF"),
  577. )
  578. expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "heredoc.txt"), "utf8"))).toBe(
  579. "with cat\n",
  580. )
  581. }),
  582. ),
  583. )
  584. it.live("parses a heredoc-wrapped patch without cat", () =>
  585. withTempTool((directory, registry) =>
  586. Effect.gen(function* () {
  587. yield* executeTool(
  588. registry,
  589. call("<<EOF\n*** Begin Patch\n*** Add File: heredoc.txt\n+without cat\n*** End Patch\nEOF"),
  590. )
  591. expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "heredoc.txt"), "utf8"))).toBe(
  592. "without cat\n",
  593. )
  594. }),
  595. ),
  596. )
  597. it.live("matches with trailing whitespace differences", () =>
  598. withTempTool((directory, registry) =>
  599. Effect.gen(function* () {
  600. const target = path.join(directory, "trailing.txt")
  601. yield* Effect.promise(() => fs.writeFile(target, "line1 \nline2\nline3 \n"))
  602. yield* executeTool(
  603. registry,
  604. call("*** Begin Patch\n*** Update File: trailing.txt\n@@\n-line2\n+changed\n*** End Patch"),
  605. )
  606. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("line1 \nchanged\nline3 \n")
  607. }),
  608. ),
  609. )
  610. it.live("matches with leading whitespace differences", () =>
  611. withTempTool((directory, registry) =>
  612. Effect.gen(function* () {
  613. const target = path.join(directory, "leading.txt")
  614. yield* Effect.promise(() => fs.writeFile(target, " line1\nline2\n line3\n"))
  615. yield* executeTool(
  616. registry,
  617. call("*** Begin Patch\n*** Update File: leading.txt\n@@\n-line2\n+changed\n*** End Patch"),
  618. )
  619. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe(" line1\nchanged\n line3\n")
  620. }),
  621. ),
  622. )
  623. it.live("matches with Unicode punctuation differences", () =>
  624. withTempTool((directory, registry) =>
  625. Effect.gen(function* () {
  626. const target = path.join(directory, "unicode.txt")
  627. yield* Effect.promise(() => fs.writeFile(target, "He said “hello”\nsome—dash\nend\n"))
  628. yield* executeTool(
  629. registry,
  630. call(
  631. '*** Begin Patch\n*** Update File: unicode.txt\n@@\n-He said "hello"\n+He said "hi"\n*** End Patch',
  632. ),
  633. )
  634. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe('He said "hi"\nsome—dash\nend\n')
  635. }),
  636. ),
  637. )
  638. it.live("rejects an update with missing context", () =>
  639. withTempTool((directory, registry) =>
  640. Effect.gen(function* () {
  641. const target = path.join(directory, "unchanged.txt")
  642. yield* Effect.promise(() => fs.writeFile(target, "line1\nline2\n"))
  643. expect(
  644. yield* executeTool(
  645. registry,
  646. call("*** Begin Patch\n*** Update File: unchanged.txt\n@@\n-missing\n+changed\n*** End Patch"),
  647. ),
  648. ).toMatchObject({ type: "error", value: expect.stringContaining("Failed to find expected lines") })
  649. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("line1\nline2\n")
  650. }),
  651. ),
  652. )
  653. it.live("rejects an update when the target file is missing", () =>
  654. withTempTool((directory, registry) =>
  655. Effect.gen(function* () {
  656. expect(
  657. yield* executeTool(
  658. registry,
  659. call("*** Begin Patch\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch"),
  660. ),
  661. ).toMatchObject({
  662. type: "error",
  663. value: expect.stringContaining(
  664. `patch verification failed: Failed to read file to update ${path.join(directory, "missing.txt")}: `,
  665. ),
  666. })
  667. }),
  668. ),
  669. )
  670. it.live("identifies a directory used as an update target", () =>
  671. withTempTool((directory, registry) =>
  672. Effect.gen(function* () {
  673. yield* Effect.promise(() => fs.mkdir(path.join(directory, "nested")))
  674. expect(
  675. yield* executeTool(registry, call("*** Begin Patch\n*** Update File: nested\n@@\n-old\n+new\n*** End Patch")),
  676. ).toEqual({
  677. type: "error",
  678. value: `patch verification failed: Failed to read file to update ${path.join(directory, "nested")}: path is a directory`,
  679. })
  680. }),
  681. ),
  682. )
  683. it.live("rejects a delete when the target file is missing", () =>
  684. withTempTool((_directory, registry) =>
  685. Effect.gen(function* () {
  686. expect(
  687. yield* executeTool(registry, call("*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch")),
  688. ).toMatchObject({ type: "error", value: expect.stringContaining("patch verification failed") })
  689. }),
  690. ),
  691. )
  692. it.live("approves an external directory before reading and requests edit permission afterward", () =>
  693. Effect.acquireUseRelease(
  694. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  695. ([active, outside]) => {
  696. reset()
  697. const target = path.join(outside.path, "external.txt")
  698. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  699. Effect.andThen(
  700. withTool(active.path, (registry) =>
  701. Effect.gen(function* () {
  702. expect(
  703. yield* executeTool(
  704. registry,
  705. call(`*** Begin Patch\n*** Update File: ${target}\n@@\n-before\n+after\n*** End Patch`),
  706. ),
  707. ).toMatchObject({ type: "text" })
  708. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  709. expect(readsBeforeEditApproval).toBe(1)
  710. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
  711. }),
  712. ),
  713. ),
  714. )
  715. },
  716. ([active, outside]) =>
  717. Effect.promise(() =>
  718. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  719. ),
  720. ),
  721. )
  722. it.live("does not inspect an external file when external permission is denied", () =>
  723. Effect.acquireUseRelease(
  724. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  725. ([active, outside]) => {
  726. reset()
  727. denyAction = "external_directory"
  728. const target = path.join(outside.path, "external.txt")
  729. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  730. Effect.andThen(
  731. withTool(
  732. active.path,
  733. (registry) =>
  734. Effect.gen(function* () {
  735. expect(
  736. yield* executeTool(
  737. registry,
  738. call(`*** Begin Patch\n*** Update File: ${target}\n@@\n-before\n+after\n*** End Patch`),
  739. ),
  740. ).toMatchObject({ type: "error" })
  741. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  742. expect(readsBeforeEditApproval).toBe(0)
  743. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("before\n")
  744. }),
  745. path.parse(active.path).root,
  746. ),
  747. ),
  748. )
  749. },
  750. ([active, outside]) =>
  751. Effect.promise(() =>
  752. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  753. ),
  754. ),
  755. )
  756. it.live("treats a sibling path inside the project worktree as internal", () =>
  757. Effect.acquireUseRelease(
  758. Effect.promise(() => tmpdir()),
  759. (tmp) => {
  760. reset()
  761. const active = path.join(tmp.path, "active")
  762. const target = path.join(tmp.path, "sibling.txt")
  763. return Effect.promise(() => Promise.all([fs.mkdir(active), fs.writeFile(target, "before\n")])).pipe(
  764. Effect.andThen(
  765. withTool(
  766. active,
  767. (registry) =>
  768. Effect.gen(function* () {
  769. expect(
  770. yield* executeTool(
  771. registry,
  772. call("*** Begin Patch\n*** Update File: ../sibling.txt\n@@\n-before\n+after\n*** End Patch"),
  773. ),
  774. ).toMatchObject({ type: "text" })
  775. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  776. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
  777. }),
  778. tmp.path,
  779. ),
  780. ),
  781. )
  782. },
  783. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  784. ),
  785. )
  786. it.live("follows an internal symlink to an external file without external permission", () =>
  787. Effect.acquireUseRelease(
  788. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  789. ([active, outside]) => {
  790. reset()
  791. if (process.platform === "win32") return Effect.void
  792. const target = path.join(outside.path, "external.txt")
  793. const link = path.join(active.path, "link.txt")
  794. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  795. Effect.andThen(Effect.promise(() => fs.symlink(target, link))),
  796. Effect.andThen(
  797. withTool(active.path, (registry) =>
  798. Effect.gen(function* () {
  799. expect(
  800. yield* executeTool(
  801. registry,
  802. call("*** Begin Patch\n*** Update File: link.txt\n@@\n-before\n+after\n*** End Patch"),
  803. ),
  804. ).toMatchObject({ type: "text" })
  805. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  806. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
  807. }),
  808. ),
  809. ),
  810. )
  811. },
  812. ([active, outside]) =>
  813. Effect.promise(() =>
  814. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  815. ),
  816. ),
  817. )
  818. it.live("approves a relative external target before reading and requests edit permission afterward", () =>
  819. Effect.acquireUseRelease(
  820. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  821. ([active, outside]) => {
  822. reset()
  823. const target = path.join(outside.path, "external.txt")
  824. const relative = path.relative(active.path, target)
  825. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  826. Effect.andThen(
  827. withTool(active.path, (registry) =>
  828. Effect.gen(function* () {
  829. expect(
  830. yield* executeTool(
  831. registry,
  832. call(`*** Begin Patch\n*** Update File: ${relative}\n@@\n-before\n+after\n*** End Patch`),
  833. ),
  834. ).toMatchObject({ type: "text" })
  835. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  836. expect(readsBeforeEditApproval).toBe(1)
  837. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
  838. }),
  839. ),
  840. ),
  841. )
  842. },
  843. ([active, outside]) =>
  844. Effect.promise(() =>
  845. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  846. ),
  847. ),
  848. )
  849. it.live("approves each external file under the same parent", () =>
  850. Effect.acquireUseRelease(
  851. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  852. ([active, outside]) => {
  853. reset()
  854. const first = path.join(outside.path, "first.txt")
  855. const second = path.join(outside.path, "second.txt")
  856. return Effect.promise(() =>
  857. Promise.all([fs.writeFile(first, "before\n"), fs.writeFile(second, "before\n")]),
  858. ).pipe(
  859. Effect.andThen(
  860. withTool(active.path, (registry) =>
  861. Effect.gen(function* () {
  862. expect(
  863. yield* executeTool(
  864. registry,
  865. call(
  866. `*** Begin Patch\n*** Update File: ${first}\n@@\n-before\n+after\n*** Update File: ${second}\n@@\n-before\n+after\n*** End Patch`,
  867. ),
  868. ),
  869. ).toMatchObject({ type: "text" })
  870. expect(assertions.map((input) => input.action)).toEqual([
  871. "external_directory",
  872. "external_directory",
  873. "edit",
  874. ])
  875. expect(assertions[0]?.resources).toEqual([
  876. process.platform === "win32"
  877. ? FSUtil.normalizePathPattern(path.join(outside.path, "*"))
  878. : path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "*").replaceAll("\\", "/"),
  879. ])
  880. expect(assertions[1]?.resources).toEqual(assertions[0]?.resources)
  881. }),
  882. ),
  883. ),
  884. )
  885. },
  886. ([active, outside]) =>
  887. Effect.promise(() =>
  888. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  889. ),
  890. ),
  891. )
  892. it.live("rejects invalid later update before applying an earlier add", () =>
  893. Effect.acquireUseRelease(
  894. Effect.promise(() => tmpdir()),
  895. (tmp) => {
  896. reset()
  897. return withTool(tmp.path, (registry) =>
  898. Effect.gen(function* () {
  899. expect(
  900. yield* executeTool(
  901. registry,
  902. call(
  903. "*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: missing.txt\n@@\n-before\n+after\n*** End Patch",
  904. ),
  905. ),
  906. ).toMatchObject({
  907. type: "error",
  908. value: expect.stringContaining("patch verification failed: Failed to read file to update"),
  909. })
  910. expect(yield* exists(path.join(tmp.path, "created.txt"))).toBe(false)
  911. }),
  912. )
  913. },
  914. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  915. ),
  916. )
  917. it.live("adds files by overwriting existing targets", () =>
  918. Effect.acquireUseRelease(
  919. Effect.promise(() => tmpdir()),
  920. (tmp) => {
  921. reset()
  922. const target = path.join(tmp.path, "existing.txt")
  923. return Effect.promise(() => fs.writeFile(target, "sentinel\n")).pipe(
  924. Effect.andThen(
  925. withTool(tmp.path, (registry) =>
  926. Effect.gen(function* () {
  927. expect(
  928. yield* executeTool(
  929. registry,
  930. call("*** Begin Patch\n*** Add File: existing.txt\n+replacement\n*** End Patch"),
  931. ),
  932. ).toMatchObject({ type: "text" })
  933. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("replacement\n")
  934. }),
  935. ),
  936. ),
  937. )
  938. },
  939. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  940. ),
  941. )
  942. it.live("overwrites an add target that appears during permission approval", () =>
  943. Effect.acquireUseRelease(
  944. Effect.promise(() => tmpdir()),
  945. (tmp) => {
  946. reset()
  947. const target = path.join(tmp.path, "appeared.txt")
  948. afterEditApproval = () => Effect.promise(() => fs.writeFile(target, "winner\n")).pipe(Effect.orDie)
  949. return withTool(tmp.path, (registry) =>
  950. Effect.gen(function* () {
  951. expect(
  952. yield* executeTool(
  953. registry,
  954. call("*** Begin Patch\n*** Add File: appeared.txt\n+replacement\n*** End Patch"),
  955. ),
  956. ).toMatchObject({ type: "text" })
  957. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("replacement\n")
  958. }),
  959. )
  960. },
  961. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  962. ),
  963. )
  964. it.live("preserves a later commit defect after earlier sequential applications", () =>
  965. Effect.acquireUseRelease(
  966. Effect.promise(() => tmpdir()),
  967. (tmp) => {
  968. reset()
  969. const first = path.join(tmp.path, "first.txt")
  970. const second = path.join(tmp.path, "second.txt")
  971. failRemoveTarget = path.basename(second)
  972. return Effect.promise(() => Promise.all([fs.writeFile(first, "first"), fs.writeFile(second, "second")])).pipe(
  973. Effect.andThen(
  974. withTool(tmp.path, (registry) =>
  975. Effect.gen(function* () {
  976. expect(
  977. Exit.isFailure(
  978. yield* executeTool(
  979. registry,
  980. call("*** Begin Patch\n*** Delete File: first.txt\n*** Delete File: second.txt\n*** End Patch"),
  981. ).pipe(Effect.exit),
  982. ),
  983. ).toBe(true)
  984. expect(yield* exists(first)).toBe(false)
  985. expect(yield* exists(second)).toBe(true)
  986. }),
  987. ),
  988. ),
  989. )
  990. },
  991. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  992. ),
  993. )
  994. })