refactor(files): remove redundant edit and snapshot state

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 721cc4e23f
commit 51884a244e
6 files changed
+47 -61

No files matched your search

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