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.

feat(mcp): improve retrieval precision (#1933)

Raghav Chamadiya84491a9ee436
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
index 0bdf3bb82..411c38934 100644
--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
@@ -869,23 +869,28 @@ async def expand_via_graph(hits: list[dict], ctx: Any, repo_id: str) -> list[dic
# Damp parent score by _GRAPH_EXPAND_DAMPING for child candidates; pick
# the strongest parent each child connects to (taking the max parent
# score is conservative — favors well-connected neighbors).
- parent_score = max((h.get("score", 0.0) for h in hits[:_GRAPH_EXPAND_TOP_N]), default=0.0)
+ strongest_parent = max(
+ hits[:_GRAPH_EXPAND_TOP_N], key=lambda hit: hit.get("score", 0.0), default={}
+ )
+ parent_score = strongest_parent.get("score", 0.0)
+ confidence_factor = strongest_parent.get("_confidence_score_factor")
candidates: list[dict] = []
for path, summary, page_type in page_rows:
- candidates.append(
- {
- "page_id": f"file_page:{path}",
- "target_path": path,
- "title": f"File: {path}",
- "summary": summary or "",
- "snippet": (summary or "")[:200],
- "page_type": page_type or "file_page",
- "score": parent_score * _GRAPH_EXPAND_DAMPING,
- "_sources": {"graph_expand"},
- "_expanded_from": "graph",
- "_pagerank": pr_by_path.get(path, 0.0),
- }
- )
+ candidate = {
+ "page_id": f"file_page:{path}",
+ "target_path": path,
+ "title": f"File: {path}",
+ "summary": summary or "",
+ "snippet": (summary or "")[:200],
+ "page_type": page_type or "file_page",
+ "score": parent_score * _GRAPH_EXPAND_DAMPING,
+ "_sources": {"graph_expand"},
+ "_expanded_from": "graph",
+ "_pagerank": pr_by_path.get(path, 0.0),
+ }
+ if confidence_factor is not None:
+ candidate["_confidence_score_factor"] = confidence_factor
+ candidates.append(candidate)
# Rank candidates by PageRank within the expansion set so we pick the
# most central neighbor first when we have multiple plausible ones.
diff --git a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
index cf1bbc6d5..b0ae3a717 100644
--- a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
@@ -42,7 +42,7 @@ from __future__ import annotations
from typing import Any
-from sqlalchemy import func, select
+from sqlalchemy import func, or_, select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphNode, Page, WikiSymbol
@@ -81,9 +81,14 @@ _TERM_MATCH_SCORE = 10.0
# as opposed to being one token inside it (``persist`` -> ``_persist_symbols``).
_LEAF_NAME_BONUS = 15.0
+# These names are common because they describe an operation, not a domain.
+# They remain valid evidence when the owner, module, or path also agrees with
+# the question; the bare member name alone is deliberately insufficient.
+_GENERIC_MEMBER_NAMES = frozenset({"get", "run", "main"})
+
async def _candidates_for_term(session, repo_id: str, term: str) -> tuple[list[WikiSymbol], bool]:
- """Up to :data:`_PER_TERM_CANDIDATES` symbols whose name mentions *term*.
+ """Up to :data:`_PER_TERM_CANDIDATES` symbols whose identity mentions *term*.
Returns ``(rows, saturated)``. Shorter names first: a term is a larger
share of a short name, so ``persist`` identifies ``persist_pages`` far
@@ -95,7 +100,11 @@ async def _candidates_for_term(session, repo_id: str, term: str) -> tuple[list[W
select(WikiSymbol)
.where(
WikiSymbol.repository_id == repo_id,
- WikiSymbol.name.ilike(f"%{esc}%", escape=LIKE_ESCAPE),
+ or_(
+ WikiSymbol.name.ilike(f"%{esc}%", escape=LIKE_ESCAPE),
+ WikiSymbol.qualified_name.ilike(f"%{esc}%", escape=LIKE_ESCAPE),
+ WikiSymbol.file_path.ilike(f"%{esc}%", escape=LIKE_ESCAPE),
+ ),
)
.order_by(func.length(WikiSymbol.name))
.limit(_PER_TERM_CANDIDATES)
@@ -132,21 +141,22 @@ def _score(
def _corroborated(row: WikiSymbol, covered: dict[str, float], saturated: set[str]) -> bool:
"""Whether *row* has enough independent evidence to enter the pool.
- One term is enough when it is the symbol's whole name and it is not a
- saturated one: that is a caller naming the thing, just without the
- underscores. Otherwise **two informative terms** must land. Saturated terms
- do not count toward that pair: two common words agreeing is not corroboration,
- it is the same non-signal twice, and letting them through is what put
- ``ui/lib/cn.ts`` in the top five for a question about building skeletons.
- Directly mirrors the guard lexical code-search engines apply to bare English
- query words.
+ One term is enough when it is the symbol's whole specific name and it is not
+ saturated: that is a caller naming the thing, just without the underscores.
+ Generic members such as ``get`` remain valid only when an owner/module/path
+ term also agrees. Otherwise **two informative terms** must land. Saturated
+ terms do not count toward that pair: two common words agreeing is not
+ corroboration, it is the same non-signal twice.
"""
if not covered:
return False
name = (row.name or "").lower()
- if name in covered and name not in saturated:
+ informative = {term for term in covered if term not in saturated}
+ if name in _GENERIC_MEMBER_NAMES:
+ return any(term != name for term in informative)
+ if name in informative:
return True
- return sum(1 for t in covered if t not in saturated) >= 2
+ return len(informative) >= 2
async def search_symbols_by_terms(
@@ -207,7 +217,7 @@ async def search_symbols_by_terms(
# A term counts as covered when it survives tokenisation of the symbol
# name, not merely as a substring: ``update`` should match
# ``update_index``, not ``groupdater``.
- stoks = _tokens(row.name) | _tokens(row.qualified_name)
+ stoks = _tokens(row.name) | _tokens(row.qualified_name) | _tokens(row.file_path)
covered = {
t: (_SATURATED_TERM_WEIGHT if t in saturated else 1.0)
for t in matched.get(symbol_id, ())
diff --git a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py
new file mode 100644
index 000000000..b6b3122b1
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py
@@ -0,0 +1,107 @@
+"""Shared intent-aware calibration for page retrieval legs."""
+
+from __future__ import annotations
+
+import math
+import re
+
+from repowise.server.mcp_server._query_terms import content_terms
+
+_INFLECTIONS = {
+ "changed": "change",
+ "changes": "change",
+ "files": "file",
+ "tested": "test",
+ "testing": "test",
+ "tests": "test",
+}
+
+
+def _ranking_terms(text: str, *, max_terms: int = 8) -> set[str]:
+ """Content terms with a tiny retrieval-only inflection normalisation."""
+ return {_INFLECTIONS.get(term, term) for term in content_terms(text, max_terms=max_terms)}
+
+
+def rerank_by_context_coverage(
+ hits: list[dict],
+ query: str,
+ *,
+ score_key: str,
+ floor: float,
+ absolute_stopwords: set[str] | None = None,
+) -> list[dict]:
+ """Calibrate a fused page window with discriminating query-term coverage.
+
+ The input score remains authoritative. Coverage is a bounded multiplier,
+ computed over title, prose, and path/module identity. Candidate-relative
+ term weights make vocabulary repeated by the whole window weak evidence,
+ while terms that distinguish one candidate carry more weight.
+ """
+ terms = _ranking_terms(query)
+ if not terms or not hits:
+ return hits
+
+ texts_by_hit = [
+ " ".join(
+ [
+ hit.get("title", "") or "",
+ hit.get("snippet", "") or "",
+ hit.get("summary", "") or "",
+ hit.get("target_path", "") or "",
+ ]
+ )
+ for hit in hits
+ ]
+ tokens_by_hit = [_ranking_terms(text, max_terms=128) for text in texts_by_hit]
+ document_frequency = {
+ term: sum(1 for tokens in tokens_by_hit if term in tokens) for term in terms
+ }
+ weights = {
+ term: 1.0 + math.log((len(hits) + 1) / (document_frequency[term] + 1))
+ for term in terms
+ }
+ total_weight = sum(weights.values())
+
+ coverages = [
+ sum(weight for term, weight in weights.items() if term in tokens) / total_weight
+ for tokens in tokens_by_hit
+ ]
+ best_coverage = max(coverages)
+
+ legacy_terms = (
+ [
+ term
+ for term in re.findall(r"[a-zA-Z0-9_]+", query.lower())
+ if len(term) >= 3 and term not in absolute_stopwords
+ ]
+ if absolute_stopwords is not None
+ else []
+ )
+
+ for hit, text_value, tokens, coverage in zip(
+ hits, texts_by_hit, tokens_by_hit, coverages, strict=True
+ ):
+ raw = hit.get(score_key, 0.0) or 0.0
+ hit["_coverage"] = coverage
+ hit["_raw_score"] = raw
+ # Ranking is candidate-relative so the best contextual match keeps its
+ # source score and weaker matches lose ground. Confidence, however,
+ # keeps get_answer's pre-existing absolute coverage scale: relative
+ # calibration may change order, but cannot manufacture dominance.
+ if legacy_terms:
+ haystack = text_value.lower()
+ absolute_coverage = sum(term in haystack for term in legacy_terms) / len(
+ legacy_terms
+ )
+ else:
+ absolute_coverage = len(terms & tokens) / len(terms)
+ absolute_multiplier = floor + (1.0 - floor) * max(
+ coverage, absolute_coverage
+ )
+ relative_coverage = coverage / best_coverage if best_coverage else 1.0
+ ranking_multiplier = floor + (1.0 - floor) * relative_coverage
+ hit["_coverage_multiplier"] = ranking_multiplier
+ hit["_confidence_score_factor"] = absolute_multiplier / ranking_multiplier
+ hit[score_key] = raw * ranking_multiplier
+ hits.sort(key=lambda hit: hit.get(score_key, 0.0), reverse=True)
+ return hits
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py b/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py
index a29849f50..9d15f3e6d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py
@@ -425,6 +425,15 @@ def implicated_withheld_symbols(
return out
+def _confidence_score(hit: dict) -> float:
+ """Return a score on get_answer's absolute coverage confidence scale."""
+ score = hit.get("score", 0.0)
+ factor = hit.get("_confidence_score_factor", 1.0)
+ if isinstance(factor, (int, float)) and factor >= 0:
+ return score * factor
+ return score
+
+
def _top_two_score_ratio(hits: list[dict]) -> float:
"""The top hit's retrieval score over the runner-up's.
@@ -435,7 +444,7 @@ def _top_two_score_ratio(hits: list[dict]) -> float:
no hits at all is zero.
"""
if len(hits) >= 2:
- return hits[0].get("score", 0.0) / (hits[1].get("score", 0.0) or 1e-9)
+ return _confidence_score(hits[0]) / (_confidence_score(hits[1]) or 1e-9)
return float("inf") if hits else 0.0
@@ -548,8 +557,8 @@ def dominance_reason(hits: list[dict], *, agreement_dominant: bool = False) -> s
return None
if len(hits) < 2:
return "sole_hit"
- top_score = hits[0].get("score", 0.0)
- second_score = hits[1].get("score", 0.0) or 1e-9
+ top_score = _confidence_score(hits[0])
+ second_score = _confidence_score(hits[1]) or 1e-9
if top_score >= _DOMINANCE_ABS_SCORE_FLOOR:
if (top_score - second_score) >= _DOMINANCE_ABS_GAP:
return "gap"
@@ -587,7 +596,7 @@ def _retrieval_quality(hits: list[dict], agreement_dominant: bool) -> str:
ambiguity caveat are keyed on. Without that the payload could rate retrieval
weak and treat it as dominant in the same breath.
"""
- top_score = hits[0].get("score", 0.0) if hits else 0.0
+ top_score = _confidence_score(hits[0]) if hits else 0.0
dominant_grade = is_dominant(hits, agreement_dominant=agreement_dominant)
if dominant_grade and top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:
return "high"
@@ -685,8 +694,8 @@ def _grade_answer(
"""
dominant = dominance is not None
_ratio = _top_two_score_ratio(hits)
- _top_score = hits[0].get("score", 0.0) if hits else 0.0
- _second_score = hits[1].get("score", 0.0) if len(hits) >= 2 else 0.0
+ _top_score = _confidence_score(hits[0]) if hits else 0.0
+ _second_score = _confidence_score(hits[1]) if len(hits) >= 2 else 0.0
# A response can EARN "high" on a NON-dominant retrieval, by two routes that
# are NOT equally good and so are tracked apart. Both need the score floor,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
index dd1b6f02b..5fd921b39 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
@@ -17,6 +17,8 @@ from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import Page
from repowise.server.mcp_server._page_paths import hit_file_path
+from repowise.server.mcp_server._query_terms import content_terms
+from repowise.server.mcp_server._retrieval_rank import rerank_by_context_coverage
from repowise.server.mcp_server.tool_answer.config import (
_BACKEND_PATH_PREFIXES,
_BACKEND_QUESTION_TOKENS,
@@ -129,7 +131,8 @@ def serialize_hits(
) -> list[dict]:
"""Agent-facing view of retrieval hits — content only, no plumbing.
- Internal scoring fields (``_coverage``, ``_raw_score``, ``_sources``,
+ Internal scoring fields (``_coverage``, ``_coverage_multiplier``,
+ ``_confidence_score_factor``, ``_raw_score``, ``_sources``,
``_pagerank``, …) and ``page_id`` are ranking debug an agent can do
nothing with; they were ~70% of a get_answer response by volume. Zero
information loss for the consumer: path, title, summary, snippet,
@@ -190,12 +193,8 @@ def serialize_hits(
def _question_terms(question: str) -> list[str]:
- """Extract content terms from a question. Lowercase, alnum-tokenized,
- stopwords + length<3 dropped. Used by the term-coverage re-ranker."""
- import re
-
- raw = re.findall(r"[a-zA-Z0-9_]+", question.lower())
- return [t for t in raw if len(t) >= 3 and t not in _STOPWORDS]
+ """Extract shared snake/camel-aware content terms for retrieval ranking."""
+ return content_terms(question)
def _split_relational(question: str) -> list[str] | None:
@@ -370,38 +369,24 @@ def _candidate_justification(h: dict) -> str:
def _rerank_by_coverage(hits: list[dict], question: str) -> list[dict]:
- """Re-rank FTS hits by term-coverage boost on top of BM25.
+ """Re-rank hybrid hits by intent-bearing term coverage.
- For each hit, compute the fraction of distinct query terms present in
- (title + snippet + summary), then multiply the raw BM25 score by
- (FLOOR + (1-FLOOR)*coverage). Single-concept questions (coverage≈1.0
- across all hits) are unaffected; multi-constraint questions push hits
- that cover all the terms above hits that repeat just one term.
+ Coverage includes the path/module identity as well as title and prose.
+ Terms every candidate repeats carry less weight than discriminating terms,
+ so a generic lexical overlap such as ``coverage`` cannot beat a page that
+ also agrees on ``PR``, ``test impact``, and ``changed files``. Raw fused
+ retrieval remains the base signal; this is a bounded multiplier, not a
+ replacement score.
This addresses a common BM25 failure mode where a hit that matches one
constraint very strongly can outrank a hit that matches all constraints
moderately — the latter is usually the better answer for multi-constraint
questions.
"""
- terms = set(_question_terms(question))
- if not terms or not hits:
- return hits
- n_terms = len(terms)
- for h in hits:
- haystack = " ".join(
- [
- h.get("title", "") or "",
- h.get("snippet", "") or "",
- h.get("summary", "") or "",
- ]
- ).lower()
- # Count distinct terms present (substring match — FTS5 already handles
- # stemming upstream, so we keep this simple).
- present = sum(1 for t in terms if t in haystack)
- coverage = present / n_terms
- raw = h.get("score", 0.0)
- h["_coverage"] = coverage
- h["_raw_score"] = raw
- h["score"] = raw * (_COVERAGE_FLOOR + (1.0 - _COVERAGE_FLOOR) * coverage)
- hits.sort(key=lambda h: h["score"], reverse=True)
- return hits
+ return rerank_by_context_coverage(
+ hits,
+ question,
+ score_key="score",
+ floor=_COVERAGE_FLOOR,
+ absolute_stopwords=_STOPWORDS,
+ )
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index abe580518..fef47439f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -38,6 +38,7 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._page_paths import file_candidates, hit_file_path
from repowise.server.mcp_server._prose_symbols import symbol_backed_pages
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.tool_search_symbols import (
_qual_norm,
search_paths_single,
@@ -67,6 +68,17 @@ _FRESHNESS_TIEBREAK = 0.03
_IDENT_QUERY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]{1,29}$")
+def _canonical_symbol_query(query: str) -> tuple[str, str] | None:
+ """Return ``(path, symbol)`` for an exact canonical ``path::Symbol`` query."""
+ stripped = query.strip().replace("\\", "/")
+ if "::" not in stripped:
+ return None
+ path, symbol = stripped.rsplit("::", 1)
+ if not path or not symbol or "/" not in path:
+ return None
+ return path, symbol
+
+
def _looks_like_exact_token(query: str) -> bool:
"""True when the query is a single identifier-shaped token best served by Grep."""
stripped = query.strip()
@@ -79,7 +91,9 @@ def _looks_like_exact_token(query: str) -> bool:
# (≥1 underscore, incl. _UPPER_SNAKE constants) or CamelCase (≥2 humps).
# Plain English words never match.
_IDENT_TOKEN_RE = re.compile(
- r"\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+)\b"
+ r"\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][A-Za-z0-9_]+)"
+ r"(?:\.[A-Za-z_][A-Za-z0-9_]*)+\b"
+ r"|\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+)\b"
)
@@ -97,12 +111,31 @@ def _identifier_candidates(query: str, mode: str) -> list[str]:
"""
if mode == "symbol":
q = query.strip()
- return [q] if q else []
+ canonical = _canonical_symbol_query(q)
+ return [q, canonical[1]] if canonical else ([q] if q else [])
if mode == "hybrid":
return _embedded_identifiers(query)
return []
+def _qualified_name_matches(qn: str, wanted: set[str]) -> bool:
+ if not qn:
+ return False
+ if qn in wanted:
+ return True
+ return any("." in candidate and qn.endswith(f".{candidate}") for candidate in wanted)
+
+
+def _symbol_matches_name(item: dict, wanted: set[str]) -> bool:
+ symbol_id = (item.get("symbol_id") or "").strip().lower().replace("\\", "/")
+ if symbol_id and symbol_id in wanted:
+ return True
+ name = (item.get("name") or "").strip().lower()
+ if name and name in wanted:
+ return True
+ return _qualified_name_matches(_qual_norm(item.get("qualified_name")), wanted)
+
+
def _has_exact_symbol(candidates: list[str], symbols: list[dict]) -> bool:
"""True when some returned symbol's name/qualified-name equals a candidate.
@@ -115,12 +148,43 @@ def _has_exact_symbol(candidates: list[str], symbols: list[dict]) -> bool:
return False
wanted = {c.strip().lower() for c in candidates if c.strip()}
wanted |= {_qual_norm(c) for c in candidates if c.strip()}
- for s in symbols:
- name = (s.get("name") or "").strip().lower()
- qn = _qual_norm(s.get("qualified_name"))
- if (name and name in wanted) or (qn and qn in wanted):
- return True
- return False
+ return any(_symbol_matches_name(symbol, wanted) for symbol in symbols)
+
+
+def _protect_exact_symbols(query: str, symbols: list[dict]) -> list[dict]:
+ """Stable-partition an exact identifier or ``path::Symbol`` hit to the head."""
+ if not symbols:
+ return symbols
+ canonical = _canonical_symbol_query(query)
+ qnorm = query.strip().lower().replace("\\", "/")
+
+ def exact(item: dict) -> bool:
+ symbol_id = (item.get("symbol_id") or "").lower().replace("\\", "/")
+ if canonical:
+ return symbol_id == qnorm
+ return qnorm in {
+ (item.get("name") or "").lower(),
+ _qual_norm(item.get("qualified_name")),
+ }
+
+ protected = [item for item in symbols if exact(item)]
+ return protected + [item for item in symbols if not exact(item)]
+
+
+def _protect_named_symbols(candidates: list[str], symbols: list[dict]) -> list[dict]:
+ """Stable-partition symbols exactly named by identifiers embedded in prose."""
+ wanted = {candidate.strip().lower() for candidate in candidates if candidate.strip()}
+ wanted |= {_qual_norm(candidate) for candidate in candidates if candidate.strip()}
+
+ protected = [item for item in symbols if _symbol_matches_name(item, wanted)]
+ return protected + [item for item in symbols if not _symbol_matches_name(item, wanted)]
+
+
+def _protect_exact_paths(query: str, files: list[dict]) -> 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]
def _prose_dominates(query: str, identifiers: list[str]) -> bool:
@@ -535,6 +599,15 @@ def _drop_derivable_page_ids(results: list[dict]) -> list[dict]:
return results
+def _drop_internal_ranking_fields(results: list[dict]) -> None:
+ """Keep calibration diagnostics internal to the ranking pipeline."""
+ for item in results:
+ item.pop("_coverage", None)
+ item.pop("_coverage_multiplier", None)
+ item.pop("_confidence_score_factor", None)
+ item.pop("_raw_score", None)
+
+
async def _load_page_info(
session, output: list[dict], *, with_git: bool = False
) -> tuple[dict, set, dict]:
@@ -855,6 +928,8 @@ def _resolve_mode(query: str, mode: str | None) -> str:
m = "auto"
if m != "auto":
return m
+ if _canonical_symbol_query(query):
+ return "symbol"
if _is_path(query):
return "path"
if _looks_like_exact_token(query):
@@ -908,6 +983,9 @@ async def _structured_search(
# which then never reaches _has_exact_symbol and the response claims the
# symbol is unindexed. Score symbols on the extracted identifiers instead.
symbol_query = query
+ canonical_symbol = _canonical_symbol_query(query)
+ if canonical_symbol:
+ symbol_query = canonical_symbol[1]
if mode == "hybrid":
_idents = _embedded_identifiers(query)
if _idents:
@@ -933,11 +1011,17 @@ async def _structured_search(
symbols.sort(key=lambda x: -(x.get("score") or 0.0))
files.sort(key=lambda x: -(x.get("score") or 0.0))
+ candidates = _identifier_candidates(query, mode)
+ if mode == "symbol":
+ symbols = _protect_exact_symbols(query, symbols)
+ elif mode == "hybrid" and candidates:
+ symbols = _protect_named_symbols(candidates, symbols)
+ if mode == "path":
+ files = _protect_exact_paths(query, files)
# Whether any returned symbol matches the query's identifier(s) exactly.
# Computed once here so the hybrid interleave and the exact-match note below
# agree on the same signal.
- candidates = _identifier_candidates(query, mode)
exact = _has_exact_symbol(candidates, symbols) if candidates else False
if mode == "symbol":
@@ -1113,6 +1197,12 @@ async def search_codebase(
# Re-sort by adjusted relevance with retrieval noise (decisions on
# non-why queries, test pages on non-test queries) hard-demoted, then
# collapse near-duplicate decisions to one.
+ output = rerank_by_context_coverage(
+ output,
+ query,
+ score_key="relevance_score",
+ floor=0.5,
+ )
_downweight_test_pages(output, query)
_sort_demoting_noise(output, query)
output = _dedup_decisions(output)
@@ -1123,6 +1213,7 @@ async def search_codebase(
# weakest tail slots. No-op when the symbol leg names nothing new.
with contextlib.suppress(Exception):
output = await _append_symbol_backed(ctx, query, output, limit, kind)
+ _drop_internal_ranking_fields(output)
# The full ranked pool, kept before the caller's cut so ``candidates``
# below can reach past it. See its comment for why that matters.
ranked = list(output)
diff --git a/tests/fixtures/mcp/retrieval_precision_corpus.json b/tests/fixtures/mcp/retrieval_precision_corpus.json
new file mode 100644
index 000000000..6576b967b
--- /dev/null
+++ b/tests/fixtures/mcp/retrieval_precision_corpus.json
@@ -0,0 +1,148 @@
+{
+ "schema_version": 1,
+ "sealed_at_commit": "c2f915d07c11ca3f451309054dfb610e75b8ae26",
+ "window_size": 5,
+ "modes": ["full", "degraded"],
+ "degraded_mode": {
+ "embedder": "keyless",
+ "llm": "absent",
+ "retained_legs": ["path", "symbol", "fts", "history"]
+ },
+ "generic_member_names": ["get", "run", "main"],
+ "cases": [
+ {
+ "shape": "identifier",
+ "surface": "search_codebase",
+ "query": "search_codebase",
+ "known_correct_targets": [
+ "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase"
+ ],
+ "protected_targets": [
+ "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase"
+ ],
+ "required_targets": [],
+ "supported_generic_targets": [],
+ "oracle_basis": "Exact seeded WikiSymbol.name and canonical path::Symbol identity.",
+ "candidates": [
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase", "kind": "symbol", "member_name": "search_codebase", "path": "packages/server/src/repowise/server/mcp_server/tool_search.py", "owner": "", "context": ["search", "codebase", "mcp"], "legs": {"full": ["symbol", "semantic"], "degraded": ["symbol", "fts"]}},
+ {"target": "packages/cli/src/repowise/cli/commands/search_cmd.py::search", "kind": "symbol", "member_name": "search", "path": "packages/cli/src/repowise/cli/commands/search_cmd.py", "owner": "", "context": ["search", "cli"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "registry"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "owner": "", "context": ["mcp", "context"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}
+ ]
+ },
+ {
+ "shape": "path",
+ "surface": "search_codebase",
+ "query": "packages/core/src/repowise/core/analysis/test_impact.py",
+ "known_correct_targets": [
+ "packages/core/src/repowise/core/analysis/test_impact.py"
+ ],
+ "protected_targets": [
+ "packages/core/src/repowise/core/analysis/test_impact.py"
+ ],
+ "required_targets": [],
+ "supported_generic_targets": [],
+ "oracle_basis": "Exact seeded Page.target_path equality.",
+ "candidates": [
+ {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["analysis", "test", "impact"], "legs": {"full": ["path", "semantic"], "degraded": ["path", "fts"]}},
+ {"target": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "kind": "page", "member_name": "", "path": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "owner": "", "context": ["test", "impact", "semantics"], "legs": {"full": ["path", "semantic"], "degraded": ["path", "fts"]}},
+ {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["analysis", "pr", "blast"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/workspace/repo_index.py::RepoIndex.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/repo_index.py", "owner": "RepoIndex", "context": ["workspace", "repository"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "owner": "", "context": ["risk", "impact"], "legs": {"full": ["semantic"], "degraded": ["fts"]}}
+ ]
+ },
+ {
+ "shape": "concept",
+ "surface": "get_answer",
+ "query": "How does PR test-impact coverage choose the tests to run for changed files?",
+ "known_correct_targets": [
+ "packages/core/src/repowise/core/analysis/test_impact.py"
+ ],
+ "protected_targets": [],
+ "required_targets": [
+ "packages/core/src/repowise/core/analysis/pr_blast.py"
+ ],
+ "supported_generic_targets": [],
+ "oracle_basis": "analyze_test_impact owns measured/inferred recommendations and coverage-backed tests_to_run; pr_blast consumes it.",
+ "candidates": [
+ {"target": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "owner": "", "context": ["performance", "coverage", "health"], "legs": {"full": ["fts"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["pr", "test", "impact", "coverage", "changed", "files", "tests", "run"], "legs": {"full": ["semantic", "fts", "symbol"], "degraded": ["fts", "symbol"]}},
+ {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["pr", "changed", "files", "test", "impact"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "owner": "", "context": ["tests", "run", "basis", "risk", "directive"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}
+ ]
+ },
+ {
+ "shape": "cross_module_flow",
+ "surface": "get_answer",
+ "query": "How does an MCP question move from answer orchestration into hybrid page and symbol retrieval?",
+ "known_correct_targets": [
+ "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py"
+ ],
+ "protected_targets": [],
+ "required_targets": [
+ "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py"
+ ],
+ "supported_generic_targets": [],
+ "oracle_basis": "answer.py invokes the retrieval pipeline; _answer_pipeline.py owns hybrid page/symbol retrieval across module boundaries.",
+ "candidates": [
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "owner": "", "context": ["mcp", "question", "answer", "orchestration", "retrieval"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},
+ {"target": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "owner": "", "context": ["answer", "pipeline", "hybrid", "page", "symbol", "retrieval"], "legs": {"full": ["semantic", "fts", "symbol"], "degraded": ["fts", "symbol"]}},
+ {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "owner": "", "context": ["answer", "retrieval"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},
+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}
+ ]
+ },
+ {
+ "shape": "history_why",
+ "surface": "get_why",
+ "query": "Why does decision indexing call embed_batch directly?",
+ "known_correct_targets": ["dec_embed_batch_counters"],
+ "protected_targets": [],
+ "required_targets": [
+ "packages/core/src/repowise/core/analysis/decision_extractor.py"
+ ],
+ "supported_generic_targets": [],
+ "oracle_basis": "Standing decision: embed_batch raises on failure so indexed/failed counters stay honest; affected source is decision_extractor.py.",
+ "candidates": [
+ {"target": "dec_embed_batch_counters", "kind": "decision", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "indexing", "embed", "batch", "counters", "failure"], "legs": {"full": ["history", "semantic"], "degraded": ["history", "fts"]}},
+ {"target": "packages/core/src/repowise/core/analysis/decision_extractor.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "extractor", "indexing", "embed", "batch"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},
+ {"target": "dec_generic_branch_names", "kind": "decision", "member_name": "", "path": "", "owner": "", "context": ["branch", "names"], "legs": {"full": ["history"], "degraded": ["history"]}},
+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}
+ ]
+ },
+ {
+ "shape": "ambiguous_generic_name",
+ "surface": "search_codebase",
+ "query": "Where does OmissionStore.get expand a saved omission reference?",
+ "known_correct_targets": [
+ "packages/core/src/repowise/core/distill/store.py::OmissionStore.get"
+ ],
+ "protected_targets": [
+ "packages/core/src/repowise/core/distill/store.py::OmissionStore.get"
+ ],
+ "required_targets": [],
+ "supported_generic_targets": [
+ "packages/core/src/repowise/core/distill/store.py::OmissionStore.get"
+ ],
+ "oracle_basis": "The generic leaf is supported by exact owner, module/path, and omission-reference query context; every other generic member is manually labelled unsupported.",
+ "candidates": [
+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "alias"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/store.py::OmissionStore.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "OmissionStore", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["symbol", "semantic", "fts"], "degraded": ["symbol", "fts"]}},
+ {"target": "packages/core/src/repowise/core/ingestion/languages/registry.py::LanguageRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/ingestion/languages/registry.py", "owner": "LanguageRegistry", "context": ["language", "tag"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/sessions/cursor.py::SessionCursor.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/sessions/cursor.py", "owner": "SessionCursor", "context": ["session", "cursor", "file"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},
+ {"target": "packages/core/src/repowise/core/distill/store.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}}
+ ]
+ }
+ ]
+}
diff --git a/tests/unit/server/mcp/test_prose_symbols.py b/tests/unit/server/mcp/test_prose_symbols.py
index af73e823c..1f07f6e8b 100644
--- a/tests/unit/server/mcp/test_prose_symbols.py
+++ b/tests/unit/server/mcp/test_prose_symbols.py
@@ -82,5 +82,17 @@ def test_a_saturated_term_cannot_carry_a_leaf_name_match_alone():
assert not _corroborated(_Sym("get"), {"get": 0.25}, saturated={"get"})
+def test_generic_member_name_alone_is_weak_even_when_not_saturated():
+ assert not _corroborated(_Sym("get"), {"get": 1.0}, saturated=set())
+
+
+def test_generic_member_survives_when_owner_or_module_context_agrees():
+ assert _corroborated(
+ _Sym("get"),
+ {"get": 0.25, "omission": 1.0, "store": 1.0},
+ saturated={"get"},
+ )
+
+
def test_no_matched_terms_is_never_corroborated():
assert not _corroborated(_Sym("_persist_symbols"), {}, saturated=set())
diff --git a/tests/unit/server/mcp/test_retrieval_precision_corpus.py b/tests/unit/server/mcp/test_retrieval_precision_corpus.py
new file mode 100644
index 000000000..e8df0f4a5
--- /dev/null
+++ b/tests/unit/server/mcp/test_retrieval_precision_corpus.py
@@ -0,0 +1,175 @@
+"""Immutable oracles for the deterministic retrieval-precision corpus.
+
+This file intentionally validates only the sealed inputs. Ranking assertions
+consume this corpus in later tests, but production routing, generic-name, and
+scoring helpers must never be used to derive these expected identities.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+CORPUS_PATH = (
+ Path(__file__).resolve().parents[3] / "fixtures" / "mcp" / "retrieval_precision_corpus.json"
+)
+EXPECTED_SHAPES = {
+ "identifier",
+ "path",
+ "concept",
+ "cross_module_flow",
+ "history_why",
+ "ambiguous_generic_name",
+}
+
+
+def load_retrieval_precision_corpus() -> dict:
+ return json.loads(CORPUS_PATH.read_text(encoding="utf-8"))
+
+
+def test_sealed_corpus_has_six_independent_query_shapes() -> None:
+ corpus = load_retrieval_precision_corpus()
+ cases = corpus["cases"]
+
+ assert corpus["sealed_at_commit"] == "c2f915d07c11ca3f451309054dfb610e75b8ae26"
+ assert corpus["window_size"] == 5
+ assert corpus["modes"] == ["full", "degraded"]
+ assert {case["shape"] for case in cases} == EXPECTED_SHAPES
+ assert len(cases) == len(EXPECTED_SHAPES)
+
+ for case in cases:
+ assert case["query"]
+ assert case["known_correct_targets"]
+ assert case["oracle_basis"]
+ assert len(case["candidates"]) > corpus["window_size"]
+ candidate_targets = {candidate["target"] for candidate in case["candidates"]}
+ assert set(case["known_correct_targets"]) <= candidate_targets
+ assert set(case["required_targets"]) <= candidate_targets
+ assert set(case["protected_targets"]) <= set(case["known_correct_targets"])
+ assert set(case["supported_generic_targets"]) <= candidate_targets
+ for candidate in case["candidates"]:
+ assert set(candidate["legs"]) == set(corpus["modes"])
+ assert candidate["legs"]["degraded"], "keyless candidates must retain a local leg"
+
+
+def test_generic_support_labels_are_fixture_owned_and_include_positive_controls() -> None:
+ corpus = load_retrieval_precision_corpus()
+ generic_names = set(corpus["generic_member_names"])
+ generic_case = next(case for case in corpus["cases"] if case["shape"] == "ambiguous_generic_name")
+ generic_candidates = {
+ candidate["target"]
+ for candidate in generic_case["candidates"]
+ if candidate["member_name"] in generic_names
+ }
+
+ assert {"get", "run", "main"} <= {
+ candidate["member_name"] for candidate in generic_case["candidates"]
+ }
+ assert set(generic_case["supported_generic_targets"])
+ assert set(generic_case["supported_generic_targets"]) < generic_candidates
+ assert set(generic_case["known_correct_targets"]) == set(
+ generic_case["supported_generic_targets"]
+ )
+
+
+def test_full_and_degraded_arms_share_queries_windows_and_oracles() -> None:
+ corpus = load_retrieval_precision_corpus()
+
+ assert corpus["degraded_mode"] == {
+ "embedder": "keyless",
+ "llm": "absent",
+ "retained_legs": ["path", "symbol", "fts", "history"],
+ }
+ for case in corpus["cases"]:
+ assert all(candidate["legs"]["full"] for candidate in case["candidates"])
+ assert all(candidate["legs"]["degraded"] for candidate in case["candidates"])
+
+
+def _rank_case(case: dict, mode: str, window_size: int) -> list[dict]:
+ """Feed sealed candidates through the production ordering primitives."""
+ from repowise.server.mcp_server._prose_symbols import _corroborated
+ from repowise.server.mcp_server._query_terms import content_terms
+ from repowise.server.mcp_server.tool_answer.retrieval import _rerank_by_coverage
+ from repowise.server.mcp_server.tool_search import (
+ _protect_exact_paths,
+ _protect_exact_symbols,
+ )
+
+ hits: list[dict] = []
+ query_terms = set(content_terms(case["query"]))
+ generic_names = {"get", "run", "main"}
+ for index, candidate in enumerate(case["candidates"]):
+ member_name = candidate["member_name"]
+ if case["shape"] == "ambiguous_generic_name" and member_name in generic_names:
+ covered = {
+ term: (0.25 if term == member_name else 1.0)
+ for term in query_terms & ({member_name} | set(candidate["context"]))
+ }
+ row = SimpleNamespace(name=member_name)
+ if not _corroborated(row, covered, saturated={member_name}):
+ continue
+ hits.append(
+ {
+ "target": candidate["target"],
+ "symbol_id": candidate["target"] if candidate["kind"] == "symbol" else "",
+ "name": member_name,
+ "qualified_name": (
+ candidate["target"].split("::", 1)[-1]
+ if candidate["kind"] == "symbol"
+ else ""
+ ),
+ "file": candidate["path"],
+ "target_path": candidate["path"],
+ "title": candidate["target"].rsplit("/", 1)[-1],
+ "summary": " ".join(candidate["context"]),
+ "snippet": " ".join(candidate["context"]),
+ "page_type": "decision_record" if candidate["kind"] == "decision" else "file_page",
+ "score": 1.0 - index * 0.05,
+ "_sources": set(candidate["legs"][mode]),
+ }
+ )
+
+ if case["shape"] in {"identifier", "ambiguous_generic_name"}:
+ hits = _protect_exact_symbols(case["query"], hits)
+ elif case["shape"] == "path":
+ hits = _protect_exact_paths(case["query"], hits)
+ else:
+ hits = _rerank_by_coverage(hits, case["query"])
+ return hits[:window_size]
+
+
+def _case_metrics(corpus: dict, case: dict, mode: str) -> dict:
+ window = _rank_case(case, mode, corpus["window_size"])
+ targets = [hit["target"] for hit in window]
+ primary = case["known_correct_targets"][0]
+ unsupported_generic = [
+ hit
+ for hit in window
+ if hit["name"] in corpus["generic_member_names"]
+ and hit["target"] not in case["supported_generic_targets"]
+ ]
+ return {
+ "rank": targets.index(primary) + 1 if primary in targets else None,
+ "protected": primary in case["protected_targets"] and targets[0] == primary,
+ "generic_noise_share": len(unsupported_generic) / len(window),
+ "targets": targets,
+ "sources": [hit["_sources"] for hit in window],
+ }
+
+
+def test_sealed_ranking_corpus_in_full_and_degraded_modes() -> None:
+ corpus = load_retrieval_precision_corpus()
+
+ for mode in corpus["modes"]:
+ for case in corpus["cases"]:
+ metrics = _case_metrics(corpus, case, mode)
+ assert metrics["rank"] is not None, (case["shape"], mode, metrics)
+ assert metrics["generic_noise_share"] < 0.5, (case["shape"], mode, metrics)
+ assert metrics["targets"], (case["shape"], mode)
+ if case["protected_targets"]:
+ assert metrics["protected"], (case["shape"], mode, metrics)
+ for required in case["required_targets"]:
+ assert required in metrics["targets"], (case["shape"], mode, metrics)
+ if mode == "degraded":
+ assert all("semantic" not in sources for sources in metrics["sources"])
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index c9f6e7e95..4a499c2e7 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -788,6 +788,44 @@ class TestHybridInterleave:
assert out == symbols
+class TestProtectedExactMatches:
+ def test_canonical_symbol_id_routes_to_symbol_search(self):
+ from repowise.server.mcp_server.tool_search import _resolve_mode
+
+ query = "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase"
+ assert _resolve_mode(query, "auto") == "symbol"
+
+ def test_canonical_symbol_id_is_stably_protected(self):
+ from repowise.server.mcp_server.tool_search import _protect_exact_symbols
+
+ exact_id = "src/auth/service.py::AuthService.run"
+ symbols = [
+ {"symbol_id": "src/jobs/runner.py::run", "name": "run", "score": 999.0},
+ {"symbol_id": exact_id, "name": "run", "score": 1.0},
+ {"symbol_id": "src/cli/main.py::main", "name": "main", "score": 500.0},
+ ]
+
+ out = _protect_exact_symbols(exact_id, symbols)
+
+ assert out[0]["symbol_id"] == exact_id
+ assert out[1:] == [symbols[0], symbols[2]]
+
+ def test_exact_path_is_stably_protected(self):
+ from repowise.server.mcp_server.tool_search import _protect_exact_paths
+
+ exact_path = "src/auth/middleware.py"
+ files = [
+ {"file": "tests/auth/middleware.py", "score": 999.0},
+ {"file": exact_path, "score": 1.0},
+ {"file": "src/legacy/middleware.py", "score": 500.0},
+ ]
+
+ out = _protect_exact_paths(exact_path, files)
+
+ assert out[0]["file"] == exact_path
+ assert out[1:] == [files[0], files[2]]
+
+
class TestConceptModeUnchanged:
"""Forcing mode="concept" preserves the original semantic behavior."""
@@ -809,6 +847,13 @@ class TestConceptModeUnchanged:
# Concept mode does not set the structural "mode" routing key.
assert "results" in result
assert all(r.get("type") != "symbol" for r in result["results"])
+ assert all(
+ "_coverage" not in r
+ and "_coverage_multiplier" not in r
+ and "_confidence_score_factor" not in r
+ and "_raw_score" not in r
+ for r in result["results"]
+ )
class TestIdentifierGrepHint:
@@ -861,8 +906,31 @@ class TestExactMatchSignal:
assert _identifier_candidates("AuthService", "symbol") == ["AuthService"]
assert _identifier_candidates("where is AuthService defined", "hybrid") == ["AuthService"]
+ assert _identifier_candidates(
+ "where does OmissionStore.get expand a reference", "hybrid"
+ ) == ["OmissionStore.get"]
+ assert _identifier_candidates("for example, e.g. retrieval flow", "hybrid") == []
assert _identifier_candidates("rate limiting", "concept") == []
+ def test_qualified_member_embedded_in_prose_is_protected(self):
+ from repowise.server.mcp_server.tool_search import _protect_named_symbols
+
+ exact = {
+ "name": "get",
+ "qualified_name": "repowise.core.distill.store.OmissionStore.get",
+ "score": 1.0,
+ }
+ symbols = [
+ {"name": "get_record", "qualified_name": "OmissionStore::get_record", "score": 99.0},
+ exact,
+ {"name": "get", "qualified_name": "LanguageRegistry::get", "score": 50.0},
+ ]
+
+ out = _protect_named_symbols(["OmissionStore.get"], symbols)
+
+ assert out[0] is exact
+ assert out[1:] == [symbols[0], symbols[2]]
+
@pytest.mark.asyncio
async def test_hybrid_scores_symbols_on_the_identifier_not_the_prose(
self, setup_mcp, monkeypatch