Skip to content

The agent that grows with you

fix: unicode-preserving replacement no longer duplicates region text when an edit boundary falls inside an expansion

Yuan Lie90857ba07b3
diff --git a/tests/tools/test_fuzzy_match.py b/tests/tools/test_fuzzy_match.py
index 6c52ea47c44..b6b81b289ec 100644
--- a/tests/tools/test_fuzzy_match.py
+++ b/tests/tools/test_fuzzy_match.py
@@ -229,6 +229,22 @@ class TestUnicodeNormalized:
assert new == expected, f"Got {new!r}"
+ def test_equal_boundary_inside_expansion_keeps_region_text(self):
+ """An edit boundary falling inside a multi-char expansion (em-dash ->
+ '--') must snap to the expansion, not copy text from the region start.
+
+ SequenceMatcher splits old/new so that the second equal block begins
+ at the expansion's second '-': a norm index with no direct original
+ position. The old fallback (position 0) spliced the whole region text
+ into the replacement, duplicating it after every edit.
+ """
+ content = "value = x\u2014y\n"
+ new, count, strategy, err = fuzzy_find_and_replace(
+ content, "value = x--y", "value = x-@-y")
+ assert count == 1, f"Expected match, got err={err}"
+ assert strategy == "unicode_normalized"
+ assert new == "value = x\u2014@\u2014y\n", f"Got {new!r}"
+
class TestUnicodeSpaceAndMinusNormalized:
"""Space-separator family + Unicode minus normalization.
diff --git a/tools/fuzzy_match.py b/tools/fuzzy_match.py
index 1ee3d9f6c54..596631653bd 100644
--- a/tools/fuzzy_match.py
+++ b/tools/fuzzy_match.py
@@ -9,6 +9,7 @@ still land on the intended region::
content, old_string, new_string, replace_all=False)
"""
+import bisect
import re
from difflib import SequenceMatcher
from typing import Callable, Optional
@@ -514,7 +515,14 @@ def _preserve_unicode_in_replacement(content: str, matches: list[Span],
result_parts: list[str] = []
for tag, i1, i2, j1, j2 in SequenceMatcher(None, norm_old, new_string).get_opcodes():
if tag == "equal":
- orig_start = file_norm_to_orig.get(i1, 0)
+ orig_start = file_norm_to_orig.get(i1)
+ if orig_start is None:
+ # Equal-block boundary landed inside a multi-char expansion
+ # (em-dash -> '--'): a norm index with no original position of
+ # its own. Snap back to the expansion's first original char —
+ # the old fallback of 0 spliced region-start text into the
+ # replacement, duplicating it after the edit.
+ orig_start = bisect.bisect_right(file_orig_to_norm, i1) - 1
orig_end = _norm_end_to_orig(file_orig_to_norm, orig_start, i2)
result_parts.append(file_region[orig_start:orig_end])
elif tag != "delete":