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): write the confidence note from the reason the grade was reached (#1605)
Raghav Chamadiya946a9dc69625
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 2a1454f99..2e373509f 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@@ -120,9 +120,9 @@ from repowise.server.mcp_server.tool_answer.confidence import (_grade_answer,_is_value_question,_retrieval_quality,+ dominance_reason,)from repowise.server.mcp_server.tool_answer.config import (- _DOMINANCE_RATIO,_GATED_EXCERPT_CHARS,_LEAN_HIGH_DROP_KEYS, # noqa: F401 — re-exported for tests that assert the key set_PAGE_EXCERPT_HITS,@@ -372,7 +372,9 @@ async def get_answer(whose named mechanism is absent from the retrieved source is downgradedto medium (the rationale may be conflated). Low confidence returnsbest_guesses with one-line justifications instead of an empty answer.- retrieval_quality separately rates the retrieval that fed synthesis.+ retrieval_quality separately rates the retrieval that fed synthesis; when+ it reads "weak" beside confidence=high, the note says what the confidence+ rests on instead of the ranking, and that is the claim to trust.When the answer names a function/method/class, ``symbol_bodies`` carriesits full live body — read that instead of a follow-up get_symbol.``episodes``, when present, is a dated fact recorded about this checkout@@ -554,27 +556,16 @@ async def get_answer(# outscores the rest). It no longer decides WHETHER to synthesize — under# the always-synthesize default, synthesis runs for every retrieval so# coverage matches a research assistant that answers every question. It now- # feeds the confidence grade as a CEILING (a non-dominant retrieval is- # "answered, but verify", never "high") and gates the ambiguous-retrieval- # evidence folded into the reply.- #- # Two-tier test: at high retrieval quality (both scores excellent) close- # ratios are expected, so use an absolute gap; at lower quality the ratio- # gate flags genuinely ambiguous retrievals. Coverage (fraction of query- # terms in the top hit) biases ranking but is intentionally NOT a gate:- # natural-language questions rarely have all content terms in one page, so a- # coverage threshold over-fires. Default dominant for a lone hit (nothing to- # be ambiguous against).+ # feeds the confidence grade (as the starting grade AND the ceiling), rates+ # the retrieval, and gates the ambiguous-retrieval evidence folded into the+ # reply. All of those read `dominance_reason`, where the two-tier test now+ # lives: a second copy of it inside the grade is what let one payload claim+ # the top result dominated and append the no-dominant-page caveat to the same+ # note. The grade takes the TIER rather than the bool, because the note it+ # writes may only quote the measurement that was actually made.always_synthesize = _always_synthesize()- dominant = True- if len(hits) >= 2:- top_score = hits[0].get("score", 0.0)- second_score = hits[1].get("score", 0.0) or 1e-9- if top_score >= 3.0:- dominant = (top_score - second_score) >= 0.5- else:- dominant = (top_score / second_score) >= _DOMINANCE_RATIO- dominant = dominant or agreement_dominant+ dominance = dominance_reason(hits, agreement_dominant=agreement_dominant)+ dominant = dominance is not Noneif not always_synthesize and not dominant:return _with_candidates(@@ -711,8 +702,7 @@ async def get_answer(citations=citations,symbol_bodies=symbol_bodies,served_named_body=served_named_body,- dominant=dominant,- agreement_dominant=agreement_dominant,+ dominance=dominance,)confidence = grade.confidenceretrieval_quality = _retrieval_quality(hits, agreement_dominant)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 9ecb853bd..971c42c88 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@@ -25,14 +25,18 @@ from repowise.server.mcp_server.tool_answer.config import (_AGREEMENT_RANK_GAP,_AGREEMENT_TOP_RANK_MAX,_CLAIM_SUPPORT_GATE_ENV,+ _DOMINANCE_ABS_GAP,+ _DOMINANCE_ABS_SCORE_FLOOR,_DOMINANCE_RATIO,_EARN_HIGH_GROUNDING_ENV,+ _EARN_HIGH_ON_WEAK_RETRIEVAL_ENV,_ENRICH_TOP_N_HITS,_HEDGE_MARKERS,_HIGH_CONFIDENCE_SCORE_FLOOR,_INLINE_BODY_MAX_LINES,_SYMBOL_AGREEMENT_TOP_RANK_MAX,_flag_on,+ _opt_in,)from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question@@ -416,10 +420,11 @@ def implicated_withheld_symbols(def _top_two_score_ratio(hits: list[dict]) -> float:"""The top hit's retrieval score over the runner-up's.- The separator both the confidence grade and :func:`_retrieval_quality` are- built on, kept in one place because they must agree on what "dominant"- measures. A lone hit has nothing to be ambiguous against, so it is infinitely- dominant; no hits at all is zero.+ Reporting only. :func:`dominance_reason` owns the dominance decision and does+ not call this; the grade carries the ratio out so a note can quote it, and+ a note may quote it only when ``"ratio"`` is the tier that actually fired.+ A lone hit has nothing to be ambiguous against, so it is infinitely dominant;+ no hits at all is zero."""if len(hits) >= 2:return hits[0].get("score", 0.0) / (hits[1].get("score", 0.0) or 1e-9)@@ -504,6 +509,62 @@ def _agreement_dominant(hits: list[dict], *, vector_leg_keyless: bool = False) -return False+def dominance_reason(hits: list[dict], *, agreement_dominant: bool = False) -> str | None:+ """WHICH test found the top hit dominant, or None if none did.++ The single owner of "did retrieval clearly point at ONE page". Callers that+ only need the verdict take :func:`is_dominant`; the note builder needs the+ reason, because the three tiers measure different things and a note that+ quotes the wrong one refutes itself.++ * ``"ratio"`` — the top hit outscores the runner-up by a clear multiple.+ * ``"gap"`` — where both scores are excellent a close ratio is expected+ (6.0 vs 5.4 is a clear win reading as 1.11x), so dominance is an absolute+ gap and the RATIO IS NOT THE MEASUREMENT. Quoting it as one prints a near+ tie as the reason for confidence.+ * ``"agreement"`` — both retrievers independently rank this page top. RRF+ compresses fused scores, so this fires around 1.02x; the ratio is not the+ measurement here either.+ * ``"sole_hit"`` — one hit, nothing to be ambiguous against.++ Coverage (fraction of query terms in the top hit) biases ranking but is+ deliberately NOT a gate: natural-language questions rarely put every content+ term in one page, so a coverage threshold over-fires.++ No hits at all is not dominance: there is no page for the claim to be about,+ and rating that dominant would grade an empty retrieval as merely+ under-scoring. Unreachable from the synthesised path, which returns early on+ empty hits, but the degraded path rates its retrieval through here too.+ """+ if not hits:+ return None+ if len(hits) < 2:+ return "sole_hit"+ top_score = hits[0].get("score", 0.0)+ second_score = hits[1].get("score", 0.0) or 1e-9+ if top_score >= _DOMINANCE_ABS_SCORE_FLOOR:+ if (top_score - second_score) >= _DOMINANCE_ABS_GAP:+ return "gap"+ elif (top_score / second_score) >= _DOMINANCE_RATIO:+ return "ratio"+ return "agreement" if agreement_dominant else None+++def is_dominant(hits: list[dict], *, agreement_dominant: bool = False) -> bool:+ """Did retrieval clearly point at ONE page? See :func:`dominance_reason`.++ Three callers ask it and they must not disagree: the confidence grade uses it+ as both the starting grade and the ceiling, :func:`_retrieval_quality` rates+ the retrieval from it, and the payload folds in the ambiguous-retrieval+ evidence on it. It used to be computed twice — a two-tier version in the+ answer module and a ratio-only re-derivation inside the grade — and the two+ disagree in a real window (a 6.0/5.4 pair is dominant by gap and not by+ ratio), which is how one payload came to assert that the top result "clearly+ dominates" while appending the caveat that retrieval found no dominant page.+ """+ return dominance_reason(hits, agreement_dominant=agreement_dominant) is not None++def _retrieval_quality(hits: list[dict], agreement_dominant: bool) -> str:"""Rate the retrieval, independently of the text it fed.@@ -512,10 +573,14 @@ def _retrieval_quality(hits: list[dict], agreement_dominant: bool) -> str:``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 oneor the field is worth less than nothing.++ Reads :func:`is_dominant` rather than re-deriving the ratio, so "weak" means+ exactly "not dominant" — the same fact the confidence ceiling and the+ ambiguity caveat are keyed on. Without that the payload could rate retrieval+ weak and treat it as dominant in the same breath."""- ratio = _top_two_score_ratio(hits)top_score = hits[0].get("score", 0.0) if hits else 0.0- dominant_grade = ratio >= _DOMINANCE_RATIO or agreement_dominant+ dominant_grade = is_dominant(hits, agreement_dominant=agreement_dominant)if dominant_grade and top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:return "high"return "partial" if dominant_grade else "weak"@@ -567,6 +632,15 @@ class _Grade(NamedTuple):hedged: boolratio: floattop_score: float+ second_score: float+ #: Why the grade is "high", or None when it is not: a+ #: :func:`dominance_reason` tier, or "symbol_body" / "grounding". The note is+ #: written from this rather than from the bare label, because the reasons+ #: license different sentences — only "ratio" may quote the ratio as the+ #: measurement, and only a dominance tier or "symbol_body" may tell the agent+ #: not to re-read. Writing one reason for every high is how a payload came to+ #: quote a 1.00x dominance ratio, a tie, as the reason it was confident.+ high_reason: str | Noneungrounded_values: list[str]frame_unsupported: list[str]exclusivity_over_truncated: bool@@ -584,8 +658,7 @@ def _grade_answer(citations: list[str],symbol_bodies: list[dict],served_named_body: bool,- dominant: bool,- agreement_dominant: bool,+ dominance: str | None,) -> _Grade:"""Grade the synthesised answer through the gate cascade, in order.@@ -594,41 +667,53 @@ def _grade_answer(that one response cannot be pushed two levels for one problem. Read themas a list of reasons not to trust the prose: the order is the order theywere added, and each comment says which failure it was built to catch.++ ``dominance`` is :func:`dominance_reason`'s verdict, computed once by the+ caller and used here for the starting grade, the ceiling, and the reason the+ note is written from. A bare bool used to be accepted for the ceiling alone+ while the starting grade re-derived a ratio-only version of the same+ question, so a retrieval the rest of the pipeline treated as dominant could+ start the cascade as if it were not."""- # Compute confidence from the dominance ratio (top hit vs second hit).- # The dominance ratio is a more reliable separator than absolute BM25- # thresholds, which tend to label most retrievals "high" indiscriminately.+ dominant = dominance is not None_ratio = _top_two_score_ratio(hits)_top_score = hits[0].get("score", 0.0) if hits else 0.0- # Agreement lifts the RRF-compressed ratio: a consensus top hit (both- # retrievers rank it at/near #1) grades dominant even though its fused- # score barely outscores the runner-up. The score floor still applies, and- # is naturally cleared — a rank-0-in-both hit scores well above it.- _dominant_grade = _ratio >= _DOMINANCE_RATIO or agreement_dominant-- # Strong answer-grounding can EARN "high" on a NON-dominant retrieval. RRF- # compresses sibling scores, so a rank-1 hit buried in a cluster of related- # files never "dominates" numerically and was capped at medium even when the- # synthesised answer is fully grounded in served source. Earn high when- # EITHER the question's named symbol body is served in-hand (tier-0 anchor),- # OR every distinctive mechanism term the answer names is grounded in the- # retrieval corpus AND a cited hit carries real symbol bodies. Conservative:- # a single ungrounded mechanism term disqualifies (that is the fabricated-- # mechanism signal), and the score floor still applies — this lifts- # non-dominant *well grounded* answers, never weakly-retrieved ones. The- # demotion gates below (hedge, value, claim-support) still pull an earned+ _second_score = hits[1].get("score", 0.0) if len(hits) >= 2 else 0.0++ # A response can EARN "high" on a NON-dominant retrieval, by two routes that+ # are NOT equally good and so are tracked apart. Both need the score floor,+ # and a retrieval that clears the floor and dominates is already high — so+ # earning fires exactly when `retrieval_quality` reads "weak".+ #+ # * `earned_body` — the question named a symbol and its live body is inlined+ # in this payload. Resolved by exact name, not by ranking, so how ambiguous+ # the ranking was does not bear on it, and "do not re-read the source" is+ # literally true: the source is in the response. (An oversized body can+ # still arrive cut, which is why the note it writes says "the live body"+ # rather than "the full body" and lets the truncation tail speak.)+ # * `earned_grounding` — every distinctive mechanism term the answer names+ # appears in the material it was shown, and a cited hit carries real symbol+ # bodies. That is evidence the model did not FABRICATE a mechanism. It is+ # not evidence retrieval found the right page, which is the only thing in+ # doubt on a weak retrieval — an answer can be perfectly consistent with+ # the wrong file. Off by default; see the env flag's comment.+ #+ # The demotion gates below (hedge, value, claim-support) still pull an earned# high back down.- earn_high = False+ earned_body = False+ earned_grounding = Falseif _flag_on(_EARN_HIGH_GROUNDING_ENV) and _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:- _cited = set(citations)- _cited_has_body = any(h.get("symbols") for h in hits if h.get("target_path") in _cited)- _fu, _fg = _frame_term_grounding(answer_text, question, hits)- grounding_strong = _cited_has_body and _fg >= 1 and not _fu- earn_high = served_named_body or grounding_strong-- if (_dominant_grade or earn_high) and _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:+ earned_body = served_named_body+ if _opt_in(_EARN_HIGH_ON_WEAK_RETRIEVAL_ENV):+ _cited = set(citations)+ _cited_has_body = any(h.get("symbols") for h in hits if h.get("target_path") in _cited)+ _fu, _fg = _frame_term_grounding(answer_text, question, hits)+ earned_grounding = _cited_has_body and _fg >= 1 and not _fu+ earn_high = earned_body or earned_grounding++ if (dominant or earn_high) and _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:confidence = "high"- elif _dominant_grade:+ elif dominant:# Dominant but weak — the right file relative to its siblings, but# the signal isn't strong enough to trust the synthesised answer# without verification. Downgrade so the consumer Reads the source.@@ -779,14 +864,29 @@ def _grade_answer(# if every gate passed. (A non-dominant retrieval already scores <high via# the ratio, so this is usually a no-op; it is explicit so the# always-synthesize contract — "answered, but verify" — is self-documenting.)- # Exception: an answer that EARNED high via strong grounding (named symbol- # body in-hand, or every mechanism term grounded in a cited body) is not- # "cite without verifying" — the source IS in the payload — so the- # non-dominance ceiling does not apply to it.+ # Exception: an answer that EARNED high is not "cite without verifying". By+ # default that means only the served-body route — the source IS in the+ # payload — since grounded PROSE is merely consistent with material this same+ # retrieval says may be the wrong material, and an agent reads "high" as+ # permission to skip the verification that would catch precisely that. The+ # exemption is written against `earn_high` rather than `earned_body` so the+ # opt-in genuinely restores the old behaviour instead of being overruled two+ # lines later.if not dominant and not earn_high and confidence == "high":confidence = "medium"++ # Name the reason while the evidence for it is still in scope. The dominance+ # tier first, and the specific tier rather than "dominant": the gap and+ # agreement tiers fire at ratios near 1.0, so a note quoting the ratio as the+ # measurement would print a near tie as its own justification — the reported+ # defect, one layer down.+ high_reason = None+ if confidence == "high":+ high_reason = dominance or ("symbol_body" if earned_body else "grounding")return _Grade(confidence=confidence,+ high_reason=high_reason,+ second_score=_second_score,hedged=hedged,ratio=_ratio,top_score=_top_score,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 62ec72411..9c0a40ce1 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@@ -162,16 +162,27 @@ _KIND_PRIORITY = {"class": 0, "interface": 0, "function": 1, "method": 2}# cache-write cost on follow-up turns._MAX_SYMBOL_DOC_CHARS = 120-# Confidence gate for synthesis. When the top retrieval hit is NOT clearly-# dominant relative to the second-best hit, skip LLM synthesis and return-# ranked snippets only. This forces the agent to ground in source rather than-# trust a possibly-wrong frame. Generic, repo-agnostic, no question parsing.-# Failure modes addressed:-# (a) wrong-target retrieval where top-1 and top-2 are both plausible;-# (b) synthesis hallucination on tangential top hits.+# The lower tier of the dominance test: how far the top hit must outscore the+# runner-up, as a multiple, when neither score is strong enough for the absolute+# gap below. Generic, repo-agnostic, no question parsing. The failure modes it+# addresses are (a) wrong-target retrieval where top-1 and top-2 are both+# plausible and (b) synthesis hallucination on tangential top hits.+#+# It no longer decides WHETHER to synthesise — under the always-synthesize+# default that gate is gone, and dominance feeds the confidence grade, the+# retrieval rating and the ambiguity caveat instead._DOMINANCE_RATIO = 1.2_COVERAGE_THRESHOLD = 0.66+# The second tier of the dominance test. Where both scores are excellent a close+# ratio is expected — 6.0 vs 5.4 is a clear win that reads as 1.11x — so above+# the score floor below, dominance is measured as an absolute gap instead. Held+# here beside the ratio because ``is_dominant`` is the sole reader of all three;+# they were inline in the answer module while a second, ratio-only copy of the+# test lived in the grade, and the two disagreed in exactly this window.+_DOMINANCE_ABS_SCORE_FLOOR = 3.0+_DOMINANCE_ABS_GAP = 0.5+# Agreement-aware dominance. The dominance ratio above is computed on# RRF-fused scores, and RRF *compresses*: a page both retrievers rank #1# (2/60) barely outscores one they rank #2 (2/61) — ratio ~1.017, far below@@ -436,7 +447,13 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5# v13/v14 cap confidence on that flag, so a cached row can carry a `medium`# this version would not produce. Cached pre-v16 rows carry all three, so they# must bypass.-_ANSWER_SCHEMA_VERSION = 16+# v17: `confidence` itself moves. Dominance now has one owner, so a retrieval+# with a strong absolute gap but a compressed ratio grades high where a cached+# v16 row holds medium; and answer-grounding no longer earns high over a weak+# retrieval, so the reverse case is cached too. The note is rewritten from the+# reason the grade was reached rather than from the bare fact that it is high,+# so v16 rows carry a note this version would not produce.+_ANSWER_SCHEMA_VERSION = 17# Hard TTL on answer-cache rows. Commit-based invalidation (the payload's# stamped ``_indexed_commit`` vs the repo's current head) is the primary@@ -549,9 +566,27 @@ _UNION_MECHANISM_DEFER_ENV = "REPOWISE_ANSWER_UNION_MECHANISM_DEFER"# Require the answer's central named mechanism symbol to be grounded in served# source before a mechanism/how answer may be stamped high._CLAIM_SUPPORT_GATE_ENV = "REPOWISE_ANSWER_CLAIM_SUPPORT_GATE"-# Let strong answer-grounding earn "high" on a non-dominant retrieval (a rank-1-# hit buried in a sibling cluster), not only a clear numeric dominance margin.+# Let a response earn "high" on a non-dominant retrieval — the served body of+# the symbol the question named — rather than only a clear dominance margin._EARN_HIGH_GROUNDING_ENV = "REPOWISE_ANSWER_EARN_HIGH_GROUNDING"+# The other half of that lift, and OFF by default: earning high from the prose+# being consistent with the material it was shown.+#+# It is only ever reachable over a weak retrieval. Earning high requires the top+# score to clear the confidence floor, and a retrieval that clears the floor and+# dominates is already high without earning anything — so the lift fires exactly+# when ``retrieval_quality`` reads "weak", which is the pipeline reporting that+# it may have surfaced the wrong material. Frame-term grounding cannot answer+# that: it checks that the answer named nothing retrieval did not show it, which+# is evidence against fabrication and says nothing about whether the material+# was the right material. The served-body lift above CAN answer it — that body+# is exact-name resolution rather than ranking, and the source is in the payload+# — which is why the two are split rather than capped together.+#+# On for the previous behaviour, where grounded prose over a tied top pair+# returned high with "do not re-read the source unless a specific detail is+# missing".+_EARN_HIGH_ON_WEAK_RETRIEVAL_ENV = "REPOWISE_ANSWER_EARN_HIGH_ON_WEAK_RETRIEVAL"# Test/eval hook: skip the answer cache entirely (both read and write). The# cache keys on (repo, question) only — not on feature-flag state — so an A/Bdiff --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 318c34f6e..6cbc709bb 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@@ -508,14 +508,27 @@ async def build_synthesized_payload(_cr = _drop_already_surfaced(_cr, symbol_bodies, quotes)if _cr:payload["code_rationale"] = _cr- _caveat = (- "Retrieval was ambiguous (no single dominant page), so this was "- f"synthesized across several candidates and held at {confidence} "- "confidence — verify against best_guesses"- + (" or the code_rationale comments." if payload.get("code_rationale") else ".")- )+ if grade.high_reason == "symbol_body":+ # Held at high over an ambiguous ranking because the body of the+ # symbol the question named is inlined below. Telling the agent to+ # verify against best_guesses would send it to the ranked pages the+ # confidence deliberately does not rest on, so the caveat scopes the+ # doubt to the page choice and leaves the served body alone.+ _caveat = (+ "Retrieval was ambiguous (no single dominant page), so the "+ "candidates listed are a ranking, not a finding — the confidence "+ "above rests on the symbol body served in this payload, not on "+ "which page ranked first."+ )+ else:+ _caveat = (+ "Retrieval was ambiguous (no single dominant page), so this was "+ f"synthesized across several candidates and held at {confidence} "+ "confidence — verify against best_guesses"+ + (" or the code_rationale comments." if payload.get("code_rationale") else ".")+ )payload["note"] = (payload["note"] + " " + _caveat) if payload.get("note") else _caveat- if payload.get("best_guesses"):+ if payload.get("best_guesses") and grade.high_reason != "symbol_body":payload.setdefault("next_action_hint",f"Verify against {payload['best_guesses'][0]['file']} — it scored "@@ -594,6 +607,61 @@ async def _hedged_payload(return payload+def _high_confidence_note(grade: _Grade, tail: str) -> str:+ """The high-confidence note, written from the reason the grade was reached.++ Each branch quotes the measurement its own tier made and no other. The ratio+ is a valid justification only under ``"ratio"``: the gap tier exists BECAUSE+ the ratio is uninformative where both scores are strong (6.0 vs 5.4 reads as+ 1.11x), and fusion compresses agreement pairs to about 1.02x, so quoting it+ under either would print a near tie as the reason for confidence.++ Only the dominance tiers and ``"symbol_body"`` reach *tail*, which is what+ tells the agent it need not re-read the source. ``"grounding"`` never does:+ it establishes the prose is not fabricated, which is not a claim about+ whether the page it describes is the right one.+ """+ if grade.high_reason == "symbol_body":+ return (+ "High confidence: symbol_bodies below carries the live body of the "+ "symbol you named, so the answer rests on source in this payload "+ "rather than on the ranking, which was ambiguous (top score "+ f"{grade.top_score:.2f}, runner-up {grade.second_score:.2f}). " + tail+ )+ if grade.high_reason == "grounding":+ return (+ "High confidence: every mechanism the answer names appears in the "+ "cited source, so the prose is not fabricated. Retrieval was still "+ f"ambiguous (top score {grade.top_score:.2f}, runner-up "+ f"{grade.second_score:.2f}), so verify which file answers the "+ "question rather than the wording of the answer."+ )+ if grade.high_reason == "gap":+ return (+ "High confidence: the top retrieval result clearly dominates, by "+ f"{grade.top_score - grade.second_score:.2f} points over the "+ f"runner-up (top score {grade.top_score:.2f}). Both scores are "+ "strong, so the gap is the measure here and not the ratio. " + tail+ )+ if grade.high_reason == "agreement":+ return (+ "High confidence: both retrievers independently rank this page at "+ "the top, which is the measure here — fused scores are compressed, "+ f"so the {grade.ratio:.2f}x ratio understates the agreement "+ f"(top score {grade.top_score:.2f}). " + tail+ )+ if grade.high_reason == "sole_hit":+ return (+ "High confidence: one page matched, so there was no competing "+ f"candidate to be ambiguous against (top score {grade.top_score:.2f}). "+ + tail+ )+ return (+ "High confidence: top retrieval result clearly dominates "+ f"(dominance ratio {grade.ratio:.2f}x, top score {grade.top_score:.2f}). " + tail+ )++async def _graded_payload(*,question: str,@@ -642,6 +710,14 @@ async def _graded_payload(payload["quotes"] = quotesif symbol_bodies:payload["symbol_bodies"] = symbol_bodies+ if grade.high_reason == "symbol_body":+ # Same value the hedged path already emits for the same situation: what+ # this answer rests on is the served body, not the ranking. It also has+ # to be set for `_apply_lean_high` to see it — that strips `symbol_bodies`+ # from a high-confidence payload unless `grounding` marks it as the+ # evidence, and the note below points the agent straight at the block it+ # would otherwise have removed.+ payload["grounding"] = "symbol_body"if grade.ungrounded_values:payload["note"] = (f"Value-grounding gate: the answer asserts {grade.ungrounded_values} "@@ -733,11 +809,13 @@ async def _graded_payload(else "Some cited bodies were truncated; see ""symbol_bodies[].withheld_symbols for what was not served.")- payload["note"] = (- "High confidence: top retrieval result clearly dominates "- f"(dominance ratio {grade.ratio:.2f}x, top score {grade.top_score:.2f}). "- + _tail- )+ # Say which test earned the grade, and quote only the measurement that+ # test actually made. Writing one sentence for every high is how a+ # response came to quote "clearly dominates (dominance ratio 1.00x)" — a+ # tie — as its own justification, beside the caveat that no page+ # dominated. The gap and agreement tiers fire at ratios near 1.0 too, so+ # naming them without their own numbers would reproduce it exactly.+ payload["note"] = _high_confidence_note(grade, _tail)# Concept anchoring put a comment-justified file at the top, so synthesis may# now run high — but the agent asked a "why is X = <number>" question and thediff --git a/tests/unit/server/mcp/test_answer_agreement.py b/tests/unit/server/mcp/test_answer_agreement.pyindex 7318c21a3..0d0534958 100644--- a/tests/unit/server/mcp/test_answer_agreement.py+++ b/tests/unit/server/mcp/test_answer_agreement.py@@ -191,22 +191,42 @@ async def test_demotion_gate_still_fires_on_agreement_hit(setup_mcp, monkeypatch@pytest.mark.asyncio-async def test_earn_high_via_grounding_lifts_nondominant(setup_mcp, monkeypatch):- """A NON-dominant retrieval (no agreement, ratio < 1.2) whose answer is fully- grounded — cites a hit carrying the named symbol body and introduces no- ungrounded mechanism term — EARNS high. Flag off → medium."""+async def test_grounding_earns_high_only_when_opted_in(setup_mcp, monkeypatch):+ """A fully-grounded answer over a NON-dominant retrieval no longer earns high.++ The lift is only ever reachable over a WEAK retrieval — it needs the top score+ to clear the confidence floor, and a retrieval that clears the floor and+ dominates is already high — so this fires exactly where the pipeline is+ reporting it may have surfaced the wrong material. Frame-term grounding+ cannot speak to that: it establishes the answer named nothing retrieval did+ not show it, which rules out a fabricated mechanism and not a well-described+ wrong file. `high` tells the agent to cite without re-reading, so the two+ cannot both hold.++ Opt back in with REPOWISE_ANSWER_EARN_HIGH_ON_WEAK_RETRIEVAL for the previous+ behaviour, and then the note must say the grounding is what it rests on+ rather than claiming a dominance that was never measured.+ """import repowise.server.mcp_server.tool_answer.answer as answer_modfrom repowise.server.mcp_server import get_answermonkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "on")- # No agreement lift (top found by one retriever); the only path to high is- # the grounding-earn.+ # No agreement lift (top found by one retriever), so grounding is the only+ # route to high under test.monkeypatch.setenv("REPOWISE_ANSWER_AGREEMENT_CONFIDENCE", "off")_patch_agreement_pipeline(monkeypatch, answer_mod, top_both=False)_patch_provider(monkeypatch, answer_mod, _GOOD_ANSWER)result = await get_answer("how are large uploads handled")- assert result["confidence"] == "high"+ assert result["retrieval_quality"] == "weak"+ assert result["confidence"] == "medium", "grounded prose does not out-vote weak retrieval"++ monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_ON_WEAK_RETRIEVAL", "on")+ result_on = await get_answer("how are large uploads handled")+ assert result_on["confidence"] == "high"+ assert "clearly dominates" not in result_on["note"], (+ "the lift did not measure dominance, so the note must not claim it"+ )monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_GROUNDING", "off")result_off = await get_answer("how are large uploads handled")diff --git a/tests/unit/server/mcp/test_answer_confidence_reasons.py b/tests/unit/server/mcp/test_answer_confidence_reasons.pynew file mode 100644index 000000000..330f3f35b--- /dev/null+++ b/tests/unit/server/mcp/test_answer_confidence_reasons.py@@ -0,0 +1,286 @@+"""The reason a get_answer response is `high`, and whether it survives weak retrieval.++Three claims, all about the same seam between the confidence grade and the note+the payload writes from it:++ * **One owner for dominance.** ``answer.py`` rated retrieval with a two-tier+ test (absolute gap above a strong top score, ratio below it) while the grade+ cascade re-derived a ratio-only version. The two disagreed, so a retrieval+ the pipeline treats as dominant everywhere else could still be graded as if+ it were not.+ * **The note must not claim a reason it did not check.** "Top retrieval result+ clearly dominates (dominance ratio 1.00x)" was written on the bare fact that+ confidence was high, and a ratio of 1.00 is a tie. Printed beside the+ ambiguous-retrieval caveat it produced a payload that asserted dominance and+ denied it in the same breath.+ * **Grounding does not out-vote weak retrieval; a served body does.** Both+ routes to an earned high used to bypass the non-dominance ceiling. Only one+ of them should: a question-named symbol body is live source sitting in the+ payload, so the ranking's ambiguity says nothing about it, whereas+ "every mechanism term the answer names appears in what it was shown" only+ measures the prose against material whose selection is exactly what+ ``retrieval_quality: weak`` reports as ambiguous.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++# A symbol name distinctive enough for _distinctive_terms (underscore), so an+# answer that names it has a GROUNDED mechanism term and can earn high through+# the grounding route. Deliberately absent from every question below: a term the+# question itself supplied is excluded from the grounding count.+_SYMBOL = "run_sweep"+++def _patch_pipeline(monkeypatch, answer_mod, scores, *, with_symbols=True, matched=False):+ """Two file-page hits at *scores*, the top one carrying a hydrated symbol."""++ async def _fake_retrieve(question, ctx):+ return [+ {"page_id": "file_page:pkg/alpha/one.py", "score": scores[0], "_sources": {"fts"}},+ {"page_id": "file_page:pkg/alpha/two.py", "score": scores[1], "_sources": {"fts"}},+ ]++ async def _fake_hydrate(hits, ctx, *, scope=None):+ for i, h in enumerate(hits):+ h["target_path"] = h["page_id"].removeprefix("file_page:")+ h["title"] = h["target_path"]+ h["summary"] = "Module summary for the page. " * 4+ h["snippet"] = ""+ h["page_type"] = "file_page"+ if with_symbols and i == 0:+ h["symbols"] = [+ {+ "name": _SYMBOL,+ "kind": "function",+ "signature": f"def {_SYMBOL}()",+ "docstring": "",+ "start_line": 1,+ "end_line": 3,+ **({"_matched": True} if matched else {}),+ }+ ]+ return hits++ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)+++def _patch_provider(monkeypatch, answer_mod, content):+ class _Provider:+ provider_name = "mock"+ model_name = "mock-1"++ async def generate(self, **kwargs):+ return SimpleNamespace(content=content)++ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: _Provider())+++# Names the top hit (so it is cited) and one grounded mechanism term (so the+# grounding route to an earned high is open).+_GROUNDED_ANSWER = f"The `{_SYMBOL}` helper drives it (pkg/alpha/one.py)."+# Same citation, no distinctive term at all — the grounding route stays shut, so+# only the dominance route can produce a high.+_PLAIN_ANSWER = "The module drives it (pkg/alpha/one.py)."+_QUESTION = "how does the alpha module clear out stale rows"+++async def test_ambiguous_retrieval_never_reads_as_dominant(setup_mcp, monkeypatch):+ """The reported defect: one payload claiming dominance and ambiguity at once.++ A tied pair (ratio 1.00x) above the score floor, answered with fully grounded+ prose. Driven with the weak-retrieval opt-in ON so the grade still reaches+ high, which is what puts the note on the branch that produced the report —+ testing this at the default `medium` would prove nothing about the note,+ since a non-high grade never enters that branch at all.+ """+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_ON_WEAK_RETRIEVAL", "on")+ _patch_pipeline(monkeypatch, answer_mod, scores=(2.91, 2.91))+ _patch_provider(monkeypatch, answer_mod, _GROUNDED_ANSWER)++ result = await get_answer(_QUESTION)+ note = result.get("note") or ""+ assert result["confidence"] == "high", "the opt-in must actually reach the high branch"+ assert result["retrieval_quality"] == "weak", "a tied top pair is ambiguous retrieval"+ assert not ("dominates" in note and "ambiguous" in note), (+ f"note asserts dominance and ambiguity together: {note!r}"+ )+ assert "dominance ratio 1.00x" not in note, "a 1.00x ratio is a tie, not dominance"+ assert "do not re-read the source" not in note+++async def test_grounded_prose_does_not_earn_high_on_weak_retrieval(setup_mcp, monkeypatch):+ """Grounding measures the prose against the material, not the material's fit.++ On weak retrieval the answer can be perfectly consistent with everything it+ was shown and still be about the wrong page, so this must not reach the+ "cite this; do not re-read the source" contract.+ """+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_pipeline(monkeypatch, answer_mod, scores=(2.91, 2.91))+ _patch_provider(monkeypatch, answer_mod, _GROUNDED_ANSWER)++ result = await get_answer(_QUESTION)+ assert result["retrieval_quality"] == "weak"+ assert result["confidence"] == "medium", (+ "answer-grounding alone must not out-vote an ambiguous retrieval"+ )+ assert "do not re-read the source" not in (result.get("note") or "")+++async def test_dominance_grade_honours_the_absolute_gap_tier(setup_mcp, monkeypatch):+ """One owner: the grade uses the same dominance test the pipeline does.++ Fusion scales these to 5.60 / 5.04, which is dominant under the two-tier rule+ (top >= 3.0, gap 0.56 >= 0.5) but NOT under a bare ratio (1.11 < 1.2). The+ grade re-derived the ratio-only version, so this retrieval was capped at+ medium while the same numbers were treated as dominant for the caveat and the+ ceiling — the two answering differently about one retrieval.++ The plain answer keeps the grounding route shut, so dominance is the only+ thing under test.+ """+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_pipeline(monkeypatch, answer_mod, scores=(8.0, 7.2))+ _patch_provider(monkeypatch, answer_mod, _PLAIN_ANSWER)++ result = await get_answer(_QUESTION)+ assert result["confidence"] == "high"+ assert "ambiguous" not in (result.get("note") or ""), "no caveat on a dominant retrieval"+ assert "clearly dominates" in result["note"]+++async def test_the_gap_tier_does_not_quote_the_ratio_it_did_not_use(setup_mcp, monkeypatch):+ """The same self-refuting number, one tier down.++ The gap tier exists precisely because the ratio is uninformative when both+ scores are strong, so a note that earns high by gap and then quotes "clearly+ dominates (dominance ratio 1.11x)" is citing the measurement it declined to+ make. Report the gap, which is what was measured.+ """+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_pipeline(monkeypatch, answer_mod, scores=(8.0, 7.2))+ _patch_provider(monkeypatch, answer_mod, _PLAIN_ANSWER)++ result = await get_answer(_QUESTION)+ note = result["note"]+ assert result["confidence"] == "high"+ assert "dominance ratio" not in note, "the ratio is not what this tier measured"+ assert "points over the runner-up" in note+++async def test_agreement_note_says_agreement_not_a_compressed_ratio(setup_mcp, monkeypatch):+ """Fusion compresses agreeing pairs to roughly 1.02x, so the ratio is again+ not the measurement — the two retrievers concurring is."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ async def _fake_retrieve(question, ctx):+ import repowise.server.mcp_server._answer_pipeline as _pipeline++ _pipeline.begin_leg_record()+ return [+ {+ "page_id": "file_page:pkg/alpha/one.py",+ "score": 6.0,+ "_fts_rank": 0,+ "_vec_rank": 0,+ },+ {+ "page_id": "file_page:pkg/alpha/two.py",+ "score": 5.9,+ "_fts_rank": 1,+ "_vec_rank": 1,+ },+ ]++ _patch_pipeline(monkeypatch, answer_mod, scores=(6.0, 5.9))+ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)+ _patch_provider(monkeypatch, answer_mod, _PLAIN_ANSWER)++ result = await get_answer(_QUESTION)+ note = result["note"]+ assert result["confidence"] == "high"+ assert "both retrievers independently rank this page at the top" in note+ assert "clearly dominates" not in note+++def _patch_anchor(monkeypatch, answer_mod, anchored):+ """Attach *anchored* to the top hit, as if the question named an indexed+ symbol whose defining file was promoted into the candidate set."""++ async def _fake_anchor(session, repo_id, question_ids, hits, **kwargs):+ if hits:+ hits[0]["_anchor_symbols"] = [anchored]+ return hits, {"union": {}, "qualified_miss": []}++ monkeypatch.setattr(answer_mod, "_anchor_symbol_hits", _fake_anchor)+++async def test_a_served_named_body_still_earns_high_on_weak_retrieval(+ setup_mcp, monkeypatch, tmp_path+):+ """The other half of the split: a body in the payload DOES out-vote the ranking.++ The symbol was resolved by its name, not by the ranking, and its live source+ is inlined in the response — so "retrieval was ambiguous" is a statement+ about the candidate pages, not about the evidence this answer rests on.+ The note has to say that rather than claim a dominance of 1.00x, and the+ caveat must not send the agent off to verify against best_guesses when the+ confidence deliberately does not rest on them.+ """+ import repowise.server.mcp_server as mcp_mod+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ (tmp_path / "pkg" / "alpha").mkdir(parents=True)+ (tmp_path / "pkg" / "alpha" / "one.py").write_text(+ f"def {_SYMBOL}() -> int:\n # drop rows past the horizon\n return PURGED\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))++ # A tied pair is non-dominant at any scale, so this stays weak however fusion+ # rescales it; the magnitude is only there to clear the confidence floor,+ # which anchoring lowers the fused score enough to matter for.+ _patch_pipeline(monkeypatch, answer_mod, scores=(8.0, 8.0), matched=True)+ _patch_anchor(+ monkeypatch,+ answer_mod,+ {"name": _SYMBOL, "kind": "function", "start_line": 1, "end_line": 3},+ )+ _patch_provider(monkeypatch, answer_mod, _GROUNDED_ANSWER)++ result = await get_answer(f"How does {_SYMBOL} work?")+ assert result["retrieval_quality"] == "weak"+ assert result["symbol_bodies"], "the named body is what the grade rests on"+ assert result["confidence"] == "high"+ # Also what keeps REPOWISE_ANSWER_LEAN_HIGH from stripping symbol_bodies out+ # of a high-confidence payload whose note points straight at it.+ assert result["grounding"] == "symbol_body"+ note = result["note"]+ assert "symbol_bodies" in note, "the note must name the evidence it actually used"+ assert "clearly dominates" not in note+ assert "verify against best_guesses" not in note+ assert "next_action_hint" not in result, (+ "do not send the agent to the candidates the confidence does not rest on"+ )diff --git a/tests/unit/server/mcp/test_answer_degraded_evidence.py b/tests/unit/server/mcp/test_answer_degraded_evidence.pyindex 4e001a859..3a97440bc 100644--- a/tests/unit/server/mcp/test_answer_degraded_evidence.py+++ b/tests/unit/server/mcp/test_answer_degraded_evidence.py@@ -256,6 +256,21 @@ async def test_degraded_does_not_lift_a_genuinely_weak_retrieval():assert await _quality(_scored(6.0, 5.9)) == "weak"+async def test_degraded_reads_the_same_two_tier_dominance_as_the_graded_path():+ """The rating widened here too, deliberately, and only in one direction.++ It used to re-derive a ratio-only dominance while the synthesised path used a+ two-tier test, so this pair — a clear 0.6-point win between two strong scores+ — rated "weak" on the degraded path and dominant everywhere else. Both now+ read one owner, which is what makes "weak" mean exactly "not dominant".++ The widening cannot demote: above the score floor, clearing the ratio implies+ clearing the gap. So this is the only new outcome, and the genuinely-weak+ control above (6.0/5.9, a gap of 0.1) still holds.+ """+ assert await _quality(_scored(6.0, 5.4)) == "high"++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"