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
fix(answer): lead the keyless answer with the top retrieval file (#3184)
Raghav Chamadiya84403805a62f
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex 566eaccf7..02970fb33 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -389,6 +389,18 @@ async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:return merged+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.+ """+ 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))++async def _safe_fts_search(ctx: Any, question: str) -> list[Any]:"""FTS search wrapped in timeout + suppression. Returns [] on any failure."""if ctx.fts is None:diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex 11151cd79..594bde2bb 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -94,6 +94,9 @@ from repowise.server.mcp_server._answer_pipeline import hydrate_hits as _hydratefrom repowise.server.mcp_server._answer_pipeline import (retrieval_legs as _retrieval_legs,)+from repowise.server.mcp_server._answer_pipeline import (+ stamp_hybrid_rank as _stamp_hybrid_rank,+)from repowise.server.mcp_server._entry_trace import (expand_via_entry_trace as _expand_via_entry_trace,)@@ -233,6 +236,7 @@ async def _run_retrieval_pipeline(# Drop excluded files right after hydration (which attaches target_path) so# they never enter ranking, citations, or fallback_targets.hits = filter_dicts_by_key(hits, "target_path", exclude_spec)+ _stamp_hybrid_rank(hits)question_ids = _extract_question_identifiers(question)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.pyindex f6be5aacf..a0cc3fa72 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@@ -21,6 +21,7 @@ from repowise.server.mcp_server._answer_context import (from repowise.server.mcp_server._answer_context import (is_why_question as _is_why_question,)+from repowise.server.mcp_server._meta import _normalize_target_pathfrom repowise.server.mcp_server.tool_answer.config import (_AGREEMENT_RANK_GAP,_AGREEMENT_TOP_RANK_MAX,@@ -34,6 +35,7 @@ from repowise.server.mcp_server.tool_answer.config import (_HEDGE_MARKERS,_HIGH_CONFIDENCE_SCORE_FLOOR,_INLINE_BODY_MAX_LINES,+ _LEAD_HYBRID_TOP_K,_SYMBOL_AGREEMENT_TOP_RANK_MAX,_flag_on,_opt_in,@@ -494,7 +496,40 @@ def _retrieval_quality(hits: list[dict], agreement_dominant: bool) -> str:return "partial" if dominant_grade else "weak"-def _degraded_confidence(reason: str, retrieval_quality: str) -> str:+def file_hybrid_rank(hits: list[dict], path: str | None) -> int | None:+ """The best hybrid rank any hit of *path*'s file carries, or None if none does.++ Hits added after stamping (graph expansion, anchoring) carry no rank and can+ precede the ranked hit of the same file, so the first match is not enough.+ """+ target = _normalize_target_path(path or "")+ ranks = [+ h["_hybrid_rank"]+ for h in hits+ if "_hybrid_rank" in h and _normalize_target_path(h.get("target_path") or "") == target+ ]+ return min(ranks, default=None)+++def lead_leaves_retrieval(hits: list[dict], lead: str | None) -> bool:+ """True when the file a keyless answer names first is not where retrieval points.++ A lead outside the top :data:`_LEAD_HYBRID_TOP_K` files of the unreranked+ hybrid order, or never in it, was lifted by a rerank or an injected hit that+ hybrid retrieval does not back.+ """+ if not hits or not lead:+ return False+ # Unstamped hits carry no hybrid order to disagree with.+ if not any("_hybrid_rank" in h for h in hits):+ return False+ rank = file_hybrid_rank(hits, lead)+ return rank is None or rank >= _LEAD_HYBRID_TOP_K+++def _degraded_confidence(+ reason: str, retrieval_quality: str, *, lead_outside_top: bool = False+) -> str:"""Grade a synthesis-less payload on what a caller can act on, not on prose.The field tells an agent whether it still has work to do, so it is graded@@ -507,8 +542,12 @@ def _degraded_confidence(reason: str, retrieval_quality: str) -> str:``synthesis-failed`` stays "low": a provider is configured, so a retry canstill produce a real answer. "no-llm-provider" is the end of the line, sothere the evidence is all there is to grade.++ A strong retrieval still grades "low" when the answer leads with a file it+ does not back (:func:`lead_leaves_retrieval`): "medium" tells the caller to+ start from that lead."""- if reason != "no-llm-provider":+ if reason != "no-llm-provider" or lead_outside_top:return "low"return "low" if retrieval_quality == "weak" else "medium"diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.pyindex 1b437adc4..f3a481bf8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py@@ -125,6 +125,12 @@ _SYMBOL_AGREEMENT_TOP_RANK_MAX = 0# The runner-up must trail by at least this many ranks in at least one source._AGREEMENT_RANK_GAP = 1+# A keyless answer whose lead file sits below this many files of the unreranked+# hybrid retrieval grades "low". On 225 keyless questions over 11 repos, leads+# in the top 4 were right 38-60% of the time per rank, leads below it 17%, under+# the 27% the "low" tier already scored.+_LEAD_HYBRID_TOP_K = 4+# Phrases that mean the LLM declined to answer despite dominant retrieval.# A match downgrades confidence to "low" and drops the retrieval payload, since# a consumer told to read the source gains nothing from it in the cache.diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.pyindex f116c720c..95d89c17e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py@@ -19,6 +19,8 @@ from repowise.server.mcp_server.tool_answer.bodies import (from repowise.server.mcp_server.tool_answer.confidence import (_degraded_confidence,_retrieval_quality,+ file_hybrid_rank,+ lead_leaves_retrieval,)from repowise.server.mcp_server.tool_answer.evidence import (_drop_already_surfaced,@@ -69,6 +71,26 @@ def _degraded_summary(reason: str, symbol_bodies: list[dict], served: int) -> st)+def _rationale_in_rank_order(rows: list[dict], hits: list[dict], top: str | None) -> list[dict]:+ """Rationale rows from the top-ranked file first, the rest in hybrid-rank order.++ The miner orders rows by comment score, which would let a comment-heavy hub+ lead ``answer`` over the file retrieval put first. Ties keep that order;+ a hit with no hybrid rank sorts after the ranked ones, in hit order.+ """+ top_path = _normalize_target_path(top or "")+ paths = [_normalize_target_path(h.get("target_path") or "") for h in hits]++ def _key(row: dict) -> tuple[bool, int]:+ path = _normalize_target_path(row.get("path") or "")+ rank = file_hybrid_rank(hits, path)+ if rank is None:+ rank = len(hits) + (paths.index(path) if path in paths else len(hits))+ return path != top_path, rank++ return sorted(rows, key=_key)++async def _degraded_payload(*,reason: str,@@ -88,10 +110,9 @@ async def _degraded_payload(``degraded`` is mirrored into ``_meta``, where consumers read healthsignals. ``confidence`` is graded by :func:`_degraded_confidence` from- ``retrieval_quality``, so the two can never disagree.+ ``retrieval_quality`` and whether retrieval backs the file ``answer`` leads with."""retrieval_quality = _retrieval_quality(hits, agreement_dominant)- confidence = _degraded_confidence(reason, retrieval_quality)repo_root = _repo_root(ctx)symbol_bodies, _served_named_body = _build_symbol_bodies(_gather_body_candidates(hits, "", anchor_names=question_ids or set()),@@ -104,8 +125,12 @@ async def _degraded_payload(best_guesses = _build_best_guesses(hits)# No quotes to check against here — there is no prose to quote from.- code_rationale = _drop_already_surfaced(- await _gather_code_rationale(ctx, hits, fallback_targets, question), symbol_bodies+ code_rationale = _rationale_in_rank_order(+ _drop_already_surfaced(+ await _gather_code_rationale(ctx, hits, fallback_targets, question), symbol_bodies+ ),+ hits,+ best_guesses[0]["file"] if best_guesses else None,)seen = {_normalize_target_path(path) for path in citations}rationale_paths = [@@ -114,13 +139,23 @@ async def _degraded_payload(if (path := row.get("path")) and _normalize_target_path(path) not in seen]if rationale_paths:- # Rationale rows rank by comment score across files, so a comment-heavy- # hub would outrank the file retrieval put first; cite the ranking ahead.+ # Cite the ranked guesses ahead of the rationale files they outrank.for path in (*(g["file"] for g in best_guesses), *rationale_paths):if (key := _normalize_target_path(path)) not in seen:seen.add(key)citations.append(path)+ # The file ``answer`` will name first, in the projection's order.+ if symbol_bodies:+ lead = symbol_bodies[0]["path"]+ elif best_guesses:+ lead = best_guesses[0]["file"]+ else:+ lead = code_rationale[0].get("path") if code_rationale else None+ confidence = _degraded_confidence(+ reason, retrieval_quality, lead_outside_top=lead_leaves_retrieval(hits, lead)+ )+payload: dict = {"answer": summary,"citations": citations,diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.pyindex 39784dba8..2621a8877 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py@@ -234,6 +234,25 @@ def _deduplicate(payload: dict[str, Any]) -> None:payload["candidates"] = candidates+def _same_file(a: str | None, b: str | None) -> bool:+ return bool(a and b) and a.replace("\\", "/") == b.replace("\\", "/")+++def _lead_rationale(payload: dict[str, Any]) -> dict[str, Any] | None:+ """The rationale row ``answer`` may lead with: one from the top-ranked file.++ A row from any other file would name a file retrieval did not put first.+ """+ rows = [row for row in payload.get("code_rationale") or [] if isinstance(row, dict)]+ if not rows:+ return None+ guess = _first_guess(payload)+ if guess is None:+ return rows[0]+ top = _nav_path(guess)+ return next((row for row in rows if _same_file(_nav_path(row), top)), None)++def _rewrite_degraded_answer(payload: dict[str, Any]) -> None:"""Describe only evidence that survived the external projection."""reason = payload.get("degraded")@@ -244,8 +263,7 @@ def _rewrite_degraded_answer(payload: dict[str, Any]) -> None:f"Synthesis is unavailable ({reason}), but symbol_bodies contains live source ""for the named code. Use that evidence directly.")- elif payload.get("code_rationale"):- row = payload["code_rationale"][0]+ elif (row := _lead_rationale(payload)) is not None:conclusion = _text(row, "rationale", "comment", "quote", "source", "text")path = _path(row) or "the top source match"payload["answer"] = (diff --git a/tests/unit/server/mcp/test_answer_degraded_evidence.py b/tests/unit/server/mcp/test_answer_degraded_evidence.pyindex 106f0228d..f15725b56 100644--- a/tests/unit/server/mcp/test_answer_degraded_evidence.py+++ b/tests/unit/server/mcp/test_answer_degraded_evidence.py@@ -26,7 +26,10 @@ from repowise.server.mcp_server.tool_answer.answer import (_degraded_payload,_drop_duplicated_guess_excerpts,)-from repowise.server.mcp_server.tool_answer.confidence import _degraded_confidence+from repowise.server.mcp_server.tool_answer.confidence import (+ _degraded_confidence,+ lead_leaves_retrieval,+)from repowise.server.mcp_server.tool_answer.projection import project_answer_payload@@ -551,7 +554,7 @@ async def test_degraded_cites_the_retrieval_top_file_before_a_rationale_hub("""A comment-heavy hub wins the rationale sort by volume, not by rank.The rationale rows come back hub first; citations must still lead with the- file retrieval ranked first, and keep the rationale paths after it.+ file retrieval ranked first, and the rows follow the retrieval ranking."""_rationale_rows(monkeypatch, "cmd/completions.go", "cmd/command.go")payload = await _degraded(@@ -563,7 +566,10 @@ async def test_degraded_cites_the_retrieval_top_file_before_a_rationale_hub("cmd/command.go","cmd/completions.go",]- assert payload["code_rationale"][0]["path"] == "cmd/completions.go"+ assert [r["path"] for r in payload["code_rationale"]] == [+ "cmd/command.go",+ "cmd/completions.go",+ ]def _rationale_rows(monkeypatch, *paths: str) -> None:@@ -801,3 +807,188 @@ def test_the_hint_is_the_same_whatever_the_payload_graded():assert len(hints) == 1assert "Synthesis is what is missing here" in hints.pop()+++# --- the keyless answer leads with the top retrieval file -------------------+#+# "medium" tells the caller to start from the file `answer` names first. That+# file is the top-ranked one, a rationale comment never promotes another file+# over it, and a top file that hybrid retrieval does not back grades "low".+++def _ranked(*paths: str, ranks: tuple[int | None, ...] | None = None) -> list[dict]:+ """Strong, dominant hits in this order, each stamped with its hybrid rank."""+ hits = [+ {"target_path": p, "title": p, "summary": "s", "score": 6.0 if i == 0 else 2.0}+ for i, p in enumerate(paths)+ ]+ for h, rank in zip(hits, ranks if ranks is not None else range(len(hits)), strict=True):+ if rank is not None:+ h["_hybrid_rank"] = rank+ return hits+++async def _keyless(tmp_path, hits, question_ids=frozenset()):+ return await _degraded(+ SimpleNamespace(path=str(tmp_path), session_factory=None), hits, set(question_ids)+ )+++def _answer(payload: dict) -> str:+ return project_answer_payload(payload, question="which file")["answer"]+++async def test_the_top_file_rationale_leads_over_a_higher_scoring_hub(tmp_path, monkeypatch):+ """The miner puts the hub's comment first; the answer still names the top file."""+ _rationale_rows(monkeypatch, "src/config/types.ts", "src/agents/poll-backoff.ts")+ payload = await _keyless(tmp_path, _ranked("src/agents/poll-backoff.ts", "src/config/types.ts"))++ assert [r["path"] for r in payload["code_rationale"]] == [+ "src/agents/poll-backoff.ts",+ "src/config/types.ts",+ ]+ assert "Source rationale in src/agents/poll-backoff.ts" in _answer(payload)+ assert payload["confidence"] == "medium"+++async def test_without_a_top_file_rationale_the_answer_names_the_ranking(tmp_path, monkeypatch):+ _rationale_rows(monkeypatch, "cmd/completions.go")+ payload = await _keyless(tmp_path, _ranked("cmd/command.go", "cmd/completions.go"))++ answer = _answer(payload)+ assert "Local retrieval points first to cmd/command.go" in answer+ assert "completions.go" not in answer+ assert payload["confidence"] == "medium"+++async def test_other_rationale_rows_follow_in_hybrid_rank_order(tmp_path, monkeypatch):+ """Not comment-score order; a hit hybrid retrieval never ranked goes last."""+ _rationale_rows(monkeypatch, "pkg/d.py", "pkg/b.py", "pkg/c.py", "pkg/a.py")+ hits = _ranked("pkg/a.py", "pkg/b.py", "pkg/c.py", "pkg/d.py", ranks=(0, 2, 1, None))+ payload = await _keyless(tmp_path, hits)++ assert [r["path"] for r in payload["code_rationale"]] == [+ "pkg/a.py",+ "pkg/c.py",+ "pkg/b.py",+ "pkg/d.py",+ ]+++async def test_unranked_hits_order_rationale_by_hit_position(tmp_path, monkeypatch):+ _rationale_rows(monkeypatch, "src/Z.java", "src/Y.java")+ payload = await _keyless(tmp_path, _ranked("src/X.java", "src/Y.java", "src/Z.java", ranks=(None, None, None)))++ assert [r["path"] for r in payload["code_rationale"]] == ["src/Y.java", "src/Z.java"]+++async def test_a_ranked_lead_inside_the_hybrid_top_stays_medium(tmp_path, monkeypatch):+ _rationale_rows(monkeypatch)+ hits = _ranked("src/main/java/App.java", "src/main/java/Util.java", ranks=(3, 0))+ payload = await _keyless(tmp_path, hits)++ assert payload["confidence"] == "medium"+++async def test_a_lead_reranked_up_from_below_the_hybrid_top_grades_low(tmp_path, monkeypatch):+ _rationale_rows(monkeypatch)+ hits = _ranked("src/main/java/App.java", "src/main/java/Util.java", ranks=(4, 0))+ payload = await _keyless(tmp_path, hits)++ assert payload["confidence"] == "low"+++async def test_an_injected_lead_hybrid_retrieval_never_ranked_grades_low(tmp_path, monkeypatch):+ """Graph expansion and anchoring add hits with no hybrid rank at all."""+ _rationale_rows(monkeypatch)+ hits = _ranked("lib/faraday/adapter.rb", "lib/faraday/request.rb", ranks=(None, 0))+ payload = await _keyless(tmp_path, hits)++ assert payload["confidence"] == "low"+++async def test_a_body_lead_reads_the_same_hybrid_rank(tmp_path):+ """A served body leads `answer`, so its file's rank is the one checked."""+ inside = _hits(end_line=6)+ inside[0]["_hybrid_rank"] = 1+ outside = _hits(end_line=6)+ outside[0]["_hybrid_rank"] = 7++ ctx = _tree(tmp_path)+ assert (await _degraded(ctx, inside, {"Flask"}))["confidence"] == "medium"+ assert (await _degraded(ctx, outside, {"Flask"}))["confidence"] == "low"+++ ("lead", "expected"),+ [+ ("src/a.py", False),+ ("src/a.py::run", False),+ (r"src\b.py", False),+ ("src/c.py", True),+ ("src/missing.py", True),+ ],+)+def test_lead_leaves_retrieval_table(lead, expected):+ hits = _ranked("src/a.py::run", "src/b.py", "src/c.py", ranks=(0, 2, 5))++ assert lead_leaves_retrieval(hits, lead) is expected+++def test_unstamped_hits_have_no_hybrid_order_to_leave():+ hits = _ranked("src/a.py", "src/b.py", ranks=(None, None))++ assert lead_leaves_retrieval(hits, "src/b.py") is False+++def test_the_keyed_grade_does_not_read_the_hybrid_rank():+ """Only the keyless grade changed; synthesis is graded on its own text."""+ from repowise.server.mcp_server.tool_answer.confidence import _grade_answer++ def grade(hits):+ return _grade_answer(+ question="how does polling back off",+ question_ids=set(),+ answer_text="It backs off exponentially.",+ hits=hits,+ citations=["src/poll.ts"],+ symbol_bodies=[],+ served_named_body=False,+ dominance="gap",+ ).confidence++ far = _ranked("src/poll.ts", "src/other.ts", ranks=(9, 0))+ assert grade(far) == grade(_ranked("src/poll.ts", "src/other.ts"))+ assert _degraded_confidence("synthesis-failed", "high") == "low"+++def test_hybrid_rank_counts_files_and_symbol_pages_share_theirs():+ from repowise.server.mcp_server._answer_pipeline import stamp_hybrid_rank++ hits = [{"target_path": p} for p in ("a.go", "a.go::Run", "b.go", "a.go::Stop", "c.go")]+ stamp_hybrid_rank(hits)++ assert [h["_hybrid_rank"] for h in hits] == [0, 0, 1, 0, 2]+++async def test_an_unranked_duplicate_does_not_hide_its_files_rank(tmp_path, monkeypatch):+ """An injected symbol page of a ranked file can precede that file's own hit."""+ _rationale_rows(monkeypatch, "src/hub.ts", "src/other.ts", "src/poll.ts")+ hits = [+ {"target_path": "src/poll.ts::backoff", "title": "t", "summary": "s", "score": 6.0},+ {"target_path": "src/hub.ts", "title": "t", "summary": "s", "score": 2.0},+ {"target_path": "src/other.ts::Run", "title": "t", "summary": "s", "score": 1.5},+ {"target_path": "src/other.ts", "title": "t", "summary": "s", "score": 1.0},+ {"target_path": "src/poll.ts", "title": "t", "summary": "s", "score": 1.0},+ ]+ for h, rank in zip(hits, (None, 5, None, 1, 0), strict=True):+ if rank is not None:+ h["_hybrid_rank"] = rank+ payload = await _keyless(tmp_path, hits)++ assert payload["confidence"] == "medium"+ assert [r["path"] for r in payload["code_rationale"]] == [+ "src/poll.ts",+ "src/other.ts",+ "src/hub.ts",+ ]