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): serve evidence and rate retrieval when no LLM provider is configured (#1508)

Raghav Chamadiyabad659903c33
diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
index 222569976..7df4bb411 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
@@ -51,9 +51,16 @@ from __future__ import annotations
TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
"get_answer": (
"get_answer(question)",
- 'First call for any how / where / why question. `confidence: "high"` or '
- '`grounding: "extracted"` is content-grounded, so cite it directly; '
- "`symbol_bodies` carries full live bodies.",
+ # `degraded` earns its three words because without them the row is wrong
+ # for a whole class of install. An LLM-less repowise answers every
+ # question with `confidence: "low"`, since confidence rates prose that
+ # was never synthesised, and this row told the agent to distrust the
+ # payload on the strength of it, so it re-searched after every call.
+ # `retrieval_quality` is the field that rates what such a payload does
+ # carry. Reworded, not lengthened: 186 chars against the 179 it replaced.
+ 'First call for any how/where/why question. Cite `confidence: "high"` or '
+ '`grounding: "extracted"` directly; `degraded` means judge by '
+ "`retrieval_quality`. `symbol_bodies` has live bodies.",
),
"get_context": (
"get_context(targets=[...])",
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 2bd21a0c0..eb9867ea3 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -413,12 +413,48 @@ def symbol_hint(symbol_id: str, end_line: int, start_line: int) -> str | None:
return None
-def answer_hint(confidence: str, retrieval_count: int) -> str | None:
+def answer_hint(
+ confidence: str,
+ retrieval_count: int,
+ *,
+ degraded: str | None = None,
+ retrieval_quality: str | None = None,
+ has_bodies: bool = False,
+) -> str | None:
"""Hint for `get_answer` callers.
Encourages verification when confidence is low; never tells the agent to
"trust the answer" — that's the over-trust failure mode.
+
+ A degraded payload is keyed separately, because "low" means something
+ different there. Everywhere else it rates an answer that exists and might be
+ wrong, so "go verify" is the right push. On a degraded payload there is no
+ synthesised text at all: what is missing is the prose, not the evidence, and
+ the evidence beside it can be excellent. Telling an install with no LLM to
+ doubt its files on every question is what made a keyless agent call
+ search_codebase after every get_answer: one question, two calls, measured on
+ 11 of 26 questions whose rank-1 file was right. So say which half is missing
+ and let `retrieval_quality` rate the other half.
"""
+ if degraded:
+ if retrieval_quality == "weak":
+ return (
+ "No synthesis, and retrieval was weak. Refine the query with "
+ "search_codebase rather than reading these files in order."
+ )
+ # Name symbol_bodies only when there is one. A hint that points at a key
+ # the payload does not carry is the same misdirection this branch exists
+ # to remove, and strong retrieval without an anchored body is an ordinary
+ # outcome here (a prose question naming no identifier).
+ if has_bodies:
+ return (
+ "Synthesis is what is missing here, not retrieval. Answer from "
+ "symbol_bodies; retrieval_quality rates what was served."
+ )
+ return (
+ "Synthesis is what is missing here, not retrieval. retrieval_quality "
+ "rates the ranked hits; start from the first one."
+ )
if confidence == "low":
return "Low confidence — Read the listed fallback_targets to verify before answering."
if retrieval_count == 0:
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.py
index 67f994791..1311b0f6a 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
@@ -645,7 +645,7 @@ def _drop_already_surfaced(rationale: list[dict], *surfaced: list[dict]) -> list
def _gather_body_candidates(
- hits: list[dict], answer_text: str
+ hits: list[dict], answer_text: str, *, anchor_names: set[str] | None = None
) -> list[tuple[int, int, int, str, dict]]:
"""Rank the definitions to inline in ``symbol_bodies``, most-relevant first.
@@ -660,6 +660,15 @@ def _gather_body_candidates(
extract_all method of DecisionExtractor" serves extract_all, not the
1,300-line class head), then document order. Only definitions the answer
text actually names qualify; constants stay in ``quotes``.
+
+ ``anchor_names`` switches tier 0 off the prose and onto the identifiers the
+ QUESTION named: the degraded path, where there is no synthesised text to
+ match against. Selection was the only thing coupling ``symbol_bodies`` to
+ synthesis: the bodies themselves are read live off disk from index anchors,
+ and tier 0's input (``_anchor_symbols``) is driven by
+ ``_extract_question_identifiers`` off the question, so it is fully determined
+ before synthesis would have run. Tier 1 is skipped in this mode by
+ construction, since it exists to catch a symbol only the prose names.
"""
candidates: list[tuple[int, int, int, str, dict]] = []
for h in hits[:_ENRICH_TOP_N_HITS]:
@@ -668,11 +677,15 @@ def _gather_body_candidates(
continue
for s in h.get("_anchor_symbols") or []:
name = s.get("name")
- if not name or name not in answer_text:
+ if not name:
+ continue
+ if name not in anchor_names if anchor_names is not None else name not in answer_text:
continue
kind = s.get("kind")
kind_rank = 0 if kind in ("function", "method") else 1
candidates.append((0, kind_rank, s.get("start_line") or 0, path, s))
+ if anchor_names is not None:
+ continue
for s in h.get("symbols") or []:
name = s.get("name")
if not name or len(name) < 3 or not s.get("_matched"):
@@ -688,6 +701,94 @@ def _gather_body_candidates(
return candidates
+def _retrieval_quality(hits: list[dict], agreement_dominant: bool) -> str:
+ """Rate the retrieval, independently of the text it fed.
+
+ Where ``confidence`` says "how much should you trust the synthesised text",
+ this says "how good was the retrieval that fed it". The agent reads
+ confidence to decide whether to re-read, and this to decide whether to call
+ search_codebase again with a refined query.
+
+ Kept as one function because the degraded path needs the same rating and must
+ not invent a second one. That path has no synthesised text to rate (its
+ ``confidence`` stays low, correctly), but it ran exactly the same retrieval,
+ and "high" has to mean the same thing to a keyless caller as to a keyed one
+ or the field is worth less than nothing.
+ """
+ if len(hits) >= 2:
+ ratio = hits[0].get("score", 0.0) / (hits[1].get("score", 0.0) or 1e-9)
+ else:
+ ratio = float("inf") if hits else 0.0
+ top_score = hits[0].get("score", 0.0) if hits else 0.0
+ dominant_grade = ratio >= _DOMINANCE_RATIO or agreement_dominant
+ if dominant_grade and top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:
+ return "high"
+ return "partial" if dominant_grade else "weak"
+
+
+def _build_symbol_bodies(
+ body_candidates: list[tuple[int, int, int, str, dict]], repo_root: Path | None
+) -> tuple[list[dict], bool]:
+ """Inline the ranked definitions as live source, with the truncation contract.
+
+ Returns ``(symbol_bodies, served_named_body)``. ``served_named_body`` is True
+ once a tier-0 body (the exact symbol the question named) is inlined; the
+ confidence gates read it to avoid the "low, go Read" label on a payload that
+ already holds the answer.
+
+ Every step here is prose-independent: the body is re-read live from disk at
+ the indexed bounds, and when the indexed body outruns the line cap a
+ ``continuation`` names the exact range read for the remainder plus the
+ ``withheld_symbols`` it covers. That is why the degraded path can call this
+ too. The only thing it lacks is the answer text that selects the candidates,
+ which ``_gather_body_candidates(anchor_names=...)`` supplies instead.
+ """
+ symbol_bodies: list[dict] = []
+ seen: set[tuple[str, str]] = set()
+ served_named_body = False
+ for tier, _kind_rank, start, path, s in body_candidates:
+ if len(symbol_bodies) >= _INLINE_BODY_MAX_SYMBOLS:
+ break
+ name = s["name"]
+ if (path, name) in seen:
+ continue
+ sym_end = s.get("end_line") or 0
+ # Re-read a fuller body than the synthesis excerpt: this block is for
+ # the agent, so a docstring-heavy def shouldn't spend its whole window
+ # on docstring and truncate the logic the question asked about. Falls
+ # back to the hydrator's excerpt if the re-read fails.
+ body = _read_symbol_source(
+ repo_root, path, start, sym_end, max_lines=_INLINE_BODY_MAX_LINES
+ ) or s.get("source_excerpt")
+ if not body:
+ continue
+ served = body.count("\n") + 1
+ end_served = start + served - 1
+ sym_end = sym_end or end_served
+ entry: dict = {
+ "path": path,
+ "name": name,
+ "lines": [start, end_served],
+ "source": body,
+ }
+ if sym_end > end_served:
+ entry["truncated"] = True
+ entry["continuation"] = f"{path}:{end_served + 1}-{sym_end}"
+ # Say WHAT was withheld, not just that something was. A bare
+ # truncated flag plus a get_symbol pointer was followed zero times
+ # across the agent runs measured, so the consumer needs the names in
+ # hand to decide whether it is missing anything it cares about, and
+ # to continue inside this tool rather than falling back to Read.
+ withheld = withheld_definitions(repo_root, entry["continuation"])
+ if withheld:
+ entry["withheld_symbols"] = withheld
+ symbol_bodies.append(entry)
+ seen.add((path, name))
+ if tier == 0:
+ served_named_body = True
+ return symbol_bodies, served_named_body
+
+
def _build_data_shape_payload(grounded: dict, t0: float, repository) -> dict:
"""Shape a grounded data-shape result into a get_answer response.
@@ -803,7 +904,7 @@ def _with_candidates(payload: dict, resolved_pool: list[dict]) -> dict:
return payload
-def _degraded_payload(
+async def _degraded_payload(
*,
reason: str,
note: str,
@@ -811,6 +912,10 @@ def _degraded_payload(
fallback_targets: list[str],
repository,
t0: float,
+ ctx=None,
+ question_ids: set[str] | None = None,
+ exclude_spec=None,
+ agreement_dominant: bool = False,
resolved_pool: list[dict] | None = None,
) -> dict:
"""Shape a synthesis-less get_answer response.
@@ -831,9 +936,61 @@ def _degraded_payload(
carries, so it can never claim more than it has, and no prose about the
question itself is invented, that being precisely the part that needs a
provider.
+
+ The evidence beside the prose is built here too. Everything below the
+ provider check in ``get_answer`` (bodies, citations, the next action) is
+ read live off disk from index anchors and needs no LLM; the only thing that
+ coupled it to synthesis was that ``_gather_body_candidates`` selects against
+ the answer text. Measured on the keyless arm (26 paired questions, flask +
+ django, 2026-08-13) that cost 9 of 26 questions the very body the keyed arm
+ served: a caller asking for ``Flask`` got three paths where the keyed arm got
+ ``src/flask/app.py`` 105-225. Selecting tier 0 against the question's own
+ identifiers instead recovers it, and an agent handed the body of the symbol
+ it asked about answers from the tool rather than leaving it to Read.
+
+ ``confidence`` stays "low" and is not up for debate: it rates the synthesised
+ text, and here that text is assembled boilerplate, byte-identical on 24 of
+ the 26 measured questions. An agent told to cite it would cite that sentence.
+ What was missing is ``retrieval_quality``, which rates the retrieval instead
+ and was simply never set: 26 of 26 keyless payloads carried no such key, so
+ the only trust signal a caller had was a "low" about something it should not
+ have been trusting anyway, and 11 of them said it while rank 1 was a file the
+ keyed arm went on to cite. The same rule the synthesised path uses answers
+ that question here, and it stays honest in the other direction: 14 of the 26
+ retrievals were genuinely weak in both arms and still grade "weak".
"""
+ retrieval_quality = _retrieval_quality(hits, agreement_dominant)
+ repo_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else None
+ symbol_bodies, _served_named_body = _build_symbol_bodies(
+ _gather_body_candidates(hits, "", anchor_names=question_ids or set()),
+ repo_root,
+ )
+ # Cite what is actually in hand. `[]` was right when the payload carried no
+ # source; with bodies inlined the paths they were read from are citations in
+ # the ordinary sense, and a caller filtering on non-empty `citations` stops
+ # discarding this reply.
+ citations = list(dict.fromkeys(b["path"] for b in symbol_bodies))
+
served = len(hits)
- if served:
+ if symbol_bodies:
+ _names = ", ".join(f"`{b['name']}`" for b in symbol_bodies)
+ # Never say "full" over a body the payload itself flags as cut. The
+ # entry carries `truncated` and a `continuation` two keys away, so the
+ # claim is refutable from inside the same response.
+ _cut = any(b.get("truncated") for b in symbol_bodies)
+ summary = (
+ f"No synthesized prose ({reason}), but the evidence is here: "
+ f"`symbol_bodies` carries the live source of {_names}, read from the "
+ "current checkout"
+ + (
+ ", cut at the line cap where noted; see `continuation`. "
+ if _cut
+ else " in full. "
+ )
+ + "Answer from that; `retrieval`, `fallback_targets` and `candidates` "
+ "cover the wider question."
+ )
+ elif served:
summary = (
f"No synthesized prose ({reason}), but retrieval succeeded and this "
f"payload is usable: {served} ranked "
@@ -848,26 +1005,85 @@ def _degraded_payload(
"or search directly."
)
- return _with_candidates(
- {
- "answer": summary,
- "citations": [],
- "confidence": "low",
- "degraded": reason,
- "fallback_targets": fallback_targets,
- "retrieval": _serialize_hits(hits),
- "note": note,
- "_meta": {
- **_build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("low", len(hits)),
- repository=repository,
- targets=fallback_targets,
- ),
- "degraded": reason,
- },
- },
- resolved_pool if resolved_pool is not None else hits,
+ payload: dict = {
+ "answer": summary,
+ "citations": citations,
+ "confidence": "low",
+ "retrieval_quality": retrieval_quality,
+ "degraded": reason,
+ "fallback_targets": fallback_targets,
+ "retrieval": _serialize_hits(hits),
+ "note": note,
+ }
+ if symbol_bodies:
+ payload["symbol_bodies"] = symbol_bodies
+ payload["grounding"] = "symbol_body"
+ payload["next_action_hint"] = await _degraded_next_action(
+ symbol_bodies, ctx, repository, exclude_spec
+ )
+ payload["note"] += (
+ " symbol_bodies carries the live body of the symbol(s) you named, so "
+ "answer from that rather than re-reading the file."
+ )
+ payload["_meta"] = {
+ **_build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=_answer_hint(
+ "low",
+ len(hits),
+ degraded=reason,
+ retrieval_quality=retrieval_quality,
+ has_bodies=bool(symbol_bodies),
+ ),
+ repository=repository,
+ targets=[*citations, *fallback_targets],
+ ),
+ "degraded": reason,
+ }
+ return _with_candidates(payload, resolved_pool if resolved_pool is not None else hits)
+
+
+async def _degraded_next_action(
+ symbol_bodies: list[dict], ctx, repository, exclude_spec
+) -> str:
+ """The one next step a degraded payload with bodies in hand should name.
+
+ A whole body is a terminal answer, so say so rather than sending the caller
+ to Read a file it already holds. A cut body is not: name the continuation, or
+ a withheld symbol when one resolves.
+
+ Two filters on the withheld ids, both already established on the synthesised
+ path. A withheld entry carrying the served body's OWN name is the enclosing
+ symbol continuing past the cut, not something that never arrived, so it is
+ dropped and the ``continuation``, which fetches exactly the missing part,
+ is the pointer. And the ids come from a regex scanner over source lines, so
+ it can name something that is not a symbol at all: ``_first_resolvable_id``
+ keeps a fabricated id from becoming the next action here exactly as it does
+ there.
+ """
+ cut = next((b for b in symbol_bodies if b.get("continuation")), None)
+ if cut is None:
+ return (
+ f"Read the {symbol_bodies[0]['name']} body in symbol_bodies: it is the "
+ "full live source, so no follow-up call is needed."
+ )
+ hint_id = await _first_resolvable_id(
+ [
+ s["symbol_id"]
+ for s in (cut.get("withheld_symbols") or [])
+ if s.get("symbol_id") and s.get("name") != cut["name"]
+ ],
+ ctx,
+ repository,
+ exclude_spec,
+ )
+ return (
+ f"{cut['name']} was served through line {cut['lines'][1]}; call get_symbol "
+ + (
+ f"id='{hint_id}' for the withheld body."
+ if hint_id
+ else f"id='{cut['continuation']}' for the rest of it."
+ )
)
@@ -1536,17 +1752,20 @@ async def get_answer(
"get_answer running WITHOUT synthesis: no LLM provider resolvable "
"(set REPOWISE_PROVIDER + its API key, or any supported API key)."
)
- return _degraded_payload(
+ return await _degraded_payload(
reason="no-llm-provider",
note=(
"DEGRADED: no LLM provider configured (set REPOWISE_PROVIDER "
- "+ API key). "
- "Returning retrieval hits only — Read the listed files to answer."
+ "+ API key). Synthesis is what is missing here, not retrieval."
),
hits=hits,
fallback_targets=fallback_targets,
repository=repository,
t0=t0,
+ ctx=ctx,
+ question_ids=question_ids,
+ exclude_spec=exclude_spec,
+ agreement_dominant=agreement_dominant,
resolved_pool=resolved_pool,
)
@@ -1581,13 +1800,17 @@ async def get_answer(
repo_id=repo_id,
)
if failure_note is not None:
- return _degraded_payload(
+ return await _degraded_payload(
reason="synthesis-failed",
note=failure_note,
hits=hits,
fallback_targets=fallback_targets,
repository=repository,
t0=t0,
+ ctx=ctx,
+ question_ids=question_ids,
+ exclude_spec=exclude_spec,
+ agreement_dominant=agreement_dominant,
resolved_pool=resolved_pool,
)
@@ -1639,57 +1862,16 @@ async def get_answer(
# from get_symbol's `verified` contract. When the indexed body is longer
# than the hydrator's line cap, a `continuation` names the exact range
# read for the remainder (mirrors get_symbol).
- _body_candidates = _gather_body_candidates(hits, answer_text)
-
- symbol_bodies: list[dict] = []
- _seen_bodies: set[tuple[str, str]] = set()
- # True once a tier-0 body (the exact symbol the question named, resolved by
- # symbol anchoring) is inlined. Its full live body IS the ground truth, so a
- # response carrying it is content-grounded even when synthesis hedges — the
- # confidence gate below reads this to avoid the "low, go Read" label that
- # contradicts a payload already holding the answer (2026-07-11 dogfood).
- served_named_body = False
+ # ``served_named_body`` is True once a tier-0 body (the exact symbol the
+ # question named, resolved by symbol anchoring) is inlined. Its full live
+ # body IS the ground truth, so a response carrying it is content-grounded
+ # even when synthesis hedges. The confidence gate below reads this to avoid
+ # the "low, go Read" label that contradicts a payload already holding the
+ # answer (2026-07-11 dogfood).
repo_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else None
- for _tier, _kind_rank, start, path, s in _body_candidates:
- if len(symbol_bodies) >= _INLINE_BODY_MAX_SYMBOLS:
- break
- name = s["name"]
- if (path, name) in _seen_bodies:
- continue
- sym_end = s.get("end_line") or 0
- # Re-read a fuller body than the synthesis excerpt: this block is for
- # the agent, so a docstring-heavy def shouldn't spend its whole window
- # on docstring and truncate the logic the question asked about. Falls
- # back to the hydrator's excerpt if the re-read fails.
- body = _read_symbol_source(
- repo_root, path, start, sym_end, max_lines=_INLINE_BODY_MAX_LINES
- ) or s.get("source_excerpt")
- if not body:
- continue
- served = body.count("\n") + 1
- end_served = start + served - 1
- sym_end = sym_end or end_served
- entry: dict = {
- "path": path,
- "name": name,
- "lines": [start, end_served],
- "source": body,
- }
- if sym_end > end_served:
- entry["truncated"] = True
- entry["continuation"] = f"{path}:{end_served + 1}-{sym_end}"
- # Say WHAT was withheld, not just that something was. A bare
- # truncated flag plus a get_symbol pointer was followed zero times
- # across the agent runs measured, so the consumer needs the names in
- # hand to decide whether it is missing anything it cares about, and
- # to continue inside this tool rather than falling back to Read.
- withheld = withheld_definitions(repo_root, entry["continuation"])
- if withheld:
- entry["withheld_symbols"] = withheld
- symbol_bodies.append(entry)
- _seen_bodies.add((path, name))
- if _tier == 0:
- served_named_body = True
+ symbol_bodies, served_named_body = _build_symbol_bodies(
+ _gather_body_candidates(hits, answer_text), repo_root
+ )
# Compute confidence from the dominance ratio (top hit vs second hit).
# The dominance ratio is a more reliable separator than absolute BM25
@@ -1913,17 +2095,7 @@ async def get_answer(
if not dominant and not earn_high and confidence == "high":
confidence = "medium"
- # retrieval_quality is a separate signal from confidence. Where confidence
- # says "how much should you trust the synthesised text", retrieval_quality
- # says "how good was the retrieval that fed it". The agent uses confidence
- # to decide whether to re-read; retrieval_quality to decide whether to
- # call search_codebase again with a refined query.
- if _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR and _dominant_grade:
- retrieval_quality = "high"
- elif _dominant_grade:
- retrieval_quality = "partial"
- else:
- retrieval_quality = "weak"
+ retrieval_quality = _retrieval_quality(hits, agreement_dominant)
if hedged:
# Hedged answers: keep the retrieval payload lean but non-empty. The
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 54c889f51..9c248baca 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
@@ -356,10 +356,13 @@ def implicated_withheld_symbols(
prose happens not to name the symbol, which was 3 responses in 4 measured.
It is NOT what protects the no-LLM modes, and an earlier version of this
- docstring wrongly claimed it was. A keyless deployment returns
- ``_degraded_payload`` before ``symbol_bodies`` is built, so there is nothing
- here to gate; the homonym-union early return is the no-LLM path that does
- serve bodies, and it caps on truncation alone rather than calling this.
+ docstring wrongly claimed it was. Both of those paths now serve bodies:
+ ``_degraded_payload`` builds them from the question's anchors, and the
+ homonym-union early return inlines every definition, and neither calls this
+ gate. The union path caps on truncation alone. The degraded path does not gate
+ at all, because it has no synthesised claim to demote: its ``confidence`` is
+ already "low" for want of prose, and what a cut body costs it is said in the
+ payload instead, by the ``continuation`` on the entry and by the next action.
``body_continues`` entries sort first: a symbol whose body was cut by the
truncation boundary is the sharper failure, because the response has already
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.py
index 4bc27e6a6..51099d1b9 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
@@ -394,6 +394,14 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5
# must bypass. Secondarily, the note no longer advertises a symbol_id that
# resolves to nothing at all — a guard rather than an observed fix, since 0 of
# the 130 ids on the corpus were dead ends.
+# NOT bumped for the degraded-payload rework (`symbol_bodies` / `citations` /
+# `grounding` / `next_action_hint` / `retrieval_quality` on the no-provider and
+# synthesis-failed paths). Every one of those is a response-shape change, which
+# is normally exactly what this counter is for, but no cached row can carry the
+# old shape: the cache write is gated on `answer_text` and sits below both
+# degraded returns, so a degraded payload has never been written to it. The
+# synthesised shape is untouched. A bump here would invalidate every keyed
+# install's cache, and re-synthesis is real provider spend, for nothing.
_ANSWER_SCHEMA_VERSION = 15
# Hard TTL on answer-cache rows. Commit-based invalidation (the payload's
diff --git a/tests/unit/server/mcp/test_answer_degraded_evidence.py b/tests/unit/server/mcp/test_answer_degraded_evidence.py
new file mode 100644
index 000000000..857f8c4f6
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_degraded_evidence.py
@@ -0,0 +1,351 @@
+"""The degraded payload carries the evidence that never needed an LLM (D11).
+
+The provider check in ``get_answer`` returns above every line that builds
+``symbol_bodies``, so a keyless caller (ollama embeddings indexed, no LLM)
+received a ranked file list and nothing else. Measured on 26 paired questions
+(flask + django, both arms in one process, only the provider resolver patched):
+``symbol_bodies`` on 11 of 26 keyed answers and 2 of 26 keyless, and both
+survivors reached it through the homonym union path rather than this one.
+
+Nothing in that evidence needs a provider. Bodies are read live off disk at the
+indexed anchors. The one thing coupling them to synthesis was selection:
+``_gather_body_candidates`` matched candidate names against the answer text, so
+with no prose the candidate list was empty by construction. These tests pin the
+question-anchored selection that replaces it, and the guard that stops the
+resulting hint from advertising an id ``get_symbol`` cannot answer.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.server.mcp_server.tool_answer import answer as answer_mod
+from repowise.server.mcp_server.tool_answer.answer import _degraded_payload
+
+
+def _tree(tmp_path, *, body_lines: int = 6) -> SimpleNamespace:
+ """A one-file checkout with a `Flask` class the anchor points at."""
+ src = tmp_path / "src" / "flask"
+ src.mkdir(parents=True)
+ lines = ["class Flask:"] + [f" attr_{i} = {i}" for i in range(body_lines - 1)]
+ (src / "app.py").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return SimpleNamespace(path=str(tmp_path), session_factory=None)
+
+
+def _hits(*, end_line: int, name: str = "Flask") -> list[dict]:
+ return [
+ {
+ "target_path": "src/flask/app.py",
+ "title": "app",
+ "summary": "the app module",
+ "score": 4.0,
+ "_anchor_symbols": [
+ {
+ "name": name,
+ "kind": "class",
+ "start_line": 1,
+ "end_line": end_line,
+ }
+ ],
+ }
+ ]
+
+
+async def _degraded(ctx, hits, question_ids):
+ return await _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED: no LLM provider configured",
+ hits=hits,
+ fallback_targets=["src/flask/app.py"],
+ repository=None,
+ t0=0.0,
+ ctx=ctx,
+ question_ids=question_ids,
+ exclude_spec=None,
+ )
+
+
+async def test_degraded_serves_the_body_of_the_symbol_the_question_named(tmp_path):
+ """The named case from the keyless measurement: `Flask` served 0 bodies.
+
+ The keyed arm answered the same question with `src/flask/app.py` 105-225 in
+ hand. Selection is the only difference, and it is driven by the question.
+ """
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Flask"})
+
+ assert [b["name"] for b in payload["symbol_bodies"]] == ["Flask"]
+ assert "class Flask:" in payload["symbol_bodies"][0]["source"]
+ assert payload["grounding"] == "symbol_body"
+
+
+async def test_degraded_cites_the_files_its_bodies_came_from(tmp_path):
+ """`citations: []` was right for a payload with no source and wrong for this one.
+
+ A consumer that filters on non-empty citations discarded every keyless reply
+ (measured 2 of 26 non-empty, both from the union path).
+ """
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Flask"})
+
+ assert payload["citations"] == ["src/flask/app.py"]
+
+
+async def test_degraded_answer_points_at_the_body_not_at_the_file_list(tmp_path):
+ """The visible field must describe what the payload actually carries.
+
+ Telling a caller holding the full body to go open three paths is the
+ behaviour that sent the agent out of the tool in the first place.
+ """
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Flask"})
+
+ assert "symbol_bodies" in payload["answer"]
+ assert "Flask" in payload["answer"]
+ assert "Read the Flask body" in payload["next_action_hint"]
+
+
+async def test_degraded_selects_only_symbols_the_question_named(tmp_path):
+ """Question-anchored selection is a filter, not a dump of every anchor.
+
+ Without the name test this would inline whatever ranked first, which is the
+ fuzzy-hydration failure tier 0 exists to avoid.
+ """
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Blueprint"})
+
+ assert "symbol_bodies" not in payload
+ assert payload["citations"] == []
+ assert "next_action_hint" not in payload
+
+
+async def test_degraded_keeps_the_truncation_contract(tmp_path):
+ """Truncation / continuation is prose-independent, so it applies here too.
+
+ A body cut at the line cap must say so and name the exact range that fetches
+ the rest, exactly as the synthesised path does.
+ """
+ ctx = _tree(tmp_path, body_lines=200)
+ payload = await _degraded(ctx, _hits(end_line=200), {"Flask"})
+
+ entry = payload["symbol_bodies"][0]
+ assert entry["truncated"] is True
+ assert entry["continuation"] == "src/flask/app.py:122-200"
+ # The scanner reports the enclosing `Flask` across the cut. That symbol was
+ # served, it just continues, so the pointer is the range that fetches the
+ # remainder rather than a get_symbol call for a body already in hand.
+ assert "src/flask/app.py:122-200" in payload["next_action_hint"]
+
+
+async def test_degraded_hint_names_a_withheld_symbol_that_resolves(tmp_path, monkeypatch):
+ """When something really was not served, name it rather than the range."""
+ ctx = _tree(tmp_path, body_lines=200)
+ monkeypatch.setattr(
+ answer_mod,
+ "withheld_definitions",
+ lambda repo_root, cont: [
+ {"name": "attr_150", "line": 151, "symbol_id": "src/flask/app.py::attr_150"}
+ ],
+ )
+ payload = await _degraded(ctx, _hits(end_line=200), {"Flask"})
+
+ assert "src/flask/app.py::attr_150" in payload["next_action_hint"]
+
+
+async def test_degraded_hint_never_advertises_an_unresolvable_id(tmp_path, monkeypatch):
+ """The D5 guard still applies on this path.
+
+ ``withheld_symbols`` comes from a regex scan over source lines, so it can
+ name something that is not a symbol. A fabricated id must not become the
+ next action the payload tells the agent to take; the continuation, which is
+ a live range read, is the honest fallback.
+ """
+ ctx = _tree(tmp_path, body_lines=200)
+ monkeypatch.setattr(
+ answer_mod,
+ "withheld_definitions",
+ lambda repo_root, cont: [
+ {
+ "name": "NotARealSymbol",
+ "line": 130,
+ "symbol_id": "src/flask/app.py::NotARealSymbol",
+ }
+ ],
+ )
+ payload = await _degraded(ctx, _hits(end_line=200), {"Flask"})
+
+ hint = payload["next_action_hint"]
+ assert "NotARealSymbol" not in hint
+ assert "src/flask/app.py:122-200" in hint
+
+
+async def test_degraded_with_no_anchor_match_is_unchanged(tmp_path):
+ """The no-evidence degraded payload keeps its old shape.
+
+ This path is still reached (a question that names nothing indexed), and the
+ reply it gives (ranked hits plus where to look) is the right one. The fix
+ adds a branch; it must not rewrite the branch that was already correct.
+ """
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), set())
+
+ assert payload["confidence"] == "low"
+ assert payload["degraded"] == "no-llm-provider"
+ assert "ranked" in payload["answer"]
+ assert "symbol_bodies" not in payload
+
+
+# --- retrieval_quality on the degraded payload (D10) -----------------------
+#
+# 26 of 26 measured keyless payloads carried no `retrieval_quality` key at all,
+# so the only trust signal a caller had was `confidence: "low"`, which rates
+# synthesised prose that a degraded payload does not have. 11 of those 26 said
+# "low" while rank 1 was a file the keyed arm went on to cite. `confidence`
+# stays low on purpose; the retrieval gets rated separately, by the same rule
+# the synthesised path uses.
+
+
+def _scored(*scores: float) -> list[dict]:
+ return [
+ {"target_path": f"pkg/m{i}.py", "title": f"m{i}", "summary": "s", "score": s}
+ for i, s in enumerate(scores)
+ ]
+
+
+async def _quality(hits, **kw):
+ payload = await _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED",
+ hits=hits,
+ fallback_targets=["pkg/m0.py"],
+ repository=None,
+ t0=0.0,
+ **kw,
+ )
+ return payload["retrieval_quality"]
+
+
+async def test_degraded_rates_a_dominant_retrieval_high():
+ """A clear winner over the score floor is a good retrieval, LLM or not."""
+ assert await _quality(_scored(6.0, 1.0)) == "high"
+
+
+async def test_degraded_rates_a_dominant_but_weak_retrieval_partial():
+ """Dominant relative to its siblings, but under the floor: partial, not high."""
+ assert await _quality(_scored(1.0, 0.1)) == "partial"
+
+
+async def test_degraded_does_not_lift_a_genuinely_weak_retrieval():
+ """The control that must not move.
+
+ 14 of the 26 measured questions had retrieval that was weak in the KEYED arm
+ too. The reporter's literal fix, calling a degraded answer high-confidence,
+ would have promoted all of them, and a wrong "high" costs more trust than a
+ redundant second call saves. Ambiguous retrieval grades weak on both arms.
+ """
+ assert await _quality(_scored(6.0, 5.9)) == "weak"
+
+
+async def test_degraded_agreement_can_lift_but_the_floor_still_binds():
+ """Agreement is OR'd into dominance exactly as it is on the synthesised path."""
+ assert await _quality(_scored(6.0, 5.9), agreement_dominant=True) == "high"
+ assert await _quality(_scored(0.9, 0.8), agreement_dominant=True) == "partial"
+
+
+async def test_degraded_keeps_confidence_low():
+ """The label the reporter asked to raise stays where it is.
+
+ Confidence rates the synthesised text, and a degraded `answer` is assembled
+ boilerplate, byte-identical on 24 of the 26 measured questions. Telling an
+ agent to cite that is worse than the extra call it saves.
+ """
+ payload = await _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED",
+ hits=_scored(6.0, 1.0),
+ fallback_targets=["pkg/m0.py"],
+ repository=None,
+ t0=0.0,
+ )
+ assert payload["confidence"] == "low"
+ assert payload["retrieval_quality"] == "high"
+
+
+async def test_degraded_hint_says_what_is_missing_not_what_to_doubt():
+ """The `_meta` hint is the third push that made a keyless agent re-search.
+
+ On strong retrieval it must name the half that is actually absent (the
+ prose), not tell the caller to go verify the half that is fine.
+ """
+ payload = await _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED",
+ hits=_scored(6.0, 1.0),
+ fallback_targets=["pkg/m0.py"],
+ repository=None,
+ t0=0.0,
+ )
+ hint = payload["_meta"]["hint"]
+ assert "Synthesis is what is missing" in hint
+ assert "verify" not in hint
+
+
+async def test_degraded_hint_still_pushes_back_on_weak_retrieval():
+ """Weak retrieval keeps an honest hint; the fix must not flatter it."""
+ payload = await _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED",
+ hits=_scored(6.0, 5.9),
+ fallback_targets=["pkg/m0.py"],
+ repository=None,
+ t0=0.0,
+ )
+ assert "retrieval was weak" in payload["_meta"]["hint"]
+
+
+# --- the payload must not describe evidence it does not have ---------------
+
+
+async def test_degraded_answer_does_not_call_a_truncated_body_full(tmp_path):
+ """The entry two keys away says `truncated`; the sentence must agree with it."""
+ ctx = _tree(tmp_path, body_lines=200)
+ payload = await _degraded(ctx, _hits(end_line=200), {"Flask"})
+
+ assert payload["symbol_bodies"][0]["truncated"] is True
+ assert "in full" not in payload["answer"]
+ assert "continuation" in payload["answer"]
+
+
+async def test_degraded_answer_says_full_when_the_body_is_whole(tmp_path):
+ """The other direction: an uncut body should say so, or the hedge is noise."""
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Flask"})
+
+ assert "in full" in payload["answer"]
+
+
+async def test_degraded_note_and_hint_never_name_absent_symbol_bodies(tmp_path):
+ """Strong retrieval with nothing anchored is ordinary, not an error.
+
+ A prose question that names no identifier gets `retrieval_quality: "high"`
+ and no `symbol_bodies`. Pointing it at that key is the same misdirection the
+ change set out to remove.
+ """
+ ctx = _tree(tmp_path)
+ hits = _hits(end_line=6)
+ hits[0]["score"] = 6.0
+ payload = await _degraded(ctx, hits, {"Blueprint"})
+
+ assert "symbol_bodies" not in payload
+ assert payload["retrieval_quality"] == "high"
+ assert "symbol_bodies" not in payload["note"]
+ assert "symbol_bodies" not in payload["_meta"]["hint"]
+
+
+async def test_degraded_note_names_symbol_bodies_when_it_has_them(tmp_path):
+ """And does name it when the key is really there."""
+ ctx = _tree(tmp_path)
+ payload = await _degraded(ctx, _hits(end_line=6), {"Flask"})
+
+ assert "symbol_bodies" in payload["note"]
+ assert "symbol_bodies" in payload["_meta"]["hint"]
diff --git a/tests/unit/server/mcp/test_answer_early_return_candidates.py b/tests/unit/server/mcp/test_answer_early_return_candidates.py
index 958c02b99..fbd7be0ec 100644
--- a/tests/unit/server/mcp/test_answer_early_return_candidates.py
+++ b/tests/unit/server/mcp/test_answer_early_return_candidates.py
@@ -71,6 +71,10 @@ def test_no_post_retrieval_return_bypasses_the_candidates_helper():
if node.lineno <= pool_line:
continue # fires before retrieval; there is no pool to hand over
value = node.value
+ # ``_degraded_payload`` builds evidence off disk, so it is awaited; the
+ # covering call is the awaited expression, not the ``await`` node.
+ if isinstance(value, ast.Await):
+ value = value.value
if isinstance(value, ast.Name) and value.id == _MAINLINE_RETURN:
continue
covered = (
diff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
index 7d9bd42d3..9e11804ca 100644
--- a/tests/unit/server/mcp/test_answer_synthesis_timeout.py
+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
@@ -370,8 +370,8 @@ async def test_whitespace_only_completion_counts_as_empty():
HITS = [{"target_path": "pkg/mod.py", "title": "mod", "summary": "s", "score": 1.0}]
-def _payload(reason="synthesis-failed", note="DEGRADED: boom"):
- return _degraded_payload(
+async def _payload(reason="synthesis-failed", note="DEGRADED: boom"):
+ return await _degraded_payload(
reason=reason,
note=note,
hits=HITS,
@@ -381,20 +381,21 @@ def _payload(reason="synthesis-failed", note="DEGRADED: boom"):
)
-def test_degraded_reason_is_mirrored_into_meta():
+async def test_degraded_reason_is_mirrored_into_meta():
"""The failure path set only the top-level key, so _meta watchers missed it."""
- payload = _payload()
+ payload = await _payload()
assert payload["degraded"] == "synthesis-failed"
assert payload["_meta"]["degraded"] == "synthesis-failed"
@pytest.mark.parametrize("reason", ["no-llm-provider", "synthesis-failed"])
-def test_both_failure_modes_return_the_same_payload_shape(reason):
+async def test_both_failure_modes_return_the_same_payload_shape(reason):
"""An agent should not have to diff key sets to tell why synthesis is missing."""
- assert set(_payload(reason=reason)) == {
+ assert set(await _payload(reason=reason)) == {
"answer",
"citations",
"confidence",
+ "retrieval_quality",
"degraded",
"fallback_targets",
"retrieval",
@@ -404,23 +405,23 @@ def test_both_failure_modes_return_the_same_payload_shape(reason):
}
-def test_degraded_payload_still_hands_back_usable_retrieval():
+async def test_degraded_payload_still_hands_back_usable_retrieval():
"""Retrieval succeeded; losing it too would waste the work already done."""
- payload = _payload()
+ payload = await _payload()
assert payload["confidence"] == "low"
assert payload["fallback_targets"] == ["pkg/mod.py"]
assert len(payload["retrieval"]) == 1
assert payload["retrieval"][0]["path"] == "pkg/mod.py"
-def test_degraded_answer_describes_the_payload_instead_of_being_empty():
+async def test_degraded_answer_describes_the_payload_instead_of_being_empty():
"""An empty ``answer`` beside working retrieval reads as a failed call.
The field is the first thing a reader looks at, so leaving it blank while
``retrieval``/``candidates`` are populated invites throwing the whole
result away. It must name what survived and where to find it.
"""
- payload = _payload()
+ payload = await _payload()
answer = payload["answer"]
assert answer, "degraded answer must not be empty"
assert "synthesis-failed" in answer, "the reason belongs in the visible field"
@@ -428,14 +429,14 @@ def test_degraded_answer_describes_the_payload_instead_of_being_empty():
assert field in answer, f"{field} is populated but never mentioned"
-def test_degraded_answer_does_not_promise_hits_it_does_not_have():
+async def test_degraded_answer_does_not_promise_hits_it_does_not_have():
"""The other direction: no hits must not produce a 'this is usable' claim.
A sentence assembled from a template rather than from the payload would
advertise ranked hits on an empty retrieval, which is the failure mode that
would make the wording worse than the blank field it replaced.
"""
- payload = _degraded_payload(
+ payload = await _degraded_payload(
reason="no-llm-provider",
note="DEGRADED",
hits=[],