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(answer): retrieve files that have no wiki page (#3214)

Raghav Chamadiya538d4b85f7ff
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 a4fc5d593..2130dc808 100644
--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
@@ -70,7 +70,8 @@ from repowise.server.mcp_server._helpers import (
embed_timeout_s,
vector_search_timeout_s,
)
-from repowise.server.mcp_server._prose_symbols import symbol_backed_pages
+from repowise.server.mcp_server._page_paths import FILE_ROW_TYPES, PAGELESS_FILE, pageless_path
+from repowise.server.mcp_server._prose_symbols import filename_backed_pages, symbol_backed_pages
_log = logging.getLogger("repowise.mcp.answer")
@@ -224,6 +225,11 @@ _SYMBOL_LEG_MAX_PAGES = 8
# but it cannot outvote them.
_SYMBOL_LEG_RRF_K = 180
+# The filename leg is a name match too, weighted like the symbol leg. A name the
+# question spells in full (``full_cover``, see ``_prose_symbols``) is fused at the
+# page legs' k.
+_FILENAME_LEG_RRF_K = _SYMBOL_LEG_RRF_K
+
# ---------------------------------------------------------------------------
# The question's embedding, computed once per call
@@ -332,7 +338,7 @@ async def vector_search(
async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:
- """Run FTS, vector and symbol retrieval in parallel and merge via RRF.
+ """Run FTS, vector, symbol and filename retrieval in parallel and merge via RRF.
Returns a list of dicts shaped ``{page_id, title, score, snippet,
page_type, _sources: set[str]}``. ``_sources`` names which retrievers
@@ -343,14 +349,20 @@ async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:
Both retrievers are best-effort with timeouts so one slow path can never
block the call. An empty result from one mode just means the other mode
fully drives ranking, which matches the pre-hybrid behaviour.
+
+ The symbol and filename legs also name indexed files that have no page, as
+ ``page_type: "file"`` hits, the same rows ``search_codebase`` serves.
"""
# Reset before the legs run so the record describes this question and not
# a previous one that happened to share the task context.
begin_leg_record()
fts_task = _safe_fts_search(ctx, question)
vec_task = _safe_vector_search(ctx, question)
- sym_task = _safe_symbol_search(ctx, question)
- fts_results, vec_results, sym_results = await asyncio.gather(fts_task, vec_task, sym_task)
+ sym_task = _safe_symbol_search(ctx, question, pageless=True)
+ name_task = _safe_filename_search(ctx, question)
+ fts_results, vec_results, sym_results, name_results = await asyncio.gather(
+ fts_task, vec_task, sym_task, name_task
+ )
# RRF merge. Each hit's contribution from a source is 1/(rank + k);
# hits appearing in both sources sum their contributions naturally.
@@ -370,12 +382,23 @@ async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:
entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _RRF_K)
entry["_sources"].add("vector")
entry["_vec_rank"] = rank
- for rank, h in enumerate(sym_results):
+ for rank, h in leg_ranks(sym_results):
entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))
entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _SYMBOL_LEG_RRF_K)
entry["_sources"].add("symbol")
entry["_sym_rank"] = rank
entry["_symbol_names"] = h.symbol_names
+ # Adds files the other legs missed and never reorders a page they found.
+ # Search fuses the same rows into its own entry shape, crediting a symbol
+ # page of the file; here every leg is keyed by page id, as above.
+ for rank, (h, full) in leg_ranks(name_results):
+ if h.page_id in fused and h.page_type != PAGELESS_FILE:
+ continue
+ entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))
+ entry["score"] = entry.get("score", 0.0) + 1.0 / (
+ rank + (_RRF_K if full else _FILENAME_LEG_RRF_K)
+ )
+ entry["_sources"].add("filename")
# Scale to BM25-range so downstream confidence/dominance gates (tuned
# against the prior single-mode BM25 retrieval) keep behaving sanely.
@@ -393,12 +416,17 @@ def stamp_hybrid_rank(hits: list[dict]) -> None:
"""Record each hit's 0-based file rank in the fused order, before any rerank.
This is the order ``search_codebase`` serves; confidence reads it to tell
- when the reranked lead left it. Symbol pages share their file's rank.
+ when the reranked lead left it. Symbol pages share their file's rank. Files
+ are ranked among pages: a file with no page shares the rank of the page
+ below it, so it never pushes a page down.
"""
files: dict[str, int] = {}
for h in hits:
path = (h.get("target_path") or "").split("::", 1)[0]
- h["_hybrid_rank"] = files.setdefault(path, len(files))
+ if h.get("page_type") == PAGELESS_FILE:
+ h["_hybrid_rank"] = len(files)
+ else:
+ h["_hybrid_rank"] = files.setdefault(path, len(files))
async def _safe_fts_search(ctx: Any, question: str) -> list[Any]:
@@ -576,6 +604,47 @@ async def _safe_symbol_search(
]
+async def _safe_filename_search(ctx: Any, question: str) -> list[tuple[_SymbolLegResult, bool]]:
+ """Files whose file name the question spells, each with whether it spells all
+ of the name. [] on any failure, like the other legs."""
+ try:
+ pages = await asyncio.wait_for(
+ filename_backed_pages(ctx, question, max_files=_SYMBOL_LEG_MAX_PAGES), timeout=5.0
+ )
+ except TimeoutError:
+ _record_leg("filename", "timeout")
+ return []
+ except Exception:
+ _record_leg("filename", "error")
+ _log.debug("filename leg failed; page retrieval stands", exc_info=True)
+ return []
+ _record_leg("filename", "ok")
+ return [
+ (
+ _SymbolLegResult(p["page_id"], p["title"], p["summary"][:200], p["page_type"], []),
+ p["full_cover"],
+ )
+ for p in pages
+ ]
+
+
+def leg_ranks(results: list[Any]) -> list[tuple[int, Any]]:
+ """Each result of a leg with its rank among that leg's pages.
+
+ A file with no page takes the rank of the page below it, so it never costs
+ a page its place in the leg: the pages fuse exactly as they would without it.
+ Items may be results or ``(result, extra)`` pairs.
+ """
+ ranked: list[tuple[int, Any]] = []
+ pages = 0
+ for item in results:
+ result = item[0] if isinstance(item, tuple) else item
+ ranked.append((pages, item))
+ if result.page_type != PAGELESS_FILE:
+ pages += 1
+ return ranked
+
+
def _hit_dict_from_result(result: Any) -> dict:
"""Convert a retriever result object to the pipeline's dict shape."""
return {
@@ -624,7 +693,7 @@ def demote_noise_hits(hits: list[dict], question: str, *, is_why: bool) -> list[
def _is_noise(h: dict) -> bool:
pt = h.get("page_type")
return (pt == "decision_record" and not is_why) or (
- pt == "file_page" and not test_focused and is_test_path(h.get("target_path") or "")
+ pt in FILE_ROW_TYPES and not test_focused and is_test_path(h.get("target_path") or "")
)
real = [h for h in hits if not _is_noise(h)]
@@ -671,6 +740,10 @@ async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None)
pageless = 0
for h in hits:
meta = meta_by_id.get(h["page_id"])
+ if meta is None and h.get("page_type") == PAGELESS_FILE:
+ # An indexed file with no page: its path is in its id, and it has
+ # no summary to give, so it serves its matched code instead.
+ meta = {"target_path": pageless_path(h["page_id"]), "page_type": PAGELESS_FILE}
if meta is None:
# A retrieved id with no page behind it: a decision vector, or a
# vector left over from a page the stores have since disagreed
@@ -735,7 +808,10 @@ async def apply_pagerank_bias(hits: list[dict], ctx: Any) -> None:
if not pr_by_path:
return
- max_pr = max(pr_by_path.values(), default=0.0)
+ # Normalised over the pages, so a file with no page cannot change their bias.
+ paged = {h.get("target_path") for h in hits if h.get("page_type") != PAGELESS_FILE}
+ max_pr = max((pr for path, pr in pr_by_path.items() if path in paged), default=0.0)
+ max_pr = max_pr or max(pr_by_path.values(), default=0.0)
if max_pr <= 0:
return
@@ -743,7 +819,7 @@ async def apply_pagerank_bias(hits: list[dict], ctx: Any) -> None:
pr = pr_by_path.get(h.get("target_path"), 0.0)
# Normalised in [0, 1] then scaled to a multiplicative bias in
# [1.0, 1 + _PAGERANK_BIAS_MAX].
- bias = 1.0 + _PAGERANK_BIAS_MAX * (pr / max_pr)
+ bias = 1.0 + _PAGERANK_BIAS_MAX * min(pr / max_pr, 1.0)
h["_pagerank"] = pr
h["_pagerank_bias"] = round(bias, 3)
h["score"] = h.get("score", 0.0) * bias
@@ -835,7 +911,9 @@ async def expand_via_graph(hits: list[dict], ctx: Any, repo_id: str) -> list[dic
"""
if not hits:
return hits
- seed_paths = [h.get("target_path") for h in hits[:_GRAPH_EXPAND_TOP_N] if h.get("target_path")]
+ # Seeded from pages only, so a file with no page cannot change what pages add.
+ seeds = [h for h in hits if h.get("page_type") != PAGELESS_FILE][:_GRAPH_EXPAND_TOP_N]
+ seed_paths = [h.get("target_path") for h in seeds if h.get("target_path")]
if not seed_paths:
return hits
existing = {h.get("target_path") for h in hits}
@@ -904,7 +982,7 @@ async def expand_via_graph(hits: list[dict], ctx: Any, repo_id: str) -> list[dic
# the strongest parent each child connects to (taking the max parent
# score is conservative — favors well-connected neighbors).
strongest_parent = max(
- hits[:_GRAPH_EXPAND_TOP_N], key=lambda hit: hit.get("score", 0.0), default={}
+ seeds, 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")
diff --git a/packages/server/src/repowise/server/mcp_server/_entry_trace.py b/packages/server/src/repowise/server/mcp_server/_entry_trace.py
index aa27211ec..fcdc567c1 100644
--- a/packages/server/src/repowise/server/mcp_server/_entry_trace.py
+++ b/packages/server/src/repowise/server/mcp_server/_entry_trace.py
@@ -32,6 +32,7 @@ from repowise.core.persistence.models import GraphEdge, GraphNode, Page
from repowise.server.mcp_server._answer_pipeline import is_subsystem_query
from repowise.server.mcp_server._graph_files import node_to_file
from repowise.server.mcp_server._helpers import is_excluded
+from repowise.server.mcp_server._page_paths import FILE_ROW_TYPES
from repowise.server.mcp_server._query_terms import content_terms
from repowise.server.mcp_server.tool_search_symbols import _tokens
@@ -293,7 +294,7 @@ async def _place_files(
wanted: dict[str, float] = {}
for i, path in enumerate([entry_file, *inject]):
wanted.setdefault(path, top + _RANK_STEP * (len(inject) + 1 - i))
- by_path = {h.get("target_path"): h for h in hits if h.get("page_type") == "file_page"}
+ by_path = {h.get("target_path"): h for h in hits if h.get("page_type") in FILE_ROW_TYPES}
absent = [p for p in wanted if p not in by_path]
if absent:
res = await session.execute(
diff --git a/packages/server/src/repowise/server/mcp_server/_page_paths.py b/packages/server/src/repowise/server/mcp_server/_page_paths.py
index e041f36e2..6e249c1fc 100644
--- a/packages/server/src/repowise/server/mcp_server/_page_paths.py
+++ b/packages/server/src/repowise/server/mcp_server/_page_paths.py
@@ -20,6 +20,14 @@ from __future__ import annotations
# is the file, and there is no page behind its id to read.
PAGELESS_FILE = "file"
+# Rows that are one whole file, with or without a page behind them.
+FILE_ROW_TYPES = ("file_page", PAGELESS_FILE)
+
+
+def pageless_path(page_id: str) -> str:
+ """The file a pageless row's id (``file:<path>``) names."""
+ return page_id.partition(":")[2]
+
# Page types whose ``target_path`` is a real repository-relative file path.
#
# ``symbol_spotlight`` is included because its target_path is ``file.py::Sym``:
diff --git a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py
index afc798e24..a67832af3 100644
--- a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py
+++ b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py
@@ -8,6 +8,7 @@ import re
from collections import Counter
from collections.abc import Mapping
+from repowise.server.mcp_server._page_paths import PAGELESS_FILE
from repowise.server.mcp_server._query_terms import content_terms, split_humps
_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
@@ -152,6 +153,58 @@ def rerank_by_context_coverage(
return hits
+def rerank_pages_first(
+ hits: list[dict],
+ query: str,
+ *,
+ score_key: str,
+ floor: float,
+ absolute_stopwords: set[str] | None = None,
+) -> list[dict]:
+ """:func:`rerank_by_context_coverage` whose page order comes from the pages alone.
+
+ The weights are relative to the window, so rows for files without a page
+ would reorder the pages among themselves. Pages are reranked on their own;
+ each pageless row takes the place the whole window gives it among them, with
+ its score kept in the same ratio to the nearest page.
+ """
+ kwargs = {"score_key": score_key, "floor": floor, "absolute_stopwords": absolute_stopwords}
+ pageless = [hit for hit in hits if hit.get("page_type") == PAGELESS_FILE]
+ if not pageless:
+ return rerank_by_context_coverage(hits, query, **kwargs)
+ pages = [hit for hit in hits if hit.get("page_type") != PAGELESS_FILE]
+ copies = {id(copy): copy for copy in (dict(hit) for hit in pages)}
+ copy_of = dict(zip((id(hit) for hit in pages), copies.values(), strict=True))
+ window = rerank_by_context_coverage([*copies.values(), *pageless], query, **kwargs)
+ pages = rerank_by_context_coverage(pages, query, **kwargs)
+
+ above = 0 # pages the whole window ranks above the current row
+ slots: dict[int, list[dict]] = {}
+ for row in window:
+ if id(row) in copies:
+ above += 1
+ else:
+ slots.setdefault(above, []).append(row)
+ out: list[dict] = []
+ for i in range(len(pages) + 1):
+ for row in slots.get(i, ()):
+ # Same ratio to the nearest page as in the whole window, kept between
+ # that page and the one above so the pages keep their order.
+ anchor = pages[min(i, len(pages) - 1)] if pages else None
+ if anchor is not None:
+ base = copy_of[id(anchor)].get(score_key) or 0.0
+ score = anchor.get(score_key, 0.0) * (row.get(score_key, 0.0) / base if base else 1.0)
+ if i < len(pages):
+ score = max(score, anchor.get(score_key, 0.0))
+ if i > 0:
+ score = min(score, pages[i - 1].get(score_key, 0.0))
+ row[score_key] = score
+ out.append(row)
+ if i < len(pages):
+ out.append(pages[i])
+ return out
+
+
# 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
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/hydration.py b/packages/server/src/repowise/server/mcp_server/tool_answer/hydration.py
index ea24c3d4d..fad1fb133 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/hydration.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/hydration.py
@@ -14,7 +14,7 @@ from typing import Any
from sqlalchemy import select
from repowise.core.persistence.models import WikiSymbol
-from repowise.server.mcp_server._page_paths import hit_file_path
+from repowise.server.mcp_server._page_paths import FILE_ROW_TYPES, hit_file_path
from repowise.server.mcp_server._query_terms import content_terms, split_humps
from repowise.server.mcp_server._verify import verify_and_heal
from repowise.server.mcp_server.tool_answer.config import (
@@ -228,7 +228,7 @@ async def _hydrate_symbols_for_hits(
question_ids: set[str] | None = None,
question: str = "",
) -> None:
- """Mutate `hits` in place: attach `symbols` list to top-N file_page hits.
+ """Mutate `hits` in place: attach `symbols` list to top-N whole-file hits.
Symbols the question names by identifier move to the top of their file's
list and get a ``source_excerpt``, so synthesis sees the body it is asked
@@ -289,13 +289,13 @@ async def _hydrate_symbols_for_hits(
def _enrich_paths(hits: list[dict]) -> list[str]:
- """The top ``_ENRICH_TOP_N_HITS`` file_page paths, in retrieval-rank order."""
+ """The top ``_ENRICH_TOP_N_HITS`` whole-file paths, paged or not, in rank order."""
# `hits` is already sorted by descending score upstream.
enrich_paths: list[str] = []
for h in hits:
if len(enrich_paths) >= _ENRICH_TOP_N_HITS:
break
- if h.get("target_path") and h.get("page_type") == "file_page":
+ if h.get("target_path") and h.get("page_type") in FILE_ROW_TYPES:
enrich_paths.append(h["target_path"])
return enrich_paths
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 cfdeaed38..51d0da462 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
@@ -18,9 +18,9 @@ from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import Page
from repowise.core.persistence.search import strip_leading_headings
-from repowise.server.mcp_server._page_paths import hit_file_path
+from repowise.server.mcp_server._page_paths import PAGELESS_FILE, 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._retrieval_rank import rerank_pages_first
from repowise.server.mcp_server.tool_answer.config import (
_BACKEND_PATH_PREFIXES,
_BACKEND_QUESTION_TOKENS,
@@ -271,9 +271,10 @@ async def _attach_page_excerpts(hits: list[dict], ctx: Any = None) -> int:
Returns the number of top hits left without page content, so a hit
reaching synthesis with no body is visible rather than silent.
"""
- if not hits:
+ # A file with no page has no content to miss; its symbols carry its code.
+ top = [h for h in hits[:_PAGE_EXCERPT_HITS] if h.get("page_type") != PAGELESS_FILE]
+ if not top:
return 0
- top = hits[:_PAGE_EXCERPT_HITS]
page_ids = [h["page_id"] for h in top if h.get("page_id")]
if not page_ids:
_log.warning(
@@ -401,7 +402,7 @@ def _rerank_by_coverage(hits: list[dict], question: str) -> list[dict]:
replacement score. Counters BM25 ranking one strongly-matched constraint
above a hit that matches every constraint moderately.
"""
- return rerank_by_context_coverage(
+ return rerank_pages_first(
hits,
question,
score_key="score",
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 c97f65c7c..fa69adb8c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -22,12 +22,13 @@ from repowise.core.registry import ToolRecipe
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.core.test_paths import is_test_path, is_test_related_path
from repowise.server.mcp_server._answer_pipeline import (
+ _FILENAME_LEG_RRF_K,
_RRF_K,
_RRF_SCORE_SCALE,
- _SYMBOL_LEG_MAX_PAGES,
_SYMBOL_LEG_RRF_K,
+ _safe_filename_search,
_safe_symbol_search,
- _SymbolLegResult,
+ leg_ranks,
)
from repowise.server.mcp_server._budget import (
OmissionCollector,
@@ -50,13 +51,14 @@ from repowise.server.mcp_server._line_hits import attach_line_hits
from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._page_paths import (
+ FILE_ROW_TYPES,
PAGELESS_FILE,
add_row_paths,
file_candidates,
file_path_of,
hit_file_path,
+ pageless_path,
)
-from repowise.server.mcp_server._prose_symbols import filename_backed_pages
from repowise.server.mcp_server._query_shape import (
_DECISION_DOWNWEIGHT,
_MIN_RELEVANCE_SCORE,
@@ -80,7 +82,7 @@ from repowise.server.mcp_server._query_shape import (
from repowise.server.mcp_server._references import path_identity, symbol_identity
from repowise.server.mcp_server._retrieval_rank import (
boost_named_paths,
- rerank_by_context_coverage,
+ rerank_pages_first,
)
from repowise.server.mcp_server.tool_search_symbols import (
_MAX_CANDIDATES,
@@ -272,10 +274,6 @@ def _is_test_query(query: str) -> bool:
return bool(_TEST_QUERY_RE.search(query))
-# Rows that are one whole file, with or without a page behind them.
-_FILE_ROW_TYPES = ("file_page", PAGELESS_FILE)
-
-
def _is_test_page(item: dict) -> bool:
"""True when a hit is a whole-file row for a test file.
@@ -284,7 +282,7 @@ def _is_test_page(item: dict) -> bool:
rank. The ``kind`` filter counts both (see :func:`_classify_hit_kind`) —
asking for tests and asking to rank tests lower are different questions.
"""
- return item.get("page_type") in _FILE_ROW_TYPES and is_test_path(item.get("target_path") or "")
+ return item.get("page_type") in FILE_ROW_TYPES and is_test_path(item.get("target_path") or "")
def _downweight_test_pages(output: list[dict], query: str) -> None:
@@ -489,7 +487,7 @@ def _classify_hit_kind(target_path: str, page_type: str) -> str:
tp = (target_path or "").lower()
if page_type in ("module_page", "symbol_spotlight") or tp.endswith(".md"):
return "doc"
- if not tp or page_type not in _FILE_ROW_TYPES:
+ if not tp or page_type not in FILE_ROW_TYPES:
return "doc"
if any(tok in tp for tok in _CONFIG_PATH_TOKENS):
return "config"
@@ -702,26 +700,6 @@ async def _safe_vector(ctx, query: str, limit: int) -> list:
return []
-_FILENAME_LEG_RRF_K = _SYMBOL_LEG_RRF_K
-
-
-async def _safe_filename_search(ctx, query: str) -> list[tuple[_SymbolLegResult, bool]]:
- """Files whose file name the query spells, each with whether it spells all of
- the name. Bounded and failure-swallowing."""
- with contextlib.suppress(Exception):
- pages = await asyncio.wait_for(
- filename_backed_pages(ctx, query, max_files=_SYMBOL_LEG_MAX_PAGES), timeout=5.0
- )
- return [
- (
- _SymbolLegResult(p["page_id"], p["title"], p["summary"][:200], p["page_type"], []),
- p["full_cover"],
- )
- for p in pages
- ]
- return []
-
-
def _symbol_leg_target(fused: dict[str, dict], page_id: str) -> str:
"""The fused page a symbol-leg file page credits: the best page of its file.
@@ -751,7 +729,7 @@ def _fused_entry(r) -> dict:
}
if r.page_type == PAGELESS_FILE:
# No page row to load it from later.
- entry["target_path"] = r.page_id.partition(":")[2]
+ entry["target_path"] = pageless_path(r.page_id)
return entry
@@ -800,14 +778,14 @@ async def _fused_retrieve(ctx, query: str, fetch_limit: int, page_type: str | No
entry["_sources"].add("fts")
# Files whose symbol names the query's words spell, paged or not. Weighted
# below the page legs, as in get_answer; it has no raw score to floor.
- for rank, r in enumerate(sym_results):
+ for rank, r in leg_ranks(sym_results):
entry = fused.setdefault(_symbol_leg_target(fused, r.page_id), _fused_entry(r))
entry["_rrf"] += 1.0 / (rank + _SYMBOL_LEG_RRF_K)
entry["_sources"].add("symbol")
# Files whose file name the query's words spell, weighted as a name match.
# It adds files the other legs missed and never reorders a page they found.
# A name of three or more words the query spells in full weighs like a page hit.
- for rank, (r, full) in enumerate(name_results):
+ for rank, (r, full) in leg_ranks(name_results):
target = _symbol_leg_target(fused, r.page_id)
if target in fused and r.page_type != PAGELESS_FILE:
continue
@@ -826,28 +804,6 @@ async def _fused_retrieve(ctx, query: str, fetch_limit: int, page_type: str | No
return output
-def _rerank_pages_first(output: list[dict], query: str) -> list[dict]:
- """Coverage rerank whose window weights come from the pages alone.
-
- The weights are relative to the window, so rows for files without a page
- would reorder the pages among themselves. They are scored against a copy
- of the pages instead, and only take their own place among them.
- """
- pages = [item for item in output if item.get("page_type") != PAGELESS_FILE]
- pageless = [item for item in output if item.get("page_type") == PAGELESS_FILE]
- if pageless:
- rerank_by_context_coverage(
- [dict(item) for item in pages] + pageless,
- query,
- score_key="relevance_score",
- floor=0.5,
- )
- pages = rerank_by_context_coverage(pages, query, score_key="relevance_score", floor=0.5)
- if not pageless:
- return pages
- return sorted(pages + pageless, key=lambda item: item.get("relevance_score", 0.0), reverse=True)
-
-
async def _search_single_repo(
ctx, query: str, limit: int, page_type: str | None, kind: str | None = None
) -> list[dict]:
@@ -1385,7 +1341,7 @@ 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_pages_first(output, query)
+ output = rerank_pages_first(output, query, 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(
diff --git a/tests/unit/server/mcp/test_answer_pageless_files.py b/tests/unit/server/mcp/test_answer_pageless_files.py
new file mode 100644
index 000000000..05ca42eec
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_pageless_files.py
@@ -0,0 +1,224 @@
+"""get_answer retrieves indexed files that have no wiki page.
+
+The only file that answers each question below has no page. It must reach the
+answer's evidence through the symbol or filename leg, may lead it, and is served
+with its path and matched code but no page prose. Fixtures are shared with the
+search-side tests: TypeScript, Python and Go files plus distractors.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.mcp_server import _answer_pipeline
+from tests.unit.server.mcp.test_filename_leg import _PAGELESS, _QUERIES, _seed_pageless
+
+_TS_TARGET = "src/config/exec-command-highlighting.ts"
+_PAGELESS_PATHS = {path for path, _, _ in _PAGELESS}
+
+
+async def pageless_mcp(setup_mcp, session, tmp_path, monkeypatch):
+ await _seed_pageless(session, setup_mcp)
+ # Live source behind every seeded symbol (line 12), so hydration has real
+ # code to serve for a file with no page.
+ for path, name, _language in _PAGELESS:
+ file = tmp_path / path
+ file.parent.mkdir(parents=True, exist_ok=True)
+ lines = [f"// line {i}" for i in range(1, 12)]
+ lines += [f"function {name}() {{", " return 'MATCHED_BODY';", "}"]
+ file.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ monkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "1")
+ return setup_mcp
+
+
+def _keyless(monkeypatch) -> None:
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+
+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: None)
+
+
+def _ranked(result: dict) -> list[str]:
+ """The files an answer ranks, whichever projection its confidence chose."""
+ if result.get("candidate_files"):
+ return result["candidate_files"]
+ return [r["path"] for r in result.get("retrieval", [])] or result.get("fallback_targets", [])
+
+
+async def _ctx():
+ from repowise.server.mcp_server._helpers import _resolve_repo_context
+
+ return await _resolve_repo_context(None)
+
+
+async def test_pipeline_keeps_pageless_hits_with_their_path(pageless_mcp):
+ ctx = await _ctx()
+ hits = await _answer_pipeline.hybrid_retrieve("exec command highlighting", ctx)
+ hits = await _answer_pipeline.hydrate_hits(hits, ctx)
+ row = next(h for h in hits if h["target_path"] == _TS_TARGET)
+ assert row["page_type"] == "file"
+ assert row["summary"] == ""
+ assert {"filename", "symbol"} <= row["_sources"]
+
+
+async def test_scope_drops_pageless_hits_outside_it(pageless_mcp):
+ ctx = await _ctx()
+ hits = await _answer_pipeline.hybrid_retrieve("exec command highlighting", ctx)
+ scoped = await _answer_pipeline.hydrate_hits(hits, ctx, scope="app/")
+ assert _TS_TARGET not in [h["target_path"] for h in scoped]
+
+
[email protected](("question", "path"), _QUERIES)
+async def test_keyless_answer_leads_with_the_file(pageless_mcp, monkeypatch, question, path):
+ from repowise.server.mcp_server import get_answer
+
+ _keyless(monkeypatch)
+ result = await get_answer(question)
+ lead = result["best_guesses"][0]
+ assert lead["file"] == path
+ assert result["candidate_files"][0] == path
+ # Its evidence is the matched code, never invented page prose.
+ assert lead["functions"][0]["line"] == 12
+
+
+async def test_keyed_synthesis_reads_the_pageless_file(pageless_mcp, monkeypatch):
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ class _Provider:
+ provider_name = "mock"
+ model_name = "mock-1"
+
+ prompts: list[str] = []
+
+ async def _capture(provider, system_prompt, user_prompt, **kwargs):
+ prompts.append(user_prompt)
+ return f"It is resolved in {_TS_TARGET}.", None
+
+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: _Provider())
+ monkeypatch.setattr(answer_mod, "synthesize", _capture)
+ result = await get_answer("where is exec command highlighting resolved")
+ assert _TS_TARGET in prompts[0]
+ assert "MATCHED_BODY" in prompts[0]
+ assert _TS_TARGET in result["citations"]
+
+
+async def test_a_pageless_test_file_ranks_below_its_source(pageless_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_answer
+
+ _keyless(monkeypatch)
+ files = (await get_answer("exec command highlighting"))["candidate_files"]
+ test_file = "src/config/exec-command-highlighting.test.ts"
+ assert files.index(_TS_TARGET) < files.index(test_file)
+
+
+def _pages_only(monkeypatch) -> None:
+ """Restrict both legs to paged rows: retrieval as it was before pageless files."""
+ symbol_search = _answer_pipeline._safe_symbol_search
+ name_search = _answer_pipeline._safe_filename_search
+
+ async def symbols_paged_only(ctx, q, *, pageless=False):
+ return await symbol_search(ctx, q)
+
+ async def names_paged_only(ctx, q):
+ return [(r, full) for r, full in await name_search(ctx, q) if r.page_type != "file"]
+
+ monkeypatch.setattr(_answer_pipeline, "_safe_symbol_search", symbols_paged_only)
+ monkeypatch.setattr(_answer_pipeline, "_safe_filename_search", names_paged_only)
+
+
+async def _paged_pool(question: str, repo_id: str) -> list[tuple]:
+ from repowise.server.mcp_server.tool_answer.answer import _run_retrieval_pipeline
+
+ retrieved = await _run_retrieval_pipeline(
+ question, await _ctx(), scope=None, exclude_spec=None, repo_id=repo_id
+ )
+ return [
+ (h["target_path"], h.get("_hybrid_rank"), round(h["score"], 6))
+ for h in retrieved.resolved_pool
+ if h.get("page_type") != "file"
+ ]
+
+
+# Each spells a pageless file name and reaches several pages.
+_MIXED_QUESTIONS = [
+ "auth service middleware exec command highlighting",
+ "database models and the retry backoff policy for auth service login",
+]
+
+
[email protected]("question", _MIXED_QUESTIONS)
+async def test_pageless_files_leave_the_pages_alone(pageless_mcp, monkeypatch, question):
+ from repowise.server.mcp_server import get_answer
+
+ _keyless(monkeypatch)
+ with_rows = await _paged_pool(question, pageless_mcp)
+ with_answer = await get_answer(question)
+ assert any(p in _PAGELESS_PATHS for p in _ranked(with_answer))
+
+ _pages_only(monkeypatch)
+ without = await _paged_pool(question, pageless_mcp)
+ without_answer = await get_answer(question)
+
+ # Same pages, same order, same hybrid ranks and scores.
+ assert len(with_rows) > 2
+ assert with_rows == without
+ assert with_answer["confidence"] == without_answer["confidence"]
+ paged = [p for p in _ranked(with_answer) if p not in _PAGELESS_PATHS]
+ assert paged == _ranked(without_answer)[: len(paged)]
+
+
[email protected]("failure", [TimeoutError, RuntimeError])
+async def test_a_failed_filename_leg_is_reported(pageless_mcp, monkeypatch, failure):
+ from repowise.server.mcp_server import get_answer
+
+ async def broken(*_args, **_kwargs):
+ raise failure
+
+ _keyless(monkeypatch)
+ monkeypatch.setattr(_answer_pipeline, "filename_backed_pages", broken)
+ result = await get_answer("exec command highlighting")
+ assert "filename" in result["_meta"]["retrieval_degraded"]
+
+
+def test_rerank_keeps_page_order_and_places_pageless_rows_by_the_whole_window():
+ from repowise.server.mcp_server._retrieval_rank import (
+ rerank_by_context_coverage,
+ rerank_pages_first,
+ )
+
+ def rows():
+ pages = [
+ {"page_type": "file_page", "target_path": f"pkg/{name}.py", "score": s}
+ for name, s in (("retry_queue", 3.0), ("backoff_policy", 2.9), ("misc_util", 2.8))
+ ]
+ pageless = {
+ "page_type": "file",
+ "target_path": "pkg/retry_backoff_policy.go",
+ "score": 2.7,
+ }
+ return pages, pageless
+
+ def paths(ranked):
+ return [h["target_path"] for h in ranked]
+
+ question = "retry backoff policy"
+ kwargs = {"score_key": "score", "floor": 0.5}
+ pages, _ = rows()
+ alone = paths(rerank_by_context_coverage(pages, question, **kwargs))
+ pages, pageless = rows()
+ whole = paths(rerank_by_context_coverage([*pages, pageless], question, **kwargs))
+ pages, pageless = rows()
+ mixed = rerank_pages_first([*pages, pageless], question, **kwargs)
+ order = paths(mixed)
+ assert [p for p in order if p != pageless["target_path"]] == alone
+ # The pageless row spells every word, so the whole window ranks it first.
+ assert whole[0] == order[0] == pageless["target_path"]
+ assert [h["score"] for h in mixed] == sorted((h["score"] for h in mixed), reverse=True)