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): honesty signals for zero-exact search and filename-only get_symbol (#770)

Raghav Chamadiya90457ddc093c
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 36d083d2d..50f7a7cc1 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -24,6 +24,7 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server.tool_search_symbols import (
+ _qual_norm,
search_paths_single,
search_symbols_single,
)
@@ -63,6 +64,41 @@ def _embedded_identifiers(query: str) -> list[str]:
return _IDENT_TOKEN_RE.findall(query)
+def _identifier_candidates(query: str, mode: str) -> list[str]:
+ """Identifier tokens the query is asking after, for the exact-match signal.
+
+ A single-token query IS the identifier (symbol mode); a natural-language
+ query carrying identifiers (hybrid mode) exposes them the same way
+ ``_resolve_mode`` used to route here. Concept/path queries name none.
+ """
+ if mode == "symbol":
+ q = query.strip()
+ return [q] if q else []
+ if mode == "hybrid":
+ return _embedded_identifiers(query)
+ return []
+
+
+def _has_exact_symbol(candidates: list[str], symbols: list[dict]) -> bool:
+ """True when some returned symbol's name/qualified-name equals a candidate.
+
+ Reuses the scorer's separator-normalisation so an agent's ``Class.method``
+ matches a ``Class::method`` qualified_name in the index. This is the score
+ cliff made explicit: an exact hit and a fuzzy neighbour look identical in
+ the result list otherwise, and the agent anchors on whatever ranks first.
+ """
+ if not candidates or not symbols:
+ return False
+ wanted = {c.strip().lower() for c in candidates if c.strip()}
+ wanted |= {_qual_norm(c) for c in candidates if c.strip()}
+ for s in symbols:
+ name = (s.get("name") or "").strip().lower()
+ qn = _qual_norm(s.get("qualified_name"))
+ if (name and name in wanted) or (qn and qn in wanted):
+ return True
+ return False
+
+
# Decision records are short, dense title-statements; they win cosine
# similarity against long file-page embeddings on any query containing
# design nouns ("store", "SQLite", "cap", "prune") and crowd file pages
@@ -561,6 +597,24 @@ async def _structured_search(
"mode": mode,
"_meta": _build_meta(repository=repository, targets=_result_paths(results)),
}
+ # Exact-match honesty: an identifier-shaped query whose target names no
+ # indexed symbol still returns fuzzy neighbours. Say so, or the agent
+ # anchors on a wrong hit that looks authoritative (their Alamofire
+ # 44-overload read-spiral). Emit the boolean either way; a note only when
+ # there is no exact hit to distinguish from the fuzz.
+ candidates = _identifier_candidates(query, mode)
+ if candidates:
+ exact = _has_exact_symbol(candidates, symbols)
+ response["exact_match"] = exact
+ if not exact:
+ shown = ", ".join(repr(c) for c in candidates[:3])
+ response["note"] = (
+ 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."
+ )
if grep_hint and not results:
response["grep_hint"] = grep_hint
return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index d3ff5e8c4..4e7ad72d4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -24,6 +24,10 @@ Resolution strategy (in order):
1. Exact match on WikiSymbol.symbol_id (the canonical "{path}::{name}" key)
2. Exact match on (file_path, qualified_name) — supports class.method form
3. Exact match on (file_path, name) — supports unqualified names
+ 4. Suffix match — a bare filename or partial path ("answer.py::get_answer")
+ resolves against any file whose path ends with that segment, on the leaf
+ name; mirrors get_context's basename ladder. A total miss returns
+ ``suggestions`` (real path-qualified ids) instead of a bare "not found".
The tool also resolves **omission refs**: a ``symbol_id`` of the form
``"repowise#<12-hex>"`` (from a ``[repowise#<ref>: ...]`` truncation marker)
@@ -44,7 +48,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import or_, select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import WikiSymbol
@@ -448,9 +452,61 @@ async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> list[WikiSym
if rows:
return _order_candidates(rows, file_path)
+ # 4. Suffix file-path match — the caller passed a bare filename or partial
+ # path ("answer.py::get_answer") instead of the full indexed path.
+ # Resolve against any file whose path ends with that segment on a "/"
+ # boundary, on the bare leaf name. Mirrors get_context's basename ladder
+ # so both tools accept the same shorthand instead of a dead "not found".
+ if file_path and name:
+ from repowise.server.mcp_server.tool_context.targets import _escape_like
+
+ esc = _escape_like(file_path.strip("/").replace("\\", "/"))
+ bare = _bare_name(name)
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.name == bare,
+ or_(
+ WikiSymbol.file_path == file_path.strip("/").replace("\\", "/"),
+ WikiSymbol.file_path.like(f"%/{esc}", escape="\\"),
+ ),
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ return _order_candidates(rows, file_path)
+
return []
+async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spec) -> list[str]:
+ """Concrete symbol_ids to retry when a lookup misses entirely.
+
+ The caller usually had the right leaf name but a wrong or partial path.
+ Match that name across every file and hand back real ids (path-qualified)
+ the agent can pass straight back to get_symbol — a bare "not found" would
+ otherwise send it to get_context or a whole-file Read.
+ """
+ _, name = _parse_symbol_id(symbol_id)
+ if not name:
+ return []
+ bare = _bare_name(name)
+ res = await session.execute(
+ select(WikiSymbol.symbol_id, WikiSymbol.file_path)
+ .where(WikiSymbol.repository_id == repo_id, WikiSymbol.name == bare)
+ .limit(20)
+ )
+ out: list[str] = []
+ seen: set[str] = set()
+ for sid, fpath in res.all():
+ if sid and sid not in seen and not is_excluded(fpath, exclude_spec):
+ seen.add(sid)
+ out.append(sid)
+ if len(out) >= 5:
+ break
+ return out
+
+
def _read_file_text(repo_path: Path, file_path: str) -> str | None:
"""Read a repo file's live text, or None when unreadable/outside the root."""
abs_path = (repo_path / file_path).resolve()
@@ -696,6 +752,22 @@ async def get_symbol(
targets=[file_part],
),
}
+ async with get_session(ctx.session_factory) as session:
+ suggestions = await _symbol_suggestions(session, repository.id, symbol_id, exclude_spec)
+ if suggestions:
+ return {
+ "symbol_id": symbol_id,
+ "error": (
+ f"Symbol not found: {symbol_id!r}. A symbol with this name "
+ "exists at the path(s) below — retry with one of these "
+ "exact symbol_ids."
+ ),
+ "suggestions": suggestions,
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ repository=repository,
+ ),
+ }
return {
"symbol_id": symbol_id,
"error": (
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index 73a541236..67dea6053 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -510,3 +510,57 @@ class TestIdentifierGrepHint:
result = await search_codebase("authentication flow for the service")
assert "grep_hint" not in result
+
+
+class TestExactMatchSignal:
+ """An identifier query says whether any hit is an EXACT symbol match, so
+ the agent doesn't anchor on a fuzzy neighbour that ranks first (finding 1)."""
+
+ def test_has_exact_symbol_matches_name(self):
+ from repowise.server.mcp_server.tool_search import _has_exact_symbol
+
+ syms = [{"name": "get_answer", "qualified_name": "get_answer"}]
+ assert _has_exact_symbol(["get_answer"], syms)
+ assert not _has_exact_symbol(["get_answerX"], syms)
+ assert not _has_exact_symbol([], syms)
+ assert not _has_exact_symbol(["get_answer"], [])
+
+ def test_has_exact_symbol_normalizes_separators(self):
+ # An agent's "Class.method" must match a "Class::method" qualified_name.
+ from repowise.server.mcp_server.tool_search import _has_exact_symbol
+
+ syms = [{"name": "method", "qualified_name": "Class::method"}]
+ assert _has_exact_symbol(["Class.method"], syms)
+
+ def test_identifier_candidates_by_mode(self):
+ from repowise.server.mcp_server.tool_search import _identifier_candidates
+
+ assert _identifier_candidates("AuthService", "symbol") == ["AuthService"]
+ assert _identifier_candidates("where is AuthService defined", "hybrid") == ["AuthService"]
+ assert _identifier_candidates("rate limiting", "concept") == []
+
+ @pytest.mark.asyncio
+ async def test_exact_hit_sets_true_and_no_note(self, setup_mcp):
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase("AuthService", mode="symbol")
+ assert result["exact_match"] is True
+ assert "note" not in result
+
+ @pytest.mark.asyncio
+ async def test_fuzzy_only_sets_false_with_note(self, setup_mcp):
+ # "AuthServiceXyz" token-overlaps AuthService (a hit) but matches no
+ # symbol exactly — the signal must fire even though results are non-empty.
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase("AuthServiceXyz", mode="symbol")
+ assert result["results"], "fuzzy neighbour should still be returned"
+ assert result["exact_match"] is False
+ assert "exactly matches" in result.get("note", "")
+
+ @pytest.mark.asyncio
+ async def test_concept_query_gets_no_signal(self, setup_mcp):
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase("authentication flow for the service")
+ assert "exact_match" not in result
diff --git a/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py b/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py
index 7d31890bf..235733504 100644
--- a/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py
+++ b/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py
@@ -134,6 +134,59 @@ async def test_unambiguous_lookup_is_unchanged_shape(setup_mcp, repo_on_disk, se
assert " 10\t return x + 1" in result["source"]
+async def _add_alpha_row(session):
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository, WikiSymbol
+
+ repo = (await session.execute(select(Repository))).scalars().first()
+ session.add(
+ WikiSymbol(
+ id="alpha1",
+ repository_id=repo.id,
+ file_path="pkg/mod.py",
+ symbol_id="pkg/mod.py::alpha",
+ name="alpha",
+ qualified_name="alpha",
+ kind="function",
+ signature="def alpha(x)",
+ start_line=9,
+ end_line=10,
+ language="python",
+ )
+ )
+ await session.flush()
+
+
+async def test_filename_only_id_resolves_via_suffix(setup_mcp, repo_on_disk, session):
+ # A bare filename ("mod.py::alpha") must resolve to the full indexed path
+ # via the suffix ladder, not dead-end on "not found" (finding 2).
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_alpha_row(session)
+ result = await get_symbol("mod.py::alpha")
+
+ assert result.get("error") is None
+ assert result["symbol_id"] == "pkg/mod.py::alpha"
+ assert result["verified"] is True
+ assert " 9\tdef alpha(x):" in result["source"]
+
+
+async def test_total_miss_returns_symbol_id_suggestions(setup_mcp, repo_on_disk, session):
+ # A wrong path with a real leaf name returns retryable path-qualified ids
+ # instead of a bare "not found".
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_alpha_row(session)
+ result = await get_symbol("nope/wrong.py::alpha")
+
+ assert "source" not in result
+ assert result["suggestions"] == ["pkg/mod.py::alpha"]
+ assert "retry" in result["error"].lower()
+
+
@pytest.mark.asyncio
async def test_range_read_source_is_numbered(setup_mcp, repo_on_disk):
from repowise.server.mcp_server import get_symbol