Skip to content

The agent that grows with you

feat(search): add fast discovery file ordering

Royalaid413fd2a1fcbf
diff --git a/tests/tools/test_search_files_engine_selection.py b/tests/tools/test_search_files_engine_selection.py
new file mode 100644
index 00000000000..c887f766094
--- /dev/null
+++ b/tests/tools/test_search_files_engine_selection.py
@@ -0,0 +1,288 @@
+"""Behavior tests for file-search ordering and ripgrep selection."""
+
+import json
+import re
+
+import pytest
+
+from tools.environments.local import LocalEnvironment
+from tools.file_operations import SearchResult, ShellFileOperations
+from tools.file_tools import SEARCH_FILES_SCHEMA, _handle_search_files, search_tool
+
+
+class RecordingEnvironment:
+ is_local = False
+ cwd = "/repo"
+
+ def __init__(self, *, rg_output="/repo/one.py\n/repo/two.py\n", rg_code=0):
+ self.commands = []
+ self.rg_output = rg_output
+ self.rg_code = rg_code
+
+ 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": "/opt/Rip Grep/rg\n", "returncode": 0}
+ if "--files" in command:
+ return {"output": self.rg_output, "returncode": self.rg_code}
+ return {"output": "", "returncode": 1}
+
+ @property
+ def rg_commands(self):
+ return [command for command in self.commands if "--files" in command]
+
+
+def test_schema_exposes_fast_discovery_default_and_exact_modified_opt_in():
+ order = SEARCH_FILES_SCHEMA["parameters"]["properties"]["order"]
+
+ assert order["enum"] == ["discovery", "modified"]
+ assert order["default"] == "discovery"
+ assert "fast bounded traversal order" in order["description"]
+ assert "exact global newest-first" in order["description"]
+ assert "ignored for content" in order["description"]
+
+
+def test_default_file_search_runs_one_bounded_unsorted_rg_command():
+ env = RecordingEnvironment()
+ ops = ShellFileOperations(env)
+
+ result = ops.search("*.py", path="/repo", target="files", limit=1, offset=1)
+
+ assert result.files == ["/repo/two.py"]
+ assert len(env.rg_commands) == 1
+ assert "--sortr" not in env.rg_commands[0]
+ assert "head -n 2" in env.rg_commands[0]
+
+
+def test_modified_file_search_runs_one_exact_order_rg_command():
+ env = RecordingEnvironment()
+ ops = ShellFileOperations(env)
+
+ result = ops.search("*.py", path="/repo", target="files", order="modified")
+
+ assert result.error is None
+ assert len(env.rg_commands) == 1
+ assert "--sortr=modified" in env.rg_commands[0]
+
+
+def test_empty_discovery_output_is_zero_matches_without_retry():
+ env = RecordingEnvironment(rg_output="", rg_code=0)
+ ops = ShellFileOperations(env)
+
+ result = ops.search("*.missing", path="/repo", target="files")
+
+ assert result.error is None
+ assert result.files == []
+ assert result.total_count == 0
+ assert len(env.rg_commands) == 1
+
+
+def test_modified_capability_failure_is_actionable_and_not_downgraded():
+ env = RecordingEnvironment(rg_output="", rg_code=2)
+ ops = ShellFileOperations(env)
+
+ result = ops.search("*.py", path="/repo", target="files", order="modified")
+
+ assert len(env.rg_commands) == 1
+ assert result.error is not None
+ assert "exact modification-time order" in result.error.lower()
+ assert "ripgrep" in result.error
+
+
+def test_invalid_direct_file_order_returns_structured_error():
+ env = RecordingEnvironment()
+ ops = ShellFileOperations(env)
+
+ result = ops.search("*.py", path="/repo", target="files", order="random")
+
+ assert isinstance(result, SearchResult)
+ assert result.error == "Invalid file search order 'random'; expected 'discovery' or 'modified'."
+ assert env.rg_commands == []
+
+
+def test_handler_forwards_modified_order(monkeypatch):
+ captured = {}
+
+ def fake_search_tool(**kwargs):
+ captured.update(kwargs)
+ return "{}"
+
+ monkeypatch.setattr("tools.file_tools.search_tool", fake_search_tool)
+
+ _handle_search_files({"pattern": "*.py", "target": "files", "order": "modified"})
+
+ assert captured["order"] == "modified"
+
+
+def test_repeated_search_key_distinguishes_order(monkeypatch):
+ class StubOperations:
+ def search(self, **kwargs):
+ return SearchResult()
+
+ monkeypatch.setattr("tools.file_tools._get_file_ops", lambda task_id: StubOperations())
+ task_id = "engine-order-key"
+ for _ in range(3):
+ assert "BLOCKED" not in json.loads(
+ search_tool("*.py", target="files", order="discovery", task_id=task_id)
+ ).get("error", "")
+
+ changed = json.loads(
+ search_tool("*.py", target="files", order="modified", task_id=task_id)
+ )
+
+ assert "BLOCKED" not in changed.get("error", "")
+
+
+class RipgrepInvocationEnvironment(RecordingEnvironment):
+ 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": "/opt/Rip Grep/rg\n", "returncode": 0}
+ if "--files" in command:
+ return {"output": "/repo/a.py\n", "returncode": 0}
+ if "--line-number" in command:
+ return {"output": "/repo/a.py:1:needle\n", "returncode": 0}
+ if "--count-matches" in command:
+ return {"output": "", "returncode": 1}
+ return {"output": "", "returncode": 1}
+
+
+def test_resolved_executable_with_spaces_is_used_by_every_rg_invocation():
+ env = RipgrepInvocationEnvironment()
+ ops = ShellFileOperations(env)
+
+ assert ops.search("*.py", path="/repo", target="files").files
+ assert ops.search("needle", path="/repo", target="content").matches
+ assert ops._zero_match_probe("absent", "/repo", None) is None
+
+ invocations = [
+ command for command in env.commands
+ if any(flag in command for flag in ("--files", "--line-number", "--count-matches"))
+ ]
+ assert invocations
+ assert all("'/opt/Rip Grep/rg'" in command for command in invocations)
+ assert all(not re.search(r"(?:^|[; ])rg\s", command) for command in invocations)
+ assert len([c for c in env.commands if c.startswith("command -v rg")]) == 1
+
+
+def test_off_path_windows_rg_miss_is_reprobed_then_success_is_cached(
+ tmp_path, monkeypatch
+):
+ local_app_data = tmp_path / "Local Data"
+ candidate = local_app_data / "Microsoft" / "WinGet" / "Links" / "rg.exe"
+ monkeypatch.setenv("LOCALAPPDATA", str(local_app_data))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "User Profile"))
+ monkeypatch.delenv("SCOOP", raising=False)
+ ops = ShellFileOperations(LocalEnvironment(str(tmp_path)))
+ probes = []
+
+ def command_v_miss(command, **kwargs):
+ probes.append(command)
+ from tools.file_operations import ExecuteResult
+ return ExecuteResult(stdout="", exit_code=1)
+
+ monkeypatch.setattr(ops, "_exec", command_v_miss)
+
+ assert ops._resolve_command("rg") is None
+ candidate.parent.mkdir(parents=True)
+ candidate.write_text("")
+ expected = str(candidate).replace("\\", "/")
+ assert ops._resolve_command("rg") == expected
+ assert ops._resolve_command("rg") == expected
+ assert probes == ["command -v rg 2>/dev/null", "command -v rg 2>/dev/null"]
+
+
+def test_remote_resolution_never_probes_controller_host_paths(tmp_path, monkeypatch):
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "controller-local"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "controller-user"))
+ env = RecordingEnvironment()
+
+ def miss(command, **kwargs):
+ env.commands.append(command)
+ return {"output": "", "returncode": 1}
+
+ env.execute = miss
+ ops = ShellFileOperations(env)
+
+ assert ops._resolve_command("rg") is None
+ assert env.commands == ["command -v rg 2>/dev/null"]
+ assert str(tmp_path) not in env.commands[0]
+
+
+def test_remote_msys_shaped_executable_is_not_rewritten_as_controller_path():
+ env = RecordingEnvironment()
+
+ def execute(command, **kwargs):
+ env.commands.append(command)
+ if command.startswith("test -e "):
+ return {"output": "exists\n", "returncode": 0}
+ if command.startswith("command -v rg"):
+ return {"output": "/c/remote-tools/rg\n", "returncode": 0}
+ if "--files" in command:
+ return {"output": "/repo/a.py\n", "returncode": 0}
+ return {"output": "", "returncode": 1}
+
+ env.execute = execute
+
+ result = ShellFileOperations(env).search("*.py", path="/repo", target="files")
+
+ assert result.files
+ assert "'/c/remote-tools/rg' --files" in env.rg_commands[0]
+ assert "C:/remote-tools/rg" not in env.rg_commands[0]
+
+
+def test_modified_multi_path_search_preserves_exact_order_request():
+ env = RecordingEnvironment()
+
+ def execute(command, **kwargs):
+ env.commands.append(command)
+ if command.startswith("test -e "):
+ if "'/one /two'" in command:
+ return {"output": "not_found\n", "returncode": 0}
+ return {"output": "exists\n", "returncode": 0}
+ if command.startswith("command -v rg"):
+ return {"output": "/usr/bin/rg\n", "returncode": 0}
+ if "--files" in command:
+ return {"output": "found.py\n", "returncode": 0}
+ return {"output": "", "returncode": 1}
+
+ env.execute = execute
+ result = ShellFileOperations(env).search(
+ "*.py", path="/one /two", target="files", order="modified"
+ )
+
+ assert result.error is None
+ assert len(env.rg_commands) == 2
+ assert all("--sortr=modified" in command for command in env.rg_commands)
+
+
+def test_modified_timeout_preserves_partial_results_and_limit_reason():
+ env = RecordingEnvironment(
+ rg_output="/repo/partial.py\n[Command timed out after 60s]\n",
+ rg_code=124,
+ )
+
+ result = ShellFileOperations(env).search(
+ "*.py", path="/repo", target="files", order="modified"
+ )
+
+ assert result.files == ["/repo/partial.py"]
+ assert result.truncated is True
+ assert result.limit_reason == "search_timeout"
+
+
+def test_order_is_ignored_for_content_search():
+ env = RipgrepInvocationEnvironment()
+
+ result = ShellFileOperations(env).search(
+ "needle", path="/repo", target="content", order="not-a-file-order"
+ )
+
+ assert result.error is None
+ assert result.matches
diff --git a/tools/file_operations.py b/tools/file_operations.py
index 8e2bd2952ff..89f5268888a 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -627,7 +627,8 @@ class FileOperations(ABC):
@abstractmethod
def search(self, pattern: str, path: str = ".", target: str = "content",
file_glob: Optional[str] = None, limit: int = 50, offset: int = 0,
- output_mode: str = "content", context: int = 0) -> SearchResult:
+ output_mode: str = "content", context: int = 0,
+ order: str = "discovery") -> SearchResult:
"""Search for content or files."""
...
@@ -997,8 +998,9 @@ class ShellFileOperations(FileOperations):
self.cwd = cwd or getattr(terminal_env, 'cwd', None) or \
getattr(getattr(terminal_env, 'config', None), 'cwd', None) or "/"
- # Cache for command availability checks
- self._command_cache: Dict[str, bool] = {}
+ # Cache successful command resolutions. Misses are deliberately not
+ # cached so a tool installed while this instance is alive is visible.
+ self._command_cache: Dict[str, str] = {}
def _exec(self, command: str, cwd: str = None, timeout: int = None,
stdin_data: str = None) -> ExecuteResult:
@@ -1039,12 +1041,62 @@ class ShellFileOperations(FileOperations):
exit_code=exit_code
)
+ def _resolve_command(self, cmd: str) -> Optional[str]:
+ """Resolve an executable in the command host's namespace.
+
+ Only successful resolutions are cached. Native Windows local searches
+ additionally recognize common off-PATH ripgrep install locations;
+ remote backends must resolve exclusively in their own namespace.
+ """
+ cached = self._command_cache.get(cmd)
+ if cached:
+ return cached
+
+ result = self._exec(f"command -v {cmd} 2>/dev/null")
+ if result.exit_code == 0 and result.stdout.strip():
+ resolved = result.stdout.strip().splitlines()[0]
+ # Compatibility with test/fake environments that historically
+ # answered the old boolean probe with the literal "yes".
+ if resolved == "yes":
+ resolved = cmd
+ self._command_cache[cmd] = resolved
+ return resolved
+
+ if cmd == "rg":
+ from tools.environments.local import LocalEnvironment, _IS_WINDOWS
+
+ if _IS_WINDOWS and isinstance(self.env, LocalEnvironment):
+ user_profile = os.environ.get("USERPROFILE") or str(Path.home())
+ local_app_data = os.environ.get("LOCALAPPDATA")
+ scoop = os.environ.get("SCOOP") or os.path.join(user_profile, "scoop")
+ candidates = [
+ os.path.join(user_profile, ".cargo", "bin", "rg.exe"),
+ os.path.join(scoop, "shims", "rg.exe"),
+ ]
+ if local_app_data:
+ candidates.append(
+ os.path.join(local_app_data, "Microsoft", "WinGet", "Links", "rg.exe")
+ )
+ for candidate in candidates:
+ if os.path.isfile(candidate):
+ resolved = candidate.replace("\\", "/")
+ self._command_cache[cmd] = resolved
+ return resolved
+ return None
+
def _has_command(self, cmd: str) -> bool:
- """Check if a command exists in the environment (cached)."""
- if cmd not in self._command_cache:
- result = self._exec(f"command -v {cmd} >/dev/null 2>&1 && echo 'yes'")
- self._command_cache[cmd] = result.stdout.strip() == 'yes'
- return self._command_cache[cmd]
+ """Return whether a command resolves in the execution environment."""
+ return self._resolve_command(cmd) is not None
+
+ def _quote_executable(self, executable: str) -> str:
+ """Quote an executable without leaking controller path semantics."""
+ if re.fullmatch(r"[A-Za-z0-9_.-]+", executable):
+ return executable
+ from tools.environments.local import LocalEnvironment
+
+ if isinstance(self.env, LocalEnvironment):
+ return self._escape_native_tool_arg(executable)
+ return "'" + executable.replace("'", "'\"'\"'") + "'"
def _sample_file_bytes(self, path: str, length: int = 1000):
"""Fetch the first ``length`` raw bytes of a file through the terminal.
@@ -3271,7 +3323,8 @@ class ShellFileOperations(FileOperations):
def search(self, pattern: str, path: str = ".", target: str = "content",
file_glob: Optional[str] = None, limit: int = 50, offset: int = 0,
- output_mode: str = "content", context: int = 0) -> SearchResult:
+ output_mode: str = "content", context: int = 0,
+ order: str = "discovery") -> SearchResult:
"""
Search for content or files.
@@ -3284,12 +3337,19 @@ class ShellFileOperations(FileOperations):
offset: Skip first N results
output_mode: "content", "files_only", or "count"
context: Lines of context around matches
+ order: File-search ordering: fast discovery or exact modified time
Returns:
SearchResult with matches or file list
"""
offset, limit = normalize_search_pagination(offset, limit)
+ if target == "files" and order not in {"discovery", "modified"}:
+ return SearchResult(
+ error=(f"Invalid file search order {order!r}; expected "
+ "'discovery' or 'modified'.")
+ )
+
# Expand ~ and other shell paths
path = self._expand_path(path)
@@ -3301,7 +3361,8 @@ class ShellFileOperations(FileOperations):
# failing the whole call, split, search every path that exists,
# merge the results, and report the skipped parts.
multi = self._try_multi_path_search(
- pattern, path, target, file_glob, limit, offset, output_mode, context
+ pattern, path, target, file_glob, limit, offset, output_mode, context,
+ order,
)
if multi is not None:
return multi
@@ -3336,7 +3397,7 @@ class ShellFileOperations(FileOperations):
)
if target == "files":
- result = self._search_files(pattern, path, limit, offset)
+ result = self._search_files(pattern, path, limit, offset, order)
else:
result = self._search_content(pattern, path, file_glob, limit, offset,
output_mode, context)
@@ -3373,7 +3434,8 @@ class ShellFileOperations(FileOperations):
def _try_multi_path_search(self, pattern: str, path: str, target: str,
file_glob: Optional[str], limit: int, offset: int,
- output_mode: str, context: int) -> Optional[SearchResult]:
+ output_mode: str, context: int,
+ order: str = "discovery") -> Optional[SearchResult]:
"""Recover a not-found ``path`` that is really several paths in one string.
Production trajectories show models passing "dir1 dir2 dir3" (or
@@ -3398,7 +3460,7 @@ class ShellFileOperations(FileOperations):
merged = SearchResult()
for p in existing:
if target == "files":
- sub = self._search_files(pattern, p, limit, offset)
+ sub = self._search_files(pattern, p, limit, offset, order)
else:
sub = self._search_content(pattern, p, file_glob, limit, offset,
output_mode, context)
@@ -3430,8 +3492,10 @@ class ShellFileOperations(FileOperations):
metacharacters, also probe it as a fixed string. Bounded: two rg
invocations max, count-only output.
"""
- if not self._has_command('rg'):
+ rg_executable = self._resolve_command('rg')
+ if not rg_executable:
return None
+ rg = self._quote_executable(rg_executable)
def _tally(stdout: str):
"""Parse ``path:count`` lines from rg --count-matches."""
@@ -3451,7 +3515,7 @@ class ShellFileOperations(FileOperations):
glob_expr = f" --glob {self._escape_shell_arg(file_glob)}" if file_glob else ""
probe = self._exec(
- f"rg -i --count-matches{glob_expr} "
+ f"{rg} -i --count-matches{glob_expr} "
f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
@@ -3468,7 +3532,7 @@ class ShellFileOperations(FileOperations):
# returning a bare zero (bench case: match in .hidden/ silently
# missing from results).
hidden = self._exec(
- f"rg --hidden --no-ignore --count-matches{glob_expr} "
+ f"{rg} --hidden --no-ignore --count-matches{glob_expr} "
f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
@@ -3482,7 +3546,7 @@ class ShellFileOperations(FileOperations):
)
if re.search(r"[.\[\](){}?*+^$\\|]", pattern):
fixed = self._exec(
- f"rg -F --count-matches{glob_expr} "
+ f"{rg} -F --count-matches{glob_expr} "
f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
@@ -3497,7 +3561,8 @@ class ShellFileOperations(FileOperations):
)
return None
- def _search_files(self, pattern: str, path: str, limit: int, offset: int) -> SearchResult:
+ def _search_files(self, pattern: str, path: str, limit: int, offset: int,
+ order: str = "discovery") -> SearchResult:
"""Search for files by name pattern (glob-like)."""
# Auto-prepend **/ for recursive search if not already present
if not pattern.startswith('**/') and '/' not in pattern:
@@ -3515,7 +3580,10 @@ class ShellFileOperations(FileOperations):
# default, and has parallel directory traversal (~200x faster than
# find on wide trees). Mirrors _search_content which already uses rg.
if self._has_command('rg'):
- return self._search_files_rg(search_pattern, path, limit, offset)
+ return self._search_files_rg(
+ search_pattern, path, limit, offset, order,
+ rg_executable=self._resolve_command("rg") or "rg",
+ )
# Fallback: find (slower, no .gitignore awareness)
if not self._has_command('find'):
@@ -3602,13 +3670,15 @@ class ShellFileOperations(FileOperations):
limit_reason=limit_reason,
)
- def _search_files_rg(self, pattern: str, path: str, limit: int, offset: int) -> SearchResult:
+ def _search_files_rg(self, pattern: str, path: str, limit: int, offset: int,
+ order: str = "discovery",
+ rg_executable: Optional[str] = None) -> SearchResult:
"""Search for files by name using ripgrep's --files mode.
rg --files respects .gitignore and excludes hidden directories by
default, and uses parallel directory traversal for ~200x speedup
- over find on wide trees. Results are sorted by modification time
- (most recently edited first) when rg >= 13.0 supports --sortr.
+ over find on wide trees. Discovery order stays bounded and fast;
+ exact modification-time ordering is explicit because it scans globally.
"""
# rg --files -g uses glob patterns; wrap bare names so they match
# at any depth (equivalent to find -name).
@@ -3623,28 +3693,29 @@ class ShellFileOperations(FileOperations):
for item in self._macos_search_exclusions(path)
)
exclusion_args = f" {exclusion_globs}" if exclusion_globs else ""
- # Try mtime-sorted first (rg 13+); fall back to unsorted if not supported.
- cmd_sorted = (
- f"rg --files --sortr=modified -g {self._escape_shell_arg(glob_pattern)}"
+ rg_executable = rg_executable or self._resolve_command("rg")
+ if not rg_executable:
+ return SearchResult(error="File search requires ripgrep (rg).")
+ rg = self._quote_executable(rg_executable)
+ sort_arg = " --sortr=modified" if order == "modified" else ""
+ cmd = (
+ f"set -o pipefail; {rg} --files{sort_arg} -g {self._escape_shell_arg(glob_pattern)}"
f"{exclusion_args} "
f"{self._escape_native_tool_arg(path)} 2>/dev/null "
f"| head -n {fetch_limit}"
)
- result = self._exec(cmd_sorted, timeout=60)
+ result = self._exec(cmd, timeout=60)
stdout, limit_reason = _search_stdout_and_limit(result)
all_files = [f for f in stdout.strip().split('\n') if f]
- if not all_files and not limit_reason:
- # --sortr may have failed on older rg; retry without it.
- cmd_plain = (
- f"rg --files -g {self._escape_shell_arg(glob_pattern)}"
- f"{exclusion_args} "
- f"{self._escape_native_tool_arg(path)} 2>/dev/null "
- f"| head -n {fetch_limit}"
+ if order == "modified" and result.exit_code not in {0, 124}:
+ return SearchResult(
+ error=(
+ "Exact modification-time order requires ripgrep with "
+ "--sortr=modified support; upgrade ripgrep or use "
+ "order='discovery'."
+ )
)
- result = self._exec(cmd_plain, timeout=60)
- stdout, limit_reason = _search_stdout_and_limit(result)
- all_files = [f for f in stdout.strip().split('\n') if f]
page = all_files[offset:offset + limit]
@@ -3663,7 +3734,8 @@ class ShellFileOperations(FileOperations):
if self._has_command('rg'):
used_rg = True
result = self._search_with_rg(pattern, path, file_glob, limit, offset,
- output_mode, context)
+ output_mode, context,
+ rg_executable=self._resolve_command("rg") or "rg")
elif self._has_command('grep'):
result = self._search_with_grep(pattern, path, file_glob, limit, offset,
output_mode, context)
@@ -3694,9 +3766,13 @@ class ShellFileOperations(FileOperations):
return _maybe_warn_line_oriented_newline_pattern(result, pattern)
def _search_with_rg(self, pattern: str, path: str, file_glob: Optional[str],
- limit: int, offset: int, output_mode: str, context: int) -> SearchResult:
+ limit: int, offset: int, output_mode: str, context: int,
+ rg_executable: Optional[str] = None) -> SearchResult:
"""Search using ripgrep."""
- cmd_parts = ["rg", "--line-number", "--no-heading", "--with-filename"]
+ rg_executable = rg_executable or self._resolve_command("rg")
+ if not rg_executable:
+ return SearchResult(error="Content search requires ripgrep (rg).")
+ cmd_parts = [self._quote_executable(rg_executable), "--line-number", "--no-heading", "--with-filename"]
# Giant-single-line containment (ported from cline/cline#13525): a
# match inside a serialized dump (multi-MB single-line JSON/minified
diff --git a/tools/file_tools.py b/tools/file_tools.py
index 1697c72ae0a..a68655d59f6 100644
--- a/tools/file_tools.py
+++ b/tools/file_tools.py
@@ -2587,6 +2587,7 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,
def search_tool(pattern: str, target: str = "content", path: str = ".",
file_glob: str = None, limit: int = 50, offset: int = 0,
output_mode: str = "content", context: int = 0,
+ order: str = "discovery",
task_id: str = "default") -> str:
"""Search for content or files."""
try:
@@ -2603,6 +2604,7 @@ def search_tool(pattern: str, target: str = "content", path: str = ".",
file_glob or "",
limit,
offset,
+ order,
)
with _read_tracker_lock:
task_data = _read_tracker.setdefault(task_id, {
@@ -2648,7 +2650,8 @@ def search_tool(pattern: str, target: str = "content", path: str = ".",
file_ops = _get_file_ops(task_id)
result = file_ops.search(
pattern=pattern, path=path, target=target, file_glob=file_glob,
- limit=limit, offset=offset, output_mode=output_mode, context=context
+ limit=limit, offset=offset, output_mode=output_mode, context=context,
+ order=order,
)
omitted = _filter_read_blocked_search_results(result, task_id)
if hasattr(result, 'matches'):
@@ -2840,7 +2843,7 @@ def _is_openai_family_main() -> bool:
SEARCH_FILES_SCHEMA = {
"name": "search_files",
- "description": "Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents. On macOS, broad searches above the user home automatically skip TCC-protected folders (Desktop, Documents, Downloads, Library, Movies, Music, Pictures); target one directly when access is intentional.\n\nContent search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.\n\nFile search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls — results sorted by modification time.",
+ "description": "Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents. On macOS, broad searches above the user home automatically skip TCC-protected folders (Desktop, Documents, Downloads, Library, Movies, Music, Pictures); target one directly when access is intentional.\n\nContent search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.\n\nFile search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls. Discovery order is the fast bounded default; exact global newest-first order is an explicit opt-in and may scan the full tree.",
"parameters": {
"type": "object",
"properties": {
@@ -2850,6 +2853,7 @@ SEARCH_FILES_SCHEMA = {
"file_glob": {"type": "string", "description": "Filter files by pattern in grep mode (e.g., '*.py' to only search Python files)"},
"limit": {"type": "integer", "description": "Maximum number of results to return (default: 50)", "default": 50},
"offset": {"type": "integer", "description": "Skip first N results for pagination (default: 0)", "default": 0},
+ "order": {"type": "string", "enum": ["discovery", "modified"], "description": "File-search order: 'discovery' is fast bounded traversal order; 'modified' is exact global newest-first and may scan the full tree; ignored for content", "default": "discovery"},
"output_mode": {"type": "string", "enum": ["content", "files_only", "count"], "description": "Output format for grep mode: 'content' shows matching lines with line numbers, 'files_only' lists file paths, 'count' shows match counts per file", "default": "content"},
"context": {"type": "integer", "description": "Number of context lines before and after each match (grep mode only)", "default": 0}
},
@@ -2909,7 +2913,8 @@ def _handle_search_files(args, **kw):
return search_tool(
pattern=args.get("pattern", ""), target=target, path=args.get("path", "."),
file_glob=args.get("file_glob"), limit=args.get("limit", 50), offset=args.get("offset", 0),
- output_mode=args.get("output_mode", "content"), context=args.get("context", 0), task_id=tid)
+ output_mode=args.get("output_mode", "content"), context=args.get("context", 0),
+ order=args.get("order", "discovery"), task_id=tid)
def _read_file_schema_overrides():