import { afterEach, beforeEach, expect, it, vi } from "bun:test"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import type { AgentToolResult } from "@sayknow-cli/agent-core"; import { resetSettingsForTest, Settings } from "@sayknow-cli/coding-agent/config/settings"; import { EditTool } from "@sayknow-cli/coding-agent/edit"; import * as pathMutationLock from "@sayknow-cli/coding-agent/edit/path-mutation-lock"; import type { ToolSession } from "@sayknow-cli/coding-agent/tools"; import * as autoGeneratedGuard from "@sayknow-cli/coding-agent/tools/auto-generated-guard"; function makeSession(cwd: string, blockAutoGenerated: boolean, mode: "patch" | "apply_patch" = "patch"): ToolSession { return { cwd, hasUI: false, getSessionFile: () => null, getSessionSpawns: () => "*", enableLsp: false, settings: Settings.isolated({ "edit.mode": mode, "edit.blockAutoGenerated": blockAutoGenerated, }), getArtifactsDir: () => null, getSessionId: () => null, getPlanModeState: () => undefined, } as unknown as ToolSession; } const SOURCE = "line\n"; const MOVED = "moved\n"; const DIFF = "@@\n-line\n+moved"; let tempDir: string; beforeEach(async () => { resetSettingsForTest(); tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "edit-patch-rename-autogen-")); await Settings.init({ inMemory: true, cwd: tempDir, overrides: { "edit.blockAutoGenerated": true } }); }); afterEach(async () => { resetSettingsForTest(); await fs.promises.rm(tempDir, { recursive: true, force: true }); }); async function writePair(sourceName: string, destName: string, destBody: string): Promise { await Bun.write(path.join(tempDir, sourceName), SOURCE); await Bun.write(path.join(tempDir, destName), destBody); } function patchRename(blockAutoGenerated: boolean, sourceName: string, destName: string) { const tool = new EditTool(makeSession(tempDir, blockAutoGenerated, "patch")); return tool.execute("patch-rename-autogen", { path: sourceName, edits: [{ op: "update", rename: destName, diff: DIFF }], }); } it("refuses to rename a patch onto an existing auto-generated file", async () => { const destBody = "package widget\n"; await writePair("product.ts", "widget.pb.go", destBody); await expect(patchRename(true, "product.ts", "widget.pb.go")).rejects.toThrow(/Cannot modify auto-generated file/); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "widget.pb.go")).text()).toBe(destBody); }); it("refuses to rename a patch onto a file with an auto-generated header", async () => { const destBody = "// Code generated by sqlc. DO NOT EDIT.\nexport const foo = 1;\n"; await writePair("product.ts", "queries.ts", destBody); await expect(patchRename(true, "product.ts", "queries.ts")).rejects.toThrow(/Cannot modify auto-generated file/); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "queries.ts")).text()).toBe(destBody); }); it("still allows a patch rename onto an existing handwritten file", async () => { await writePair("product.ts", "notes.ts", "keep\n"); const result = await patchRename(true, "product.ts", "notes.ts"); expect(result.isError).toBeUndefined(); expect(await Bun.file(path.join(tempDir, "notes.ts")).text()).toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).exists()).toBe(false); }); it("refuses to rename a patch onto a missing auto-generated filename", async () => { await Bun.write(path.join(tempDir, "product.ts"), SOURCE); await expect(patchRename(true, "product.ts", "fresh.generated.ts")).rejects.toThrow( /Cannot modify auto-generated file/, ); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "fresh.generated.ts")).exists()).toBe(false); }); it("still allows a patch rename onto a new handwritten path", async () => { await Bun.write(path.join(tempDir, "product.ts"), SOURCE); const result = await patchRename(true, "product.ts", "out.ts"); expect(result.isError).toBeUndefined(); expect(await Bun.file(path.join(tempDir, "out.ts")).text()).toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).exists()).toBe(false); }); it("refuses a later patch rename onto an auto-generated file before writing the earlier edit", async () => { const source = path.join(tempDir, "product.ts"); await Bun.write(source, SOURCE); await Bun.write(path.join(tempDir, "widget.pb.go"), "package widget\n"); const tool = new EditTool(makeSession(tempDir, true, "patch")); const result = await tool.execute("patch-rename-multi", { path: "product.ts", edits: [ { op: "update", diff: DIFF }, { op: "update", rename: "widget.pb.go", diff: "@@\n-moved\n+again" }, ], }); expect(result.isError).toBe(true); const text = result.content?.find(block => block.type === "text")?.text ?? ""; expect(text).toContain("Cannot modify auto-generated file"); expect((result.details as { diff?: string } | undefined)?.diff ?? "").toBe(""); expect(await Bun.file(source).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "widget.pb.go")).text()).toBe("package widget\n"); }); it("refuses an apply_patch rename onto an auto-generated file before writing an earlier file", async () => { await Bun.write(path.join(tempDir, "first.ts"), "old\n"); await Bun.write(path.join(tempDir, "product.ts"), SOURCE); await Bun.write(path.join(tempDir, "widget.pb.go"), "package widget\n"); const tool = new EditTool(makeSession(tempDir, true, "apply_patch")); const input = [ "*** Begin Patch", "*** Update File: first.ts", "@@", "-old", "+changed", "*** Update File: product.ts", "*** Move to: widget.pb.go", "@@", "-line", "+moved", "*** End Patch", ].join("\n"); const result = await tool.execute("apply-patch-rename-autogen", { input }); expect(result.isError).toBe(true); const text = result.content?.find(block => block.type === "text")?.text ?? ""; expect(text).toContain("Cannot modify auto-generated file"); expect((result.details as { diff?: string } | undefined)?.diff ?? "").toBe(""); expect(await Bun.file(path.join(tempDir, "first.ts")).text()).toBe("old\n"); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "widget.pb.go")).text()).toBe("package widget\n"); }); it("still allows two handwritten files in one apply_patch", async () => { await Bun.write(path.join(tempDir, "a.ts"), "a\n"); await Bun.write(path.join(tempDir, "c.ts"), "c\n"); const tool = new EditTool(makeSession(tempDir, true, "apply_patch")); const input = [ "*** Begin Patch", "*** Update File: a.ts", "@@", "-a", "+b", "*** Update File: c.ts", "@@", "-c", "+d", "*** End Patch", ].join("\n"); const result = await tool.execute("apply-patch-two-handwritten", { input }); expect(result.isError).toBeUndefined(); expect(await Bun.file(path.join(tempDir, "a.ts")).text()).toBe("b\n"); expect(await Bun.file(path.join(tempDir, "c.ts")).text()).toBe("d\n"); }); it("still allows a patch rename onto an auto-generated file when the setting is off", async () => { await writePair("product.ts", "widget.pb.go", "package widget\n"); const result = await patchRename(false, "product.ts", "widget.pb.go"); expect(result.isError).toBeUndefined(); expect(await Bun.file(path.join(tempDir, "widget.pb.go")).text()).toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).exists()).toBe(false); }); function applyPatchRenameAfterUpdate(firstDiff: string, moveTo: string): Promise> { const tool = new EditTool(makeSession(tempDir, true, "apply_patch")); const input = [ "*** Begin Patch", "*** Update File: output.ts", "@@", ...firstDiff.split("\n"), "*** Update File: product.ts", `*** Move to: ${moveTo}`, "@@", "-line", "+moved", "*** End Patch", ].join("\n"); return tool.execute("apply-patch-rename-after-update", { input }); } it("refuses a later rename after an earlier entry writes a generated header", async () => { const outputPath = path.join(tempDir, "output.ts"); await Bun.write(outputPath, "hand\n"); await Bun.write(path.join(tempDir, "product.ts"), SOURCE); const result = await applyPatchRenameAfterUpdate( "-hand\n+// Code generated by sqlc. DO NOT EDIT.\n+export const kept = 1;", "output.ts", ); const text = result.content?.find(block => block.type === "text")?.text ?? ""; expect(text).toContain("Cannot modify auto-generated file"); expect(await Bun.file(outputPath).text()).toContain("Code generated by sqlc"); expect(await Bun.file(outputPath).text()).not.toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); }); it("still allows a later rename after an earlier entry leaves the destination handwritten", async () => { const outputPath = path.join(tempDir, "output.ts"); await Bun.write(outputPath, "hand\n"); await Bun.write(path.join(tempDir, "product.ts"), SOURCE); const result = await applyPatchRenameAfterUpdate("-hand\n+note", "output.ts"); expect(result.isError).toBeUndefined(); expect(await Bun.file(outputPath).text()).toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).exists()).toBe(false); }); it("aborts a multi-entry patch between destination checks", async () => { await Bun.write(path.join(tempDir, "product.ts"), SOURCE); const controller = new AbortController(); let calls = 0; const spy = vi.spyOn(autoGeneratedGuard, "assertEditableFile").mockImplementation(async () => { calls += 1; if (calls === 1) controller.abort(); }); const tool = new EditTool(makeSession(tempDir, true, "patch")); try { await expect( tool.execute( "patch-abort-between", { path: "product.ts", edits: [ { op: "update", diff: DIFF }, { op: "update", diff: "@@\n-moved\n+again" }, ], }, controller.signal, ), ).rejects.toThrow(/abort/i); } finally { spy.mockRestore(); } expect(calls).toBe(1); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); }); it("aborts a patch rename between its source and destination guards", async () => { await Bun.write(path.join(tempDir, "product.ts"), SOURCE); const controller = new AbortController(); let calls = 0; const spy = vi.spyOn(autoGeneratedGuard, "assertEditableFile").mockImplementation(async () => { calls += 1; if (calls === 1) controller.abort(); }); const tool = new EditTool(makeSession(tempDir, true, "patch")); try { await expect( tool.execute( "patch-abort-between-rename-guards", { path: "product.ts", edits: [{ op: "update", rename: "renamed.ts", diff: DIFF }], }, controller.signal, ), ).rejects.toThrow(/abort/i); } finally { spy.mockRestore(); } expect(calls).toBe(1); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "renamed.ts")).exists()).toBe(false); }); const GENERATED_DEST = "// Code generated by sqlc. DO NOT EDIT.\nexport const foo = 1;\n"; /** * Hold the destination mutation lock, start a public patch rename, and run * `whileBlocked` only after that rename has entered the lock and is waiting. */ async function renameWhileDestLocked( destName: string, whileBlocked: (destAbs: string) => Promise, ): Promise> { const destAbs = path.resolve(tempDir, destName); let releaseHold = (): void => {}; const entered = Promise.withResolvers(); const hold = pathMutationLock.withEditPathMutation( [destAbs], async () => { entered.resolve(); await new Promise(resolve => { releaseHold = resolve; }); }, { crossProcess: false }, ); await entered.promise; const blocked = Promise.withResolvers(); const realLock = pathMutationLock.withEditPathMutation; const spy = vi.spyOn(pathMutationLock, "withEditPathMutation").mockImplementation((paths, fn, opts) => { blocked.resolve(); return realLock(paths, fn, opts); }); const pending = patchRename(true, "product.ts", destName); try { const arrived = await Promise.race([ blocked.promise.then(() => "blocked" as const), pending.then( () => "settled" as const, () => "settled" as const, ), ]); if (arrived === "blocked") await whileBlocked(destAbs); releaseHold(); return await pending; } finally { releaseHold(); spy.mockRestore(); await hold; } } it("refuses a patch rename when a concurrent edit turns the destination generated before the move commits", async () => { await writePair("product.ts", "notes.ts", "keep\n"); await expect( renameWhileDestLocked("notes.ts", async destAbs => { await Bun.write(destAbs, GENERATED_DEST); }), ).rejects.toThrow(/Cannot modify auto-generated file/); expect(await Bun.file(path.join(tempDir, "product.ts")).text()).toBe(SOURCE); expect(await Bun.file(path.join(tempDir, "notes.ts")).text()).toBe(GENERATED_DEST); }); it("still allows a patch rename when a concurrent edit leaves the destination handwritten", async () => { await writePair("product.ts", "notes.ts", "keep\n"); const result = await renameWhileDestLocked("notes.ts", async destAbs => { await Bun.write(destAbs, "note\n"); }); expect(result.isError).toBeUndefined(); expect(await Bun.file(path.join(tempDir, "notes.ts")).text()).toBe(MOVED); expect(await Bun.file(path.join(tempDir, "product.ts")).exists()).toBe(false); });