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.

feat(mcp): answer-by-union for homonym symbols in get_answer (#772)

Raghav Chamadiya436e155a70ab
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 928d95ffa..6e36337bb 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
@@ -15,8 +15,19 @@ search → context → read loop with one tool call that returns:
follow-up); present only when the answer
names a function/method/class that was
hydrated
+ "more_definitions": list only on an answer-by-union (homonym) reply
+ whose bodies overflowed the char budget:
+ {file, name, line, symbol_id, hint} entries
+ the agent fetches with get_symbol, not Read
}
+Answer-by-union: when the question names a symbol with N>=2 definitions no
+qualifier disambiguates (``_severity_for`` x 4), the tool returns the UNION of
+their bodies in ``symbol_bodies`` (grounding="exact_symbol", confidence="high")
+rather than a best_guesses pointer list (the pointer list is what triggers the
+agent's get_symbol/get_context drill). A qualified miss (``Parent.leaf`` matching
+no def) returns not-found instead of guessing a same-named symbol elsewhere.
+
When no LLM provider is configured, the tool degrades to retrieval-only
mode (returns ranked hits + snippets, confidence="low") so C1 / index-only
deployments still benefit from the structured single-call shortcut.
@@ -107,6 +118,7 @@ from repowise.server.mcp_server.tool_answer.symbols import (
_extract_value_answer,
_hydrate_symbols_for_hits,
_read_symbol_source,
+ build_homonym_union_bodies,
)
from repowise.server.mcp_server.tool_answer.synthesis import (
_hash_question,
@@ -412,10 +424,11 @@ async def get_answer(
# Fuzzy retrieval misses deep-path definitions even when the symbol is
# indexed; this makes "explain X" one-shot-complete instead of degrading
# to best_guesses on plausible-but-wrong neighbors.
+ homonyms: dict = {"union": {}, "qualified_miss": []}
if question_ids:
with contextlib.suppress(Exception):
async with get_session(ctx.session_factory) as session:
- hits = await _anchor_symbol_hits(session, repo_id, question_ids, hits)
+ hits, homonyms = await _anchor_symbol_hits(session, repo_id, question_ids, hits)
# Concept anchoring: when a why/value question pins a literal number to a
# described behaviour (no named symbol), grep source COMMENTS for the file
# that justifies the number and anchor it as a dominant hit. Rescues the
@@ -438,6 +451,88 @@ async def get_answer(
session, repo_id, hits, ctx, question_ids=question_ids
)
+ # --- Qualified-miss guard ----------------------------------------------
+ # The question qualified a symbol (``Parent.leaf``) but the exact-name scan
+ # found the leaf only under OTHER parents. Return not-found rather than
+ # synthesizing from a same-named symbol elsewhere: a precise query must
+ # never degrade to a confidently-wrong answer (CodeGraph #173).
+ if homonyms.get("qualified_miss"):
+ missed = homonyms["qualified_miss"]
+ return {
+ "answer": "",
+ "citations": [],
+ "confidence": "low",
+ "note": (
+ f"No indexed definition matches the qualified name(s) {missed}. "
+ "The base name is defined elsewhere, but not under the "
+ "class/module you named, so this is not returning a same-named "
+ "symbol from another file, to avoid a confidently-wrong answer. "
+ 'Re-check the qualifier, or call search_codebase mode="symbol" '
+ "on the base name to see every definition."
+ ),
+ "fallback_targets": [],
+ "retrieval": [],
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=_answer_hint("low", 0),
+ repository=repository,
+ targets=[],
+ ),
+ }
+
+ # --- Answer-by-union (homonym exact-name lookup) -----------------------
+ # The question named a symbol with N>=2 defs no qualifier disambiguates
+ # (``_severity_for`` x 4). Instead of bailing to a best_guesses pointer list
+ # (the exact thing that triggers the agent's get_symbol/get_context drill),
+ # inline the UNION of the candidate bodies (char-budgeted, Read-parity) so
+ # 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.
+ union_groups = homonyms.get("union") or {}
+ 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)
+ if union_bodies:
+ names = sorted(union_groups)
+ total = sum(len(v) for v in union_groups.values())
+ cited = sorted({b["path"] for b in union_bodies})
+ note = (
+ f"{total} definition(s) of {', '.join(names)} exist (exact-name "
+ f"index scan; this is the complete set). {len(union_bodies)} "
+ "inlined below in symbol_bodies as live source; use them "
+ "directly, no verification Read."
+ )
+ if more_defs:
+ note += (
+ f" {len(more_defs)} more are in more_definitions; call "
+ "get_symbol with the listed id, do NOT Read."
+ )
+ payload: dict = {
+ "answer": (
+ f"`{', '.join(names)}` has {total} definition(s) in this repo; "
+ "all are inlined in symbol_bodies below. They are distinct "
+ "implementations, so pick the one for your context."
+ ),
+ "citations": cited,
+ "confidence": "high",
+ "grounding": "exact_symbol",
+ "symbol_bodies": union_bodies,
+ "fallback_targets": [b["path"] for b in union_bodies],
+ "retrieval": [],
+ "note": note,
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=_answer_hint("high", len(union_bodies)),
+ repository=repository,
+ targets=cited,
+ ),
+ }
+ if more_defs:
+ payload["more_definitions"] = more_defs
+ return payload
+ # Bodies unreadable (no repo root / files gone) — fall through to the
+ # normal retrieval/gate path rather than returning an empty union.
+
fallback_targets = [
h["target_path"] for h in hits
if h.get("target_path") and _is_readable_path(h["target_path"])
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 1bdea3392..3ac9e297f 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
@@ -42,6 +42,17 @@ _INLINE_BODY_MAX_SYMBOLS = 2
# body of ~99% of symbols in one shot; the rest carry a continuation token.
_INLINE_BODY_MAX_LINES = 120
+# Answer-by-union (homonym exact-name lookup). When a question names a symbol
+# with N>=2 defs that no qualifier disambiguates (`_severity_for` x 4), get_answer
+# inlines the UNION of their bodies instead of a best_guesses pointer list — the
+# pointer list is exactly what triggers the agent's get_symbol/get_context drill.
+# Bodies render greedily under this char budget (mirrors the get_context budget
+# philosophy); defs that don't fit are listed file:line with a "call get_symbol,
+# do NOT Read" redirect. First def always renders even if it alone exceeds budget.
+_HOMONYM_UNION_CHAR_BUDGET = 12000
+# Line cap per union body — same rationale as _INLINE_BODY_MAX_LINES.
+_HOMONYM_UNION_BODY_MAX_LINES = 120
+
# Sort priority by symbol kind. Classes first because "what does X do" /
# "which class inherits from Y" questions resolve at the class level. Then
# top-level functions, then methods (which usually only matter once the
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 abdff36fd..205ad7897 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
@@ -16,6 +16,8 @@ from repowise.core.persistence.models import WikiSymbol
from repowise.server.mcp_server.tool_answer.config import (
_ENRICH_TOP_N_HITS,
_HIGH_CONFIDENCE_SCORE_FLOOR,
+ _HOMONYM_UNION_BODY_MAX_LINES,
+ _HOMONYM_UNION_CHAR_BUDGET,
_MATCHED_SYMBOL_SOURCE_LINES,
_MAX_RICH_SIG_LINES,
_MAX_SYMBOLS_PER_HIT,
@@ -179,12 +181,25 @@ def _extract_value_answer(hits: list[dict], question_ids: set[str]) -> dict | No
return candidates[0] if candidates else None
+def _symbol_def_dict(sym) -> dict:
+ """Plain-dict view of a WikiSymbol def (decouples answer.py from the ORM)."""
+ return {
+ "name": sym.name,
+ "kind": sym.kind,
+ "file_path": sym.file_path,
+ "start_line": sym.start_line,
+ "end_line": sym.end_line,
+ "qualified_name": sym.qualified_name,
+ "parent_name": sym.parent_name,
+ }
+
+
async def _anchor_symbol_hits(
session,
repo_id: str,
question_ids: set[str],
hits: list[dict],
-) -> list[dict]:
+) -> tuple[list[dict], dict[str, Any]]:
"""Inject the defining file of a question-named indexed symbol into hits.
BM25 / vector retrieval misses deep-path files even when the named symbol
@@ -193,14 +208,34 @@ async def _anchor_symbol_hits(
the definition, so synthesis hedges and ``symbol_bodies`` can't fire. When
a question identifier resolves to a single indexed function / method /
class, prepend (or boost) its defining file as the dominant hit so the
- answer grounds in the actual definition. Homonyms are kept only when the
- question also names the parent (``DecisionExtractor``) — never guessed.
-
- Returns ``hits`` re-sorted by score (mutated in place).
+ answer grounds in the actual definition.
+
+ Homonyms (N>=2 defs of one name) split three ways:
+
+ * The question names the parent / qualifies the name so exactly one def
+ survives → anchor that def (as before).
+ * The question does NOT qualify the name → the whole def set is returned in
+ ``homonyms["union"]`` so the caller can inline the UNION of bodies instead
+ of bailing to a best_guesses pointer list (the pointer list is exactly
+ what triggers the agent's get_symbol/get_context drill). This is the fix
+ for the retrieval-MISS class (``_severity_for`` x 4) - the defs are never
+ in the fuzzy candidate set, so an exact-name index scan is the only thing
+ that surfaces them.
+ * The question qualifies the name (``Parent.leaf``) but NO def matches that
+ qualifier → recorded in ``homonyms["qualified_miss"]`` so the caller can
+ return not-found instead of synthesizing from a same-named symbol
+ elsewhere (a precise query must never degrade to a confident wrong answer).
+
+ Returns ``(hits, homonyms)``; ``hits`` is re-sorted by score (mutated in
+ place). ``homonyms = {"union": {name: [def_dict, ...]}, "qualified_miss":
+ [name, ...]}``.
"""
+ homonyms: dict[str, Any] = {"union": {}, "qualified_miss": []}
if not question_ids:
- return hits
+ return hits, homonyms
qids_lower = {q.lower() for q in question_ids}
+ # Qualifiers the question used (dotted forms like ``decisionextractor.extract_all``).
+ qualifiers = {q for q in qids_lower if "." in q}
res = await session.execute(
select(WikiSymbol).where(
WikiSymbol.repository_id == repo_id,
@@ -213,13 +248,12 @@ async def _anchor_symbol_hits(
by_name.setdefault(row.name, []).append(row)
chosen: list = []
- for cands in by_name.values():
+ for name, cands in by_name.items():
if len(cands) == 1:
chosen.append(cands[0])
continue
- # Disambiguate a homonym only when the question names its parent or
- # the parent appears in the qualified name. Otherwise skip — a wrong
- # anchor is worse than no anchor.
+ # Disambiguate a homonym when the question names its parent or the
+ # parent appears in the qualified name.
narrowed = [
c
for c in cands
@@ -232,9 +266,23 @@ async def _anchor_symbol_hits(
]
if len(narrowed) == 1:
chosen.append(narrowed[0])
+ continue
+ # Can't narrow to exactly one. Decide union vs qualified-miss.
+ leaf = (name or "").lower()
+ targeted = any(q.rsplit(".", 1)[-1] == leaf and q != leaf for q in qualifiers)
+ if narrowed:
+ # Qualifier matched >1 def: union of the narrowed set (still all
+ # genuine candidates for the qualified name).
+ homonyms["union"][name] = [_symbol_def_dict(c) for c in narrowed]
+ elif targeted:
+ # Qualifier present but matched nothing: do not guess.
+ homonyms["qualified_miss"].append(name)
+ else:
+ # Bare homonym, no qualifier: union of every def.
+ homonyms["union"][name] = [_symbol_def_dict(c) for c in cands]
if not chosen:
- return hits
+ return hits, homonyms
by_path = {h.get("target_path"): h for h in hits}
top_score = max((h.get("score", 0.0) for h in hits), default=0.0)
@@ -272,7 +320,75 @@ async def _anchor_symbol_hits(
}
)
hits.sort(key=lambda h: h.get("score", 0.0), reverse=True)
- return hits
+ return hits, homonyms
+
+
+def build_homonym_union_bodies(
+ repo_root: Path | None,
+ union_groups: dict[str, list[dict]],
+ char_budget: int = _HOMONYM_UNION_CHAR_BUDGET,
+) -> tuple[list[dict], list[dict]]:
+ """Inline the UNION of a homonym's defining bodies, char-budgeted.
+
+ ``union_groups`` maps a symbol name to the list of its indexed defs (from
+ ``_anchor_symbol_hits``). Returns ``(symbol_bodies, more_definitions)``:
+
+ * ``symbol_bodies``: Read-parity entries (same shape as get_answer's
+ existing ``symbol_bodies``: ``path`` / ``name`` / ``lines`` / ``source``,
+ plus ``truncated`` / ``continuation`` when the body was line-capped)
+ rendered greedily until ``char_budget`` is exhausted. The first def always
+ renders even if it alone exceeds the budget (a homonym with one huge def
+ must still answer), matching the CodeGraph "first match always renders"
+ contract.
+ * ``more_definitions``: the defs that did not fit, each ``{file, name,
+ line, symbol_id, hint}`` with a "call get_symbol, do NOT Read" redirect so
+ the agent never falls back to Read for the remainder.
+
+ Defs are ordered by (name, file_path) so output is deterministic across runs.
+ """
+ symbol_bodies: list[dict] = []
+ more: list[dict] = []
+ spent = 0
+ defs: list[dict] = []
+ for name in sorted(union_groups):
+ for d in sorted(union_groups[name], key=lambda x: (x.get("file_path") or "")):
+ defs.append(d)
+
+ for d in defs:
+ path = d.get("file_path")
+ name = d.get("name")
+ start = d.get("start_line") or 0
+ end = d.get("end_line") or 0
+ symbol_id = f"{path}::{name}"
+ body = _read_symbol_source(
+ repo_root, path, start, end, max_lines=_HOMONYM_UNION_BODY_MAX_LINES
+ )
+ # Budget: always render the first, then only while under budget.
+ if body and (not symbol_bodies or spent + len(body) <= char_budget):
+ served = body.count("\n") + 1
+ end_served = start + served - 1
+ entry: dict = {
+ "path": path,
+ "name": name,
+ "lines": [start, end_served],
+ "source": body,
+ }
+ if end and end > end_served:
+ entry["truncated"] = True
+ entry["continuation"] = f"{path}:{end_served + 1}-{end}"
+ symbol_bodies.append(entry)
+ spent += len(body)
+ else:
+ more.append(
+ {
+ "file": path,
+ "name": name,
+ "line": start,
+ "symbol_id": symbol_id,
+ "hint": f"call get_symbol id='{symbol_id}' for this definition, do NOT Read",
+ }
+ )
+ return symbol_bodies, more
async def _concept_anchor_hits(
diff --git a/tests/unit/server/mcp/test_answer_calibration.py b/tests/unit/server/mcp/test_answer_calibration.py
index 9ce16b53a..2952e3b51 100644
--- a/tests/unit/server/mcp/test_answer_calibration.py
+++ b/tests/unit/server/mcp/test_answer_calibration.py
@@ -485,16 +485,19 @@ async def test_anchor_injects_defining_file_as_dominant_hit():
)
]
hits = [{"target_path": "core/pipeline/incremental.py", "score": 3.6}]
- out = await _anchor_symbol_hits(
+ out, homonyms = await _anchor_symbol_hits(
_FakeSession(rows), "repo1", {"extract_all", "DecisionExtractor"}, hits
)
assert out[0]["target_path"] == "core/decisions/extractor.py"
assert out[0]["_symbol_anchored"] is True
assert out[0]["score"] > 3.6 # dominates the fuzzy top hit
+ assert not homonyms["union"] # single resolved def, no union
@pytest.mark.asyncio
-async def test_anchor_skips_ambiguous_homonym():
+async def test_anchor_unresolvable_homonym_becomes_union():
+ """A bare homonym (no qualifier) is not injected as a hit — its full def
+ set is returned in homonyms['union'] for the answer-by-union path."""
from repowise.server.mcp_server.tool_answer.symbols import _anchor_symbol_hits
rows = [
@@ -502,9 +505,30 @@ async def test_anchor_skips_ambiguous_homonym():
_Sym("extract_all", "b/y.py", parent_name="B", qualified_name="B.extract_all"),
]
hits = [{"target_path": "c/z.py", "score": 2.0}]
- out = await _anchor_symbol_hits(_FakeSession(rows), "r", {"extract_all"}, hits)
+ out, homonyms = await _anchor_symbol_hits(_FakeSession(rows), "r", {"extract_all"}, hits)
+ assert all(not h.get("_symbol_anchored") for h in out)
+ assert out[0]["target_path"] == "c/z.py" # nothing injected into hits
+ assert {d["file_path"] for d in homonyms["union"]["extract_all"]} == {"a/x.py", "b/y.py"}
+ assert not homonyms["qualified_miss"]
+
+
+async def test_anchor_qualified_miss_records_not_found():
+ """The question qualifies the name (Foo.extract_all) but no def sits under
+ Foo — record a qualified miss instead of guessing another Parent's def."""
+ from repowise.server.mcp_server.tool_answer.symbols import _anchor_symbol_hits
+
+ rows = [
+ _Sym("extract_all", "a/x.py", parent_name="A", qualified_name="A.extract_all"),
+ _Sym("extract_all", "b/y.py", parent_name="B", qualified_name="B.extract_all"),
+ ]
+ hits = [{"target_path": "c/z.py", "score": 2.0}]
+ out, homonyms = await _anchor_symbol_hits(
+ _FakeSession(rows), "r", {"extract_all", "Foo.extract_all", "Foo"}, hits
+ )
+ assert homonyms["qualified_miss"] == ["extract_all"]
+ assert not homonyms["union"] # a qualified miss must NOT fall back to a union
assert all(not h.get("_symbol_anchored") for h in out)
- assert out[0]["target_path"] == "c/z.py" # nothing injected
@pytest.mark.asyncio
@@ -521,10 +545,11 @@ async def test_anchor_disambiguates_homonym_by_named_parent():
),
]
hits = [{"target_path": "c/z.py", "score": 2.0}]
- out = await _anchor_symbol_hits(
+ out, homonyms = await _anchor_symbol_hits(
_FakeSession(rows), "r", {"extract_all", "DecisionExtractor"}, hits
)
assert out[0]["target_path"] == "b/y.py"
+ assert not homonyms["union"]
@pytest.mark.asyncio
@@ -536,7 +561,7 @@ async def test_anchor_boosts_existing_hit_without_duplicating():
{"target_path": "mcp/tool_symbol.py", "score": 9.4},
{"target_path": "other.py", "score": 7.9},
]
- out = await _anchor_symbol_hits(_FakeSession(rows), "r", {"get_symbol"}, hits)
+ out, _homonyms = await _anchor_symbol_hits(_FakeSession(rows), "r", {"get_symbol"}, hits)
paths = [h["target_path"] for h in out]
assert paths.count("mcp/tool_symbol.py") == 1 # boosted, not duplicated
anchored = next(h for h in out if h["target_path"] == "mcp/tool_symbol.py")
@@ -544,6 +569,56 @@ async def test_anchor_boosts_existing_hit_without_duplicating():
assert anchored["score"] >= 9.4
+def _write(tmp_path, rel, body):
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+ return rel
+
+
+def test_union_bodies_inlines_all_defs_under_budget(tmp_path):
+ """Answer-by-union renders every def body (Read-parity) when they fit."""
+ from repowise.server.mcp_server.tool_answer.symbols import build_homonym_union_bodies
+
+ a = _write(tmp_path, "a/x.py", "def _sev(op):\n return op > 3\n")
+ 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},
+ ]
+ }
+ bodies, more = build_homonym_union_bodies(tmp_path, union)
+ assert len(bodies) == 2 and not more
+ assert {e["path"] for e in bodies} == {a, b}
+ assert "op > 3" in bodies[0]["source"] and "corr < 0.1" in bodies[1]["source"]
+ assert bodies[0]["lines"] == [1, 2]
+
+
+def test_union_bodies_overflow_lists_remainder_as_pointers(tmp_path):
+ """Under a tiny budget, first def always renders; the rest go to
+ more_definitions with a do-NOT-Read get_symbol redirect."""
+ from repowise.server.mcp_server.tool_answer.symbols import build_homonym_union_bodies
+
+ a = _write(tmp_path, "a/x.py", "def _sev(op):\n return op > 3\n")
+ 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},
+ ]
+ }
+ bodies, more = build_homonym_union_bodies(tmp_path, union, char_budget=5)
+ assert len(bodies) == 1 # first always renders even over budget
+ assert len(more) == 1
+ assert more[0]["symbol_id"] == f"{b}::_sev"
+ assert "do NOT Read" in more[0]["hint"]
+
+
# ---------------------------------------------------------------------------
# code_rationale — the T4 lever: in-code rationale recovered when the wiki /
# decision corpus could not ground the question (low-confidence exits).