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): calibrate confidence on answer grounding, not retrieval shape (#923)
Swati Ahuja6bccc0432917
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_context.py b/packages/server/src/repowise/server/mcp_server/_answer_context.pyindex e188ec05a..0fb1920c4 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_context.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_context.py@@ -36,6 +36,49 @@ from repowise.core.persistence.models import DecisionRecord, GitMetadata# needs and doesn't want ADR-driven hedging)._WHY_PATTERN = re.compile(r"\bwhy\b", re.IGNORECASE)+# Heuristic for "how does X work" mechanism questions. Two precise signals, both+# tuned to avoid the union path's two failure directions:+#+# * ``_MECHANISM_HOW_RE`` — "how" as a whole word, but NOT the quantity/degree+# phrasings ("how many/much/long/large/big/old/often"), which are VALUE+# questions, nor "how come" (a "why" in disguise). "How does X verify …" is+# mechanism; "how many definitions of X" is not.+# * ``_MECHANISM_LEAD_RE`` — an imperative walkthrough verb at the START of the+# question ("explain …", "trace …", "walk me through …"). Anchored to the+# lead so it fires on "Explain how bounds heal" but not on a naming question+# that merely contains the word ("where is the trace helper defined").+#+# A bare mechanism VERB anywhere in the sentence is deliberately NOT a signal: it+# false-fires on lookup questions ("where is compute_score defined", "what does+# route_request return") that the union-of-bodies reply answers correctly. On the+# real question distribution every mechanism question leads with "how" or an+# imperative, so the verb-anywhere path bought recall we don't need at a precision+# cost we can't afford — dropped.+_MECHANISM_HOW_RE = re.compile(+ r"\bhow\b(?!\s+(?:many|much|long|large|big|old|often|frequently|come)\b)",+ re.IGNORECASE,+)+_MECHANISM_LEAD_RE = re.compile(+ r"^\s*(?:explain|describe|trace|outline|walk(?:\s+me)?\s+through|step\s+through)\b",+ re.IGNORECASE,+)+++def is_mechanism_question(question: str) -> bool:+ """True when the question asks HOW a mechanism works, not merely names a symbol.++ "How does get_symbol verify bounds?" is a mechanism question whose answer may+ live in a *different* file than the named symbol's body — so the exact-name+ union fast path (which just dumps the named symbol's definitions) is the wrong+ reply, even for a small union. A bare naming/lookup question ("what does X+ return", "where is Y defined") or a value question ("how many definitions of+ X") is not a mechanism question and still unions.+ """+ if not question:+ return False+ return bool(_MECHANISM_HOW_RE.search(question) or _MECHANISM_LEAD_RE.search(question))++# How many decision records to inject, and per-record truncation. Three is# usually enough — most files are governed by 0–2 active ADRs; 3 gives room# for one tangential overlap without blowing the context budget.diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex e2da95729..62e11b9f9 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -108,15 +108,22 @@ async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:# RRF merge. Each hit's contribution from a source is 1/(rank + k);# hits appearing in both sources sum their contributions naturally.+ # Per-source rank is preserved alongside the fused score: RRF *compresses*+ # scores (rank-0-in-both barely outscores rank-1-in-both), so the summed+ # number loses the "both retrievers independently ranked this #1" signal.+ # Downstream confidence uses these ranks to recover retriever *agreement*+ # as a dominance signal the numeric ratio can't see.fused: dict[str, dict] = {}for rank, h in enumerate(fts_results):entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _RRF_K)entry["_sources"].add("fts")+ entry["_fts_rank"] = rankfor rank, h in enumerate(vec_results):entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _RRF_K)entry["_sources"].add("vector")+ entry["_vec_rank"] = rank# Scale to BM25-range so downstream confidence/dominance gates (tuned# against the prior single-mode BM25 retrieval) keep behaving sanely.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 ad26f42ec..72a77890e 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@@ -62,7 +62,10 @@ from repowise.server.mcp_server._answer_context import (from repowise.server.mcp_server._answer_context import (fetch_relevant_decisions as _fetch_relevant_decisions,)-from repowise.server.mcp_server._answer_context import is_why_question as _is_why_question+from repowise.server.mcp_server._answer_context import (+ is_mechanism_question as _is_mechanism_question,+ is_why_question as _is_why_question,+)from repowise.server.mcp_server._answer_pipeline import (apply_pagerank_bias as _apply_pagerank_bias,)@@ -95,6 +98,8 @@ from repowise.server.mcp_server.tool_answer.confidence import (_ungrounded_numbers,)from repowise.server.mcp_server.tool_answer.config import (+ _AGREEMENT_RANK_GAP,+ _AGREEMENT_TOP_RANK_MAX,_ANSWER_CACHE_TTL_DAYS,_ANSWER_SCHEMA_VERSION,_DOMINANCE_RATIO,@@ -144,6 +149,33 @@ _log = logging.getLogger("repowise.mcp.answer")# question (the pre-synthesis dominance gate abstained on ~58%). Set to a falsey# value (0/off/false/no) to restore the legacy abstain-on-ambiguous behaviour._ALWAYS_SYNTHESIZE_ENV = "REPOWISE_ANSWER_ALWAYS_SYNTHESIZE"+_AGREEMENT_CONFIDENCE_ENV = "REPOWISE_ANSWER_AGREEMENT_CONFIDENCE"+# Keep the exact_symbol union fast path from hijacking a "how does X work"+# mechanism question, whose real answer often lives in a different file than the+# named symbol's body.+_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.+_EARN_HIGH_GROUNDING_ENV = "REPOWISE_ANSWER_EARN_HIGH_GROUNDING"+++def _flag_on(env_name: str) -> bool:+ """A REPOWISE_* feature flag: on by default, off for {0,false,no,off}."""+ return os.environ.get(env_name, "").strip().lower() not in {"0", "false", "no", "off"}+++# 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/B+# eval that flips the REPOWISE_ANSWER_* flags between arms would otherwise read+# the first arm's cached answers. Off by default; set truthy in the eval harness.+_DISABLE_CACHE_ENV = "REPOWISE_ANSWER_DISABLE_CACHE"+++def _cache_disabled() -> bool:+ return os.environ.get(_DISABLE_CACHE_ENV, "").strip().lower() in {"1", "true", "yes", "on"}def _always_synthesize() -> bool:@@ -156,6 +188,64 @@ def _always_synthesize() -> bool:}+def _agreement_confidence_enabled() -> bool:+ """Whether retriever-agreement lifts confidence (default) or pure ratio rules.++ A falsey value restores the exact prior RRF-compressed ratio/gap behaviour,+ for A/B measurement and instant reversibility.+ """+ return os.environ.get(_AGREEMENT_CONFIDENCE_ENV, "").strip().lower() not in {+ "0",+ "false",+ "no",+ "off",+ }+++def _agreement_dominant(hits: list[dict]) -> bool:+ """True when the top hit is the confident pick by retriever AGREEMENT.++ RRF fusion compresses scores: a page both retrievers rank #1 barely+ outscores one they rank #2 (ratio ~1.017), so the numeric dominance ratio+ calls the *most* confident retrieval "non-dominant" and demotes it. This+ reads the per-source ranks (``_fts_rank`` / ``_vec_rank``) instead: when FTS+ and vector independently put the SAME page at (or within a rank of) the top,+ that consensus is a stronger ground-truth signal than any RRF score margin.++ Conservative. Requires the top hit to be found by BOTH retrievers near the+ top of each, to rank no lower than the runner-up in either source, and the+ runner-up to be meaningfully weaker (found by only one retriever, or clearly+ lower-ranked in a source). Otherwise returns False and the caller falls back+ to the pure ratio/gap gate. Agreement can only LIFT — the demotion gates+ still apply.+ """+ if len(hits) < 2:+ return False+ top = hits[0]+ top_fts = top.get("_fts_rank")+ top_vec = top.get("_vec_rank")+ # Top must be a consensus pick: found by both retrievers, near the top of+ # each. A one-retriever top hit is exactly the ambiguous case we must NOT+ # lift.+ if top_fts is None or top_vec is None:+ return False+ if top_fts > _AGREEMENT_TOP_RANK_MAX or top_vec > _AGREEMENT_TOP_RANK_MAX:+ return False+ second = hits[1]+ sec_fts = second.get("_fts_rank")+ sec_vec = second.get("_vec_rank")+ # Runner-up found by only one retriever → the consensus top clearly wins.+ if sec_fts is None or sec_vec is None:+ return True+ # Runner-up found by both: the top must rank at least as high in BOTH+ # sources (no source disagrees) and strictly ahead in at least one.+ if top_fts <= sec_fts and top_vec <= sec_vec:+ return (sec_fts - top_fts) >= _AGREEMENT_RANK_GAP or (+ sec_vec - top_vec+ ) >= _AGREEMENT_RANK_GAP+ return False++def _build_best_guesses(hits: list[dict]) -> list[dict]:"""Decision-shaped candidate list: per-file justification, score, excerpt.@@ -490,14 +580,17 @@ async def get_answer(# scoped queries are uncommon and including scope would balloon hit rate# variance. We hash on (repo_id, normalized_question) only.qhash = _hash_question(question)- async with get_session(ctx.session_factory) as session:- res = await session.execute(- select(AnswerCache).where(- AnswerCache.repository_id == repo_id,- AnswerCache.question_hash == qhash,+ cache_disabled = _cache_disabled()+ cached = None+ if not cache_disabled:+ async with get_session(ctx.session_factory) as session:+ res = await session.execute(+ select(AnswerCache).where(+ AnswerCache.repository_id == repo_id,+ AnswerCache.question_hash == qhash,+ ))- )- cached = res.scalar_one_or_none()+ cached = res.scalar_one_or_none()if cached is not None:with contextlib.suppress(Exception):payload = _json.loads(cached.payload_json)@@ -734,6 +827,15 @@ async def get_answer(union_groups = homonyms.get("union") or {}if union_groups and union_defers_to_synthesis(question, question_ids, union_groups):union_groups = {}+ # A mechanism/"how" question that merely NAMES an indexed symbol (e.g. "how+ # does X verify its bounds?") must not short-circuit to a dump of that+ # symbol's bodies: the mechanism it asks about often lives in another file the+ # union path never retrieves, yielding a confidently-wrong "here are the+ # definitions" non-answer. Defer to synthesis regardless of def count.+ # Naming/lookup questions ("what does X return", "where is Y") are untouched+ # and still answer by union.+ if union_groups and _flag_on(_UNION_MECHANISM_DEFER_ENV) and _is_mechanism_question(question):+ union_groups = {}if union_groups:repo_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else Noneunion_bodies, more_defs = build_homonym_union_bodies(repo_root, union_groups)@@ -823,6 +925,11 @@ async def get_answer(# (typical 0.15-0.25), so a coverage threshold over-fires. Default dominant# for a lone hit (nothing to be ambiguous against).always_synthesize = _always_synthesize()+ # Agreement dominance recovers the "both retrievers rank this #1" signal+ # that RRF fusion compresses out of the numeric score. Computed once and+ # OR'd into every place the ratio/gap gate decides dominance, so it can+ # only LIFT a retrieval — never demote one the ratio already trusts.+ agreement_dominant = _agreement_dominant(hits) if _agreement_confidence_enabled() else Falsedominant = Trueif len(hits) >= 2:top_score = hits[0].get("score", 0.0)@@ -831,6 +938,7 @@ async def get_answer(dominant = (top_score - second_score) >= 0.5else:dominant = (top_score / second_score) >= _DOMINANCE_RATIO+ dominant = dominant or agreement_dominantif not always_synthesize and not dominant:# Legacy abstain path (REPOWISE_ANSWER_ALWAYS_SYNTHESIZE=off): retrieval@@ -1135,9 +1243,35 @@ async def get_answer(else:_ratio = float("inf") if hits else 0.0_top_score = hits[0].get("score", 0.0) if hits else 0.0- if _ratio >= _DOMINANCE_RATIO and _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:+ # 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 ~6 after RRF scaling.+ _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+ # high back down.+ earn_high = False+ if _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:confidence = "high"- elif _ratio >= _DOMINANCE_RATIO:+ elif _dominant_grade:# 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.@@ -1196,20 +1330,28 @@ async def get_answer(if not any(h.get("symbols") for h in hits if h.get("target_path") in cited):confidence = "medium"- # Sixth gate — frame grounding (why-questions): a high-confidence "why"- # answer must explain the rationale in terms the cited material actually- # contains. The dominance gate is generous on repo-internal why-questions- # (an anchored symbol + a dominant hit clear it), so a synthesis that- # conflates two mechanisms — right number, right file, wrong reason —- # rides through at high confidence. The tell is a distinctive code-like- # term (a class / function / module the answer names as the cause) that- # appears nowhere in everything retrieval showed. When such terms are not- # outweighed by grounded ones, downgrade high→medium so the consumer- # verifies the "because X" instead of trusting it. Scoped to why-questions:- # mechanism/architecture answers legitimately introduce vocabulary; only- # rationale claims, where an unsupported frame is a factual error, get gated.+ # Sixth gate — claim-support / frame grounding: a high-confidence answer+ # must name its mechanism in terms the cited material actually contains. The+ # dominance gate is generous on repo-internal questions (an anchored symbol ++ # a dominant hit clear it), so a synthesis that conflates two mechanisms —+ # right file, wrong reason/function — rides through at high confidence. The+ # tell is a distinctive code-like term (a class / function / module the+ # answer names AS the mechanism) that appears nowhere in everything retrieval+ # showed: the "right file, wrong function inside it" failure. When such terms+ # are not outweighed by grounded ones, downgrade high→medium so the consumer+ # verifies instead of trusting.+ #+ # The original gate fired only on "why" questions, but the same failure+ # occurs on "how" questions that name the mechanism in the ANSWER, not the+ # question — the "right file, wrong function inside it" case. Broaden to+ # mechanism/how questions too (behind the claim-support flag). Value questions+ # have their own numeric gate above; naming/lookup questions legitimately just+ # echo the named symbol, so they are excluded.frame_unsupported: list[str] = []- if confidence == "high" and not hedged and _is_why_question(question):+ _claim_scope = _is_why_question(question) or (+ _flag_on(_CLAIM_SUPPORT_GATE_ENV) and _is_mechanism_question(question)+ )+ if confidence == "high" and not hedged and _claim_scope:frame_unsupported, _grounded_terms = _frame_term_grounding(answer_text, question, hits)if frame_unsupported and len(frame_unsupported) >= _grounded_terms:confidence = "medium"@@ -1222,7 +1364,11 @@ async def get_answer(# if all six gates 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.)- if not dominant and confidence == "high":+ # 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.+ if not dominant and not earn_high and confidence == "high":confidence = "medium"# retrieval_quality is a separate signal from confidence. Where confidence@@ -1230,9 +1376,9 @@ async def get_answer(# 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 _ratio >= _DOMINANCE_RATIO:+ if _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR and _dominant_grade:retrieval_quality = "high"- elif _ratio >= _DOMINANCE_RATIO:+ elif _dominant_grade:retrieval_quality = "partial"else:retrieval_quality = "weak"@@ -1332,8 +1478,8 @@ async def get_answer(f"{ungrounded_values} against the live source.")elif frame_unsupported:- # The synthesised "why" leaned on a term retrieval never showed,- # so the real rationale likely lives in a code comment the wiki /+ # The synthesised answer leaned on a mechanism term retrieval never+ # showed, so the real mechanism likely lives in code the wiki /# decision corpus never captured. Mine the candidate source for it# — the same lever the gated/hedged paths use — so the downgrade# ships a lead, not just a warning.@@ -1342,15 +1488,15 @@ async def get_answer(if code_rationale:payload["code_rationale"] = code_rationalepayload["note"] = (- f"Frame-grounding gate: the answer names {frame_unsupported} to "- "explain the rationale, but that term is absent from every "- "retrieved excerpt — the 'why' may be conflated with a different "- "mechanism. Downgraded to medium; verify against "+ f"Claim-support gate: the answer names {frame_unsupported} as the "+ "mechanism, but that term is absent from every retrieved excerpt "+ "— it may be conflated with a different function/file. Downgraded "+ "to medium; verify against "f"{fallback_targets[0] if fallback_targets else 'the cited source'}"+ (" or the code_rationale comments below." if code_rationale else "."))payload["next_action_hint"] = (- f"Verify the rationale before citing: the asserted frame term(s) "+ f"Verify the mechanism before citing: the asserted term(s) "f"{frame_unsupported} are not in the retrieved material.")elif confidence == "high":@@ -1414,7 +1560,7 @@ async def get_answer(# were never upgraded. Delete-then-insert in one transaction is the# dialect-agnostic upsert; the stamped _indexed_commit drives the# read-side freshness check.- if answer_text:+ if answer_text and not cache_disabled:cache_payload = dict(payload)cache_payload["_schema_version"] = _ANSWER_SCHEMA_VERSIONcommit_now = getattr(repository, "head_commit", None)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 7f17f43d2..464af10d9 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@@ -124,6 +124,23 @@ _MAX_SYMBOL_DOC_CHARS = 120_DOMINANCE_RATIO = 1.2_COVERAGE_THRESHOLD = 0.66+# 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+# _DOMINANCE_RATIO — so the numeric gate calls the *most* confident retrieval+# (both retrievers agree on the top page) "non-dominant". These knobs let the+# grade read the per-source ranks directly: when FTS and vector independently+# put the SAME page at (or within one rank of) the top and the runner-up is+# meaningfully weaker, that consensus is treated as dominance the ratio can't+# see. Conservative by design — agreement only LIFTS a retrieval to high; the+# six demotion gates still pull it back if the synthesised text is ungrounded.+# The top hit must rank no lower than this in EACH retriever (0-indexed, so+# 1 == "#1 or #2 in both").+_AGREEMENT_TOP_RANK_MAX = 1+# The runner-up must trail the top by at least this many ranks in at least one+# source (when it was found by both). 1 == "top is strictly ahead somewhere".+_AGREEMENT_RANK_GAP = 1+# Hedge-phrase markers that indicate the LLM refused to synthesize even though# retrieval was dominant. When the answer contains any of these, we downgrade# confidence to "low" and drop the retrieval payload — the hits aren't useful@@ -295,7 +312,19 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5# carry synthesized prose + best_guesses/code_rationale evidence at medium/low# instead of an empty pointer list. Cached v8 gated (empty-answer) rows must# bypass so the new answered-with-evidence contract reaches callers.-_ANSWER_SCHEMA_VERSION = 9+# v9: agreement-aware confidence — the top hit is graded "dominant/high" when+# both retrievers independently rank it at/near the top, not only when its+# RRF-fused score numerically dominates. RRF compresses scores, so retriever+# agreement (the most confident case) previously graded medium/low. Cached+# pre-v9 rows carry the compressed-ratio grade and must bypass.+# v10: (reserved for the agreement rollout above.)+# v11: answer-grounding calibration — (1) a mechanism/"how" question that merely+# names an indexed symbol no longer short-circuits to an exact_symbol body dump;+# (2) the claim-support gate now covers how-questions, not only why; (3) strong+# answer-grounding earns high on a non-dominant retrieval. Cached pre-v11 rows+# carry the old body-dump / dominance-only grade and must bypass so the+# recalibrated confidence reaches callers.+_ANSWER_SCHEMA_VERSION = 11# Hard TTL on answer-cache rows. Commit-based invalidation (the payload's# stamped ``_indexed_commit`` vs the repo's current head) is the primarydiff --git a/tests/unit/server/mcp/test_answer_agreement.py b/tests/unit/server/mcp/test_answer_agreement.pynew file mode 100644index 000000000..a58f10bcf--- /dev/null+++ b/tests/unit/server/mcp/test_answer_agreement.py@@ -0,0 +1,222 @@+"""Agreement-aware confidence for get_answer.++RRF fusion compresses retrieval scores: a page BOTH retrievers rank #1 barely+outscores one they rank #2 (fused ratio ~1.017), so the numeric dominance-ratio+gate calls the *most* confident retrieval "non-dominant" and demotes it to+medium/low. These tests pin the fix: retriever *agreement* (the same page at/near+the top of both FTS and vector) lifts confidence to high even when the fused+scores don't numerically dominate — subject to the existing demotion gates, and+fully reversible via ``REPOWISE_ANSWER_AGREEMENT_CONFIDENCE=off``.+"""++from __future__ import annotations++import pytest++from repowise.server.mcp_server.tool_answer.answer import _agreement_dominant+++# ---------------------------------------------------------------------------+# Pure-predicate unit tests for the agreement signal+# ---------------------------------------------------------------------------+++class TestAgreementDominant:+ def test_consensus_top_lifts(self) -> None:+ # Top page is #1 in both retrievers; runner-up is #2 in both.+ hits = [+ {"_fts_rank": 0, "_vec_rank": 0},+ {"_fts_rank": 1, "_vec_rank": 1},+ ]+ assert _agreement_dominant(hits) is True++ def test_top_found_by_one_retriever_does_not_lift(self) -> None:+ # Top hit missing from vector → ambiguous, must NOT lift.+ hits = [+ {"_fts_rank": 0},+ {"_fts_rank": 1, "_vec_rank": 0},+ ]+ assert _agreement_dominant(hits) is False++ def test_runner_up_by_one_retriever_lifts(self) -> None:+ # Top is a consensus pick; runner-up surfaced in only one source.+ hits = [+ {"_fts_rank": 0, "_vec_rank": 0},+ {"_fts_rank": 1},+ ]+ assert _agreement_dominant(hits) is True++ def test_top_not_near_top_does_not_lift(self) -> None:+ hits = [+ {"_fts_rank": 3, "_vec_rank": 3},+ {"_fts_rank": 4, "_vec_rank": 4},+ ]+ assert _agreement_dominant(hits) is False++ def test_source_disagreement_does_not_lift(self) -> None:+ # Runner-up beats the (RRF-)top in FTS → no clean consensus.+ hits = [+ {"_fts_rank": 1, "_vec_rank": 0},+ {"_fts_rank": 0, "_vec_rank": 2},+ ]+ assert _agreement_dominant(hits) is False++ def test_single_hit_is_not_agreement(self) -> None:+ assert _agreement_dominant([{"_fts_rank": 0, "_vec_rank": 0}]) is False+++# ---------------------------------------------------------------------------+# End-to-end grade tests (agreement lifts a compressed-score retrieval)+# ---------------------------------------------------------------------------+++def _patch_provider(monkeypatch, answer_mod, content: str):+ from types import SimpleNamespace++ 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())+++_MATCHED_SYMBOL = {+ "name": "chunk_upload",+ "kind": "function",+ "signature": "def chunk_upload(body) -> None",+ "docstring": "Streams the body in fixed chunks.",+ "start_line": 10,+ "end_line": 20,+ "_matched": False,+}+++def _patch_agreement_pipeline(monkeypatch, answer_mod, *, top_both: bool):+ """Two near-tied hits (fused ratio < 1.2) with per-source ranks.++ ``top_both`` toggles whether the top hit is a consensus pick (found by both+ retrievers at rank 0) or a one-retriever hit — the difference between+ agreement-lift firing and not.+ """++ async def _fake_retrieve(question, ctx):+ top = {"page_id": "file_page:pkg/alpha/one.py", "score": 6.0, "_fts_rank": 0}+ if top_both:+ top["_vec_rank"] = 0+ return [+ top,+ {+ "page_id": "file_page:pkg/alpha/two.py",+ "score": 5.9,+ "_fts_rank": 1,+ "_vec_rank": 1,+ },+ ]++ 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"] = "Upload module summary."+ h["snippet"] = ""+ h["page_type"] = "file_page"+ if i == 0:+ h["symbols"] = [dict(_MATCHED_SYMBOL)]+ return hits++ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)+++# A non-hedged answer that cites the top file so the citation-source gate passes.+_GOOD_ANSWER = "Uploads are streamed in fixed-size chunks by chunk_upload in pkg/alpha/one.py."+# A hedged answer — the demotion gate must still pull an agreement-dominant hit down.+_HEDGED_ANSWER = "The excerpts do not contain the chunking logic; you should inspect the source."+++async def test_agreement_lifts_compressed_retrieval_to_high(setup_mcp, monkeypatch):+ """(a) Both retrievers rank the top page #1; fused ratio < 1.2 → still high."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_AGREEMENT_CONFIDENCE", "on")+ _patch_agreement_pipeline(monkeypatch, answer_mod, top_both=True)+ _patch_provider(monkeypatch, answer_mod, _GOOD_ANSWER)++ result = await get_answer("how does upload chunking work")+ assert result["confidence"] == "high"+ assert result["retrieval_quality"] == "high"+++async def test_one_retriever_top_does_not_get_agreement_lift(setup_mcp, monkeypatch):+ """(b) Top hit found by only one retriever → no lift; stays medium."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_AGREEMENT_CONFIDENCE", "on")+ # Isolate agreement: disable the grounding-earn lift, a separate path to high+ # (this well-grounded answer would otherwise earn high on its own).+ monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_GROUNDING", "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"] == "medium"+++async def test_demotion_gate_still_fires_on_agreement_hit(setup_mcp, monkeypatch):+ """(c) Agreement-dominant retrieval + hedged synthesis → still demoted."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_AGREEMENT_CONFIDENCE", "on")+ _patch_agreement_pipeline(monkeypatch, answer_mod, top_both=True)+ _patch_provider(monkeypatch, answer_mod, _HEDGED_ANSWER)++ result = await get_answer("how does chunk buffering behave")+ assert result["confidence"] != "high"+++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."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "on")+ # No agreement lift (top found by one retriever); the only path to high is+ # the grounding-earn.+ 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"++ monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_GROUNDING", "off")+ result_off = await get_answer("how are large uploads handled")+ assert result_off["confidence"] == "medium"+++async def test_flag_off_restores_pure_ratio(setup_mcp, monkeypatch):+ """(d) Flag off → agreement is ignored, compressed ratio grades medium."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ monkeypatch.setenv("REPOWISE_ANSWER_AGREEMENT_CONFIDENCE", "off")+ # Isolate the ratio path: the grounding-earn is a separate high-lift lever.+ monkeypatch.setenv("REPOWISE_ANSWER_EARN_HIGH_GROUNDING", "off")+ _patch_agreement_pipeline(monkeypatch, answer_mod, top_both=True)+ _patch_provider(monkeypatch, answer_mod, _GOOD_ANSWER)++ result = await get_answer("how does upload streaming chunk data")+ assert result["confidence"] == "medium"diff --git a/tests/unit/server/mcp/test_answer_calibration.py b/tests/unit/server/mcp/test_answer_calibration.pyindex 3b4fad339..5b3a56e80 100644--- a/tests/unit/server/mcp/test_answer_calibration.py+++ b/tests/unit/server/mcp/test_answer_calibration.py@@ -49,7 +49,9 @@ class TestHedgeMarkers:def test_curly_apostrophe_hedge_detected(self) -> None:# LLMs routinely emit the curly U+2019; the markers use plain ASCII.# Without normalization this hedged answer rides through as high.- assert _answer_is_hedged("I can\u2019t determine why the threshold is 1.2 from the excerpts.")+ assert _answer_is_hedged(+ "I can\u2019t determine why the threshold is 1.2 from the excerpts."+ )class TestValueQuestionShape:@@ -123,9 +125,12 @@ class TestDistinctiveTerms:# Sentence-initial / markdown-header words are prose, not mechanisms.# A leading capital alone must not register as a frame term (the live# over-fire that flagged Because/Determine/Mechanism/Short/Since/What).- assert _distinctive_terms(- "## What happens. Because the Mechanism is Short, Determine it Since When."- ) == set()+ assert (+ _distinctive_terms(+ "## What happens. Because the Mechanism is Short, Determine it Since When."+ )+ == set()+ )def test_internal_caps_and_acronyms_kept(self) -> None:terms = _distinctive_terms("It wraps WikiSymbol over an HTTP transport.")@@ -458,9 +463,7 @@ async def test_hedged_but_named_body_served_holds_medium(setup_mcp, monkeypatch,(tmp_path / "pkg" / "alpha").mkdir(parents=True)(tmp_path / "pkg" / "alpha" / "one.py").write_text(- "def min_count_policy() -> int:\n"- " # gate retries at the floor\n"- " return MIN_COUNT\n",+ "def min_count_policy() -> int:\n # gate retries at the floor\n return MIN_COUNT\n",encoding="utf-8",)monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))@@ -669,10 +672,24 @@ def test_union_bodies_inlines_all_defs_under_budget(tmp_path):b = _write(tmp_path, "b/y.py", "def _sev(corr):\n return corr < 0.1\n")union = {"_sev": [- {"name": "_sev", "kind": "function", "file_path": a, "start_line": 1, "end_line": 2,- "qualified_name": "_sev", "parent_name": None},- {"name": "_sev", "kind": "function", "file_path": b, "start_line": 1, "end_line": 2,- "qualified_name": "_sev", "parent_name": None},+ {+ "name": "_sev",+ "kind": "function",+ "file_path": a,+ "start_line": 1,+ "end_line": 2,+ "qualified_name": "_sev",+ "parent_name": None,+ },+ {+ "name": "_sev",+ "kind": "function",+ "file_path": b,+ "start_line": 1,+ "end_line": 2,+ "qualified_name": "_sev",+ "parent_name": None,+ },]}bodies, more = build_homonym_union_bodies(tmp_path, union)@@ -691,10 +708,24 @@ def test_union_bodies_overflow_lists_remainder_as_pointers(tmp_path):b = _write(tmp_path, "b/y.py", "def _sev(corr):\n return corr < 0.1\n")union = {"_sev": [- {"name": "_sev", "kind": "function", "file_path": a, "start_line": 1, "end_line": 2,- "qualified_name": "_sev", "parent_name": None},- {"name": "_sev", "kind": "function", "file_path": b, "start_line": 1, "end_line": 2,- "qualified_name": "_sev", "parent_name": None},+ {+ "name": "_sev",+ "kind": "function",+ "file_path": a,+ "start_line": 1,+ "end_line": 2,+ "qualified_name": "_sev",+ "parent_name": None,+ },+ {+ "name": "_sev",+ "kind": "function",+ "file_path": b,+ "start_line": 1,+ "end_line": 2,+ "qualified_name": "_sev",+ "parent_name": None,+ },]}bodies, more = build_homonym_union_bodies(tmp_path, union, char_budget=5)@@ -729,7 +760,9 @@ def test_union_defers_only_when_prose_and_many_defs():_union("_severity_for", 4),)# Bare symbol lookup (prose does not dominate) still unions at any count.- assert not union_defers_to_synthesis("provider_name", {"provider_name"}, _union("provider_name", 12))+ assert not union_defers_to_synthesis(+ "provider_name", {"provider_name"}, _union("provider_name", 12)+ )# No union → nothing to defer.assert not union_defers_to_synthesis(q_prose, {"provider_name"}, {})@@ -767,7 +800,9 @@ async def test_prose_mention_of_generic_method_synthesizes(setup_mcp, monkeypatc_patch_anchor_union(monkeypatch, answer_mod, _union("to_dict", 12))_patch_provider(monkeypatch, answer_mod, "The page is serialized in pkg/alpha/one.py.")- result = await get_answer("How is a parsed file turned into a dict with to_dict before it is stored?")+ result = await get_answer(+ "How is a parsed file turned into a dict with to_dict before it is stored?"+ )assert result.get("grounding") != "exact_symbol"assert "symbol_bodies" not in result or len(result.get("symbol_bodies") or []) < 12@@ -796,11 +831,52 @@ async def test_small_union_still_answers_by_union(setup_mcp, monkeypatch, tmp_pa_patch_anchor_union(monkeypatch, answer_mod, {"render_widget": defs})_patch_provider(monkeypatch, answer_mod, "unused — union short-circuits before synthesis")- result = await get_answer("How does render_widget build its output?")+ # A naming/lookup question ("what are the definitions") is exactly what the+ # union-of-bodies reply is for; it must still short-circuit.+ result = await get_answer("What are the definitions of render_widget in this repo?")assert result.get("grounding") == "exact_symbol"assert len(result["symbol_bodies"]) == 3+async def test_mechanism_question_defers_union_to_synthesis(setup_mcp, monkeypatch, tmp_path):+ """A "how does X work" question that merely NAMES a small-union symbol defers+ to synthesis instead of dumping bodies with grounding=exact_symbol — the+ mechanism it asks about may live in a different file the union never sees."""+ 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").mkdir(parents=True)+ defs = []+ for i in range(3):+ (tmp_path / "pkg" / f"f{i}.py").write_text(+ f"class C:\n def render_widget(self):\n return {i}\n",+ encoding="utf-8",+ )+ defs.append(+ {"file_path": f"pkg/f{i}.py", "name": "render_widget", "start_line": 2, "end_line": 3}+ )+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))++ # Same question is asked twice (flag on then off); bypass the answer cache+ # so the second call re-synthesizes under the flipped flag instead of+ # replaying the first call's cached payload.+ monkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "on")+ _patch_pipeline(monkeypatch, answer_mod, with_symbols=False)+ _patch_anchor_union(monkeypatch, answer_mod, {"render_widget": defs})+ _patch_provider(monkeypatch, answer_mod, "render_widget builds output by returning an index.")++ result = await get_answer("How does render_widget build its output?")+ # Deferred: synthesis ran, so grounding is NOT the exact_symbol union dump.+ assert result.get("grounding") != "exact_symbol"++ # Flag off restores the legacy union short-circuit for the same question.+ monkeypatch.setenv("REPOWISE_ANSWER_UNION_MECHANISM_DEFER", "off")+ result_off = await get_answer("How does render_widget build its output?")+ assert result_off.get("grounding") == "exact_symbol"++# ---------------------------------------------------------------------------# code_rationale — the T4 lever: in-code rationale recovered when the wiki /# decision corpus could not ground the question (low-confidence exits).@@ -959,7 +1035,7 @@ async def test_why_answer_with_unsupported_frame_downgrades_to_medium(setup_mcp,result = await get_answer("why is the caller list limited the way it is")assert result["confidence"] == "medium"assert "PageRank" in result["note"]- assert "Frame-grounding" in result["note"]+ assert "Claim-support gate" in result["note"]assert "next_action_hint" in result@@ -974,8 +1050,7 @@ async def test_why_answer_with_grounded_frame_stays_high(setup_mcp, monkeypatch)_patch_provider(monkeypatch,answer_mod,- "The caller list is limited because MIN_COUNT bounds the retries "- "(pkg/alpha/one.py).",+ "The caller list is limited because MIN_COUNT bounds the retries (pkg/alpha/one.py).",)result = await get_answer("why is the caller list limited the way it is")@@ -984,22 +1059,30 @@ async def test_why_answer_with_grounded_frame_stays_high(setup_mcp, monkeypatch)@pytest.mark.asyncio-async def test_frame_gate_scoped_to_why_questions(setup_mcp, monkeypatch):- """A mechanism (non-why) question with the same ungrounded term is NOT- gated — only rationale claims get the frame check."""+async def test_claim_support_gate_covers_mechanism_questions(setup_mcp, monkeypatch):+ """The claim-support gate covers "how" mechanism questions, not only "why".+ A mechanism answer that names an ungrounded term (PageRank, absent from every+ retrieved excerpt) is downgraded high→medium — the "right file, wrong function+ inside it" failure. Flag off restores the why-only scope (question stays+ high)."""import repowise.server.mcp_server.tool_answer.answer as answer_modfrom repowise.server.mcp_server import get_answer+ monkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "on")_patch_pipeline(monkeypatch, answer_mod, with_symbols=True)_patch_provider(monkeypatch,answer_mod,- "The caller list is bounded by the PageRank centrality cap "- "(pkg/alpha/one.py).",+ "The caller list is bounded by the PageRank centrality cap (pkg/alpha/one.py).",)result = await get_answer("how does the caller list get bounded")- assert result["confidence"] == "high"+ assert result["confidence"] == "medium"+ assert "PageRank" in result["note"]++ monkeypatch.setenv("REPOWISE_ANSWER_CLAIM_SUPPORT_GATE", "off")+ result_off = await get_answer("how does the caller list get bounded")+ assert result_off["confidence"] == "high"@pytest.mark.asyncio@@ -1014,8 +1097,7 @@ async def test_frame_gated_answer_surfaces_code_rationale(setup_mcp, monkeypatch_patch_provider(monkeypatch,answer_mod,- "The caller list is limited because the PageRank cap applies "- "(pkg/alpha/one.py).",+ "The caller list is limited because the PageRank cap applies (pkg/alpha/one.py).",)(tmp_path / "pkg" / "alpha").mkdir(parents=True)(tmp_path / "pkg" / "alpha" / "one.py").write_text(diff --git a/tests/unit/server/mcp/test_mechanism_question.py b/tests/unit/server/mcp/test_mechanism_question.pynew file mode 100644index 000000000..fef196f23--- /dev/null+++ b/tests/unit/server/mcp/test_mechanism_question.py@@ -0,0 +1,66 @@+"""Precision tests for ``is_mechanism_question`` (union-deferral signal).++The predicate decides whether a question that NAMES an indexed symbol should+defer the exact_symbol union fast path to synthesis (mechanism/how questions) or+answer by dumping the symbol's bodies (naming/lookup/value questions). The cases+below span the question SHAPES the predicate must separate — mechanism vs+naming/lookup/value, including adversarial phrasings (a mechanism verb inside a+lookup, quantity-"how", "how come") — so a pass is evidence the signal+generalises across phrasing rather than matching a fixed list.+"""++from __future__ import annotations++import pytest++from repowise.server.mcp_server._answer_context import is_mechanism_question++# Mechanism / "how does X work" — MUST defer the union to synthesis, because the+# mechanism can live in a file other than the named symbol's body.+_MECHANISM = [+ "How does get_symbol verify that stored symbol bounds match the live file?",+ "how do ingestion symbol bounds end up used by MCP skeleton rendering",+ "How is unreachable dead code detected across the repository?",+ "how does retrieval feed synthesis in get_answer",+ "How does search_codebase route a query to symbol, path, or concept mode?",+ "Explain how the hydrator turns stored bounds into signatures and bodies.",+ "Trace how a parsed symbol's line range travels into a get_answer body.",+ "Walk me through how decision records are down-weighted when ranking.",+ "Describe how get_why surfaces architectural rationale with evidence.",+ "Outline the flow from a changed file to re-persisted symbols.",+ "step through how a retrieval hit becomes an enriched symbol body",+]++# Naming / lookup / value — MUST NOT defer; the union-of-bodies reply is correct.+_NOT_MECHANISM = [+ # naming: what/where lookups, including ones that contain a mechanism VERB+ "What does get_answer return when a question names a symbol with several defs?",+ "Where is filter_dicts_by_key defined?",+ "What are the definitions of render_widget in this repo?",+ "where is the compute_score function defined", # 'compute' is a verb, still a lookup+ "what does route_request return", # 'route' is a verb, still a lookup+ "which file defines reconcile_symbols_for_files",+ "reconcile_symbols_for_files", # bare identifier+ # value / quantity: "how many/much/long/large" are value questions+ "How many definitions of get_symbol are there?",+ "how much memory does the ComplexityWalker use",+ "how long is the default retry budget",+ "how large is the token budget for skeletons",+ # "how come" is a why-in-disguise, not a mechanism ask+ "how come the dominance threshold is 1.2",+]++[email protected]("q", _MECHANISM)+def test_mechanism_questions_defer(q: str) -> None:+ assert is_mechanism_question(q) is True, q++[email protected]("q", _NOT_MECHANISM)+def test_naming_and_value_questions_do_not_defer(q: str) -> None:+ assert is_mechanism_question(q) is False, q+++def test_empty_is_not_mechanism() -> None:+ assert is_mechanism_question("") is False+ assert is_mechanism_question(None) is False # type: ignore[arg-type]