diff --git a/nanobot/agent/tools/search.py b/nanobot/agent/tools/search.py index 9232a1231..c772dfac9 100644 --- a/nanobot/agent/tools/search.py +++ b/nanobot/agent/tools/search.py @@ -181,6 +181,12 @@ def _text_page( return page, truncated +def _ordered_prefix( + items: Iterable[T], size: int | None, *, key: Callable[[T], tuple[float, str]], +) -> list[T]: + return sorted(items, key=key) if size is None else heapq.nsmallest(size, items, key=key) + + def _pagination_note(limit: int | None, offset: int, truncated: bool) -> str | None: if truncated: if limit is None: @@ -523,14 +529,7 @@ class FindFilesTool(_SearchTool): by_modified = self._iter_modified( tree, include_dirs=include_dirs, matches=matches_entry, budget=budget, ) - if selection_size is None: - matches = sorted(by_modified, key=lambda item: (-item[1], item[0])) - else: - matches = heapq.nsmallest( - selection_size, - by_modified, - key=lambda item: (-item[1], item[0]), - ) + matches = _ordered_prefix(by_modified, selection_size, key=lambda item: (-item[1], item[0])) paths = [item[0] for item in matches] else: matching_paths = ( @@ -762,7 +761,7 @@ class GrepTool(_SearchTool): content_page = ContentPage(limit, offset, self._MAX_RESULT_CHARS, self._MAX_RENDERED_LINE_CHARS) skipped_binary = 0 skipped_large = 0 - document_errors: list[str] = [] + document_error: str | None = None document_continuations: list[str] = [] counts: dict[str, int] = {} file_mtimes: dict[str, float] = {} @@ -786,6 +785,7 @@ class GrepTool(_SearchTool): source_iterator: Iterator[LocatedDocumentLine] | None = None is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS + file_matches = 0 try: if is_document: try: @@ -812,24 +812,21 @@ class GrepTool(_SearchTool): skipped_binary += 1 continue source_iterator = source.lines - if source.continuation: + if source.continuation and len(document_continuations) < 10: document_continuations.append( f"({display_path}: continue PDF search with {source.continuation})" ) source_lines = checked_lines(source_iterator) - file_had_match = False if output_mode == "content": content_page.scan(display_path, source_lines, regex, context_before, context_after) else: for line in source_lines: if not line.searchable or regex.search(line.text) is None: continue - file_had_match = True - if output_mode == "count": - counts[display_path] = counts.get(display_path, 0) + 1 - continue - break + file_matches += 1 + if output_mode != "count": + break except (_SearchCancelledError, _SearchBudgetExceededError, MatchTooLargeError): raise except Exception as e: @@ -844,13 +841,18 @@ class GrepTool(_SearchTool): f"Error searching document {display_path}: {e!s}" ) skipped_binary += 1 - document_errors.append(f"{display_path}: {e!s}") + if document_error is None: + document_error = f"{display_path}: {e!s}" continue finally: close = getattr(source_iterator, "close", None) if close is not None: close() - if file_had_match: + # A document can fail after yielding matches. Keep the count + # of those lines even though the failed file is not ranked. + if file_matches and output_mode == "count": + counts[display_path] = counts.get(display_path, 0) + file_matches + if file_matches: file_mtimes[display_path] = mtime if content_page.stopped: break @@ -862,8 +864,9 @@ class GrepTool(_SearchTool): if note: notes.append(note) else: - ordered_files = sorted( - file_mtimes, key=lambda name: (-file_mtimes.get(name, 0.0), name), + ordered_files = _ordered_prefix( + file_mtimes, None if limit is None else offset + limit + 1, + key=lambda name: (-file_mtimes[name], name), ) entries = ( [f"{name}: {counts[name]}" for name in ordered_files] @@ -882,9 +885,9 @@ class GrepTool(_SearchTool): notes.append(f"(skipped {skipped_binary} binary/unreadable files)") if skipped_large: notes.append(f"(skipped {skipped_large} large files)") - if document_errors: - notes.append(f"(first document error: {document_errors[0]})") - notes.extend(document_continuations[:10]) + if document_error is not None: + notes.append(f"(first document error: {document_error})") + notes.extend(document_continuations) if output_mode == "count" and counts: notes.append( f"(total matches: {sum(counts.values())} in {len(counts)} files)" diff --git a/nanobot/execution/files.py b/nanobot/execution/files.py index 12feb2a6d..6684a0306 100644 --- a/nanobot/execution/files.py +++ b/nanobot/execution/files.py @@ -336,7 +336,12 @@ class FileSearch: with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size): if opened_size > limit: return None - return SearchBytes(stream.read(limit + 1), modified) + # Avoid allocating the full scan limit for each small file. The + # extra byte detects growth (including streams with a reported size of zero). + data = stream.read(opened_size + 1) + if len(data) > opened_size: + data += stream.read(limit + 1 - len(data)) + return SearchBytes(data, modified) @contextmanager def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]: diff --git a/tests/tools/test_search_tools.py b/tests/tools/test_search_tools.py index f57be0b9b..d98397142 100644 --- a/tests/tools/test_search_tools.py +++ b/tests/tools/test_search_tools.py @@ -857,26 +857,29 @@ async def test_grep_files_with_matches_mode_returns_unique_paths(tmp_path: Path) @pytest.mark.asyncio -async def test_grep_files_with_matches_supports_head_limit_and_offset(tmp_path: Path) -> None: +@pytest.mark.parametrize("mode", ["files_with_matches", "count"]) +async def test_grep_ranked_modes_preserve_order_and_totals_when_paging(tmp_path: Path, mode: str) -> None: (tmp_path / "src").mkdir() - for name in ("a.py", "b.py", "c.py"): - (tmp_path / "src" / name).write_text("needle\n", encoding="utf-8") + for name, mtime, matches in (("c.py", 2, 3), ("b.py", 2, 2), ("a.py", 1, 1)): + path = tmp_path / "src" / name + path.write_text("needle\n" * matches, encoding="utf-8") + os.utime(path, (mtime, mtime)) tool = GrepTool(workspace=tmp_path, allowed_dir=tmp_path) result = await tool.execute( pattern="needle", path="src", - output_mode="files_with_matches", + output_mode=mode, head_limit=1, offset=1, ) - # Filesystem order is not deterministic across platforms, so just verify: - # 1. Only one file path is returned (head_limit=1 after offset=1) - # 2. The pagination info is correct - assert "pagination: limit=1, offset=1" in result - file_lines = [line for line in result.splitlines() if line.startswith("src/")] - assert len(file_lines) == 1 + assert result.splitlines() == [ + "src/c.py: 3" if mode == "count" else "src/c.py", + "", + "(pagination: limit=1, offset=1; use offset=2 to continue)", + *(["(total matches: 6 in 3 files)"] if mode == "count" else []), + ] @pytest.mark.asyncio @@ -936,6 +939,34 @@ async def test_grep_reports_skipped_binary_and_large_files( assert "skipped 1 large files" in result +@pytest.mark.parametrize("exceeds_limit", [False, True]) +async def test_grep_keeps_read_limit_when_an_open_file_grows(tmp_path, monkeypatch, exceeds_limit): + from nanobot.execution import files + + target = tmp_path / "growing.log" + target.write_bytes(b"start\n") + open_regular_file = files._open_regular_file + + @contextmanager + def grow_after_stat(path, *, dir_fd=None): + with open_regular_file(path, dir_fd=dir_fd) as (stream, size): + with target.open("ab") as writer: + writer.write(b"needle\n" + (b"x" * 64 if exceeds_limit else b"")) + yield stream, size + + monkeypatch.setattr(files, "_open_regular_file", grow_after_stat) + monkeypatch.setattr(GrepTool, "_MAX_EXPLICIT_FILE_BYTES", 64) + result = await GrepTool(workspace=tmp_path).execute( + pattern="needle", path="growing.log", output_mode="files_with_matches", + ) + + if exceeds_limit: + assert result.startswith("No matches found") + assert "skipped 1 binary/unreadable files" in result + else: + assert result == "growing.log" + + @pytest.mark.asyncio async def test_grep_uses_a_larger_bounded_limit_for_an_explicit_file( tmp_path: Path,