refactor(tools): unify edit summaries with shared fast diffs

Return compact, workspace-relative summaries from edit_file and apply_patch.
Compute one RapidFuzz line alignment per file and reuse it for summary counts
and WebUI unified diffs, checking snapshots before reuse. Summarize batched
edits by their final file state.

Warn only when a recorded file version changed, without asking for a read
after an edit has already succeeded. Preserve existing edit errors.

Validate summary and activity reuse, repetitive files, diff formatting,
snapshot changes, file creation, and read-state behavior.
This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-15 11:25:01 +08:00
1 parent 3a725b35a7
commit 1c3c68262f
13 files changed
+346 -170

No files matched your search

+6 -1
View File
@@ -15,6 +15,7 @@ from nanobot.bus.outbound_events import FileEditEvent
from nanobot.events import EventSink
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.file_edit_events import (
FileEditResult,
FileEditTracker,
build_file_edit_end_event,
build_file_edit_error_event,
@@ -76,7 +77,11 @@ class FileEditActivityHook(AgentHook):
key = self._tool_call_key(tool_call)
trackers = self._trackers_by_call.get(key, [])
if trackers:
await self._emit([build_file_edit_end_event(tracker) for tracker in trackers])
diffs = result.file_diffs if isinstance(result, FileEditResult) else {}
await self._emit([
build_file_edit_end_event(tracker, diff=diffs.pop(tracker.path, None))
for tracker in trackers
])
self._trackers_by_call.pop(key, None)
async def on_execute_tool_error(
+21 -61
View File
@@ -2,8 +2,6 @@
from __future__ import annotations
import difflib
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
@@ -16,14 +14,7 @@ from nanobot.agent.tools.schema import (
StringSchema,
tool_parameters_schema,
)
@dataclass(slots=True)
class _PatchSummary:
action: str
path: str
added: int = 0
deleted: int = 0
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path
class _PatchError(ValueError):
@@ -39,28 +30,6 @@ def _validate_patch_path(path: str) -> str:
return normalized
def _text_line_count(text: str) -> int:
if not text:
return 0
return len(text.splitlines())
def _line_diff_stats(before: str, after: str) -> tuple[int, int]:
before_lines = before.replace("\r\n", "\n").splitlines()
after_lines = after.replace("\r\n", "\n").splitlines()
added = 0
deleted = 0
matcher = difflib.SequenceMatcher(a=before_lines, b=after_lines, autojunk=False)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
continue
if tag in ("replace", "delete"):
deleted += i2 - i1
if tag in ("replace", "insert"):
added += j2 - j1
return added, deleted
def _append_text(content: str, addition: str) -> str:
"""Append text without merging it into an unterminated final line."""
base = content.replace("\r\n", "\n")
@@ -73,13 +42,6 @@ def _append_text(content: str, addition: str) -> str:
return combined
def _format_summary(summary: _PatchSummary) -> str:
stats = ""
if summary.added or summary.deleted:
stats = f" (+{summary.added}/-{summary.deleted})"
return f"- {summary.action} {summary.path}{stats}"
@tool_parameters(
tool_parameters_schema(
edits=ArraySchema(
@@ -143,7 +105,8 @@ class ApplyPatchTool(_FsTool):
raise _PatchError("must provide edits")
writes: dict[Path, str] = {}
summaries: list[_PatchSummary] = []
originals: dict[Path, str] = {}
actions: dict[Path, str] = {}
for edit_value in edits:
if not isinstance(edit_value, dict):
@@ -185,23 +148,14 @@ class ApplyPatchTool(_FsTool):
if uses_crlf:
new_norm = new_norm.replace("\n", "\r\n")
writes[source] = new_norm
added, deleted = _line_diff_stats(content, new_norm)
action_name = "update"
else:
new_norm = new_text.replace("\r\n", "\n")
if new_norm and not new_norm.endswith("\n"):
new_norm += "\n"
writes[source] = new_norm
added = _text_line_count(new_norm)
deleted = 0
action_name = "add"
summaries.append(
_PatchSummary(
action=action_name, path=path, added=added, deleted=deleted
)
)
elif action == "replace":
old_text = edit.get("old_text") or ""
if not old_text:
@@ -248,20 +202,28 @@ class ApplyPatchTool(_FsTool):
new_norm = new_norm.replace("\n", "\r\n")
writes[source] = new_norm
added, deleted = _line_diff_stats(content, new_norm)
summaries.append(
_PatchSummary(
action="update", path=path, added=added, deleted=deleted
)
)
action_name = "update"
else:
raise _PatchError(f"unknown action: {action}")
originals.setdefault(source, content)
actions.setdefault(source, action_name)
diffs = {
source: FileDiff.from_text(originals[source], content)
for source, content in writes.items()
}
summaries: list[str] = []
for source, diff in diffs.items():
action_name = actions[source]
path = display_file_edit_path(source, self._display_workspace())
added, deleted = diff.added, diff.deleted
stats = f" (+{added}/-{deleted})" if added or deleted else ""
summaries.append(f"- {action_name} {path}{stats}")
if dry_run:
return "Patch dry-run succeeded:\n" + "\n".join(
_format_summary(summary) for summary in summaries
)
return "Patch dry-run succeeded:\n" + "\n".join(summaries)
backups: dict[Path, bytes | None] = {}
for path in writes:
@@ -283,9 +245,7 @@ class ApplyPatchTool(_FsTool):
for path in writes:
self._file_states.record_write(path)
return "Patch applied:\n" + "\n".join(
_format_summary(summary) for summary in summaries
)
return FileEditResult("Patch applied:\n" + "\n".join(summaries), diffs)
except PermissionError as exc:
return ToolResult.error(f"Error: {exc}")
except _PatchError as exc:
+5 -4
View File
@@ -71,7 +71,7 @@ class FileStates:
)
def check_read(self, path: str | Path) -> str | None:
"""Check if a file has been read and is fresh.
"""Warn when a file differs from its recorded read/write state.
Returns None if OK, or a warning string.
When mtime changed but file content is identical (e.g. touch, editor save),
@@ -80,7 +80,8 @@ class FileStates:
p = str(Path(path).resolve())
entry = self._state.get(p)
if entry is None:
return "Warning: file has not been read yet. Read it first to verify content before editing."
# Shell reads and content already in context may not be recorded here.
return None
try:
current_mtime = os.path.getmtime(p)
except OSError:
@@ -89,10 +90,10 @@ class FileStates:
if entry.content_hash and _hash_file(p) == entry.content_hash:
entry.mtime = current_mtime
return None
return "Warning: file has been modified since last read. Re-read to verify content before editing."
return "Warning: file was modified since the last recorded read or write."
# mtime unchanged - still check content hash to detect quick modifications
if entry.content_hash and _hash_file(p) != entry.content_hash:
return "Warning: file has been modified since last read. Re-read to verify content before editing."
return "Warning: file was modified since the last recorded read or write."
return None
def is_unchanged(self, path: str | Path, offset: int = 1, limit: int | None = None) -> bool:
+18 -6
View File
@@ -21,6 +21,7 @@ from nanobot.agent.tools.schema import (
)
from nanobot.config_base import Base
from nanobot.security.workspace_access import current_tool_workspace
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path
from nanobot.utils.helpers import build_image_content_blocks, detect_image_mime
@@ -911,6 +912,20 @@ class EditFileTool(_FsTool):
"""Strip trailing whitespace from each line."""
return "\n".join(line.rstrip() for line in text.split("\n"))
def _format_summary(
self, resolved_path: Path, before: str, after: str, *,
created: bool = False, warning: str | None = None,
) -> FileEditResult:
diff = FileDiff.from_text(before, after)
added, deleted = diff.added, diff.deleted
action = "add" if created else "update"
stats = f" (+{added}/-{deleted})" if added or deleted else ""
path = display_file_edit_path(resolved_path, self._display_workspace())
text = f"Patch applied:\n- {action} {path}{stats}"
if warning:
text = f"{warning}\n{text}"
return FileEditResult(text, {resolved_path: diff})
async def execute(
self, path: str | None = None, old_text: str | None = None,
new_text: str | None = None,
@@ -942,7 +957,7 @@ class EditFileTool(_FsTool):
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(new_text, encoding="utf-8")
self._file_states.record_write(fp)
return f"Successfully created {fp}"
return self._format_summary(fp, "", fp.read_bytes().decode("utf-8"), created=True)
return self._file_not_found_msg(path, fp)
# File size protection
@@ -961,7 +976,7 @@ class EditFileTool(_FsTool):
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.")
fp.write_text(new_text, encoding="utf-8")
self._file_states.record_write(fp)
return f"Successfully edited {fp}"
return self._format_summary(fp, content, fp.read_bytes().decode("utf-8"))
# Read-before-edit check
warning = self._file_states.check_read(fp)
@@ -1054,10 +1069,7 @@ class EditFileTool(_FsTool):
fp.write_bytes(new_content.encode("utf-8"))
self._file_states.record_write(fp)
msg = f"Successfully edited {fp}"
if warning:
msg = f"{warning}\n{msg}"
return msg
return self._format_summary(fp, content, new_content, warning=warning)
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
except Exception as e:
+121 -50
View File
@@ -2,12 +2,14 @@
from __future__ import annotations
import difflib
import re
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
from rapidfuzz.distance import Indel, Opcode, Opcodes
TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"})
_MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024
_MAX_DIFF_LINES = 500
@@ -43,6 +45,108 @@ class FileEditTracker:
before: FileSnapshot
@dataclass(slots=True)
class FileDiff:
"""One line alignment shared by edit summaries and activity events."""
before_lines: list[str]
after_lines: list[str]
opcodes: Opcodes
added: int
deleted: int
@classmethod
def from_text(cls, before: str, after: str) -> FileDiff:
before_lines = before.replace("\r\n", "\n").splitlines()
after_lines = after.replace("\r\n", "\n").splitlines()
opcodes = Indel.opcodes(before_lines, after_lines)
added = deleted = 0
for code in opcodes:
if code.tag in ("replace", "delete"):
deleted += code.src_end - code.src_start
if code.tag in ("replace", "insert"):
added += code.dest_end - code.dest_start
return cls(before_lines, after_lines, opcodes, added, deleted)
def matches(self, before: str, after: str) -> bool:
"""Check that an observed file still has the compared line contents."""
return (
self.before_lines == before.replace("\r\n", "\n").splitlines()
and self.after_lines == after.replace("\r\n", "\n").splitlines()
)
def _groups(self, context: int) -> Iterator[list[Opcode]]:
codes = list(self.opcodes)
if not codes:
return
first, last = codes[0], codes[-1]
if first.tag == "equal":
codes[0] = Opcode(
"equal", max(first.src_start, first.src_end - context), first.src_end,
max(first.dest_start, first.dest_end - context), first.dest_end,
)
if last.tag == "equal":
last = codes[-1]
codes[-1] = Opcode(
"equal", last.src_start, min(last.src_end, last.src_start + context),
last.dest_start, min(last.dest_end, last.dest_start + context),
)
group: list[Opcode] = []
for code in codes:
tag = code.tag
i1, i2 = code.src_start, code.src_end
j1, j2 = code.dest_start, code.dest_end
if tag == "equal" and i2 - i1 > context * 2:
group.append(Opcode(tag, i1, i1 + context, j1, j1 + context))
yield group
group = []
i1, j1 = i2 - context, j2 - context
group.append(Opcode(tag, i1, i2, j1, j2))
if any(code.tag != "equal" for code in group):
yield group
def unified_lines(self, fromfile: str, tofile: str, context: int) -> Iterator[str]:
if not self.added and not self.deleted:
return
yield f"--- {fromfile}"
yield f"+++ {tofile}"
for group in self._groups(context):
first, last = group[0], group[-1]
old_count = last.src_end - first.src_start
new_count = last.dest_end - first.dest_start
old_range = _format_hunk_range(first.src_start + bool(old_count), old_count)
new_range = _format_hunk_range(first.dest_start + bool(new_count), new_count)
yield f"@@ -{old_range} +{new_range} @@"
for code in group:
if code.tag == "equal":
yield from (
" " + line for line in self.before_lines[code.src_start:code.src_end]
)
if code.tag in ("replace", "delete"):
yield from (
"-" + line for line in self.before_lines[code.src_start:code.src_end]
)
if code.tag in ("replace", "insert"):
yield from (
"+" + line for line in self.after_lines[code.dest_start:code.dest_end]
)
class FileEditResult(str):
"""Text observation carrying reusable diffs for the tool's activity hook."""
file_diffs: dict[Path, FileDiff]
def __new__(cls, content: str, file_diffs: dict[Path, FileDiff]) -> FileEditResult:
result = str.__new__(cls, content)
result.file_diffs = file_diffs
return result
def __reduce__(self) -> tuple[type[str], tuple[str]]:
# Transcript copies and persistence carry only the model observation.
return str, (str(self),)
def is_file_edit_tool(tool_name: str | None) -> bool:
return bool(tool_name) and tool_name in TRACKED_FILE_EDIT_TOOLS
@@ -79,21 +183,8 @@ def line_diff_stats(before: str | None, after: str | None) -> tuple[int, int]:
"""Return ``(added, deleted)`` for a UTF-8 text line-level diff."""
if before is None or after is None:
return 0, 0
if before == "":
return _text_line_count(after), 0
before_lines = before.replace("\r\n", "\n").splitlines()
after_lines = after.replace("\r\n", "\n").splitlines()
added = 0
deleted = 0
matcher = difflib.SequenceMatcher(a=before_lines, b=after_lines, autojunk=False)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
continue
if tag in ("replace", "delete"):
deleted += i2 - i1
if tag in ("replace", "insert"):
added += j2 - j1
return added, deleted
diff = FileDiff.from_text(before, after)
return diff.added, diff.deleted
def build_unified_diff_payload(
@@ -105,20 +196,14 @@ def build_unified_diff_payload(
context_lines: int = _DIFF_CONTEXT_LINES,
max_lines: int = _MAX_DIFF_LINES,
max_line_chars: int = _MAX_DIFF_LINE_CHARS,
diff: FileDiff | None = None,
) -> dict[str, Any] | None:
"""Return a compact standard unified diff for WebUI rendering."""
if before is None or after is None:
return None
before_lines = before.replace("\r\n", "\n").splitlines()
after_lines = after.replace("\r\n", "\n").splitlines()
diff_lines = list(difflib.unified_diff(
before_lines,
after_lines,
fromfile=fromfile,
tofile=tofile,
n=max(0, int(context_lines)),
lineterm="",
))
if diff is None:
diff = FileDiff.from_text(before, after)
diff_lines = list(diff.unified_lines(fromfile, tofile, max(0, int(context_lines))))
if not diff_lines:
return None
@@ -252,28 +337,6 @@ def _format_hunk_range(start: int, line_count: int) -> str:
return str(start) if line_count == 1 else f"{start},{line_count}"
def _text_line_count(text: str) -> int:
if not text:
return 0
line_count = 0
last_was_newline = False
last_was_cr = False
for ch in text:
if ch == "\r":
line_count += 1
last_was_newline = True
last_was_cr = True
elif ch == "\n":
if not last_was_cr:
line_count += 1
last_was_newline = True
last_was_cr = False
else:
last_was_newline = False
last_was_cr = False
return line_count if last_was_newline else line_count + 1
def prepare_file_edit_trackers(
*,
call_id: str,
@@ -411,16 +474,24 @@ def build_file_edit_start_event(
def build_file_edit_end_event(
tracker: FileEditTracker,
params: dict[str, Any] | None = None,
*,
diff: FileDiff | None = None,
) -> dict[str, Any]:
after = read_file_snapshot(tracker.path)
diff_payload: dict[str, Any] | None = None
if tracker.before.countable and after.countable:
added, deleted = line_diff_stats(tracker.before.text, after.text)
if (
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):
diff = FileDiff.from_text(tracker.before.text, after.text)
added, deleted = diff.added, diff.deleted
diff_payload = build_unified_diff_payload(
tracker.before.text,
after.text,
fromfile=tracker.display_path,
tofile=tracker.display_path,
diff=diff,
)
binary = False
else:
+1
View File
@@ -48,6 +48,7 @@ dependencies = [
"tiktoken>=0.12.0,<1.0.0",
"jinja2>=3.1.0,<4.0.0",
"dulwich>=0.22.0,<1.0.0",
"rapidfuzz>=3.14.6,<4.0.0",
"pyyaml>=6.0,<7.0.0",
"filelock>=3.25.2",
"watchfiles>=1.1.1,<2.0.0",
+1 -1
View File
@@ -245,7 +245,7 @@ class TestDreamTools:
)
assert "Patch applied" in memory_result
assert "Successfully edited" in soul_result
assert "Patch applied" in soul_result
assert "Successfully wrote" in user_result
assert "Project Y active" in store.memory_file.read_text(encoding="utf-8")
assert "Precise" in store.soul_file.read_text(encoding="utf-8")
+29 -10
View File
@@ -9,9 +9,11 @@ from agent.runner_helpers import make_run_spec
from nanobot.agent.hooks import FileEditActivityHook
from nanobot.agent.progress_hook import AgentProgressHook
from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.agent.tools.filesystem import EditFileTool, WriteFileTool
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.utils.file_edit_events import Indel
from nanobot.utils.progress_events import output_events
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -167,7 +169,7 @@ async def test_runner_fails_pending_hosted_tool_when_model_request_fails():
@pytest.mark.asyncio
async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_path):
async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_path, monkeypatch):
provider = MagicMock()
call_count = 0
progress_events: list[dict] = []
@@ -178,6 +180,8 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pa
progress_events.extend(file_edit_events)
tool = WriteFileTool(workspace=tmp_path)
align = MagicMock(wraps=Indel.opcodes)
monkeypatch.setattr(Indel, "opcodes", align)
class Tools:
def get_definitions(self):
@@ -218,6 +222,7 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pa
))
assert result.final_content == "done"
assert align.call_count == 1
assert progress_events[0]["phase"] == "start"
assert progress_events[0]["added"] == 0
assert progress_events[0]["deleted"] == 0
@@ -232,7 +237,8 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pa
@pytest.mark.asyncio
async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_path):
@pytest.mark.parametrize("tool_name", ["edit_file", "apply_patch"])
async def test_runner_reuses_edit_diff_for_summary_and_progress(tmp_path, monkeypatch, tool_name):
provider = MagicMock()
call_count = 0
progress_events: list[dict] = []
@@ -244,10 +250,23 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_pat
progress_events.extend(file_edit_events)
tool = EditFileTool(workspace=tmp_path)
arguments = {
"path": str(target),
"old_text": "old\nkeep\n",
"new_text": "new\nkeep\nextra\n",
}
if tool_name == "apply_patch":
tool = ApplyPatchTool(workspace=tmp_path)
arguments = {"edits": [
{"path": str(target), "action": "replace", "old_text": "old", "new_text": "new"},
{"path": str(target), "action": "add", "new_text": "extra"},
]}
align = MagicMock(wraps=Indel.opcodes)
monkeypatch.setattr(Indel, "opcodes", align)
class Tools:
def get_definitions(self):
return [{"type": "function", "function": {"name": "edit_file"}}]
return [{"type": "function", "function": {"name": tool_name}}]
def prepare_call(self, name, params):
return tool, params, None
@@ -261,12 +280,8 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_pat
tool_calls=[
ToolCallRequest(
id="call-edit",
name="edit_file",
arguments={
"path": "notes.txt",
"old_text": "old\nkeep\n",
"new_text": "new\nkeep\nextra\n",
},
name=tool_name,
arguments=arguments,
)
],
usage=None,
@@ -288,8 +303,12 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_pat
))
assert result.final_content == "done"
assert align.call_count == 1
assert target.read_text() == "new\nkeep\nextra\n"
observation = next(m["content"] for m in result.messages if m["role"] == "tool")
assert observation == "Patch applied:\n- update notes.txt (+2/-1)"
assert any(
event["tool"] == "edit_file"
event["tool"] == tool_name
and not event["approximate"]
and event["phase"] == "end"
and event["added"] == 2
+13 -13
View File
@@ -46,7 +46,7 @@ class TestDeleteLineCleanup:
content = f"{prefix}{indent}line2\nline3\n"
f.write_bytes(content.replace("\n", newline).encode("utf-8"))
result = await tool.execute(path=str(f), old_text=f"{indent}line2", new_text="")
assert "Successfully" in result
assert "Patch applied:" in result
# Should not leave a blank line where line2 was
assert f.read_bytes() == f"{prefix}line3\n".replace("\n", newline).encode("utf-8")
@@ -61,7 +61,7 @@ class TestDeleteLineCleanup:
content = f"{prefix}x = 1{old_text}\ny = 2\n"
f.write_bytes(content.replace("\n", newline).encode("utf-8"))
result = await tool.execute(path=str(f), old_text=old_text, new_text="")
assert "Successfully" in result
assert "Patch applied:" in result
expected = f"{prefix}x = 1\ny = 2\n"
assert f.read_bytes() == expected.replace("\n", newline).encode("utf-8")
@@ -76,7 +76,7 @@ class TestDeleteLineCleanup:
result = await tool.execute(
path=str(f), old_text=" # obsolete", new_text="", replace_all=True,
)
assert "Successfully" in result
assert "Patch applied:" in result
expected = "x = 1\ny = 2\nz = 3\n"
assert f.read_bytes() == expected.replace("\n", newline).encode("utf-8")
@@ -85,7 +85,7 @@ class TestDeleteLineCleanup:
f = tmp_path / "a.py"
f.write_text("line1\nline2\nline3\n", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="line2\n", new_text="")
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text() == "line1\nline3\n"
@pytest.mark.asyncio
@@ -94,7 +94,7 @@ class TestDeleteLineCleanup:
f = tmp_path / "a.py"
f.write_text("hello world here\n", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="world ", new_text="")
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text() == "hello here\n"
@@ -119,7 +119,7 @@ class TestQuoteStylePreservation:
old_text='message = "hello"',
new_text='message = "goodbye"',
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text(encoding="utf-8") == 'message = “goodbye”\n'
@pytest.mark.asyncio
@@ -131,7 +131,7 @@ class TestQuoteStylePreservation:
old_text="it's fine",
new_text="it's better",
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text(encoding="utf-8") == "it’s better\n"
@@ -161,7 +161,7 @@ class TestIndentationPreservation:
old_text="def foo():\n pass",
new_text="def bar():\n return 1",
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text(encoding="utf-8") == (
"if True:\n"
" def bar():\n"
@@ -238,7 +238,7 @@ class TestAdvancedReplaceAll:
new_text="def bar():\n return 1",
replace_all=True,
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text(encoding="utf-8") == (
"if a:\n"
" def bar():\n"
@@ -257,7 +257,7 @@ class TestAdvancedReplaceAll:
old_text='message = "hello"',
new_text='message = "goodbye"',
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text(encoding="utf-8") == " message = “goodbye”\n"
@@ -280,7 +280,7 @@ class TestTrailingWhitespaceStrip:
result = await tool.execute(
path=str(f), old_text="x = 1", new_text="x = 2 \ny = 3 ",
)
assert "Successfully" in result
assert "Patch applied:" in result
content = f.read_text()
assert "x = 2\ny = 3\n" == content
@@ -292,7 +292,7 @@ class TestTrailingWhitespaceStrip:
result = await tool.execute(
path=str(f), old_text="# Title", new_text="# Title \nSubtitle ",
)
assert "Successfully" in result
assert "Patch applied:" in result
content = f.read_text()
# Trailing spaces should be preserved for markdown
assert "Title " in content
@@ -361,6 +361,6 @@ class TestStaleDetectionContentFallback:
os.utime(f, (stat.st_atime, stat.st_mtime + 10))
result = await edit_tool.execute(path=str(f), old_text="world", new_text="earth")
assert "Successfully" in result
assert "Patch applied:" in result
# Should NOT warn about modification since content is the same
assert "modified" not in result.lower()
+40 -14
View File
@@ -1,9 +1,12 @@
"""Tests for EditFileTool enhancements: read-before-edit tracking, path suggestions,
notebook JSON editing, and create-file semantics."""
import os
import pytest
from nanobot.agent.tools import file_state
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool
# ---------------------------------------------------------------------------
@@ -23,7 +26,7 @@ def _clear_file_state():
# ---------------------------------------------------------------------------
class TestEditReadTracking:
"""edit_file should warn when file hasn't been read first."""
"""edit_file warns only when a recorded file version has changed."""
@pytest.fixture()
def file_states(self):
@@ -38,13 +41,12 @@ class TestEditReadTracking:
return EditFileTool(workspace=tmp_path, file_states=file_states)
@pytest.mark.asyncio
async def test_edit_warns_if_file_not_read_first(self, edit_tool, tmp_path):
async def test_edit_does_not_warn_without_read_record(self, edit_tool, tmp_path):
f = tmp_path / "a.py"
f.write_text("hello world", encoding="utf-8")
result = await edit_tool.execute(path=str(f), old_text="world", new_text="earth")
# Should still succeed but include a warning
assert "Successfully" in result
assert "not been read" in result.lower() or "warning" in result.lower()
assert result == "Patch applied:\n- update a.py (+1/-1)"
assert f.read_text() == "hello earth"
@pytest.mark.asyncio
async def test_edit_succeeds_cleanly_after_read(self, read_tool, edit_tool, tmp_path):
@@ -52,21 +54,30 @@ class TestEditReadTracking:
f.write_text("hello world", encoding="utf-8")
await read_tool.execute(path=str(f))
result = await edit_tool.execute(path=str(f), old_text="world", new_text="earth")
assert "Successfully" in result
# No warning when file was read first
assert "not been read" not in result.lower()
assert result == "Patch applied:\n- update a.py (+1/-1)"
assert f.read_text() == "hello earth"
@pytest.mark.asyncio
async def test_edit_warns_if_file_modified_since_read(self, read_tool, edit_tool, tmp_path):
@pytest.mark.parametrize("reread", [False, True])
async def test_edit_after_file_modified_since_read(
self, read_tool, edit_tool, tmp_path, reread,
):
f = tmp_path / "a.py"
f.write_text("hello world", encoding="utf-8")
await read_tool.execute(path=str(f))
# External modification
mtime = f.stat().st_mtime
f.write_text("hello universe", encoding="utf-8")
os.utime(f, (mtime + 2, mtime + 2))
if reread:
assert "hello universe" in await read_tool.execute(path=str(f))
result = await edit_tool.execute(path=str(f), old_text="universe", new_text="earth")
assert "Successfully" in result
assert "modified" in result.lower() or "warning" in result.lower()
summary = "Patch applied:\n- update a.py (+1/-1)"
assert result == (
summary if reread
else "Warning: file was modified since the last recorded read or write.\n" + summary
)
assert f.read_text() == "hello earth"
# ---------------------------------------------------------------------------
@@ -84,7 +95,7 @@ class TestEditCreateFile:
async def test_create_new_file_with_empty_old_text(self, tool, tmp_path):
f = tmp_path / "subdir" / "new.py"
result = await tool.execute(path=str(f), old_text="", new_text="print('hi')")
assert "created" in result.lower() or "Successfully" in result
assert result == "Patch applied:\n- add subdir/new.py (+1/-0)"
assert f.exists()
assert f.read_text() == "print('hi')"
@@ -102,7 +113,7 @@ class TestEditCreateFile:
f = tmp_path / "empty.py"
f.write_text("", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="", new_text="print('hi')")
assert "Successfully" in result
assert result == "Patch applied:\n- update empty.py (+1/-0)"
assert f.read_text() == "print('hi')"
@@ -126,7 +137,7 @@ class TestEditIpynbFiles:
old_text='"cells": []',
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
)
assert "Successfully edited" in result
assert "Patch applied:" in result
assert '"source": "hi"' in f.read_text(encoding="utf-8")
@@ -158,3 +169,18 @@ class TestEditPathSuggestion:
path=str(tmp_path / "nonexistent.py"), old_text="a", new_text="b",
)
assert "Error" in result
async def test_edit_summary_matches_apply_patch(tmp_path):
states = file_state.FileStates()
target = tmp_path / "config.toml"
target.write_bytes(b"a = 1\n")
edited = await EditFileTool(workspace=tmp_path, file_states=states).execute(
path="config.toml", old_text="1", new_text="2",
)
target.write_bytes(b"a = 1\n")
patched = await ApplyPatchTool(workspace=tmp_path, file_states=states).execute(
edits=[{"path": "config.toml", "action": "replace", "old_text": "1", "new_text": "2"}],
)
assert patched == "Patch applied:\n- update config.toml (+1/-1)"
assert edited == patched
@@ -32,7 +32,7 @@ def test_edit_file_can_select_occurrence(tmp_path):
occurrence=2,
))
assert "Successfully edited" in result
assert "Patch applied:" in result
assert target.read_text() == "one\nsame\ntwo\nchanged\n"
@@ -66,7 +66,7 @@ def test_edit_file_expected_replacements_allows_replace_all_when_count_matches(t
expected_replacements=2,
))
assert "Successfully edited" in result
assert "Patch applied:" in result
assert target.read_text() == "changed\nchanged\n"
@@ -82,7 +82,7 @@ def test_edit_file_line_hint_selects_matching_occurrence(tmp_path):
line_hint=4,
))
assert "Successfully edited" in result
assert "Patch applied:" in result
assert target.read_text() == "one\nsame\ntwo\nchanged\n"
@@ -115,7 +115,7 @@ def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):
line_hint=3,
))
assert "Successfully edited" in result
assert "Patch applied:" in result
assert target.read_text() == "before\nstart\nchanged\nend\nafter\n"
@@ -130,7 +130,7 @@ def test_edit_file_can_edit_ipynb_as_json(tmp_path):
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
))
assert "Successfully edited" in result
assert "Patch applied:" in result
assert '"source": "hi"' in target.read_text()
+5 -5
View File
@@ -130,7 +130,7 @@ class TestEditFileTool:
f = tmp_path / "a.py"
f.write_text("hello world", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="world", new_text="earth")
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text() == "hello earth"
@pytest.mark.asyncio
@@ -150,7 +150,7 @@ class TestEditFileTool:
result = await tool.execute(
path=str(f), old_text="line1\nline2", new_text="LINE1\nLINE2",
)
assert "Successfully" in result
assert "Patch applied:" in result
raw = f.read_bytes()
assert b"LINE1" in raw
# CRLF line endings should be preserved throughout the file
@@ -163,7 +163,7 @@ class TestEditFileTool:
result = await tool.execute(
path=str(f), old_text="def foo():\n pass", new_text="def bar():\n return 1",
)
assert "Successfully" in result
assert "Patch applied:" in result
assert "bar" in f.read_text()
@pytest.mark.asyncio
@@ -180,7 +180,7 @@ class TestEditFileTool:
result = await tool.execute(
path=str(f), old_text="foo", new_text="baz", replace_all=True,
)
assert "Successfully" in result
assert "Patch applied:" in result
assert f.read_text() == "baz bar baz bar baz"
@pytest.mark.asyncio
@@ -476,5 +476,5 @@ class TestWorkspaceRestriction:
old_text="before",
new_text="after",
)
assert "Successfully edited" in result
assert "Patch applied:" in result
assert target.read_text(encoding="utf-8") == "after\n"
+81
View File
@@ -1,10 +1,16 @@
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
import pytest
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.agent.tools.filesystem import EditFileTool, WriteFileTool
from nanobot.utils.file_edit_events import (
FileDiff,
FileEditResult,
build_file_edit_end_event,
build_file_edit_start_event,
build_unified_diff_payload,
@@ -39,6 +45,81 @@ def test_line_diff_stats_counts_new_file_crlf_lines_once() -> None:
assert line_diff_stats("", "a\r\nb\r\n") == (2, 0)
@pytest.mark.parametrize("position", [0, 3000, 6000])
@pytest.mark.parametrize(
("before_text", "after_text", "expected"),
[("old\n", "new\n", (1, 1)), ("", "new\n", (1, 0)), ("old\n", "", (0, 1))],
)
def test_line_diff_stats_small_edit_in_repeated_lines(
position: int, before_text: str, after_text: str, expected: tuple[int, int],
) -> None:
prefix = "same\n" * position
suffix = "same\n" * (6000 - position)
assert line_diff_stats(prefix + before_text + suffix, prefix + after_text + suffix) == expected
def test_sparse_edits_in_repeated_lines_have_compact_diff() -> None:
middle = "same,0\n" * 6000
before = "obsolete,1\n" + middle + "obsolete,2\n"
after = "current,1\n" + middle + "current,2\n"
assert line_diff_stats(before, after) == (2, 2)
payload = build_unified_diff_payload(before, after)
assert payload is not None and not payload["truncated"]
body = payload["text"].splitlines()[2:]
assert sum(line.startswith("@@") for line in body) == 2
assert sum(line.startswith("+") for line in body) == 2
assert sum(line.startswith("-") for line in body) == 2
assert body.count(" same,0") == 6
@pytest.mark.parametrize(("before", "after", "expected"), [
("", "new\n", "@@ -0,0 +1 @@\n+new"),
("old\n", "", "@@ -1 +0,0 @@\n-old"),
("keep\n", "keep\nnew\n", "@@ -1,0 +2 @@\n+new"),
("keep\nold\n", "keep\n", "@@ -2 +1,0 @@\n-old"),
])
def test_unified_diff_empty_ranges(before: str, after: str, expected: str) -> None:
payload = build_unified_diff_payload(before, after, context_lines=0)
assert payload is not None
assert payload["text"] == "--- before\n+++ after\n" + expected
@pytest.mark.parametrize("gap", [0, 5, 6, 7])
def test_unified_diff_groups_changes_by_context(gap: int) -> None:
middle = "".join(f"keep {i}\n" for i in range(gap))
payload = build_unified_diff_payload("old\n" + middle + "old\n", "new\n" + middle + "new\n")
assert payload is not None
assert payload["text"].count("@@ -") == (2 if gap > 6 else 1)
def test_file_edit_result_copies_and_serializes_only_observation(tmp_path: Path) -> None:
result = FileEditResult("Patch applied", {tmp_path: FileDiff.from_text("old", "new")})
assert type(deepcopy(result)) is str
assert json.loads(json.dumps({"content": result})) == {"content": "Patch applied"}
assert result.file_diffs
@pytest.mark.asyncio
@pytest.mark.parametrize("changed_state", ["before", "after"])
async def test_activity_recomputes_diff_when_snapshots_changed(tmp_path: Path, changed_state: str) -> None:
target = tmp_path / "notes.txt"
target.write_text("old\n", encoding="utf-8")
tool = _edit_tool(tmp_path)
params = {"path": "notes.txt", "old_text": "old", "new_text": "new"}
[tracker] = prepare_file_edit_trackers(
call_id="call-edit", tool_name="edit_file", tool=tool, workspace=tmp_path, params=params,
)
if changed_state == "before":
target.write_text("old\nexternal\n", encoding="utf-8")
result = await tool.execute(**params)
assert isinstance(result, FileEditResult)
if changed_state == "after":
target.write_text("new\nexternal\n", encoding="utf-8")
event = build_file_edit_end_event(tracker, diff=result.file_diffs[target.resolve()])
assert (event["added"], event["deleted"]) == (2, 1)
assert "+external" in event["diff"]["text"]
def test_write_file_start_tracks_snapshot_and_end_emits_exact_diff(tmp_path: Path) -> None:
target = tmp_path / "notes.txt"
target.write_text("old\nkeep\n", encoding="utf-8")