The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): add V4A boundary note
Elisa Martinez Abad5b2c0c1eb690
diff --git a/tests/tools/test_file_tools_live.py b/tests/tools/test_file_tools_live.pyindex 984ee25d93b..5603c55d048 100644--- a/tests/tools/test_file_tools_live.py+++ b/tests/tools/test_file_tools_live.py@@ -199,6 +199,59 @@ class TestPatchReplace:assert result.note is None+class TestPatchV4A:+ """The V4A path runs the same fuzzy chain as patch_replace, so it gets the same boundary note."""+ FUNC = TestPatchReplace.FUNC++ @staticmethod+ def _patch(path, *hunk_lines):+ return "\n".join(["*** Begin Patch", f"*** Update File: {path}", "@@ @@", *hunk_lines, "*** End Patch"])++ def test_similarity_match_gets_boundary_note_naming_the_file(self, ops, tmp_path):+ from tools.fuzzy_match import fuzzy_find_and_replace+ old = "def total(x):\n y = x + 2\n return y"+ assert fuzzy_find_and_replace(self.FUNC, old, "pass", False)[2] == "block_anchor"+ path = tmp_path / "anchor.py"+ path.write_text(self.FUNC)+ result = ops.patch_v4a(self._patch(+ path, " def total(x):", "- y = x + 2", "- return y", "+ return x + 1"))+ assert result.success, result.error+ assert result.note and "block_anchor" in result.note and str(path) in result.note++ def test_line_trimmed_match_gets_no_note(self, ops, tmp_path):+ from tools.fuzzy_match import fuzzy_find_and_replace+ assert fuzzy_find_and_replace(self.FUNC, "y = x + 1\nreturn y", "pass", False)[2] == "line_trimmed"+ path = tmp_path / "trimmed.py"+ path.write_text(self.FUNC)+ result = ops.patch_v4a(self._patch(path, "-y = x + 1", "+y = x + 3", " return y"))+ assert result.success, result.error+ assert path.read_text() == "def total(x):\n y = x + 3\n return y\n"+ assert result.note is None++ def test_exact_match_gets_no_note(self, ops, tmp_path):+ path = tmp_path / "exact.py"+ path.write_text(self.FUNC)+ result = ops.patch_v4a(self._patch(+ path, " def total(x):", "- y = x + 1", "+ y = x + 3", " return y"))+ assert result.success, result.error+ assert result.note is None++ def test_note_names_only_the_file_that_matched_approximately(self, ops, tmp_path):+ approx, exact = tmp_path / "approx.py", tmp_path / "exact.py"+ approx.write_text(self.FUNC)+ exact.write_text("a = 1\nb = 2\n")+ patch = "\n".join([+ "*** Begin Patch",+ f"*** Update File: {approx}", "@@ @@",+ " def total(x):", "- y = x + 2", "- return y", "+ return x + 1",+ f"*** Update File: {exact}", "@@ @@",+ "-a = 1", "+a = 5",+ "*** End Patch"])+ result = ops.patch_v4a(patch)+ assert result.success, result.error+ assert str(approx) in result.note and str(exact) not in result.note++# ── search ───────────────────────────────────────────────────────────────class TestSearch:diff --git a/tools/file_operations.py b/tools/file_operations.pyindex a15f5c3aaca..bd22b810946 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -1645,7 +1645,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):raw_content = data.decode("utf-8", "surrogateescape")content, _ = _strip_bom(raw_content)- from tools.fuzzy_match import SIMILARITY_STRATEGIES, fuzzy_find_and_replace+ from tools.fuzzy_match import boundary_note, fuzzy_find_and_replacecorrection_notes = []new_content, match_count, strategy, error = fuzzy_find_and_replace(content, old_string, new_string, replace_all, correction_notes=correction_notes)@@ -1663,23 +1663,10 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):if verify_error is not None:return verify_errorlint_result = self._check_lint_delta(path, pre_content=content, post_content=new_content)- # The similarity strategies accept a window whose lines only resemble old_string, so- # the spliced span can land a line off (observed: a duplicated closing delimiter/brace- # just outside the intended region). The normalizing strategies still match every- # line, so their boundaries are exact — and they fire on routine edits (e.g. missing- # base indentation), where a note would teach the model to ignore it. Post-write- # verification above cannot catch a shifted span: it only confirms new_content landed.- boundary_note = (- f"Non-exact match (strategy: {strategy}). The edit span was located approximately, "- "not matched to old_string's literal boundaries — review the diff below to confirm "- "the change landed exactly where intended (a shifted boundary can duplicate or drop "- "a line just outside the edited region)."- if strategy in SIMILARITY_STRATEGIES else None- )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="\n".join(n for n in (*correction_notes, boundary_note) if n) or None,+ note="\n".join(n for n in (*correction_notes, boundary_note([strategy])) if n) 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.pyindex 7e364e9f497..183ab5c3670 100644--- a/tools/fuzzy_match.py+++ b/tools/fuzzy_match.py@@ -12,7 +12,7 @@ still land on the intended region::import bisectimport refrom difflib import SequenceMatcher-from typing import Callable, Optional+from typing import Callable, Iterable, OptionalSpan = tuple[int, int]@@ -302,6 +302,27 @@ STRATEGIES: list[tuple[str, Callable[[str, str], list[Span]]]] = [SIMILARITY_STRATEGIES = frozenset({"block_anchor", "context_aware"})+def boundary_note(strategies: Iterable[Optional[str]], target: str = "old_string's",+ where: str = "") -> Optional[str]:+ """The note for an edit whose span was found by a similarity strategy, else None.++ Those strategies accept a window whose lines only resemble the search text, so the spliced span+ can land a line off (observed: a duplicated closing delimiter just outside the intended region).+ The normalizing strategies still match every line, so their boundaries are exact; they fire on+ routine edits (e.g. missing base indentation), where a note would teach the model to ignore it.+ Post-write verification cannot catch a shifted span: it only confirms the new content landed.+ """+ used = list(dict.fromkeys(s for s in strategies if s in SIMILARITY_STRATEGIES))+ if not used:+ return None+ return (+ f"Non-exact match (strategy: {', '.join(used)}){where}. The edit span was located "+ f"approximately, not matched to {target} literal boundaries — review the diff below to "+ "confirm the change landed exactly where intended (a shifted boundary can duplicate or "+ "drop a line just outside the edited region)."+ )++# ── Orchestrator ─────────────────────────────────────────────────────────def is_already_applied(content: str, old_string: str, new_string: str) -> bool:diff --git a/tools/patch_parser.py b/tools/patch_parser.pyindex 7eef6818397..55aa5cb37e6 100644--- a/tools/patch_parser.py+++ b/tools/patch_parser.py@@ -42,6 +42,8 @@ class PatchOperation:file_path: strnew_path: Optional[str] = None # MOVE onlyhunks: list[Hunk] = field(default_factory=list)+ # Fuzzy strategies that located this operation's hunks (filled while applying an UPDATE).+ strategies_used: list[str] = field(default_factory=list)# Markers must occupy the whole line at column 0 so content lines that merely@@ -295,6 +297,7 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Pat"""Two-phase: validate everything, then apply (atomic on validation failure). A phase-2failure (validate/apply race) carries a ``git diff`` note since state may be inconsistent.``file_ops`` needs read_file_raw/write_file/delete_file/move_file."""+ from tools.fuzzy_match import boundary_notedef _bullets(errs: list[str]) -> str:return "\n".join(f" • {e}" for e in errs)@@ -310,6 +313,8 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Patlsp_blocks: list[str] = []lint_results: dict[str, dict] = {}writes: list[tuple] = []+ # A hunk found by a similarity strategy may have landed a line off; say so, per file.+ boundary_notes: list[str] = []for op in operations:handler, verb, bucket = _APPLY_DISPATCH[op.operation]try:@@ -328,6 +333,8 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Patall_diffs.append(payload)if write:writes.append(write)+ if note := boundary_note(op.strategies_used, "the hunk's", f" in {op.file_path}"):+ boundary_notes.append(note)if lsp:lsp_blocks.append(lsp)if lint:@@ -340,7 +347,7 @@ def apply_v4a_operations(operations: list[PatchOperation], file_ops: Any) -> Patdiff='\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,- note="\n".join(dict.fromkeys(correction_notes)) or None)+ note="\n".join([*dict.fromkeys(correction_notes), *boundary_notes]) or None)def _write_file_accepts_pre_content(file_ops: Any) -> bool:@@ -430,19 +437,22 @@ def _apply_update(op: PatchOperation, file_ops: Any, *,if err:return _fail(err)continue- new_content, count, _strategy, error = fuzzy_find_and_replace(+ new_content, count, strategy, error = fuzzy_find_and_replace(new_content, search_pattern, replacement, replace_all=False, correction_notes=hunk_notes)if not (error and count == 0):+ if count > 0:+ op.strategies_used.append(strategy)continue# Retry inside a window around the context hint, if any.hint_pos = new_content.find(hunk.context_hint) if hunk.context_hint else -1if hint_pos != -1: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(+ window_new, count, strategy, error = fuzzy_find_and_replace(new_content[window_start:window_end], search_pattern, replacement, replace_all=False,correction_notes=hunk_notes)if count > 0:+ op.strategies_used.append(strategy)new_content = new_content[:window_start] + window_new + new_content[window_end:]error = Noneif error: