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.

fix(agent-core): structural edit budgets, refuse non-atomic writes

cyh6570896e0c3c
diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.py
index ace4ea92a..3cb6675c2 100644
--- a/core/agent_core/tools/edit.py
+++ b/core/agent_core/tools/edit.py
@@ -15,7 +15,7 @@ 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, apply_edits, display_diff
+from core.agent_core.tools.edit_diff import Edit, EditError, ResultTooLarge, apply_edits, display_diff
from core.agent_core.tools.paths import (
NotRegularFile,
errno_name,
@@ -28,11 +28,13 @@ from core.agent_core.tools.paths import (
)
from core.agent_core.tools.text import decode_file, encode_file, model_text
from core.agent_core.tools.truncate import format_size
-from core.agent_core.tools.write import FileChanged, FileIdentity, write_bytes
+from core.agent_core.tools.write import FileChanged, FileIdentity, NotReplaceable, write_bytes
#: Avibe: larger files are refused rather than loaded whole; the display diff stops at a smaller size.
MAX_EDIT_BYTES = 10 * 1024 * 1024
MAX_DIFF_BYTES = 1024 * 1024
+#: Avibe: planning keeps a few hundred bytes of Python objects per line, so lines have a budget too.
+MAX_EDIT_LINES = 200_000
EDIT_DESCRIPTION = (
"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping "
@@ -131,6 +133,17 @@ class _TooLarge(Exception):
self.size = size
+class _TooManyLines(Exception):
+ def __init__(self, lines: int) -> None:
+ super().__init__(lines)
+ self.lines = lines
+
+
+def _line_count(text: str) -> int:
+ """Lines as edit's view counts them: ``\\r\\n``, ``\\r`` and ``\\n`` each end one."""
+ return text.count("\n") + text.count("\r") - text.count("\r\n") + 1
+
+
def _plan_edits(absolute: str, edits: list[Edit], path: str) -> tuple[int, bytes, str, str, FileIdentity]:
"""Read the file and compute its new bytes: ``(size, data, view_before, view_after, identity)``.
@@ -151,7 +164,11 @@ def _plan_edits(absolute: str, edits: list[Edit], path: str) -> tuple[int, bytes
os.close(fd)
if len(raw) > MAX_EDIT_BYTES:
raise _TooLarge(max(size, len(raw)))
- new_text, before, after = apply_edits(decode_file(raw), edits, path)
+ text = decode_file(raw)
+ lines = _line_count(text)
+ if lines > MAX_EDIT_LINES:
+ raise _TooManyLines(lines)
+ new_text, before, after = apply_edits(text, edits, path, max_result_chars=MAX_EDIT_BYTES)
return len(raw), encode_file(new_text), before, after, FileIdentity.of(real, st)
@@ -189,11 +206,7 @@ class EditTool:
try:
size, data, base, new_content, identity = await to_thread_joined(_plan_edits, absolute, edits, path)
if len(data) > MAX_EDIT_BYTES:
- return error_result(
- f"File {path} would be {format_size(len(data))} after this edit, over the "
- f"{format_size(MAX_EDIT_BYTES)} edit limit. "
- "Use bash (for example sed or a short script) to change files this large."
- )
+ raise ResultTooLarge()
if ctx.cancel.cancelled:
return error_result("Operation aborted")
await to_thread_joined(write_bytes, absolute, data, identity)
@@ -203,6 +216,20 @@ class EditTool:
f"File {path} is {format_size(exc.size)}, over the {format_size(MAX_EDIT_BYTES)} edit limit. "
"Use bash (for example sed or a short script) to change files this large."
)
+ except _TooManyLines as exc:
+ return error_result(
+ f"File {path} has {exc.lines} lines, over the {MAX_EDIT_LINES} line edit limit. "
+ "Use bash (for example sed or a short script) to change files this large."
+ )
+ except ResultTooLarge:
+ return error_result(
+ f"File {path} would be over the {format_size(MAX_EDIT_BYTES)} edit limit after this edit. "
+ "Use bash (for example sed or a short script) to change files this large."
+ )
+ except NotReplaceable:
+ return error_result(
+ f"Could not edit file: {path}. Its directory is not writable, so the file cannot be replaced safely."
+ )
except EditError as exc:
return error_result(str(exc))
except FileChanged:
diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.py
index d21d8d4e6..8051fe8db 100644
--- a/core/agent_core/tools/edit_diff.py
+++ b/core/agent_core/tools/edit_diff.py
@@ -68,28 +68,38 @@ def normalize_for_fuzzy_match(text: str) -> str:
return _SPECIAL_SPACES.sub(" ", text)
-def _find_all(content: str, needle: str) -> list[int]:
+#: Avibe: replacements one ``replaceAll`` may make. Each costs a few hundred bytes of Python objects in
+#: the process every Session shares, so the budget is structural, not only the file's size.
+MAX_REPLACEMENTS = 10_000
+
+
+class ResultTooLarge(Exception):
+ """The edits insert more text than the result may hold; nothing was built."""
+
+
+def _find_all(content: str, needle: str, limit: int) -> list[int]:
found: list[int] = []
- if not needle:
- return found
index = content.find(needle)
- while index != -1:
+ while index != -1 and len(found) < limit:
found.append(index)
index = content.find(needle, index + len(needle))
return found
-def _occurrences(content: str, normalized: Callable[[], str], old_text: str) -> tuple[bool, list[tuple[int, int]]]:
- """``(used_normalized, spans)``: the edit's occurrences in the first tier that has one.
+def _tier(content: str, normalized: Callable[[], str], old_text: str) -> tuple[bool, str, str, int]:
+ """``(used_normalized, haystack, needle, count)`` for the first tier where the edit occurs.
- Exact spans are in the original text, normalized spans in the normalized text. Text that
- normalizes to nothing never matches in the normalized tier.
+ Counting is ``str.count`` (no objects per match), so a match budget holds before any are built.
+ Text that normalizes to nothing never matches in the normalized tier.
"""
- exact = _find_all(content, old_text)
- if exact:
- return False, [(index, len(old_text)) for index in exact]
+ count = content.count(old_text)
+ if count:
+ return False, content, old_text, count
fuzzy_old = normalize_for_fuzzy_match(old_text)
- return True, [(index, len(fuzzy_old)) for index in _find_all(normalized(), fuzzy_old)]
+ if not fuzzy_old:
+ return True, "", "", 0
+ haystack = normalized()
+ return True, haystack, fuzzy_old, haystack.count(fuzzy_old)
def _not_found(path: str, index: int, total: int) -> EditError:
@@ -116,6 +126,14 @@ def _duplicate(path: str, index: int, total: int, occurrences: int) -> EditError
)
+def _too_many(path: str, index: int, total: int, occurrences: int) -> EditError:
+ which = "the text" if total == 1 else f"edits[{index}]"
+ return EditError(
+ f"Found {occurrences} occurrences of {which} in {path}, over the {MAX_REPLACEMENTS} replaceAll limit. "
+ "Use bash (for example sed or a short script) to replace this many."
+ )
+
+
def _empty(path: str, index: int, total: int) -> EditError:
if total == 1:
return EditError(f"oldText must not be empty in {path}.")
@@ -265,7 +283,9 @@ def _line_groups(lines: _Lines, normalized: str, matches: list[_Replacement]) ->
return out
-def apply_edits(text: str, edits: list[Edit], path: str) -> tuple[str, str, str]:
+def apply_edits(
+ text: str, edits: list[Edit], path: str, max_result_chars: Optional[int] = None
+) -> tuple[str, str, str]:
"""Apply every edit to the file's ``text``; return the new text and the LF views before and after.
Each edit matches in its own tier against the original, in the file's LF view. Exact edits replace
@@ -291,15 +311,21 @@ def apply_edits(text: str, edits: list[Edit], path: str) -> tuple[str, str, str]
exact: list[_Replacement] = []
fuzzy: list[_Replacement] = []
+ inserted = 0
for index, edit in enumerate(edits):
- used_normalized, spans = _occurrences(lines.view, normalized, edit.old_text)
- if not spans:
+ used_normalized, haystack, needle, count = _tier(lines.view, normalized, edit.old_text)
+ if not count:
raise _not_found(path, index, total)
- if not edit.replace_all and len(spans) > 1:
- raise _duplicate(path, index, total, len(spans))
- chosen = spans if edit.replace_all else spans[:1]
+ if not edit.replace_all and count > 1:
+ raise _duplicate(path, index, total, count)
+ if count > MAX_REPLACEMENTS:
+ raise _too_many(path, index, total, count)
+ # The result holds at least every inserted text, so this bound never refuses a result that fits.
+ inserted += count * len(edit.new_text)
+ if max_result_chars is not None and inserted > max_result_chars:
+ raise ResultTooLarge()
(fuzzy if used_normalized else exact).extend(
- _Replacement(index, at, length, edit.new_text) for at, length in chosen
+ _Replacement(index, at, len(needle), edit.new_text) for at in _find_all(haystack, needle, count)
)
_check_disjoint(path, fuzzy) # in normalized coordinates, before they are grouped into lines
@@ -308,7 +334,12 @@ def apply_edits(text: str, edits: list[Edit], path: str) -> tuple[str, str, str]
new_text = _apply(text, replacements)
if new_text == text:
raise _no_change(path, total)
- return new_text, lines.view, _Lines(new_text).view
+ return new_text, lines.view, lf_view(new_text)
+
+
+def lf_view(text: str) -> str:
+ """``_Lines(text).view`` without per-line state: the result may have far more lines than the file."""
+ return shown(normalize_to_lf(text[len(BOM) :] if text.startswith(BOM) else text))
#: The display diff runs difflib only on the changed middle, and skips it when either side is longer.
diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.py
index 36ea44d49..2ab833502 100644
--- a/core/agent_core/tools/paths.py
+++ b/core/agent_core/tools/paths.py
@@ -17,7 +17,7 @@ import stat
import unicodedata
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Callable, Literal, TypeVar
-from urllib.parse import unquote, urlparse
+from urllib.parse import unquote
from core.agent_core.tools.args import ToolInputError
diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.py
index 88f77fa5a..e36af3e96 100644
--- a/core/agent_core/tools/write.py
+++ b/core/agent_core/tools/write.py
@@ -6,7 +6,6 @@ Ported from Pi ``packages/coding-agent/src/core/tools/write.ts`` (MIT, Copyright
from __future__ import annotations
-import asyncio
import contextlib
import os
import secrets
@@ -19,7 +18,6 @@ from core.agent_core.tools.base import ToolContext, ToolResult, ToolSpec
from core.agent_core.tools.paths import (
KIND_REASON,
file_mutation_lock,
- open_regular,
os_reason,
resolve_to_cwd,
target_kind,
@@ -68,6 +66,10 @@ class WriteTool:
if ctx.cancel.cancelled:
return error_result("Operation aborted")
await to_thread_joined(write_text, absolute, content)
+ except NotReplaceable:
+ return error_result(
+ f"Cannot write {path}: its directory is not writable, so the file cannot be replaced safely."
+ )
except OSError as exc:
return error_result(f"Cannot write {path}: {os_reason(exc)}.")
return text_result(f"Successfully wrote to {path}")
@@ -103,6 +105,13 @@ class FileChanged(Exception):
"""The file is no longer the one a read-modify-write read; nothing was written."""
+class NotReplaceable(Exception):
+ """An existing file in a directory no temp file can be created in; nothing was written.
+
+ Writing it in place could leave it half-written (ENOSPC, a quota), so it is refused.
+ """
+
+
@dataclass(frozen=True)
class FileIdentity:
"""The file a read-modify-write read, so its result is published only over that same file."""
@@ -132,9 +141,11 @@ def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None)
created with the umask default it keeps, so the process umask is never read or changed. Then
``os.replace`` puts it in place.
- With ``expected``, the file must still be the one that was read: checked once, right before the
- rename, or with ``fstat`` on the descriptor an in-place write goes through. POSIX has no
- compare-and-rename, so a change between that check and the rename is not seen.
+ An existing file whose directory does not let a temp file be created is refused
+ (``NotReplaceable``) rather than written in place, which a full disk could leave half-written.
+
+ With ``expected``, the file must still be the one that was read, checked once right before the
+ rename. POSIX has no compare-and-rename, so a change between that check and the rename is not seen.
"""
target = os.path.realpath(path)
try:
@@ -147,12 +158,7 @@ def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None)
except PermissionError:
if mode is None:
raise
- # An existing, writable file in a directory we cannot add to: only an in-place write is possible.
- with os.fdopen(open_regular(target, os.O_WRONLY), "wb") as handle:
- _require(expected, target, os.fstat(handle.fileno()))
- handle.truncate(0)
- handle.write(data)
- return
+ raise NotReplaceable() from None
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
diff --git a/tests/agent_core/tools/test_file_kinds.py b/tests/agent_core/tools/test_file_kinds.py
index a393f36eb..5046c3aa1 100644
--- a/tests/agent_core/tools/test_file_kinds.py
+++ b/tests/agent_core/tools/test_file_kinds.py
@@ -161,15 +161,9 @@ async def test_write_has_a_defined_result_for_every_kind(tmp_path, make_ctx, pla
result = await _run(WriteTool(), {"path": path, "content": "new\n"}, make_ctx(), tmp_path)
- if kind in ("regular", "link_regular", "dangling", "missing", "in_locked_dir"):
+ if kind in ("regular", "link_regular", "dangling", "missing"):
assert (result.is_error, result_text(result)) == (False, f"Successfully wrote to {path}")
- target = {
- "regular": "f",
- "link_regular": "f",
- "dangling": "missing/f",
- "missing": "missing/sub/f",
- "in_locked_dir": "ro/f", # written in place: the only non-atomic case
- }[kind]
+ target = {"regular": "f", "link_regular": "f", "dangling": "missing/f", "missing": "missing/sub/f"}[kind]
assert (tmp_path / target).read_text() == "new\n"
if kind in ("link_regular", "dangling"):
assert (tmp_path / path).is_symlink()
@@ -177,6 +171,8 @@ async def test_write_has_a_defined_result_for_every_kind(tmp_path, make_ctx, pla
reason = {
"read_only": "permission denied",
"unreadable": "permission denied",
+ # Replacing needs a temp file beside it; writing in place could leave it half-written (ENOSPC).
+ "in_locked_dir": "its directory is not writable, so the file cannot be replaced safely",
"under_file": "not a directory",
"loop": "too many levels of symbolic links",
**dict.fromkeys(DIRECTORY, "it is a directory"),
@@ -188,6 +184,8 @@ async def test_write_has_a_defined_result_for_every_kind(tmp_path, make_ctx, pla
assert os.lstat(path if os.path.isabs(path) else tmp_path / path).st_mode == before
if kind == "read_only":
assert (tmp_path / "f").read_text() == "hello\n"
+ if kind == "in_locked_dir":
+ assert (tmp_path / "ro" / "f").read_text() == "hello\n"
@pytest.mark.parametrize("kind", _cases(KINDS))
@@ -197,14 +195,15 @@ 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", "in_locked_dir"):
+ if kind in ("regular", "link_regular"):
assert (result.is_error, result_text(result)) == (False, f"Successfully replaced 1 block(s) in {path}.")
- assert (tmp_path / ("ro/f" if kind == "in_locked_dir" else "f")).read_text() == "bye\n"
+ assert (tmp_path / "f").read_text() == "bye\n"
assert (tmp_path / path).is_symlink() == (kind == "link_regular")
return
detail = {
"read_only": "Error code: EACCES.",
"unreadable": "Error code: EACCES.",
+ "in_locked_dir": "Its directory is not writable, so the file cannot be replaced safely.",
"loop": "Error code: ELOOP.",
"under_file": "Error code: ENOTDIR.",
**dict.fromkeys(DIRECTORY, "Error code: EISDIR."),
@@ -214,3 +213,5 @@ async def test_edit_has_a_defined_result_for_every_kind(tmp_path, make_ctx, plac
assert (result.is_error, result_text(result)) == (True, f"Could not edit file: {path}. {detail}")
if kind == "read_only":
assert stat.S_IMODE(os.stat(tmp_path / "f").st_mode) == 0o444
+ if kind == "in_locked_dir":
+ assert (tmp_path / "ro" / "f").read_text() == "hello\n"
diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.py
index d920eb38c..82cf819d7 100644
--- a/tests/agent_core/tools/test_write_edit.py
+++ b/tests/agent_core/tools/test_write_edit.py
@@ -10,6 +10,7 @@ import re
import stat
import threading
import time
+import tracemalloc
import pytest
@@ -17,6 +18,7 @@ import core.agent_core.tools.paths as paths_module
import core.agent_core.tools.write as write_module
import core.agent_core.tools.edit as edit_module
+import core.agent_core.tools.edit_diff as edit_diff_module
from core.agent_core.tools.args import ToolInputError
from core.agent_core.tools.edit import EditTool
from core.agent_core.tools.read import ReadTool
@@ -246,7 +248,7 @@ async def test_a_cancelled_write_lands_before_the_next_writer_takes_the_lock(
assert (tmp_path / "f.txt").read_text() == "second\n"
[email protected]("change", ["replaced", "retargeted", "rewritten", "rewritten-in-place"])
[email protected]("change", ["replaced", "retargeted", "rewritten"])
async def test_an_edit_publishes_only_over_the_file_it_read(tmp_path, make_ctx, monkeypatch, change):
"""Another writer (bash, an editor) changed the file after edit read it: nothing is written over it."""
(tmp_path / "d").mkdir()
@@ -269,12 +271,7 @@ async def test_an_edit_publishes_only_over_the_file_it_read(tmp_path, make_ctx,
return planned
monkeypatch.setattr(edit_module, "_plan_edits", plan_then_change)
- if change == "rewritten-in-place":
- (tmp_path / "d").chmod(0o555) # no temp file can be created beside it
- try:
- result = await _edit(make_ctx, "d/f.txt", {"oldText": "alpha", "newText": "beta"})
- finally:
- (tmp_path / "d").chmod(0o755)
+ result = await _edit(make_ctx, "d/f.txt", {"oldText": "alpha", "newText": "beta"})
assert (result.is_error, result_text(result)) == (
True,
@@ -391,6 +388,83 @@ async def test_edit_work_stays_linear_on_adversarial_files(tmp_path, make_ctx, c
assert time.monotonic() - started < 1.0
+ ("content", "edit", "is_error"),
+ [
+ # A unique edit stops looking after the second match; the count comes from str.count.
+ ("x" * 1_000_000, {"oldText": "x", "newText": "y"}, True),
+ # More lines than edit plans per-line state for: refused before any is built.
+ ("\n" * 1_000_000 + "t", {"oldText": "t", "newText": "u"}, True),
+ # More occurrences than replaceAll builds replacements for: refused before any is built.
+ ("x" * 1_000_000, {"oldText": "x", "newText": "y", "replaceAll": True}, True),
+ # A result of three million lines, within the byte limit: its view is built without per-line state.
+ ("t," * 10, {"oldText": "t", "newText": "\n" * 300_000, "replaceAll": True}, False),
+ ],
+ ids=["duplicate", "many-lines", "many-occurrences", "many-result-lines"],
+)
+async def test_edit_memory_is_bounded_by_its_budgets_not_by_the_file(tmp_path, make_ctx, content, edit, is_error):
+ """Python objects per line or per match cost hundreds of bytes each, in the process every Session shares."""
+ (tmp_path / "f.txt").write_text(content)
+ tracemalloc.start()
+ try:
+ result = await _edit(make_ctx, "f.txt", edit)
+ peak = tracemalloc.get_traced_memory()[1]
+ finally:
+ tracemalloc.stop()
+
+ assert result.is_error == is_error, result_text(result)
+ assert peak < 32 * 1024 * 1024
+
+
+async def test_edit_refuses_files_with_more_lines_than_it_plans(tmp_path, make_ctx, monkeypatch):
+ monkeypatch.setattr(edit_module, "MAX_EDIT_LINES", 100)
+ (tmp_path / "ok.txt").write_text("x\n" * 99 + "t")
+ (tmp_path / "big.txt").write_text("x\r\n" * 100 + "t")
+
+ ok = await _edit(make_ctx, "ok.txt", {"oldText": "t", "newText": "u"})
+ big = await _edit(make_ctx, "big.txt", {"oldText": "t", "newText": "u"})
+
+ assert not ok.is_error, result_text(ok)
+ assert (big.is_error, result_text(big)) == (
+ True,
+ "File big.txt has 101 lines, over the 100 line edit limit. "
+ "Use bash (for example sed or a short script) to change files this large.",
+ )
+
+
+ ("edits", "message"),
+ [
+ (
+ [{"oldText": "a", "newText": "b", "replaceAll": True}],
+ "Found 11 occurrences of the text in f.txt, over the 10 replaceAll limit. "
+ "Use bash (for example sed or a short script) to replace this many.",
+ ),
+ (
+ [{"oldText": "zz", "newText": "q"}, {"oldText": "a", "newText": "b", "replaceAll": True}],
+ "Found 11 occurrences of edits[1] in f.txt, over the 10 replaceAll limit. "
+ "Use bash (for example sed or a short script) to replace this many.",
+ ),
+ (
+ # Ten replacements of 200 characters: over a 1,000-byte limit before anything is built.
+ [{"oldText": "c", "newText": "y" * 200, "replaceAll": True}],
+ "File f.txt would be over the 1000B edit limit after this edit. "
+ "Use bash (for example sed or a short script) to change files this large.",
+ ),
+ ],
+ ids=["single", "batch", "inserted-text"],
+)
+async def test_replace_all_has_a_budget(tmp_path, make_ctx, monkeypatch, edits, message):
+ monkeypatch.setattr(edit_module, "MAX_EDIT_BYTES", 1000)
+ monkeypatch.setattr(edit_diff_module, "MAX_REPLACEMENTS", 10)
+ (tmp_path / "f.txt").write_text("a," * 11 + "zz\n" + "c," * 10 + "\n")
+
+ result = await _edit(make_ctx, "f.txt", *edits)
+
+ assert (result.is_error, result_text(result)) == (True, message)
+ assert (tmp_path / "f.txt").read_text() == "a," * 11 + "zz\n" + "c," * 10 + "\n"
+
+
async def test_a_large_changed_middle_skips_the_display_diff(tmp_path, make_ctx):
(tmp_path / "f.txt").write_text("".join(f"line {i}\n" for i in range(3000)))
@@ -416,7 +490,7 @@ async def test_a_planned_result_over_the_limit_is_refused_and_its_diff_skipped(t
assert grown.details == {"diff_skipped": True}
assert too_big.is_error
assert result_text(too_big) == (
- "File small.txt would be 2.0KB after this edit, over the 1000B edit limit. "
+ "File small.txt would be over the 1000B edit limit after this edit. "
"Use bash (for example sed or a short script) to change files this large."
)
assert (tmp_path / "small.txt").read_text() == "x" * 600 + "\n"