Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(agent-core): report edit's rewritten lines and ambiguous-match locations (#2427)

Call Whitedeb05c3993a6
diff --git a/core/agent_core/agent/scratch.py b/core/agent_core/agent/scratch.py
index 2115bf3ef..73119e0f1 100644
--- a/core/agent_core/agent/scratch.py
+++ b/core/agent_core/agent/scratch.py
@@ -99,7 +99,9 @@ class ScratchRoot:
return error_result(f"Could not edit file: {path}. It is not a regular file.")
if len(raw) > MAX_EDIT_BYTES:
return error_result(f"File {path} is over the edit limit. Write it again instead.")
- new_text, _, _, counts = apply_edits(decode_file(raw), edits, path, max_result_chars=MAX_EDIT_BYTES)
+ new_text, _, _, counts, changed = apply_edits(
+ decode_file(raw), edits, path, max_result_chars=MAX_EDIT_BYTES
+ )
self._publish(name, encode_file(new_text), expected=identity)
except EditError as exc:
return error_result(str(exc))
@@ -109,7 +111,7 @@ class ScratchRoot:
return error_result(f"Could not edit file: {path}. It changed while the edit was being applied; read it again.")
except OSError as exc:
return error_result(f"Could not edit file: {path}. {os.strerror(exc.errno) if exc.errno else exc}.")
- return text_result(edit_summary(path, edits, counts))
+ return text_result(edit_summary(path, edits, counts, changed))
# --- descriptor-relative steps ------------------------------------------------------------
diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.py
index ff0bc8fe8..d1d6dc0e2 100644
--- a/core/agent_core/tools/edit.py
+++ b/core/agent_core/tools/edit.py
@@ -3,7 +3,10 @@
Ported from Pi ``packages/coding-agent/src/core/tools/edit.ts`` (MIT, Copyright
(c) 2025 Mario Zechner); the description and model-facing strings are Pi's.
``replaceAll`` is an Avibe addition, so its schema text and the "unless
-replaceAll is true" clause are Avibe's.
+replaceAll is true" clause are Avibe's. Avibe improvements to Pi's result
+texts: a successful edit names the lines it rewrote, and an ambiguous match
+lists its first occurrences (``edit_diff``), so the model can inspect the result
+or add context without another read; Pi reports only counts.
"""
from __future__ import annotations
@@ -15,7 +18,14 @@ from typing import Any, Mapping
from core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_result
from core.agent_core.tools.base import ToolContext, ToolResult, ToolSpec
-from core.agent_core.tools.edit_diff import Edit, EditError, ResultTooLarge, apply_edits, display_diff
+from core.agent_core.tools.edit_diff import (
+ MAX_LOCATIONS,
+ Edit,
+ EditError,
+ ResultTooLarge,
+ apply_edits,
+ display_diff,
+)
from core.agent_core.tools.paths import (
NotRegularFile,
errno_name,
@@ -127,15 +137,29 @@ def _edits_arg(arguments: Mapping[str, Any]) -> list[Edit]:
return parsed
-def edit_summary(path: str, edits: list[Edit], counts: tuple[int, ...]) -> str:
- """Pi's result line, or, when an item used ``replaceAll`` (Avibe), the occurrences each item replaced."""
+def _line_ranges(changed: tuple[tuple[int, int], ...]) -> str:
+ """``lines 40-52, 88-90`` (``line 7`` for one line), the first ``MAX_LOCATIONS`` ranges then how many more."""
+ shown = [str(first) if first == last else f"{first}-{last}" for first, last in changed[:MAX_LOCATIONS]]
+ if len(changed) > MAX_LOCATIONS:
+ shown.append(f"...and {len(changed) - MAX_LOCATIONS} more")
+ single = len(changed) == 1 and changed[0][0] == changed[0][1]
+ return f"{'line' if single else 'lines'} {', '.join(shown)}"
+
+
+def edit_summary(
+ path: str, edits: list[Edit], counts: tuple[int, ...], changed: tuple[tuple[int, int], ...]
+) -> str:
+ """Pi's result line, or, when an item used ``replaceAll`` (Avibe), the occurrences each item replaced.
+
+ Avibe adds the new file's rewritten lines, so the model can read just those to check the result.
+ """
if not any(edit.replace_all for edit in edits):
- return f"Successfully replaced {len(edits)} block(s) in {path}."
+ return f"Successfully replaced {len(edits)} block(s) in {path} ({_line_ranges(changed)})."
total = sum(counts)
- summary = f"Successfully replaced {total} occurrence{'' if total == 1 else 's'} in {path}"
+ summary = f"Successfully replaced {total} occurrence{'' if total == 1 else 's'} in {path} ({_line_ranges(changed)}"
if len(counts) > 1:
- summary += " (" + ", ".join(f"edits[{index}]: {count}" for index, count in enumerate(counts)) + ")"
- return summary + "."
+ summary += "; " + ", ".join(f"edits[{index}]: {count}" for index, count in enumerate(counts))
+ return summary + ")."
class _TooLarge(Exception):
@@ -157,8 +181,8 @@ def _line_count(text: str) -> int:
def _plan_edits(
absolute: str, edits: list[Edit], path: str
-) -> tuple[int, bytes, str, str, FileIdentity, tuple[int, ...]]:
- """Read the file and compute its new bytes: ``(size, data, view_before, view_after, identity, counts)``.
+) -> tuple[int, bytes, str, str, FileIdentity, tuple[int, ...], tuple[tuple[int, int], ...]]:
+ """Read the file and compute its new bytes: ``(size, data, view_before, view_after, identity, counts, changed)``.
One descriptor gives the size and the contents, read up to the limit, so a file that grew after an
earlier check by path cannot get past it. ``surrogateescape`` carries bytes that are not UTF-8
@@ -181,8 +205,8 @@ def _plan_edits(
lines = _line_count(text)
if lines > MAX_EDIT_LINES:
raise _TooManyLines(lines)
- new_text, before, after, counts = apply_edits(text, edits, path, max_result_chars=MAX_EDIT_BYTES)
- return len(raw), encode_file(new_text), before, after, FileIdentity.of(real, st), counts
+ new_text, before, after, counts, changed = apply_edits(text, edits, path, max_result_chars=MAX_EDIT_BYTES)
+ return len(raw), encode_file(new_text), before, after, FileIdentity.of(real, st), counts, changed
class EditTool:
@@ -217,7 +241,7 @@ class EditTool:
if not os.access(absolute, os.R_OK | os.W_OK):
return error_result(f"Could not edit file: {path}. Error code: EACCES.")
try:
- size, data, base, new_content, identity, counts = await to_thread_joined(
+ size, data, base, new_content, identity, counts, changed = await to_thread_joined(
_plan_edits, absolute, edits, path
)
if len(data) > MAX_EDIT_BYTES:
@@ -258,7 +282,7 @@ class EditTool:
except OSError as exc:
return error_result(f"Could not edit file: {path}. Error code: {errno_name(exc)}.")
- result = edit_summary(path, edits, counts)
+ result = edit_summary(path, edits, counts, changed)
if max(size, len(data)) > MAX_DIFF_BYTES:
# The diff is for display only, and difflib is superlinear on large inputs.
return text_result(result, details={"diff_skipped": True})
diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.py
index 7ed96e8d8..997446024 100644
--- a/core/agent_core/tools/edit_diff.py
+++ b/core/agent_core/tools/edit_diff.py
@@ -10,6 +10,9 @@ tier, so one normalized edit no longer switches the whole batch to normalized
text; uniqueness is counted in the tier that matched; and the file is never
re-encoded: replacements are spliced into the original text, so its BOM, its
line breaks (mixed or not), and every byte outside a replaced span survive.
+Avibe additions to Pi's messages: an ambiguous match lists where its first
+occurrences are, and a successful edit reports the lines it rewrote, so the
+model need not read the file again to disambiguate or to inspect the result.
"""
from __future__ import annotations
@@ -111,6 +114,10 @@ _ASCII = re.compile("[\x00-\x7f]")
#: Avibe: every edit scans the whole file (``str.count``/``find``, which hold the GIL), so the number of
#: edits times the file's length is bounded: about a quarter second of scanning.
MAX_EDIT_SCAN_CHARS = 256 * 1024 * 1024
+#: Avibe: occurrences an ambiguous match lists, and rewritten line ranges a result lists, before "...and N more".
+MAX_LOCATIONS = 5
+#: Avibe: characters of a long line an occurrence's excerpt shows.
+EXCERPT_CHARS = 100
class ResultTooLarge(Exception):
@@ -162,15 +169,19 @@ def _not_found(path: str, index: int, total: int, *, loose_unavailable: bool = F
)
-def _duplicate(path: str, index: int, total: int, occurrences: int) -> EditError:
+def _duplicate(path: str, index: int, total: int, occurrences: int, locations: list[str]) -> EditError:
+ # Avibe addition: where the first occurrences are, so the model can add context without reading the file.
+ shown_locations = "\n".join(locations)
+ if occurrences > len(locations):
+ shown_locations += f"\n...and {occurrences - len(locations)} more"
if total == 1:
return EditError(
f"Found {occurrences} occurrences of the text in {path}. The text must be unique. Please provide more "
- "context to make it unique."
+ f"context to make it unique. Occurrences:\n{shown_locations}"
)
return EditError(
f"Found {occurrences} occurrences of edits[{index}] in {path}. Each oldText must be unique. Please provide "
- "more context to make it unique."
+ f"more context to make it unique. Occurrences:\n{shown_locations}"
)
@@ -273,6 +284,10 @@ class _Lines:
view_pos += len(content) + 1
pos += len(content) + len(brk)
+ def read_line(self, line: int) -> int:
+ """The number ``read`` shows for ``line``: read breaks lines only at ``\\n``, not at a lone ``\\r``."""
+ return self.text.count("\n", 0, self.starts[line]) + 1
+
def to_original(self, view_offset: int) -> int:
line = bisect.bisect_right(self.view_starts, view_offset) - 1
return self.starts[line] + (view_offset - self.view_starts[line])
@@ -308,6 +323,121 @@ class _Lines:
return "".join(out)
+def _excerpt(line: str, column: int) -> str:
+ """``line`` without its indentation; a long line only around ``column``."""
+ if len(line) <= EXCERPT_CHARS:
+ return line.strip()
+ start = max(0, min(column - EXCERPT_CHARS // 4, len(line) - EXCERPT_CHARS))
+ end = start + EXCERPT_CHARS
+ return ("..." if start else "") + line[start:end].strip() + ("..." if end < len(line) else "")
+
+
+def _original_column(line: str, column: int) -> int:
+ """The column of ``line`` where its normalized form reaches ``column``.
+
+ Only NFKC changes lengths (the substitutions after it are one character for one, and trailing
+ whitespace is stripped after any occurrence). The line is measured in pieces ending just before an
+ ASCII character, as ``_bounded_fuzzy_view`` normalizes it; a piece already in NFKC maps one for
+ one, and the piece that changes length across ``column`` is bisected. ``_bounded_fuzzy_view``
+ gave up on any longer run that is not in NFKC, so a bisected piece stays bounded.
+ """
+ pos = reached = 0
+ while pos < len(line):
+ boundary = _ASCII.search(line, pos + _NFKC_CHUNK_CHARS)
+ end = boundary.start() if boundary else len(line)
+ piece = line[pos:end]
+ if unicodedata.is_normalized("NFKC", piece):
+ if reached + len(piece) > column:
+ return pos + column - reached
+ reached += len(piece)
+ else:
+ grown = len(unicodedata.normalize("NFKC", piece))
+ if reached + grown > column:
+ lo, hi = 0, len(piece)
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if len(unicodedata.normalize("NFKC", piece[:mid])) <= column - reached:
+ lo = mid
+ else:
+ hi = mid - 1
+ return pos + lo
+ reached += grown
+ pos = end
+ return len(line)
+
+
+def _locations(lines: _Lines, haystack: str, needle: str, normalized: bool) -> list[str]:
+ """``line {n}: {excerpt}`` for the first ``MAX_LOCATIONS`` occurrences of ``needle`` in ``haystack``.
+
+ ``haystack`` is the view or, when ``normalized``, its normalized form, which keeps every line break,
+ so its line ``i`` is the view's line ``i``; the excerpt is that line of the view, as read showed it.
+ """
+ out = []
+ for at in _find_all(haystack, needle, MAX_LOCATIONS):
+ line = haystack.count("\n", 0, at)
+ column = at - (haystack.rfind("\n", 0, at) + 1)
+ start = lines.view_starts[line]
+ text = lines.view[start : start + len(lines.contents[line])]
+ if normalized and len(text) > EXCERPT_CHARS:
+ # A column of the normalized form; NFKC may have changed lengths earlier on the line.
+ column = _original_column(text, column)
+ out.append(f"line {lines.read_line(line)}: {_excerpt(text, column)}")
+ return out
+
+
+def _common_prefix(a: str, b: str, limit: int) -> int:
+ """How many leading characters, up to ``limit``, ``a`` and ``b`` share; bisected over slice
+ comparisons, so a long shared run costs a few memcmp calls rather than a loop per character."""
+ lo, hi = 0, limit
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if a[:mid] == b[:mid]:
+ lo = mid
+ else:
+ hi = mid - 1
+ return lo
+
+
+def _common_suffix(a: str, b: str, limit: int) -> int:
+ """How many trailing characters, up to ``limit``, ``a`` and ``b`` share."""
+ lo, hi = 0, limit
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if a[len(a) - mid :] == b[len(b) - mid :]:
+ lo = mid
+ else:
+ hi = mid - 1
+ return lo
+
+
+def _changed_lines(text: str, replacements: list[_Replacement]) -> tuple[tuple[int, int], ...]:
+ """The new file's rewritten line ranges, numbered as ``read`` shows them; touching ranges merge.
+
+ A replacement counts from its first to its last character that differs from the text it replaced,
+ so unchanged context at either end of an edit, or a replacement that changed nothing, is not
+ reported. This says where to look, not a line diff: an unchanged line between two changes of one
+ edit is part of its range.
+ """
+ ranges: list[tuple[int, int]] = []
+ line, pos = 1, 0
+ for replacement in sorted(replacements, key=lambda r: r.index):
+ line += text.count("\n", pos, replacement.index)
+ old, new = text[replacement.index : replacement.index + replacement.length], replacement.new_text
+ if old != new:
+ head = _common_prefix(old, new, min(len(old), len(new)))
+ tail = _common_suffix(old, new, min(len(old), len(new)) - head)
+ first = line + new.count("\n", 0, head)
+ # The last differing character's line; a removal marks the line it was removed from.
+ last = line + new.count("\n", 0, len(new) - tail - 1) if len(new) - tail > head else first
+ if ranges and first <= ranges[-1][1] + 1:
+ ranges[-1] = (ranges[-1][0], max(ranges[-1][1], last))
+ else:
+ ranges.append((first, last))
+ line += new.count("\n")
+ pos = replacement.index + replacement.length
+ return tuple(ranges)
+
+
def _exact_replacements(lines: _Lines, matches: list[_Replacement]) -> list[_Replacement]:
out = []
for match in matches:
@@ -353,9 +483,9 @@ def _line_groups(lines: _Lines, normalized: str, matches: list[_Replacement]) ->
def apply_edits(
text: str, edits: list[Edit], path: str, max_result_chars: Optional[int] = None
-) -> tuple[str, str, str, tuple[int, ...]]:
- """Apply every edit to the file's ``text``; return the new text, the LF views before and after, and
- how many occurrences each edit replaced.
+) -> tuple[str, str, str, tuple[int, ...], tuple[tuple[int, int], ...]]:
+ """Apply every edit to the file's ``text``; return the new text, the LF views before and after, how
+ many occurrences each edit replaced, and the new text's rewritten line ranges (``read``'s numbers).
Each edit matches in its own tier against the original, in the file's LF view. Exact edits replace
exactly the text they matched; a normalized edit rewrites the whole lines it touches from the
@@ -391,7 +521,7 @@ def apply_edits(
if not count:
raise _not_found(path, index, total, loose_unavailable=bool(cache) and cache[0] is None)
if not edit.replace_all and count > 1:
- raise _duplicate(path, index, total, count)
+ raise _duplicate(path, index, total, count, _locations(lines, haystack, needle, used_normalized))
replacements_made += count
counts.append(count)
if replacements_made > MAX_REPLACEMENTS:
@@ -410,7 +540,7 @@ def apply_edits(
new_text = _apply(text, replacements)
if new_text == text:
raise _no_change(path, total)
- return new_text, lines.view, lf_view(new_text), tuple(counts)
+ return new_text, lines.view, lf_view(new_text), tuple(counts), _changed_lines(text, replacements)
def lf_view(text: str) -> str:
diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.md
index def3fdf17..320dbf92b 100644
--- a/docs/plans/agent-core-contracts/tools.md
+++ b/docs/plans/agent-core-contracts/tools.md
@@ -113,15 +113,25 @@ is true". Logic, from Pi's `edit-diff.ts`:
4. Apply all edits against the original, restore line endings and BOM, write once. Nothing is written if any edit
fails.
-Result: `Successfully replaced {n} block(s) in {path}.`; the diff goes to `details` for display only. Avibe: when an
-item uses `replaceAll`, the result counts occurrences instead, `Successfully replaced {total} occurrences in {path}.`
-(`1 occurrence` when singular), followed for several items by ` (edits[0]: {count}, edits[1]: {count})` before the
-period, so the model need not read the file again to count them. Errors:
+Result: Pi's `Successfully replaced {n} block(s) in {path}.`; the diff goes to `details` for display only. Avibe
+improvement: before the period, the result names the new file's rewritten lines, ` ({lines})`, for example
+`Successfully replaced 2 block(s) in {path} (lines 40-52, 88-90).` (`line 7` for a single line). Each replacement's
+rewritten lines run from its first to its last character that differs from the text it replaced, so unchanged context
+at either end of an edit, and a replacement that changed nothing, are left out. The range says where to look, not a
+line diff: an unchanged line between two changes of one edit is inside its range. Lines are numbered as `read`
+numbers them (only `\n` ends a line), touching ranges merge, and after five ranges the rest are counted
+(`..., ...and 3 more`). No diff is returned to the model. Avibe: when an item uses `replaceAll`, the result counts
+occurrences instead, `Successfully replaced {total} occurrences in {path} ({lines}).` (`1 occurrence` when singular),
+with `; edits[0]: {count}, edits[1]: {count}` after the lines for several items, so the model need not read the file
+again to count or inspect them. Errors:
- `Could not find edits[{i}] in {path}. The oldText must match exactly including all whitespace and newlines.`; when
the normalization budget was reached, Avibe ends it with `: the file is too large to match it loosely after Unicode
normalization.` instead of the period
- `Found {count} occurrences of edits[{i}] in {path}. Each oldText must be unique. Please provide more context to make it unique.`
+ Avibe improvement: it continues ` Occurrences:` and one `line {n}: {excerpt}` line per occurrence, for the first five
+ in file order, then `...and {k} more`. The excerpt is the text of the line it starts on, without indentation; a line over
+ 100 characters is shown only around the occurrence, with `...` where it is cut.
- `edits[{a}] and edits[{b}] overlap in {path}. Merge them into one edit or target disjoint regions.`
- `edits[{i}].oldText must not be empty in {path}.`
diff --git a/tests/agent_core/agent/test_compaction.py b/tests/agent_core/agent/test_compaction.py
index 44132651c..842ae1fa7 100644
--- a/tests/agent_core/agent/test_compaction.py
+++ b/tests/agent_core/agent/test_compaction.py
@@ -1454,7 +1454,7 @@ async def test_scratch_edit_reads_and_publishes_through_the_root_descriptor(tmp_
ToolCallBlock("d", "write", {"path": "state/scratch/session/..", "content": "no"}),
]
results = await _scratch_checkpoint(tmp_path, scratch, calls, [])
- assert results["e"].content[0].text == "Successfully replaced 1 block(s) in state/scratch/session/plan.md."
+ assert results["e"].content[0].text == "Successfully replaced 1 block(s) in state/scratch/session/plan.md (line 2)."
assert (scratch / "plan.md").read_bytes() == "\ufeffa\r\nc\r\n".encode() # BOM and CRLF kept
assert results["l"].is_error and (outside / "secret.md").read_text() == "a\n" # a symlink is never followed
assert results["d"].content[0].text == DENIED
diff --git a/tests/agent_core/tools/test_file_kinds.py b/tests/agent_core/tools/test_file_kinds.py
index 5046c3aa1..eb8214f0a 100644
--- a/tests/agent_core/tools/test_file_kinds.py
+++ b/tests/agent_core/tools/test_file_kinds.py
@@ -196,7 +196,7 @@ async def test_edit_has_a_defined_result_for_every_kind(tmp_path, make_ctx, plac
result = await _run(EditTool(), arguments, make_ctx(), tmp_path)
if kind in ("regular", "link_regular"):
- assert (result.is_error, result_text(result)) == (False, f"Successfully replaced 1 block(s) in {path}.")
+ assert (result.is_error, result_text(result)) == (False, f"Successfully replaced 1 block(s) in {path} (line 1).")
assert (tmp_path / "f").read_text() == "bye\n"
assert (tmp_path / path).is_symlink() == (kind == "link_regular")
return
diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.py
index bfab00d66..43c8d2b07 100644
--- a/tests/agent_core/tools/test_write_edit.py
+++ b/tests/agent_core/tools/test_write_edit.py
@@ -90,7 +90,7 @@ async def test_disjoint_edits_apply_against_the_original(tmp_path, make_ctx):
make_ctx, "f.py", {"oldText": "a = 1", "newText": "a = 10"}, {"oldText": "c = 3", "newText": "c = 30"}
)
- assert result_text(result) == "Successfully replaced 2 block(s) in f.py."
+ assert result_text(result) == "Successfully replaced 2 block(s) in f.py (lines 1, 3)."
assert (tmp_path / "f.py").read_text() == "a = 10\nb = 2\nc = 30\n"
assert "+1 a = 10" in result.details["diff"]
@@ -117,13 +117,13 @@ async def test_replace_all_replaces_every_occurrence(tmp_path, make_ctx):
)
# The model learns how many occurrences each item replaced without reading the file again.
- assert result_text(result) == "Successfully replaced 4 occurrences in f.txt (edits[0]: 3, edits[1]: 1)."
+ assert result_text(result) == "Successfully replaced 4 occurrences in f.txt (lines 1-4; edits[0]: 3, edits[1]: 1)."
assert (tmp_path / "f.txt").read_text() == "baz(1)\nqux\nbaz(2)\nbaz(3)\n"
@pytest.mark.parametrize(("content", "summary"), [
- ("color=red\nborder=red\naccent=red\n", "Successfully replaced 3 occurrences in f.txt."),
- ("color=red\n", "Successfully replaced 1 occurrence in f.txt."),
+ ("color=red\nborder=red\naccent=red\n", "Successfully replaced 3 occurrences in f.txt (lines 1-3)."),
+ ("color=red\n", "Successfully replaced 1 occurrence in f.txt (line 1)."),
])
async def test_a_single_replace_all_reports_its_occurrences(tmp_path, make_ctx, content, summary):
(tmp_path / "f.txt").write_text(content)
@@ -133,6 +133,87 @@ async def test_a_single_replace_all_reports_its_occurrences(tmp_path, make_ctx,
assert result_text(result) == summary
[email protected](("original", "edits", "summary"), [
+ # The new file's lines: an edit that adds lines moves every later range down.
+ (
+ "a\nb\nc\nd\n",
+ [{"oldText": "a\n", "newText": "a\na2\na3\n"}, {"oldText": "d", "newText": "D"}],
+ "Successfully replaced 2 block(s) in f.txt (lines 2-3, 6).",
+ ),
+ # Unchanged context at an edit's ends, and an edit that changes nothing, are not rewritten lines.
+ ("a\nb\nc\nd\n", [{"oldText": "a\nb\nc", "newText": "a\nB\nc"}],
+ "Successfully replaced 1 block(s) in f.txt (line 2)."),
+ ("x\ny\nc\n", [{"oldText": "x", "newText": "x"}, {"oldText": "c", "newText": "C"}],
+ "Successfully replaced 2 block(s) in f.txt (line 3)."),
+ # A removed line is reported where it was.
+ ("a\nb\nc\n", [{"oldText": "b\n", "newText": ""}], "Successfully replaced 1 block(s) in f.txt (line 2)."),
+ # Numbered as read numbers them: a CRLF ends one line, a lone "\r" ends none.
+ ("x\ry\r\nz\r\n", [{"oldText": "z", "newText": "Z"}], "Successfully replaced 1 block(s) in f.txt (line 2)."),
+ # A normalized edit rewrites its whole line, break included, and that is still one line.
+ ("a\nt = \u201cq\u201d \nb\n", [{"oldText": 't = "q"', "newText": 't = "r"'}],
+ "Successfully replaced 1 block(s) in f.txt (line 2)."),
+ # Touching ranges are one; past five ranges the rest are counted.
+ ("a\nb\n", [{"oldText": "a", "newText": "A"}, {"oldText": "b", "newText": "B"}],
+ "Successfully replaced 2 block(s) in f.txt (lines 1-2)."),
+ (
+ "k\n-\n" * 7,
+ [{"oldText": "k", "newText": "K", "replaceAll": True}],
+ "Successfully replaced 7 occurrences in f.txt (lines 1, 3, 5, 7, 9, ...and 2 more).",
+ ),
+])
+async def test_a_successful_edit_names_the_lines_it_changed(tmp_path, make_ctx, original, edits, summary):
+ (tmp_path / "f.txt").write_bytes(original.encode())
+
+ result = await _edit(make_ctx, "f.txt", *edits)
+
+ assert (result.is_error, result_text(result)) == (False, summary)
+
+
+_UNIQUE = "Please provide more context to make it unique. Occurrences:\n"
+
+
[email protected](("original", "old_text", "occurrences"), [
+ # The first five, in file order, without indentation, then how many more.
+ (
+ "".join(f" MODE = 'isolated' # {n}\n" for n in range(1, 8)),
+ "MODE = 'isolated'",
+ "Found 7 occurrences of the text in f.txt. The text must be unique. " + _UNIQUE
+ + "\n".join(f"line {n}: MODE = 'isolated' # {n}" for n in range(1, 6)) + "\n...and 2 more",
+ ),
+ # read's line numbers: a lone "\r" ends no line for read, a CRLF ends one.
+ ("a\rdup\r\ndup\n", "dup", "Found 2 occurrences of the text in f.txt. The text must be unique. " + _UNIQUE
+ + "line 1: dup\nline 2: dup"),
+ # Occurrences found only after normalization are shown as the file has them.
+ (
+ "say \u201cHi\u201d\nkeep\nsay \u201cHi\u201d \n",
+ 'say "Hi"',
+ "Found 2 occurrences of the text in f.txt. The text must be unique. " + _UNIQUE
+ + "line 1: say \u201cHi\u201d\nline 3: say \u201cHi\u201d",
+ ),
+ # A long line is shown only around the occurrence.
+ (
+ "a" * 120 + " dup " + "b" * 120 + "\ndup\n",
+ "dup",
+ "Found 2 occurrences of the text in f.txt. The text must be unique. " + _UNIQUE
+ + "line 1: ..." + "a" * 24 + " dup " + "b" * 71 + "...\nline 2: dup",
+ ),
+ # ... also when it was found after normalization lengthened the line before it (U+FB01 is "fi").
+ (
+ "\ufb01" * 150 + " say \u201cHi\u201d " + "b" * 100 + "\nsay \u201cHi\u201d\n",
+ 'say "Hi"',
+ "Found 2 occurrences of the text in f.txt. The text must be unique. " + _UNIQUE
+ + "line 1: ..." + "\ufb01" * 24 + " say \u201cHi\u201d " + "b" * 66 + "...\nline 2: say \u201cHi\u201d",
+ ),
+])
+async def test_an_ambiguous_edit_lists_where_the_text_occurs(tmp_path, make_ctx, original, old_text, occurrences):
+ (tmp_path / "f.txt").write_bytes(original.encode())
+
+ result = await _edit(make_ctx, "f.txt", {"oldText": old_text, "newText": "x"})
+
+ assert (result.is_error, result_text(result)) == (True, occurrences)
+ assert (tmp_path / "f.txt").read_bytes() == original.encode()
+
+
async def test_text_copied_from_read_edits_a_file_with_invalid_bytes(tmp_path, make_ctx):
"""read and edit show undecodable bytes the same way, so a block copied from read matches."""
(tmp_path / "f.txt").write_bytes(b"a\xffb\xe2\x82c\nkeep\x80\n")
@@ -825,12 +906,12 @@ async def test_an_edit_never_changes_bytes_outside_the_lines_it_replaces(tmp_pat
(
[{"oldText": "dup", "newText": "x"}],
"Found 2 occurrences of the text in f.txt. The text must be unique. Please provide more context to make "
- "it unique.",
+ "it unique. Occurrences:\nline 2: dup one\nline 3: dup two",
),
(
[{"oldText": "alpha", "newText": "A"}, {"oldText": "dup", "newText": "x"}],
"Found 2 occurrences of edits[1] in f.txt. Each oldText must be unique. Please provide more context to "
- "make it unique.",
+ "make it unique. Occurrences:\nline 2: dup one\nline 3: dup two",
),
(
[{"oldText": "alpha beta", "newText": "x"}, {"oldText": "beta", "newText": "y"}],