Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(search): rank files the query names first and return an exact symbol alone (#3127)
Raghav Chamadiya229ffcef2355
diff --git a/packages/server/src/repowise/server/mcp_server/_query_shape.py b/packages/server/src/repowise/server/mcp_server/_query_shape.pyindex 271d81ae9..6ed9d660a 100644--- a/packages/server/src/repowise/server/mcp_server/_query_shape.py+++ b/packages/server/src/repowise/server/mcp_server/_query_shape.py@@ -9,7 +9,7 @@ from __future__ import annotationsimport os.pathimport re-from collections.abc import Container+from collections.abc import Container, Sequencefrom functools import cachefrom repowise.server.mcp_server._stack_trace import parse_trace@@ -83,6 +83,40 @@ def _is_path(query: str) -> bool:return ext in _code_exts()+_TOKEN_EDGE_CHARS = "`'\"()[]{},;"+_LINE_SUFFIX_RE = re.compile(r":\d+(?:-\d+)?$")+++def path_tokens(query: str, paths: Sequence[str] = ()) -> list[str]:+ """The words of ``query`` that read as paths. ``services/x.py register+ hotkey`` -> ``[services/x.py]``.++ A word with a code file extension counts. A ``/`` or ``\\`` word without+ one counts only when it is a run of whole segments of one of ``paths``, so+ ``and/or`` does not. URLs never count; a ``::member`` or ``:line`` suffix+ is dropped.+ """+ out: list[str] = []+ for raw in query.split():+ if "://" in raw:+ continue+ token = raw.strip(_TOKEN_EDGE_CHARS).split("::", 1)[0].rstrip(".:")+ token = _LINE_SUFFIX_RE.sub("", token)+ if os.path.splitext(token)[1] in _code_exts() or (+ ("/" in token or "\\" in token) and _names_indexed_segments(token, paths)+ ):+ out.append(token)+ return out+++def _names_indexed_segments(token: str, paths: Sequence[str]) -> bool:+ norm = token.lower().replace("\\", "/").removeprefix("./").strip("/")+ if not norm:+ return False+ needle = f"/{norm}/"+ return any(needle in f"/{path.lower()}/" for path in paths)++def _qual_norm(name: str | None) -> str:"""Normalize a qualified name's separators (``::``/``/`` -> ``.``), lowered."""s = name or ""diff --git a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.pyindex e3e8933d2..921299e9f 100644--- a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py+++ b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py@@ -3,7 +3,10 @@from __future__ import annotationsimport math+import osimport re+from collections import Counter+from collections.abc import Mappingfrom repowise.server.mcp_server._query_terms import content_terms, split_humps@@ -147,3 +150,45 @@ def rerank_by_context_coverage(hit[score_key] = raw * ranking_multiplierhits.sort(key=lambda hit: hit.get(score_key, 0.0), reverse=True)return hits+++# A query word naming a file lifts it by the word's squared rarity among indexed+# paths (1.0 when one path carries it), capped so content relevance still leads.+_PATH_NAME_LIFT_CAP = 1.0+# Below this many files nearly every word is rare, so a path match says nothing.+_MIN_INDEXED_PATHS = 30+++def path_words(path: str) -> set[str]:+ """``services/_hotkey_pynput.py`` -> ``{services, hotkey, pynput}``; the+ extension is not a word."""+ return {w for w in _identifier_words(os.path.splitext(path)[0]) if len(w) >= 3}+++def path_word_counts(paths: list[str]) -> Counter[str]:+ """How many of ``paths`` carry each path word."""+ return Counter(word for path in paths for word in path_words(path))+++def boost_named_paths(+ hits: list[dict], query: str, df: Mapping[str, int], total: int, *, score_key: str+) -> None:+ """Lift hits whose path names a query word, by how rare that word is among+ the ``total`` indexed paths (``df`` per word). In place, unsorted."""+ if total < _MIN_INDEXED_PATHS:+ return+ log_total = math.log(total)+ weights = {+ t: (math.log(total / df[t]) / log_total) ** 2 for t in content_terms(query) if df.get(t)+ }+ if not any(weights.values()):+ return+ for hit in hits:+ path = hit.get("target_path") or ""+ score = hit.get(score_key)+ if not path or not score:+ continue+ words = path_words(path)+ lift = sum(w for t, w in weights.items() if t in words)+ if lift:+ hit[score_key] = round(score * (1.0 + min(_PATH_NAME_LIFT_CAP, lift)), 4)diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 54cf07406..de9c439ee 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -6,7 +6,7 @@ import asyncioimport contextlibimport loggingimport re-from collections.abc import Container+from collections.abc import Container, Sequencefrom typing import Anyfrom sqlalchemy import select@@ -59,11 +59,17 @@ from repowise.server.mcp_server._query_shape import (_qual_norm,_resolve_mode,_symbol_matches_name,+ path_tokens,)from repowise.server.mcp_server._references import path_identity, symbol_identity-from repowise.server.mcp_server._retrieval_rank import rerank_by_context_coverage+from repowise.server.mcp_server._retrieval_rank import (+ boost_named_paths,+ rerank_by_context_coverage,+)from repowise.server.mcp_server.tool_search_symbols import (+ _MAX_CANDIDATES,IssueFiles,+ file_path_index,indexed_names,issue_files,search_paths_single,@@ -109,11 +115,14 @@ def _protect_named_symbols(candidates: list[str], symbols: list[dict]) -> list[dreturn protected + [item for item in symbols if not _symbol_matches_name(item, wanted)]-def _protect_exact_paths(query: str, files: list[dict]) -> list[dict]:+def _protect_exact_paths(+ query: str, files: list[dict], paths: Sequence[str] = ()+) -> list[dict]:"""Stable-partition an exact path hit ahead of basename/fuzzy neighbours."""- qnorm = query.strip().lower().replace("\\", "/")- protected = [item for item in files if (item.get("file") or "").lower() == qnorm]- return protected + [item for item in files if (item.get("file") or "").lower() != qnorm]+ tokens = path_tokens(query, paths) or [query]+ wanted = {t.strip().lower().replace("\\", "/") for t in tokens}+ protected = [item for item in files if (item.get("file") or "").lower() in wanted]+ return protected + [item for item in files if (item.get("file") or "").lower() not in wanted]def _prose_dominates(query: str, identifiers: list[str]) -> bool:@@ -775,9 +784,13 @@ async def _search_single_repo(if output:async with get_session(ctx.session_factory) as session:page_info, tombstoned, _ = await _load_page_info(session, output)+ path_index = await file_path_index(session, (await _get_repo(session)).id)output = [item for item in output if item["page_id"] not in tombstoned]_attach_paths(output, page_info)output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))+ boost_named_paths(+ output, query, path_index.word_counts, len(path_index.paths), score_key="relevance_score"+ )_downweight_test_pages(output, query)_sort_demoting_noise(output, query)@@ -959,6 +972,7 @@ async def _structured_search(# collapsing same-file rows frees, and never steer the exact-match signal.spare: list[dict] = []files: list[dict] = []+ indexed_paths: list[str] = []concepts: list[dict] = []# A hybrid query is prose wrapped around an identifier ("where is X@@ -977,8 +991,11 @@ async def _structured_search(symbol_query = " ".join(_idents)# Only the hybrid window collapses symbol rows, so only it over-fetches- # them; path hits are file pages, already one row per file.+ # them; path hits are file pages, already one row per file. Symbol mode+ # takes every candidate so ``fuzzy_omitted`` counts the names an exact hit hides.fetch = limit * _FILE_WINDOW_OVERFETCH if mode == "hybrid" else limit+ if mode == "symbol":+ fetch = _MAX_CANDIDATESfor ctx in contexts:if mode in ("symbol", "hybrid"):s = await search_symbols_single(@@ -989,6 +1006,9 @@ async def _structured_search(spare.extend(s[limit:])if mode == "path":f = await search_paths_single(ctx, query, limit)+ async with get_session(ctx.session_factory) as session:+ index = await file_path_index(session, (await _get_repo(session)).id)+ indexed_paths.extend(index.paths)_tag_repo(f, ctx, multi)files.extend(f)if mode == "hybrid":@@ -1007,7 +1027,7 @@ async def _structured_search(elif mode == "hybrid" and candidates:symbols = _protect_named_symbols(candidates, symbols)if mode == "path":- files = _protect_exact_paths(query, files)+ files = _protect_exact_paths(query, files, indexed_paths)# Whether any returned symbol matches the query's identifier(s) exactly.# Computed once here so the hybrid interleave and the exact-match note below@@ -1018,8 +1038,19 @@ async def _structured_search(symbols = [s for s in symbols if _has_exact_symbol(candidates, [s])]spare = [s for s in spare if _has_exact_symbol(candidates, [s])]+ fuzzy_omitted = 0if mode == "symbol":- results = symbols[:limit]+ # An exact hit is the answer; its fuzzy neighbours only cost bytes.+ # Summed over repos when federated, and a floor past the candidate cap.+ pool = symbols + spare+ named = [s for s in pool if _has_exact_symbol(candidates, [s])] if exact else []+ if named:+ ident = (canonical_symbol[1] if canonical_symbol else query).strip().lower()+ shown = {id(s) for s in named}+ fuzzy_omitted = sum(+ 1 for s in pool if id(s) not in shown and ident in (s.get("name") or "").lower()+ )+ results = (named or symbols)[:limit]elif mode == "path":results = files[:limit]else: # hybrid: interleave symbol matches and concept pages for new files@@ -1053,6 +1084,8 @@ async def _structured_search("mode": mode,"_meta": _build_meta(repository=repository, targets=_result_paths(results)),}+ if fuzzy_omitted:+ response["fuzzy_omitted"] = fuzzy_omitted# Symbols first, then everything else the window holds: in symbol and# hybrid modes the ranked pool leads with symbol hits, and those are the# entries most likely to collapse onto one another (several symbols of one@@ -1092,6 +1125,11 @@ async def _structured_search("what you meant before relying on it. If you expected an exact ""symbol, recheck spelling/casing. " + EXHAUSTIVE_SWEEP_HINT)+ elif fuzzy_omitted:+ response["note"] = (+ f"{fuzzy_omitted} other symbols contain this name; search a "+ "longer or partial name to list them."+ )if grep_hint and not results:response["grep_hint"] = grep_hint# Last, so nothing above has to know the field is on its way out. Paths@@ -1211,6 +1249,7 @@ async def search_codebase(if output:async with get_session(ctx.session_factory) as session:page_info, tombstoned, git_map = await _load_page_info(session, output, with_git=True)+ path_index = await file_path_index(session, repository.id)# Tombstoned pages document deleted/renamed files — never results.output = [item for item in output if item["page_id"] not in tombstoned]@@ -1236,6 +1275,11 @@ async def search_codebase(score_key="relevance_score",floor=0.5,)+ # After the coverage rerank, whose window-relative weights cannot tell+ # a word rare across the repo from one rare in these few hits.+ boost_named_paths(+ output, query, path_index.word_counts, len(path_index.paths), score_key="relevance_score"+ )_downweight_test_pages(output, query)_sort_demoting_noise(output, query)output = _dedup_decisions(output)diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.pyindex 25528da10..339ec1aa5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py@@ -19,6 +19,7 @@ graph node.from __future__ import annotationsimport re+from collections import Counterfrom typing import Any, NamedTuplefrom sqlalchemy import case, func, or_, select@@ -26,6 +27,7 @@ from sqlalchemy import case, func, or_, selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNode, Page, WikiSymbolfrom repowise.core.test_paths import is_test_path, is_test_related_path+from repowise.server.mcp_server._graph_files import per_indexfrom repowise.server.mcp_server._helpers import (LIKE_ESCAPE,_get_exclude_spec,@@ -39,7 +41,9 @@ from repowise.server.mcp_server._query_shape import (_qual_norm,defined_identifiers,is_issue_shaped,+ path_tokens,)+from repowise.server.mcp_server._retrieval_rank import path_word_countsfrom repowise.server.mcp_server._stack_trace import (frame_basenames,map_to_repo_paths,@@ -416,23 +420,54 @@ def _path_score(target_path: str, qnorm: str) -> float:return score+class PathIndex(NamedTuple):+ paths: tuple[str, ...] # every file page's path+ word_counts: Counter[str] # path word -> how many paths carry it+++async def file_path_index(session: Any, repo_id: str) -> PathIndex:+ """The repo's file paths and their word counts, built once per index state."""++ async def build() -> PathIndex:+ res = await session.execute(+ select(Page.target_path).where(+ Page.repository_id == repo_id, Page.page_type == "file_page"+ )+ )+ paths = tuple(p for (p,) in res.all() if p)+ return PathIndex(paths, path_word_counts(list(paths)))++ return await per_index(session, repo_id, "search_file_paths", build)++async def search_paths_single(ctx: Any, query: str, limit: int) -> list[dict]:- """Path search against one repo context. Returns ranked file result dicts."""+ """Path search against one repo context. Returns ranked file result dicts.++ Only the path-shaped words of ``query`` are matched (``path_tokens``), so+ words around a path do not empty the result; the whole query is matched+ when it carries none.+ """# Path mode is substring matching, so boundary ``*?`` markers carry no# information and are stripped. Mid-string globs (``src/*/main.py``) are# left alone: a substring match cannot honour them, so stripping there# would change the query.- qnorm = query.strip().lower().replace("\\", "/").strip("*?")- if not qnorm:- return []-async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)+ index = await file_path_index(session, repository.id)+ tokens = path_tokens(query, index.paths) or [query]+ qnorms = [q for q in (t.strip().lower().replace("\\", "/").strip("*?") for t in tokens) if q]+ if not qnorms:+ return []res = await session.execute(select(Page.id, Page.title, Page.target_path, Page.freshness_status).where(Page.repository_id == repository.id,Page.page_type == "file_page",- Page.target_path.ilike(f"%{escape_like(qnorm)}%", escape=LIKE_ESCAPE),+ or_(+ *(+ Page.target_path.ilike(f"%{escape_like(q)}%", escape=LIKE_ESCAPE)+ for q in qnorms+ )+ ),))rows = res.all()@@ -444,7 +479,9 @@ async def search_paths_single(ctx: Any, query: str, limit: int) -> list[dict]:continueif is_excluded(target_path, spec):continue- scored.append((_path_score(target_path, qnorm), (page_id, title, target_path)))+ scored.append(+ (max(_path_score(target_path, q) for q in qnorms), (page_id, title, target_path))+ )scored.sort(key=lambda pair: (-pair[0], pair[1][2]))return [diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex 9a7254902..1262e3e5b 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -1061,12 +1061,12 @@ class TestExactMatchSignal:assert seen == ["AuthService"]@pytest.mark.asyncio- async def test_exact_hit_sets_true_and_no_note(self, setup_mcp):+ async def test_exact_hit_sets_true_and_no_fuzzy_note(self, setup_mcp):from repowise.server.mcp_server import search_codebaseresult = await search_codebase("AuthService", mode="symbol")assert result["exact_match"] is True- assert "note" not in result+ assert "exactly matches" not in result.get("note", "")@pytest.mark.asyncioasync def test_fuzzy_only_sets_false_with_note(self, setup_mcp):@@ -1849,3 +1849,168 @@ class TestPathlessPagesInCodeLocationModes:)pages = [r["page_type"] for r in res["results"] if r["type"] == "page"]assert pages == ["module_page"]+++class TestNamedPathBoost:+ """A query word that names a file's path lifts that file, by its rarity."""++ def _hits(self, carbon: float, pynput: float) -> list[dict]:+ return [+ {"target_path": "services/_hotkey_carbon.py", "relevance_score": carbon},+ {"target_path": "services/_hotkey_pynput.py", "relevance_score": pynput},+ ]++ def _boost(self, hits: list[dict], query: str, df: dict, total: int = 854) -> list[str]:+ from repowise.server.mcp_server._retrieval_rank import boost_named_paths++ boost_named_paths(hits, query, df, total, score_key="relevance_score")+ hits.sort(key=lambda h: -h["relevance_score"])+ return [h["target_path"] for h in hits]++ def test_a_rare_path_word_lifts_the_file_it_names(self):+ df = {"hotkey": 7, "pynput": 1, "backend": 3, "services": 120}+ order = self._boost(self._hits(2.4, 2.0), "register global hotkey pynput backend", df)+ assert order[0] == "services/_hotkey_pynput.py"++ def test_a_common_path_word_stays_neutral(self):+ hits = [{"target_path": "services/a.py", "relevance_score": 1.0}]+ self._boost(hits, "services registry", {"services": 300})+ assert hits[0]["relevance_score"] < 1.05++ def test_a_path_match_cannot_beat_a_much_stronger_content_match(self):+ order = self._boost(self._hits(9.0, 2.0), "hotkey pynput", {"hotkey": 7, "pynput": 1})+ assert order[0] == "services/_hotkey_carbon.py"++ def test_a_tiny_repo_gets_no_boost(self):+ hits = self._hits(3.0, 2.0)+ self._boost(hits, "pynput", {"pynput": 1}, total=12)+ assert [h["relevance_score"] for h in hits] == [3.0, 2.0]++ def test_extensions_stopwords_and_short_words_never_count(self):+ from repowise.server.mcp_server._retrieval_rank import path_word_counts, path_words++ assert path_words("src/the/io_utils.json") == {"src", "the", "utils"}+ assert path_word_counts(["a/models.py", "b/models.ts"])["models"] == 2+ hits = [{"target_path": "the/py/json.py", "relevance_score": 1.0}]+ self._boost(hits, "the py io", {"the": 1, "py": 1, "io": 1}, total=100)+ assert hits[0]["relevance_score"] == 1.0++ @pytest.mark.asyncio+ @pytest.mark.parametrize("leg", ["concept", "hybrid"])+ async def test_search_ranks_the_named_file_first(self, setup_mcp, leg):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import search_codebase+ from repowise.server.mcp_server._helpers import _resolve_repo_context+ from repowise.server.mcp_server.tool_search import _search_single_repo++ await _seed_page("file_page:services/_hotkey_carbon.py", "services/_hotkey_carbon.py")+ await _seed_page("file_page:services/_hotkey_pynput.py", "services/_hotkey_pynput.py")+ for n in range(30): # past the tiny-repo floor+ await _seed_page(f"file_page:pkg/mod_{n}.py", f"pkg/mod_{n}.py")++ async def fake_search(query, limit=10):+ return [+ _mk_result(+ "file_page:services/_hotkey_carbon.py",+ "Register a global hotkey backend, not pynput",+ "file_page", "services/_hotkey_carbon.py", 0.9,+ ),+ _mk_result(+ "file_page:services/_hotkey_pynput.py", "Register a global hotkey backend",+ "file_page", "services/_hotkey_pynput.py", 0.8,+ ),+ ]++ mcp_mod._vector_store.search = fake_search+ mcp_mod._fts.search = fake_search+ query = "register global hotkey pynput backend"+ if leg == "concept":+ rows = (await search_codebase(query, mode="concept"))["results"]+ else: # the page leg hybrid search runs+ rows = await _search_single_repo(await _resolve_repo_context(None), query, 5, None)+ assert (rows[0].get("path") or rows[0]["target_path"]) == "services/_hotkey_pynput.py"+++class TestPathModeWithWords:+ def test_path_tokens(self):+ from repowise.server.mcp_server._query_shape import path_tokens++ assert path_tokens("services/_hotkey_pynput.py register hotkey") == [+ "services/_hotkey_pynput.py"+ ]+ assert path_tokens(r"see `src\a.py:120`, then b.ts.") == [r"src\a.py", "b.ts"]+ assert path_tokens("register hotkey") == []++ def test_path_tokens_skip_urls_prose_slashes_and_member_suffixes(self):+ from repowise.server.mcp_server._query_shape import path_tokens++ paths = ["src/client/http.py", "docs/guide.md"]+ assert path_tokens("see https://x.dev/a.py and/or client/server", paths) == []+ assert path_tokens("tests/a.py::test_x fails") == ["tests/a.py"]+ assert path_tokens("look in src/client please", paths) == ["src/client"]+ assert path_tokens("look in src/client please") == []++ @pytest.mark.asyncio+ async def test_words_around_a_path_do_not_empty_the_result(self, setup_mcp):+ from repowise.server.mcp_server import search_codebase++ await _seed_page("file_page:services/_hotkey_pynput.py", "services/_hotkey_pynput.py")+ result = await search_codebase(+ "services/_hotkey_pynput.py register hotkey", mode="path"+ )+ assert [r["file"] for r in result["results"]] == ["services/_hotkey_pynput.py"]+++class TestSymbolModeExactOnly:+ @pytest.mark.asyncio+ async def test_an_exact_match_is_returned_alone(self, session, populated_db, setup_mcp):+ from repowise.server.mcp_server import search_codebase++ _add_symbols(session, populated_db, _WIDGET_ROWS)+ await session.commit()++ res = await search_codebase("widget", mode="symbol", limit=5)+ assert sorted(r["symbol_id"] for r in res["results"]) == [+ "src/widget/core.py::Box.widget",+ "src/widget/core.py::widget",+ ]+ assert res["fuzzy_omitted"] == 3+ assert res["exact_match"] is True+ assert res["note"].startswith("3 other symbols contain this name")++ @pytest.mark.asyncio+ async def test_fuzzy_omitted_counts_past_the_limit(self, session, populated_db, setup_mcp):+ from repowise.server.mcp_server import search_codebase++ _add_symbols(session, populated_db, _WIDGET_ROWS)+ await session.commit()++ res = await search_codebase("widget", mode="symbol", limit=1)+ assert len(res["results"]) == 1+ assert res["results"][0]["name"] == "widget"+ assert res["fuzzy_omitted"] == 3++ @pytest.mark.asyncio+ async def test_a_shared_token_is_not_a_name_neighbour(self, session, populated_db, setup_mcp):+ from repowise.server.mcp_server import search_codebase++ _add_symbols(session, populated_db, [+ ("src/carbon.py", "CarbonRegistrar", "CarbonRegistrar", 1),+ ("src/tools.py", "carbon_tools", "carbon_tools", 1),+ ("src/reg.py", "registrar_for", "registrar_for", 1),+ ])+ await session.commit()++ res = await search_codebase("CarbonRegistrar", mode="symbol")+ assert [r["name"] for r in res["results"]] == ["CarbonRegistrar"]+ assert "fuzzy_omitted" not in res+ assert "note" not in res++ @pytest.mark.asyncio+ async def test_no_exact_match_keeps_the_fuzzy_list(self, setup_mcp):+ from repowise.server.mcp_server import search_codebase++ res = await search_codebase("AuthServ", mode="symbol")+ assert res["results"]+ assert "fuzzy_omitted" not in res+ assert "exactly matches" in res["note"]