Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(answer): serve a body the question names only as context as evidence, not as the answer (#3771)

Swati Ahujae9313946336a
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 81461e243..15d720d67 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
@@ -538,6 +538,7 @@ async def get_answer(
repository,
t0,
_retrieval_quality(hits, agreement_dominant, question),
+ hits,
)
if union_payload is not None:
return _with_candidates(
@@ -704,11 +705,12 @@ async def get_answer(
quotes = build_quotes(hits, answer_text)
- # ``served_named_body``: the question-named symbol's live body is inlined, so
- # the response is content-grounded even when synthesis hedges.
+ # ``served_named_body``: the question-named symbol's live body is inlined and
+ # carries what was asked, so the response is content-grounded even when
+ # synthesis hedges.
repo_root = _repo_root(ctx)
symbol_bodies, served_named_body = _build_symbol_bodies(
- _gather_body_candidates(hits, answer_text), repo_root
+ _gather_body_candidates(hits, answer_text), repo_root, question=question, hits=hits
)
# One coverage measurement for the grade and the retrieval rating.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
index 56e2ba88a..b2d2eecfc 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from pathlib import Path
from repowise.server.mcp_server._verify import end_anchor_holds, name_at_line
+from repowise.server.mcp_server.tool_answer.confidence import body_leaves_out, hit_stems
from repowise.server.mcp_server.tool_answer.config import (
_ENRICH_TOP_N_HITS,
_INLINE_BODY_MAX_LINES,
@@ -103,12 +104,18 @@ def _is_named_definition(s: dict, answer_text: str) -> bool:
def _build_symbol_bodies(
- body_candidates: list[tuple[int, int, int, str, dict]], repo_root: Path | None
+ body_candidates: list[tuple[int, int, int, str, dict]],
+ repo_root: Path | None,
+ *,
+ question: str = "",
+ hits: list[dict] | None = None,
) -> tuple[list[dict], bool]:
"""Inline the ranked definitions as live source, with the truncation contract.
Returns ``(symbol_bodies, served_named_body)``; the latter is True once a
- tier-0 body (the exact symbol the question named) is inlined.
+ tier-0 body (the exact symbol the question named) is inlined that also
+ carries the rest of *question* (:func:`body_leaves_out`). A body named only
+ as the place the question asks about is still served, not as the answer.
Prose-independent, so the degraded path calls it too: bodies are re-read
live at the indexed bounds, and a body past the line cap gets a
@@ -119,6 +126,7 @@ def _build_symbol_bodies(
seen: set[tuple[str, str]] = set()
served_named_body = False
texts: dict[str, str | None] = {}
+ served_stems = hit_stems(hits or []) if question else []
for tier, _kind, start, path, s in body_candidates:
if len(symbol_bodies) >= _INLINE_BODY_MAX_SYMBOLS:
break
@@ -162,7 +170,7 @@ def _build_symbol_bodies(
)
symbol_bodies.append(entry)
seen.add((path, name))
- if tier == 0:
+ if tier == 0 and not body_leaves_out(question, {**s, "source": body}, served_stems):
served_named_body = True
return symbol_bodies, served_named_body
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py b/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py
index ad752e9de..8264367ac 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
@@ -517,16 +517,50 @@ def uncovered_terms(question: str, hits: list[dict]) -> list[str]:
Returns ``[]`` when the hit covers at least :data:`_ANSWER_COVERAGE_FLOOR`
of that weight.
"""
+ if not hits:
+ return []
+ served = hit_stems(hits)
+ return _left_out(_question_words(question), served[0], served)
+
+
+def hit_stems(hits: list[dict]) -> list[set[str]]:
+ """Each hit's served text as stems, the population coverage weighs words over."""
+ return [_text_stems(_retrieval_corpus([h], include_paths=True)) for h in hits]
+
+
+def body_leaves_out(question: str, body: dict, served: list[set[str]]) -> list[str]:
+ """The question's words a body served for the name it carries leaves out.
+
+ A question can name a function as the place it asks about ("the FTS
+ timeout in get_answer"): the body is the named code, not the answer. The
+ words besides the body's own name and owner that some retrieved hit
+ carries (*served*, from :func:`hit_stems`) must be in its source, weighed
+ as in :func:`uncovered_terms`. A word no hit carries ("definitions",
+ "parameters") is framing, not a fact found elsewhere, so it never counts.
+ ``[]`` when nothing else is asked.
+ """
+ named = _text_stems(f"{body.get('name') or ''} {body.get('parent_name') or ''}")
words = {
- t: w for t, w in _text_words(question).items() if t not in _QUESTION_FRAME_STEMS
+ t: w
+ for t, w in _question_words(question).items()
+ if t not in named and any(_stem_hit(t, s) for s in served)
}
- if not words or not hits:
+ return _left_out(words, _text_stems(body.get("source") or ""), served)
+
+
+def _question_words(question: str) -> dict[str, str]:
+ return {t: w for t, w in _text_words(question).items() if t not in _QUESTION_FRAME_STEMS}
+
+
+def _left_out(words: dict[str, str], covering: set[str], served: list[set[str]]) -> list[str]:
+ """*words* missing from *covering*, when their rarity weight across *served*
+ exceeds what :data:`_ANSWER_COVERAGE_FLOOR` lets go."""
+ if not words:
return []
- served = [_text_stems(_retrieval_corpus([h], include_paths=True)) for h in hits]
weight = {
t: window_term_weight(sum(_stem_hit(t, s) for s in served), len(served)) for t in words
}
- missing = [t for t in words if not _stem_hit(t, served[0])]
+ missing = [t for t in words if not _stem_hit(t, covering)]
left_out = sum(weight[t] for t in missing)
if left_out <= (1.0 - _ANSWER_COVERAGE_FLOOR) * sum(weight.values()):
return []
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 1acc5150a..5221cca97 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
@@ -306,7 +306,8 @@ _ANSWER_COVERAGE_FLOOR = 0.5
# 21: impact questions carry ``graph_neighbors``, the users of the lead file.
# 22: ``confidence`` also asks whether the top hit covers the question's words.
# 23: bodies include the function holding a literal the question writes, and an
-# exact name off the topic no longer anchors its definition.
+# exact name off the topic no longer anchors its definition; a question-named
+# body grounds the answer only when it carries what else was asked.
_ANSWER_SCHEMA_VERSION = 23
# Above this a whole-file Read costs more than the answer, so the low-confidence
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
index 1f94e510c..02bee7b49 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
@@ -122,14 +122,18 @@ async def _degraded_payload(
"""
retrieval_quality = _retrieval_quality(hits, agreement_dominant, question)
repo_root = _repo_root(ctx)
- symbol_bodies, _served_named_body = _build_symbol_bodies(
+ # A named body that leaves out the rest of the question is served as
+ # evidence, never as the answer the payload leads with.
+ symbol_bodies, served_named_body = _build_symbol_bodies(
_gather_body_candidates(hits, "", anchor_names=question_ids or set()),
repo_root,
+ question=question,
+ hits=hits,
)
# Inlined bodies are citations in the ordinary sense.
citations = list(dict.fromkeys(b["path"] for b in symbol_bodies))
- summary = _degraded_summary(reason, symbol_bodies, len(hits))
+ summary = _degraded_summary(reason, symbol_bodies if served_named_body else [], len(hits))
best_guesses = _build_best_guesses(hits)
# No quotes to check against here — there is no prose to quote from.
@@ -154,7 +158,7 @@ async def _degraded_payload(
citations.append(path)
# The file ``answer`` will name first, in the projection's order.
- if symbol_bodies:
+ if served_named_body:
lead = symbol_bodies[0]["path"]
elif best_guesses:
lead = best_guesses[0]["file"]
@@ -188,6 +192,7 @@ async def _degraded_payload(
)
if symbol_bodies:
payload["symbol_bodies"] = symbol_bodies
+ if served_named_body:
payload["grounding"] = "symbol_body"
payload["next_action_hint"] = await _degraded_next_action(
symbol_bodies, ctx, repository, exclude_spec
@@ -210,7 +215,7 @@ async def _degraded_payload(
confidence,
degraded=reason,
retrieval_quality=retrieval_quality,
- has_bodies=bool(symbol_bodies),
+ has_bodies=served_named_body,
),
repository=repository,
targets=[*citations, *fallback_targets],
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py b/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py
index 2c1024b31..1ebbe7c72 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
@@ -26,6 +26,8 @@ from repowise.server.mcp_server._page_paths import hit_file_path
from repowise.server.mcp_server.tool_answer.confidence import (
_Grade,
_is_enclosing_continuation,
+ body_leaves_out,
+ hit_stems,
)
from repowise.server.mcp_server.tool_answer.config import (
_GATED_RETURN_HITS,
@@ -200,6 +202,7 @@ def _union_answer_payload(
repository,
t0: float,
retrieval_quality: str,
+ hits: list[dict] | None = None,
) -> dict | None:
"""The answer-by-union reply, or None to let synthesis handle the question.
@@ -209,7 +212,8 @@ def _union_answer_payload(
Returns None when the union is not the answer: a prose question merely
mentioning a generic many-def method, a mechanism question whose answer
- often lives elsewhere, or unreadable bodies.
+ often lives elsewhere, a question no body carries the rest of
+ (:func:`body_leaves_out`), or unreadable bodies.
"""
union_groups = homonyms.get("union") or {}
if union_groups and union_defers_to_synthesis(question, question_ids, union_groups):
@@ -220,7 +224,8 @@ def _union_answer_payload(
return None
repo_root = _repo_root(ctx)
union_bodies, more_defs = build_homonym_union_bodies(repo_root, union_groups)
- if not union_bodies:
+ served = hit_stems(hits or [])
+ if not union_bodies or all(body_leaves_out(question, b, served) for b in union_bodies):
return None
names = sorted(union_groups)
total = sum(len(v) for v in union_groups.values())
@@ -524,11 +529,7 @@ async def _hedged_payload(
"the full live body of the symbol(s) you named — cite that "
"directly, no verification Read needed."
)
- else:
- payload["note"] = (
- "Synthesis hedged, but symbol_bodies carries the live body "
- "of the symbol(s) you named — read that to answer."
- )
+ # Otherwise the bodies lack what was asked: the note's fallback_targets stand.
# A hedge often means the rationale is a code comment, not wiki prose. A
# comment already visible in symbol_bodies must not surface twice.
code_rationale = await _gather_code_rationale(ctx, hits, fallback_targets, question)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
index 38db94b89..b78e4b1d0 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
@@ -271,11 +271,19 @@ def _rewrite_degraded_answer(payload: dict[str, Any]) -> None:
reason = payload.get("degraded")
if not reason:
return
- if payload.get("symbol_bodies"):
+ if payload.get("symbol_bodies") and payload.get("grounding"):
payload["answer"] = (
f"Synthesis is unavailable ({reason}), but symbol_bodies contains live source "
"for the named code. Use that evidence directly."
)
+ elif payload.get("symbol_bodies"):
+ # No ``grounding``: the question names this code as the place it asks about.
+ payload["answer"] = (
+ f"Synthesis is unavailable ({reason}). symbol_bodies holds the code the "
+ "question names, but not what it asks; "
+ f"{'best_guesses' if payload.get('best_guesses') else 'retrieval'} "
+ "ranks the files to read."
+ )
elif (row := _lead_rationale(payload)) is not None:
conclusion = _text(row, "rationale", "comment", "quote", "source", "text")
path = _path(row) or "the top source match"
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 3bc4f4cbe..7c63ad2ed 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
@@ -497,6 +497,7 @@ async def _anchor_chosen_symbols(
{
"name": sym.name,
"kind": sym.kind,
+ "parent_name": sym.parent_name,
"start_line": vd["start_line"],
"end_line": vd["end_line"],
**({"_named_by": named_by} if named_by else {}),
diff --git a/tests/unit/server/mcp/test_answer_context_named_body.py b/tests/unit/server/mcp/test_answer_context_named_body.py
new file mode 100644
index 000000000..9767e129c
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_context_named_body.py
@@ -0,0 +1,176 @@
+"""get_answer: a body the question names only as the place it asks about.
+
+"Is prefix matching enabled by default when Execute runs?" names ``Execute``,
+so its body is served, but the asked fact lives elsewhere. Such a body stays
+in ``symbol_bodies`` as evidence and is never presented as the answer.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.server.mcp_server.tool_answer.answer import _degraded_payload
+from repowise.server.mcp_server.tool_answer.bodies import _build_symbol_bodies
+from repowise.server.mcp_server.tool_answer.confidence import body_leaves_out, hit_stems
+from repowise.server.mcp_server.tool_answer.payload import _union_answer_payload
+from repowise.server.mcp_server.tool_answer.projection import project_answer_payload
+
+_EXECUTE = "func (c *Command) Execute() error {\n\t_, err := c.ExecuteC()\n\treturn err\n}\n"
+_HOOK = (
+ "func preExecHook(c *Command) {\n"
+ "\tif MousetrapHelpText != \"\" {\n"
+ "\t\tc.Print(MousetrapHelpText)\n"
+ "\t\ttime.Sleep(MousetrapDisplayDuration)\n"
+ "\t}\n"
+ "}\n"
+)
+
+
+def _body(name: str, source: str) -> dict:
+ return {"name": name, "source": source}
+
+
+# Retrieval found the fact in another file: the word is asked, not framing.
+_ELSEWHERE = [
+ {"target_path": "cobra.go", "summary": "defaultPrefixMatching sets prefix matching"},
+ {"target_path": "command_win.go", "summary": "mousetrap help text display duration"},
+]
+
+
+def test_a_body_without_the_asked_fact_leaves_it_out():
+ q = "Is prefix matching enabled by default when Execute runs?"
+ assert "prefix" in body_leaves_out(q, _body("Execute", _EXECUTE), hit_stems(_ELSEWHERE))
+
+
+def test_a_body_carrying_the_asked_fact_covers_it():
+ q = "How long does preExecHook display the mousetrap help text?"
+ assert body_leaves_out(q, _body("preExecHook", _HOOK), hit_stems(_ELSEWHERE)) == []
+
+
+def test_a_question_about_the_body_itself_asks_nothing_else():
+ q = "What does preExecHook do?"
+ assert body_leaves_out(q, _body("preExecHook", _HOOK), hit_stems(_ELSEWHERE)) == []
+
+
+def test_a_word_no_hit_carries_is_framing():
+ q = "What are the definitions of Execute in this repo?"
+ assert body_leaves_out(q, _body("Execute", _EXECUTE), hit_stems(_ELSEWHERE)) == []
+
+
+def test_the_owner_the_question_names_is_not_asked_of_the_body():
+ q = "How does Command.preExecHook print the mousetrap text?"
+ body = {**_body("preExecHook", _HOOK), "parent_name": "Command"}
+ hits = [*_ELSEWHERE, {"target_path": "command.go", "summary": "Command tree"}]
+ assert body_leaves_out(q, body, hit_stems(hits)) == []
+
+
+def _tree(tmp_path) -> SimpleNamespace:
+ (tmp_path / "command.go").write_text(_EXECUTE, encoding="utf-8")
+ return SimpleNamespace(path=str(tmp_path), session_factory=None)
+
+
+def _hits() -> list[dict]:
+ anchor = {"name": "Execute", "kind": "method", "start_line": 1, "end_line": 4}
+ return [
+ {
+ "target_path": "command.go",
+ "title": "command",
+ "summary": "the command tree",
+ "score": 4.0,
+ "_anchor_symbols": [anchor],
+ },
+ *_ELSEWHERE,
+ ]
+
+
+def test_a_named_body_without_the_asked_fact_is_served_but_not_the_answer(tmp_path):
+ _tree(tmp_path)
+ cands = [(0, 0, 1, "command.go", _hits()[0]["_anchor_symbols"][0])]
+ q = "Is prefix matching enabled by default when Execute runs?"
+ bodies, named = _build_symbol_bodies(cands, tmp_path, question=q, hits=_hits())
+ assert [b["name"] for b in bodies] == ["Execute"]
+ assert named is False
+ _, named = _build_symbol_bodies(cands, tmp_path, question="What does Execute do?", hits=_hits())
+ assert named is True
+
+
+async def _degraded(ctx, question: str) -> dict:
+ payload = await _degraded_payload(
+ reason="no-llm-provider",
+ note="Synthesis is unavailable.",
+ question=question,
+ hits=_hits(),
+ fallback_targets=["command.go"],
+ repository=None,
+ t0=0.0,
+ ctx=ctx,
+ question_ids={"Execute"},
+ exclude_spec=None,
+ )
+ return project_answer_payload(payload, question=question)
+
+
+async def test_the_keyless_reply_does_not_tell_the_agent_to_answer_from_it(tmp_path):
+ payload = await _degraded(
+ _tree(tmp_path), "Is prefix matching enabled by default when Execute runs?"
+ )
+ assert payload["symbol_bodies"][0]["name"] == "Execute"
+ assert "grounding" not in payload
+ assert "not what it asks" in payload["answer"]
+ assert "Use that evidence directly" not in payload["answer"]
+ assert "answer from that" not in payload["note"]
+
+
+async def test_the_keyless_reply_still_answers_from_a_body_that_carries_it(tmp_path):
+ payload = await _degraded(_tree(tmp_path), "What does Execute do?")
+ assert payload["grounding"] == "symbol_body"
+ assert "Use that evidence directly" in payload["answer"]
+
+
+def _union(tmp_path, question: str):
+ for name in ("reader.java", "writer.java"):
+ (tmp_path / name).write_text(
+ "public void beginArray() {\n push(EMPTY_ARRAY);\n}\n", encoding="utf-8"
+ )
+ defs = [
+ {"name": "beginArray", "file_path": p, "start_line": 1, "end_line": 3}
+ for p in ("reader.java", "writer.java")
+ ]
+ ctx = SimpleNamespace(path=str(tmp_path), session_factory=None)
+ homonyms = {"union": {"beginArray": defs}, "qualified_miss": []}
+ hits = [{"target_path": "reader.java", "summary": "DEFAULT_NESTING_LIMIT caps nesting"}]
+ return _union_answer_payload(
+ question, {"beginArray"}, homonyms, ctx, None, 0.0, "high", hits
+ )
+
+
+def test_a_union_no_body_of_which_carries_the_question_defers(tmp_path):
+ assert _union(tmp_path, "What is the default nesting limit that beginArray enforces?") is None
+
+
+def test_a_union_still_answers_a_question_about_its_bodies(tmp_path):
+ payload = _union(tmp_path, "What does beginArray do?")
+ assert payload is not None and payload["grounding"] == "exact_symbol"
+
+
+async def test_a_hedged_keyed_reply_does_not_ground_on_a_context_body(tmp_path):
+ from repowise.server.mcp_server.tool_answer.payload import _hedged_payload
+
+ ctx = _tree(tmp_path)
+ q = "Is prefix matching enabled by default when Execute runs?"
+ cands = [(0, 0, 1, "command.go", _hits()[0]["_anchor_symbols"][0])]
+ bodies, named = _build_symbol_bodies(cands, tmp_path, question=q, hits=_hits())
+ payload = await _hedged_payload(
+ question=q,
+ answer_text="I could not determine this from the provided context.",
+ citations=["command.go"],
+ confidence="low",
+ retrieval_quality="weak",
+ hits=_hits(),
+ fallback_targets=["cobra.go"],
+ symbol_bodies=bodies,
+ served_named_body=named,
+ ctx=ctx,
+ )
+ assert payload["symbol_bodies"] and "grounding" not in payload
+ assert "cite that directly" not in payload["note"]