The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(search): fail closed and preserve explicit roots
Royalaide11d91339ddd
diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.pyindex c84ffe96c85..779fa92ec35 100644--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@ -1,5 +1,6 @@"""macOS TCC-safe behavior for broad file searches."""+import refrom pathlib import Pathimport tools.file_operations as file_operations@@ -203,6 +204,67 @@ def test_find_fallback_prunes_protected_directories(tmp_path, monkeypatch):assert "-prune" in command+def _multi_root_protected_search(tmp_path, monkeypatch, engine):+ home = tmp_path / "Users" / "alice"+ downloads = home / "Downloads"+ downloads.mkdir(parents=True)+ env = RecordingEnvironment(home)+ ops = ShellFileOperations(env)+ monkeypatch.setattr(file_operations, "_HOME", str(home))+ monkeypatch.setattr(file_operations.sys, "platform", "darwin")+ monkeypatch.setattr(ops, "_has_command", lambda command: command == engine)+ path_checks = 0++ def execute(command, cwd=None, **kwargs):+ nonlocal path_checks+ env.commands.append(command)+ if command.startswith("test -e"):+ path_checks += 1+ output = "not_found\n" if path_checks == 1 else "exists\n"+ return {"output": output, "returncode": 0}+ if "--files" in command or command.startswith("set -o pipefail; find "):+ return {"output": "", "returncode": 0}+ return {"output": "yes\n", "returncode": 0}++ env.execute = execute+ result = ops.search("*.txt", path=f"{home} {downloads}", target="files")+ return ops, env, result, downloads+++def test_rg_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(+ tmp_path, monkeypatch+):+ ops, env, result, downloads = _multi_root_protected_search(+ tmp_path, monkeypatch, "rg"+ )++ command = _rg_files_commands(env.commands)[0]+ assert downloads.as_posix() in command+ assert "!Downloads/**" not in command+ assert "path contained 2 entries" in (result.warning or "")+ assert "macOS protected folders" in (result.warning or "")+ protected_warning = result.warning.split("macOS protected folders", 1)[1]+ assert "Desktop" in protected_warning+ assert "Downloads" not in protected_warning+++def test_find_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(+ tmp_path, monkeypatch+):+ ops, env, result, downloads = _multi_root_protected_search(+ tmp_path, monkeypatch, "find"+ )++ command = _find_commands(env.commands)[0]+ assert "Downloads" in command+ assert re.search(r"(?<!! )-path '[^']*/Downloads'", command) is None+ assert "path contained 2 entries" in (result.warning or "")+ assert "macOS protected folders" in (result.warning or "")+ protected_warning = result.warning.split("macOS protected folders", 1)[1]+ assert "Desktop" in protected_warning+ assert "Downloads" not in protected_warning++def test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"safe = home / "safe"diff --git a/tests/tools/test_search_budget_truncation.py b/tests/tools/test_search_budget_truncation.pyindex d14a54e89ef..76dd9abdd14 100644--- a/tests/tools/test_search_budget_truncation.py+++ b/tests/tools/test_search_budget_truncation.py@@ -182,6 +182,45 @@ def test_find_modified_capability_failure_is_actionable_without_retry():assert len(env.find_commands) == 1+ ("order", "output", "error_fragment"),+ [+ ("discovery", "/narrow/partial.py\n", "bounded find traversal"),+ ("modified", "/narrow/not-a-timestamp.py\n", "modification-time"),+ ],+)+def test_find_hard_error_discards_partial_output(order, output, error_fragment):+ env = FindRecordingEnvironment(output, code=2)++ result = ShellFileOperations(env)._search_files(+ "*.py", "/narrow", limit=2, offset=0, order=order+ )++ assert error_fragment in (result.error or "")+ assert result.files == []+ assert result.total_count == 0+++def test_find_timeout_preserves_partial_results_and_limit_reason():+ env = FindRecordingEnvironment(timeout_output("/narrow/partial.py"), code=124)++ result = ShellFileOperations(env)._search_files(+ "*.py", "/narrow", limit=2, offset=0, order="discovery"+ )++ assert result.files == ["/narrow/partial.py"]+ assert_timed_out(result)+++def test_find_zero_match_exit_zero_is_success():+ result = ShellFileOperations(FindRecordingEnvironment("", code=0))._search_files(+ "*.missing", "/narrow", limit=2, offset=0, order="discovery"+ )++ assert result.error is None+ assert result.files == []++def test_local_broad_no_rg_refuses_before_find(monkeypatch, tmp_path):home = tmp_path / "home"home.mkdir()diff --git a/tests/tools/test_search_files_engine_selection.py b/tests/tools/test_search_files_engine_selection.pyindex 9d3fa262d96..84bd74f045c 100644--- a/tests/tools/test_search_files_engine_selection.py+++ b/tests/tools/test_search_files_engine_selection.py@@ -297,6 +297,19 @@ def test_remote_msys_shaped_executable_is_not_rewritten_as_controller_path():assert "C:/remote-tools/rg" not in env.rg_commands[0][email protected]_only+def test_every_windows_drive_root_is_broad_even_when_home_is_on_another_drive(+ tmp_path, monkeypatch+):+ import tools.file_operations as file_operations++ monkeypatch.setattr(file_operations, "_HOME", "C:/Users/alice")+ ops = ShellFileOperations(LocalEnvironment(str(tmp_path)))++ assert ops._is_broad_local_search_root("D:/") is True+ assert ops._is_broad_local_search_root("D:/repo") is False++def test_modified_multi_path_search_preserves_exact_order_request():env = RecordingEnvironment()diff --git a/tools/file_operations.py b/tools/file_operations.pyindex 6a08d8f4670..6618cde4899 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -3460,6 +3460,35 @@ class ShellFileOperations(FileOperations):return _macos_protected_search_exclusions(path, cwd=cwd, home=_HOME, platform=sys.platform)++ def _effective_macos_search_exclusions(+ self, roots: List[str]+ ) -> List[tuple[str, str, str]]:+ """Return unique exclusions without pruning an explicitly chosen root."""+ explicit_roots = {+ os.path.normcase(os.path.abspath(os.path.normpath(root)))+ for root in roots+ }+ seen = set()+ effective = []+ for root in roots:+ for relative in self._macos_search_exclusions(root):+ absolute = os.path.normpath(os.path.join(root, relative))+ key = os.path.normcase(os.path.abspath(absolute))+ if key in explicit_roots or key in seen:+ continue+ seen.add(key)+ effective.append((root, relative, absolute))+ return effective++ @staticmethod+ def _macos_protected_search_warning(paths: List[str]) -> str:+ skipped = ", ".join(os.path.basename(item) for item in paths)+ return (+ "Skipped macOS protected folders during broad search to avoid "+ f"an unattended privacy prompt: {skipped}. Search a protected "+ "folder directly when access is intentional."+ )def _try_multi_path_search(self, pattern: str, path: str, target: str,file_glob: Optional[str], limit: int, offset: int,@@ -3518,7 +3547,18 @@ class ShellFileOperations(FileOperations):note += "; skipped missing: " + ", ".join(missing[:3])if len(missing) > 3:note += f" (+{len(missing) - 3} more)"- merged.warning = note+ warning_parts = [note]+ if not merged.error:+ protected_paths = [+ absolute+ for _root, _relative, absolute+ in self._effective_macos_search_exclusions(existing)+ ]+ if protected_paths:+ warning_parts.append(+ self._macos_protected_search_warning(protected_paths)+ )+ merged.warning = " ".join(warning_parts)return mergeddef _zero_match_probe(self, pattern: str, path: str,@@ -3618,12 +3658,15 @@ class ShellFileOperations(FileOperations):root = normalized(path)home = normalized(_HOME)+ drive = os.path.splitdrive(root)[0]+ anchor = drive + os.sep if drive else os.path.abspath(os.sep)+ if root == os.path.normcase(anchor):+ return Truetry:common = os.path.commonpath([root, home])except ValueError:return False- anchor = os.path.splitdrive(root)[0] + os.sep if os.path.splitdrive(root)[0] else os.path.abspath(os.sep)- return root == home or common == root or root == os.path.normcase(anchor)+ return root == home or common == rootdef _search_files(self, pattern: str, path: str | List[str], limit: int, offset: int,order: str = "discovery") -> SearchResult:@@ -3668,9 +3711,9 @@ class ShellFileOperations(FileOperations):f" \\( -type d -name '.*'{root_exemptions} \\) -prune -o")protected_paths = [- os.path.normpath(os.path.join(root, item))- for root in roots- for item in self._macos_search_exclusions(root)+ absolute+ for _root, _relative, absolute+ in self._effective_macos_search_exclusions(roots)]protected_prune = ""if protected_paths:@@ -3697,12 +3740,12 @@ class ShellFileOperations(FileOperations):result = self._exec(cmd, timeout=60)stdout, limit_reason = _search_stdout_and_limit(result)- if order == "modified" and result.exit_code not in {0, 124} and not stdout.strip():+ if order == "modified" and result.exit_code not in {0, 124}:return SearchResult(error=("Exact modification-time order requires GNU find with ""-printf support; install ripgrep 14+ or use order='discovery'."))- if order == "discovery" and result.exit_code not in {0, 1, 124} and not stdout.strip():+ if order == "discovery" and result.exit_code not in {0, 124}:return SearchResult(error="File search failed while running bounded find traversal.")raw_files: List[str] = []@@ -3746,12 +3789,11 @@ class ShellFileOperations(FileOperations):roots = [path] if isinstance(path, str) else pathfetch_limit = limit + offset + 1- exclusion_terms: List[str] = []- for root in roots:- exclusion_terms.extend(- f"--glob {self._escape_shell_arg(f'!{item}/**')}"- for item in self._macos_search_exclusions(root)- )+ exclusion_terms = [+ f"--glob {self._escape_shell_arg(f'!{relative}/**')}"+ for _root, relative, _absolute+ in self._effective_macos_search_exclusions(roots)+ ]exclusion_globs = " ".join(dict.fromkeys(exclusion_terms))exclusion_args = f" {exclusion_globs}" if exclusion_globs else ""rg_executable = rg_executable or self._resolve_command("rg")