Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): resolve Class.method and bare unique names the same way everywhere (#3099)
Raghav Chamadiya5201e0605eb7
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex d7b869c12..62c7c7a77 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -54,7 +54,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._index_state import index_state_keyfrom repowise.server.mcp_server._references import path_identity, symbol_identity-from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows+from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows, symbol_id_variantsfrom repowise.server.mcp_server.tool_context.enrichment import (_DOC_DRIFT_PATH,_resolve_call_graph,@@ -404,6 +404,9 @@ async def _resolve_one_target(# Set only when a symbol target resolved through the call graph rather than# the symbol index (index-only mode); carries the fields the node has.graph_symbol: GraphNode | None = None+ # The resolved symbol's graph id. Graph queries key on it, never on the+ # caller's spelling, so ``Class.method`` and ``Class::method`` agree.+ symbol_node_id: str | None = Noneif page and page.repository_id == repo_id:target_type = "file"@@ -490,6 +493,7 @@ async def _resolve_one_target(if sym_matches:target_type = "symbol"file_path_for_git = sym_matches[0].file_path+ symbol_node_id = sym_matches[0].symbol_idelse:# 4. Try file page by target_path searchres = await session.execute(@@ -507,18 +511,25 @@ async def _resolve_one_target(if target_type is None:# Fallback 1: index-only mode (no wiki pages). Return the graph node,# typed by what it is: a symbol node is a symbol target whose file is- # the node's file, not its id.+ # the node's file, not its id. Every separator form is tried, as the+ # symbol rung does. Among several, the verbatim id wins, then a symbol+ # node, then the id order, so the pick never depends on row order.res = await session.execute(select(GraphNode).where(GraphNode.repository_id == repo_id,- GraphNode.node_id == target,+ GraphNode.node_id.in_(symbol_id_variants(target)),))- gnode = res.scalar_one_or_none()+ gnode = min(+ res.scalars().all(),+ key=lambda g: (g.node_id != target, g.node_type != "symbol", g.node_id),+ default=None,+ )if gnode is not None and gnode.node_type == "symbol":target_type = "symbol"graph_symbol = gnodefile_path_for_git = gnode.file_path+ symbol_node_id = gnode.node_idpage = Noneelif gnode is not None:target_type = "file"@@ -1263,7 +1274,7 @@ async def _resolve_one_target(await _resolve_call_graph(session,repository,- target,+ symbol_node_id or target,target_type,result_data,want_callers=want_callers,@@ -1274,12 +1285,12 @@ async def _resolve_one_target(# --- Metrics (replaces get_graph_metrics) ---if include and "metrics" in include:- await _resolve_metrics(session, repository, target, result_data)+ await _resolve_metrics(session, repository, symbol_node_id or target, result_data)# --- Community (replaces get_community) ---if include and "community" in include:await _resolve_community(- session, repository, target, result_data, exclude_spec=exclude_spec+ session, repository, symbol_node_id or target, result_data, exclude_spec=exclude_spec)# --- Code health (Phase 2) ---diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 14a1a846c..e9a11bc45 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -110,6 +110,20 @@ _MAX_RANGE_LINES = 200# but the file exists on disk._MAX_FALLBACK_MATCHES = 8+# A matched line that declares the name rather than using it: a definition+# keyword at line start, after decorators and modifiers. Keyword-based, so a+# definition without one (``const f = () =>``) reads as a plain match.+_DEF_KEYWORDS = r"(?:def|class|function\*?|func|fn|struct|interface|enum|trait|type|module|sub)"+_DEF_MODIFIERS = (+ r"(?:(?:export|default|pub(?:\([^)]*\))?|public|private|protected|internal|static"+ r"|abstract|final|override|virtual|async|unsafe|extern|inline|open|sealed|partial|data)\s+)*"+)+_COMMENT_PREFIXES = ("#", "//", "/*", "*", "--", ";")++# Rows read when matching a name across files. A scan that fills it is not+# exhaustive, so its single survivor is never taken as the only match.+_NAME_SCAN_CAP = 20+# When a lookup is ambiguous (overloads, re-exports, conditional defs) every# candidate body is served in ONE response — a silently-picked wrong candidate# sends the agent into a read-spiral that costs far more than the extra bytes.@@ -637,12 +651,18 @@ def _live_grep_fallback(repo_root: Path, file_path: str, name: str) -> list[dictbare = _bare_name(name)if not bare:return []+ defines = re.compile(+ rf"^\s*(?:@\S+\s+)*{_DEF_MODIFIERS}{_DEF_KEYWORDS}\s+(?:\([^)]*\)\s*)?{re.escape(bare)}\b"+ )lines = text.splitlines()matches: list[dict] = []for i, line in enumerate(lines, 1):if bare in line:lo, hi = max(1, i - 2), min(len(lines), i + 2)- matches.append({"line": i, "context": _number_lines("\n".join(lines[lo - 1 : hi]), lo)})+ match = {"line": i, "context": _number_lines("\n".join(lines[lo - 1 : hi]), lo)}+ if not line.lstrip().startswith(_COMMENT_PREFIXES) and defines.match(line):+ match["defines"] = True+ matches.append(match)if len(matches) >= _MAX_FALLBACK_MATCHES:breakreturn matches@@ -660,6 +680,31 @@ _order_candidates = order_candidates_resolve_symbol = resolve_symbol_rows+async def _symbols_named(+ session, repo_id: str, symbol_id: str, exclude_spec+) -> tuple[list[str], bool]:+ """Non-excluded ids of symbols carrying the name in *symbol_id*.++ The second value says whether the scan saw every row with that name, so a+ caller can tell "exactly one" from "one survivor of a capped scan".+ """+ qualified = "::" in symbol_id+ # A bare name is matched whole: it has no path half to strip.+ name = _parse_symbol_id(symbol_id)[1] if qualified else symbol_id.strip()+ if not name:+ return [], True+ bare = _bare_name(name) if qualified else name+ res = await session.execute(+ select(WikiSymbol.symbol_id, WikiSymbol.file_path)+ .where(WikiSymbol.repository_id == repo_id, WikiSymbol.name == bare)+ .order_by(WikiSymbol.symbol_id)+ .limit(_NAME_SCAN_CAP)+ )+ rows = res.all()+ ids = [sid for sid, fpath in rows if sid and not is_excluded(fpath, exclude_spec)]+ return list(dict.fromkeys(ids)), len(rows) < _NAME_SCAN_CAP++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.@@ -668,24 +713,8 @@ async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spethe agent can pass straight back to get_symbol — a bare "not found" wouldotherwise 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+ ids, _ = await _symbols_named(session, repo_id, symbol_id, exclude_spec)+ return ids[:5]def _read_file_text(repo_path: Path, file_path: str) -> str | None:@@ -980,6 +1009,14 @@ async def get_symbol(exclude_spec = _get_exclude_spec(ctx.path)rows = [r for r in rows if not is_excluded(r.file_path, exclude_spec)]+ if not rows and "::" not in symbol_id:+ # A bare name one symbol carries is that symbol; several stay suggestions.+ async with get_session(ctx.session_factory) as session:+ named, complete = await _symbols_named(+ session, repository.id, symbol_id, exclude_spec+ )+ if complete and len(named) == 1:+ rows = await _resolve_symbol(session, repository.id, named[0])if not rows:# Dead-end recovery: constants/imports/aliases between indexed# symbols miss the index but live in the file — grep the live file@@ -989,6 +1026,12 @@ async def get_symbol(if file_part and name_part and not is_excluded(file_part, exclude_spec):matches = _live_grep_fallback(Path(str(ctx.path)), file_part, name_part)if matches:+ likely = (+ "defined here, so likely added after the last index; "+ "run `repowise update` to index it"+ if any(m.get("defines") for m in matches)+ else "likely a constant, import, or alias"+ )return {"symbol_id": symbol_id,"file": file_part,@@ -997,9 +1040,8 @@ async def get_symbol("verified": True,"note": ("Not an indexed symbol, but the name matches these "- "live-file lines (likely a constant, import, or "- "alias). For surrounding source use a range read: "- f'"{file_part}:<start>-<end>".'+ f"live-file lines ({likely}). For surrounding source "+ f'use a range read: "{file_part}:<start>-<end>".'),"_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,diff --git a/tests/unit/server/mcp/test_symbol_id_resolution.py b/tests/unit/server/mcp/test_symbol_id_resolution.pynew file mode 100644index 000000000..da74933f8--- /dev/null+++ b/tests/unit/server/mcp/test_symbol_id_resolution.py@@ -0,0 +1,267 @@+"""One symbol id, one meaning, in get_context's graph blocks and in get_symbol.++* ``path::Class.method`` and ``path::Class::method`` reach the same graph edges+* a bare name that exactly one symbol carries resolves; a shared one suggests+* a live-grep hit on a definition line points at a stale index, not an alias+"""++from __future__ import annotations++import pytest++from repowise.core.persistence.models import GraphEdge, GraphNode, Repository, WikiSymbol+from repowise.server.mcp_server.tool_context.targets import _resolve_one_target++_FILE = "src/auth/service.py"+++async def repository(session, populated_db) -> Repository:+ return await session.get(Repository, populated_db)+++def _node(repository, node_id: str, name: str, **extra) -> GraphNode:+ return GraphNode(+ id=f"gn-{node_id}",+ repository_id=repository.id,+ node_id=node_id,+ node_type="symbol",+ name=name,+ file_path=node_id.split("::", 1)[0],+ language="python",+ **extra,+ )+++def _calls(repository, source: str, target: str) -> GraphEdge:+ return GraphEdge(+ id=f"ge-{source}",+ repository_id=repository.id,+ source_node_id=source,+ target_node_id=target,+ edge_type="calls",+ confidence=0.95,+ )+++async def _callers(session, repository, target: str) -> list[str]:+ card = await _resolve_one_target(+ session, repository, target, {"callers"}, True, exclude_spec=None+ )+ return [c["symbol_id"] for c in card["callers"]]+++async def test_dotted_and_double_colon_targets_reach_the_same_edges(session, repository) -> None:+ """The fixture indexes ``login`` as ``path::login`` with a dotted qualified name."""+ login = f"{_FILE}::login"+ caller = f"{_FILE}::handler"+ # A same-named symbol elsewhere, so a name-only match cannot pass by luck.+ other = "src/api/routes.py::login"+ other_caller = "src/api/routes.py::route"+ session.add_all(+ [+ _node(repository, login, "login"),+ _node(repository, caller, "handler"),+ _node(repository, other, "login"),+ _node(repository, other_caller, "route"),+ ]+ )+ session.add(_calls(repository, caller, login))+ session.add(_calls(repository, other_caller, other))+ await session.flush()++ dotted = await _callers(session, repository, f"{_FILE}::AuthService.login")+ colon = await _callers(session, repository, f"{_FILE}::AuthService::login")+ assert dotted == colon == [caller]+++async def test_graph_only_symbol_resolves_in_either_separator(session, repository) -> None:+ """Index-only mode: the graph node is the only record, keyed with ``::``."""+ ghost = f"{_FILE}::AuthService::ghost"+ caller = f"{_FILE}::AuthService::caller"+ session.add_all([_node(repository, ghost, "ghost"), _node(repository, caller, "caller")])+ session.add(_calls(repository, caller, ghost))+ await session.flush()++ assert await _callers(session, repository, f"{_FILE}::AuthService.ghost") == [caller]+ assert await _callers(session, repository, ghost) == [caller]+++ ("stored", "name", "parent", "target"),+ [+ ("src/v.py::Validate::notNull#1", "notNull", "Validate", "src/v.py::Validate.notNull"),+ ("src/o.py::Outer::Inner::run", "run", "Inner", "src/o.py::Outer.Inner.run"),+ ],+ ids=["overload", "nested-class"],+)+async def test_resolved_id_reaches_callers_metrics_and_community(+ session, repository, stored, name, parent, target+) -> None:+ path = stored.split("::", 1)[0]+ caller = f"{path}::caller"+ session.add(+ WikiSymbol(+ id=f"ws-{name}",+ repository_id=repository.id,+ file_path=path,+ symbol_id=stored,+ name=name,+ qualified_name=f"{parent}.{name}",+ kind="method",+ signature=f"def {name}()",+ start_line=1,+ end_line=2,+ language="python",+ parent_name=parent,+ )+ )+ session.add_all(+ [+ _node(repository, stored, name, community_id=3, pagerank=0.5),+ _node(repository, caller, "caller", community_id=3),+ ]+ )+ session.add(_calls(repository, caller, stored))+ await session.flush()++ card = await _resolve_one_target(+ session, repository, target, {"callers", "metrics", "community"}, True, exclude_spec=None+ )+ assert card["type"] == "symbol"+ assert [c["symbol_id"] for c in card["callers"]] == [caller]+ assert card["metrics"]["in_degree"] == 1+ assert card["community"]["id"] == 3+++# --- get_symbol on a bare name ----------------------------------------------+++def service_on_disk(setup_mcp, tmp_path):+ lines = [f"# line {n}" for n in range(1, 101)]+ lines[19] = " async def login(self, username: str, password: str) -> Token:"+ (tmp_path / "src" / "auth").mkdir(parents=True)+ (tmp_path / "src" / "auth" / "service.py").write_text("\n".join(lines) + "\n", "utf-8")+ return tmp_path+++async def test_bare_name_with_one_symbol_resolves(service_on_disk) -> None:+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("login")+ assert "error" not in result, result.get("error")+ assert result["symbol_id"] == f"{_FILE}::login"+ assert "async def login" in result["source"]+++async def test_bare_name_shared_by_two_symbols_still_suggests(+ service_on_disk, session, repo_id+) -> None:+ from repowise.server.mcp_server import get_symbol++ session.add(+ WikiSymbol(+ id="sym-login-2",+ repository_id=repo_id,+ file_path="src/api/routes.py",+ symbol_id="src/api/routes.py::login",+ name="login",+ qualified_name="login",+ kind="function",+ signature="def login()",+ start_line=1,+ end_line=2,+ language="python",+ )+ )+ await session.flush()++ result = await get_symbol("login")+ assert "error" in result+ assert sorted(result["suggestions"]) == ["src/api/routes.py::login", f"{_FILE}::login"]+++async def test_bare_name_is_case_sensitive(service_on_disk) -> None:+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("Login")+ assert "error" in result+++def _vendor_logins(repo_id: str, count: int) -> list[WikiSymbol]:+ return [+ WikiSymbol(+ id=f"vendor-login-{i}",+ repository_id=repo_id,+ file_path=f"vendor/m{i:02d}.py",+ symbol_id=f"vendor/m{i:02d}.py::login",+ name="login",+ qualified_name="login",+ kind="function",+ signature="def login()",+ start_line=1,+ end_line=2,+ language="python",+ )+ for i in range(count)+ ]++[email protected](("excluded", "resolves"), [(3, True), (20, False)])+async def test_bare_name_resolves_only_when_the_scan_saw_every_match(+ service_on_disk, session, repo_id, monkeypatch, excluded, resolves+) -> None:+ """One visible match among excluded ones resolves only if no row was cut."""+ from repowise.server.mcp_server import get_symbol, tool_symbol++ session.add_all(_vendor_logins(repo_id, excluded))+ await session.flush()+ monkeypatch.setattr(+ tool_symbol, "is_excluded", lambda path, _spec: str(path).startswith("vendor/")+ )++ result = await get_symbol("login")+ if resolves:+ assert result["symbol_id"] == f"{_FILE}::login"+ else:+ assert "error" in result+ assert result["suggestions"] == [f"{_FILE}::login"]+++# --- live-grep wording -------------------------------------------------------+++async def test_live_grep_on_a_definition_line_names_the_refresh(setup_mcp, tmp_path) -> None:+ from repowise.server.mcp_server import get_symbol++ (tmp_path / "pkg").mkdir()+ (tmp_path / "pkg" / "mod.py").write_text("LIMIT = 2\n\n\ndef fresh(x):\n return x\n")++ defined = await get_symbol("pkg/mod.py::fresh")+ assert defined["resolution"] == "live_grep"+ assert "added after the last index" in defined["note"]+ assert "`repowise update`" in defined["note"]+ assert "constant, import, or alias" not in defined["note"]++ constant = await get_symbol("pkg/mod.py::LIMIT")+ assert constant["resolution"] == "live_grep"+ assert "constant, import, or alias" in constant["note"]+ assert "repowise update" not in constant["note"]+++def test_definition_flag_needs_a_definition_at_line_start(tmp_path) -> None:+ from repowise.server.mcp_server import tool_symbol++ lines = [+ "# the module config lives here",+ "// fn config is described below",+ "x = config()",+ "export async function config() {}",+ " pub(crate) fn config() {}",+ "@cached def config(): pass",+ "func (s *Server) config() {}",+ ]+ (tmp_path / "m.txt").write_text("\n".join(lines) + "\n", "utf-8")+ matches = tool_symbol._live_grep_fallback(tmp_path, "m.txt", "config")+ assert [m["line"] for m in matches if m.get("defines")] == [4, 5, 6, 7]