Skip to content

The agent that grows with you

fix(search): degrade on unreadable paths instead of hard-failing

Byrd-IT32e21a1352ab
diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.py
index 3963868fbc6..d2fa21adb52 100644
--- a/tests/tools/test_macos_protected_search.py
+++ b/tests/tools/test_macos_protected_search.py
@@ -173,7 +173,7 @@ def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monke
command = _rg_files_commands(env.commands)[0]
assert "cd '/Users/alice' &&" in command
- assert " -- '.' '--version' 2>/dev/null" in command
+ assert " -- '.' '--version'" in command
assert result.error is None
diff --git a/tests/tools/test_search_permission_degradation.py b/tests/tools/test_search_permission_degradation.py
new file mode 100644
index 00000000000..944756826b5
--- /dev/null
+++ b/tests/tools/test_search_permission_degradation.py
@@ -0,0 +1,408 @@
+"""Regression tests: search_files degrades on unreadable (EACCES) paths.
+
+A broad file/content search over a tree containing a permission-
+restricted directory made rg exit 2. The file-discovery branch discarded stderr
+(``2>/dev/null``) and failed closed with an opaque message (or, for
+``order='modified'``, the misleading "ripgrep 14+ is required" even though the
+version gate had already passed). Content search hard-failed the same way when
+no readable file matched.
+
+Contract after the fix:
+- rg/grep exit 2 whose diagnostics are ALL permission-denied lines is a
+ partial-success condition: results already on stdout are returned, and a
+ warning names the skipped paths. With no payload, the result degrades to an
+ explicit empty result + actionable warning (never a hard error).
+- Any OTHER exit-2 diagnostic (bad glob, bad regex) still fails closed, now
+ including the diagnostic text.
+- The modified-order invocation-failure message no longer claims a version
+ problem the capability gate already ruled out.
+"""
+
+import os
+import shutil
+
+import pytest
+
+from tools.file_operations import ShellFileOperations
+from tools.file_operations_search import (
+ _extract_unreadable_paths,
+ _is_permission_only_error,
+)
+from tools.environments.local import LocalEnvironment
+
+
+# --- unit coverage for the helpers ----------------------------------------------
+
+
+def test_permission_only_true_for_all_denied_lines():
+ diagnostics = (
+ "rg: /srv/locked: Permission denied (os error 13)\n"
+ "rg: /srv/other: Permission denied (os error 13)\n"
+ )
+ assert _is_permission_only_error(diagnostics) is True
+
+
+def test_permission_only_false_when_any_other_diagnostic():
+ diagnostics = (
+ "rg: /srv/locked: Permission denied (os error 13)\n"
+ "rg: error parsing glob '[': unclosed character class\n"
+ )
+ assert _is_permission_only_error(diagnostics) is False
+
+
+def test_permission_only_false_for_empty_diagnostics():
+ assert _is_permission_only_error("") is False
+
+
+def test_extract_paths_handles_both_rg_shapes_and_dedups():
+ diagnostics = (
+ "rg: /srv/a: Permission denied (os error 13)\n"
+ "rg: /srv/b: IO error for operation on /srv/b: Permission denied (os error 13)\n"
+ "rg: /srv/a: Permission denied (os error 13)\n"
+ )
+ assert _extract_unreadable_paths(diagnostics) == ["/srv/a", "/srv/b"]
+
+
+# GNU grep spells the same condition without ripgrep's "(os error N)" suffix
+# (captured from grep 3.11: ``grep -rnHE needle <tree with a chmod 000 dir>``).
+GREP_EACCES = (
+ "grep: /srv/locked: Permission denied\n"
+ "grep: /srv/unread.txt: Permission denied\n"
+)
+
+
+def test_permission_only_true_for_grep_denied_lines():
+ assert _is_permission_only_error(GREP_EACCES) is True
+
+
+def test_permission_only_false_for_grep_other_diagnostic():
+ diagnostics = GREP_EACCES + "grep: /srv/gone: No such file or directory\n"
+ assert _is_permission_only_error(diagnostics) is False
+
+
+def test_extract_paths_handles_grep_shape():
+ assert _extract_unreadable_paths(GREP_EACCES) == ["/srv/locked", "/srv/unread.txt"]
+
+
+def test_extract_paths_ignores_other_diagnostics():
+ assert _extract_unreadable_paths("rg: regex parse error:\n^") == []
+
+
+# --- fake environments -----------------------------------------------------------
+
+
+class RecordingEnvironment:
+ """Minimal non-local env fake matching the engine-selection test harness."""
+
+ is_local = False
+ cwd = "/repo"
+
+ def __init__(self, *, rg_output="", rg_code=0, rg_version="ripgrep 14.1.0\n"):
+ self.commands = []
+ self.rg_output = rg_output
+ self.rg_code = rg_code
+ self.rg_version = rg_version
+
+ def execute(self, command, **kwargs):
+ self.commands.append(command)
+ if command.startswith("test -e "):
+ return {"output": "exists\n", "returncode": 0}
+ if command.startswith("command -v rg"):
+ return {"output": "/usr/bin/rg\n", "returncode": 0}
+ if "--version" in command:
+ return {"output": self.rg_version, "returncode": 0}
+ if "--files" in command:
+ return {"output": self.rg_output, "returncode": self.rg_code}
+ if "--line-number" in command:
+ # rg content-search invocation (goes through the same canned output).
+ return {"output": self.rg_output, "returncode": self.rg_code}
+ if "--count-matches" in command:
+ return {"output": "", "returncode": 1}
+ return {"output": "", "returncode": 1}
+
+ @property
+ def rg_commands(self):
+ return [command for command in self.commands if "--files" in command]
+
+
+class GrepOnlyEnvironment(RecordingEnvironment):
+ """Same harness but without rg, forcing the bounded-find fallback."""
+
+ def execute(self, command, **kwargs):
+ self.commands.append(command)
+ if command.startswith("test -e "):
+ return {"output": "exists\n", "returncode": 0}
+ if command.startswith("command -v rg"):
+ return {"output": "", "returncode": 1}
+ if command.startswith("command -v find"):
+ return {"output": "yes\n", "returncode": 0}
+ if "find " in command:
+ return {"output": self.rg_output, "returncode": self.rg_code}
+ return {"output": "", "returncode": 1}
+
+
+class GrepContentEnvironment(RecordingEnvironment):
+ """No rg, grep present: content search takes the plain ``grep -r`` lane."""
+
+ def execute(self, command, **kwargs):
+ self.commands.append(command)
+ if command.startswith("test -e "):
+ return {"output": "exists\n", "returncode": 0}
+ if command.startswith("command -v rg"):
+ return {"output": "", "returncode": 1}
+ if command.startswith("command -v grep"):
+ return {"output": "yes\n", "returncode": 0}
+ if "grep -rnHE" in command:
+ return {"output": self.rg_output, "returncode": self.rg_code}
+ return {"output": "", "returncode": 1}
+
+
+EACCES_DIR = "rg: /srv/locked: Permission denied (os error 13)\n"
+EACCES_DIR_SORTED = (
+ "rg: /srv/locked: IO error for operation on /srv/locked: "
+ "Permission denied (os error 13)\n"
+)
+
+
+# --- file discovery (rg lane) ----------------------------------------------------
+
+
[email protected]("order", ["discovery", "modified"])
+def test_file_search_with_unreadable_dir_returns_partial_results(order):
+ output = EACCES_DIR + "/repo/partial.py\n"
+ env = RecordingEnvironment(rg_output=output, rg_code=2)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/repo", target="files", order=order)
+
+ assert result.error is None
+ assert result.files == ["/repo/partial.py"]
+ assert result.total_count == 1
+ assert "unreadable path" in (result.warning or "")
+ assert "/srv/locked" in (result.warning or "")
+
+
+def test_file_search_modified_uses_io_error_diagnostic_shape():
+ env = RecordingEnvironment(rg_output=EACCES_DIR_SORTED + "/repo/partial.py\n", rg_code=2)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/repo", target="files", order="modified")
+
+ assert result.error is None
+ assert result.files == ["/repo/partial.py"]
+ assert "/srv/locked" in (result.warning or "")
+
+
[email protected]("order", ["discovery", "modified"])
+def test_file_search_fully_unreadable_degrades_to_actionable_empty(order):
+ env = RecordingEnvironment(rg_output=EACCES_DIR, rg_code=2)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/srv", target="files", order=order)
+
+ assert result.error is None
+ assert result.files == []
+ assert result.total_count == 0
+ assert "unreadable path" in (result.warning or "")
+ assert "fix permissions" in (result.warning or "")
+
+
+def test_file_search_non_permission_exit2_still_fails_closed_with_detail():
+ env = RecordingEnvironment(
+ rg_output="rg: error parsing glob '[': unclosed character class\n", rg_code=2)
+
+ result = ShellFileOperations(env).search("*.py", path="/repo", target="files")
+
+ assert result.error is not None
+ assert result.files == []
+ assert "File search failed while running ripgrep" in result.error
+ assert "unclosed character class" in result.error
+
+
+def test_file_search_modified_non_permission_error_no_longer_blames_version():
+ env = RecordingEnvironment(
+ rg_output="rg: /srv/broken: IO error: disk exploded\n", rg_code=2)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/repo", target="files", order="modified")
+
+ assert result.error is not None
+ assert "exact modification-time order" in result.error.lower()
+ assert "ripgrep" in result.error
+ assert "invocation failure" in result.error
+ assert "disk exploded" in result.error
+ assert "Upgrade ripgrep" not in result.error
+
+
+def test_file_search_permission_degrade_keeps_timeout_limit_reason():
+ output = EACCES_DIR + "/repo/partial.py\n[Command timed out after 60s]\n"
+ env = RecordingEnvironment(rg_output=output, rg_code=124)
+
+ result = ShellFileOperations(env).search("*.py", path="/repo", target="files")
+
+ assert result.error is None
+ assert result.files == ["/repo/partial.py"]
+ assert result.limit_reason == "search_timeout"
+ assert "unreadable path" in (result.warning or "")
+
+
+# --- content search --------------------------------------------------------------
+
+
+def test_content_search_with_unreadable_dir_returns_partial_matches():
+ output = EACCES_DIR + "/repo/a.py:3:needle\n"
+ env = RecordingEnvironment(rg_output=output, rg_code=2)
+
+ result = ShellFileOperations(env).search(
+ "needle", path="/repo", target="content")
+
+ assert result.error is None
+ assert [(m.path, m.line_number, m.content) for m in result.matches] == [
+ ("/repo/a.py", 3, "needle")]
+ assert "unreadable path" in (result.warning or "")
+ assert "/srv/locked" in (result.warning or "")
+
+
+def test_content_search_fully_unreadable_degrades_to_actionable_empty():
+ env = RecordingEnvironment(rg_output=EACCES_DIR, rg_code=2)
+
+ result = ShellFileOperations(env).search("needle", path="/srv", target="content")
+
+ assert result.error is None
+ assert result.total_count == 0
+ assert "unreadable path" in (result.warning or "")
+ assert "fix permissions" in (result.warning or "")
+
+
+def test_content_search_hard_error_regex_still_surfaced():
+ env = RecordingEnvironment(
+ rg_output="rg: regex parse error:\n (?:[\n ^\nerror: unclosed character class\n",
+ rg_code=2)
+
+ result = ShellFileOperations(env).search("[", path="/repo", target="content")
+
+ assert result.error is not None
+ assert result.error.startswith("Search failed: rg: regex parse error:")
+ assert "unclosed character class" in result.error
+ assert result.warning is None
+
+
+# --- content search, grep lane (rg absent) ---------------------------------------
+
+
+def test_grep_content_search_with_unreadable_paths_returns_partial_matches():
+ output = "grep: /repo/locked: Permission denied\n/repo/a.py:3:needle\n"
+ env = GrepContentEnvironment(rg_output=output, rg_code=2)
+
+ result = ShellFileOperations(env).search("needle", path="/repo", target="content")
+
+ assert any("grep -rnHE" in command for command in env.commands)
+ assert result.error is None
+ assert [(m.path, m.line_number, m.content) for m in result.matches] == [
+ ("/repo/a.py", 3, "needle")]
+ assert "unreadable path" in (result.warning or "")
+ assert "/repo/locked" in (result.warning or "")
+
+
+def test_grep_content_search_fully_unreadable_degrades_to_actionable_empty():
+ env = GrepContentEnvironment(rg_output=GREP_EACCES, rg_code=2)
+
+ result = ShellFileOperations(env).search("needle", path="/srv", target="content")
+
+ assert result.error is None
+ assert result.total_count == 0
+ assert "/srv/locked" in (result.warning or "")
+ assert "fix permissions" in (result.warning or "")
+
+
+def test_grep_content_search_non_permission_error_still_fails_closed():
+ env = GrepContentEnvironment(
+ rg_output="grep: Unmatched ( or \\(\n", rg_code=2)
+
+ result = ShellFileOperations(env).search("(", path="/repo", target="content")
+
+ assert result.error is not None
+ assert "Unmatched" in result.error
+
+
+# --- bounded-find fallback --------------------------------------------------------
+
+
[email protected]("order", ["discovery", "modified"])
+def test_find_exit1_with_payload_degrades_to_partial(order):
+ output = "/narrow/partial.py\n" if order == "discovery" else "10 /narrow/partial.py\n"
+ env = GrepOnlyEnvironment(rg_output=output, rg_code=1)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/narrow", target="files", order=order)
+
+ assert result.error is None
+ assert result.files == ["/narrow/partial.py"]
+ assert result.total_count == 1
+ assert result.warning is not None
+ assert "unreadable" in (result.warning or "")
+ assert "partial" in (result.warning or "")
+
+
[email protected]("order", ["discovery", "modified"])
+def test_find_exit1_with_empty_payload_still_fails_closed(order):
+ env = GrepOnlyEnvironment(rg_output="", rg_code=1)
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/narrow", target="files", order=order)
+
+ assert result.error is not None
+ assert result.files == []
+
+
+def test_find_exit2_still_fails_closed():
+ env = GrepOnlyEnvironment(rg_output="/narrow/partial.py\n", rg_code=2)
+
+ result = ShellFileOperations(env).search("*.py", path="/narrow", target="files")
+
+ assert result.error is not None
+ assert result.files == []
+
+
+# --- live end-to-end (real rg, real filesystem) -----------------------------------
+
+
[email protected](shutil.which("rg") is None, reason="ripgrep not installed")
[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root reads chmod 000 dirs")
+def test_live_file_search_skips_unreadable_dir(tmp_path):
+ (tmp_path / "open").mkdir()
+ (tmp_path / "open" / "a.py").write_text("x = 1\n")
+ locked = tmp_path / "locked"
+ locked.mkdir()
+ (locked / "secret.py").write_text("x = 2\n")
+ os.chmod(locked, 0o000)
+ try:
+ ops = ShellFileOperations(LocalEnvironment(str(tmp_path)), cwd=str(tmp_path))
+ result = ops.search("*.py", path=str(tmp_path), target="files")
+ assert result.error is None
+ assert result.files == [str(tmp_path / "open" / "a.py")]
+ assert result.total_count == 1
+ assert str(locked) in (result.warning or "")
+ finally:
+ os.chmod(locked, 0o755)
+
+
[email protected](shutil.which("rg") is None, reason="ripgrep not installed")
[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root reads chmod 000 dirs")
+def test_live_content_search_skips_unreadable_dir(tmp_path):
+ (tmp_path / "open").mkdir()
+ (tmp_path / "open" / "a.py").write_text("needle here\n")
+ locked = tmp_path / "locked"
+ locked.mkdir()
+ (locked / "secret.py").write_text("needle hidden\n")
+ os.chmod(locked, 0o000)
+ try:
+ ops = ShellFileOperations(LocalEnvironment(str(tmp_path)), cwd=str(tmp_path))
+ result = ops.search("needle", path=str(tmp_path), target="content")
+ assert result.error is None
+ assert [m.path for m in result.matches] == [str(tmp_path / "open" / "a.py")]
+ assert str(locked) in (result.warning or "")
+ finally:
+ os.chmod(locked, 0o755)
\ No newline at end of file
diff --git a/tools/file_operations_search.py b/tools/file_operations_search.py
index 496e9d9025d..1151c6ff352 100644
--- a/tools/file_operations_search.py
+++ b/tools/file_operations_search.py
@@ -157,6 +157,65 @@ def _split_tool_diagnostics(output: str) -> tuple[str, str]:
return '\n'.join(diagnostics), '\n'.join(payload)
+# One unreadable-path diagnostic, in every shape the search lanes produce:
+# rg: ``rg: <path>: Permission denied (os error 13)``
+# rg modified-sort walk: ``rg: <path>: IO error for operation on <path>: Permission denied (os error 13)``
+# grep: ``grep: <path>: Permission denied`` (no ``(os error N)`` suffix)
+# The ``(os error N)`` suffix is ripgrep's Rust io::Error spelling, so it is optional.
+_PERMISSION_DENIED_RE = re.compile(
+ r"^(?:(?:rg|grep): )?(?P<path>.+?): "
+ r"(?:IO error for operation on .+?: )?Permission denied(?: \(os error \d+\))?$")
+
+
+def _is_permission_only_error(diagnostics: str) -> bool:
+ """True when every diagnostic line reports an unreadable path (rg or grep).
+ That is a partial-success condition — the tool still emits results for the
+ readable remainder — not a broken invocation like a bad glob or regex."""
+ lines = [line.strip() for line in diagnostics.splitlines() if line.strip()]
+ return bool(lines) and all(_PERMISSION_DENIED_RE.match(line) for line in lines)
+
+
+def _extract_unreadable_paths(diagnostics: str) -> list[str]:
+ """Paths reported unreadable by rg or grep, deduplicated in first-seen order."""
+ paths: list[str] = []
+ for line in diagnostics.splitlines():
+ match = _PERMISSION_DENIED_RE.match(line.strip())
+ if not match:
+ continue
+ path = match.group("path").strip()
+ if path and path not in paths:
+ paths.append(path)
+ return paths
+
+
+def _compact_unreadable_paths(paths: list[str], keep: int = 3) -> str:
+ shown = ", ".join(paths[:keep])
+ extra = len(paths) - keep
+ return shown + (f" (+{extra} more)" if extra > 0 else "")
+
+
+def _skipped_unreadable_warning(paths: list[str]) -> str:
+ return ("Skipped " + str(len(paths)) + " unreadable path(s) with restricted "
+ "permissions: " + _compact_unreadable_paths(paths)
+ + ". Results are partial; fix permissions or search the path directly "
+ "to include it.")
+
+
+def _prepend_skipped_paths_warning(diagnostics: str, existing: Optional[str]) -> Optional[str]:
+ """Warning naming the skipped unreadable paths, prepended to any existing warning."""
+ paths = _extract_unreadable_paths(diagnostics)
+ if not paths:
+ return existing
+ warning = _skipped_unreadable_warning(paths)
+ return warning if not existing else f"{warning} {existing}"
+
+
+_PERMISSION_SEARCH_HINT = (
+ "Every reported path was skipped for restricted permissions, so the searchable "
+ "scope itself is unreadable: fix permissions (e.g. chown the path back to the "
+ "service user) or search a readable subtree.")
+
+
def _parse_search_context_line(line: str) -> tuple[str, int, str] | None:
"""Parse a ``path-line-content`` context line using the RIGHTMOST numeric
separator (filenames may contain ``-<digits>-`` segments):
@@ -219,7 +278,18 @@ def _parse_search_output(result, output_mode: str, limit: int, offset: int,
diagnostics, payload = _split_tool_diagnostics(stdout)
if result.exit_code == 2 and not payload.strip():
error_msg = diagnostics.strip() or result.stdout.strip() or "Search error"
+ if _is_permission_only_error(error_msg):
+ # Pure unreadable-path failure: rg read nothing but the invocation was
+ # sound. Degrade to an explicit empty result instead of failing — the
+ # model can still act on the named paths.
+ warning = _prepend_skipped_paths_warning(error_msg, warning)
+ if not warning:
+ warning = _PERMISSION_SEARCH_HINT
+ elif _PERMISSION_SEARCH_HINT not in warning:
+ warning = f"{warning} {_PERMISSION_SEARCH_HINT}"
+ return SearchResult(total_count=0, warning=warning)
return SearchResult(error=f"Search failed: {error_msg}", total_count=0)
+ warning = _prepend_skipped_paths_warning(diagnostics, warning)
lines = [ln for ln in payload.strip().split('\n') if ln]
if output_mode == "files_only":
return SearchResult(
@@ -905,12 +975,28 @@ class SearchMixin:
elif line:
raw_files.append(line)
bounded_sigpipe = result.exit_code == 141 and len(raw_files) >= fetch_limit
- if result.exit_code not in {0, 124} and not bounded_sigpipe:
+ if result.exit_code not in {0, 1, 124} and not bounded_sigpipe:
if order == "modified":
return SearchResult(error=(
"Exact modification-time order requires GNU find with "
"-printf support; install ripgrep 14+ or use order='discovery'."))
return SearchResult(error="File search failed while running bounded find traversal.")
+ # GNU find exits 1 when traversal hit unreadable dirs (EACCES et al.) but
+ # still prints what it could read. With a payload that is a partial-success
+ # condition (stderr is discarded, so the paths cannot be named here); with
+ # an empty payload it is a real failure (parse errors also exit 1).
+ partial_warning: Optional[str] = None
+ if result.exit_code == 1 and not bounded_sigpipe:
+ if not raw_files:
+ if order == "modified":
+ return SearchResult(error=(
+ "Exact modification-time order requires GNU find with "
+ "-printf support; install ripgrep 14+ or use order='discovery'."))
+ return SearchResult(error="File search failed while running bounded find traversal.")
+ partial_warning = (
+ "find traversal skipped one or more unreadable paths (restricted "
+ "permissions); results are partial. Fix permissions or search a "
+ "readable subtree to include them.")
from tools.environments.base import env_uses_host_filesystem
from tools.environments.local import _IS_WINDOWS, _msys_to_windows_path
@@ -918,7 +1004,8 @@ class SearchMixin:
raw_files = [_msys_to_windows_path(file_path) for file_path in raw_files]
return SearchResult(
files=raw_files[offset:offset + limit], total_count=len(raw_files),
- truncated=len(raw_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason)
+ truncated=len(raw_files) > offset + limit or bool(limit_reason),
+ limit_reason=limit_reason, warning=partial_warning)
def _search_files_rg(self, pattern: str, path: str | list[str], limit: int, offset: int,
order: str = "discovery", rg_executable: Optional[str] = None) -> SearchResult:
@@ -965,20 +1052,45 @@ class SearchMixin:
rg_cmd = (f"{rg} --files{sort_arg} -g {self._escape_shell_arg(glob_pattern)}"
f"{exclusion_args} -- {root_args}")
result = self._run_rg_bounded([rg_cmd], fetch_limit, timeout=60, native_ok=not scoped_common,
+ merge_stderr=True,
shell_prefix=f"set -o pipefail; {cd_prefix}")
stdout, limit_reason = _search_stdout_and_limit(result)
- all_files = [f for f in stdout.splitlines() if f]
+ # Files-mode transport mixes stderr into stdout, but file paths may contain
+ # spaces — the content-mode shape matcher (_SEARCH_OUTPUT_RE) would drop
+ # them as "diagnostics". rg/grep diagnostic lines always begin with
+ # "rg: "/"grep: " (continuation lines only matter on the fail-closed path),
+ # so classify by that prefix instead.
+ stdout_lines = stdout.splitlines()
+ diagnostics = "\n".join(
+ line for line in stdout_lines if line.lstrip().startswith(("rg: ", "grep: ")))
+ all_files = [
+ line for line in stdout_lines
+ if line and not line.lstrip().startswith(("rg: ", "grep: "))]
+ # Permission-denied diagnostics are partial-success signals independent of
+ # the exit code: exit 2 = traversal hit unreadable paths (degrade below),
+ # exit 124 = timed out while ALSO skipping them (warning rides along).
+ skipped = _extract_unreadable_paths(diagnostics) \
+ if _is_permission_only_error(diagnostics) else []
+ permission_only = result.exit_code == 2 and bool(skipped)
+ warning = _skipped_unreadable_warning(skipped) if skipped else None
if scoped_common:
all_files = [
f if posixpath.isabs(f) else posixpath.normpath(posixpath.join(scoped_common, f))
for f in all_files]
bounded_sigpipe = result.exit_code == 141 and len(all_files) >= fetch_limit
- if result.exit_code not in {0, 1, 124} and not bounded_sigpipe:
+ if (result.exit_code not in {0, 1, 124} and not bounded_sigpipe
+ and not permission_only):
+ detail = diagnostics.strip() or "no diagnostics"
if order == "modified":
+ # ripgrep 14+ was already verified by the capability gate, so this
+ # failure is an invocation/traversal error, not a version problem.
return SearchResult(error=(
- "Exact modification-time order failed; ripgrep 14+ is "
- "required. Upgrade ripgrep or use order='discovery'."))
- return SearchResult(error="File search failed while running ripgrep.")
+ "Exact modification-time order search failed (ripgrep 14+ "
+ "required for --sortr=modified; the installed rg passed the "
+ f"version check, so this is an invocation failure: {detail}). "
+ "Use order='discovery'."))
+ return SearchResult(error=(
+ f"File search failed while running ripgrep: {detail}"))
# 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
@@ -994,9 +1106,13 @@ class SearchMixin:
# the merged view keeps the newest-first contract globally.
all_files = merged_entries
limit_reason = limit_reason or directory_limit_reason
+ if permission_only and not all_files:
+ return SearchResult(files=[], total_count=0,
+ warning=f"{warning} {_PERMISSION_SEARCH_HINT}")
return 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)
+ truncated=len(all_files) > offset + limit or bool(limit_reason),
+ limit_reason=limit_reason, warning=warning)
def _search_content(self, pattern: str, path: str, file_glob: Optional[str],
limit: int, offset: int, output_mode: str, context: int) -> SearchResult: