Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(answer): serve a compact ranked shortlist on low and keyless answers (#3108)
Raghav Chamadiya4531c8efbf7c
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex a052d2d05..89881a5e3 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -147,7 +147,7 @@ Answers a how, where or why question in one call: it runs hybrid retrieval over| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported || `include` | list[string] | none | `["evidence"]` returns the full evidence projection with a larger budget |-**Key return fields:** `answer`, `confidence` (`high` / `medium` / `low`, rates the prose), `retrieval_quality` (`high` / `partial` / `weak`, rates the evidence), `citations`, `symbol_bodies` (live bodies of symbols the answer names), `retrieval`, `best_guesses` and `fallback_targets` (on low confidence), `candidate_files` (ranked file paths the citations do not already name: up to 3 at `high`, 5 otherwise), `episodes` (dated facts bearing on the question), `degraded` (synthesis could not run), `_meta.scope_hint` (areas the answer did not touch).+**Key return fields:** `answer`, `confidence` (`high` / `medium` / `low`, rates the prose), `retrieval_quality` (`high` / `partial` / `weak`, rates the evidence), `citations`, `symbol_bodies` (live bodies of symbols the answer names), `retrieval`, `best_guesses` and `fallback_targets` (on low confidence; a low `best_guesses` row carries `functions`, `lines` and `size_bytes` instead of a page excerpt), `candidate_files` (ranked file paths the citations do not already name: up to 3 at `high`, 5 otherwise), `episodes` (dated facts bearing on the question), `degraded` (synthesis could not run), `_meta.scope_hint` (areas the answer did not touch).A `high` answer can be cited directly. On `low`, read the rows the reply names, then `candidate_files`, before searching again. Without an LLM provider the tool still answers from retrieval, marked `degraded`.diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 545f610b6..186ac2708 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -128,7 +128,7 @@ Every suggested follow-up (`get_health`'s `fix_first[].next_call`, the refactori| `retrieval` | Evidence rows (summary, snippet, key symbols). Shrinks as confidence rises || `candidate_files` | Ranked file paths retrieval resolved, minus those already in `citations`: up to 3 at `high`, 5 at `medium`, `low` or `degraded`. Navigation, not evidence. Served at every confidence; absent when retrieval resolved no file || `candidates` | The top 5 of those files as `{path, lines?, defines?}` rows. Only with `include=["evidence"]` |-| `best_guesses`, `fallback_targets` | On low confidence: where to look, each with a one-line reason |+| `best_guesses`, `fallback_targets` | On low confidence: where to look, each with a one-line reason. At `low` or `degraded` a `best_guesses` row drops its page `excerpt` and carries `functions` (up to 3 `{name, line}` symbols relevant to the question) and the live file's `lines` and `size_bytes`; `include=["evidence"]` brings the excerpt back || `episodes` | A dated fact recorded about this checkout that bears on the question; `still_true` says how current it is || `degraded` | Synthesis could not run (no provider, or the call failed). The answer is assembled from retrieval and mined rationale with no LLM, and `confidence` is graded from the retrieval: `medium` unless `retrieval_quality` is `weak`, never `high` |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 10e340015..1b437adc4 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@@ -272,7 +272,12 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5# confined to them need no bump; a needless bump costs every keyed install a# round of provider spend.# 18: rows carry ``candidate_files``, the ranked paths-only list.-_ANSWER_SCHEMA_VERSION = 18+# 19: rows carry ``_candidate_file_facts``; low answers serve slim best_guesses rows.+_ANSWER_SCHEMA_VERSION = 19++# Above this a whole-file Read costs more than the answer, so the low-confidence+# hint names a ranged Read or a skeleton instead.+_LARGE_FILE_BYTES = 40_000# How many paths ``candidate_files`` serves: the knee of measured coverage# gained per extra file, past which each path mostly costs precision. A highdiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py b/packages/server/src/repowise/server/mcp_server/tool_answer/payload.pyindex d7be4e5f5..bdeb963ea 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py@@ -45,6 +45,9 @@ from repowise.server.mcp_server.tool_answer.retrieval import (_CANDIDATE_LIMIT,_candidate_justification,)+from repowise.server.mcp_server.tool_answer.retrieval import (+ serialize_candidate_file_facts as _serialize_candidate_file_facts,+)from repowise.server.mcp_server.tool_answer.retrieval import (serialize_candidate_files as _serialize_candidate_files,)@@ -158,6 +161,9 @@ def _with_candidates(payload: dict, resolved_pool: list[dict]) -> dict:# Longer than ``candidates``: the projection serves these paths at# every confidence, while ``candidates`` waits for include=["evidence"].payload["candidate_files"] = _serialize_candidate_files(resolved_pool)+ # Internal: the projection adds these to slimmed best_guesses on low+ # answers and drops them everywhere else.+ payload["_candidate_file_facts"] = _serialize_candidate_file_facts(resolved_pool)return payloaddiff --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 2b9cc8e4e..0a112f31f 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@@ -3,13 +3,16 @@from __future__ import annotationsimport copy+import refrom collections.abc import Callablefrom functools import wraps+from pathlib import Pathfrom typing import Anyfrom repowise.server.mcp_server.tool_answer.config import (_CANDIDATE_FILES_HIGH,_CANDIDATE_FILES_MAX,+ _LARGE_FILE_BYTES,)_COLLECTIONS = (@@ -307,6 +310,57 @@ def _shape_candidate_files(payload: dict[str, Any], *, expanded: bool) -> None:payload["candidate_files"] = paths+# Only the legacy abstain reply points at excerpts; once slimmed there are none.+_EXCERPT_NOTE = re.compile(r", and its excerpt carries that page's actual content(?=\.)")+++def _first_guess(payload: dict[str, Any]) -> dict[str, Any] | None:+ """The first ``best_guesses`` row naming a file: what both hints point at."""+ return next(+ (+ row for row in payload.get("best_guesses") or []+ if isinstance(row, dict) and _nav_path(row)+ ),+ None,+ )+++def _slim_best_guesses(payload: dict[str, Any], facts: dict[str, Any]) -> bool:+ """Swap each low-confidence guess's page excerpt for compact facts about its file.++ Rows, keys and order stay; ``excerpt`` returns with ``include=["evidence"]``.+ The row's own ``why_relevant`` and ``score`` win: they come from the same hit.+ Returns whether there were rows to slim, so sizes are stamped on those only.+ """+ guesses = payload.get("best_guesses")+ if not isinstance(guesses, list) or not guesses:+ return False+ dropped = False+ for row in guesses:+ if not isinstance(row, dict):+ continue+ dropped |= row.pop("excerpt", None) is not None+ known = facts.get(_nav_path(row))+ if not isinstance(known, dict):+ continue+ if not row.get("why_relevant") and known.get("why"):+ row["why"] = known["why"]+ if known.get("functions"):+ row["functions"] = known["functions"]+ first = _first_guess(payload)+ if dropped:+ note = payload.get("note")+ if isinstance(note, str):+ payload["note"] = _EXCERPT_NOTE.sub("", note)+ hint = payload.get("next_action_hint")+ if first and isinstance(hint, str) and hint.startswith("Start from the excerpt of "):+ payload["next_action_hint"] = (+ f"Read {_nav_path(first)} first: it scored highest, and best_guesses "+ "says why each file is in the running."+ )+ return True++def _default_shape(payload: dict[str, Any], question: str) -> None:confidence = _shape_confidence(payload)why = question.lstrip().lower().startswith("why")@@ -401,6 +455,14 @@ def project_answer_payload(repo: str | None = None, include: list[str] | None = None) -> dict[str, Any]:"""Return the cache-independent, confidence-specific external response."""+ return _project(raw, question=question, scope=scope, repo=repo, include=include)[0]+++def _project(+ raw: dict[str, Any], *, question: str, scope: str | None,+ repo: str | None, include: list[str] | None+) -> tuple[dict[str, Any], bool]:+ """The projection, and whether it slimmed ``best_guesses`` (decided once, here)."""payload = copy.deepcopy(raw)totals = {key: len(payload.get(key) or []) if isinstance(payload.get(key), list) else 0@@ -408,8 +470,12 @@ def project_answer_payload(}_deduplicate(payload)expanded = "evidence" in set(include or [])+ facts = payload.pop("_candidate_file_facts", None)+ slimmed = Falseif not expanded:_default_shape(payload, question)+ if _shape_confidence(payload) == "low":+ slimmed = _slim_best_guesses(payload, facts if isinstance(facts, dict) else {})_shape_candidate_files(payload, expanded=expanded)_rewrite_degraded_answer(payload)for key in _COLLECTIONS:@@ -419,7 +485,7 @@ def project_answer_payload(unknown = sorted(set(include or []) - {"evidence"})if unknown:payload.setdefault("_meta", {})["ignored_arguments"] = {"include": unknown}- return payload+ return payload, slimmeddef _served_paths(payload: dict[str, Any]) -> list[str]:@@ -499,6 +565,75 @@ async def _refresh_freshness(payload: dict[str, Any], repo: str | None) -> None:meta["hint"] = hint+_LINE_COUNT_MAX_BYTES = 2_000_000+++def _file_size(root: Path, path: str) -> tuple[int | None, int] | None:+ """``(lines, size_bytes)`` of a repo file on disk, or None when it is not one.++ Size from ``stat``; lines by streaming, and None above+ :data:`_LINE_COUNT_MAX_BYTES` so a huge file is never read to count them.+ """+ try:+ abs_path = (root / path).resolve()+ # An index row is not a trust boundary; refuse anything outside the repo.+ abs_path.relative_to(root.resolve())+ if not abs_path.is_file():+ return None+ size = abs_path.stat().st_size+ if size > _LINE_COUNT_MAX_BYTES:+ return None, size+ lines, last = 0, b""+ with abs_path.open("rb") as handle:+ while chunk := handle.read(65536):+ lines += chunk.count(b"\n")+ last = chunk[-1:]+ except (OSError, ValueError):+ return None+ return lines + (1 if last and last != b"\n" else 0), size+++def _add_file_sizes(payload: dict[str, Any], root: Path | None) -> None:+ """Stamp live ``lines`` / ``size_bytes`` on slimmed guesses and cue a ranged read.++ Serve-time, not cached, so a dirty tree reports the bytes an agent would Read.+ """+ if root is None:+ return+ for row in payload.get("best_guesses") or []:+ path = _nav_path(row) if isinstance(row, dict) else None+ size = _file_size(root, path) if path else None+ if size is None:+ continue+ lines, row["size_bytes"] = size+ if lines is not None:+ row["lines"] = lines+ top = _first_guess(payload)+ if top and top.get("size_bytes", 0) > _LARGE_FILE_BYTES:+ path = _nav_path(top)+ cue = (+ f"{path} is {top['size_bytes'] // 1024} KB: Read a line range, or call "+ f"get_context(targets=[\"{path}\"], include=[\"skeleton\"]), "+ "rather than the whole file."+ )+ hint = payload.get("next_action_hint")+ payload["next_action_hint"] = f"{hint.rstrip()} {cue}" if isinstance(hint, str) else cue+++async def _refresh_file_sizes(payload: dict[str, Any], repo: str | None) -> None:+ """Size the slimmed guesses. Best-effort: a sync stat and bounded read of <= 3 files."""+ if repo == "all":+ return+ try:+ from repowise.server.mcp_server._helpers import _resolve_repo_context+ from repowise.server.mcp_server.tool_answer.evidence import _repo_root++ root = _repo_root(await _resolve_repo_context(repo))+ except Exception:+ return+ _add_file_sizes(payload, root)++def _whole_bodies(payload: dict[str, Any]) -> int:"""Count symbol bodies that survived the projection intact.@@ -542,10 +677,12 @@ def projected_answer(fn: Callable[..., Any]) -> Callable[..., Any]:include: list[str] | None = None,) -> dict[str, Any]:raw = await fn(question=question, scope=scope, repo=repo, include=include)- payload = project_answer_payload(+ payload, slimmed = _project(raw, question=question, scope=scope, repo=repo, include=include)await _refresh_freshness(payload, repo)+ if slimmed:+ await _refresh_file_sizes(payload, repo)_stamp_completeness(payload)return payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.pyindex 6cbcc1b7d..54e70a042 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@@ -100,6 +100,47 @@ def serialize_candidate_files(hits: list[dict]) -> list[str]:return paths+# Symbol names a shortlist row carries: enough to point at a line, not an outline.+_SHORTLIST_FUNCTIONS = 3+++def serialize_candidate_file_facts(hits: list[dict]) -> dict[str, dict[str, Any]]:+ """Per-path ``why`` and ``functions`` for the ``candidate_files`` pool.++ Built from what retrieval already resolved, no extra query: the first hit+ naming a file supplies the reason, and ``functions`` takes the+ question-matched hydrated symbols first, then the indexed ``_defines``.+ Paths with nothing to say get no entry.+ """+ facts: dict[str, dict[str, Any]] = {}+ seen: set[str] = set()+ for h in hits:+ path = hit_file_path(h)+ if not path or path in seen:+ continue+ seen.add(path)+ row: dict[str, Any] = {}+ why = _candidate_justification(h)+ if why:+ row["why"] = why+ named: dict[str, int] = {}+ for s in h.get("symbols") or []:+ if s.get("_matched") and s.get("name") and s.get("start_line"):+ named.setdefault(s["name"], s["start_line"])+ for name, line in h.get("_defines") or ():+ named.setdefault(name, line)+ if named:+ row["functions"] = [+ {"name": name, "line": line}+ for name, line in list(named.items())[:_SHORTLIST_FUNCTIONS]+ ]+ if row:+ facts[path] = row+ if len(seen) >= _CANDIDATE_FILES_POOL:+ break+ return facts++def serialize_hits(hits: list[dict],*,diff --git a/tests/unit/server/mcp/test_answer_degraded_evidence.py b/tests/unit/server/mcp/test_answer_degraded_evidence.pyindex d19b703d9..106f0228d 100644--- a/tests/unit/server/mcp/test_answer_degraded_evidence.py+++ b/tests/unit/server/mcp/test_answer_degraded_evidence.py@@ -663,9 +663,14 @@ async def test_degraded_does_not_ship_the_excerpt_twice(tmp_path):hits[0]["excerpt"] = "x" * 1500payload = await _degraded(ctx, hits, {"Blueprint"})- external = project_answer_payload(payload, question="what is Blueprint")+ external = project_answer_payload(+ payload, question="what is Blueprint", include=["evidence"]+ )assert external["best_guesses"][0]["excerpt"] == "x" * 1500- assert "retrieval" not in external+ # The default low shape serves the guess without its excerpt.+ compact = project_answer_payload(payload, question="what is Blueprint")+ assert "excerpt" not in compact["best_guesses"][0]+ assert "retrieval" not in compactasync def test_degraded_keeps_the_guess_excerpt_when_nothing_duplicates_it(tmp_path):diff --git a/tests/unit/server/mcp/test_answer_shortlist.py b/tests/unit/server/mcp/test_answer_shortlist.pynew file mode 100644index 000000000..f5da8643f--- /dev/null+++ b/tests/unit/server/mcp/test_answer_shortlist.py@@ -0,0 +1,245 @@+"""Low and degraded answers serve slim best_guesses rows instead of page excerpts."""++from __future__ import annotations++import copy+import inspect+import json+import os++import pytest++from repowise.server.mcp_server.tool_answer.payload import build_abstain_payload+from repowise.server.mcp_server.tool_answer.projection import (+ _EXCERPT_NOTE,+ _add_file_sizes,+ _file_size,+ project_answer_payload,+)+from repowise.server.mcp_server.tool_answer.retrieval import serialize_candidate_file_facts++_EXCERPT = "Page prose. " * 125 # about the 1,500-char excerpt a real guess carries+_POOL = [f"src/pkg/f{i}.py" for i in range(10)]+++def _raw(confidence: str, **extra) -> dict:+ raw = {+ "answer": "Probably in f0.",+ "citations": ["src/pkg/f1.py"],+ "confidence": confidence,+ "retrieval_quality": "weak",+ "fallback_targets": _POOL[:3],+ "retrieval": [{"path": p, "excerpt": _EXCERPT, "score": 1.0} for p in _POOL[:5]],+ "best_guesses": [+ {"file": p, "why_relevant": f"guess {p}", "score": 3.0 - i, "excerpt": _EXCERPT}+ for i, p in enumerate(_POOL[:3])+ ],+ "candidate_files": list(_POOL),+ "_candidate_file_facts": {+ p: {+ "why": f"Implements function run_{i}.",+ "functions": [{"name": f"run_{i}", "line": 10 + i}],+ }+ for i, p in enumerate(_POOL)+ },+ "next_action_hint": "Start from src/pkg/f0.py, it ranked highest.",+ "note": "Each best_guess entry names why that file is in the running.",+ "_meta": {"contract_version": 1},+ }+ raw.update(extra)+ return raw+++ ("confidence", "extra"), [("low", {}), ("medium", {"degraded": "no-llm-provider"})]+)+def test_low_and_degraded_slim_the_guesses(confidence, extra):+ out = project_answer_payload(_raw(confidence, **extra), question="where is run handled")++ assert "excerpt" not in json.dumps(out)+ assert [g["file"] for g in out["best_guesses"]] == _POOL[:3]+ # Existing keys stay as they were; the facts only add what is missing.+ assert out["best_guesses"][0] == {+ "file": "src/pkg/f0.py",+ "why_relevant": "guess src/pkg/f0.py",+ "score": 3.0,+ "functions": [{"name": "run_0", "line": 10}],+ }+ # candidate_files keeps its bare-path shape at every grade.+ assert out["candidate_files"] == [p for p in _POOL if p != "src/pkg/f1.py"][:5]+ assert "_candidate_file_facts" not in out+++def test_a_guess_without_a_reason_takes_the_facts_reason():+ raw = _raw("low")+ raw["best_guesses"][0].pop("why_relevant")+ out = project_answer_payload(raw, question="q")+ assert out["best_guesses"][0]["why"] == "Implements function run_0."+++def test_the_abstain_prose_stops_pointing_at_an_excerpt():+ raw = _raw(+ "low",+ note="Each best_guess entry names why that file is in the running, and its "+ "excerpt carries that page's actual content.",+ next_action_hint="Start from the excerpt of src/pkg/f0.py, it scored highest.",+ )+ out = project_answer_payload(raw, question="q")+ assert out["note"] == "Each best_guess entry names why that file is in the running."+ assert "excerpt" not in out["next_action_hint"]+ assert out["next_action_hint"].startswith("Read src/pkg/f0.py first")+++def test_the_retargeted_prose_still_matches_the_abstain_source():+ """The rewrite keys on literal abstain wording; a reword there must fail here."""+ source = inspect.getsource(build_abstain_payload)+ clause = ", and its excerpt carries that page's actual content."+ assert clause in source+ assert _EXCERPT_NOTE.search(clause)+ assert 'f"Start from the excerpt of ' in source+++def test_the_hint_names_the_first_guess_with_a_path():+ raw = _raw("low", next_action_hint="Start from the excerpt of x, it scored highest.")+ raw["best_guesses"].insert(0, {"why_relevant": "no file", "excerpt": "e"})+ out = project_answer_payload(raw, question="q")+ assert out["next_action_hint"].startswith("Read src/pkg/f0.py first")++[email protected]("confidence", ["high", "medium"])+def test_medium_and_high_bytes_do_not_change(confidence):+ with_facts = project_answer_payload(_raw(confidence), question="q")+ raw = _raw(confidence)+ raw.pop("_candidate_file_facts")+ without = project_answer_payload(raw, question="q")++ assert json.dumps(with_facts, sort_keys=True) == json.dumps(without, sort_keys=True)+++def test_evidence_include_still_serves_guess_excerpts_on_low():+ raw = _raw("low")+ without = copy.deepcopy(raw)+ without.pop("_candidate_file_facts")+ out = project_answer_payload(raw, question="q", include=["evidence"])++ assert all(g["excerpt"] == _EXCERPT for g in out["best_guesses"])+ assert out == project_answer_payload(without, question="q", include=["evidence"])+++def test_slim_low_answer_is_much_smaller():+ raw = _raw("low")+ compact = project_answer_payload(copy.deepcopy(raw), question="q")+ expanded = project_answer_payload(raw, question="q", include=["evidence"])+ assert len(json.dumps(compact)) * 3 < len(json.dumps(expanded))+++def test_file_sizes_are_stamped_live_and_a_large_top_file_cues_a_ranged_read(tmp_path):+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "big.py").write_bytes(b"x = 1\n" * 8000)+ (tmp_path / "src" / "small.py").write_bytes(b"a\nb")+ payload = {+ "best_guesses": [{"file": "src/big.py"}, {"file": "src/small.py"}, {"file": "gone.py"}],+ "next_action_hint": "Start from src/big.py.",+ }++ _add_file_sizes(payload, tmp_path)++ big, small, gone = payload["best_guesses"]+ assert (big["lines"], big["size_bytes"]) == (8000, 48000)+ assert (small["lines"], small["size_bytes"]) == (2, 3)+ assert gone == {"file": "gone.py"}+ assert payload["next_action_hint"].startswith("Start from src/big.py. src/big.py is 46 KB")+ assert 'include=["skeleton"]' in payload["next_action_hint"]++ payload = {"best_guesses": [{"file": "src/small.py"}], "next_action_hint": "h"}+ _add_file_sizes(payload, tmp_path)+ assert payload["next_action_hint"] == "h"+++def test_the_size_cue_uses_the_first_guess_with_a_path(tmp_path):+ (tmp_path / "big.py").write_bytes(b"x\n" * 30000)+ payload = {"best_guesses": [{"why_relevant": "no file"}, {"file": "big.py"}]}+ _add_file_sizes(payload, tmp_path)+ assert payload["best_guesses"][0] == {"why_relevant": "no file"}+ assert payload["next_action_hint"].startswith("big.py is 58 KB")+++def test_a_huge_file_reports_its_size_but_is_never_read_for_lines(tmp_path):+ with (tmp_path / "huge.bin").open("wb") as handle:+ handle.truncate(3_000_000)+ assert _file_size(tmp_path, "huge.bin") == (None, 3_000_000)+ assert _file_size(tmp_path, "missing.py") is None+ (tmp_path / "dir").mkdir()+ assert _file_size(tmp_path, "dir") is None+++def test_file_sizes_refuse_paths_outside_the_repo(tmp_path):+ (tmp_path / "outside.py").write_text("secret\n")+ root = tmp_path / "repo"+ root.mkdir()+ payload = {"best_guesses": [{"file": "../outside.py"}]}+ _add_file_sizes(payload, root)+ assert payload["best_guesses"] == [{"file": "../outside.py"}]+++def test_file_sizes_refuse_a_symlink_that_escapes_the_repo(tmp_path):+ (tmp_path / "outside.py").write_text("secret\n")+ root = tmp_path / "repo"+ root.mkdir()+ try:+ os.symlink(tmp_path / "outside.py", root / "link.py")+ except (OSError, NotImplementedError):+ pytest.skip("symlinks are not available here")+ assert _file_size(root, "link.py") is None+++def test_candidate_file_facts_come_from_the_resolved_hits():+ hits = [+ {+ "target_path": "src/a.py",+ "page_type": "file_page",+ "score": 2.34567,+ "symbols": [{"name": "handle", "kind": "function", "start_line": 40, "_matched": True}],+ "_defines": [("handle", 40), ("Router", 5), ("route", 70), ("extra", 90)],+ },+ {"target_path": "src/a.py", "page_type": "file_page", "score": 1.0},+ {"target_path": "src/b.py", "page_type": "file_page", "summary": "Routes requests. More."},+ {"target_path": "src/c.py", "page_type": "file_page", "score": 0.5},+ ]++ facts = serialize_candidate_file_facts(hits)++ # c.py has nothing to say, so it gets no entry.+ assert list(facts) == ["src/a.py", "src/b.py"]+ assert facts["src/a.py"] == {+ "why": "Implements function handle.",+ "functions": [+ {"name": "handle", "line": 40},+ {"name": "Router", "line": 5},+ {"name": "route", "line": 70},+ ],+ }+ assert facts["src/b.py"] == {"why": "Routes requests."}+++async def test_candidate_file_facts_never_leak_through_the_tool_on_a_cache_hit(+ setup_mcp, monkeypatch+):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer, tool_middleware++ from .test_answer_projection import _patch_retrieval, _Provider++ _patch_retrieval(monkeypatch, answer_mod)+ provider = _Provider("Authentication is implemented in src/auth/service.py.")+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _path: provider)+ call = tool_middleware(get_answer)++ fresh = await call("where is the leak-free authentication implemented")+ cached = await call("where is the leak-free authentication implemented")++ assert cached["_meta"]["cached"] is True+ assert provider.calls == 1+ for reply in (fresh, cached):+ assert "_candidate_file_facts" not in json.dumps(reply, default=str)diff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.pyindex 72f38685d..76b7b42ac 100644--- a/tests/unit/server/mcp/test_answer_synthesis_timeout.py+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py@@ -469,6 +469,7 @@ async def test_both_failure_modes_return_the_same_payload_shape(reason):"retrieval","candidates","candidate_files",+ "_candidate_file_facts","best_guesses","next_action_hint","note",