The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(search): path-scoped grep pruning + execution-backend gating for macOS TCC exclusions
Teknium979b7d14fdc1
diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.pyindex ce6f16910eb..501280a85f7 100644--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@ -110,7 +110,10 @@ def test_legacy_ripgrep_file_fallback_keeps_protected_globs(tmp_path, monkeypatcassert "!Downloads/**" in command-def test_grep_fallback_excludes_protected_directories(tmp_path, monkeypatch):+def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):+ """The grep fallback must NOT use --exclude-dir (basename-wide: it would+ skip every nested dir named Downloads anywhere under the root). It routes+ through find's path-scoped -prune instead."""home = tmp_path / "Users" / "alice"home.mkdir(parents=True)env = RecordingEnvironment(home)@@ -121,9 +124,54 @@ def test_grep_fallback_excludes_protected_directories(tmp_path, monkeypatch):ops.search("needle", path=str(home), target="content")- grep_command = next(command for command in env.commands if " grep " in command)+ pruned_command = next(command for command in env.commands if "-prune" in command)for dirname in PROTECTED_NAMES:- assert f"--exclude-dir='{dirname}'" in grep_command+ # Path-scoped pruning: full protected path present, no basename-wide+ # --exclude-dir for protected names.+ assert str(home / dirname) in pruned_command+ assert f"--exclude-dir={dirname}" not in pruned_command+ assert f"--exclude-dir='{dirname}'" not in pruned_command+++def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypatch):+ """A repo-internal directory literally named 'Downloads' must still be+ searched by the pruned grep path — the exact regression --exclude-dir had."""+ home = tmp_path / "Users" / "alice"+ project = home / "work" / "repo" / "Downloads"+ project.mkdir(parents=True)+ (project / "notes.txt").write_text("needle here\n")+ protected = home / "Downloads"+ protected.mkdir()+ (protected / "secret.txt").write_text("needle protected\n")+ monkeypatch.setattr(file_operations, "_HOME", str(home))+ monkeypatch.setattr(file_operations.sys, "platform", "darwin")+ ops = ShellFileOperations(LocalEnvironment(cwd=str(home)))+ monkeypatch.setattr(ops, "_has_command", lambda command: command == "grep")++ result = ops.search("needle", path=str(home), target="content")++ matched_paths = [m.path for m in (result.matches or [])]+ assert any("work/repo/Downloads/notes.txt" in p for p in matched_paths)+ assert not any(str(protected / "secret.txt") in p for p in matched_paths)+++def test_remote_backend_never_prunes(tmp_path, monkeypatch):+ """Non-local environments get no exclusions: platform facts describe the+ controller, not the execution host (macOS controller + Linux SSH backend+ must not prune the remote's Downloads)."""+ home = tmp_path / "Users" / "alice"+ home.mkdir(parents=True)+ env = RecordingEnvironment(home)+ env.is_local = False # remote/container-shaped backend+ ops = ShellFileOperations(env)+ monkeypatch.setattr(file_operations, "_HOME", str(home))+ monkeypatch.setattr(file_operations.sys, "platform", "darwin")++ result = ops.search("*.txt", path=str(home), target="files")++ rg_command = next(command for command in env.commands if command.startswith("rg --files"))+ assert "!Downloads/**" not in rg_command+ assert result.warning is Nonedef test_find_fallback_prunes_protected_directories(tmp_path, monkeypatch):diff --git a/tools/environments/base.py b/tools/environments/base.pyindex 184d44cca0f..aeee54e47c1 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -658,6 +658,13 @@ class BaseEnvironment(ABC):# Subclasses that embed stdin as a heredoc (Modal, Daytona) set this._stdin_mode: str = "pipe" # "pipe" or "heredoc"+ # True only when commands execute on the SAME host as the Hermes process+ # (LocalEnvironment). Controller-host facts (sys.platform, Path.home())+ # only describe the execution target when this is True — remote/container+ # backends must not inherit controller-side platform behavior (e.g. the+ # macOS TCC search pruning in tools/file_operations.py).+ is_local: bool = False+# Snapshot creation timeout (override for slow cold-starts)._snapshot_timeout: int = 30diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 661067ebe6b..04fee8f6f01 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -1746,6 +1746,10 @@ class LocalEnvironment(BaseEnvironment):_profile_scoped_passthrough = True+ # Commands run on the Hermes host itself — controller-side platform+ # behavior (macOS TCC pruning, etc.) legitimately applies here.+ is_local = True+def __init__(self, cwd: str = "", timeout: int = 60, env: dict = None):cwd = _resolve_local_initial_cwd(cwd)super().__init__(cwd=cwd, timeout=timeout, env=env)diff --git a/tools/file_operations.py b/tools/file_operations.pyindex 6b9f96e410d..fbfd06cab8e 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -2890,7 +2890,20 @@ class ShellFileOperations(FileOperations):return resultdef _macos_search_exclusions(self, path: str) -> List[str]:- """Protected descendants to prune for this search root, if any."""+ """Protected descendants to prune for this search root, if any.++ Gated on ``env.is_local``: ``sys.platform``/``Path.home()`` describe+ the CONTROLLER, but search commands execute on ``self.env``'s host — a+ macOS controller driving a Linux container/SSH backend must not prune+ the remote's (unprotected) Downloads, and TCC doesn't exist there+ anyway. A Linux controller driving a macOS SSH host keeps today's+ behavior (no pruning); detecting the remote OS is out of scope here.+ Environments without the flag (test fakes, plugins) default to local+ semantics — pruning is a warning-carrying skip, never data loss.+ """+ env = getattr(self, "env", None)+ if env is not None and getattr(env, "is_local", True) is False:+ return []cwd = getattr(self.env, "cwd", None) or self.cwdreturn _macos_protected_search_exclusions(path, cwd=cwd, home=_HOME, platform=sys.platform@@ -3368,9 +3381,23 @@ class ShellFileOperations(FileOperations):# Exclude hidden directories (matching ripgrep's default behavior).# This prevents searching inside .hub/index-cache/, .git/, etc.cmd_parts.append("--exclude-dir='.*'")- for item in self._macos_search_exclusions(path):- dirname = item.split("/")[-1]- cmd_parts.append(f"--exclude-dir={self._escape_shell_arg(dirname)}")++ # Protected-dir pruning CANNOT use --exclude-dir here: grep matches+ # exclude-dir globs against BASENAMES anywhere in the tree, so+ # --exclude-dir=Downloads would silently skip every nested directory+ # named Downloads (a repo's own Downloads/ folder included), not just+ # the protected home child. When exclusions apply (darwin broad-home+ # search on a local backend), route through find's path-scoped -prune+ # instead — same traversal-prevention the find backend uses.+ protected_paths = [+ os.path.normpath(os.path.join(path, item))+ for item in self._macos_search_exclusions(path)+ ]+ if protected_paths:+ return self._search_with_grep_pruned(+ pattern, path, file_glob, limit, offset, output_mode, context,+ protected_paths,+ )# Add context if requestedif context > 0:@@ -3415,6 +3442,56 @@ class ShellFileOperations(FileOperations):# pipefail does not turn truncated results into false errors.cmd = "set -o pipefail; " + " ".join(cmd_parts)result = self._exec(cmd, timeout=60)+ return self._parse_grep_search_output(result, output_mode, limit, offset, context)++ def _search_with_grep_pruned(self, pattern: str, path: str, file_glob: Optional[str],+ limit: int, offset: int, output_mode: str, context: int,+ protected_paths: List[str]) -> SearchResult:+ """grep fallback with PATH-scoped protected-dir pruning.++ Files are enumerated by ``find`` with the same ``-path ... -prune``+ expression the find backend uses (traversal never enters the protected+ dirs, so macOS never sees an access attempt), then handed to grep via+ ``-exec {} +``. This exists because grep's own ``--exclude-dir``+ matches basenames anywhere in the tree — it cannot express "only the+ home-level Downloads". Hidden directories are pruned to mirror the+ plain path's ``--exclude-dir='.*'``. Trade-off: with ``-exec {} +``+ find folds grep's exit code into its own generic non-zero, so a hard+ grep error surfaces as an empty result rather than exit 2 — acceptable+ for this darwin-local-broad-search-only branch.+ """+ grep_parts = ["grep", "-nHE"]+ if context > 0:+ grep_parts.extend(["-C", str(context)])+ if output_mode == "files_only":+ grep_parts.append("-l")+ elif output_mode == "count":+ grep_parts.append("-c")+ grep_parts.append(self._escape_shell_arg(pattern))++ prune_terms = " -o ".join(+ f"-path {self._escape_shell_arg(item)}" for item in protected_paths+ )+ find_parts = [+ "find", self._escape_shell_arg(path or "."),+ f"\\( {prune_terms} \\) -prune", "-o",+ "\\( -type d -name '.*' \\) -prune", "-o",+ "-type f",+ ]+ if file_glob:+ find_parts.extend(["-name", self._escape_shell_arg(file_glob)])+ find_parts.extend(["-exec", *grep_parts, "{}", "+"])+ fetch_limit = limit + offset + (200 if context > 0 else 0)+ cmd = (+ "set -o pipefail; " + " ".join(find_parts)+ + f" 2>/dev/null | head -n {fetch_limit}"+ )+ result = self._exec(cmd, timeout=60)+ return self._parse_grep_search_output(result, output_mode, limit, offset, context)++ def _parse_grep_search_output(self, result, output_mode: str, limit: int,+ offset: int, context: int) -> SearchResult:+ """Shared grep output parsing for the plain and pruned variants."""stdout, limit_reason = _search_stdout_and_limit(result)# _exec merges stderr into stdout, so grep's diagnostic lines