Skip to content

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

fix(answer): keep the retrieval ranking first in keyless citations (#3102)

Raghav Chamadiya7106426057b8
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.py
index 9a9a84081..f116c720c 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
@@ -9,6 +9,7 @@ from __future__ import annotations
import time
+from repowise.server.mcp_server._meta import _normalize_target_path
from repowise.server.mcp_server._meta import answer_hint as _answer_hint
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server.tool_answer.bodies import (
@@ -106,11 +107,19 @@ async def _degraded_payload(
code_rationale = _drop_already_surfaced(
await _gather_code_rationale(ctx, hits, fallback_targets, question), symbol_bodies
)
- citations.extend(
+ seen = {_normalize_target_path(path) for path in citations}
+ rationale_paths = [
path
for row in code_rationale
- if (path := row.get("path")) and path not in citations
- )
+ 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.
+ 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)
payload: dict = {
"answer": summary,
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.py
index c34e58f46..2b9cc8e4e 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
@@ -289,12 +289,20 @@ def _shape_candidate_files(payload: dict[str, Any], *, expanded: bool) -> None:
if not isinstance(rows, list):
return
cited = {path for path in map(_nav_path, payload.get("citations") or []) if path}
+ spent = cited
+ if payload.get("degraded"):
+ # Keyless citations also name the ranked guesses; they keep their
+ # shortlist slots so citing them reorders the files served, not adds.
+ evidence = set(map(_nav_path, payload.get("symbol_bodies") or []))
+ evidence.update(map(_nav_path, payload.get("code_rationale") or []))
+ spent = cited - (set(map(_nav_path, payload.get("best_guesses") or [])) - evidence)
paths = [
path for path in dict.fromkeys(row for row in rows if isinstance(row, str))
- if path not in cited
+ if path not in spent
]
high = not expanded and _shape_confidence(payload) == "high"
paths = paths[: _CANDIDATE_FILES_HIGH if high else _CANDIDATE_FILES_MAX]
+ paths = [path for path in paths if path not in cited]
if paths:
payload["candidate_files"] = paths
diff --git a/tests/unit/server/mcp/test_answer_degraded_evidence.py b/tests/unit/server/mcp/test_answer_degraded_evidence.py
index cee3c0337..d19b703d9 100644
--- a/tests/unit/server/mcp/test_answer_degraded_evidence.py
+++ b/tests/unit/server/mcp/test_answer_degraded_evidence.py
@@ -545,6 +545,113 @@ async def test_degraded_mines_rationale_comments_from_the_candidates(tmp_path):
assert "code_rationale" in payload["note"]
+async def test_degraded_cites_the_retrieval_top_file_before_a_rationale_hub(
+ tmp_path, monkeypatch
+):
+ """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.
+ """
+ _rationale_rows(monkeypatch, "cmd/completions.go", "cmd/command.go")
+ payload = await _degraded(
+ SimpleNamespace(path=str(tmp_path), session_factory=None), _go_hits(), set()
+ )
+
+ assert payload["citations"] == [
+ "cmd/powershell_completions.go",
+ "cmd/command.go",
+ "cmd/completions.go",
+ ]
+ assert payload["code_rationale"][0]["path"] == "cmd/completions.go"
+
+
+def _rationale_rows(monkeypatch, *paths: str) -> None:
+ """Stub the rationale miner to return one row per path, in the given order."""
+ import repowise.server.mcp_server.tool_answer.degraded as degraded_mod
+
+ async def _rows(ctx, hits, fallback_targets, question):
+ return [
+ {"path": p, "lines": [100 + i, 101 + i], "comment": "c", "matched_terms": []}
+ for i, p in enumerate(paths)
+ ]
+
+ monkeypatch.setattr(degraded_mod, "_gather_code_rationale", _rows)
+
+
+def _go_hits() -> list[dict]:
+ return [
+ {"target_path": "cmd/powershell_completions.go", "title": "ps", "summary": "s", "score": 4.0},
+ {"target_path": "cmd/command.go", "title": "cmd", "summary": "s", "score": 2.0},
+ ]
+
+
+async def test_degraded_dedups_citations_across_path_forms(tmp_path, monkeypatch):
+ """A backslash rationale path names the same file as the slash guess."""
+ _rationale_rows(monkeypatch, "cmd\\command.go", "cmd\\completions.go")
+ payload = await _degraded(
+ SimpleNamespace(path=str(tmp_path), session_factory=None), _go_hits(), set()
+ )
+
+ assert payload["citations"] == [
+ "cmd/powershell_completions.go",
+ "cmd/command.go",
+ "cmd\\completions.go",
+ ]
+
+
+async def test_degraded_citations_unchanged_when_rationale_adds_nothing(tmp_path, monkeypatch):
+ """Rationale only on the body's own file: no ranked files join the citations."""
+ _rationale_rows(monkeypatch, "src/flask/app.py")
+ hits = [
+ *_hits(end_line=6),
+ {"target_path": "src/flask/other.py", "title": "o", "summary": "s", "score": 2.0},
+ ]
+ payload = await _degraded(_tree(tmp_path), hits, {"Flask"})
+
+ assert payload["citations"] == ["src/flask/app.py"]
+
+
+async def test_degraded_cites_rationale_alone_without_best_guesses(tmp_path, monkeypatch):
+ _rationale_rows(monkeypatch, "cmd/completions.go")
+ payload = await _degraded(SimpleNamespace(path=str(tmp_path), session_factory=None), [], set())
+
+ assert "best_guesses" not in payload
+ assert payload["citations"] == ["cmd/completions.go"]
+
+
+async def test_degraded_body_path_then_guesses_then_rationale(tmp_path, monkeypatch):
+ _rationale_rows(monkeypatch, "src/flask/hub.py")
+ hits = [
+ *_hits(end_line=6),
+ {"target_path": "src/flask/other.py", "title": "o", "summary": "s", "score": 2.0},
+ ]
+ payload = await _degraded(_tree(tmp_path), hits, {"Flask"})
+
+ assert payload["symbol_bodies"][0]["path"] == "src/flask/app.py"
+ assert payload["citations"] == ["src/flask/app.py", "src/flask/other.py", "src/flask/hub.py"]
+
+
+def test_degraded_citing_the_guesses_does_not_grow_the_served_files():
+ """Ranked guesses moved into citations keep their candidate_files slots."""
+ from repowise.server.mcp_server.tool_answer.projection import _shape_candidate_files
+
+ pool = ["top.go", "a.go", "b.go", "c.go", "d.go", "e.go", "f.go"]
+
+ def served(citations: list[str]) -> set[str]:
+ payload = {
+ "degraded": "no-llm-provider",
+ "citations": citations,
+ "best_guesses": [{"file": "top.go"}],
+ "code_rationale": [{"path": "hub.go", "lines": [1, 2]}],
+ "candidate_files": list(pool),
+ }
+ _shape_candidate_files(payload, expanded=False)
+ return set(payload["citations"]) | set(payload.get("candidate_files") or [])
+
+ assert served(["top.go", "hub.go"]) == served(["hub.go"])
+
+
async def test_degraded_does_not_ship_the_excerpt_twice(tmp_path):
"""`best_guesses[].excerpt` and `retrieval[].excerpt` are the same bytes.