diff --git a/nanobot/agent/tools/apply_patch.py b/nanobot/agent/tools/apply_patch.py index 9e472e0c9..111e99ed5 100644 --- a/nanobot/agent/tools/apply_patch.py +++ b/nanobot/agent/tools/apply_patch.py @@ -1,6 +1,7 @@ from __future__ import annotations from collections.abc import Iterator, Mapping +from pathlib import Path from typing import Any, cast from nanobot.agent.tools.base import ToolResult, tool_parameters @@ -102,8 +103,7 @@ class ApplyPatchTool(_WritableFsTool): raise _PatchError("must provide edits") writes: dict[WritableFile, str] = {} - originals: dict[WritableFile, str] = {} - actions: dict[WritableFile, str] = {} + originals: dict[WritableFile, str | None] = {} for edit_value in edits: if not isinstance(edit_value, dict): @@ -124,21 +124,20 @@ class ApplyPatchTool(_WritableFsTool): raise _PatchError(f"new_text required for {action}: {path}") new_text = cast(str, new_text) - pending = writes.get(source) - content = pending - if content is None and source.exists(): - try: - content = source.read_bytes().decode("utf-8") - except UnicodeDecodeError: - raise _PatchError(f"file is not UTF-8 text: {path}") - created = content is None + content = writes.get(source) if content is None: - if action == "replace": + if source.exists(): + try: + content = source.read_bytes().decode("utf-8") + except UnicodeDecodeError: + raise _PatchError(f"file is not UTF-8 text: {path}") + if action == "replace" and not source.is_file(): + raise _PatchError(f"path to update is not a file: {path}") + elif action == "replace": raise _PatchError(f"file to update does not exist: {path}") - content = "" - - if action == "replace" and pending is None and not source.is_file(): - raise _PatchError(f"path to update is not a file: {path}") + originals[source] = content + if content is None: + content = "" norm_content = content.replace("\r\n", "\n") if action == "add": @@ -164,16 +163,14 @@ class ApplyPatchTool(_WritableFsTool): if updated and not updated.endswith("\n"): updated += "\n" writes[source] = updated.replace("\n", "\r\n") if "\r\n" in content else updated - originals.setdefault(source, content) - actions.setdefault(source, "add" if created else "update") - diffs = { - source: FileDiff.from_text(originals[source], content) - for source, content in writes.items() - } + diffs: dict[Path, FileDiff] = {} summaries: list[str] = [] - for source, diff in diffs.items(): - action_name = actions[source] + for source, content in writes.items(): + original = originals[source] + action_name = "add" if original is None else "update" + diff = FileDiff.from_text(original or "", content) + diffs[source.path] = diff path = display_file_edit_path(source.path, self._files.display_workspace) added, deleted = diff.added, diff.deleted stats = f" (+{added}/-{deleted})" if added or deleted else "" @@ -187,7 +184,7 @@ class ApplyPatchTool(_WritableFsTool): self._file_states.record_write(target.path) return FileEditResult( "Patch applied:\n" + "\n".join(summaries), - {target.path: diff for target, diff in diffs.items()}, + diffs, ) except PermissionError as exc: return ToolResult.error(f"Error: {exc}") diff --git a/nanobot/agent/tools/search.py b/nanobot/agent/tools/search.py index 25dbc17b4..a013b98f1 100644 --- a/nanobot/agent/tools/search.py +++ b/nanobot/agent/tools/search.py @@ -8,6 +8,7 @@ import heapq import re import threading import time +from collections import Counter from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass @@ -749,7 +750,7 @@ class GrepTool(_SearchTool): skipped_large = 0 document_error: str | None = None document_continuations: list[str] = [] - counts: dict[str, int] = {} + counts: Counter[str] = Counter() file_mtimes: dict[str, float] = {} root = tree.root if tree.is_directory else tree.root.parent max_file_bytes = ( @@ -835,7 +836,7 @@ class GrepTool(_SearchTool): # A document can fail after yielding matches. Keep the count # of those lines even though the failed file is not ranked. if file_matches and output_mode == "count": - counts[display_path] = counts.get(display_path, 0) + file_matches + counts[display_path] += file_matches if file_matches: file_mtimes[display_path] = mtime if content_page.stopped: diff --git a/nanobot/execution/files.py b/nanobot/execution/files.py index 6684a0306..2fc90c88a 100644 --- a/nanobot/execution/files.py +++ b/nanobot/execution/files.py @@ -99,15 +99,10 @@ class ReadableFile: @dataclass(frozen=True, slots=True) class FileSnapshot: + """Text for the edit preview: empty for missing files, None if unavailable.""" + exists: bool text: str | None - unreadable: bool = False - binary: bool = False - oversized: bool = False - - @property - def countable(self) -> bool: - return self.text is not None and not (self.binary or self.oversized or self.unreadable) @dataclass(frozen=True, slots=True) @@ -140,18 +135,16 @@ class WritableFile: return FileSnapshot(exists=False, text="") with _open_regular_file(self.path) as (stream, size): if size > max_bytes: - return FileSnapshot(exists=True, text=None, oversized=True) + return FileSnapshot(exists=True, text=None) raw = stream.read(max_bytes + 1) except OSError: - return FileSnapshot(exists=self.exists(), text=None, unreadable=True) - if len(raw) > max_bytes: - return FileSnapshot(exists=True, text=None, oversized=True) - if b"\x00" in raw: - return FileSnapshot(exists=True, text=None, binary=True) + return FileSnapshot(exists=self.exists(), text=None) + if len(raw) > max_bytes or b"\x00" in raw: + return FileSnapshot(exists=True, text=None) try: text = raw.decode("utf-8") except UnicodeDecodeError: - return FileSnapshot(exists=True, text=None, binary=True) + return FileSnapshot(exists=True, text=None) return FileSnapshot(exists=True, text=text.replace("\r\n", "\n")) diff --git a/nanobot/utils/file_edit_events.py b/nanobot/utils/file_edit_events.py index 4f17b5e57..839e7998e 100644 --- a/nanobot/utils/file_edit_events.py +++ b/nanobot/utils/file_edit_events.py @@ -248,10 +248,7 @@ def build_file_edit_end_event( ) -> dict[str, Any]: after = tracker.target.snapshot(_MAX_SNAPSHOT_BYTES) diff_payload: dict[str, Any] | None = None - if ( - tracker.before.countable and after.countable - and tracker.before.text is not None and after.text is not None - ): + if tracker.before.text is not None and after.text is not None: if diff is None or not diff.matches(tracker.before.text, after.text): diff = FileDiff.from_text(tracker.before.text, after.text) added, deleted = diff.added, diff.deleted @@ -265,14 +262,7 @@ def build_file_edit_end_event( binary = False else: added, deleted = 0, 0 - binary = ( - tracker.before.binary - or tracker.before.oversized - or tracker.before.unreadable - or after.binary - or after.oversized - or after.unreadable - ) + binary = True payload = _event_payload( tracker, phase="end", diff --git a/tests/tools/test_apply_patch_tool.py b/tests/tools/test_apply_patch_tool.py index f9934441a..2d07cf6d0 100644 --- a/tests/tools/test_apply_patch_tool.py +++ b/tests/tools/test_apply_patch_tool.py @@ -141,11 +141,11 @@ def test_apply_patch_edits_add_to_existing_crlf_file_without_final_newline(tmp_p assert target.read_bytes() == b"alpha\r\nbravo\r\ncharlie\r\n" -@pytest.mark.parametrize("existing", [False, True], ids=["new-file", "existing-crlf"]) -def test_apply_patch_replaces_text_from_an_earlier_edit_in_the_batch(tmp_path, existing): +@pytest.mark.parametrize("original", [None, b"", b"alpha\r\nbravo"], ids=["new", "empty", "crlf"]) +def test_apply_patch_replaces_text_from_an_earlier_edit_in_the_batch(tmp_path, original): target = tmp_path / "notes.txt" - if existing: - target.write_bytes(b"alpha\r\nbravo") + if original is not None: + target.write_bytes(original) tool = ApplyPatchTool(workspace=tmp_path) result = asyncio.run(tool.execute(edits=[ @@ -155,8 +155,8 @@ def test_apply_patch_replaces_text_from_an_earlier_edit_in_the_batch(tmp_path, e assert result.startswith("Patch applied:\n") assert result.count("notes.txt") == 1 - assert f"{'update' if existing else 'add'} notes.txt" in result - assert target.read_bytes() == (b"alpha\r\nbravo\r\ndelta\r\n" if existing else b"delta\n") + assert f"{'add' if original is None else 'update'} notes.txt" in result + assert target.read_bytes() == (b"alpha\r\nbravo\r\ndelta\r\n" if original else b"delta\n") def test_apply_patch_rejects_delete_action(tmp_path): diff --git a/tests/utils/test_file_edit_events.py b/tests/utils/test_file_edit_events.py index 4cfd855e5..647b28132 100644 --- a/tests/utils/test_file_edit_events.py +++ b/tests/utils/test_file_edit_events.py @@ -256,7 +256,6 @@ def test_binary_file_is_reported_but_not_counted(tmp_path: Path) -> None: params={"path": "data.bin", "old_text": "before", "new_text": "after"}, ) [tracker] = trackers - assert not tracker.before.countable target.write_bytes(b"\x00\x01after") event = build_file_edit_end_event(tracker) assert event["binary"] is True @@ -264,9 +263,15 @@ def test_binary_file_is_reported_but_not_counted(tmp_path: Path) -> None: assert "diff" not in event -def test_binary_before_file_is_reported_but_not_counted(tmp_path: Path) -> None: +@pytest.mark.parametrize( + "before", [b"\x00\x01before", b"text\n" * 20], ids=["binary", "oversized"], +) +def test_unavailable_before_is_reported_but_not_counted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, before: bytes, +) -> None: + monkeypatch.setattr("nanobot.utils.file_edit_events._MAX_SNAPSHOT_BYTES", 64) target = tmp_path / "data.bin" - target.write_bytes(b"\x00\x01before") + target.write_bytes(before) trackers = prepare_file_edit_trackers( call_id="call-bin", tool_name="write_file",