Skip to content

The agent that grows with you

refactor(tools): pass each region to the Unicode-preserving replacement

kshitijk4poor992f7807bf60
diff --git a/tests/tools/test_fuzzy_match.py b/tests/tools/test_fuzzy_match.py
index b56b3888f19..8d1273f763a 100644
--- a/tests/tools/test_fuzzy_match.py
+++ b/tests/tools/test_fuzzy_match.py
@@ -161,6 +161,17 @@ class TestReplaceAll:
assert count == 2
assert new == "ccc bbb ccc"
+ def test_unicode_normalized_preserves_each_matches_own_unicode(self):
+ """Each normalized match keeps ITS typographic characters; the regions were
+ once concatenated, which spliced both matches' text into every replacement."""
+ content = "Price \u2018old\u2019\u2014ready\nPrice 'old'\u2014ready\n"
+ new, count, strategy, err = fuzzy_find_and_replace(
+ content, "Price 'old'--ready", "Price 'new'--ready", replace_all=True)
+ assert err is None
+ assert count == 2
+ assert strategy == "unicode_normalized"
+ assert new == "Price \u2018new\u2019\u2014ready\nPrice 'new'\u2014ready\n"
+
def test_self_overlapping_pattern_non_overlapping_matches(self):
"""Self-overlapping patterns must produce non-overlapping spans.
diff --git a/tests/tools/test_patch_unicode_replace_all.py b/tests/tools/test_patch_unicode_replace_all.py
deleted file mode 100644
index 1cf787ed935..00000000000
--- a/tests/tools/test_patch_unicode_replace_all.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""Replacing every normalized match preserves each region's untouched Unicode."""
-
-import json
-
-from tools import file_tools, terminal_tool
-from tools.registry import registry
-
-
-def test_replace_all_preserves_each_matches_unicode(tmp_path, monkeypatch):
- home = tmp_path / "home"
- home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- path = tmp_path / "notes.txt"
- original = "Price ‘old’—ready\nPrice 'old'—ready\n"
- path.write_text(original, encoding="utf-8")
- task = "unicode-replace-all"
- terminal_tool.register_task_env_overrides(task, {"env_type": "local", "cwd": str(tmp_path)})
- try:
- read = json.loads(registry.dispatch("read_file", {"path": str(path)}, task_id=task))
- assert "error" not in read
- result = json.loads(registry.dispatch("patch", {
- "mode": "replace", "path": str(path), "old_string": "Price 'old'--ready",
- "new_string": "Price 'new'--ready", "replace_all": True,
- }, task_id=task))
- assert "error" not in result, result
- assert path.read_text(encoding="utf-8") == original.replace("old", "new")
- finally:
- file_tools.clear_file_ops_cache(task)
- terminal_tool.clear_task_env_overrides(task)
diff --git a/tools/fuzzy_match.py b/tools/fuzzy_match.py
index e1892e19a50..d5f8e84f54f 100644
--- a/tools/fuzzy_match.py
+++ b/tools/fuzzy_match.py
@@ -550,19 +550,26 @@ def _reindent_replacement(file_region: str, old_string: str, new_string: str) ->
return "\n".join(out_lines)
-def _preserve_unicode_in_replacement(content: str, matches: list[Span],
- old_string: str, new_string: str) -> str:
- """Apply only the old->new edits onto the file's original (Unicode) text, so a
- unicode_normalized match doesn't flatten the file's em-dashes/smart quotes."""
- file_region = _matched_regions(content, matches)
+def _unicode_edit_plan(old_string: str, new_string: str) -> tuple[str, list]:
+ """``(normalized old, old->new opcodes)``: independent of the file region, so
+ a replace_all computes it once for every match."""
norm_old = _unicode_normalize(old_string)
+ return norm_old, SequenceMatcher(None, norm_old, new_string).get_opcodes()
+
+
+def _preserve_unicode_in_replacement(file_region: str, old_string: str, new_string: str,
+ plan: Optional[tuple[str, list]] = None) -> str:
+ """Apply only the old->new edits onto ``file_region``'s original (Unicode) text,
+ so a unicode_normalized match doesn't flatten the file's em-dashes/smart quotes.
+ ``plan`` is a precomputed ``_unicode_edit_plan(old_string, new_string)``."""
+ norm_old, opcodes = plan or _unicode_edit_plan(old_string, new_string)
if norm_old != _unicode_normalize(file_region):
return new_string # strategy shouldn't have fired; fall back
file_orig_to_norm = _build_orig_to_norm_map(file_region)
result_parts: list[str] = []
- for tag, i1, i2, j1, j2 in SequenceMatcher(None, norm_old, new_string).get_opcodes():
+ for tag, i1, i2, j1, j2 in opcodes:
if tag == "equal":
# The original char owning norm index i1, even one inside a multi-char expansion (em-dash -> '--').
orig_start = bisect.bisect_right(file_orig_to_norm, i1) - 1
@@ -579,15 +586,16 @@ def _apply_replacements(content: str, matches: list[Span],
"""Splice ``new_string`` over each span (end-to-start so offsets stay valid);
``old_string`` non-None (non-exact match) re-indents it per region."""
result = content
+ plan = _unicode_edit_plan(old_string, new_string) if preserve_unicode and old_string is not None else None
for start, end in sorted(matches, key=lambda x: x[0], reverse=True):
adjusted = new_string
if old_string is not None:
- if preserve_unicode:
+ region = content[start:end]
+ if plan is not None:
# Each occurrence may use different typographic characters even
# though all normalize to the same old_string.
- adjusted = _preserve_unicode_in_replacement(
- content, [(start, end)], old_string, adjusted)
- adjusted = _reindent_replacement(content[start:end], old_string, adjusted)
+ adjusted = _preserve_unicode_in_replacement(region, old_string, adjusted, plan)
+ adjusted = _reindent_replacement(region, old_string, adjusted)
result = result[:start] + adjusted + result[end:]
return result