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.

feat(context): list callers that reach an implementation through its interface (#4506)

Raghav Chamadiya7cb72e3237de
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py b/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py
index 6bf5e6130..dcbb2389f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/call_graph.py
@@ -25,6 +25,8 @@ from repowise.server.mcp_server._index_state import index_state_key
from repowise.server.mcp_server._wrapper_callers import forwarding_wrapper_callers
from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF
+from .interface_callers import VIA_INTERFACE, interface_call_edges
+
# Symbol-level call floor. The file-level rollup uses the shared
# ``_graph_files`` floor instead; the totals query and the symbol rows must
# share this one.
@@ -44,6 +46,11 @@ _CALL_EDGE_TYPES = ["calls"]
#: tests can force an omission.
_SYMBOL_NEIGHBOR_LIMIT = 50
+#: Interface-dispatch caller rows served per symbol, beside up to 50 direct
+#: ones; the rest are counted and banked. Kept small because each is a possible
+#: dispatch target, not a proven call, and Java rows are long.
+_INTERFACE_ROW_CAP = 10
+
#: Rows carried per relation kind, far below the call cap: the kind and the
#: honest total answer "what else reaches this, and how".
_RELATION_ROW_CAP = 5
@@ -104,6 +111,9 @@ class _CallGraphRun:
collector: OmissionCollector | None
repo_root: Any
node_map: dict[str, Any] = field(default_factory=dict)
+ #: Callers of the base methods this symbol implements, served after the
+ #: direct callers under the same cap.
+ interface_rows: list[dict[str, Any]] = field(default_factory=list)
def wants(self, direction: str) -> bool:
return self.want_callers if direction == "in" else self.want_callees
@@ -181,11 +191,19 @@ async def _resolve_call_graph(
),
)
+ # ``dispatches_to`` lands only on ``has_method`` members, which are all
+ # ``kind == "method"``; anything else skips the read.
+ if want_callers and node.kind == "method":
+ run.interface_rows = await _interface_rows(run)
+
relations: list[dict[str, Any]] = []
for edge_type, edges in edges_by_type.items():
inbound, outbound = _split_edges(run, edge_type, edges)
for direction, rows in (("in", inbound), ("out", outbound)):
await _place_rows(run, edge_type, direction, rows, relations)
+ # No direct call edge at all, so the calls block above never ran.
+ if run.interface_rows and "callers" not in result_data:
+ await _serve_call_rows(run, "in", [])
# An omitted key reads as "not asked for" rather than "none".
if want_callers:
@@ -352,33 +370,71 @@ async def _place_rows(
relations.append(relation)
+async def _interface_rows(run: _CallGraphRun) -> list[dict[str, Any]]:
+ """Caller rows reaching this symbol through a base method it implements."""
+ pairs = await interface_call_edges(run.session, run.repository.id, [run.node.node_id])
+ if not pairs:
+ return []
+ nodes = await get_graph_nodes_by_ids(
+ run.session, run.repository.id, sorted({e.source_node_id for e, _ in pairs})
+ )
+ rows: list[dict[str, Any]] = []
+ for edge, base_id in sorted(pairs, key=lambda p: (-(p[0].confidence or 0), p[0].source_node_id)):
+ row = _neighbor_entry(edge, edge.source_node_id, nodes, with_edge_type=True)
+ row["via"] = VIA_INTERFACE
+ row["via_base"] = base_id
+ if call_line := first_call_line(edge.call_lines_json):
+ row["call_line"] = call_line
+ rows.append(row)
+ return _unique_by_symbol(filter_dicts_by_key(rows, "file", run.exclude_spec))
+
+
async def _serve_call_rows(run: _CallGraphRun, direction: str, rows: list[dict[str, Any]]) -> None:
- """Cap ``callers``/``callees``; callers also get wrapper hops and call text."""
+ """Cap ``callers``/``callees``; callers also get interface, wrapper hops and call text.
+
+ Interface rows rank after every direct caller and have a cap of their own,
+ so they cannot crowd out a direct caller or push the block over budget.
+ """
key = "callers" if direction == "in" else "callees"
result_data = run.result_data
- total = len(rows)
# Nearly every symbol fits under the cap; a hub gets explicit truncation counts.
limit = _SYMBOL_NEIGHBOR_LIMIT
+ emitted = rows[:limit]
+ if direction == "in" and run.interface_rows:
+ direct = {str(r.get("symbol_id")) for r in rows}
+ extra = [r for r in run.interface_rows if r["symbol_id"] not in direct]
+ if extra:
+ result_data["callers_via_interface"] = len(extra)
+ emitted = (rows + extra[:_INTERFACE_ROW_CAP])[:limit]
+ rows = rows + extra
+ total = len(rows)
visible = cap_collection(
result_data,
key,
rows,
limit,
run.collector,
+ emitted=emitted,
label=f"{run.target} :: {key} beyond cap={limit}",
)
if direction != "in":
return
if total > len(visible):
+ order = (
+ f"{len(visible)} of {total} callers: direct callers by confidence, then up "
+ f"to {_INTERFACE_ROW_CAP} reaching it through an interface (via: interface)"
+ if "callers_via_interface" in result_data
+ else f"top {len(visible)} of {total} callers by confidence"
+ )
result_data["_callers_note"] = (
- f"Showing top {len(visible)} of {total} callers by confidence. "
+ f"Showing {order}. "
"Recover the omitted rows with get_symbol on the response's "
"repowise omission reference; grep remains useful when graph "
"coverage itself may be incomplete."
)
else:
- # Appended after the direct rows and only under the cap, so the
- # callers_* counts keep meaning direct callers.
+ # Appended only under the cap, so the callers_* counts never include
+ # wrapper hops.
hop = await forwarding_wrapper_callers(
run.session,
run.repository.id,
@@ -391,8 +447,10 @@ async def _serve_call_rows(run: _CallGraphRun, direction: str, rows: list[dict[s
result_data[key] = visible + hop
await attach_call_text(run.repo_root, result_data[key], run.node.node_id)
# Unserved rows are never checked against the live file.
- for row in rows[len(visible) :]:
- row.pop("call_line", None)
+ served = {id(row) for row in visible}
+ for row in rows:
+ if id(row) not in served:
+ row.pop("call_line", None)
def _relation_block(
@@ -445,7 +503,12 @@ def _attach_relations(
relations.sort(key=lambda r: (r["direction"], -r["total"], r["edge_type"]))
run.result_data["relations"] = relations
inbound_kinds = [r for r in relations if r["direction"] == "in"]
- if run.want_callers and not row_counts_in.get("calls") and inbound_kinds:
+ if (
+ run.want_callers
+ and not row_counts_in.get("calls")
+ and not run.interface_rows
+ and inbound_kinds
+ ):
reached = ", ".join(f"{r['total']} {r['edge_type']}" for r in inbound_kinds)
run.result_data["_call_graph_note"] = (
f"Nothing calls '{run.node.name}'; it is reached by {reached}. See `relations`."
@@ -464,23 +527,37 @@ async def _resolve_file_level_callers(
) -> None:
"""File-target callers: importing files + inbound symbol-call rollup.
- Two granularities merged per caller file: ``imports: true`` when the
+ Three granularities merged per caller file: ``imports: true`` when the
file imports this one, ``inbound_calls`` counting cross-file call edges
- into any symbol defined here.
+ into any symbol defined here, and ``interface_calls`` counting calls into
+ a base method that a symbol here implements. A file reached only that
+ way is marked ``via: "interface"``.
"""
importer_files = await _file_importers(session, repo_id, node)
- calls_by_file = await _file_inbound_calls(session, repo_id, node)
+ calls_by_file, interface_by_file = await _file_inbound_calls(session, repo_id, node)
entries: list[dict[str, Any]] = []
- for f in sorted(importer_files | set(calls_by_file)):
+ for f in sorted(importer_files | set(calls_by_file) | set(interface_by_file)):
entry: dict[str, Any] = {"file": f}
if f in importer_files:
entry["imports"] = True
if calls_by_file.get(f):
entry["inbound_calls"] = calls_by_file[f]
+ if interface_by_file.get(f):
+ entry["interface_calls"] = interface_by_file[f]
+ if f not in importer_files and not calls_by_file.get(f):
+ entry["via"] = VIA_INTERFACE
entries.append(entry)
entries = filter_dicts_by_key(entries, "file", exclude_spec)
- entries.sort(key=lambda x: -(x.get("inbound_calls") or 0))
+ # Every direct entry, importers included, before any interface-only one:
+ # interface dispatch is a possible target, not a proven one.
+ entries.sort(
+ key=lambda x: (
+ x.get("via") == VIA_INTERFACE,
+ -(x.get("inbound_calls") or 0),
+ -(x.get("interface_calls") or 0),
+ )
+ )
cap_collection(
result_data,
@@ -490,10 +567,22 @@ async def _resolve_file_level_callers(
collector,
label=f"{node.node_id} :: file callers beyond cap=20",
)
- result_data["_call_graph_note"] = (
+ note = (
"File-level rollup: importing files plus inbound cross-file call "
"counts. For symbol-precise callers pass 'file.py::Symbol'."
)
+ # Files reached only that way, as ``callers_via_interface`` counts symbols.
+ via_interface = sum(1 for e in entries if e.get("via") == VIA_INTERFACE)
+ if via_interface:
+ result_data["callers_via_interface"] = via_interface
+ # The gap a reader sees next to get_risk: dependents are file-level
+ # edges, these are calls, and neither is a subset of the other.
+ note += (
+ f" {via_interface} files reach it only through a base method it "
+ "implements (via: interface). get_risk's dependents_count counts "
+ "file-level edges (import, type use, injection), not calls."
+ )
+ result_data["_call_graph_note"] = note
if repository is not None and not result_data.get("callers"):
result_data["callers_basis"] = await call_resolution_basis(
session, repo_id, node.language, cache_key=index_state_key(repository)
@@ -522,8 +611,8 @@ async def _file_importers(session: AsyncSession, repo_id: str, node: GraphNode)
async def _file_inbound_calls(
session: AsyncSession, repo_id: str, node: GraphNode
-) -> dict[str, int]:
- """Cross-file calls into any symbol defined in this file, counted per calling file."""
+) -> tuple[dict[str, int], dict[str, int]]:
+ """Cross-file calls per calling file: direct, and through a base method implemented here."""
target_file = node.file_path or node.node_id
sym_res = await session.execute(
select(GraphNode.node_id).where(
@@ -535,7 +624,7 @@ async def _file_inbound_calls(
sym_ids = [row[0] for row in sym_res.all()]
calls_by_file: dict[str, int] = {}
if not sym_ids:
- return calls_by_file
+ return calls_by_file, {}
edge_res = await session.execute(
select(GraphEdge.source_node_id, GraphEdge.confidence).where(
GraphEdge.repository_id == repo_id,
@@ -550,4 +639,9 @@ async def _file_inbound_calls(
if not keep_projected_edge(src_file, target_file, "calls", confidence):
continue
calls_by_file[src_file] = calls_by_file.get(src_file, 0) + 1
- return calls_by_file
+ interface_by_file: dict[str, int] = {}
+ for edge, _base in await interface_call_edges(session, repo_id, sym_ids):
+ src_file = node_to_file(edge.source_node_id)
+ if keep_projected_edge(src_file, target_file, "calls", edge.confidence):
+ interface_by_file[src_file] = interface_by_file.get(src_file, 0) + 1
+ return calls_by_file, interface_by_file
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/interface_callers.py b/packages/server/src/repowise/server/mcp_server/tool_context/interface_callers.py
new file mode 100644
index 000000000..783ccdb72
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/interface_callers.py
@@ -0,0 +1,62 @@
+"""Callers that reach an implementation through the base method it answers for.
+
+A call written against an interface (or a base class) resolves to the base's
+method, so an implementation injected by a container reads as called only by
+its own unit test. Ingestion already joins each base method to the
+implementations that can answer for it with a ``dispatches_to`` edge; this
+reads that edge one hop back and returns the calls into the base. One hop
+only, never a walk up the hierarchy: ``dispatches_to`` already spans it.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.batches import chunked
+from repowise.core.persistence.models import GraphEdge
+
+#: Same floor as the direct call rows; ``dispatches_to`` is emitted at 0.75.
+MIN_CONFIDENCE = 0.7
+
+#: The ``via`` marker on every row this module produces.
+VIA_INTERFACE = "interface"
+
+
+async def interface_call_edges(
+ session: AsyncSession, repo_id: str, impl_ids: list[str]
+) -> list[tuple[GraphEdge, str]]:
+ """``(call edge, base method id)`` for calls into a base dispatching to *impl_ids*.
+
+ Calls made from inside *impl_ids* are left out: an implementation going
+ through its own interface is not an outside caller.
+ """
+ impls = set(impl_ids)
+ bases: set[str] = set()
+ for batch in chunked(sorted(impls)):
+ res = await session.execute(
+ select(GraphEdge.source_node_id).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(batch),
+ GraphEdge.edge_type == "dispatches_to",
+ GraphEdge.confidence >= MIN_CONFIDENCE,
+ )
+ )
+ bases.update(row[0] for row in res.all())
+ bases -= impls
+ out: list[tuple[GraphEdge, str]] = []
+ for batch in chunked(sorted(bases)):
+ res = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(batch),
+ GraphEdge.edge_type == "calls",
+ GraphEdge.confidence >= MIN_CONFIDENCE,
+ )
+ )
+ out.extend(
+ (edge, edge.target_node_id)
+ for edge in res.scalars().all()
+ if edge.source_node_id not in impls
+ )
+ return out
diff --git a/tests/unit/server/mcp/test_context_interface_callers.py b/tests/unit/server/mcp/test_context_interface_callers.py
new file mode 100644
index 000000000..7c23a60b1
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_interface_callers.py
@@ -0,0 +1,178 @@
+"""Callers of an implementation include the calls written against its interface.
+
+A Spring service is injected and called as its interface, so the call lands on
+the interface method and the implementation read as called only by its unit
+test (Fineract's ``PortfolioCommandSourceWritePlatformServiceImpl``: one test
+caller against 121 dependents). ``dispatches_to`` joins the two; get_context
+reads it one hop back and marks those rows ``via: "interface"``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+IFACE = "svc/Writer.java"
+IMPL = "svc/WriterImpl.java"
+BASE_RUN = f"{IFACE}::Writer::run"
+IMPL_RUN = f"{IMPL}::WriterImpl::run"
+TEST = "test/WriterImplTest.java::WriterImplTest::testRun"
+N_CALLERS = 25
+
+
+async def _seed(session) -> None:
+ repo = (await session.execute(select(Repository))).scalars().first()
+
+ def node(node_id: str, node_type: str = "symbol") -> None:
+ session.add(
+ GraphNode(
+ id=f"ifc_{node_id}",
+ repository_id=repo.id,
+ node_id=node_id,
+ node_type=node_type,
+ name=node_id.split("::")[-1],
+ file_path=node_id.split("::")[0],
+ kind="method" if node_type == "symbol" else None,
+ start_line=1,
+ end_line=5,
+ created_at=_NOW,
+ )
+ )
+
+ def edge(source: str, target: str, edge_type: str, confidence: float) -> None:
+ session.add(
+ GraphEdge(
+ id=f"ifc_{source}_{target}_{edge_type}",
+ repository_id=repo.id,
+ source_node_id=source,
+ target_node_id=target,
+ edge_type=edge_type,
+ confidence=confidence,
+ created_at=_NOW,
+ )
+ )
+
+ for file_id in (IFACE, IMPL):
+ node(file_id, "file")
+ for sym in (BASE_RUN, IMPL_RUN, TEST):
+ node(sym)
+ edge(BASE_RUN, IMPL_RUN, "dispatches_to", 0.75)
+ edge(TEST, IMPL_RUN, "calls", 0.9)
+ for i in range(N_CALLERS):
+ caller = f"app/Use{i:02d}.java::Use{i:02d}::go"
+ node(caller)
+ edge(caller, BASE_RUN, "calls", 0.8)
+ await session.flush()
+
+
+async def _ctx(target: str) -> dict:
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context([target], include=["callers"], compact=False)
+ return result["targets"][target]
+
+
+async def test_file_target_rolls_up_callers_through_the_interface(setup_mcp, session):
+ await _seed(session)
+
+ t = await _ctx(IMPL)
+
+ callers = t["callers"]
+ # The direct caller ranks first; the interface rows follow under the same cap.
+ assert callers[0]["file"] == "test/WriterImplTest.java"
+ assert callers[0]["inbound_calls"] == 1 and "via" not in callers[0]
+ via = [c for c in callers if c.get("via") == "interface"]
+ assert via and all(c["interface_calls"] == 1 for c in via)
+ assert t["callers_via_interface"] == N_CALLERS
+ assert t["callers_total"] == N_CALLERS + 1
+ assert len(callers) == 20 and t["callers_truncated"]
+ assert "dependents_count" in t["_call_graph_note"]
+
+
+async def test_symbol_target_lists_interface_callers_after_direct_ones(setup_mcp, session):
+ await _seed(session)
+
+ t = await _ctx(IMPL_RUN)
+
+ callers = t["callers"]
+ assert callers[0]["symbol_id"] == TEST and callers[0].get("via") != "interface"
+ via = callers[1:]
+ # Interface rows have their own small cap; the rest are counted, not served.
+ assert len(via) == 10
+ assert all(c["via"] == "interface" and c["via_base"] == BASE_RUN for c in via)
+ assert t["callers_via_interface"] == N_CALLERS
+ assert t["callers_total"] == N_CALLERS + 1 and t["callers_truncated"]
+ assert "via: interface" in t["_callers_note"]
+
+
+async def test_interface_callers_alone_still_fill_callers(setup_mcp, session):
+ """No direct call edge at all: the implementation is still called."""
+ await _seed(session)
+ await session.execute(
+ GraphEdge.__table__.delete().where(GraphEdge.source_node_id == TEST)
+ )
+ await session.flush()
+
+ t = await _ctx(IMPL_RUN)
+
+ assert len(t["callers"]) == 10 and t["callers_total"] == N_CALLERS
+ assert "Nothing calls" not in t.get("_call_graph_note", "")
+
+
+async def test_the_base_method_keeps_only_its_own_callers(setup_mcp, session):
+ """The rollup runs from implementation to base, never the other way."""
+ await _seed(session)
+
+ t = await _ctx(BASE_RUN)
+
+ assert all(c.get("via") != "interface" for c in t["callers"])
+ assert "callers_via_interface" not in t
+
+
+async def test_importers_are_never_crowded_out_by_interface_only_files(setup_mcp, session):
+ """25 interface-only files must not push an import-only file past the 20 cap."""
+ await _seed(session)
+ repo = (await session.execute(select(Repository))).scalars().first()
+ importers = [f"app/Wire{i}.java" for i in range(3)]
+ for path in importers:
+ session.add(
+ GraphNode(
+ id=f"ifc_{path}",
+ repository_id=repo.id,
+ node_id=path,
+ node_type="file",
+ name=path.rsplit("/", 1)[-1],
+ file_path=path,
+ created_at=_NOW,
+ )
+ )
+ session.add(
+ GraphEdge(
+ id=f"ifc_{path}_imports",
+ repository_id=repo.id,
+ source_node_id=path,
+ target_node_id=IMPL,
+ edge_type="imports",
+ created_at=_NOW,
+ )
+ )
+ await session.flush()
+
+ t = await _ctx(IMPL)
+
+ shown = [c["file"] for c in t["callers"]]
+ assert len(shown) == 20
+ assert set(importers) <= set(shown)
+ first_via = next(i for i, c in enumerate(t["callers"]) if c.get("via") == "interface")
+ assert all(c.get("via") == "interface" for c in t["callers"][first_via:])