diff --git a/core/harness/tools/search.py b/core/harness/tools/search.py index bfa059884..a52d26aba 100644 --- a/core/harness/tools/search.py +++ b/core/harness/tools/search.py @@ -14,6 +14,7 @@ import os import re import shutil +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -22,7 +23,26 @@ from core.harness.permissions import is_sensitive_path _MAX_MATCHES = 200 +_MAX_CONTEXT_LINES = 50 +_MAX_CONTENT_LINES = 1_000 _SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build"} +_MODES = ("content", "files_with_matches", "count") + + +@dataclass(slots=True) +class _Match: + path: Path + rel: str + line: int + text: str + + +def _clamped(value: Any, *, low: int, high: int, default: int) -> int: + try: + number = int(value) + except (TypeError, ValueError): + return default + return max(low, min(high, number)) @tool_parameters( @@ -41,12 +61,46 @@ "type": "string", "description": "Optional glob to limit files, e.g. '*.py'.", }, + "output_mode": { + "type": "string", + "enum": list(_MODES), + "description": ( + "content (default) returns matching lines; files_with_matches " + "returns only file paths; count returns per-file match counts." + ), + }, + "context": { + "type": "integer", + "description": ( + "Lines of context before and after each match (like grep -C). " + "Default 0." + ), + }, + "context_before": { + "type": "integer", + "description": "Lines of context before each match (overrides context).", + }, + "context_after": { + "type": "integer", + "description": "Lines of context after each match (overrides context).", + }, + "case_insensitive": { + "type": "boolean", + "description": "Match case-insensitively (like grep -i). Default false.", + }, + "head_limit": { + "type": "integer", + "description": ( + f"Max matches to return (default {_MAX_MATCHES}); 0 means the " + "hard cap." + ), + }, }, "required": ["pattern"], } ) class GrepTool(Tool): - """Search file contents by regex, returning ``path:line: text`` matches.""" + """Search file contents by regex, returning ``path:line:text`` matches.""" def __init__(self, workspace: str, *, protect_sensitive_paths: bool = True): # Resolved like the search roots below, so results are relative to it @@ -62,8 +116,10 @@ def name(self) -> str: def description(self) -> str: return ( "Search file contents by regular expression. Returns matching " - "`path:line: text` lines. Optionally restrict files with `include` " - "(e.g. '*.py')." + "`path:line:text` lines, or file paths / per-file counts with " + "`output_mode`. Optionally restrict files with `include` (e.g. " + "'*.py'), add surrounding lines with `context`, and match " + "case-insensitively." ) @property @@ -74,37 +130,79 @@ async def execute(self, **kwargs: Any) -> Any: pattern = kwargs.get("pattern", "") if not pattern: return "Error: pattern is required." + mode = str(kwargs.get("output_mode") or "content") + if mode not in _MODES: + return f"Error: output_mode must be one of {', '.join(_MODES)}." rel = kwargs.get("path") or "." include = kwargs.get("include") root = (Path(self._workspace) / rel).resolve() if not root.exists(): return f"Error: path not found: {rel}" + context = _clamped( + kwargs.get("context"), low=0, high=_MAX_CONTEXT_LINES, default=0 + ) + before = ( + context + if kwargs.get("context_before") is None + else _clamped( + kwargs.get("context_before"), + low=0, + high=_MAX_CONTEXT_LINES, + default=context, + ) + ) + after = ( + context + if kwargs.get("context_after") is None + else _clamped( + kwargs.get("context_after"), + low=0, + high=_MAX_CONTEXT_LINES, + default=context, + ) + ) + head_limit = _clamped( + kwargs.get("head_limit"), low=0, high=_MAX_MATCHES * 5, default=_MAX_MATCHES + ) + if head_limit == 0: + head_limit = _MAX_MATCHES * 5 + ignore_case = bool(kwargs.get("case_insensitive")) + # Either search can take seconds (rg is allowed 30). Neither runs on # the event loop, which the service shares with every other session. if shutil.which("rg"): - matches = await self._ripgrep(pattern, root, include) + found = await self._ripgrep(pattern, root, include, mode, ignore_case) else: - matches = await asyncio.to_thread(self._python_grep, pattern, root, include) - if matches is None: + found = await asyncio.to_thread( + self._python_grep, pattern, root, include, mode, ignore_case + ) + if found is None: return f"Error: invalid regular expression: {pattern}" - if not matches: - return "No matches." - out = matches[:_MAX_MATCHES] - suffix = ( - f"\n... ({len(matches) - _MAX_MATCHES} more matches; refine the pattern)" - if len(matches) > _MAX_MATCHES - else "" - ) - return "\n".join(out) + suffix + return self._render(mode, found, before, after, head_limit) + + # -- search backends ------------------------------------------------------- async def _ripgrep( - self, pattern: str, root: Path, include: str | None - ) -> list[str] | None: - argv = ["rg", "--line-number", "--no-heading", "--color", "never"] + self, + pattern: str, + root: Path, + include: str | None, + mode: str, + ignore_case: bool, + ) -> list[_Match] | list[str] | dict[str, int] | None: + argv = ["rg", "--no-heading", "--color", "never"] # Every match starts with its file's path, ended by NUL, so the path # can be checked against the protected-path guard below. argv += ["--with-filename", "--null"] + if mode == "content": + argv.append("--line-number") + elif mode == "files_with_matches": + argv.append("--files-with-matches") + else: + argv.append("--count") + if ignore_case: + argv.append("-i") # Both come from the model: attached with "=" they stay values, so a # pattern like "--pre=" can't make rg run a program. if include: @@ -116,45 +214,117 @@ async def _ripgrep( except OSError: result = None if result is None: - return await asyncio.to_thread(self._python_grep, pattern, root, include) + return await asyncio.to_thread( + self._python_grep, pattern, root, include, mode, ignore_case + ) returncode, stdout, stderr = result if returncode not in (0, 1): # 1 = no matches; >1 = error if b"regex parse error" in stderr.lower(): return None - return await asyncio.to_thread(self._python_grep, pattern, root, include) - matches: list[str] = [] - for line in stdout.decode("utf-8", errors="replace").splitlines(): + return await asyncio.to_thread( + self._python_grep, pattern, root, include, mode, ignore_case + ) + text = stdout.decode("utf-8", errors="replace") + if mode == "files_with_matches": + files: list[str] = [] + for path in text.split("\0"): + path = path.strip() + if path and not (self._protect and is_sensitive_path(path)): + files.append(self._relativize(path)) + return files + if mode == "count": + counts: dict[str, int] = {} + for line in text.splitlines(): + path, sep, number = line.partition("\0") + if not sep or (self._protect and is_sensitive_path(path)): + continue + try: + counts[self._relativize(path)] = int(number.strip() or 0) + except ValueError: + continue + return counts + matches: list[_Match] = [] + for line in text.splitlines(): path, sep, rest = line.partition("\0") if not sep or (self._protect and is_sensitive_path(path)): continue - # make paths workspace-relative for readability - matches.append(f"{self._relativize(path)}:{rest}") + lineno, sep2, content = rest.partition(":") + if not sep2: + continue + try: + line_no = int(lineno) + except ValueError: + continue + matches.append( + _Match( + Path(path) if os.path.isabs(path) else root / path, + self._relativize(path), + line_no, + content, + ) + ) return matches def _python_grep( - self, pattern: str, root: Path, include: str | None - ) -> list[str] | None: + self, + pattern: str, + root: Path, + include: str | None, + mode: str = "content", + ignore_case: bool = False, + ) -> list[_Match] | list[str] | dict[str, int] | None: try: - regex = re.compile(pattern) + regex = re.compile(pattern, re.IGNORECASE if ignore_case else 0) except re.error: return None - results: list[str] = [] - targets = [root] if root.is_file() else self._walk(root, include) - for file in targets: + if mode == "files_with_matches": + files: list[str] = [] + for file in self._walk_targets(root, include): + if self._protect and is_sensitive_path(str(file)): + continue + try: + text = file.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + if any(regex.search(line) for line in text.splitlines()): + files.append(os.path.relpath(file, self._workspace)) + if len(files) > _MAX_MATCHES * 5: + break + return files + if mode == "count": + counts: dict[str, int] = {} + for file in self._walk_targets(root, include): + if self._protect and is_sensitive_path(str(file)): + continue + try: + text = file.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + count = sum(1 for line in text.splitlines() if regex.search(line)) + if count: + counts[os.path.relpath(file, self._workspace)] = count + if len(counts) > _MAX_MATCHES * 5: + break + return counts + results: list[_Match] = [] + for file in self._walk_targets(root, include): if self._protect and is_sensitive_path(str(file)): continue try: text = file.read_text(encoding="utf-8", errors="ignore") except OSError: continue + rel = os.path.relpath(file, self._workspace) for i, line in enumerate(text.splitlines(), 1): if regex.search(line): - rel = os.path.relpath(file, self._workspace) - results.append(f"{rel}:{i}: {line.strip()[:300]}") - if len(results) > _MAX_MATCHES * 2: + results.append(_Match(file, rel, i, line.strip()[:300])) + if len(results) > _MAX_MATCHES * 5: return results return results + def _walk_targets(self, root: Path, include: str | None): + return [root] if root.is_file() else self._walk(root, include) + def _walk(self, root: Path, include: str | None): for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS] @@ -163,6 +333,104 @@ def _walk(self, root: Path, include: str | None): continue yield Path(dirpath) / name + # -- rendering ------------------------------------------------------------- + + def _render( + self, + mode: str, + found: list[_Match] | list[str] | dict[str, int], + before: int, + after: int, + head_limit: int, + ) -> str: + if mode == "files_with_matches": + files = list(found) if not isinstance(found, dict) else list(found) + if not files: + return "No matches." + shown = files[:head_limit] + suffix = ( + f"\n... ({len(files) - len(shown)} more files; refine the pattern)" + if len(files) > len(shown) + else "" + ) + return "\n".join(shown) + suffix + if mode == "count": + counts = found if isinstance(found, dict) else {} + if not counts: + return "No matches." + items = list(counts.items()) + shown = items[:head_limit] + suffix = ( + f"\n... ({len(items) - len(shown)} more files; refine the pattern)" + if len(items) > len(shown) + else "" + ) + total = sum(count for _, count in items) + return ( + "\n".join(f"{rel}:{count}" for rel, count in shown) + + f"\n(total {total} matches in {len(items)} files)" + + suffix + ) + + matches = found if isinstance(found, list) else [] + if not matches: + return "No matches." + shown = matches[:head_limit] + suffix = ( + f"\n... ({len(matches) - len(shown)} more matches; refine the pattern)" + if len(matches) > len(shown) + else "" + ) + if before or after: + body = self._render_context(shown, before, after) + else: + body = "\n".join( + f"{match.rel}:{match.line}:{match.text}" for match in shown + ) + return body + suffix + + def _render_context(self, matches: list[_Match], before: int, after: int) -> str: + grouped: dict[str, list[_Match]] = {} + for match in matches: + grouped.setdefault(match.rel, []).append(match) + + lines_out: list[str] = [] + for rel, file_matches in grouped.items(): + try: + file_lines = ( + file_matches[0] + .path.read_text(encoding="utf-8", errors="replace") + .splitlines() + ) + except OSError: + continue + match_lines = {match.line for match in file_matches} + spans: list[tuple[int, int]] = [] + for line_no in sorted(match_lines): + start = max(1, line_no - before) + end = min(len(file_lines), line_no + after) + if end < 1: + continue + if spans and start <= spans[-1][1] + 1: + spans[-1] = (spans[-1][0], max(spans[-1][1], end)) + else: + spans.append((start, end)) + for start, end in spans: + for line_no in range(start, end + 1): + marker = ":" if line_no in match_lines else "-" + text = file_lines[line_no - 1][:300] + lines_out.append(f"{rel}{marker}{line_no}{marker}{text}") + if len(lines_out) >= _MAX_CONTENT_LINES: + lines_out.append( + "... [context output capped; narrow the search or " + "lower the context size]" + ) + return "\n".join(lines_out) + lines_out.append("--") + if lines_out and lines_out[-1] == "--": + lines_out.pop() + return "\n".join(lines_out) + def _relativize(self, path: str) -> str: if os.path.isabs(path): try: @@ -233,7 +501,9 @@ def _glob(self, pattern: str, path: str | None) -> str: if self._protect and is_sensitive_path(str(p)): continue if p.is_file(): - matches.append(os.path.relpath(p, self._workspace)) + # POSIX-style separators: the model file-reads these paths and + # Claude-Code-style tools report them this way on every OS. + matches.append(Path(os.path.relpath(p, self._workspace)).as_posix()) if not matches: return "No files matched." out = matches[:_MAX_MATCHES] diff --git a/tests/contract/test_default_capability_compatibility.py b/tests/contract/test_default_capability_compatibility.py index aa65c236b..f9706bc8f 100644 --- a/tests/contract/test_default_capability_compatibility.py +++ b/tests/contract/test_default_capability_compatibility.py @@ -42,6 +42,12 @@ "pattern": ("string", True), "path": ("string", False), "include": ("string", False), + "output_mode": ("string", False), + "context": ("integer", False), + "context_before": ("integer", False), + "context_after": ("integer", False), + "case_insensitive": ("boolean", False), + "head_limit": ("integer", False), }, "glob": { "pattern": ("string", True), diff --git a/tests/test_grep_options.py b/tests/test_grep_options.py new file mode 100644 index 000000000..beabcc9b9 --- /dev/null +++ b/tests/test_grep_options.py @@ -0,0 +1,89 @@ +"""grep's output modes and context options, on both search backends. + +``GrepTool`` used to render one shape only: ``path:line: text`` for every +match, capped at 200. The options here follow the grep contract a coding agent +already knows (``output_mode``, ``-C`` context, ``-i``, ``head_limit``), so a +caller can ask for the file list or the counts instead of parsing 200 lines. + +Each shape is asserted against the real backend when ripgrep is installed and +against the Python fallback when it is not: the two must agree, because the +fallback is the only path on a machine without ``rg``. +""" + +from __future__ import annotations + +import shutil +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from core.harness.tools.search import GrepTool + + +@pytest.fixture() +def workspace(tmp_path): + (tmp_path / "a.py").write_text( + "def alpha():\n return 1\n\nbeta = 2\n", encoding="utf-8" + ) + (tmp_path / "b.py").write_text("ALPHA = True\n", encoding="utf-8") + return tmp_path + + +@pytest.mark.asyncio +async def test_content_adds_the_requested_context_lines(workspace): + out = await GrepTool(str(workspace)).execute(pattern="def alpha", context=1) + assert "a.py:1:def alpha():" in out + assert "a.py-2- return 1" in out + + +@pytest.mark.asyncio +@pytest.mark.parametrize("ripgrep", [True, False]) +async def test_files_with_matches_lists_each_file_once(workspace, monkeypatch, ripgrep): + if not ripgrep: + monkeypatch.setattr("core.harness.tools.search.shutil.which", lambda _: None) + elif shutil.which("rg") is None: + pytest.skip("needs ripgrep") + + out = await GrepTool(str(workspace)).execute( + pattern="alpha", output_mode="files_with_matches", case_insensitive=True + ) + assert set(out.splitlines()) == {"a.py", "b.py"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("ripgrep", [True, False]) +async def test_count_reports_per_file_counts_and_a_total( + workspace, monkeypatch, ripgrep +): + if not ripgrep: + monkeypatch.setattr("core.harness.tools.search.shutil.which", lambda _: None) + elif shutil.which("rg") is None: + pytest.skip("needs ripgrep") + + out = await GrepTool(str(workspace)).execute( + pattern="alpha", output_mode="count", case_insensitive=True + ) + assert "a.py:1" in out and "b.py:1" in out + assert "total 2 matches in 2 files" in out + + +@pytest.mark.asyncio +async def test_case_insensitive_and_head_limit(workspace): + tool = GrepTool(str(workspace)) + sensitive = await tool.execute(pattern="alpha") + assert "b.py" not in sensitive + limited = await tool.execute(pattern="alpha", case_insensitive=True, head_limit=1) + assert "more matches" in limited + + +@pytest.mark.asyncio +async def test_invalid_mode_and_regex_are_reported(workspace): + tool = GrepTool(str(workspace)) + assert "output_mode must be" in await tool.execute(pattern="x", output_mode="bogus") + invalid = await tool.execute(pattern="(") + assert "invalid regular expression" in invalid.lower()