The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: include directories in file search
Dustin Persekbe1b85efeaf7
diff --git a/tests/tools/test_file_operations.py b/tests/tools/test_file_operations.pyindex 06fc625de3c..665e13bde36 100644--- a/tests/tools/test_file_operations.py+++ b/tests/tools/test_file_operations.py@@ -3,6 +3,7 @@import base64import osimport pytest+import shutilimport subprocessfrom pathlib import Pathfrom unittest.mock import MagicMock@@ -362,6 +363,116 @@ class TestSearchPathValidation:assert "search failed" in result.error.lower() or "Search error" in result.error+class TestSearchFilesIncludesDirectories:+ """``search_files(target='files')`` is documented as an ls replacement and must+ list matching directories, not just files — empty directories included (#54347)."""++ @pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")+ def test_rg_target_files_includes_matching_empty_directory(self, tmp_path):+ root = tmp_path / "repo"+ empty_dir = root / "vault"+ empty_dir.mkdir(parents=True)++ ops = ShellFileOperations(LocalEnvironment("/"))+ result = ops.search("vault", path=str(root), target="files")++ assert result.error is None+ assert str(empty_dir) in result.files++ @pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")+ @pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")+ def test_rg_target_files_excludes_gitignored_empty_directory(self, tmp_path):+ root = tmp_path / "repo"+ ignored_dir = root / "ignored_dir"+ visible_dir = root / "visible_dir"+ ignored_dir.mkdir(parents=True)+ visible_dir.mkdir()+ (root / ".gitignore").write_text("ignored_dir/\n")+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)++ ops = ShellFileOperations(LocalEnvironment("/"))+ result = ops.search("*dir", path=str(root), target="files")++ assert result.error is None+ assert str(visible_dir) in result.files+ assert str(ignored_dir) not in result.files++ @pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")+ def test_rg_sorts_files_and_directories_before_pagination(self, tmp_path):+ """A newer directory must page ahead of older files and dirs (globally+ merged mtime order before offset/limit, not dirs appended after)."""+ root = tmp_path / "repo"+ older_file = root / "older.log"+ newer_dir = root / "alpha-newer"+ older_dirs = [root / "zulu-older", root / "yankee-older"]+ root.mkdir()+ older_file.write_text("x")+ newer_dir.mkdir()+ for older_dir in older_dirs:+ older_dir.mkdir()+ os.utime(older_file, (1_000, 1_000))+ for older_dir in older_dirs:+ os.utime(older_dir, (1_000, 1_000))+ os.utime(newer_dir, (2_000, 2_000))++ ops = ShellFileOperations(LocalEnvironment("/"))+ result = ops.search("*", path=str(root), target="files", limit=1)++ assert result.error is None+ assert result.files == [str(newer_dir)]+ assert result.truncated is True++ def test_find_target_files_includes_matching_empty_directory(self, tmp_path, monkeypatch):+ root = tmp_path / "repo"+ empty_dir = root / "vault"+ regular_file = root / "vault.txt"+ empty_dir.mkdir(parents=True)+ regular_file.write_text("x")++ ops = ShellFileOperations(LocalEnvironment("/"))+ monkeypatch.setattr(ops, "_has_command", lambda command: command == "find")+ result = ops.search("vault*", path=str(root), target="files")++ assert result.error is None+ assert {str(empty_dir), str(regular_file)}.issubset(set(result.files))++ def test_target_files_still_excludes_hidden_matching_directories(self, tmp_path, monkeypatch):+ root = tmp_path / "repo"+ visible_dir = root / "visible" / "cache"+ hidden_dir = root / ".hidden" / "cache"+ visible_dir.mkdir(parents=True)+ hidden_dir.mkdir(parents=True)++ ops = ShellFileOperations(LocalEnvironment("/"))+ monkeypatch.setattr(ops, "_has_command", lambda command: command == "find")+ result = ops.search("cache", path=str(root), target="files")++ assert result.error is None+ assert str(visible_dir) in result.files+ assert str(hidden_dir) not in result.files++ def test_target_files_paginates_combined_files_and_directories(self, tmp_path, monkeypatch):+ """Files and directories share one ordering: page slices must compose."""+ root = tmp_path / "repo"+ empty_dir = root / "alpha"+ regular_file = root / "bravo"+ empty_dir.mkdir(parents=True)+ regular_file.write_text("x")++ ops = ShellFileOperations(LocalEnvironment("/"))+ monkeypatch.setattr(ops, "_has_command", lambda command: command == "find")++ first = ops.search("*", path=str(root), target="files", limit=1, offset=0)+ second = ops.search("*", path=str(root), target="files", limit=1, offset=1)+ combined = ops.search("*", path=str(root), target="files", limit=2, offset=0)++ assert first.error is None+ assert second.error is None+ assert combined.error is None+ assert first.files + second.files == combined.files+ assert set(combined.files) == {str(empty_dir), str(regular_file)}++class TestSearchFilesFallbackHiddenPaths:def _make_env(self):return LocalEnvironment("/")diff --git a/tools/file_operations_search.py b/tools/file_operations_search.pyindex fa57bfa2419..20301ff84be 100644--- a/tools/file_operations_search.py+++ b/tools/file_operations_search.py@@ -655,6 +655,124 @@ class SearchMixin:return Falsereturn root == home or common == root+ def _filter_hidden_descendants(self, paths: List[str], root: Path) -> List[str]:+ """Drop hidden descendants while allowing an explicit hidden search root."""+ normalized_root = root.resolve()+ filtered = []+ for item_path in paths:+ try:+ rel_parts = Path(item_path).resolve().relative_to(normalized_root).parts+ except ValueError:+ rel_parts = Path(item_path).parts+ if any(part not in {".", ".."} and part.startswith(".") for part in rel_parts):+ continue+ filtered.append(item_path)+ return filtered++ def _filter_gitignored_paths(self, paths: List[str], root: str) -> List[str]:+ """Drop paths ignored by git when *root* is inside a git worktree."""+ if not paths:+ return paths++ escaped_root = self._escape_shell_arg(root)+ probe = self._exec(+ f"git -C {escaped_root} rev-parse --is-inside-work-tree >/dev/null 2>&1",+ timeout=10,+ )+ if probe.exit_code != 0:+ return paths++ result = self._exec(+ f"git -C {escaped_root} check-ignore --stdin",+ timeout=10,+ stdin_data="\n".join(paths),+ )+ ignored = set(result.stdout.splitlines())+ return [item_path for item_path in paths if item_path not in ignored]++ def _sort_paths_by_mtime(self, paths: List[str]) -> List[str]:+ """Sort paths newest-first using metadata from the active backend."""+ if len(paths) < 2:+ return paths++ script = (+ 'while IFS= read -r item || [ -n "$item" ]; do '+ 'mtime="$(stat -c%Y "$item" 2>/dev/null '+ '|| stat -f%m "$item" 2>/dev/null || true)"; '+ "printf '%s\\n' \"${mtime:-0}\"; "+ "done"+ )+ result = self._exec(script, timeout=60, stdin_data="\n".join(paths))++ mtimes = []+ for line in result.stdout.splitlines()[:len(paths)]:+ try:+ mtimes.append(float(line))+ except ValueError:+ mtimes.append(0.0)+ # A path can disappear between traversal and stat. Keep such paths at+ # the end, preserving their existing relative order as a stable fallback.+ mtimes.extend([0.0] * (len(paths) - len(mtimes)))+ return [+ item+ for _, item in sorted(+ zip(mtimes, paths), key=lambda pair: pair[0], reverse=True+ )+ ]++ def _search_directories_with_find(+ self, pattern: str, path: str, fetch_limit: int+ ) -> tuple[List[str], Optional[str]]:+ """Return matching descendant directories using find, if available.++ ``rg --files`` and ``find -type f`` both enumerate files only, so+ directories — especially empty ones — are invisible (#54347). rg stays+ authoritative for which *files* survive ignore processing; this adds+ the matching directory entries so the tool honours its documented+ ls-replacement contract.+ """+ if fetch_limit <= 0 or not self._has_command("find"):+ return [], None++ escaped_path = self._escape_shell_arg(path)+ escaped_pattern = self._escape_shell_arg(pattern)+ q_roots = [escaped_path]+ hidden_prune = self._hidden_prune_expr(q_roots)+ cmd = (+ f"find -H {escaped_path} {hidden_prune} -o -type d "+ f"! -name '.*' -name {escaped_pattern} -printf '%T@ %p\\n' "+ f"2>/dev/null | sort -rn"+ )+ result = self._exec(cmd, timeout=30)+ stdout, limit_reason = _search_stdout_and_limit(result)++ if not stdout.strip() and not limit_reason:+ # Try without -printf (BSD find compatibility -- macOS)+ cmd_simple = (+ f"find -H {escaped_path} {hidden_prune} -o -type d "+ f"! -name '.*' -name {escaped_pattern} 2>/dev/null"+ )+ result = self._exec(cmd_simple, timeout=30)+ stdout, limit_reason = _search_stdout_and_limit(result)++ dirs = []+ for line in stdout.strip().split('\n'):+ if not line:+ continue+ parts = line.split(' ', 1)+ if len(parts) == 2 and parts[0].replace('.', '').isdigit():+ dirs.append(parts[1])+ else:+ dirs.append(line)++ if dirs:+ # An explicitly selected hidden root keeps its (hidden) subtree;+ # any other hidden descendants stay invisible, matching rg.+ if self._root_under_hidden_dir(path):+ dirs = self._filter_hidden_descendants(dirs, Path(path))+ dirs = self._filter_gitignored_paths(dirs, path)+ return self._sort_paths_by_mtime(dirs)[:fetch_limit], limit_reason+def _search_files(self, pattern: str, path: str | List[str], limit: int, offset: int,order: str = "discovery") -> SearchResult:"""Search for files by name (glob-like) across one or more roots: rg --files,@@ -713,8 +831,8 @@ class SearchMixin:# same argument (#116270). Following the operand inside the command is also what# covers a link that only exists on the execution host (SSH/container), with no# probe of its own.- base = (f"find -H {' '.join(q_roots)}{protected_prune}{hidden_prune} -type f "- f"! -name '.*' -name {self._escape_shell_arg(search_pattern)}")+ base = (f"find -H {' '.join(q_roots)}{protected_prune}{hidden_prune} "+ f"\\( -type f -o -type d \\) ! -name '.*' -name {self._escape_shell_arg(search_pattern)}")if order == "modified":cmd = "set -o pipefail; " + base + f" -printf '%T@ %p\\n' 2>/dev/null | sort -rn | head -n {fetch_limit}"else:@@ -815,6 +933,21 @@ class SearchMixin:"Exact modification-time order failed; ripgrep 14+ is ""required. Upgrade ripgrep or use order='discovery'."))return SearchResult(error="File search failed while running ripgrep.")+ # rg --files lists files only; supplement with matching directories so+ # empty directories stay discoverable (#54347). Skip the extra traversal+ # when rg already timed out — partial file results must not be presented+ # as a coherent page. Only the single-root path supplements (a multi-root+ # walk is already the merged view across roots).+ if limit_reason != "search_timeout" and isinstance(path, str) and self._has_command("find"):+ dirs, directory_limit_reason = self._search_directories_with_find(glob_pattern, path, fetch_limit)+ if dirs:+ existing = set(all_files)+ merged_entries = self._sort_paths_by_mtime(+ all_files + [d for d in dirs if d not in existing])+ # Under exact modified order rg is authoritative for files;+ # the merged view keeps the newest-first contract globally.+ all_files = merged_entries+ limit_reason = limit_reason or directory_limit_reasonreturn SearchResult(files=all_files[offset:offset + limit], total_count=len(all_files),truncated=len(all_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason)