Skip to content

Commit c0cafd7

Browse files
authored
fix: write tool skips overwrites after lossy UTF-8 decoding (#133282)
Compare requested and existing UTF-8 bytes before reporting a terminal no-op, matching persisted-write verification. Preserve bounded display diffs and remove the obsolete optional-stat guard from the same owner. Cover invalid-byte overwrites, encoded surrogate no-ops, delegated readbacks, and unchanged Unicode/CRLF content.
1 parent 46c1eef commit c0cafd7

2 files changed

Lines changed: 69 additions & 46 deletions

File tree

‎src/agents/sessions/tools/write.test.ts‎

Lines changed: 63 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -125,18 +125,24 @@ describe("write tool", () => {
125125
await expect(fs.stat(filePath)).rejects.toMatchObject({ code: "ENOENT" });
126126
});
127127

128-
it("rejects a delegated write that leaves stale same-size content", async () => {
129-
const filePath = await createTempPath("stale.txt");
130-
await fs.writeFile(filePath, "stale\n", "utf-8");
131-
const tool = createWriteTool(tmpDir, {
132-
operations: createRecoverableOperations(async () => {}),
133-
});
134-
135-
await expect(
136-
tool.execute("call-1", { path: filePath, content: "fresh\n" }, undefined),
137-
).rejects.toThrow("Write verification failed");
138-
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe("stale\n");
139-
});
128+
it.each([
129+
{ name: "text", original: Buffer.from("stale\n"), content: "fresh\n" },
130+
{ name: "invalid UTF-8", original: Buffer.from([0xf0, 0x90, 0x80]), content: "\uFFFD" },
131+
])(
132+
"rejects a delegated write that leaves stale same-size bytes: $name",
133+
async ({ original, content }) => {
134+
const filePath = await createTempPath("stale.txt");
135+
await fs.writeFile(filePath, original);
136+
const tool = createWriteTool(tmpDir, {
137+
operations: createRecoverableOperations(async () => {}),
138+
});
139+
140+
await expect(tool.execute("call-1", { path: filePath, content }, undefined)).rejects.toThrow(
141+
"Write verification failed",
142+
);
143+
await expect(fs.readFile(filePath)).resolves.toEqual(original);
144+
},
145+
);
140146

141147
it("rejects a delegated write that leaves a non-file target", async () => {
142148
const filePath = await createTempPath("directory");
@@ -150,19 +156,38 @@ describe("write tool", () => {
150156
).rejects.toThrow("Write verification failed");
151157
});
152158

153-
it("verifies delegated writes by their persisted UTF-8 bytes", async () => {
154-
const filePath = await createTempPath("surrogate.txt");
155-
const content = "unpaired \ud800 surrogate\n";
156-
const tool = createWriteTool(tmpDir, {
157-
operations: createRecoverableOperations((absolutePath, requestedContent) =>
159+
it.each(["buffer", "text"] as const)(
160+
"verifies delegated UTF-8 bytes with %s readback",
161+
async (readback) => {
162+
const filePath = await createTempPath("surrogate.txt");
163+
const content = "unpaired \ud800 surrogate\n";
164+
const operations = createRecoverableOperations((absolutePath, requestedContent) =>
158165
fs.writeFile(absolutePath, requestedContent, "utf-8"),
159-
),
160-
});
166+
);
167+
if (readback === "text") {
168+
operations.readFile = (absolutePath) => fs.readFile(absolutePath, "utf8");
169+
}
170+
const tool = createWriteTool(tmpDir, { operations });
171+
172+
await expect(
173+
tool.execute("call-1", { path: filePath, content }, undefined),
174+
).resolves.toMatchObject({ details: { changed: true, created: true } });
175+
await expect(fs.readFile(filePath)).resolves.toEqual(Buffer.from(content, "utf8"));
176+
await expect(
177+
tool.execute("call-2", { path: filePath, content }, undefined),
178+
).resolves.toMatchObject({ details: { changed: false }, terminate: true });
179+
},
180+
);
181+
182+
it("overwrites invalid UTF-8 bytes that decode to the requested text", async () => {
183+
const filePath = await createTempPath("invalid.txt");
184+
await fs.writeFile(filePath, Buffer.from([0xf0, 0x90, 0x80]));
185+
const tool = createWriteTool(tmpDir);
161186

162187
await expect(
163-
tool.execute("call-1", { path: filePath, content }, undefined),
164-
).resolves.toMatchObject({ details: { changed: true, created: true } });
165-
await expect(fs.readFile(filePath)).resolves.toEqual(Buffer.from(content, "utf8"));
188+
tool.execute("call-1", { path: filePath, content: "\uFFFD" }, undefined),
189+
).resolves.toMatchObject({ details: { changed: true, created: false } });
190+
await expect(fs.readFile(filePath)).resolves.toEqual(Buffer.from("\uFFFD", "utf8"));
166191
});
167192

168193
it("writes file URL paths through the shared session path resolver", async () => {
@@ -190,23 +215,22 @@ describe("write tool", () => {
190215
await expect(fs.readFile(asciiPath, "utf-8")).resolves.toBe("ascii\n");
191216
});
192217

193-
it("returns terminal no-op when writing identical content to existing file", async () => {
194-
const filePath = await createTempPath("identical.txt");
195-
await fs.writeFile(filePath, "hello\n", "utf-8");
196-
const tool = createWriteTool(tmpDir);
197-
198-
const result = await tool.execute(
199-
"call-1",
200-
{ path: "identical.txt", content: "hello\n" },
201-
undefined,
202-
);
203-
204-
const tc0 = expectDefined(result.content[0], "result.content[0] test invariant");
205-
expect("text" in tc0 ? tc0.text : "").toContain("No changes made");
206-
expect((result as { terminate?: boolean }).terminate).toBe(true);
207-
expect(result.details).toEqual({ changed: false });
208-
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe("hello\n");
209-
});
218+
it.each(["hello\n", "café 🦀\r\n日本語 e\u0301\r\n", "\uFFFD\r\n"])(
219+
"returns terminal no-op for identical UTF-8 content: %j",
220+
async (content) => {
221+
const filePath = await createTempPath("identical.txt");
222+
await fs.writeFile(filePath, content, "utf-8");
223+
const tool = createWriteTool(tmpDir);
224+
225+
const result = await tool.execute("call-1", { path: "identical.txt", content }, undefined);
226+
227+
const tc0 = expectDefined(result.content[0], "result.content[0] test invariant");
228+
expect("text" in tc0 ? tc0.text : "").toContain("No changes made");
229+
expect((result as { terminate?: boolean }).terminate).toBe(true);
230+
expect(result.details).toEqual({ changed: false });
231+
await expect(fs.readFile(filePath)).resolves.toEqual(Buffer.from(content, "utf8"));
232+
},
233+
);
210234

211235
it("reports a created file with its authoritative diff", async () => {
212236
await createTempPath("created.txt");

‎src/agents/sessions/tools/write.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -328,9 +328,6 @@ async function readOriginalWriteState(
328328
content: string,
329329
ops: WriteOperations,
330330
): Promise<WriteToolPrecheck> {
331-
if (!ops.statFile) {
332-
return { state: "unknown" };
333-
}
334331
let stat: PersistedFileStat | null;
335332
try {
336333
stat = await ops.statFile(absolutePath);
@@ -354,14 +351,16 @@ async function readOriginalWriteState(
354351

355352
try {
356353
const originalContent = await ops.readFile(absolutePath);
357-
const originalText = Buffer.isBuffer(originalContent)
358-
? originalContent.toString("utf8")
359-
: originalContent;
354+
const originalBytes = Buffer.isBuffer(originalContent)
355+
? originalContent
356+
: Buffer.from(originalContent, "utf8");
357+
const originalText = originalBytes.toString("utf8");
360358
if (Buffer.byteLength(originalText, "utf8") > WRITE_PRECHECK_READ_LIMIT_BYTES) {
361359
return { state: "unknown", beforeStat: stat, readAttempted: true };
362360
}
363361
return {
364-
state: originalText === content ? "same" : "different",
362+
// No-op receipts need the same encoded bytes as post-write verification.
363+
state: originalBytes.equals(Buffer.from(content, "utf8")) ? "same" : "different",
365364
beforeStat: stat,
366365
beforeText: originalText,
367366
readAttempted: true,

0 commit comments

Comments
 (0)