diff --git a/.changeset/2486-literal-edit-replacement.md b/.changeset/2486-literal-edit-replacement.md new file mode 100644 index 0000000000..e944d517dd --- /dev/null +++ b/.changeset/2486-literal-edit-replacement.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-backend-pi": patch +"@schlessera/brain-backend-claude": patch +"@schlessera/brain-ui-server": patch +--- + +`edit_file` now writes `new_string` exactly as given. Before, `$$`, `$&`, `` $` `` and `$'` in it were expanded as replacement patterns, so LaTeX display math, a price like `$$5` or a shell snippet changed on its way to disk. This applies to the pi backend's direct edit and to the hosted application route. The Claude backend now also records the version of a native `Edit` from the same literal bytes the runtime wrote, so a later write to that file is no longer refused as stale. diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index d4f2598d0e..98499c0ec2 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -165,7 +165,10 @@ export function createNativeFileGuards(options: PermissionWiringOptions) { let written: string | undefined; if (hookInput.tool_name === "Write" && typeof response?.content === "string") written = response.content; if (hookInput.tool_name === "Edit" && typeof response?.originalFile === "string" && typeof response.oldString === "string" && typeof response.newString === "string") { - if (response.originalFile.includes(response.oldString)) written = response.replaceAll ? response.originalFile.replaceAll(response.oldString, response.newString) : response.originalFile.replace(response.oldString, response.newString); + // Rebuilt literally, as the runtime applies an Edit: a string + // replacement would expand `$` sequences in newString (#2486). + const newString = response.newString; + if (response.originalFile.includes(response.oldString)) written = response.replaceAll ? response.originalFile.replaceAll(response.oldString, () => newString) : response.originalFile.replace(response.oldString, () => newString); } if (written !== undefined) await fileVersions.remember(current.key, createHash("sha256").update(written, "utf8").digest("hex")); else await fileVersions.finishWrite(current.key, current.version); diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 17dbcc1f1d..a7c182bbdf 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -3,6 +3,7 @@ * The whole-wiring behaviour stays pinned by characterization-permissions, * allowlist-enforcement, confirm-bash, confirm-archive and edited-approval. */ +import { createHash } from "node:crypto"; import { describe, expect, test } from "bun:test"; import type { PermissionRequest } from "@schlessera/brain-ui-sdk/server"; @@ -201,3 +202,24 @@ describe("admissions, refusals and the collector's last check", () => { expect(admitted, "CLAUDE_REUSED_ID_ADMISSION_IS_REPORTED_ONCE").toEqual(["oar-4", "oar-4"]); }); }); + +describe("native edit versions", () => { + // The installed runtime applies an Edit literally (a function replacement), + // so the version the host remembers must hash the same literal bytes. + for (const replaceAll of [false, true]) test(`a native Edit${replaceAll ? " with replaceAll" : ""} whose newString has $ sequences remembers the literal result`, async () => { + const remembered: [string, string][] = []; + const options = { + req: { prompt: "Mend the loom", signal: new AbortController().signal, bridge: { emit: () => {} } } as never, + allowedTools: ["Edit"], confirmPatterns: [], brainPath: "/srv/odysseus-brain", childEnv: {}, log: () => {}, + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never, + observeFile: () => ({ key: "loom.md", version: { status: "unavailable" } }), + fileVersions: { remember: async (key: string, hash: string) => { remembered.push([key, hash]); }, finishWrite: async () => { throw new Error("the written bytes were known"); } } as never, + } as PermissionWiringOptions; + const { finishNativeFile } = createNativeFileGuards(options); + const originalFile = "Penelope weaves. Penelope waits.\n", newString = "Odysseus pays $$5 for $& and $' and $`"; + await finishNativeFile({ hook_event_name: "PostToolUse", tool_name: "Edit", tool_use_id: "loom-1", tool_input: { file_path: "/srv/odysseus-brain/loom.md" }, + tool_response: { originalFile, oldString: "Penelope", newString, replaceAll } } as never, undefined, { signal: new AbortController().signal }); + const literal = replaceAll ? originalFile.split("Penelope").join(newString) : `${newString} weaves. Penelope waits.\n`; + expect(remembered).toEqual([["loom.md", createHash("sha256").update(literal, "utf8").digest("hex")]]); + }); +}); diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 320f4500c5..5ba1f5a75d 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -139,8 +139,11 @@ export function editFileTool(kit: BrainToolKit): ToolDefinition { `old_string is not unique in ${params.path} (${occurrences} matches); add more context.` ); } - writeFileSync(abs, raw.replace(params.old_string, params.new_string), "utf-8"); - rememberBase(params.path, raw.replace(params.old_string, params.new_string)); + // A function replacement writes new_string literally: a string one + // would expand `$$`, `$&`, `$'` and `` $` `` in it (#2486). + const next = raw.replace(params.old_string, () => params.new_string); + writeFileSync(abs, next, "utf-8"); + rememberBase(params.path, next); await deps.nativeFileObservation?.("write_end", params.path, _id); return textResult(`Edited ${params.path}.`, { path: params.path }); }); diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index f6a45ffb6d..5bd9b03ec1 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -89,6 +89,19 @@ test("editFileTool replaces one unique string and refuses an ambiguous one", asy await expect(run(editFileTool(kit()), { path: "notes/ithaca.md", old_string: "a", new_string: "b" })).rejects.toThrow("is not unique"); }); +test("editFileTool writes $ sequences in new_string verbatim, and its remembered base matches the file", async () => { + const literal = "costs $$5, keeps $& and $' and $` as typed"; + // Governed direct writes: the base the edit remembers is checked against + // the file before the next direct write. + const tools = kit({ directWrites: true }); + await run(editFileTool(tools), { path: "notes/ithaca.md", old_string: "sails home", new_string: literal }); + expect(readFileSync(join(root, "notes/ithaca.md"), "utf8")).toBe(`# Ithaca\n\nOdysseus ${literal}.\n`); + // The remembered base is the literal text, so a second edit in the same + // kit passes its base check instead of reading the file as changed. + await run(editFileTool(tools), { path: "notes/ithaca.md", old_string: "as typed", new_string: "as written" }); + expect(readFileSync(join(root, "notes/ithaca.md"), "utf8")).toBe("# Ithaca\n\nOdysseus costs $$5, keeps $& and $' and $` as written.\n"); +}); + test("bashTool runs one command in the repository and keeps a nonzero exit", async () => { const tools = kit({ exec: {} }); expect(resultText(await run(bashTool(tools), { command: "echo Odysseus" }))).toBe("Odysseus"); diff --git a/packages/ui-server/src/brain/application.ts b/packages/ui-server/src/brain/application.ts index de6c08504d..230a5f93eb 100644 --- a/packages/ui-server/src/brain/application.ts +++ b/packages/ui-server/src/brain/application.ts @@ -414,7 +414,8 @@ export function createBrainApplication(options: { const raw = target.content!; if (input.operation === "edit") { if (raw.split(input.old_string).length - 1 !== 1) refuse("edit_conflict", "The old string must occur exactly once in the stated base."); - content = raw.replace(input.old_string, input.new_string); + // Literal: a string replacement would expand `$` sequences in new_string (#2486). + content = raw.replace(input.old_string, () => input.new_string); } else { const updated = new Date().toISOString().slice(0, 10); const fields: Record = { updated }; diff --git a/packages/ui-server/tests/brain-application.test.ts b/packages/ui-server/tests/brain-application.test.ts index e4ce4dbc4e..95223b52f5 100644 --- a/packages/ui-server/tests/brain-application.test.ts +++ b/packages/ui-server/tests/brain-application.test.ts @@ -199,6 +199,16 @@ describe("server-owned application boundary", () => { expect(edit.ok).toBe(true); expect(readFileSync(join(root, path), "utf8")).toBe("Odysseus rows.\n"); expect(approvals).toEqual([]); expect(receipts).toEqual([result, edit]); policyUnchanged(); }); + test("an edit stores $ sequences in new_string verbatim", async () => { + const apply = application(); + expect((await apply(request(write()))).ok).toBe(true); + const base = readBrainApplicationBase(root, path); + const literal = "sails for $$5, with $& and $' and $` as typed"; + const edit = await apply(request({ operation: "edit", path, expectedBaseHash: base.expectedBaseHash, old_string: "sails", new_string: literal })); + expect(edit.ok).toBe(true); + expect(readFileSync(join(root, path), "utf8")).toBe(`Odysseus ${literal}.\n`); + expect(edit.changes).toEqual([{ path, contentHash: contentHash(`Odysseus ${literal}.\n`) }]); + }); test("kernel write failure cleans private staging and preserves Markdown", async () => { const bwrap = Bun.which("bwrap"); expect(bwrap).not.toBeNull(); const child = Bun.spawn([bwrap!, "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev",