diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index d522da779..a161fb235 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -11,7 +11,7 @@ from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable from copy import deepcopy -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any, cast @@ -200,6 +200,7 @@ class ModelRequestState: tool_definitions: list[dict[str, Any]] | None = None compaction: ContextCompactionState | None = None provider_compaction_applied: bool = False + compacted_tool_results: set[str] = field(default_factory=set) events: EventSink = NO_EVENTS @@ -444,6 +445,19 @@ class ContextGovernor: ) -> None: """Materialize the exact input replaced by provider-native compaction.""" compaction = state.compaction + if response.provider_compaction_applied: + # Native compaction can omit results while the local transcript keeps + # their full text. They no longer prove what the model can read. + replaced_messages = ( + compaction.accepted_messages + if response.provider_compaction_scope == "prior_context" and compaction is not None + else state.messages or [] + ) + state.compacted_tool_results.update( + message["tool_call_id"] for message in replaced_messages + if message.get("role") == "tool" + and isinstance(message.get("tool_call_id"), str) + ) if ( not response.provider_compaction_applied or response.provider_compaction_state is None diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 9688c6080..bfcdcdb54 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -517,6 +517,8 @@ class AgentRunner: workspace_violation_counts=workspace_violation_counts, hook=hook, context=context, + model_messages=messages_for_model, + compacted_tool_results=request_state.compacted_tool_results, ) tool_events.extend(new_events) tools_used.extend( diff --git a/nanobot/agent/tools/execution.py b/nanobot/agent/tools/execution.py index f26f872ef..7ec3b71dc 100644 --- a/nanobot/agent/tools/execution.py +++ b/nanobot/agent/tools/execution.py @@ -4,11 +4,14 @@ from __future__ import annotations import asyncio from collections.abc import Callable +from contextlib import nullcontext +from functools import cache from typing import Any, cast from loguru import logger from nanobot.agent.hook import AgentHook, AgentHookContext +from nanobot.agent.tools.file_state import file_read_context from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result from nanobot.providers.base import ToolCallRequest from nanobot.utils.runtime import ( @@ -59,8 +62,21 @@ async def execute_tool_calls( workspace_violation_counts: dict[str, int], hook: AgentHook, context: AgentHookContext, + model_messages: list[dict[str, Any]] | None = None, + compacted_tool_results: set[str] | None = None, ) -> tuple[list[Any], list[dict[str, str]]]: """Execute one model response's tool calls in stable result order.""" + @cache + def read_results() -> dict[str, str]: + """Index once, on the first read-dedup check in this batch.""" + return { + message["tool_call_id"]: message["content"] + for message in model_messages or [] + if message.get("role") == "tool" + and isinstance(message.get("tool_call_id"), str) + and isinstance(message.get("content"), str) + and message["tool_call_id"] not in (compacted_tool_results or ()) + } tool_results: list[tuple[Any, dict[str, str]]] = [] for batch in _partition_tool_batches(tools, tool_calls, concurrent=concurrent): if concurrent and len(batch) > 1: @@ -72,6 +88,7 @@ async def execute_tool_calls( workspace_violation_counts, hook, context, + read_results, ) for tool_call in batch )) @@ -85,6 +102,7 @@ async def execute_tool_calls( workspace_violation_counts, hook, context, + read_results, ) tool_results.append(result) @@ -100,6 +118,7 @@ async def _execute_tool_call( workspace_violation_counts: dict[str, int], hook: AgentHook, context: AgentHookContext, + read_results: Callable[[], dict[str, str]], ) -> tuple[Any, dict[str, str]]: lookup_error = repeated_external_lookup_error( tool_call.name, @@ -145,10 +164,14 @@ async def _execute_tool_call( await hook.before_execute_tool(context, tool_call, tool, params) try: - if tool is not None: - result = await tool.execute(**params) - else: - result = await tools.execute(tool_call.name, params) + with ( + file_read_context(tool_call.id, read_results) + if tool_call.name == "read_file" else nullcontext() + ): + if tool is not None: + result = await tool.execute(**params) + else: + result = await tools.execute(tool_call.name, params) except asyncio.CancelledError: raise except Exception as exc: diff --git a/nanobot/agent/tools/file_state.py b/nanobot/agent/tools/file_state.py index 47198bf41..bb60a5faa 100644 --- a/nanobot/agent/tools/file_state.py +++ b/nanobot/agent/tools/file_state.py @@ -1,22 +1,46 @@ -"""Track file-read state for read-before-edit warnings and read deduplication.""" +"""Track file reads whose original results may still be in model context.""" from __future__ import annotations import hashlib -import os from collections import OrderedDict +from collections.abc import Callable, Generator, Mapping +from contextlib import contextmanager from contextvars import ContextVar, Token from dataclasses import dataclass from pathlib import Path +@dataclass(frozen=True) +class _FileReadContext: + call_id: str + tool_results: Callable[[], Mapping[str, str]] + + +_current_file_read: ContextVar[_FileReadContext | None] = ContextVar( + "nanobot_file_read_context", default=None, +) + + +@contextmanager +def file_read_context( + call_id: str, tool_results: Callable[[], Mapping[str, str]], +) -> Generator[None]: + """Bind one file read; resolve visible results only when checking a prior read.""" + token = _current_file_read.set(_FileReadContext(call_id, tool_results)) + try: + yield + finally: + _current_file_read.reset(token) + + @dataclass(slots=True) class ReadState: - mtime: float offset: int limit: int | None content_hash: str | None - can_dedup: bool + call_id: str | None + result_hash: str | None def _hash_file(p: str) -> str | None: @@ -27,101 +51,50 @@ def _hash_file(p: str) -> str | None: class FileStates: - """Per-session read/write tracker. - - Owns its own state dict so read-dedup ("File unchanged since last read") - and read-before-edit warnings stay scoped to one agent session and do - not leak across sessions sharing this process. - """ + """Cache read receipts per session; deduplicate only while their results are visible.""" __slots__ = ("_state",) def __init__(self) -> None: self._state: dict[str, ReadState] = {} - def record_read(self, path: str | Path, offset: int = 1, limit: int | None = None) -> None: - """Record that a file was read (called after successful read).""" + def record_read( + self, path: str | Path, offset: int = 1, limit: int | None = None, *, + content_hash: str | None = None, result: str | None = None, + ) -> None: + """Record the file snapshot and complete result of a successful text read.""" p = str(Path(path).resolve()) - try: - mtime = os.path.getmtime(p) - except OSError: - return + context = _current_file_read.get() self._state[p] = ReadState( - mtime=mtime, offset=offset, limit=limit, - content_hash=_hash_file(p), - can_dedup=True, + content_hash=content_hash if content_hash is not None else _hash_file(p), + call_id=context.call_id if context is not None else None, + result_hash=hashlib.sha256(result.encode("utf-8")).hexdigest() if result else None, ) def record_write(self, path: str | Path) -> None: - """Record that a file was written (updates mtime in state).""" - p = str(Path(path).resolve()) - try: - mtime = os.path.getmtime(p) - except OSError: - self._state.pop(p, None) - return - self._state[p] = ReadState( - mtime=mtime, - offset=1, - limit=None, - content_hash=_hash_file(p), - can_dedup=False, - ) + """Invalidate a prior read after a write; a write summary is not file content.""" + self._state.pop(str(Path(path).resolve()), None) - def check_read(self, path: str | Path) -> str | None: - """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), - the check passes to avoid false-positive staleness warnings. - """ + def is_unchanged( + self, path: str | Path, offset: int = 1, limit: int | None = None, *, + content_hash: str | None = None, + ) -> bool: + """Check both file identity and the original result in the actual model input.""" p = str(Path(path).resolve()) entry = self._state.get(p) - if entry is None: - # Shell reads and content already in context may not be recorded here. - return None - try: - current_mtime = os.path.getmtime(p) - except OSError: - return None - if current_mtime != entry.mtime: - if entry.content_hash and _hash_file(p) == entry.content_hash: - entry.mtime = current_mtime - return None - 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 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: - """Return True if file was previously read with same params and content is unchanged.""" - p = str(Path(path).resolve()) - entry = self._state.get(p) - if entry is None: - return False - if not entry.can_dedup: + context = _current_file_read.get() + if entry is None or context is None or not entry.call_id or not entry.result_hash: return False if entry.offset != offset or entry.limit != limit: return False - try: - current_mtime = os.path.getmtime(p) - except OSError: + result = context.tool_results().get(entry.call_id) + if result is None or hashlib.sha256(result.encode("utf-8")).hexdigest() != entry.result_hash: + self._state.pop(p, None) return False - if current_mtime != entry.mtime: - # mtime changed - check if content also changed - current_hash = _hash_file(p) - if current_hash != entry.content_hash: - # Content actually changed - don't dedup - entry.can_dedup = False - return False - # Content identical despite mtime change (e.g. touch) - mark as not dedupable to force full read next time - entry.can_dedup = False - return True - # mtime unchanged - content must be identical - return True + current_hash = content_hash if content_hash is not None else _hash_file(p) + return current_hash is not None and current_hash == entry.content_hash def get(self, path: str | Path) -> ReadState | None: """Return the raw ReadState entry for a path, or None.""" @@ -199,10 +172,6 @@ def record_write(path: str | Path) -> None: _default.record_write(path) -def check_read(path: str | Path) -> str | None: - return _default.check_read(path) - - def is_unchanged(path: str | Path, offset: int = 1, limit: int | None = None) -> bool: return _default.is_unchanged(path, offset=offset, limit=limit) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index c6dcbf971..7a2ae142f 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -3,15 +3,15 @@ # pyright: reportPrivateUsage=false, reportUnusedFunction=false import difflib +import hashlib import mimetypes -import os from dataclasses import dataclass from pathlib import Path from typing import Any from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters from nanobot.agent.tools.context import ToolContext -from nanobot.agent.tools.file_state import FileStates, _hash_file, current_file_states +from nanobot.agent.tools.file_state import FileStates, current_file_states from nanobot.agent.tools.path_utils import resolve_workspace_path from nanobot.agent.tools.schema import ( BooleanSchema, @@ -343,44 +343,11 @@ class ReadFileTool(_FsTool): if mime and mime.startswith("image/"): return build_image_content_blocks(raw, mime, str(fp), f"(Image file: {path})") - # Read dedup: same path + offset + limit + unchanged mtime → stub - # Always check for external modifications before dedup - entry = self._file_states.get(fp) - try: - current_mtime = os.path.getmtime(fp) - except OSError: - current_mtime = 0.0 - if ( - not force - and entry - and entry.can_dedup - and entry.offset == offset - and entry.limit == limit + content_hash = hashlib.sha256(raw).hexdigest() + if not force and self._file_states.is_unchanged( + fp, offset=offset, limit=limit, content_hash=content_hash, ): - if current_mtime != entry.mtime: - # File was modified externally - force full read and mark as not dedupable - entry.can_dedup = False - self._file_states.record_read(fp, offset=offset, limit=limit) # Update state with new mtime - # Continue to read full content (don't return dedup message) - else: - # File unchanged - return dedup message - # But only if content is actually unchanged (not just mtime) - current_hash = _hash_file(str(fp)) - if current_hash == entry.content_hash: - return f"[File unchanged since last read: {path}]" - else: - # Content changed despite same mtime - force full read - entry.can_dedup = False - self._file_states.record_read(fp, offset=offset, limit=limit) - else: - # No previous state or marked as not dedupable - read full content - self._file_states.record_read(fp, offset=offset, limit=limit) - # Force full read by setting can_dedup to False for this read - if entry: - entry.can_dedup = False - - # Read the file content after dedup check - raw = fp.read_bytes() + return f"[File unchanged since last read: {path}]" try: text_content = raw.decode("utf-8") except UnicodeDecodeError: @@ -438,7 +405,9 @@ class ReadFileTool(_FsTool): result += f"\n\n(Showing lines {offset}-{end} of {total}. Use offset={end + 1} to continue.)" else: result += f"\n\n(End of file — {total} lines total)" - self._file_states.record_read(fp, offset=offset, limit=limit) + self._file_states.record_read( + fp, offset=offset, limit=limit, content_hash=content_hash, result=result, + ) return result except PermissionError as e: return ToolResult.error(f"Error: {e}") @@ -914,7 +883,7 @@ class EditFileTool(_FsTool): def _format_summary( self, resolved_path: Path, before: str, after: str, *, - created: bool = False, warning: str | None = None, + created: bool = False, ) -> FileEditResult: diff = FileDiff.from_text(before, after) added, deleted = diff.added, diff.deleted @@ -922,8 +891,6 @@ class EditFileTool(_FsTool): 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( @@ -978,9 +945,6 @@ class EditFileTool(_FsTool): self._file_states.record_write(fp) return self._format_summary(fp, content, fp.read_bytes().decode("utf-8")) - # Read-before-edit check - warning = self._file_states.check_read(fp) - raw = fp.read_bytes() uses_crlf = b"\r\n" in raw content = raw.decode("utf-8").replace("\r\n", "\n") @@ -1069,7 +1033,7 @@ class EditFileTool(_FsTool): fp.write_bytes(new_content.encode("utf-8")) self._file_states.record_write(fp) - return self._format_summary(fp, content, new_content, warning=warning) + return self._format_summary(fp, content, new_content) except PermissionError as e: return ToolResult.error(f"Error: {e}") except Exception as e: diff --git a/tests/agent/test_agent_plugins.py b/tests/agent/test_agent_plugins.py index 6e23206bb..c8470b8c1 100644 --- a/tests/agent/test_agent_plugins.py +++ b/tests/agent/test_agent_plugins.py @@ -253,7 +253,7 @@ async def test_restricted_project_can_read_only_enabled_plugin_skill( reset_workspace_scope(token) assert "plugin reference" in read_result - assert "File unchanged since last read" in repeated_read_result + assert repeated_read_result == read_result assert activation_checks == 1 assert "outside allowed directory" in write_result assert "outside allowed directory" in disabled_result diff --git a/tests/agent/test_runner_file_reads.py b/tests/agent/test_runner_file_reads.py new file mode 100644 index 000000000..73131d400 --- /dev/null +++ b/tests/agent/test_runner_file_reads.py @@ -0,0 +1,258 @@ +"""File-read deduplication follows the model request, including context rewrites.""" + +import asyncio +from copy import deepcopy +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from agent.runner_helpers import make_run_spec +from nanobot.agent.context import TranscriptInput +from nanobot.agent.hook import AgentHook, AgentHookContext +from nanobot.agent.runner import AgentRunner +from nanobot.agent.tools.execution import execute_tool_calls +from nanobot.agent.tools.file_state import FileStates, bind_file_states, reset_file_states +from nanobot.agent.tools.filesystem import ListDirTool, ReadFileTool +from nanobot.agent.tools.registry import ToolRegistry +from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest + + +def _tools(tmp_path): + (tmp_path / "data.txt").write_text("alpha\nbeta\n", encoding="utf-8") + tools = ToolRegistry() + tools.register(ReadFileTool(workspace=tmp_path)) + return tools + + +async def _read(tools, call_id, history=None, **kwargs): + provider = MagicMock(spec=LLMProvider) + requests = [] + + async def request(*, messages, **_kwargs): + requests.append(deepcopy(messages)) + if len(requests) == 1: + return LLMResponse(content=None, tool_calls=[ + ToolCallRequest(id=call_id, name="read_file", arguments={"path": "data.txt"}), + ]) + return LLMResponse(content="done") + + provider.chat_stream_with_retry = request + initial = None if "transcript_input" in kwargs else [ + *(history or []), {"role": "user", "content": "Read data.txt again."}, + ] + result = await AgentRunner().run(make_run_spec( + provider, model="test-model", tools=tools, initial_messages=initial, + max_iterations=2, max_tool_result_chars=128_000, **kwargs, + )) + observation = next( + message["content"] for message in result.messages + if message.get("role") == "tool" and message.get("tool_call_id") == call_id + ) + return result, observation, requests + + +@pytest.mark.parametrize("retained", ["original", "summary", "truncated", "stub_only", "orphan"]) +async def test_repeat_requires_original_read_result_in_current_context(tmp_path, retained): + tools = _tools(tmp_path) + first, contents, _ = await _read(tools, "read-1") + second, stub, _ = await _read(tools, "read-2", first.messages) + assert "1| alpha" in contents + assert stub == "[File unchanged since last read: data.txt]" + + history = deepcopy(second.messages) + if retained == "summary": + history = [{"role": "user", "content": "Summary: data.txt contains alpha and beta."}] + elif retained == "truncated": + for message in history: + if message.get("tool_call_id") == "read-1": + message["content"] = "1| alpha\n[truncated]" + elif retained in {"stub_only", "orphan"}: + history = [ + message for message in history + if not any(call["id"] == "read-1" for call in message.get("tool_calls", [])) + and (retained == "orphan" or message.get("tool_call_id") != "read-1") + ] + + _, repeated, _ = await _read(tools, "read-3", history) + assert repeated == (stub if retained == "original" else contents) + + +@pytest.mark.parametrize("rewrite", ["compact", "snip"]) +async def test_dedup_uses_governed_request_instead_of_raw_transcript(tmp_path, monkeypatch, rewrite): + tools = _tools(tmp_path) + first, contents, _ = await _read(tools, "read-1") + + def estimate(_provider, _model, messages, _tools): + contains_original = any(message.get("tool_call_id") == "read-1" for message in messages) + return (600 if contains_original else 100), "test-counter" + + monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate) + monkeypatch.setattr("nanobot.agent.context_governance.estimate_message_tokens", lambda _: 300) + consolidate = AsyncMock(return_value="The file was inspected; its original text was omitted.") + + def build(transcript): + system = transcript.session_summary["text"] if transcript.session_summary else "system" + messages = [{"role": "system", "content": system}, *transcript.history] + if transcript.current_message is not None: + messages.append({"role": "user", "content": transcript.current_message}) + return messages + + options = {} + if rewrite == "compact": + options = { + "transcript_input": TranscriptInput( + history=first.messages, current_message="Read data.txt again.", + ), + "transcript_builder": build, + "consolidate_history": consolidate, + } + result, repeated, requests = await _read( + tools, "read-2", first.messages, context_window_tokens=1_624, max_tokens=100, **options, + ) + + assert any(message.get("tool_call_id") == "read-1" for message in result.messages) + assert not any(message.get("tool_call_id") == "read-1" for message in requests[0]) + assert repeated == contents + if rewrite == "compact": + consolidate.assert_awaited_once() + assert result.summary_checkpoint is not None + + +async def test_direct_read_without_model_context_never_omits_contents(tmp_path): + tools = _tools(tmp_path) + first = await tools.execute("read_file", {"path": "data.txt"}) + second = await tools.execute("read_file", {"path": "data.txt"}) + assert second == first + assert "1| alpha" in second + + +@pytest.mark.parametrize("operation", ["list_dir", "first_read", "forced_read", "repeat_batch"]) +async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, operation): + tools = _tools(tmp_path) + tools.register(ListDirTool(workspace=tmp_path)) + first, contents, _ = await _read(tools, "read-1") + + class CountedMessages(list): + scans = 0 + + def __iter__(self): + self.scans += 1 + return super().__iter__() + + messages = CountedMessages(first.messages) + name, arguments = "read_file", {"path": "data.txt"} + if operation == "list_dir": + name, arguments = "list_dir", {"path": "."} + elif operation == "first_read": + (tmp_path / "fresh.txt").write_text("alpha\nbeta\n", encoding="utf-8") + arguments = {"path": "fresh.txt"} + elif operation == "forced_read": + arguments["force"] = True + calls = [ToolCallRequest(id="batch-1", name=name, arguments=arguments)] + if operation == "repeat_batch": + calls.append(ToolCallRequest(id="batch-2", name=name, arguments=arguments)) + + results, _ = await execute_tool_calls( + tools, calls, concurrent=True, external_lookup_counts={}, workspace_violation_counts={}, + hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]), + model_messages=messages, + ) + + if operation == "repeat_batch": + assert results == ["[File unchanged since last read: data.txt]"] * 2 + assert messages.scans == 1 + else: + assert messages.scans == 0 + if operation == "list_dir": + assert "data.txt" in results[0] + else: + assert results == [contents] + # A later direct read has no model input proving that its contents are visible. + assert await tools.execute("read_file", {"path": "data.txt"}) == contents + + +@pytest.mark.parametrize("error", [RuntimeError, asyncio.CancelledError]) +async def test_failed_file_read_restores_context(tmp_path, monkeypatch, error): + tools = _tools(tmp_path) + first, contents, _ = await _read(tools, "read-1") + tool = tools.get("read_file") + original_execute = tool.execute + + async def fail(**_kwargs): + raise error("read interrupted") + + monkeypatch.setattr(tool, "execute", fail) + request = execute_tool_calls( + tools, [ToolCallRequest(id="failed-read", name="read_file", arguments={"path": "data.txt"})], + concurrent=False, external_lookup_counts={}, workspace_violation_counts={}, + hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]), + model_messages=first.messages, + ) + if error is asyncio.CancelledError: + with pytest.raises(asyncio.CancelledError): + await request + else: + results, _ = await request + assert results[0].startswith("Error: RuntimeError: read interrupted") + + monkeypatch.setattr(tool, "execute", original_execute) + assert await tools.execute("read_file", {"path": "data.txt"}) == contents + + +async def test_native_compaction_invalidates_old_results_but_new_reads_can_dedup(tmp_path): + tools = _tools(tmp_path) + provider = MagicMock(spec=LLMProvider) + requests = [] + + async def request(*, messages, **_kwargs): + requests.append(deepcopy(messages)) + if len(requests) <= 3: + return LLMResponse( + content=None, + tool_calls=[ToolCallRequest( + id=f"read-{len(requests)}", name="read_file", arguments={"path": "data.txt"}, + )], + provider_compaction_applied=len(requests) == 2, + provider_compaction_scope="current_request" if len(requests) == 2 else None, + ) + return LLMResponse(content="done") + + provider.chat_stream_with_retry = request + result = await AgentRunner().run(make_run_spec( + provider, model="test-model", tools=tools, + initial_messages=[{"role": "user", "content": "Read data.txt."}], + max_iterations=4, max_tool_result_chars=128_000, + )) + observations = [message["content"] for message in result.messages if message.get("role") == "tool"] + assert "1| alpha" in observations[0] + assert observations[1] == observations[0] + assert observations[2] == "[File unchanged since last read: data.txt]" + assert any(message.get("tool_call_id") == "read-1" for message in requests[2]) + + +async def test_concurrent_sessions_keep_separate_read_contexts(tmp_path, monkeypatch): + tools = _tools(tmp_path) + session_a, session_b = FileStates(), FileStates() + + async def session_read(states, call_id, history=None): + token = bind_file_states(states) + try: + return await _read(tools, call_id, history) + finally: + reset_file_states(token) + + first, contents, _ = await session_read(session_a, "read-a1") + tool = tools.get("read_file") + execute = tool.execute + + async def interleave(**kwargs): + await asyncio.sleep(0) + return await execute(**kwargs) + + monkeypatch.setattr(tool, "execute", interleave) + (_, repeated, _), (_, other_session, _) = await asyncio.gather( + session_read(session_a, "read-a2", first.messages), + session_read(session_b, "read-b1"), + ) + assert repeated == "[File unchanged since last read: data.txt]" + assert other_session == contents diff --git a/tests/tools/test_edit_enhancements.py b/tests/tools/test_edit_enhancements.py index 4a4d324ac..fbf08b43c 100644 --- a/tests/tools/test_edit_enhancements.py +++ b/tests/tools/test_edit_enhancements.py @@ -1,4 +1,4 @@ -"""Tests for EditFileTool enhancements: read-before-edit tracking, path suggestions, +"""Tests for EditFileTool enhancements: read-independent editing, path suggestions, notebook JSON editing, and create-file semantics.""" import os @@ -22,11 +22,11 @@ def _clear_file_state(): # --------------------------------------------------------------------------- -# Read-before-edit tracking +# Read-independent editing # --------------------------------------------------------------------------- class TestEditReadTracking: - """edit_file warns only when a recorded file version has changed.""" + """edit_file validates current contents independently of prior reads.""" @pytest.fixture() def file_states(self): @@ -58,7 +58,7 @@ class TestEditReadTracking: assert f.read_text() == "hello earth" @pytest.mark.asyncio - @pytest.mark.parametrize("reread", [False, True]) + @pytest.mark.parametrize("reread", ["none", "read_file", "shell"]) async def test_edit_after_file_modified_since_read( self, read_tool, edit_tool, tmp_path, reread, ): @@ -69,14 +69,20 @@ class TestEditReadTracking: mtime = f.stat().st_mtime f.write_text("hello universe", encoding="utf-8") os.utime(f, (mtime + 2, mtime + 2)) - if reread: + if reread == "read_file": assert "hello universe" in await read_tool.execute(path=str(f)) + elif reread == "shell": + import subprocess + import sys + + read = subprocess.run( + [sys.executable, "-c", "from pathlib import Path; import sys; print(Path(sys.argv[1]).read_text())", str(f)], + capture_output=True, text=True, check=True, + ) + assert read.stdout.strip() == "hello universe" result = await edit_tool.execute(path=str(f), old_text="universe", new_text="earth") summary = "Patch applied:\n- update a.py (+1/-1)" - assert result == ( - summary if reread - else "Warning: file was modified since the last recorded read or write.\n" + summary - ) + assert result == summary assert f.read_text() == "hello earth" diff --git a/tests/tools/test_file_edit_coding_enhancements.py b/tests/tools/test_file_edit_coding_enhancements.py index 26c0ca75f..c9d69f905 100644 --- a/tests/tools/test_file_edit_coding_enhancements.py +++ b/tests/tools/test_file_edit_coding_enhancements.py @@ -2,6 +2,7 @@ from __future__ import annotations import asyncio +from nanobot.agent.tools.file_state import file_read_context from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool @@ -10,9 +11,11 @@ def test_read_file_force_bypasses_dedup(tmp_path): target.write_text("alpha\n") tool = ReadFileTool(workspace=tmp_path) - first = asyncio.run(tool.execute(path=str(target))) - second = asyncio.run(tool.execute(path=str(target))) - forced = asyncio.run(tool.execute(path=str(target), force=True)) + with file_read_context("read-1", lambda: {}): + first = asyncio.run(tool.execute(path=str(target))) + with file_read_context("read-2", lambda: {"read-1": first}): + second = asyncio.run(tool.execute(path=str(target))) + forced = asyncio.run(tool.execute(path=str(target), force=True)) assert "alpha" in first assert "unchanged" in second.lower() diff --git a/tests/tools/test_read_enhancements.py b/tests/tools/test_read_enhancements.py index 0a4ab0768..7e5b9264e 100644 --- a/tests/tools/test_read_enhancements.py +++ b/tests/tools/test_read_enhancements.py @@ -46,7 +46,7 @@ class TestReadDescriptionFix: # --------------------------------------------------------------------------- class TestReadDedup: - """Same file + same offset/limit + unchanged mtime -> short stub.""" + """Only reads whose original result remains in context may return a stub.""" @pytest.fixture() def tool(self, tmp_path): @@ -60,9 +60,11 @@ class TestReadDedup: async def test_second_read_returns_unchanged_stub(self, tool, tmp_path): f = tmp_path / "data.txt" f.write_text("\n".join(f"line {i}" for i in range(100)), encoding="utf-8") - first = await tool.execute(path=str(f)) + with file_state.file_read_context("read-1", lambda: {}): + first = await tool.execute(path=str(f)) assert "line 0" in first - second = await tool.execute(path=str(f)) + with file_state.file_read_context("read-2", lambda: {"read-1": first}): + second = await tool.execute(path=str(f)) assert "unchanged" in second.lower() # Stub should not contain file content assert "line 0" not in second @@ -71,18 +73,22 @@ class TestReadDedup: async def test_read_after_external_modification_returns_full(self, tool, tmp_path): f = tmp_path / "data.txt" f.write_text("original", encoding="utf-8") - await tool.execute(path=str(f)) + with file_state.file_read_context("read-1", lambda: {}): + first = await tool.execute(path=str(f)) # Modify the file externally f.write_text("modified content", encoding="utf-8") - second = await tool.execute(path=str(f)) + with file_state.file_read_context("read-2", lambda: {"read-1": first}): + second = await tool.execute(path=str(f)) assert "modified content" in second @pytest.mark.asyncio async def test_different_offset_returns_full(self, tool, tmp_path): f = tmp_path / "data.txt" f.write_text("\n".join(f"line {i}" for i in range(1, 21)), encoding="utf-8") - await tool.execute(path=str(f), offset=1, limit=5) - second = await tool.execute(path=str(f), offset=6, limit=5) + with file_state.file_read_context("read-1", lambda: {}): + first = await tool.execute(path=str(f), offset=1, limit=5) + with file_state.file_read_context("read-2", lambda: {"read-1": first}): + second = await tool.execute(path=str(f), offset=6, limit=5) # Different offset → full read, not stub assert "line 6" in second @@ -121,8 +127,8 @@ class TestReadDedup: # --------------------------------------------------------------------------- # Each session must keep its own read cache. When session A reads a file, # session B reading the same file must still receive the full content, not -# the "[File unchanged since last read]" dedup stub. The stub is only valid -# within the session that first cached the read. +# the "[File unchanged since last read]" dedup stub. Within each session, +# the original result must also remain in the current model context. class TestReadDedupSessionIsolation: @@ -159,8 +165,10 @@ class TestReadDedupSessionIsolation: token = file_state.bind_file_states(session_a) try: - first = await shared_tool.execute(path=str(f)) - repeat = await shared_tool.execute(path=str(f)) + with file_state.file_read_context("read-a1", lambda: {}): + first = await shared_tool.execute(path=str(f)) + with file_state.file_read_context("read-a2", lambda: {"read-a1": first}): + repeat = await shared_tool.execute(path=str(f)) finally: file_state.reset_file_states(token) @@ -285,35 +293,29 @@ class TestReadDeviceBlacklist: # --------------------------------------------------------------------------- -# file_state: mtime-unchanged / content-changed fallback +# File changes with preserved mtime # --------------------------------------------------------------------------- -# On filesystems with coarse mtime resolution (NTFS ~100ms, FAT 2s) a fast -# write-after-read can leave mtime unchanged. The content-hash fallback is -# what protects against stale-read warnings being false-negative on those -# platforms. Lock that behavior down here so nobody reverts it silently. +# An editor can preserve mtime while replacing contents. Deduplication must +# compare the file snapshot even when the original result remains in context. class TestFileStateHashFallback: - def test_check_read_warns_when_content_changed_but_mtime_same(self, tmp_path): + async def test_read_returns_changed_content_when_mtime_same(self, tmp_path): f = tmp_path / "data.txt" f.write_text("original", encoding="utf-8") - file_state.record_read(f) + tool = ReadFileTool(workspace=tmp_path) + with file_state.file_read_context("read-1", lambda: {}): + first = await tool.execute(path=str(f)) original_mtime = os.path.getmtime(f) f.write_text("modified", encoding="utf-8") os.utime(f, (original_mtime, original_mtime)) assert os.path.getmtime(f) == original_mtime - warning = file_state.check_read(f) - assert warning is not None - assert "modified" in warning.lower() - - def test_check_read_passes_when_content_and_mtime_unchanged(self, tmp_path): - f = tmp_path / "data.txt" - f.write_text("stable", encoding="utf-8") - file_state.record_read(f) - - assert file_state.check_read(f) is None + with file_state.file_read_context("read-2", lambda: {"read-1": first}): + second = await tool.execute(path=str(f)) + assert "modified" in second + assert "unchanged" not in second.lower() # ---------------------------------------------------------------------------