Skip to content

Open-source, local-first AI agent for real work.

15.5 KB
Raw Blame
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
	createEditTool,
	createEditToolRegistration,
	EDIT_TOOL_DESCRIPTION,
	type EditOperations,
	type EditPathPolicy,
	type EditToolInput,
	EditToolInputSchema,
} from "../../../src/coding/index.js";
import { createTestEditPathPolicy } from "../../support/path-policy.js";

const temporaryDirectories: string[] = [];
const permissivePathPolicy: EditPathPolicy = {
	getRejectionReason: () => undefined,
};

afterEach(() => {
	for (const directory of temporaryDirectories) rmSync(directory, { recursive: true, force: true });
	temporaryDirectories.length = 0;
});

function createTemporaryDirectory(label: string): string {
	const directory = mkdtempSync(join(tmpdir(), `vetta-runtime-edit-${label}-`));
	temporaryDirectories.push(directory);
	return directory;
}

function runtimeRequest(input: EditToolInput, signal = new AbortController().signal) {
	return {
		sessionId: "session-1",
		turnId: "turn-1",
		toolCallId: "runtime-edit",
		input,
		signal,
	};
}

async function errorMessage(operation: Promise<unknown>): Promise<string> {
	try {
		await operation;
		throw new Error("expected operation to reject");
	} catch (error: unknown) {
		return error instanceof Error ? error.message : String(error);
	}
}

async function compareExactEdit(options: {
	readonly label: string;
	readonly initial: string;
	readonly oldText: string;
	readonly newText: string;
	readonly expected: string;
}): Promise<void> {
	const runtimeDirectory = createTemporaryDirectory(options.label);
	writeFileSync(join(runtimeDirectory, "file.txt"), options.initial);
	const input = { path: "file.txt", oldText: options.oldText, newText: options.newText };
	const runtimeResult = await createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(
		runtimeRequest(input),
	);
	expect(runtimeResult.content[0]).toMatchObject({ text: "Successfully replaced text in file.txt." });
	expect(readFileSync(join(runtimeDirectory, "file.txt"), "utf-8")).toBe(options.expected);
}

describe("runtime edit tool", () => {
	it("keeps the public runtime definition", () => {
		const runtime = createEditToolRegistration(process.cwd(), { pathPolicy: permissivePathPolicy });
		expect(runtime.tool).toMatchObject({
			name: "edit",
			label: "edit",
			description: EDIT_TOOL_DESCRIPTION,
			inputSchema: EditToolInputSchema,
		});
	});

	it.each([
		{
			label: "exact",
			initial: "first\nsecond\nthird\n",
			oldText: "second\n",
			newText: "changed\n",
			expected: "first\nchanged\nthird\n",
		},
		{
			label: "fuzzy-whitespace",
			initial: "first   \nsecond  \nthird\n",
			oldText: "first\nsecond\n",
			newText: "changed\n",
			expected: "changed\nthird\n",
		},
		{
			label: "unicode-normalization",
			initial: "const value = ‘one—two’;\n",
			oldText: "const value = 'one-two';",
			newText: "const value = 'changed';",
			expected: "const value = 'changed';\n",
		},
		{
			label: "crlf-bom",
			initial: "\uFEFFfirst\r\nsecond\r\nthird\r\n",
			oldText: "second\n",
			newText: "changed\n",
			expected: "\uFEFFfirst\r\nchanged\r\nthird\r\n",
		},
	])("preserves exact-text behavior for $label", compareExactEdit);

	it.each([
		{
			label: "missing text",
			initial: "alpha\n",
			oldText: "missing",
			newText: "changed",
		},
		{
			label: "duplicate text",
			initial: "same   \nsame\n",
			oldText: "same",
			newText: "changed",
		},
		{
			label: "identical replacement",
			initial: "same\n",
			oldText: "same",
			newText: "same",
		},
	])("preserves exact-text rejection for $label", async ({ label, initial, oldText, newText }) => {
		const runtimeDirectory = createTemporaryDirectory(`error-${label}`);
		writeFileSync(join(runtimeDirectory, "file.txt"), initial);
		const input = { path: "file.txt", oldText, newText };
		const runtimeError = await errorMessage(
			createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(runtimeRequest(input)),
		);
		expect(runtimeError).toMatch(
			label === "missing text"
				? /Could not find the exact text/
				: label === "duplicate text"
					? /Found 2 occurrences/
					: /No changes made/,
		);
		expect(readFileSync(join(runtimeDirectory, "file.txt"), "utf-8")).toBe(initial);
	});

	it("preserves atomic block replacement, receipts, and diff details", async () => {
		const initial = ["const a = 1;", "const b = 2;", "const c = 3;", "const d = 4;"].join("\n");
		const runtimeDirectory = createTemporaryDirectory("block-batch");
		writeFileSync(join(runtimeDirectory, "file.ts"), initial);
		const input = {
			path: "file.ts",
			edits: [
				{ oldText: "const a = 1;", newText: "const a = 10;\nconst added = 11;" },
				{ oldText: "const c = 3;", newText: "const afterC = 30;" },
			],
		};
		const runtimeResult = await createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(
			runtimeRequest(input),
		);
		expect(runtimeResult.details).toMatchObject({ appliedEdits: 2 });
		expect(readFileSync(join(runtimeDirectory, "file.ts"), "utf-8")).toBe(
			["const a = 10;", "const added = 11;", "const b = 2;", "const afterC = 30;", "const d = 4;"].join("\n"),
		);
	});

	it("locates blocks by text across unrelated line shifts", async () => {
		const runtimeDirectory = createTemporaryDirectory("block-shift");
		writeFileSync(join(runtimeDirectory, "file.txt"), ["a", "b", "c", "d"].join("\n"));
		const input = {
			path: "file.txt",
			edits: [
				{ oldText: "c", newText: "C" },
				{ oldText: "d", newText: "D" },
			],
		};
		const runtimeResult = await createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(
			runtimeRequest(input),
		);
		expect(runtimeResult.content[0]).toMatchObject({ text: expect.stringContaining("Applied 2 block edit(s)") });
		expect(readFileSync(join(runtimeDirectory, "file.txt"), "utf-8")).toBe("a\nb\nC\nD");
	});

	it.each([
		{
			label: "unmatched block",
			initial: ["const a = 1;", "const b = 2;", "const c = 3;"].join("\n"),
			input: {
				path: "file.ts",
				edits: [
					{ oldText: "const a = 1;", newText: "const a = 10;" },
					{ oldText: "const zzz = 9;", newText: "const c = 30;" },
				],
			},
		},
		{
			label: "overlapping blocks",
			initial: ["const a = 1;", "const b = 2;", "const c = 3;"].join("\n"),
			input: {
				path: "file.ts",
				edits: [
					{ oldText: "const a = 1;", oldEndText: "const c = 3;", newText: "x" },
					{ oldText: "const b = 2;", newText: "y" },
				],
			},
		},
		{
			label: "dropped structural closer",
			initial: ["function value() {", "  return 1;", "}"].join("\n"),
			input: {
				path: "file.ts",
				edits: [{ oldText: "return 1;", oldEndText: "}", newText: "  return 1;" }],
			},
		},
	])("preserves rejection and atomicity for $label", async ({ label, initial, input }) => {
		const runtimeDirectory = createTemporaryDirectory(label);
		writeFileSync(join(runtimeDirectory, "file.ts"), initial);
		const runtimeError = await errorMessage(
			createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(runtimeRequest(input)),
		);
		expect(runtimeError).toMatch(/could not be located|overlap|structurally broken/i);
		expect(readFileSync(join(runtimeDirectory, "file.ts"), "utf-8")).toBe(initial);
	});

	it.each([
		{ path: "file.txt", oldText: "a", newText: "b", edits: [] },
		{ path: "file.txt" },
		{ path: "file.txt", edits: [] },
	])("preserves mode and payload validation for %#", async (input) => {
		const directory = createTemporaryDirectory("payload");
		writeFileSync(join(directory, "file.txt"), "a");
		const runtimeError = await errorMessage(
			createEditTool(directory, { pathPolicy: permissivePathPolicy }).execute(runtimeRequest(input)),
		);
		expect(runtimeError).toMatch(/not both|missing edit payload|edits array is empty/i);
	});

	describe("replaceAll", () => {
		async function runEdit(initial: string, input: Omit<EditToolInput, "path">, fileName = "file.tsx") {
			const runtimeDirectory = createTemporaryDirectory("replace-all");
			writeFileSync(join(runtimeDirectory, fileName), initial);
			const tool = createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy });
			const run = () => tool.execute(runtimeRequest({ path: fileName, ...input }));
			const readBack = () => readFileSync(join(runtimeDirectory, fileName), "utf-8");
			return { run, readBack };
		}

		const selectorFile = [
			"await renderAskBar()",
			"const trigger = container.querySelector('button[aria-label=\"Recipes\"]')",
			"expect(trigger).not.toBeNull()",
			"await renderAskBar()",
			"const trigger = container.querySelector('button[aria-label=\"Recipes\"]')!",
			"await act(async () => trigger.click())",
		].join("\n");

		it("changes every occurrence of a repeated selector in one call and reports the count", async () => {
			const { run, readBack } = await runEdit(selectorFile, {
				oldText: 'button[aria-label="Recipes"]',
				newText: 'button[aria-label="Quick prompts"]',
				replaceAll: true,
			});

			const result = await run();

			expect(result.content[0]).toMatchObject({ text: expect.stringContaining("replaced 2 occurrences") });
			expect(readBack()).toBe(selectorFile.replaceAll('"Recipes"', '"Quick prompts"'));
		});

		it("without replaceAll still refuses a repeated text and points at replaceAll", async () => {
			const { run, readBack } = await runEdit(selectorFile, {
				oldText: 'button[aria-label="Recipes"]',
				newText: 'button[aria-label="Quick prompts"]',
			});

			const message = await errorMessage(run());

			expect(message).toMatch(/Found 2 occurrences/);
			expect(message).toContain("replaceAll: true");
			expect(readBack()).toBe(selectorFile);
		});

		it("points a block edit that matches several places at replaceAll", async () => {
			const { run, readBack } = await runEdit(selectorFile, {
				edits: [{ oldText: "await renderAskBar()", newText: "await renderAskBar({})" }],
			});

			expect(await errorMessage(run())).toContain("`replaceAll: true`");
			expect(readBack()).toBe(selectorFile);
		});

		it("keeps CRLF line endings and replaces a single occurrence like a normal edit", async () => {
			const { run, readBack } = await runEdit("a = 1\r\nb = 2\r\n", {
				oldText: "b = 2",
				newText: "b = 3",
				replaceAll: true,
			});

			const result = await run();

			expect(result.content[0]).toMatchObject({ text: "Successfully replaced text in file.tsx." });
			expect(readBack()).toBe("a = 1\r\nb = 3\r\n");
		});

		it("replaces multi-line occurrences without touching overlapping text twice", async () => {
			const { run, readBack } = await runEdit(
				"x\nx\nx\n",
				{ oldText: "x\nx", newText: "y", replaceAll: true },
				"f.txt",
			);

			await run();

			expect(readBack()).toBe("y\nx\n");
		});

		it("matches every occurrence when oldText uses typographic quotes the file does not", async () => {
			const { run, readBack } = await runEdit(
				"say('hi')\nsay('hi')\n",
				{
					oldText: "say(\u2018hi\u2019)",
					newText: "say('bye')",
					replaceAll: true,
				},
				"f.txt",
			);

			await run();

			expect(readBack()).toBe("say('bye')\nsay('bye')\n");
		});

		it("rejects an empty oldText and a combination with block edits, writing nothing", async () => {
			const empty = await runEdit("abc", { oldText: "", newText: "x", replaceAll: true }, "f.txt");
			expect(await errorMessage(empty.run())).toMatch(/non-empty oldText/);
			expect(empty.readBack()).toBe("abc");

			const mixed = await runEdit("abc", { edits: [{ oldText: "abc", newText: "x" }], replaceAll: true }, "f.txt");
			expect(await errorMessage(mixed.run())).toMatch(/only applies to exact-text mode/);
			expect(mixed.readBack()).toBe("abc");
		});
	});

	it("preserves fuzzy existing-path resolution without rewriting path-like replacement text", async () => {
		const runtimeDirectory = createTemporaryDirectory("path");
		const exactName = "招标文件-发布稿.txt";
		const requestedName = "招标文件 - 发布稿.txt";
		writeFileSync(join(runtimeDirectory, exactName), 'const path = "old.docx";\n');
		const input = { path: requestedName, oldText: '"old.docx"', newText: '"招标文件 - 发布稿.docx"' };
		const runtimeResult = await createEditTool(runtimeDirectory, { pathPolicy: permissivePathPolicy }).execute(
			runtimeRequest(input),
		);
		expect(runtimeResult.content[0]).toMatchObject({ text: expect.stringContaining("Successfully replaced text") });
		expect(readFileSync(join(runtimeDirectory, exactName), "utf-8")).toContain('"招标文件 - 发布稿.docx"');
	});

	it.each([".vetta/skills/file.txt", ".agents/skills/file.txt"])(
		"preserves protected skill path rejection for %s",
		async (path) => {
			const cwd = createTemporaryDirectory("protected");
			const input = { path, oldText: "a", newText: "b" };
			const runtimeError = await errorMessage(
				createEditTool(cwd, {
					pathPolicy: createTestEditPathPolicy({ cwd, knowledgeRoot: join(cwd, "knowledges") }),
				}).execute(runtimeRequest(input)),
			);
			expect(runtimeError).toContain("inside a skill directory");
		},
	);

	it("preserves knowledge wiki rejection", async () => {
		const cwd = createTemporaryDirectory("wiki");
		const knowledgeRoot = join(cwd, "knowledges");
		const input = { path: join(knowledgeRoot, "wiki", "page.md"), oldText: "a", newText: "b" };
		const runtimeError = await errorMessage(
			createEditTool(cwd, { pathPolicy: createTestEditPathPolicy({ cwd, knowledgeRoot }) }).execute(
				runtimeRequest(input),
			),
		);
		expect(runtimeError).toContain("managed exclusively by kb_write_page");
	});

	it("preserves exact-mode operation order and early cancellation", async () => {
		const cwd = createTemporaryDirectory("operations");
		const calls: string[] = [];
		const operations: EditOperations = {
			access: async (path) => {
				calls.push(`access:${path}`);
			},
			readFile: async (path) => {
				calls.push(`read:${path}`);
				return Buffer.from("old");
			},
			writeFile: async (path, content) => {
				calls.push(`write:${path}:${content}`);
			},
		};
		await expect(
			createEditTool(cwd, { operations, pathPolicy: permissivePathPolicy }).execute(
				runtimeRequest({ path: "file.txt", edits: [] }),
			),
		).rejects.toThrow("edits array is empty");
		expect(calls).toEqual([]);

		const controller = new AbortController();
		controller.abort();
		await expect(
			createEditTool(cwd, { operations, pathPolicy: permissivePathPolicy }).execute(
				runtimeRequest({ path: "file.txt", oldText: "old", newText: "new" }, controller.signal),
			),
		).rejects.toThrow("Operation aborted");
		expect(calls).toEqual([]);

		const result = await createEditTool(cwd, { operations, pathPolicy: permissivePathPolicy }).execute(
			runtimeRequest({ path: "file.txt", oldText: "old", newText: "new" }),
		);
		expect(result.content[0]).toMatchObject({ text: "Successfully replaced text in file.txt." });
		expect(calls.map((call) => call.split(":", 1)[0])).toEqual(["access", "read", "write"]);
	});

	it("preserves block-mode cooperative cancellation after reading", async () => {
		const cwd = createTemporaryDirectory("anchor-abort");
		const controller = new AbortController();
		const calls: string[] = [];
		const operations: EditOperations = {
			access: async () => {
				calls.push("access");
			},
			readFile: async () => {
				calls.push("read");
				controller.abort();
				return Buffer.from("old");
			},
			writeFile: async () => {
				calls.push("write");
			},
		};
		await expect(
			createEditTool(cwd, { operations, pathPolicy: permissivePathPolicy }).execute(
				runtimeRequest({ path: "file.txt", edits: [{ oldText: "old", newText: "new" }] }, controller.signal),
			),
		).rejects.toThrow("Operation aborted");
		expect(calls).toEqual(["access", "read"]);
	});
});