Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(search): scan the whole repo for literal and identifier line hits (#3201)

Raghav Chamadiya0be187fe5cbe
diff --git a/packages/server/src/repowise/server/mcp_server/_line_hits.py b/packages/server/src/repowise/server/mcp_server/_line_hits.py
index df22a0f34..9ee5f82a7 100644
--- a/packages/server/src/repowise/server/mcp_server/_line_hits.py
+++ b/packages/server/src/repowise/server/mcp_server/_line_hits.py
@@ -5,8 +5,9 @@ sets (definition, imports, calls, references) from :mod:`_edit_sites`. A
single-token query naming no indexed symbol (a number, a quoted string, an
unindexed name) is scanned for in every file git lists (tracked and
untracked, ignore rules applied), so config and docs the indexer never parsed
-are read too. ``complete`` is true only when nothing was skipped or capped,
-so the lines are every match.
+are read too. git grep narrows that list to the files holding the token;
+without it the scan reads source files first. ``complete`` is true only when
+nothing was skipped or capped, so the lines are every match.
"""
from __future__ import annotations
@@ -29,6 +30,7 @@ from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphNode
from repowise.core.repo_config import load_repo_config
+from repowise.core.support_paths import file_population
from repowise.core.test_paths import is_test_related_path
from repowise.server.mcp_server._budget import OmissionCollector, register_post_enforce
from repowise.server.mcp_server._edit_sites import (
@@ -66,6 +68,8 @@ MAX_SCAN_FILES = 20_000
MAX_SCAN_BYTES = 32_000_000
# Wall-clock ceiling on the literal scan; past it the lines are marked incomplete.
MAX_SCAN_SECONDS = 0.5
+# Past this git grep is abandoned for the Python scan.
+_GIT_GREP_SECONDS = 5.0
_SNIFF_BYTES = 8192
# A binary past this is not streamed for the token; it is reported as skipped.
_MAX_STREAM_BYTES = 64_000_000
@@ -159,27 +163,65 @@ def _is_utf8(data: bytes) -> bool:
return True
-def _listed_files(root: Path) -> list[str]:
- """Tracked and untracked files minus ignored ones, or a pruned walk without git."""
- cmd = ["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard"]
+def _git_paths(
+ root: Path, args: list[str], timeout: float, ok: tuple[int, ...]
+) -> list[str] | None:
+ """The NUL-separated paths a git command prints outside pruned dirs, or ``None`` on failure."""
try:
proc = subprocess.run(
- cmd, capture_output=True, stdin=subprocess.DEVNULL, timeout=10, check=False
- )
- except (OSError, subprocess.SubprocessError):
- proc = None
- if proc is not None and proc.returncode == 0:
- listed = proc.stdout.decode("utf-8", errors="replace").split("\0")
- return sorted(
- {p for p in listed if p and not PRUNED_DIRS.intersection(p.split("/")[:-1])}
+ ["git", "-C", str(root), *args],
+ capture_output=True,
+ stdin=subprocess.DEVNULL,
+ timeout=timeout,
+ check=False,
)
- return sorted(
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return None
+ if proc.returncode not in ok:
+ return None
+ listed = proc.stdout.decode("utf-8", errors="replace").split("\0")
+ return [
+ p for p in dict.fromkeys(listed) if p and not PRUNED_DIRS.intersection(p.split("/")[:-1])
+ ]
+
+
+def _listed_files(root: Path) -> list[str]:
+ """Tracked and untracked files minus ignored ones, or a pruned walk without git."""
+ args = ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]
+ listed = _git_paths(root, args, 10, (0,))
+ if listed is not None:
+ return listed
+ return [
(Path(d) / f).relative_to(root).as_posix() for d, _, names in walk_repo(root) for f in names
- )
+ ]
+
+
+def _files_holding(root: Path, needle: str) -> list[str] | None:
+ """The files :func:`_listed_files` would list whose bytes hold *needle*, via git grep.
+
+ ``None`` when git cannot answer in time, for a needle that is not one plain
+ argument, or for a non-ASCII one, whose misses in non-UTF-8 files only the
+ Python scan can report.
+ """
+ if not needle.isascii() or "\n" in needle or "\0" in needle or needle.startswith("-"):
+ return None
+ args = ["-c", "grep.fullName=false", "grep", "-l", "-z", "--untracked", "--no-color", "-F"]
+ args += ["-e", needle]
+ # Exit 1 is "no file matched".
+ return _git_paths(root, args, _GIT_GREP_SECONDS, (0, 1))
+
+
+def _scan_rank(rel: str) -> int:
+ """Production code first, then tests, examples, and docs or config."""
+ population = file_population(rel, is_test=is_test_related_path(rel))
+ return ("production", "test", "example", "doc").index(population)
def _scan_listed(root: Path, needle: str, word: bool) -> tuple[list[dict[str, Any]], list[str]]:
- files = _listed_files(root)
+ held = _files_holding(root, needle)
+ files = _listed_files(root) if held is None else held
+ # Ordered so a scan that stops on a budget has read source before docs.
+ files = sorted(files, key=lambda f: (_scan_rank(f), f))
patterns = load_repo_config(root).get("exclude_patterns") or []
reasons: list[str] = []
if patterns:
@@ -231,7 +273,8 @@ def scan_literal(
continue
if scanned + size > MAX_SCAN_BYTES:
reasons.append(
- f"over {MAX_SCAN_BYTES // 1_000_000} MB: scanned {i} of {len(files)} files"
+ f"over {MAX_SCAN_BYTES // 1_000_000} MB: scanned {i} of {len(files)}"
+ " files, source first"
)
break
scanned += size
diff --git a/tests/unit/server/mcp/test_search_line_hits.py b/tests/unit/server/mcp/test_search_line_hits.py
index a71bdfacd..8773d7a32 100644
--- a/tests/unit/server/mcp/test_search_line_hits.py
+++ b/tests/unit/server/mcp/test_search_line_hits.py
@@ -537,3 +537,109 @@ async def test_single_name_keeps_the_full_cap_and_every_omitted_file(tree, sessi
assert len(out["lines_omitted_by_file"]) == 8
assert "lines_omitted_by_file_total" not in out
assert not any(r == _line_hits.OVER_LINES_MIXED for r in out["reasons"])
+
+
+_SCAN_TREE = {
+ "docs/guide.md": "Set `retryLimit` in the config.\n",
+ "docs/api/retry.md": "retryLimit: the number of retries\n",
+ "src/core/retry.ts": "export const retryLimit = 3;\nuse(retryLimit);\nuse($retryLimit);\n",
+ "src/net/client.py": "retryLimit = 5\nself.retryLimit_old = 1\nprint(retryLimit)\n",
+ "src/my dir/sub/limits.go": "var retryLimit = 4\nfunc f() { g(retryLimit) }\n",
+ "tests/test_retry.py": "assert retryLimit == 3\n",
+ "README.md": "retryLimit.\n",
+}
+
+
+def scan_repo(tmp_path):
+ for rel, text in _SCAN_TREE.items():
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(text, encoding="utf-8")
+ git = ["git", "-C", str(tmp_path), "-c", "user.name=t", "-c", "user.email=t@t"]
+ subprocess.run([*git, "init", "-q"], check=True)
+ subprocess.run([*git, "add", "docs", "src"], check=True)
+ subprocess.run([*git, "commit", "-q", "-m", "seed"], check=True)
+ # tests/ and README.md stay untracked: git grep must still read them.
+ return tmp_path
+
+
+def _python_only(monkeypatch):
+ monkeypatch.setattr(_line_hits, "_files_holding", lambda _root, _needle: None)
+
+
+def test_git_grep_and_python_scan_serve_the_same_rows(scan_repo, monkeypatch):
+ held = _line_hits._files_holding(scan_repo, "retryLimit")
+ assert held is not None and "src/my dir/sub/limits.go" in held
+ assert "tests/test_retry.py" in held
+ via_git = _line_hits._scan_listed(scan_repo, "retryLimit", True)
+ _python_only(monkeypatch)
+ via_python = _line_hits._scan_listed(scan_repo, "retryLimit", True)
+
+ assert via_git == via_python
+ rows, reasons = via_git
+ assert reasons == []
+ found = {(r["path"], r["line"], r["kind"]) for r in rows}
+ # Word-bounded on both paths: $retryLimit and retryLimit_old are other names.
+ assert ("src/core/retry.ts", 3, "match") not in found
+ assert ("src/net/client.py", 2, "match") not in found
+ assert {
+ ("src/core/retry.ts", 1, "definition"),
+ ("src/core/retry.ts", 2, "match"),
+ ("src/net/client.py", 1, "definition"),
+ ("src/my dir/sub/limits.go", 1, "definition"),
+ ("tests/test_retry.py", 1, "match"),
+ ("docs/guide.md", 1, "match"),
+ } <= found
+
+
+def test_git_grep_paths_are_relative_to_a_nested_root(scan_repo, monkeypatch):
+ root = scan_repo / "src"
+ via_git = _line_hits._scan_listed(root, "retryLimit", True)
+ _python_only(monkeypatch)
+ assert via_git == _line_hits._scan_listed(root, "retryLimit", True)
+ assert {r["path"] for r in via_git[0]} == {
+ "core/retry.ts",
+ "net/client.py",
+ "my dir/sub/limits.go",
+ }
+
+
+def test_byte_budget_reads_source_before_tests_and_docs(scan_repo, monkeypatch):
+ _python_only(monkeypatch)
+ sizes = sorted((scan_repo / rel).stat().st_size for rel in _SCAN_TREE if rel.startswith("src/"))
+ monkeypatch.setattr(_line_hits, "MAX_SCAN_BYTES", sum(sizes))
+
+ rows, reasons = _line_hits._scan_listed(scan_repo, "retryLimit", True)
+
+ assert {r["path"].split("/")[0] for r in rows} == {"src"}
+ assert reasons == [f"over 0 MB: scanned 3 of {len(_SCAN_TREE)} files, source first"]
+
+
+ "failure",
+ [FileNotFoundError("git"), subprocess.TimeoutExpired("git", 5)],
+ ids=["git-missing", "timeout"],
+)
+def test_git_failure_falls_back_to_the_python_scan(scan_repo, monkeypatch, failure):
+ expected = _line_hits._scan_listed(scan_repo, "retryLimit", True)
+ real_run = subprocess.run
+
+ def broken(cmd, *args, **kwargs):
+ if "grep" in cmd or isinstance(failure, FileNotFoundError):
+ raise failure
+ return real_run(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(_line_hits.subprocess, "run", broken)
+
+ assert _line_hits._files_holding(scan_repo, "retryLimit") is None
+ assert _line_hits._scan_listed(scan_repo, "retryLimit", True) == expected
+
+
+def test_token_nowhere_in_the_repo_is_complete_and_empty(scan_repo):
+ assert _line_hits._files_holding(scan_repo, "noSuchTokenAnywhere") == []
+ assert _line_hits._scan_listed(scan_repo, "noSuchTokenAnywhere", True) == ([], [])
+
+
[email protected]("needle", ["a\nb", "a\0b", "-e", "café"])
+def test_needles_git_cannot_take_as_one_argument_use_the_python_scan(scan_repo, needle):
+ assert _line_hits._files_holding(scan_repo, needle) is None