The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): reject ambiguous backslash drift
Elisa Martinez Abad4f3dbdd51284
diff --git a/tests/tools/test_escape_drift_autocorrect.py b/tests/tools/test_escape_drift_autocorrect.pyindex 80e436f4944..0929493cc8b 100644--- a/tests/tools/test_escape_drift_autocorrect.py+++ b/tests/tools/test_escape_drift_autocorrect.py@@ -1,8 +1,8 @@"""Tests for escape-drift auto-correction on ``patch`` (tools/escape_drift_autocorrect.py).-Contract: a call whose arguments were escaped one extra time on the wire is un-escaped only when-old_string is verified against the file AND new_string is uniformly escaped; a backslash the-model meant in new code is never removed, and ``note`` reports exactly when a correction fired.+Contract: a verified doubled anchor is corrected only for a backslash-free replacement;+replacement backslashes require a clean resend and leave the file unchanged. Quote+correction retains its separate checks, and ``note`` reports when a correction fired."""import json@@ -25,11 +25,6 @@ def _patch_tool(**kwargs):# (file content, drifted old_string, new_string that also adds a legitimately escaped line)_MIXED_CALLS = {- "backslash_new_line_single_escaped": (- 'pat = re.compile(r"\\d+")\n',- r'pat = re.compile(r"\\d+")',- 'pat = re.compile(r"\\\\d+")\nprint("done\\n")',- ),"quote_new_line_really_escaped": ("x = 'it'\n",r"x = \'it\'",@@ -38,19 +33,36 @@ _MIXED_CALLS = {}[email protected]("content,old,new", _MIXED_CALLS.values(), ids=_MIXED_CALLS.keys())-def test_mixed_escaping_is_not_corrected(content, old, new):+def test_mixed_quote_escaping_is_not_corrected():+ content, old, new = _MIXED_CALLS["quote_new_line_really_escaped"]assert maybe_correct_escape_drift(old, new, content) == (old, new, None)class TestPatchEndToEnd:+ @pytest.mark.parametrize("replacement", [+ r'sep = r"a\c"',+ r'sep = r"a\\c"' + "\n" + r'other = "C:\\backup"',+ r'sep = r"a\\c"' + "\n" + r'print("done\n")',+ r'sep = r"a\\c"',+ ], ids=["clean_replacement", "windows_path", "odd_escape", "all_runs_even"])+ def test_doubled_anchor_with_replacement_backslashes_is_rejected(self, workdir, replacement):+ f = workdir / "anchor.py"+ original = 'sep = r"a\\b"\n'+ f.write_text(original)+ result = _patch_tool(path=str(f), old_string=r'sep = r"a\\b"',+ new_string=replacement, task_id="t-drift")+ assert result.get("success") is not True+ assert "intentional backslashes" in result["error"]+ assert f.read_text() == original+def test_backslash_mixed_call_rejected_not_mangled(self, workdir):- # Two runs so the existing doubling guard has a non-trivial signal and rejects.+ # A multi-line doubled anchor also requires a clean resend of mixed new code.f = workdir / "a.py"original = 'pat = re.compile(r"\\d+")\nsep = r"a\\b"\n'f.write_text(original)+ replacement = r'pat = re.compile(r"\\w+")' + "\n" + r'sep = r"a\\b"' + "\n" + r'print("done\n")'r = _patch_tool(path=str(f), old_string=r'pat = re.compile(r"\\d+")' + "\n" + r'sep = r"a\\b"',- new_string=r'pat = re.compile(r"\\w+")' + "\n" + r'sep = r"a\\b"' + "\n" + r'print("done\n")',+ new_string=replacement,task_id="t-drift")assert r.get("success") is not Trueassert f.read_text() == original@@ -64,12 +76,12 @@ class TestPatchEndToEnd:assert f.read_text() == content@pytest.mark.parametrize("content,old,new,expected", [- ('pat = re.compile(r"\\d+")\n', r'pat = re.compile(r"\\d+")', r'pat = re.compile(r"\\w+")',- 'pat = re.compile(r"\\w+")\n'),+ ('pat = re.compile(r"\\d+")\n', r'pat = re.compile(r"\\d+")', 'pat = None',+ 'pat = None\n'),("x = 'it'\n", r"x = \'it\'", r"x = \'its\'" + "\n" + r"y = \'ok\'","x = 'its'\ny = 'ok'\n"),- ], ids=["backslash_doubled", "quote_escaped"])- def test_uniformly_drifted_call_is_corrected_with_note(self, workdir, content, old, new, expected):+ ], ids=["backslash_free_replacement", "quote_escaped"])+ def test_verified_correction_with_note(self, workdir, content, old, new, expected):f = workdir / "c.py"f.write_text(content)r = _patch_tool(path=str(f), old_string=old, new_string=new, task_id="t-drift")@@ -80,7 +92,9 @@ class TestPatchEndToEnd:@pytest.mark.parametrize("content,old,new", [('s = "a\\\\b"\n', r's = "a\\b"', r's = "a\\c"'),("s = 'it\\'s'\n", r"s = 'it\'s'", r"s = 'it\'s ok'"),- ], ids=["real_double_backslash", "real_escaped_quote"])+ ('sep = r"a\\b"\n', r'sep = r"a\b"',+ r'sep = r"a\c"' + "\n" + r'other = "C:\\backup"'),+ ], ids=["real_double_backslash", "real_escaped_quote", "clean_resend"])def test_file_really_containing_escapes_is_left_alone(self, workdir, content, old, new):f = workdir / "d.py"f.write_text(content)diff --git a/tools/escape_drift_autocorrect.py b/tools/escape_drift_autocorrect.pyindex 01af3d9f398..1acce643d7a 100644--- a/tools/escape_drift_autocorrect.py+++ b/tools/escape_drift_autocorrect.py@@ -1,35 +1,14 @@-"""Auto-correction for JSON-double-escaping wire artifacts on ``patch`` calls.--``tools/fuzzy_match.py::_detect_escape_drift``/``_detect_backslash_doubling`` already diagnose,-with certainty, two shapes of the same underlying artifact -- a spurious backslash before a-quote/apostrophe (``\\'``/``\\"``) that the file does not have, or every backslash run in-``old_string`` being exactly twice as long as the matched region's -- but only ever reject the-call and ask the model to resend, costing a full round trip.--Applied unconditionally, not gated to any particular model: each correction is safe by-construction rather than by knowing which model is talking. Both only ever fire when the-corrected ``old_string`` is verified to appear verbatim in the file's actual content -- a model-that deliberately sent genuinely-escaped content (a correctly backslash-doubled string in a-regex/shell string, or a source file that legitimately contains the two-character sequence-``\\'``/``\\"``) would need the corrected form to coincidentally already exist at the same spot-in the file for either correction to apply, which the checks below rule out; a wrong guess-simply fails verification and falls through to the existing reject-and-ask guard unchanged.-That verification covers ``old_string`` only: the lines ``new_string`` adds are not in the file,-so each correction also requires ``new_string`` to be uniformly escaped (every backslash run-even; every escaped quote escaped by exactly one backslash) and otherwise makes no correction,-since un-escaping a backslash the model meant in new code would corrupt the file silently. An-earlier version of the backslash-doubling correction gated it to a model-name substring match;-that gate was removed because the substring check turned out to be unreliable in practice (the-resolved "model" value at the check site did not reliably match the serving model's real name),-and because the verification-against-file-content step already provides the safety property the-gate was meant to add. Per-model gating can be reintroduced later if a model is found where a-verified correction itself proves unsafe -- nothing observed so far suggests that.--Called once from ``tools/file_operations.py::patch_replace``, before fuzzy matching runs, so a-verified correction produces a clean exact match instead of ever reaching the guard. The applied-correction (if any) is surfaced back to the caller as a note so it stays observable and-auditable -- a bare `success: true` does not by itself distinguish a call that was silently-auto-corrected from one whose arguments never needed correction at all.+"""Conservative correction of escape drift before ``patch_replace`` matches text.++Corrections require the corrected ``old_string`` to appear verbatim in the file.+That evidence cannot establish the intended escaping of newly added code: deliberate+double backslashes look the same as a serialization artifact. Backslash correction+therefore halves only ``old_string`` and requires a backslash-free ``new_string``.+An otherwise verified doubled anchor with replacement backslashes raises an explicit+error; callers must reject it before fuzzy matching can apply the ambiguous text.++Quote correction retains its separate consistency checks. Successful corrections+return a note for the tool result; already-exact anchors are left unchanged."""from __future__ import annotations@@ -40,6 +19,10 @@ from typing import Optional, Tuple_BACKSLASH_RUN_RE = re.compile(r"\\+")+class AmbiguousEscapeDriftError(ValueError):+ """The replacement's intentional backslashes cannot be distinguished from drift."""++def _halve_backslash_runs(s: str) -> str:"""Replace every maximal run of backslashes with half its length."""return _BACKSLASH_RUN_RE.sub(lambda m: "\\" * (len(m.group(0)) // 2), s)@@ -50,27 +33,28 @@ def _all_backslash_runs_even(s: str) -> bool:def maybe_correct_backslash_doubling(old_string: str, new_string: str, content: str) -> Tuple[str, str]:- """Return a corrected ``(old_string, new_string)`` if a doubled-backslash wire artifact is- detected AND verified against the file's actual content; otherwise return them unchanged.-- Two requirements, one per string. The halved ``old_string`` must appear verbatim in- ``content`` -- that verifies old_string. Nothing in the file can verify new_string (its- new lines are, by definition, not in the file yet), so it is checked structurally: an- extra escape doubles EVERY backslash, so every run in both strings must have even length.- An odd run (``print("done\\n")`` added alongside a doubled old_string) means that string- was not double-escaped; halving it would silently delete a real backslash, so the call is- left unchanged for the existing reject-and-ask guard.+ """Halve a verified doubled anchor only when the replacement has no backslashes.++ Every old_string run must be even and its halved form must occur in the file.+ Replacement backslashes are ambiguous regardless of run length, so raise+ ``AmbiguousEscapeDriftError`` rather than let fuzzy matching apply them."""if "\\" not in old_string or old_string in content:return old_string, new_string- if not (_all_backslash_runs_even(old_string) and _all_backslash_runs_even(new_string)):+ if not _all_backslash_runs_even(old_string):return old_string, new_stringhalved_old = _halve_backslash_runs(old_string)if halved_old not in content:return old_string, new_string- return halved_old, _halve_backslash_runs(new_string)+ if "\\" in new_string:+ raise AmbiguousEscapeDriftError(+ "Escape-drift detected: halving old_string's backslashes matches the file, "+ "but correcting new_string could remove intentional backslashes. "+ "Re-read the file and resend old_string/new_string with their intended escaping."+ )+ return halved_old, new_string_QUOTE_WITH_BACKSLASHES_RE = {q: re.compile(r"(\\*)" + q) for q in ("'", '"')}@@ -132,10 +116,9 @@ def maybe_correct_escape_drift(old_string: str, new_string: str, content: str) -"""Apply whichever escape-drift auto-correction (if any) is verified against the file'sactual content and report which one fired.- Tries quote-escaping then backslash-doubling; both are independently gated on the corrected- old_string being confirmed present in content, so at most one meaningfully changes anything- for a given call -- trying both in sequence just avoids an artificial ordering dependency,- not a real ambiguity between them.+ Tries quote escaping, then backslash correction of the anchor only. Raises+ ``AmbiguousEscapeDriftError`` for a verified doubled anchor whose replacement+ contains backslashes; the caller must return an error without attempting a match.Returns ``(corrected_old, corrected_new, note)``: ``note`` is a human-readable descriptionof the correction that was applied, or ``None`` if neither fired. The caller attaches@@ -152,8 +135,8 @@ def maybe_correct_escape_drift(old_string: str, new_string: str, content: str) -corrected_old, corrected_new = maybe_correct_backslash_doubling(old_string, new_string, content)if corrected_old != old_string:return corrected_old, corrected_new, (- "escape-drift auto-corrected: halved doubled backslash runs in old_string/new_string "- "(a JSON-double-escaping wire artifact) before matching."+ "escape-drift auto-corrected: halved doubled backslash runs in old_string "+ "before matching; new_string has no backslashes and was left unchanged.")return old_string, new_string, Nonediff --git a/tools/file_operations.py b/tools/file_operations.pyindex 8ea37f959be..859232d79b2 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -1618,8 +1618,11 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):raw_content = data.decode("utf-8", "surrogateescape")content, _ = _strip_bom(raw_content)- from tools.escape_drift_autocorrect import maybe_correct_escape_drift- old_string, new_string, escape_drift_note = maybe_correct_escape_drift(old_string, new_string, content)+ from tools.escape_drift_autocorrect import AmbiguousEscapeDriftError, maybe_correct_escape_drift+ try:+ old_string, new_string, escape_drift_note = maybe_correct_escape_drift(old_string, new_string, content)+ except AmbiguousEscapeDriftError as exc:+ return PatchResult(error=str(exc))from tools.fuzzy_match import fuzzy_find_and_replacenew_content, match_count, _strategy, error = fuzzy_find_and_replace(