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(mcp): keep a dead end inside the tool surface, and stop a pathless anchor (#1840)

Raghav Chamadiyac34fb972e6e8
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index e0ba942d1..beb78f825 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -220,7 +220,7 @@ One-call RAG: retrieves over the wiki, gates synthesis on confidence, and return
| `question` | string | Yes | Natural language question about the codebase |
| `repo` | string | No | *(workspace only)* Target repo alias |
-**Returns:** A synthesized answer with file/symbol citations and a confidence label (`high`, `medium`, `low`). High-confidence answers can be cited directly. Low-confidence answers return ranked wiki excerpts instead.
+**Returns:** A synthesized answer with file/symbol citations and a confidence label (`high`, `medium`, `low`). High-confidence answers can be cited directly. Low-confidence answers return ranked wiki candidates instead, with the page excerpt served on the highest-scoring few; the rest carry path, title and summary, and one follow-up call opens any of them.
Two path-bearing blocks, with different jobs:
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index fe9735d51..d627e16de 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -413,9 +413,26 @@ def symbol_hint(symbol_id: str, end_line: int, start_line: int) -> str | None:
return None
+# One wording for each of the two ways a response can be a dead end, so a
+# spelling cannot drift in on its own.
+#
+# The rule they encode: a dead end redirects into another call of OUR surface,
+# naming the tool and the argument to use. An external tool is named only for a
+# job we do not do, which is EXHAUSTIVE_SWEEP_HINT and nothing else.
+NO_HITS_RECOVERY_HINT = (
+ 'Retry search_codebase with mode="symbol" for an identifier or mode="path" '
+ "for a file name; if the question names a file, call get_context on it "
+ "directly."
+)
+
+EXHAUSTIVE_SWEEP_HINT = (
+ "For an exhaustive sweep of every literal usage — before a rename, say — "
+ "Grep the name; that is the one job this surface does not do."
+)
+
+
def answer_hint(
confidence: str,
- retrieval_count: int,
*,
degraded: str | None = None,
retrieval_quality: str | None = None,
@@ -426,6 +443,13 @@ def answer_hint(
Encourages verification when confidence is low; never tells the agent to
"trust the answer" — that's the over-trust failure mode.
+ Deliberately takes no retrieval count. An empty ``retrieval`` block is a
+ confidence-conditional VIEW, not a measure of what retrieval found — a
+ high-confidence answer sets it to ``[]`` on purpose — so keying "no hits"
+ off its length would tell the most trustworthy answers on the surface that
+ there were none. The one site that genuinely knows retrieval came back empty
+ writes its own note there.
+
A degraded payload is keyed separately, because "low" means something
different there. Everywhere else it rates an answer that exists and might be
wrong, so "go verify" is the right push. On a degraded payload there is no
@@ -457,9 +481,4 @@ def answer_hint(
)
if confidence == "low":
return "Low confidence — Read the listed fallback_targets to verify before answering."
- if retrieval_count == 0:
- return (
- "No wiki hits — try search_codebase (mode=symbol/path) or "
- "get_context on the named file; Grep only if those miss too."
- )
return None
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 40b055280..5ab030bd2 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
@@ -101,6 +101,7 @@ from repowise.server.mcp_server._helpers import (
_unsupported_repo_all,
filter_dicts_by_key,
)
+from repowise.server.mcp_server._meta import NO_HITS_RECOVERY_HINT as _NO_HITS_RECOVERY_HINT
from repowise.server.mcp_server._meta import answer_hint as _answer_hint
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._neighbor_rerank import (
@@ -522,10 +523,7 @@ async def get_answer(
return _with_candidates(
_no_answer_payload(
"No wiki hits for this question. Rephrase around the code "
- 'concept, or use search_codebase (mode="symbol" for an '
- 'identifier, mode="path" for a file name); if the question '
- "names a file, call get_context on it directly. Grep only "
- "if those come back empty too.",
+ "concept. " + _NO_HITS_RECOVERY_HINT,
repository=repository,
t0=t0,
),
@@ -752,7 +750,7 @@ async def get_answer(
payload["_meta"] = _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint(confidence, len(hits)),
+ hint=_answer_hint(confidence),
repository=repository,
targets=[*citations, *fallback_targets],
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
index 05631c82c..b7ac19a5b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
@@ -164,10 +164,7 @@ async def _serve_cached_answer(
payload["_meta"] = _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
cached=True,
- hint=_answer_hint(
- payload.get("confidence", "low"),
- len(payload.get("retrieval", [])),
- ),
+ hint=_answer_hint(payload.get("confidence", "low")),
repository=repository,
targets=[p for p in cached_paths if isinstance(p, str) and p],
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/data_shape.py b/packages/server/src/repowise/server/mcp_server/tool_answer/data_shape.py
index 838688204..172cd640c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/data_shape.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/data_shape.py
@@ -629,7 +629,7 @@ def build_data_shape_payload(grounded: dict, t0: float, repository) -> dict:
"note": note,
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint(grounded["confidence"], len(citations)),
+ hint=_answer_hint(grounded["confidence"]),
repository=repository,
targets=citations,
),
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 b75a11a24..b2b2be89e 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
@@ -167,7 +167,6 @@ async def _degraded_payload(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint(
"low",
- len(hits),
degraded=reason,
retrieval_quality=retrieval_quality,
has_bodies=bool(symbol_bodies),
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 6cbc709bb..e31d80373 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
@@ -19,6 +19,7 @@ from repowise.server.mcp_server._answer_context import (
from repowise.server.mcp_server._answer_context import (
is_why_question as _is_why_question,
)
+from repowise.server.mcp_server._meta import NO_HITS_RECOVERY_HINT as _NO_HITS_RECOVERY_HINT
from repowise.server.mcp_server._meta import answer_hint as _answer_hint
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._page_paths import hit_file_path
@@ -211,7 +212,7 @@ def _no_answer_payload(note: str, *, repository, t0: float) -> dict:
"retrieval": [],
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("low", 0),
+ hint=_answer_hint("low"),
repository=repository,
targets=[],
),
@@ -321,7 +322,7 @@ def _union_answer_payload(
"note": note,
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint(_union_confidence, len(union_bodies)),
+ hint=_answer_hint(_union_confidence),
repository=repository,
targets=cited,
),
@@ -369,11 +370,7 @@ async def build_abstain_payload(
"before answering."
)
if best_guesses
- else (
- 'Retry search_codebase with mode="symbol" or '
- 'mode="path" on the key terms; Grep only if those '
- "miss too."
- )
+ else _NO_HITS_RECOVERY_HINT
),
"fallback_targets": fallback_targets,
"retrieval": [],
@@ -392,7 +389,7 @@ async def build_abstain_payload(
)
gated["_meta"] = _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("low", len(hits)),
+ hint=_answer_hint("low"),
repository=repository,
targets=fallback_targets,
)
@@ -430,7 +427,7 @@ def build_value_payload(
),
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("high", len(hits)),
+ hint=_answer_hint("high"),
repository=repository,
targets=[extraction["file"], *fallback_targets],
),
@@ -566,7 +563,14 @@ async def _hedged_payload(
"confidence": confidence,
"retrieval_quality": retrieval_quality,
"fallback_targets": fallback_targets[:5],
- "retrieval": _serialize_hits(hits, limit=5, lean_symbols=True),
+ # The hedge is the priciest reply we send and the least likely to be
+ # right, so it gets the graded low branch's excerpt budget rather than
+ # one of its own. Safe to cut at build time, unlike most payload cuts:
+ # `_cache_bypass_reason` refuses every hedged row, so a hedged reply is
+ # always freshly built and no stored row can keep the wider shape.
+ "retrieval": _serialize_hits(
+ hits, limit=5, lean_symbols=True, excerpt_rows=_GATED_RETURN_HITS
+ ),
"note": (
"Synthesis hedged: the LLM could not ground the question in "
"the indexed wiki. Read one of fallback_targets to answer."
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
index 396f445a4..dd1b6f02b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
@@ -125,6 +125,7 @@ def serialize_hits(
summary_chars: int | None = None,
symbols_for_expanded: bool = True,
lean_symbols: bool = False,
+ excerpt_rows: int | None = None,
) -> list[dict]:
"""Agent-facing view of retrieval hits — content only, no plumbing.
@@ -142,9 +143,16 @@ def serialize_hits(
gated low-confidence path, where the hits are candidates to pick between,
not answer material, and ``best_guesses`` + ``code_rationale`` already
carry the choosing signal.
+
+ ``excerpt_rows`` serves the page excerpt on the first N rows only. An
+ excerpt is ~1,500 characters against ~300 for the whole rest of a row, so it
+ is essentially the entire cost of this block; rows past the cut keep path,
+ title, summary, snippet and score, which is a described candidate rather
+ than a bare pointer. Deliberately a *field* cut and not a row cut: dropping
+ rows takes paths out of the response, and a named path costs almost nothing.
"""
out: list[dict] = []
- for h in hits[: limit if limit is not None else len(hits)]:
+ for idx, h in enumerate(hits[: limit if limit is not None else len(hits)]):
target = h.get("target_path")
entry: dict[str, Any] = {"path": target}
# A symbol_spotlight page's target_path is ``file.py::Symbol``: a page
@@ -160,8 +168,9 @@ def serialize_hits(
summary = summary[: summary_chars - 1].rstrip() + "…"
if summary:
entry["summary"] = summary
+ serve_excerpt = excerpt_rows is None or idx < excerpt_rows
for key in ("snippet", "excerpt"):
- if h.get(key):
+ if h.get(key) and (key != "excerpt" or serve_excerpt):
entry[key] = h[key]
if h.get("score") is not None:
entry["score"] = round(h["score"], 3)
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 fbd74139f..f91994db5 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
@@ -496,6 +496,13 @@ async def _anchor_symbol_hits(
anchor_score = max(top_score + 2.0, _HIGH_CONFIDENCE_SCORE_FLOOR + 1.0)
for sym in chosen:
fp = sym.file_path
+ if not fp:
+ # The same guard the concept-anchoring twin applies to its winner.
+ # An anchor scores above every real hit by construction, so a
+ # pathless one takes rank 1 and serves a row carrying nothing but a
+ # score — no path, title, summary or excerpt — while displacing a
+ # real hit from the synthesis window.
+ continue
target = by_path.get(fp)
if target is None:
target = {
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index b6923a9bf..393db7688 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -31,6 +31,7 @@ from repowise.server.mcp_server._helpers import (
resolve_enum_argument,
vector_search_timeout_s,
)
+from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._page_paths import file_candidates, hit_file_path
from repowise.server.mcp_server._prose_symbols import symbol_backed_pages
@@ -806,17 +807,14 @@ def _grep_hint_for(query: str) -> str | None:
if _looks_like_exact_token(query):
return (
f"No indexed match for identifier {query!r}. Retry with "
- 'mode="symbol" (or check spelling/casing); if you need every '
- "literal usage for an exhaustive sweep such as a rename, Grep "
- "is the right tool for that."
+ 'mode="symbol" (or check spelling/casing). ' + EXHAUSTIVE_SWEEP_HINT
)
if idents := _embedded_identifiers(query):
shown = ", ".join(repr(t) for t in idents[:3])
return (
f"Query names identifier(s) {shown} but nothing matched. Search "
'the identifier alone with mode="symbol", then pipe the hit '
- "into get_symbol for its body. For an exhaustive every-usage "
- "sweep, Grep the literal name."
+ "into get_symbol for its body. " + EXHAUSTIVE_SWEEP_HINT
)
return None
@@ -972,8 +970,7 @@ async def _structured_search(
f"No indexed symbol exactly matches {shown}. The results are "
"fuzzy neighbours ranked by token overlap — confirm a hit names "
"what you meant before relying on it. If you expected an exact "
- "symbol, recheck spelling/casing, or Grep the literal name for "
- "an exhaustive usage sweep."
+ "symbol, recheck spelling/casing. " + EXHAUSTIVE_SWEEP_HINT
)
if grep_hint and not results:
response["grep_hint"] = grep_hint
diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.py
index 6ef6565f8..ef643f315 100644
--- a/tests/unit/cli/test_search_collapse.py
+++ b/tests/unit/cli/test_search_collapse.py
@@ -26,6 +26,7 @@ from click.testing import CliRunner
from repowise.cli.commands import _tool_adapters as _ta
from repowise.cli.commands.risk_cmd import project_risk, risk_command
from repowise.cli.commands.search_cmd import project, search_command
+from repowise.server.mcp_server.tool_search import _grep_hint_for
# --------------------------------------------------------------------------
# Payloads shaped like the real tools build them
@@ -98,10 +99,10 @@ SYMBOL_MISS_PAYLOAD = {
"No indexed symbol exactly matches 'reslove_width'. The results are fuzzy "
"neighbours ranked by token overlap — confirm a hit names what you meant."
),
- "grep_hint": (
- "No indexed match for identifier 'reslove_width'. Retry with mode=\"symbol\"; "
- "if you need every literal usage, Grep is the right tool for that."
- ),
+ # Taken from the server rather than hand-written: a fixture that spells the
+ # hint itself is one more copy of a wording the tools keep in one place, and
+ # it drifts silently because nothing compares the two.
+ "grep_hint": _grep_hint_for("reslove_width"),
"_meta": META,
}
diff --git a/tests/unit/server/mcp/test_answer_calibration.py b/tests/unit/server/mcp/test_answer_calibration.py
index ae24fdc3b..e23139ca3 100644
--- a/tests/unit/server/mcp/test_answer_calibration.py
+++ b/tests/unit/server/mcp/test_answer_calibration.py
@@ -659,6 +659,27 @@ async def test_anchor_injects_defining_file_as_dominant_hit():
assert not homonyms["union"] # single resolved def, no union
+async def test_anchor_skips_a_symbol_with_no_file_path():
+ """A pathless symbol must not become a hit."""
+ from repowise.server.mcp_server.tool_answer.symbols import _anchor_symbol_hits
+
+ rows = [
+ _Sym(
+ "extract_all",
+ "",
+ parent_name="DecisionExtractor",
+ qualified_name="DecisionExtractor.extract_all",
+ )
+ ]
+ hits = [{"target_path": "core/pipeline/incremental.py", "score": 3.6}]
+ out, _ = await _anchor_symbol_hits(
+ _FakeSession(rows), "repo1", {"extract_all", "DecisionExtractor"}, hits
+ )
+ assert all(h.get("target_path") for h in out)
+ assert out[0]["target_path"] == "core/pipeline/incremental.py"
+
+
@pytest.mark.asyncio
async def test_anchor_unresolvable_homonym_becomes_union():
"""A bare homonym (no qualifier) is not injected as a hit — its full def
diff --git a/tests/unit/server/mcp/test_answer_payload.py b/tests/unit/server/mcp/test_answer_payload.py
index f6ee5e3e2..9c46e24bb 100644
--- a/tests/unit/server/mcp/test_answer_payload.py
+++ b/tests/unit/server/mcp/test_answer_payload.py
@@ -156,6 +156,19 @@ class TestSerializeHits:
[kept] = serialize_hits([expanded], symbols_for_expanded=True)
assert "key_symbols" in kept
+ def test_excerpt_rows_cuts_the_excerpt_and_nothing_else(self) -> None:
+ hits = [dict(RAW_HIT, target_path=f"pkg/m{i}.py", excerpt="E" * 1500) for i in range(5)]
+ rows = serialize_hits(hits, limit=5, excerpt_rows=3)
+ assert [("excerpt" in r) for r in rows] == [True, True, True, False, False]
+ # The cut is a field cut, not a row cut: every path still ships, which is
+ # what keeps a withheld excerpt one follow-up call away rather than lost.
+ assert [r["path"] for r in rows] == [f"pkg/m{i}.py" for i in range(5)]
+ assert all({"title", "summary", "snippet", "score"} <= set(r) for r in rows)
+
+ def test_excerpt_rows_unset_serves_every_excerpt(self) -> None:
+ hits = [dict(RAW_HIT, target_path=f"pkg/m{i}.py", excerpt="E" * 1500) for i in range(5)]
+ assert all("excerpt" in r for r in serialize_hits(hits, limit=5))
+
# ---------------------------------------------------------------------------
# Confidence-conditional retrieval through get_answer
diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.py
index 9eeca944b..405092747 100644
--- a/tests/unit/server/mcp/test_meta_freshness.py
+++ b/tests/unit/server/mcp/test_meta_freshness.py
@@ -213,3 +213,28 @@ def test_changed_files_between_real_git(tmp_path):
assert changed == frozenset({"b.py"})
# Unknown SHA → None (fail toward warning), and the miss is cached too.
assert _meta._changed_files_between(str(tmp_path), "f" * 40, sha2) is None
+
+
+def test_confident_answer_is_never_told_retrieval_found_nothing() -> None:
+ """A high-confidence answer empties ``retrieval`` deliberately, so the hint
+ must never read that block's length as a count of what retrieval found.
+ Every cached reply re-derives its hint from the stored payload, which is
+ where such a misreading would reach the most trustworthy answers we send."""
+ from repowise.server.mcp_server._meta import answer_hint
+
+ assert answer_hint("high") is None
+ assert answer_hint("medium") is None
+ assert "Read the listed fallback_targets" in (answer_hint("low") or "")
+
+
+def test_no_answer_hint_names_an_external_tool() -> None:
+ """A dead end redirects into our own surface; only the exhaustive-sweep
+ wording may name an external tool, and it is not a get_answer hint."""
+ from repowise.server.mcp_server._meta import NO_HITS_RECOVERY_HINT, answer_hint
+
+ hints = [answer_hint(c) for c in ("high", "medium", "low")]
+ hints += [answer_hint("low", degraded="no-llm-provider", retrieval_quality=q)
+ for q in ("high", "partial", "weak")]
+ assert not [h for h in hints if h and "Grep" in h]
+ assert "Grep" not in NO_HITS_RECOVERY_HINT
+ assert "search_codebase" in NO_HITS_RECOVERY_HINT