diff --git a/nanobot/agent/tools/search.py b/nanobot/agent/tools/search.py index bf60cca24..9232a1231 100644 --- a/nanobot/agent/tools/search.py +++ b/nanobot/agent/tools/search.py @@ -12,6 +12,7 @@ from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass from functools import lru_cache +from itertools import islice from pathlib import Path, PurePosixPath from typing import Any, Iterable, Iterator, TypeVar @@ -200,14 +201,6 @@ def _matches_type(name: str, file_type: str | None) -> bool: return any(fnmatch.fnmatch(name.lower(), pattern.lower()) for pattern in patterns) -def _matches_query(rel_path: str, query: str | None) -> bool: - if not query: - return True - haystack = rel_path.lower() - terms = [part for part in query.lower().split() if part] - return all(term in haystack for term in terms) - - class _SearchTool(_FsTool): _IGNORE_DIRS = ListDirTool._IGNORE_DIRS | {".worktrees", ".worktree", ".nanobot"} _MAX_SCAN_PATHS = 500_000 @@ -438,23 +431,6 @@ class FindFilesTool(_SearchTool): for entry, mtime in zip(selected, times, strict=True): yield entry.display_path + ("/" if entry.is_dir else ""), mtime - @staticmethod - def _matches_entry( - entry: _FindFilesEntry, - *, - query: str | None, - glob: str | None, - file_type: str | None, - ) -> bool: - if glob and not _match_glob(entry.rel_path, entry.name, glob): - return False - if entry.is_dir: - if file_type: - return False - elif not _matches_type(entry.name, file_type): - return False - return _matches_query(entry.display_path, query) - async def execute( self, path: str = ".", @@ -529,40 +505,40 @@ class FindFilesTool(_SearchTool): max_paths=self._MAX_SCAN_PATHS, ) + terms = query.lower().split() if query else [] + def matches_entry(entry: _FindFilesEntry) -> bool: - return self._matches_entry(entry, query=query, glob=glob, file_type=file_type) + if glob and not _match_glob(entry.rel_path, entry.name, glob): + return False + if file_type and (entry.is_dir or not _matches_type(entry.name, file_type)): + return False + if not terms: + return True + haystack = entry.display_path.lower() + return all(term in haystack for term in terms) - def matching_paths() -> Iterator[tuple[str, float]]: - for entry in self._iter_paths( - tree, - include_dirs=include_dirs, - budget=budget, - ): - if matches_entry(entry): - yield entry.display_path + ("/" if entry.is_dir else ""), 0.0 - - matches: list[tuple[str, float]] + selection_size = None if limit is None else offset + limit + 1 try: if sort == "modified": by_modified = self._iter_modified( tree, include_dirs=include_dirs, matches=matches_entry, budget=budget, ) - if limit is None: + if selection_size is None: matches = sorted(by_modified, key=lambda item: (-item[1], item[0])) else: - selection_size = offset + limit + 1 matches = heapq.nsmallest( selection_size, by_modified, key=lambda item: (-item[1], item[0]), ) + paths = [item[0] for item in matches] else: - selection_size = None if limit is None else offset + limit + 1 - matches = [] - for match in matching_paths(): - matches.append(match) - if selection_size is not None and len(matches) >= selection_size: - break + matching_paths = ( + entry.display_path + ("/" if entry.is_dir else "") + for entry in self._iter_paths(tree, include_dirs=include_dirs, budget=budget) + if matches_entry(entry) + ) + paths = list(islice(matching_paths, selection_size)) budget.checkpoint() except _SearchBudgetExceededError as exc: if str(exc) == "paths": @@ -574,7 +550,6 @@ class FindFilesTool(_SearchTool): "narrow path, query, glob, or type and retry." ) - paths = [item[0] for item in matches] paged, truncated = _text_page(paths, limit, offset, self._MAX_RESULT_CHARS) if not paged: return "No files found" diff --git a/nanobot/execution/files.py b/nanobot/execution/files.py index 05f66b478..12feb2a6d 100644 --- a/nanobot/execution/files.py +++ b/nanobot/execution/files.py @@ -8,6 +8,8 @@ import stat from collections.abc import Callable, Generator, Iterable from contextlib import AbstractContextManager, ExitStack, contextmanager from dataclasses import dataclass +from heapq import nsmallest +from operator import itemgetter from pathlib import Path from typing import TYPE_CHECKING, BinaryIO @@ -491,23 +493,29 @@ class WorkspaceFiles: if not directory.is_dir(): raise NotADirectoryError(path) tree = FileSearch(directory, True, self._read_path) - pending = [directory] - entries: list[tuple[Path, bool]] = [] - while pending: - parent = pending.pop() - try: - for entry in tree.entries(parent): - if entry.name in ignored: - continue - child = parent / entry.name - entries.append((child.relative_to(directory), entry.is_directory)) - if recursive and entry.is_directory and not entry.is_directory_link: - pending.append(child) - except PermissionError: - if not recursive: - raise - entries.sort(key=lambda entry: entry[0]) - return DirectoryListing(entries[:max(0, limit)], len(entries)) + total = 0 + + def walk() -> Generator[tuple[Path, bool]]: + nonlocal total + pending = [directory] + while pending: + parent = pending.pop() + try: + for entry in tree.entries(parent): + if entry.name in ignored: + continue + child = parent / entry.name + if recursive and entry.is_directory and not entry.is_directory_link: + pending.append(child) + total += 1 + yield child.relative_to(directory), entry.is_directory + except PermissionError: + if not recursive: + raise + + # Scan all entries for the exact total, but retain only the requested prefix. + entries = nsmallest(max(1, limit), walk(), key=itemgetter(0)) + return DirectoryListing(entries if limit > 0 else [], total) def sibling_files(self, target: WritableFile) -> list[str]: """Suggest names only when the caller can read the directory itself.""" diff --git a/tests/tools/test_filesystem_tools.py b/tests/tools/test_filesystem_tools.py index c8b59b371..f807fb739 100644 --- a/tests/tools/test_filesystem_tools.py +++ b/tests/tools/test_filesystem_tools.py @@ -385,6 +385,22 @@ class TestListDirTool: assert "truncated" in result assert "3 of 10" in result + @pytest.mark.asyncio + async def test_recursive_limit_preserves_sorted_prefix_and_exact_total(self, tool, tmp_path): + (tmp_path / "z").mkdir() + (tmp_path / "z" / "a.txt").touch() + (tmp_path / "a").mkdir() + (tmp_path / "a" / "z.txt").touch() + (tmp_path / "b.txt").touch() + (tmp_path / ".git").mkdir() + (tmp_path / ".git" / "ignored").touch() + + result = await tool.execute(path=".", recursive=True, max_entries=3) + + assert result.replace("\\", "/").splitlines() == [ + "a/", "a/z.txt", "b.txt", "", "(truncated, showing first 3 of 5 entries)", + ] + @pytest.mark.asyncio async def test_empty_dir(self, tool, tmp_path): d = tmp_path / "empty"