Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/2486-literal-edit-replacement.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion packages/ui-backend-claude/src/permission-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
22 changes: 22 additions & 0 deletions packages/ui-backend-claude/tests/permission-wiring-units.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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")]]);
});
});
7 changes: 5 additions & 2 deletions packages/ui-backend-pi/src/file-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
Expand Down
13 changes: 13 additions & 0 deletions packages/ui-backend-pi/tests/tool-factories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
3 changes: 2 additions & 1 deletion packages/ui-server/src/brain/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string | string[] | null> = { updated };
Expand Down
10 changes: 10 additions & 0 deletions packages/ui-server/tests/brain-application.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading