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.

@ (#823)

Raghav Chamadiyae8053cf1e6ad
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 f2b0f614c..363aeae89 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
@@ -124,6 +124,7 @@ from repowise.server.mcp_server.tool_answer.symbols import (
_hydrate_symbols_for_hits,
_read_symbol_source,
build_homonym_union_bodies,
+ union_defers_to_synthesis,
)
from repowise.server.mcp_server.tool_answer.synthesis import (
_hash_question,
@@ -663,7 +664,14 @@ async def get_answer(
# the agent picks the one it wants from material already in-hand. This is
# the fix for the retrieval-MISS class: those defs are never in the fuzzy
# candidate set, so the exact-name scan is the only thing that surfaces them.
+ # Defer to synthesis when the union is incidental: a prose question that
+ # merely mentions a many-def generic method (``to_dict``, ``provider_name``)
+ # would otherwise dump every unrelated body as a confidence=high answer,
+ # burying what was actually asked. A bare symbol lookup, or a small genuine
+ # parallel-impl set (``_severity_for`` x4), still answers by union.
union_groups = homonyms.get("union") or {}
+ if union_groups and union_defers_to_synthesis(question, question_ids, union_groups):
+ union_groups = {}
if union_groups:
repo_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else None
union_bodies, more_defs = build_homonym_union_bodies(repo_root, union_groups)
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 12dd0401f..ab858977d 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
@@ -65,6 +65,20 @@ _SYNTH_FULL_BODY_MAX_SYMBOLS = 2
_HOMONYM_UNION_CHAR_BUDGET = 12000
# Line cap per union body — same rationale as _INLINE_BODY_MAX_LINES.
_HOMONYM_UNION_BODY_MAX_LINES = 120
+# Ceiling on how many same-named defs a *prose* question may answer-by-union.
+# The union is for a small set of genuine parallel implementations of one concept
+# (``_severity_for`` has 4 across the biomarkers); past a handful, the name is a
+# generic method implemented on many unrelated classes (``to_dict`` x33,
+# ``from_dict`` x26, ``provider_name`` x12), and inlining every body as a
+# confidence=high answer buries the actual question. So a prose question that
+# merely *mentions* such a name (measured: "how does a wiki page get its
+# provider_name during indexing?" dumped 12 unrelated provider stubs) falls
+# through to synthesis, which grounds in the file the question is really about.
+# An explicit symbol lookup (a bare name, where prose does not dominate) still
+# unions at any count — that caller asked for every definition. The gap between a
+# genuine union (<=4 seen) and a generic method (>=12 seen) is wide, so this is
+# not tuned to an exact count.
+_HOMONYM_UNION_PROSE_DEF_CEILING = 6
# Data-shape grounding. "what fields does each entry in <blob> contain" is
# answered directly by mining the field set from source instead of gating to a
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
index 70f87d81c..fda4ab963 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
@@ -19,6 +19,7 @@ from repowise.server.mcp_server.tool_answer.config import (
_HIGH_CONFIDENCE_SCORE_FLOOR,
_HOMONYM_UNION_BODY_MAX_LINES,
_HOMONYM_UNION_CHAR_BUDGET,
+ _HOMONYM_UNION_PROSE_DEF_CEILING,
_MATCHED_SYMBOL_SOURCE_LINES,
_MAX_RICH_SIG_LINES,
_MAX_SYMBOLS_PER_HIT,
@@ -27,6 +28,7 @@ from repowise.server.mcp_server.tool_answer.config import (
_SYNTH_FULL_BODY_MAX_SYMBOLS,
_SYNTH_FULL_SOURCE_LINES,
)
+from repowise.server.mcp_server.tool_search import _prose_dominates
def _extract_question_identifiers(question: str) -> set[str]:
@@ -67,6 +69,38 @@ def _extract_question_identifiers(question: str) -> set[str]:
return ids
+def union_defers_to_synthesis(
+ question: str, question_ids: set[str], union_groups: dict
+) -> bool:
+ """True when an answer-by-union should fall through to synthesis.
+
+ Answer-by-union is the right reply for a small set of genuine parallel
+ implementations the question is actually about (``_severity_for`` has 4
+ across the biomarkers). It is the WRONG reply when a prose question merely
+ *mentions* a generic method that happens to have many definitions: measured,
+ "how does a wiki page get its provider_name during indexing?" dumped 12
+ unrelated provider stubs as a confidence=high answer, and a ``to_dict``
+ mention dumped 28. Two signals must both hold before deferring, so the
+ narrowest population is affected:
+
+ * ``_prose_dominates`` — the query reads as prose, not a bare symbol lookup.
+ A bare ``provider_name`` (prose does not dominate) still unions: that
+ caller explicitly asked for every definition.
+ * the def count exceeds ``_HOMONYM_UNION_PROSE_DEF_CEILING`` — past a
+ handful, the name is a generic method, not a small parallel-impl set.
+
+ Small genuine unions and explicit lookups are untouched; only a prose
+ question naming a many-def generic method falls through to synthesis (which
+ grounds in the file the question is really about).
+ """
+ if not union_groups:
+ return False
+ total_defs = sum(len(defs) for defs in union_groups.values())
+ if total_defs <= _HOMONYM_UNION_PROSE_DEF_CEILING:
+ return False
+ return _prose_dominates(question, list(question_ids))
+
+
def _read_repo_text(repo_root: Path | None, file_path: str) -> str | None:
"""Read a repo file's live text, refusing paths outside the root.
diff --git a/tests/unit/server/mcp/test_answer_calibration.py b/tests/unit/server/mcp/test_answer_calibration.py
index bfaab2f5c..66c06d9e0 100644
--- a/tests/unit/server/mcp/test_answer_calibration.py
+++ b/tests/unit/server/mcp/test_answer_calibration.py
@@ -704,6 +704,103 @@ def test_union_bodies_overflow_lists_remainder_as_pointers(tmp_path):
assert "do NOT Read" in more[0]["hint"]
+# ---------------------------------------------------------------------------
+# Answer-by-union incidental gate — a prose question that merely MENTIONS a
+# many-def generic method (to_dict x33) must not dump every unrelated body as a
+# confidence=high answer; it falls through to synthesis. A small genuine union
+# (_severity_for x4) and an explicit bare-symbol lookup still answer by union.
+# ---------------------------------------------------------------------------
+
+
+def _union(name: str, n: int) -> dict:
+ return {name: [{"file_path": f"pkg/f{i}.py", "name": name} for i in range(n)]}
+
+
+def test_union_defers_only_when_prose_and_many_defs():
+ from repowise.server.mcp_server.tool_answer.symbols import union_defers_to_synthesis
+
+ q_prose = "How does a wiki page get its provider_name during indexing?"
+ # Prose + many defs → defer to synthesis.
+ assert union_defers_to_synthesis(q_prose, {"provider_name"}, _union("provider_name", 12))
+ # Small genuine union stays (the _severity_for x4 case) even in prose.
+ assert not union_defers_to_synthesis(
+ "How does _severity_for compute a severity level?",
+ {"_severity_for"},
+ _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))
+ # No union → nothing to defer.
+ assert not union_defers_to_synthesis(q_prose, {"provider_name"}, {})
+
+
+def test_union_defer_ceiling_is_inclusive():
+ from repowise.server.mcp_server.tool_answer.config import _HOMONYM_UNION_PROSE_DEF_CEILING
+ from repowise.server.mcp_server.tool_answer.symbols import union_defers_to_synthesis
+
+ q = "How is a parsed record serialized with widget_dump before it is stored?"
+ ids = {"widget_dump"}
+ at = _HOMONYM_UNION_PROSE_DEF_CEILING
+ # At the ceiling: still a handful, keep the union.
+ assert not union_defers_to_synthesis(q, ids, _union("widget_dump", at))
+ # One past it: a generic method, defer.
+ assert union_defers_to_synthesis(q, ids, _union("widget_dump", at + 1))
+
+
+def _patch_anchor_union(monkeypatch, answer_mod, union_groups: dict):
+ """Force _anchor_symbol_hits to report a homonym union (no hit boost)."""
+
+ async def _fake_anchor(session, repo_id, question_ids, hits, **kwargs):
+ return hits, {"union": union_groups, "qualified_miss": []}
+
+ monkeypatch.setattr(answer_mod, "_anchor_symbol_hits", _fake_anchor)
+
+
+async def test_prose_mention_of_generic_method_synthesizes(setup_mcp, monkeypatch):
+ """A prose question naming a 12-def generic method falls through to synthesis
+ instead of returning grounding='exact_symbol' with a wall of unrelated bodies."""
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ _patch_pipeline(monkeypatch, answer_mod, with_symbols=False)
+ _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?")
+ assert result.get("grounding") != "exact_symbol"
+ assert "symbol_bodies" not in result or len(result.get("symbol_bodies") or []) < 12
+
+
+async def test_small_union_still_answers_by_union(setup_mcp, monkeypatch, tmp_path):
+ """A small genuine parallel-impl union (3 defs, under the ceiling) still
+ short-circuits to grounding='exact_symbol' — the gate must not over-suppress."""
+ 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))
+
+ _patch_pipeline(monkeypatch, answer_mod, with_symbols=False)
+ _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?")
+ assert result.get("grounding") == "exact_symbol"
+ assert len(result["symbol_bodies"]) == 3
+
+
# ---------------------------------------------------------------------------
# code_rationale — the T4 lever: in-code rationale recovered when the wiki /
# decision corpus could not ground the question (low-confidence exits).