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): stop used_by and search notes contradicting their own payload (#3699)
Swati Ahujae824d5f82c5d
diff --git a/packages/server/src/repowise/server/mcp_server/_basis.py b/packages/server/src/repowise/server/mcp_server/_basis.pyindex 857ced15f..65b2ee444 100644--- a/packages/server/src/repowise/server/mcp_server/_basis.py+++ b/packages/server/src/repowise/server/mcp_server/_basis.py@@ -113,6 +113,19 @@ async def call_resolution_basis(return _entry(language or "", grouping.get(language or "", {}))+def same_file_basis(users: int) -> dict[str, Any]:+ """Basis for an empty ``used_by`` whose only users share the symbol's file.++ The resolver-coverage figures answer "could a user have been missed"; here+ users were found, so the zero says only where they are. A use that is not+ a call (a subclass, a reference) is served under ``relations``.+ """+ uses = "1 use" if users == 1 else f"{users} uses"+ return {+ "note": f'{uses}, all in this file; include=["callers"] lists them in callers or relations.'+ }++async def call_resolution_bases(session: AsyncSession, repo_id: str, *, cache_key: str) -> list[dict[str, Any]]:diff --git a/packages/server/src/repowise/server/mcp_server/_line_hits.py b/packages/server/src/repowise/server/mcp_server/_line_hits.pyindex 2c2e9b780..ea8eca055 100644--- a/packages/server/src/repowise/server/mcp_server/_line_hits.py+++ b/packages/server/src/repowise/server/mcp_server/_line_hits.py@@ -461,6 +461,28 @@ async def _attach(response["complete"] = not reasonsif reasons:response["reasons"] = reasons+ if response["lines"]:+ _reconcile_symbol_miss(response, literal_scan=not sets)+++def _reconcile_symbol_miss(response: dict, *, literal_scan: bool) -> None:+ """Keep the symbol stage's miss advice from contradicting the lines found.++ ``grep_hint`` and the no-exact-symbol ``note`` were written before any+ line was read, and tell the reader to recheck spelling or grep. With+ lines in hand both are wrong; ``exact_match: false`` still says no symbol+ has the name, so the note stays only to label fuzzy results.+ """+ response.pop("grep_hint", None)+ if not literal_scan or response.get("exact_match") is not False:+ return+ if response.get("results"):+ response["note"] = (+ "No indexed symbol has this exact name: the results are other "+ "symbols, and `lines` are where the text occurs."+ )+ else:+ response.pop("note", None)def _lines_after_budget(result: dict[str, Any]) -> None: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 8df658c23..eb86e4ed8 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@@ -43,7 +43,7 @@ from repowise.core.persistence.models import (Repository,WikiSymbol,)-from repowise.server.mcp_server._basis import call_resolution_basis+from repowise.server.mcp_server._basis import call_resolution_basis, same_file_basisfrom repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._edit_sites import reference_edit_setfrom repowise.server.mcp_server._helpers import (@@ -65,6 +65,7 @@ from repowise.server.mcp_server._symbol_lookup import ()from repowise.server.mcp_server.tool_context.enrichment import (_DOC_DRIFT_PATH,+ _MIN_CALL_CONFIDENCE,_resolve_call_graph,_resolve_community,_resolve_health,@@ -994,7 +995,7 @@ async def _resolve_one_target(# survive matters: rank by source-file PageRank, path breaking ties.sym_node_id = getattr(sym, "symbol_id", None) or getattr(sym, "node_id", None)res = await session.execute(- select(GraphEdge.source_node_id, GraphNode.file_path)+ select(GraphEdge.source_node_id, GraphNode.file_path, GraphEdge.confidence).outerjoin(GraphNode,(GraphNode.repository_id == GraphEdge.repository_id)@@ -1008,13 +1009,24 @@ async def _resolve_one_target()# An id the graph no longer holds still names its file, so fall# back to the path half rather than dropping a real user.- user_files = {- file_path or source_node_id.split("::", 1)[0]- for source_node_id, file_path in res.all()- }+ user_files: set[str] = set()# A same-file caller is a real use, but naming the file already# being read spends a capped row; ``callers`` has it at symbol grain.+ # Counted first, by the confidence floor include=["callers"] serves+ # (a recursive call is not a user), so an empty list can say so.+ same_file_users: set[str] = set()+ for source_node_id, file_path, confidence in res.all():+ path = file_path or source_node_id.split("::", 1)[0]+ user_files.add(path)+ if (+ path == sym.file_path+ and source_node_id != sym_node_id+ and (confidence or 0) >= _MIN_CALL_CONFIDENCE+ ):+ same_file_users.add(source_node_id)user_files.discard(sym.file_path)+ # Before exclusion: an excluded user elsewhere is still a user.+ other_file_users = bool(user_files)# Looked up by the folded path, not joined above: a source whose# symbol node is missing has no file to join through and would rank# 0.0. Chunked because this binds one parameter per using file.@@ -1042,7 +1054,10 @@ async def _resolve_one_target()# No users found says nothing on its own until the reader knows how# much of this language's call graph the resolver actually bound.- if not docs.get("used_by"):+ # Same-file users make the zero a fact about other files instead.+ if not docs.get("used_by") and same_file_users and not other_file_users:+ docs["used_by_basis"] = same_file_basis(len(same_file_users))+ elif not docs.get("used_by"):docs["used_by_basis"] = await call_resolution_basis(session,repo_id,diff --git a/tests/unit/server/mcp/test_search_line_hits.py b/tests/unit/server/mcp/test_search_line_hits.pyindex a34810b4c..f9f3d7320 100644--- a/tests/unit/server/mcp/test_search_line_hits.py+++ b/tests/unit/server/mcp/test_search_line_hits.py@@ -145,6 +145,39 @@ async def test_quoted_string_is_scanned_as_a_substring(tree):assert out["complete"] is True+async def test_a_name_with_no_symbol_but_live_lines_is_not_reported_missing(tree):+ """The symbol stage's miss advice is written before any line is read.++ Next to the lines it found, "recheck the spelling" and "grep the name" say+ the opposite of what the reply holds; ``exact_match`` still says no symbol.+ """+ out = await search_codebase("connect", mode="symbol")++ assert _rows(out) == [("app/widget.py", 4, "match")]+ assert out["complete"] is True+ assert out["exact_match"] is False+ assert "grep_hint" not in out+ assert "note" not in out+++def test_fuzzy_results_beside_literal_lines_keep_a_short_label():+ out = {"results": [{"name": "connect_pool"}], "exact_match": False, "note": "x", "grep_hint": "y"}++ _line_hits._reconcile_symbol_miss(out, literal_scan=True)++ assert "grep_hint" not in out+ assert "other symbols" in out["note"]+++async def test_a_name_with_no_symbol_and_no_lines_keeps_its_miss_advice(tree):+ out = await search_codebase("disconnect", mode="symbol")++ assert "lines" not in out or out["lines"] == []+ assert "grep_hint" in out++@pytest.mark.asyncioasync def test_cap_hit_marks_lines_incomplete(tree, monkeypatch):monkeypatch.setattr(_line_hits, "MAX_LINES_PER_FILE", 0)diff --git a/tests/unit/server/mcp/test_used_by_ranking.py b/tests/unit/server/mcp/test_used_by_ranking.pyindex c5350681b..4a15e818b 100644--- a/tests/unit/server/mcp/test_used_by_ranking.py+++ b/tests/unit/server/mcp/test_used_by_ranking.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport pytestfrom repowise.core.persistence.models import GraphEdge, GraphNode, Repository+from repowise.server.mcp_server._basis import same_file_basisfrom repowise.server.mcp_server.tool_context.targets import _MAX_USED_BY, _resolve_one_target_FILE = "src/auth/service.py"@@ -229,9 +230,106 @@ async def test_the_symbols_own_file_is_not_listed_as_its_user()await session.commit()- used_by = (await _card(session, repository, "AuthService"))["docs"]["used_by"]+ docs = (await _card(session, repository, "AuthService"))["docs"]++ assert _FILE not in docs["used_by"]+ # The empty list must not then claim no resolved edge reaches the symbol.+ assert docs["used_by"] == []+ assert docs["used_by_basis"] == same_file_basis(1)+++async def test_a_recursive_call_is_not_a_same_file_user(+ session, repository, populated_db+) -> None:+ session.add(+ GraphEdge(+ id="ge-recursive",+ repository_id=populated_db,+ source_node_id=_SYMBOL,+ target_node_id=_SYMBOL,+ edge_type="calls",+ imported_names_json="[]",+ )+ )+ await session.commit()++ docs = (await _card(session, repository, "AuthService"))["docs"]- assert _FILE not in used_by+ # The resolver-coverage basis, not the same-file one.+ assert "language" in docs["used_by_basis"]+++async def test_a_same_file_use_that_is_not_a_call_is_where_the_note_points(+ session, repository, populated_db+) -> None:+ """The note points at include=["callers"], so every counted use must be served there."""+ session.add(+ GraphNode(+ id="gn-auth-service",+ repository_id=populated_db,+ node_id=_SYMBOL,+ node_type="symbol",+ name="AuthService",+ kind="class",+ file_path=_FILE,+ language="python",+ )+ )+ for edge_id, source, edge_type, confidence in (+ ("ge-sub", f"{_FILE}::AdminService", "extends", 0.9),+ # Below the floor the callers block serves, so not counted.+ ("ge-weak", f"{_FILE}::guess", "calls", 0.3),+ ):+ session.add(+ GraphEdge(+ id=edge_id,+ repository_id=populated_db,+ source_node_id=source,+ target_node_id=_SYMBOL,+ edge_type=edge_type,+ confidence=confidence,+ imported_names_json="[]",+ )+ )+ await session.commit()++ card = await _resolve_one_target(+ session, repository, "AuthService", {"docs", "callers"}, exclude_spec=None, repo_root=None+ )++ assert card["docs"]["used_by_basis"] == same_file_basis(1)+ served = {row["symbol_id"] for r in card["relations"] for row in r["rows"]}+ assert served == {f"{_FILE}::AdminService"}+++async def test_an_excluded_user_elsewhere_keeps_the_coverage_basis(+ session, repository, populated_db+) -> None:+ """Exclusion empties used_by, but "all in this file" would then be false."""+ import pathspec++ for edge_id, source in (("ge-own", f"{_FILE}::login"), ("ge-gen", "gen/client.py::boot")):+ session.add(+ GraphEdge(+ id=edge_id,+ repository_id=populated_db,+ source_node_id=source,+ target_node_id=_SYMBOL,+ edge_type="calls",+ imported_names_json="[]",+ )+ )+ await session.commit()++ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["gen/**"])+ docs = (+ await _resolve_one_target(+ session, repository, "AuthService", None, True, exclude_spec=spec, repo_root=None+ )+ )["docs"]++ assert docs["used_by"] == []+ assert "language" in docs["used_by_basis"]async def test_ranking_survives_a_chunked_rank_lookup(