Skip to content

The agent that grows with you

feat(tools): share escape-drift correction

Elisa Martinez Abad74bec4c243f1
diff --git a/tests/tools/test_escape_drift_autocorrect.py b/tests/tools/test_escape_drift_autocorrect.py
index 0929493cc8b..ad89f3e2226 100644
--- a/tests/tools/test_escape_drift_autocorrect.py
+++ b/tests/tools/test_escape_drift_autocorrect.py
@@ -38,6 +38,70 @@ def test_mixed_quote_escaping_is_not_corrected():
assert maybe_correct_escape_drift(old, new, content) == (old, new, None)
+_SHARED_CASES = [
+ ('pat = r"\\d+"\n', r'pat = r"\\d+"', 'pat = None', 'pat = None\n'),
+ ("x = 'it'\n", r"x = \'it\'", r"x = \'its\'", "x = 'its'\n"),
+ ('pat = r"\\d+"\n', r'pat = r"\\d+"', r'pat = r"\\w+"', None),
+]
+
+
[email protected]("engine", ["replace", "v4a", "skill"])
[email protected]("content,old,new,expected", _SHARED_CASES,
+ ids=["backslash_free", "quote", "ambiguous"])
+def test_shared_correction_policy_across_tools(workdir, monkeypatch, engine, content, old, new, expected):
+ target = workdir / "example.txt"
+ target.write_text(content)
+ if engine == "skill":
+ from tools import skill_manager_tool
+ skill_dir = workdir / "skills" / "example"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text("---\nname: example\ndescription: Test skill.\n---\n")
+ target = skill_dir / "references" / "example.txt"
+ target.parent.mkdir()
+ target.write_text(content)
+ monkeypatch.setattr(skill_manager_tool, "SKILLS_DIR", skill_dir.parent)
+ monkeypatch.setattr("agent.skill_utils.get_all_skills_dirs", lambda: [skill_dir.parent])
+ result = json.loads(skill_manager_tool.skill_manage(
+ action="patch", name="example", file_path=str(target.relative_to(skill_dir)),
+ old_string=old, new_string=new, task_id="t-shared"))
+ elif engine == "v4a":
+ patch = (f"*** Begin Patch\n*** Update File: {target}\n@@\n"
+ + "\n".join("-" + line for line in old.splitlines()) + "\n"
+ + "\n".join("+" + line for line in new.splitlines()) + "\n*** End Patch")
+ result = _patch_tool(mode="patch", patch=patch, task_id="t-shared")
+ else:
+ result = _patch_tool(path=str(target), old_string=old, new_string=new, task_id="t-shared")
+ if expected is None:
+ assert result.get("success") is not True
+ assert "intentional backslashes" in result["error"]
+ assert target.read_text() == content
+ else:
+ assert result["success"] is True
+ assert target.read_text() == expected
+ assert "escape-drift auto-corrected" in result["note"]
+
+
[email protected]("content,old,new,expected", _SHARED_CASES,
+ ids=["backslash_free", "quote", "ambiguous"])
+def test_approval_preview_agrees_with_patch(workdir, content, old, new, expected):
+ from acp_adapter.edit_approval import build_edit_proposal
+ target = workdir / "preview.txt"
+ target.write_text(content)
+ arguments = dict(path=str(target), old_string=old, new_string=new)
+ if expected is None:
+ with pytest.raises(ValueError, match="intentional backslashes"):
+ build_edit_proposal("patch", arguments)
+ result = _patch_tool(**arguments, task_id="t-preview")
+ assert result.get("success") is not True
+ assert target.read_text() == content
+ else:
+ proposal = build_edit_proposal("patch", arguments)
+ assert target.read_text() == content
+ result = _patch_tool(**arguments, task_id="t-preview")
+ assert result["success"] is True
+ assert proposal.new_text == target.read_text() == expected
+
+
class TestPatchEndToEnd:
@pytest.mark.parametrize("replacement", [
r'sep = r"a\c"',
diff --git a/tests/tools/test_fuzzy_match.py b/tests/tools/test_fuzzy_match.py
index 2fbe2b2ce7d..d7778b3af8a 100644
--- a/tests/tools/test_fuzzy_match.py
+++ b/tests/tools/test_fuzzy_match.py
@@ -751,7 +751,7 @@ class TestBackslashDoublingDrift:
new = old + ' # touched'
result, count, _strategy, err = self.replace(content, old, new)
assert count == 0
- assert err is not None and "twice as long" in err
+ assert err is not None and "intentional backslashes" in err
assert result == content # untouched
def test_matching_backslashes_apply(self):
@@ -772,16 +772,14 @@ class TestBackslashDoublingDrift:
assert count == 1 and err is None
assert strategy == "exact"
- def test_model_corrected_new_string_allowed(self):
- """Doubled old_string but corrected new_string writes the right bytes."""
+ def test_model_corrected_new_string_requires_clean_anchor(self):
+ """A corrected replacement is still unverifiable beside a doubled anchor."""
b = "\\"
content, old = self._make(n_file=2, n_args=4)
new = old.replace(b * 4, b * 2).replace("next line", "corrected")
result, count, _strategy, err = self.replace(content, old, new)
- assert count == 1 and err is None
- assert "corrected" in result
- # No doubling in the output
- assert b * 4 not in result
+ assert count == 0 and "intentional backslashes" in err
+ assert result == content
def test_single_prose_backslash_not_blocked(self):
"""A lone ``\\`` vs ``\\`` in prose is too weak a signal to block."""
@@ -792,12 +790,12 @@ class TestBackslashDoublingDrift:
_result, _count, _strategy, err = self.replace(content, old, new)
assert err is None or "twice" not in err
- def test_quote_drift_guard_still_fires(self):
- """The pre-existing apostrophe escape-drift guard must keep working."""
+ def test_verified_quote_drift_is_corrected(self):
+ """Shared matching corrects quote drift when its anchor is verified."""
b = "\\"
content = "print('hello world')\nrest = 1\n"
old = "print(" + b + "'hello world" + b + "')\nrest = 1"
new = "print(" + b + "'hello there" + b + "')\nrest = 1"
- _result, count, _strategy, err = self.replace(content, old, new)
- assert count == 0
- assert err is not None and "apostrophe" in err
+ result, count, _strategy, err = self.replace(content, old, new)
+ assert count == 1 and err is None
+ assert result == "print('hello there')\nrest = 1\n"
diff --git a/tools/escape_drift_autocorrect.py b/tools/escape_drift_autocorrect.py
index 1acce643d7a..a1154f3dd6e 100644
--- a/tools/escape_drift_autocorrect.py
+++ b/tools/escape_drift_autocorrect.py
@@ -1,4 +1,4 @@
-"""Conservative correction of escape drift before ``patch_replace`` matches text.
+"""Conservative correction of escape drift before shared fuzzy matching.
Corrections require the corrected ``old_string`` to appear verbatim in the file.
That evidence cannot establish the intended escaping of newly added code: deliberate
diff --git a/tools/file_operations.py b/tools/file_operations.py
index 859232d79b2..976e77dcf10 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1618,15 +1618,10 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
raw_content = data.decode("utf-8", "surrogateescape")
content, _ = _strip_bom(raw_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_replace
+ correction_notes = []
new_content, match_count, _strategy, error = fuzzy_find_and_replace(
- content, old_string, new_string, replace_all)
+ content, old_string, new_string, replace_all, correction_notes=correction_notes)
if error or match_count == 0:
return self._no_match_result(path, content, old_string, new_string, match_count, error)
# Models send bare-LF old/new strings; normalize the substituted region to
@@ -1644,7 +1639,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return PatchResult(
success=True, diff=self._unified_diff(content, new_content, path), files_modified=[path],
lint=lint_result.to_dict() if lint_result else None,
- note=escape_drift_note,
+ note="\n".join(correction_notes) or None,
# From the internal write_file call, whose baseline was the pre-patch content.
lsp_diagnostics=write_result.lsp_diagnostics,
_writes=[(path, hashlib.sha256(data).hexdigest(), write_result._content_sha256)])
diff --git a/tools/fuzzy_match.py b/tools/fuzzy_match.py
index f06c1659043..7e364e9f497 100644
--- a/tools/fuzzy_match.py
+++ b/tools/fuzzy_match.py
@@ -336,11 +336,13 @@ def _format_match_locations(content: str, matches: list[Span], cap: int = 5) ->
def fuzzy_find_and_replace(content: str, old_string: str, new_string: str,
- replace_all: bool = False) -> tuple[str, int, Optional[str], Optional[str]]:
+ replace_all: bool = False, *,
+ correction_notes: Optional[list[str]] = None) -> tuple[str, int, Optional[str], Optional[str]]:
"""Find and replace via the strategy chain.
Returns ``(new_content, match_count, strategy_name, error)``; on failure
- ``(content, 0, None, error)``.
+ ``(content, 0, None, error)``. Successful escape corrections append their
+ explanation to ``correction_notes`` when supplied by a tool caller.
"""
if not old_string:
# Actionable recovery text: a terse "cannot be empty" leaves the model
@@ -358,6 +360,13 @@ def fuzzy_find_and_replace(content: str, old_string: str, new_string: str,
"old_string is only whitespace — provide non-blank text to match. Set it "
"to the exact existing text the replacement should replace (read the file "
"first if unsure). Do not re-send this call unchanged.")
+ # All consumers, including validation and approval previews, must use the
+ # same correction policy before a fuzzy strategy can match ambiguous text.
+ from tools.escape_drift_autocorrect import AmbiguousEscapeDriftError, maybe_correct_escape_drift
+ try:
+ old_string, new_string, correction_note = maybe_correct_escape_drift(old_string, new_string, content)
+ except AmbiguousEscapeDriftError as exc:
+ return content, 0, None, str(exc)
if old_string == new_string:
return content, 0, None, IDENTICAL_STRINGS_ERROR
@@ -395,6 +404,8 @@ def fuzzy_find_and_replace(content: str, old_string: str, new_string: str,
unicode_plan=(_unicode_edit_plan(old_string, effective_new)
if strategy_name == "unicode_normalized" else None))
_note_edit_match(strategy_name)
+ if correction_note and correction_notes is not None:
+ correction_notes.append(correction_note)
return new_content, len(matches), strategy_name, None
_note_edit_match(None, "no_match")
diff --git a/tools/patch_parser.py b/tools/patch_parser.py
index 3d7e25d1c68..7eef6818397 100644
--- a/tools/patch_parser.py
+++ b/tools/patch_parser.py
@@ -305,6 +305,7 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Pat
error="Patch validation failed (no files were modified):\n" + _bullets(errors))
files: dict[str, list[str]] = {"created": [], "deleted": [], "modified": []}
all_diffs: list[str] = []
+ correction_notes: list[str] = []
# V4A bypasses write_file's WriteResult plumbing: LSP diagnostics and lint propagate per file.
lsp_blocks: list[str] = []
lint_results: dict[str, dict] = {}
@@ -312,7 +313,10 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Pat
for op in operations:
handler, verb, bucket = _APPLY_DISPATCH[op.operation]
try:
- ok, payload, lsp, lint, write = handler(op, file_ops)
+ if op.operation is OperationType.UPDATE:
+ ok, payload, lsp, lint, write = handler(op, file_ops, correction_notes=correction_notes)
+ else:
+ ok, payload, lsp, lint, write = handler(op, file_ops)
except Exception as e:
ok, payload = None, str(e)
if not ok:
@@ -335,7 +339,8 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Pat
+ _bullets(errors)) if errors else None,
diff='\n'.join(all_diffs),
files_modified=files["modified"], files_created=files["created"], files_deleted=files["deleted"],
- lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None, _writes=writes)
+ lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None, _writes=writes,
+ note="\n".join(dict.fromkeys(correction_notes)) or None)
def _write_file_accepts_pre_content(file_ops: Any) -> bool:
@@ -406,13 +411,15 @@ def _insert_addition_only(new_content: str, hunk: Hunk, insert_text: str) -> tup
return new_content.rstrip('\n') + '\n' + insert_text + '\n', None
-def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
+def _apply_update(op: PatchOperation, file_ops: Any, *,
+ correction_notes: Optional[list[str]] = None) -> ApplyResult:
"""Apply each hunk via fuzzy replace, then write once."""
from tools.fuzzy_match import fuzzy_find_and_replace, is_already_applied
read_result = file_ops.read_file_raw(op.file_path) # raw: no line numbers / truncation
if read_result.error:
return _fail(f"Cannot read file: {read_result.error}")
current_content = new_content = read_result.content
+ hunk_notes: list[str] = []
for hunk in op.hunks:
search_lines, replace_lines = _split_hunk(hunk)
if search_lines and search_lines == replace_lines:
@@ -424,7 +431,7 @@ def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
return _fail(err)
continue
new_content, count, _strategy, error = fuzzy_find_and_replace(
- new_content, search_pattern, replacement, replace_all=False)
+ new_content, search_pattern, replacement, replace_all=False, correction_notes=hunk_notes)
if not (error and count == 0):
continue
# Retry inside a window around the context hint, if any.
@@ -433,7 +440,8 @@ def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
window_start = max(0, hint_pos - 500)
window_end = min(len(new_content), hint_pos + 2000)
window_new, count, _strategy, error = fuzzy_find_and_replace(
- new_content[window_start:window_end], search_pattern, replacement, replace_all=False)
+ new_content[window_start:window_end], search_pattern, replacement, replace_all=False,
+ correction_notes=hunk_notes)
if count > 0:
new_content = new_content[:window_start] + window_new + new_content[window_end:]
error = None
@@ -446,8 +454,11 @@ def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
# Pass pre_content to skip a redundant re-read inside write_file when supported.
extra = {"pre_content": current_content} if _write_file_accepts_pre_content(file_ops) else {}
write_result = file_ops.write_file(op.file_path, new_content, **extra)
- return _written(write_result, _unified_diff(op.file_path, current_content, new_content),
- op.file_path, getattr(read_result, "_content_sha256", None))
+ result = _written(write_result, _unified_diff(op.file_path, current_content, new_content),
+ op.file_path, getattr(read_result, "_content_sha256", None))
+ if result[0] and correction_notes is not None:
+ correction_notes.extend(hunk_notes)
+ return result
# operation -> (handler, verb for error text, files_* bucket)
diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py
index 8d4d4ef375c..06fc0ddb870 100644
--- a/tools/skill_manager_tool.py
+++ b/tools/skill_manager_tool.py
@@ -532,8 +532,9 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str | N
# Use the same fuzzy matching engine as the file patch tool.
from tools.fuzzy_match import fuzzy_find_and_replace
+ correction_notes = []
new_content, match_count, _strategy, match_error = fuzzy_find_and_replace(
- content, old_string, new_string, replace_all)
+ content, old_string, new_string, replace_all, correction_notes=correction_notes)
if match_error:
with suppress(Exception):
from tools.fuzzy_match import format_no_match_hint
@@ -549,6 +550,8 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str | N
"success": True,
"message": f"Patched {target_label} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).",
"_change": {"old": _clip(old_string, 200, "…"), "new": _clip(new_string, 200, "…")}}
+ if correction_notes:
+ result["note"] = "\n".join(correction_notes)
# SKILL.md grows by patches, not by creates: surface findings on the patch that crosses a line
# (oversized-body, incident-log-shape) — a clean patch attaches nothing and stays quiet.
if not file_path: