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:
1 parent
3a725b35a7
commit
1c3c68262f
13 files changed
+346
-170
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user