claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

Write/Edit tools silently decode \uXXXX in file content, corrupting escape-sequence text (Linux)

Open joeyparrish opened this issue 5 months ago • 18 comments

Summary

The Write and Edit tools silently decode \uXXXX sequences in file content as JSON Unicode escapes before writing to disk. As a result, it is impossible to store a literal \uXXXX escape sequence in a file via these tools:

  • Authoring the six-character text \uE010 writes the actual U+E010 character.
  • Authoring \\uE010 to compensate writes a doubled backslash (\\uE010).

Neither produces the intended single-backslash literal \uE010 on disk.

This is the content-corruption analog of several closed Windows-path reports (#58358, #54583, #51815). Those were framed around home-directory paths on Windows and closed as stale/duplicate. This report is about arbitrary file content on Linux, is trivially reproducible, and still occurs, so I am filing fresh per the maintainer note on #54583 ("Please open a new issue if this is still relevant").

Why it matters

Any workflow that legitimately needs literal \uXXXX text in a file is silently corrupted:

  • Source code / test fixtures that assert on escape-sequence strings.
  • Config or data files that store Unicode escapes as text (e.g. a YAML field holding \uE010).
  • Documentation about escape sequences (this very issue body hit the bug while being drafted).

The corruption is invisible: the written characters often render as nothing or as unrelated glyphs, Read shows an apparently empty "", and grep for the intended text cannot find the line. The agent cannot tell it went wrong without dropping to od -c.

Reproducer (Linux)

Call the Write tool so that the file content is the line tengwar: " followed by the six literal characters \uE010, then \uE046, then ". Inspect the raw bytes:

$ od -c file.txt
0000000   t   e   n   g   w   a   r   :       " 356 200 220 356 201 206
0000020   "  \n

356 200 220 = UTF-8 for U+E010, 356 201 206 = U+E046. The escape text was decoded into the actual characters before the file was written.

Attempted workaround — author the content with doubled backslashes (\\uE010\\uE046):

$ od -c file2.txt
0000000   t   e   n   g   w   a   r   :       "   \   \   u   E   0   1
0000020   0   \   \   u   E   0   4   6   "  \n

That yields a doubled backslash, not the intended single-backslash escape. So there is no way to write a literal single-backslash \uXXXX through Write/Edit.

Note this is not clean JSON round-tripping: standard JSON would decode a doubled backslash to a single one, but here the doubled backslash is preserved literally while a bare \uXXXX is decoded. The two behaviors are inconsistent.

Working alternative (for reference)

Writing the same value via Bash with sed/printf produces the correct single-backslash escape on disk (the shell tool's own escape handling collapses the doubled backslash). So the corruption is specific to how \uXXXX in the Write/Edit content argument is decoded at the tool boundary, not an inherent filesystem limitation.

Expected

The content (and Edit new_string) should be written to disk byte-for-byte as authored. A literal single-backslash escape in the intended file content should appear on disk as the six ASCII characters backslash, u, E, 0, 1, 0, not be decoded into U+E010.

Environment

  • Platform: Linux
  • Tools affected: Write, Edit (content / new_string). The related Edit old_string matching case is #52813.
  • Appears to be a transport/argument-decoding issue (JSON Unicode-escape decoding of tool arguments), so likely platform-independent.

Related (but closed)

  • #58358 — Write/Edit/Bash decode escapes in paths/heredoc content (closed as duplicate of #54583)
  • #54583 — escape in Windows path decoded (closed, not planned, stale; invites a new issue)
  • #52813 — Edit silently normalizes escapes in old_string, breaking exact matches

Related (still open)

  • #51815 — Read/Edit fail on Windows username with an escape sequence
  • #64479 - Edit tool fails on mixed literal/escape Unicode in multi-line old_string
  • #73483 - Write emits raw U+0000 where the model intended the six-character NUL escape sequence
  • #66058 - Edit tool corrupts literal escape sequences

🤖 Filed with Claude Code

joeyparrish avatar Jul 01 '26 21:07 joeyparrish

Thanks for the detailed repro. Ran it on 2.1.233 (Linux) and reproduced the symptom exactly: asking for the literal six characters \uE010 via Write produced the 3-byte character ee 80 90 on disk, and escaping as \\uE010 produced a doubled backslash. Same with Edit.

However, the raw stream-json output shows the Write/Edit tools are not doing the decoding: the string in the tool call had already become the single U+E010 character before the tool ran, and when the tool did receive a two-backslash string it wrote two backslashes to disk byte-for-byte. Tool arguments travel as JSON, and the model is emitting the JSON unicode-escape form ("\uE010" — which is the character) when the intent is literal text, so the six characters never reach the tool.

So: confirmed and reproduced on 2.1.233, but the root cause is in how the model encodes its tool arguments, not in the Write/Edit tools themselves — we're routing it accordingly. In the meantime, the reliable workaround is to have Claude write such content via a shell command (e.g. printf/heredoc), which is what it eventually did in our runs.

🤖 Generated with Claude Code

bcherny avatar Aug 17 '26 02:08 bcherny

Same problem on MCP tool arguments, on Windows.

Sending a tool argument intended to contain the literal characters \ u 2 0 1 C: \u201C, \\u201C and \\\\u201C all arrive at the server as “. I found no escaping form that gets the literal through — doubling does not help at this surface.

Btw, \\\\u201C does get through in a Bash command, but still decoded to “ in MCP tool arguments.

moshekar avatar Aug 26 '26 23:08 moshekar

Still reproducible, and wider than Write/Edit on Linux.

Scope. On Windows 11 Pro 10.0.26220 (Git Bash, pwsh 7) the \uXXXX decode happens in the Bash tool, the PowerShell tool and the Write tool alike, so it is not a Write/Edit bug. It sits upstream of tool dispatch.

Evidence that it is upstream. A PreToolUse hook that inspects tool_input never sees the escape: a quoted heredoc body containing \u03b1 reaches the hook with the escape already decoded, and the file lands with the character. By contrast the Windows backslash collapse of #88561 is visible to such a hook. The two rewrites are therefore at different layers, and this one cannot be guarded or fixed at the tool level.

Decoder behaviour, measured through the Bash tool with od -c:

input result
\u0041 A
\u00e9 U+00E9
\u4e2d U+4E2D
\ud83d\ude00 U+1F600, surrogate pair correctly combined
\uZZZZ unchanged
\n \t \" \b \r \0 \x41 all unchanged

Correct surrogate-pair combining points at a real JSON string unescaper rather than a regex, applied to a string that has already been JSON-decoded once. Only \u is handled, which is why it stays unnoticed: every escape people check first looks fine.

A workaround exists on Windows, which I think answers the open question in the issue body ("neither produces the intended single-backslash literal"). On Linux with Write/Edit, no. But the Bash tool on Windows can write a literal \uXXXX, by doubling the backslash. This tool call:

cat > probe.json <<'JEOF'
{"greek": "\\u03b1", "path": "C:\\\\Users"}
JEOF

produces on disk, verified with od -c:

{"greek": "\u03b1", "path": "C:\\Users"}

which is correct JSON for both fields. The doubling survives because the Bash-specific collapse of #88561 also applies on this path; I am reporting that as an empirical recipe rather than a claim about the relative order of the two passes, since the PowerShell tool preserves doubled backslashes while still decoding \u, and I cannot see the internals.

So on Windows the two bugs partly cancel, and the Bash tool is the only one of the three that can emit a literal \uXXXX at all.

Attrexx avatar Sep 19 '26 22:09 Attrexx

Still present on 2.1.278 (Linux), and one more data point on where it sits and what it costs.

It is a single named pass over tool input, not a per-tool bug. In 2.1.278 the bundle carries a function called tengu_repair_double_escaped_unicode, applied after streaming to the input of every tool — Bash command, Write/Edit content/new_string alike. The one exception I found is the Workflow tool's script key, which is skipped. That matches the hook evidence in the comment above: the rewrite happens before tool dispatch, so a PreToolUse hook cannot see or guard it. No setting disables it.

Linux behaviour matches the table above: a single-backslash \uXXXX (exactly four hex digits) is decoded; \U0001F600, a doubled \\uXXXX, \t and \n all survive.

What it cost us. An agent writing a C# file through a quoted heredoc — where bash performs no expansion at all, so the bytes should arrive verbatim — emitted a character-literal line containing the source text \u2028 and \uFEFF. On disk those were the bytes e2 80 a8 and ef bb bf, and U+2028 is a real line separator in C#, so the build failed with CS1010 Newline in constant on a file whose source text was valid. Nothing warned; the compiler blamed a character the agent never wrote. The same hazard applies to JSON/JS fixtures that assert on escape text, where it compiles and the test passes for the wrong reason.

Workaround that works on Linux, for anyone hitting this from an agent: never let the four-hex-digit form appear in the tool input at all — build it in the writing program, e.g. esc = lambda h: chr(92) + "u" + h inside a python heredoc, so the input carries the backslash and the hex digits separately. No agent will guess that unaided.

Original report, with the od -c probes: trainerroad/positron-terminal-server#51 (closed as not a terminal-server bug).

🤖 Filed with Claude Code https://claude.com/claude-code

originalmoose avatar Sep 21 '26 01:09 originalmoose

One more data point, from 2.1.282 on Windows 11 Home (26200): the pass is skipped when the same tool input also holds a Windows-path-like string.

Write probes, with the file's bytes read back in Python:

content sent (the escape as six characters) on disk
O\u2028P decoded (e2 80 a8)
V\u2028W then \uXXXX (non-hex) decoded; the non-hex one kept as text
a\u2028b and \q here decoded; \q kept
Y\u2028Z and a path C:\Users\x not decoded: every byte literal

So the pass does not stop at just any invalid escape. A stray \q or a non-hex \u leaves it running, but a C:\... path turns it off. This looks like the guard from the 2.1.218 fix ("Windows paths with \u-prefixed segments ... being corrupted ... in tool inputs"). The practical effect for an agent is that whether an escape survives depends on unrelated content elsewhere in the same input. Neither outcome can be relied on, and building the characters in code (chr(92) + "u" + hex) remains the only safe route.

corpus-folk avatar Sep 25 '26 17:09 corpus-folk

Still present on 2.1.284 (macOS, desktop app). Three points not yet in this thread.

1. Security: the pass writes invisible format characters (Cf) into source files. Asking for the escape of U+202E (RIGHT-TO-LEFT OVERRIDE) or U+200B (ZERO WIDTH SPACE) in a .ts file writes the invisible character itself. That is the Trojan Source vector (CVE-2021-42574): bidi controls that make the reviewed code differ from the compiled code, planted without anyone typing them.

2. The pass already has the right exception, one category too narrow. Since 2.1.277, "escaped control characters now stay as literal text", and the 2.1.284 binary counts control_escape_skips next to repaired_strings and windows_path_skips. Measured here: the NUL and ESC escapes stay as text, the U+202E and U+200B escapes are decoded. Claude Code already neutralizes bidi and zero-width characters in permission previews (2.1.211), prompts (2.1.277, 2.1.280) and recalled memory (2.1.284). Extending the same skip to Cf, Zl and Zp (U+2028 is the C# failure reported above) would close the security side without touching the CJK repair this pass exists for.

3. A workaround that works at the hook layer. As noted above, a PreToolUse hook cannot see the escape. A PostToolUse hook on Write|Edit can: it scans the written file for categories Cf, Cc (except tab and line breaks), Zl and Zp, and returns decision: "block" with a reason that tells the model to rewrite with a form the pass ignores (\u{202E} in JS/TS, \U0000202E in Python, String.fromCodePoint or chr), plus a perl -CSD -pi repair line. In our session the model fixed the file on the next turn.

landraud63 avatar Sep 30 '26 16:09 landraud63

Two more details, from the 2.1.286 build (macOS, desktop app):

  1. The Windows-path guard also fires on ordinary escaped text. Its UNC branch matches a quote, space or =, two backslashes, a run without separators and then a backslash, so a line such as printf 'x = "\\u200b";\n' anywhere in a Write content makes the pass skip the whole string. Every other escape in that file then lands as typed; without that line they are decoded.
  2. \u005c is decoded like any other escape, in a single pass. Wherever the pass runs, typing \u005cu200b writes the six characters \u200b, which puts a literal escape through Write and Edit without a helper program. Where point 1 makes the pass skip the string, \u005c stays as typed too, so check the bytes either way.

A side effect on Edit that this pass sets off is filed separately as #99361: after an escaped-form match, every non-ASCII character in new_string is written as an escape.

ctbot000 avatar Oct 04 '26 01:10 ctbot000

Also happens on Windows (Windows 11 Pro 10.0.26200, Claude Code desktop app, 2026-10-12). An Edit whose new_string contained the six-character escape \uFEFF inside a JS regex literal (buf.replace(/^\uFEFF/, '')) wrote the literal U+FEFF character to disk instead. od -c on that line showed / ^ 357 273 277 /. The code still ran, so the only sign was an invisible character in the source.

Workaround: keep \u escapes out of Write/Edit content (we used buf.charCodeAt(0) === 0xFEFF).

apalm8 avatar Oct 12 '26 22:10 apalm8

Still present on 2.1.295 (Windows 10, desktop app) and in the bundled 2.1.302 CLI, in the same pass (tengu_repair_double_escaped_unicode). There are two points not yet in this thread.

1. The session transcript already shows both sides of the boundary. For the same call, the JSONL records wireToolInputs[<tool_use_id>] (what the model sent) and message.content[].input (what the tool got). Parsing the line once gives codepoints 92,117,48,48,52,49 (\u0041) on the wire side and 65 (A) on the input side.

We saw this for Bash command, PowerShell command and Write content in one session. Maintainers can check any report from a user's transcript without a packet capture.

2. It silently weakens tests. We were adding regression tests for secret redaction: a key that arrives percent-encoded or as \uXXXX escapes must still be redacted. The escaped test inputs were decoded to the plain key before they reached the file, so the tests passed while testing the plain-key case only. It was caught only by scanning the files for non-ASCII bytes and asserting in the tests that the input really contains a backslash.

A workaround that works today: build the backslash at run time and keep it out of the tool text, e.g. chr(92) + "u0041" in Python or [char]92 in PowerShell.

The fix we'd hope for: make the repair opt-in or remove it. Ordinary JSON already tells an encoded character apart from a literal escape, so the extra pass can only change text the model meant literally.

jullduxster avatar Oct 18 '26 03:10 jullduxster

Still present in 2.1.303 (latest release, 2026-10-18, Windows 10). No changelog entry since 2.1.278 touches this pass, and on 2.1.299 (desktop app) a PostToolUse hook that compares each call's wireToolInputs with its input in the transcript kept flagging decoded calls through 2026-10-18.

Two requests, since the maintainer reply above routed this to the model's encoding:

  1. Please re-route it to the client. In the 2.1.303 binary, one function runs over every tool's input after the streamed JSON has been parsed, and logs tengu_repair_double_escaped_unicode with repaired_strings, windows_path_skips and control_escape_skips. The only exception is a hard-coded restore of the Workflow tool's script after the pass. No setting or environment variable turns it off. The transcript records both sides of the same call: wireToolInputs[<tool_use_id>] holds the six characters (backslash, u, four hex digits) and input holds the decoded character. Had the model sent the JSON escape form, the parsed wire value would already be the character.

  2. Please widen the title and labels. The thread shows the decoding on Linux, Windows and macOS, and in Bash, PowerShell, Write, Edit and MCP tool arguments, so "Write/Edit" and platform:linux undersell it. Something like "Tool input: \uXXXX text is decoded to the character before any tool runs (all tools, all platforms)".

What would close it for us: remove the pass or make it opt-in. Failing that, skip it for the fields that carry file or shell text (Bash and PowerShell command, Write content, Edit old_string/new_string, MCP tool arguments), the way the Workflow script is already skipped.

jullduxster avatar Oct 19 '26 14:10 jullduxster

Still present in 2.1.308 (the build bundled with desktop app 3.6556.2.0, current stable), Windows 10. Same method as my earlier comments: for five hand-typed calls I compared wireToolInputs[<tool_use_id>] (what the model sent: a backslash, then u0041) with the input of the tool_use block in the session transcript (what ran).

call result
Bash: printf '%s' 'x\u0041y' decoded: prints xAy
PowerShell: the same text decoded
Write: file content x\u0041y decoded: the file holds xAy
Bash: a quoted heredoc piping the same text into a script that writes a file decoded
Bash: two arguments, 'C:\x' and 'x\u0041y' kept whole: the string holding a drive path is skipped (the windows_path_skips case reported above on 2.1.282)

A doubled backslash before u0041 is not decoded in any of these tools. I did not try the npm CLI 2.1.309.

jullduxster avatar Oct 25 '26 21:10 jullduxster

Controlled follow-up on Claude Code 2.1.312 (Windows 11), using exact local fixture API messages rather than a real model. This adds reproduction evidence to this existing report; it is not a claim of original discovery.

Observed boundary: the client changes literal Unicode escape text after ordinary JSON parsing and before dispatch. The earlier ten Edit probes reproduced the same four rewrites on 2.1.267 and 2.1.312. In this follow-up, an explicitly UTF-8 dummy MCP server also received four of ten arguments changed; all six controls were preserved, including an actual non-ASCII character. Its received codepoints match the Edit dispatch results.

Semantic impact: supplying the valid Python source sample = r"x\u0041y" through Edit produced sample = r"xAy" The intended eight-character string became three characters. Both sources parse; values were inspected with AST literal evaluation, without executing generated code. Adding an unrelated comment containing a synthetic Windows-path-shaped string preserved the original eight-character value. An ordinary-string control was unchanged.

Mechanism: the inspected verified release embeds an input-normalization step calling a recursive Unicode-repair pass. The escape, double-backslash and whole-string path guards agree with the controls; the altered value already appears at tool dispatch. This supports client normalization as the cause in this tested release, rather than Edit's disk-writing behavior or model encoding.

Reproducer, measured results, scope and excluded fixture failures: https://github.com/mahmood726-cyber/anthropic-public-report-index/tree/main/reproductions/deeper

Run from that folder after downloading the pinned official binary using the parent download_current.py: python unicode_extension.py --binary ../binaries/2.1.312/claude.exe --case mcp python unicode_extension.py --binary ../binaries/2.1.312/claude.exe --case semantics

Windows executable SHA-256: 6099672ebe5dcb518b67d1d32dde1e3360bc6bee1dae7f8d28a69c49acc7c865. The package integrity was checked.

All model messages and canary data are synthetic inputs; client outputs are runtime measurements. No production model behavior, attacker capability, cross-user exposure, privilege escalation or security severity has been established. An initial dummy-server encoding error was caught by the non-ASCII control and excluded; the published result uses explicit UTF-8. Please route the demonstrated integrity failure to the relevant client owner. Research and drafting were AI-assisted.

mahmood726-cyber avatar Oct 28 '26 16:10 mahmood726-cyber

One more workaround, for Agent SDK / stream-json consumers that run tool calls themselves (not yet in this thread):

Each assistant message the SDK yields carries wire_tool_inputs: a map from tool_use id to the input as parsed from the API response, beside the decoded message.content[].input. The raw stream_event input_json_delta fragments are not decoded either.

Measured on 2.1.314 (Windows) through @anthropic-ai/claude-agent-sdk 0.3.284, with one call to an SDK MCP tool whose text argument was the six characters backslash, u, 0041:

source text
the input_json_delta fragments, parsed once the six characters
wire_tool_inputs[id] the six characters
message.content[].input A
the MCP tool's tools/call arguments A

So a harness that dispatches tool calls from the SDK stream can run wire_tool_inputs[id] (falling back to the streamed JSON, then to input) and gets what the model sent. A tool served to Claude Code over MCP still receives the decoded copy. wire_tool_inputs isn't in the SDK's type definitions, so documenting it would help, and removing the pass would help more.

NateMateS avatar Oct 31 '26 17:10 NateMateS

Still present in Claude Code 2.1.317 (desktop app Code tab, Windows 11). Same test: a backslash followed by u2028, and backslash-u-0041, arrive decoded through the built-in Write tool, through an MCP tool’s plain string parameter, and inside an MCP tool’s array-of-objects parameter. The doubled form arrives doubled. The same MCP server, called directly with the Python MCP client, receives the six characters intact.

scott8 avatar Nov 04 '26 05:11 scott8

Still present on 2.1.317 (desktop app, macOS 27.3 arm64), and the 2.1.318 CLI binary still carries tengu_repair_double_escaped_unicode. One effect not in this thread yet: at the end of a line in Write or Edit content, a \u2028 or \u2029 escape is deleted, along with any spaces before it.

One Write call into a scratch .txt (no format hook), bytes read back with xxd:

line sent on disk
a\u2028 61
b \u2028 62
c\u2028d 63 e2 80 a8 64
e \u202E 65 20 e2 80 ae
f\u2029 66

Edit's new_string does the same: n \u2028 at line end landed as 6e.

It looks like two passes stacking. The decode turns the escape into U+2028, then the trailing-whitespace strip from #100296 counts U+2028 and U+2029 as whitespace and removes them. Two controls back that up. The same lines written to a .md file, which #100296 says the strip skips, keep the character (61 e2 80 a8, 62 20 e2 80 a8). A quoted Bash heredoc keeps it too: decoded, never stripped. For every probe call the transcript's wireToolInputs holds the six characters. The .txt Write and the Edit reach the tool with the escape and its space already gone, so the strip runs at the same layer as the decode, before dispatch.

Mid-line, the escape turns into a character you can't see. At line end it's simply gone, and the diff gives no sign it was ever typed.

Where I hit it: an agent wrote a regex to strip bidi controls from visitor-submitted text, using four-hex escapes for U+202A to U+202E. The committed source held the raw controls, and so did the PR body it passed to gh pr create through a quoted heredoc. bun fmt got blamed first, because nobody checked the bytes before it ran. A repo test that fails on any \p{Bidi_Control} in tracked files catches it now.

oddharsh avatar Nov 07 '26 13:11 oddharsh

Also on macOS (Claude Code 2.1.325, macOS 27.0.1). Writing a Ruby file with the Write tool whose content is

LRE = "‪"

produced the literal U+202A character in the file (od -c shows 342 200 252 between the quotes), not the six-character escape. With bidi control characters this is especially bad: the result is invisible in diffs and editors. We only caught it with git grep -P "[\x{202A}-\x{202E}\x{2066}-\x{2069}]".

elektronaut avatar Nov 15 '26 16:11 elektronaut

Still present on 2.1.327 (CLI, Windows 11 Pro 10.0.26300). One case not in this thread yet: a drive path written with a forward slash, such as D:/x, also turns the pass off for the whole string, like the C:\... guard reported above.

Each call below held A=\u0041 ESC=\u001b with the escapes typed as six characters. I read the bytes back with od -c. For every call the transcript's wireToolInputs holds the six characters (92,117,48,48,52,49).

Call Bytes for \u0041
Write, content see docs/x, then the line A
Write, content see D:/x, then the line \ u 0 0 4 1
Bash, a quoted heredoc of the line piped to od -c A
Bash, the same command after printf '%s\n' 'unrelated D:/x'; \ u 0 0 4 1

\u001b stays as text in every row. A Bash command that starts with cd "D:/..." keeps every escape in it. The same command without that path decodes them.

YevheniiKotyrlo avatar Nov 18 '26 21:11 YevheniiKotyrlo

Still present on 2.1.330 (desktop app Code tab, WSL2 Ubuntu). Two things from six weeks of daily use.

  1. Our transcripts put the decode in the client, in every case we had. Between 15 Oct and 26 Nov (2.1.299 to 2.1.330), 32 Edit and Write calls, from main sessions and subagents alike, reached the tool holding a raw U+2028, U+2029 or bidi control. In all 32, wireToolInputs holds the escape text the model sent, and in none does it hold the raw character. That backs the request above to route this to the client.

  2. A PreToolUse hook can't see the escape, but it does see the decoded character, and that is enough to stop the write. Ours refuses (exit 2) any Write, Edit, MultiEdit or NotebookEdit whose written text adds one of 11 code points: U+2028, U+2029, U+202A–U+202E and U+2066–U+2069. Its message tells the model to keep the escape out of the tool text and build the character at run time. It adds about 10 ms per call.

Replayed over our stored transcripts (about 9,400 file-editing calls), it would have refused 15 calls that put a raw line or paragraph separator into a file, 7 of them inside regex literals, and 5 that put a raw bidi control into a code file. All 20 were decoded escapes, so no false positives. One of the separator cases took down a TypeScript file (0 of 53 tests ran), and the agent then failed three times to remove the characters with Edit, because it read them as spaces. Since the hook went live it has refused one more call, from a subagent on 2.1.330.

+1 to extending control_escape_skips to Cf, Zl and Zp, or to removing the pass.

Found out and reported using Claude Code.

Raazgar avatar Nov 26 '26 14:11 Raazgar