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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(agent-core): per-edit match tiers, atomic file writes, and bounded-log results
cyh502b849e1c13
diff --git a/core/agent_core/tools/args.py b/core/agent_core/tools/args.pyindex 6b5dedae7..44ebe0e7a 100644--- a/core/agent_core/tools/args.py+++ b/core/agent_core/tools/args.py@@ -32,9 +32,27 @@ def optional_number_arg(arguments: Mapping[str, Any], name: str) -> Optional[flovalue = arguments.get(name)if value is None:return None- if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ if isinstance(value, bool) or not isinstance(value, (int, float)):raise ToolInputError(f"{name} must be a number")- return float(value)+ try:+ number = float(value) # an integer too large for a float overflows here+ except OverflowError:+ raise ToolInputError(f"{name} must be a finite number") from None+ if not math.isfinite(number):+ raise ToolInputError(f"{name} must be a finite number")+ return number+++def optional_line_arg(arguments: Mapping[str, Any], name: str) -> Optional[int]:+ """A JSON integer of at least 1 (an integral float such as ``3.0`` is accepted)."""+ value = arguments.get(name)+ if value is None:+ return None+ if isinstance(value, float) and math.isfinite(value) and value.is_integer():+ value = int(value)+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise ToolInputError(f"{name} must be an integer of at least 1")+ return valuedef optional_bool_arg(arguments: Mapping[str, Any], name: str) -> bool:diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.pyindex 2182e9798..c836c0932 100644--- a/core/agent_core/tools/edit_diff.py+++ b/core/agent_core/tools/edit_diff.py@@ -5,18 +5,20 @@ Copyright (c) 2025 Mario Zechner): exact match first, then Pi's deterministicnormalized match with no similarity threshold, every edit matched against theoriginal, overlapping edits rejected. Avibe adds ``replaceAll`` (from ClaudeCode and OpenCode): every occurrence in the tier that matched, each one a span-for the overlap check. Two Avibe departures from Pi: uniqueness is counted in-the tier that matched (Pi always counts normalized text), and classic Mac CR-line endings are restored like CRLF.+for the overlap check. Avibe departures from Pi: each edit matches in its own+tier, so one normalized edit no longer switches the whole batch to normalized+text; uniqueness is counted in the tier that matched; classic Mac CR line+endings are restored like CRLF."""from __future__ import annotations+import bisectimport difflibimport reimport unicodedatafrom dataclasses import dataclass-from typing import Optional+from typing import Callable, OptionalBOM = "\ufeff"@@ -26,7 +28,6 @@ _SMART_SINGLE = re.compile("[\u2018\u2019\u201a\u201b]")_SMART_DOUBLE = re.compile("[\u201c\u201d\u201e\u201f]")_DASHES = re.compile("[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]")_SPECIAL_SPACES = re.compile("[\u00a0\u2002-\u200a\u202f\u205f\u3000]")-_LINES_WITH_ENDINGS = re.compile(r"[^\n]*\n|[^\n]+")class EditError(ValueError):@@ -89,32 +90,17 @@ def _find_all(content: str, needle: str) -> list[int]:return found-def _find(content: str, old_text: str) -> Optional[tuple[int, int, int, bool]]:- """``(index, length, occurrences, used_fuzzy)`` of the first match, exact before normalized.+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.- Occurrences are counted in the tier that matched.+ Exact spans are in the original text, normalized spans in the normalized text. Text that+ normalizes to nothing never matches in the normalized tier."""- exact = content.find(old_text)- if exact != -1:- return exact, len(old_text), content.count(old_text), False- fuzzy_old = normalize_for_fuzzy_match(old_text)- if not fuzzy_old:- # Whitespace that normalizes away would match everywhere, length zero.- return None- fuzzy_content = normalize_for_fuzzy_match(content)- fuzzy = fuzzy_content.find(fuzzy_old)- if fuzzy == -1:- return None- return fuzzy, len(fuzzy_old), fuzzy_content.count(fuzzy_old), True---def _find_every(content: str, old_text: str) -> list[tuple[int, int]]:- """All occurrences in the first tier that has one. ``content`` is already normalized when needed."""exact = _find_all(content, old_text)if exact:- return [(index, len(old_text)) for index in exact]+ return False, [(index, len(old_text)) for index in exact]fuzzy_old = normalize_for_fuzzy_match(old_text)- return [(index, len(fuzzy_old)) for index in _find_all(normalize_for_fuzzy_match(content), fuzzy_old)]+ return True, [(index, len(fuzzy_old)) for index in _find_all(normalized(), fuzzy_old)]def _not_found(path: str, index: int, total: int) -> EditError:@@ -158,68 +144,77 @@ def _no_change(path: str, total: int) -> EditError:def _apply(content: str, replacements: list[_Replacement], offset: int = 0) -> str:result = content- for replacement in reversed(replacements):+ for replacement in sorted(replacements, key=lambda r: r.index, reverse=True):start = replacement.index - offsetresult = result[:start] + replacement.new_text + result[start + replacement.length :]return result-def _line_spans(content: str) -> list[tuple[int, int]]:- spans = []- offset = 0- for line in _LINES_WITH_ENDINGS.findall(content):- spans.append((offset, offset + len(line)))- offset += len(line)- return spans+def _line_starts(text: str) -> list[int]:+ starts = [0]+ index = text.find("\n")+ while index != -1:+ starts.append(index + 1)+ index = text.find("\n", index + 1)+ return starts+++def _overlap(path: str, first: int, second: int) -> EditError:+ return EditError(+ f"edits[{first}] and edits[{second}] overlap in {path}. Merge them into one edit or target disjoint regions."+ )-def _line_range(lines: list[tuple[int, int]], replacement: _Replacement) -> tuple[int, int]:- start, end = replacement.index, replacement.index + replacement.length- start_line = next((i for i, (lo, hi) in enumerate(lines) if lo <= start < hi), -1)- if start_line == -1:- raise EditError("Replacement range is outside the base content.")- end_line = start_line- while end_line < len(lines) and lines[end_line][1] < end:- end_line += 1- if end_line >= len(lines):- raise EditError("Replacement range is outside the base content.")- return start_line, end_line + 1+def _check_disjoint(path: str, replacements: list[_Replacement]) -> None:+ ordered = sorted(replacements, key=lambda r: r.index)+ for previous, current in zip(ordered, ordered[1:]):+ if previous.index + previous.length > current.index:+ raise _overlap(path, previous.edit_index, current.edit_index)-def _apply_preserving_unchanged_lines(original: str, base: str, replacements: list[_Replacement]) -> str:- """Apply replacements found in the normalized ``base`` to ``original``.+def _line_groups(content: str, normalized: str, replacements: list[_Replacement]) -> list[_Replacement]:+ """Normalized-tier replacements as whole-line replacements in original coordinates.- Lines a replacement touches are rewritten from the normalized base; every- other line keeps its original bytes.+ Normalization keeps every line break, so line ``i`` of the normalized text is line ``i`` of the+ original. Replacements sharing lines form one group; its lines are rewritten from the+ normalized text with the group's replacements applied (Pi's way of applying a normalized match)."""- original_lines = _LINES_WITH_ENDINGS.findall(original)- base_lines = _line_spans(base)- if len(original_lines) != len(base_lines):+ original_starts, normalized_starts = _line_starts(content), _line_starts(normalized)+ if len(original_starts) != len(normalized_starts):raise EditError("Cannot preserve unchanged lines because the base content has a different line count.")- groups: list[list] = [] # [start_line, end_line, replacements]++ def line_of(index: int) -> int:+ return bisect.bisect_right(normalized_starts, index) - 1++ groups: list[list] = [] # [first_line, last_line, members]for replacement in sorted(replacements, key=lambda r: r.index):- start_line, end_line = _line_range(base_lines, replacement)- if groups and start_line < groups[-1][1]:- groups[-1][1] = max(groups[-1][1], end_line)+ first, last = line_of(replacement.index), line_of(replacement.index + replacement.length - 1)+ if groups and first <= groups[-1][1]:+ groups[-1][1] = max(groups[-1][1], last)groups[-1][2].append(replacement)- continue- groups.append([start_line, end_line, [replacement]])- out: list[str] = []- line = 0- for start_line, end_line, members in groups:- out.append("".join(original_lines[line:start_line]))- lo, hi = base_lines[start_line][0], base_lines[end_line - 1][1]- out.append(_apply(base[lo:hi], members, lo))- line = end_line- out.append("".join(original_lines[line:]))- return "".join(out)+ else:+ groups.append([first, last, [replacement]])++ def bounds(starts: list[int], text: str, first: int, last: int) -> tuple[int, int]:+ return starts[first], starts[last + 1] if last + 1 < len(starts) else len(text)++ out: list[_Replacement] = []+ for first, last, members in groups:+ lo, hi = bounds(normalized_starts, normalized, first, last)+ original_lo, original_hi = bounds(original_starts, content, first, last)+ rewritten = _apply(normalized[lo:hi], members, lo)+ out.append(_Replacement(members[0].edit_index, original_lo, original_hi - original_lo, rewritten))+ return outdef apply_edits_to_normalized_content(content: str, edits: list[Edit], path: str) -> str:"""Apply every edit to LF-normalized ``content`` and return the new content.- If any edit needs the normalized match, all edits are matched in normalized- space and only the touched lines are taken from it.+ Each edit matches in its own tier against the original. Exact edits replace exactly the text+ they matched; a normalized edit rewrites the whole lines it touches from the normalized text.+ Uniqueness, ``replaceAll``, overlap, and application are all per edit in original coordinates,+ so nothing an exact edit did not match is touched. (Pi matches a whole batch in normalized text+ as soon as one edit needs it.)"""edits = [Edit(normalize_to_lf(e.old_text), normalize_to_lf(e.new_text), e.replace_all) for e in edits]total = len(edits)@@ -227,35 +222,30 @@ def apply_edits_to_normalized_content(content: str, edits: list[Edit], path: strif not edit.old_text:raise _empty(path, index, total)- used_fuzzy = any(m is not None and m[3] for m in (_find(content, e.old_text) for e in edits))- base = normalize_for_fuzzy_match(content) if used_fuzzy else content+ cache: list[str] = []++ def normalized() -> str:+ if not cache:+ cache.append(normalize_for_fuzzy_match(content))+ return cache[0]- replacements: list[_Replacement] = []+ exact: list[_Replacement] = []+ fuzzy: list[_Replacement] = []for index, edit in enumerate(edits):- if edit.replace_all:- spans = _find_every(base, edit.old_text)- if not spans:- raise _not_found(path, index, total)- replacements.extend(_Replacement(index, at, length, edit.new_text) for at, length in spans)- continue- match = _find(base, edit.old_text)- if match is None:+ used_normalized, spans = _occurrences(content, normalized, edit.old_text)+ if not spans:raise _not_found(path, index, total)- if match[2] > 1:- raise _duplicate(path, index, total, match[2])- replacements.append(_Replacement(index, match[0], match[1], edit.new_text))-- replacements.sort(key=lambda r: r.index)- for previous, current in zip(replacements, replacements[1:]):- if previous.index + previous.length > current.index:- raise EditError(- f"edits[{previous.edit_index}] and edits[{current.edit_index}] overlap in {path}. Merge them into "- "one edit or target disjoint regions."- )+ 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]+ (fuzzy if used_normalized else exact).extend(+ _Replacement(index, at, length, edit.new_text) for at, length in chosen+ )- new_content = (- _apply_preserving_unchanged_lines(content, base, replacements) if used_fuzzy else _apply(base, replacements)- )+ _check_disjoint(path, fuzzy) # in normalized coordinates, before they are grouped into lines+ replacements = exact + (_line_groups(content, normalized(), fuzzy) if fuzzy else [])+ _check_disjoint(path, replacements)+ new_content = _apply(content, replacements)if new_content == content:raise _no_change(path, total)return new_contentdiff --git a/core/agent_core/tools/output.py b/core/agent_core/tools/output.pyindex 1a5b4892d..5d63e89b0 100644--- a/core/agent_core/tools/output.py+++ b/core/agent_core/tools/output.py@@ -13,6 +13,7 @@ from dataclasses import replacefrom typing import Any, Optionalfrom core.agent_core.tools.base import MAX_BYTES, MAX_LINES, JobHost+from core.agent_core.tools import jobs as job_hostfrom core.agent_core.tools.normalize import OutputNormalizerfrom core.agent_core.tools.truncate import TruncationResult, format_size, truncate_tail, utf8_len@@ -132,38 +133,42 @@ class JobOutput:return self._accumulator.snapshot("" if self._finished else self._normalizer.peek())def render(self, empty_text: str) -> tuple[str, Optional[TruncationResult]]:- """Pi's ``formatOutput``: the tail (or ``empty_text``) and, when truncated, the notice naming the full output."""+ """Pi's ``formatOutput``: the tail (or ``empty_text``) and, when truncated, the notice naming the full output.++ The truncation is returned whenever a notice was added, which a log bounded on disk always gets.+ """truncation = self.snapshot()text = truncation.content or empty_text- if not truncation.truncated:+ if not truncation.truncated and not self._omitted:return text, None- path = self.path+ # C-7 section 5: a log bounded on disk (J4) is never called the full output.+ label = "Full output"+ if self._omitted:+ label = f"Output log (middle omitted beyond {format_size(job_host.OUTPUT_HEAD_BYTES + job_host.OUTPUT_TAIL_BYTES)})"+ where = f"{label}: {self.path}"start = truncation.total_lines - truncation.output_lines + 1end = truncation.total_lines- if truncation.last_line_partial:+ if not truncation.truncated:+ notice = f"[{where}]"+ elif truncation.last_line_partial:open_line = "" if self._finished else self._normalizer.peek()line_size = format_size(self._accumulator.last_line_bytes(open_line))notice = (- f"[Showing last {format_size(truncation.output_bytes)} of line {end} (line is {line_size}). "- f"Full output: {path}]"+ f"[Showing last {format_size(truncation.output_bytes)} of line {end} (line is {line_size}). {where}]")elif truncation.truncated_by == "lines":- notice = f"[Showing lines {start}-{end} of {truncation.total_lines}. Full output: {path}]"+ notice = f"[Showing lines {start}-{end} of {truncation.total_lines}. {where}]"else:notice = (- f"[Showing lines {start}-{end} of {truncation.total_lines} ({format_size(MAX_BYTES)} limit). "- f"Full output: {path}]"+ f"[Showing lines {start}-{end} of {truncation.total_lines} ({format_size(MAX_BYTES)} limit). {where}]")if self._omitted:# Only LocalJobHost drops output, and it keeps the end in tail.log next to output.log.- notice += (- f"\n[{format_size(self._omitted)} from the middle of the output was not kept on disk: "- "output.log holds the start, tail.log beside it the end.]"- )+ notice += f"\n[{format_size(self._omitted)} were omitted; the end of the log is in tail.log beside it.]"return f"{text}\n\n{notice}", truncationdef details(self, truncation: Optional[TruncationResult]) -> dict[str, Any]:- out: dict[str, Any] = {"job_id": self._job_id, "full_output_path": self.path}+ out: dict[str, Any] = {"job_id": self._job_id, "output_path": self.path}if self._omitted:out["omitted_bytes"] = self._omittedif truncation is not None:diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.pyindex 46eb42c3a..bec97fcac 100644--- a/core/agent_core/tools/paths.py+++ b/core/agent_core/tools/paths.py@@ -8,6 +8,7 @@ Mario Zechner).from __future__ import annotationsimport asyncio+import nturl2pathimport osimport reimport unicodedata@@ -20,6 +21,7 @@ from core.agent_core.tools.args import ToolInputError_UNICODE_SPACES = re.compile("[\u00a0\u2000-\u200a\u202f\u205f\u3000]")_NARROW_NO_BREAK_SPACE = "\u202f"_AM_PM = re.compile(r" (AM|PM)\.", re.IGNORECASE)+_WINDOWS = os.name == "nt"def expand_path(path: str) -> str:@@ -30,10 +32,21 @@ def expand_path(path: str) -> str:if value == "~" or value.startswith("~/"):value = os.path.expanduser(value)if value.startswith("file://"):- value = unquote(urlparse(value).path)+ value = _file_url_to_path(value)return value+def _file_url_to_path(url: str) -> str:+ """Like Node's ``fileURLToPath``: drive letters and UNC hosts on Windows, the path elsewhere."""+ parsed = urlparse(url)+ if not _WINDOWS:+ return unquote(parsed.path)+ path = nturl2path.url2pathname(parsed.path)+ if parsed.netloc and parsed.netloc.lower() != "localhost":+ return f"\\\\{parsed.netloc}{path}"+ return path++def resolve_to_cwd(path: str, cwd: str) -> str:"""The absolute path; raises ``ToolInputError`` for a path no file can have (a NUL byte, possibly from ``%00``)."""expanded = expand_path(path)diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.pyindex bf40d0667..c701d821e 100644--- a/core/agent_core/tools/read.py+++ b/core/agent_core/tools/read.py@@ -23,7 +23,7 @@ from core.agent_core.tools.args import (ToolInputError,error_result,format_number,- optional_number_arg,+ optional_line_arg,os_error_text,str_arg,text_result,@@ -53,8 +53,8 @@ READ_SCHEMA: Mapping[str, Any] = {"required": ["path"],"properties": {"path": {"type": "string", "description": "Path to the file to read (relative or absolute)"},- "offset": {"type": "number", "description": "Line number to start reading from (1-indexed)"},- "limit": {"type": "number", "description": "Maximum number of lines to read"},+ "offset": {"type": "integer", "minimum": 1, "description": "Line number to start reading from (1-indexed)"},+ "limit": {"type": "integer", "minimum": 1, "description": "Maximum number of lines to read"},},}@@ -73,10 +73,8 @@ class ReadTool:return error_result("Operation aborted")try:path = str_arg(arguments, "path")- offset = optional_number_arg(arguments, "offset")- limit = optional_number_arg(arguments, "limit")- if limit is not None and limit < 1:- raise ToolInputError("limit must be at least 1")+ offset = optional_line_arg(arguments, "offset")+ limit = optional_line_arg(arguments, "limit")except ToolInputError as exc:return error_result(str(exc))@@ -149,13 +147,13 @@ def _read_bytes(path: str) -> bytes:def _read_text(- absolute: str, path: str, offset: Optional[float], limit: Optional[float], cancelled: Callable[[], bool]+ absolute: str, path: str, offset: Optional[int], limit: Optional[int], cancelled: Callable[[], bool]) -> ToolResult:- start_line = max(0, int(offset) - 1) if offset else 0- stop_line = start_line + int(limit) if limit is not None else None+ start_line = offset - 1 if offset is not None else 0+ stop_line = start_line + limit if limit is not None else Nonecollected, total_lines, first_line_bytes = _scan_lines(absolute, start_line, stop_line, cancelled)if start_line >= total_lines:- raise ToolInputError(f"Offset {format_number(offset or 0)} is beyond end of file ({total_lines} lines total)")+ raise ToolInputError(f"Offset {offset} is beyond end of file ({total_lines} lines total)")truncation = truncate_head("\n".join(collected))start_display = start_line + 1diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.pyindex a985655b3..519cbe107 100644--- a/core/agent_core/tools/write.py+++ b/core/agent_core/tools/write.py@@ -7,7 +7,10 @@ Ported from Pi ``packages/coding-agent/src/core/tools/write.ts`` (MIT, Copyrightfrom __future__ import annotationsimport asyncio+import contextlibimport os+import stat+import tempfilefrom typing import Any, Mappingfrom core.agent_core.tools.args import ToolInputError, error_result, os_error_text, str_arg, text_result@@ -60,6 +63,37 @@ class WriteTool:def write_text(path: str, content: str) -> None:- """UTF-8 without newline translation; a lone surrogate (possible from JSON) is replaced."""+ """UTF-8 without newline translation; a lone surrogate (possible from JSON) is replaced.++ An existing file is replaced only once the new content is completely on disk, so a failed write+ (a full disk, a quota) leaves the original intact. The replacement goes through symlinks and keeps+ the file's mode.+ """+ target = os.path.realpath(path)+ try:+ mode = stat.S_IMODE(os.stat(target).st_mode)+ except FileNotFoundError:+ _write_file(target, content)+ return+ try:+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(target), prefix=f".{os.path.basename(target)}.", suffix=".tmp")+ except PermissionError:+ # A writable file in a directory we cannot add to: only an in-place write is possible.+ _write_file(target, content)+ return+ try:+ with os.fdopen(fd, "w", encoding="utf-8", errors="replace", newline="") as handle:+ handle.write(content)+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(tmp, mode)+ os.replace(tmp, target)+ except BaseException:+ with contextlib.suppress(FileNotFoundError):+ os.unlink(tmp)+ raise+++def _write_file(path: str, content: str) -> None:with open(path, "w", encoding="utf-8", errors="replace", newline="") as handle:handle.write(content)diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.pyindex 780ef2005..e6a4f0df0 100644--- a/tests/agent_core/tools/test_bash.py+++ b/tests/agent_core/tools/test_bash.py@@ -10,6 +10,7 @@ import psutilfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.tools.bash import BashTool, settle_bash_call+import core.agent_core.tools.jobs as jobs_modulefrom core.agent_core.tools.jobs import LocalJobHostfrom tests.agent_core.tools.conftest import result_text@@ -43,12 +44,26 @@ def _process_gone(pid: int, timeout_s: float = 3.0) -> bool:async def test_long_output_keeps_the_tail_and_names_the_full_output(tmp_path, make_ctx):result = await BashTool(_host(tmp_path)).execute({"command": "seq 1 2500"}, make_ctx())- path = result.details["full_output_path"]+ path = result.details["output_path"]assert not result.is_errorassert result_text(result).endswith(f"2499\n2500\n\n[Showing lines 501-2500 of 2500. Full output: {path}]")assert open(path).read() == "".join(f"{i}\n" for i in range(1, 2501))+async def test_a_log_bounded_on_disk_is_not_called_the_full_output(tmp_path, make_ctx, monkeypatch):+ """J4: the result says the middle is gone instead of promising a complete file."""+ monkeypatch.setattr(jobs_module, "OUTPUT_HEAD_BYTES", 1000)+ monkeypatch.setattr(jobs_module, "OUTPUT_TAIL_BYTES", 2000)++ result = await BashTool(_host(tmp_path)).execute({"command": "seq 1 100000"}, make_ctx())++ text = result_text(result)+ assert text.startswith("1\n2\n3\n")+ assert f"100000\n\n\n[Output log (middle omitted beyond 2.9KB): {result.details['output_path']}]" in text+ assert "Full output" not in text+ assert result.details["omitted_bytes"] == len("".join(f"{i}\n" for i in range(1, 100001))) - 3000++async def test_a_non_zero_exit_is_an_error_result(tmp_path, make_ctx):result = await BashTool(_host(tmp_path)).execute({"command": "echo oops >&2; exit 3"}, make_ctx())@@ -56,6 +71,13 @@ async def test_a_non_zero_exit_is_an_error_result(tmp_path, make_ctx):assert result_text(result) == "oops\n\n\nCommand exited with code 3"+async def test_an_out_of_range_timeout_is_an_error_result(tmp_path, make_ctx):+ result = await BashTool(_host(tmp_path)).execute({"command": "true", "timeout": 10**400}, make_ctx())++ assert result.is_error+ assert result_text(result) == "Invalid timeout: must be a finite number of seconds"++async def test_stdin_is_closed(tmp_path, make_ctx):started = time.monotonic()result = await BashTool(_host(tmp_path)).execute({"command": 'read x; echo "rc=$?"'}, make_ctx())diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.pyindex 98f33b432..5fd918381 100644--- a/tests/agent_core/tools/test_read.py+++ b/tests/agent_core/tools/test_read.py@@ -58,6 +58,16 @@ async def test_offset_beyond_the_end_is_an_error(tmp_path, make_ctx):assert result_text(result) == "Offset 5 is beyond end of file (2 lines total)"[email protected](("arguments", "message"), [({"offset": 0}, "offset"), ({"limit": 2.5}, "limit")])+async def test_offset_and_limit_are_integers_of_at_least_one(tmp_path, make_ctx, arguments, message):+ (tmp_path / "ten.txt").write_text("a\nb\n")++ result = await _read(make_ctx, path="ten.txt", **arguments)++ assert result.is_error+ assert result_text(result) == f"{message} must be an integer of at least 1"++async def test_an_over_long_first_line_points_at_bash(tmp_path, make_ctx):(tmp_path / "big file.txt").write_text("short\n" + "x" * 61_440 + "\nafter\n")diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex a9d2352f7..930734a78 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -2,8 +2,14 @@from __future__ import annotations+import errno+import stat+import pytest+import core.agent_core.tools.paths as paths_module+import core.agent_core.tools.write as write_module+from core.agent_core.tools.edit import EditToolfrom core.agent_core.tools.read import ReadToolfrom core.agent_core.tools.write import WriteTool@@ -18,6 +24,34 @@ async def test_write_creates_parent_directories_and_keeps_bytes(tmp_path, make_cassert (tmp_path / "a/b/notes.txt").read_bytes() == "第一行\r\nsecond\n".encode()+async def test_a_failed_write_leaves_the_original_intact(tmp_path, make_ctx, monkeypatch):+ (tmp_path / "f.txt").write_text("original\n")++ def disk_full(fd):+ raise OSError(errno.ENOSPC, "No space left on device")++ monkeypatch.setattr(write_module.os, "fsync", disk_full)+ result = await WriteTool().execute({"path": "f.txt", "content": "replacement\n"}, make_ctx())++ assert result.is_error+ assert (tmp_path / "f.txt").read_text() == "original\n"+ assert sorted(p.name for p in tmp_path.iterdir()) == ["f.txt"]+++async def test_write_goes_through_a_symlink_and_keeps_the_mode(tmp_path, make_ctx):+ target = tmp_path / "real.sh"+ target.write_text("old\n")+ target.chmod(0o751)+ (tmp_path / "link.sh").symlink_to(target)++ result = await WriteTool().execute({"path": "link.sh", "content": "new\n"}, make_ctx())++ assert not result.is_error, result_text(result)+ assert (tmp_path / "link.sh").is_symlink()+ assert target.read_text() == "new\n"+ assert stat.S_IMODE(target.stat().st_mode) == 0o751++async def _edit(make_ctx, path, *edits, **extra):return await EditTool().execute({"path": path, "edits": list(edits), **extra}, make_ctx())@@ -78,6 +112,56 @@ async def test_an_exact_match_is_unique_even_with_a_normalized_twin(tmp_path, maassert (tmp_path / "f.txt").read_text() == 'say "Hello"\nsay \u201cHi\u201d\n'+L, R = "\u201c", "\u201d" # smart double quotes+++ ("original", "edits", "expected"),+ [+ # An exact replaceAll beside a normalized edit replaces only exact occurrences.+ (+ f'say "A"\nsay {L}A{R}\ntitle = {L}T{R} \n',+ [+ {"oldText": 'say "A"', "newText": 'say "B"', "replaceAll": True},+ {"oldText": 'title = "T"', "newText": 'title = "U"'},+ ],+ f'say "B"\nsay {L}A{R}\ntitle = "U"\n',+ ),+ # An exact edit stays unique beside a normalized edit, though their normalized forms collide.+ (+ f'x = "1"\nx = {L}1{R}\ny = \u20182\u2019 \n',+ [{"oldText": 'x = "1"', "newText": 'x = "9"'}, {"oldText": "y = '2'", "newText": "y = '3'"}],+ f"x = \"9\"\nx = {L}1{R}\ny = '3'\n",+ ),+ # replaceAll uses the first tier with a match: exact occurrences only.+ (+ f'a = {L}q{R}\nc = "q"\n',+ [{"oldText": '= "q"', "newText": '= "r"', "replaceAll": True}],+ f'a = {L}q{R}\nc = "r"\n',+ ),+ # With no exact occurrence, every normalized occurrence is rewritten, line by line.+ (+ f"a = {L}q{R} \nkeep \u2014 me \nb = {L}q{R}\n",+ [{"oldText": '= "q"', "newText": '= "r"', "replaceAll": True}],+ 'a = "r"\nkeep \u2014 me \nb = "r"\n',+ ),+ # Two normalized edits on one line apply together.+ (+ f"k = {L}v{R}; j = {L}w{R}\n",+ [{"oldText": 'k = "v"', "newText": 'k = "1"'}, {"oldText": 'j = "w"', "newText": 'j = "2"'}],+ 'k = "1"; j = "2"\n',+ ),+ ],+)+async def test_each_edit_matches_in_its_own_tier(tmp_path, make_ctx, original, edits, expected):+ (tmp_path / "f.txt").write_text(original)++ result = await _edit(make_ctx, "f.txt", *edits)++ assert not result.is_error, result_text(result)+ assert (tmp_path / "f.txt").read_text() == expected++@pytest.mark.parametrize(("edits", "message"),[@@ -115,6 +199,11 @@ async def test_an_exact_match_is_unique_even_with_a_normalized_twin(tmp_path, ma[{"oldText": "dup", "newText": "x", "replaceAll": True}, {"oldText": "dup two", "newText": "y"}],"edits[0] and edits[1] overlap in f.txt. Merge them into one edit or target disjoint regions.",),+ (+ # A normalized edit rewrites its whole line, so an exact edit on that line overlaps it.+ [{"oldText": "alpha", "newText": "A"}, {"oldText": "beta ", "newText": "B"}],+ "edits[0] and edits[1] overlap in f.txt. Merge them into one edit or target disjoint regions.",+ ),([{"oldText": "alpha", "newText": "A"}, {"oldText": "", "newText": "x"}],"edits[1].oldText must not be empty in f.txt.",@@ -145,3 +234,13 @@ async def test_a_path_no_file_can_have_is_an_error_result(make_ctx, tool, argumeassert result.is_errorassert result_text(result) == f"Invalid path: {arguments['path']!r} contains a NUL byte"+++ ("url", "path"),+ [("file:///C:/tmp/a%20b.txt", "C:\\tmp\\a b.txt"), ("file://server/share/x.txt", "\\\\server\\share\\x.txt")],+)+def test_windows_file_urls_keep_drive_and_share(monkeypatch, url, path):+ monkeypatch.setattr(paths_module, "_WINDOWS", True)++ assert paths_module.expand_path(url) == path