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 through forwarding wrappers (#3195)

Raghav Chamadiya6ae995bc647c
diff --git a/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py
new file mode 100644
index 000000000..ee214a4a5
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py
@@ -0,0 +1,223 @@
+"""Callers one hop past a forwarding wrapper.
+
+A thin wrapper (a runtime seam, a re-export, a lazy-load shim) sits between a
+symbol and the code that really uses it, so the symbol's direct callers name
+the wrapper and stop. This module recognises such wrappers from the graph
+alone and returns *their* callers, each marked with the wrapper it came
+through. It is one bounded hop over wrappers only, never a general walk.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.crud import get_graph_nodes_by_ids
+from repowise.core.persistence.models import GraphEdge, GraphNode
+
+#: Same floor as the direct caller rows, so a hop row is no weaker than they are.
+MIN_CALL_CONFIDENCE = 0.7
+
+#: Line span of a function whose only resolved call is the target. A pass-through
+#: is 3 lines, 5 with a wrapped signature; on a 97k-function TypeScript index
+#: single-callee functions spread to 40+ lines, and the longer ones do work the
+#: graph does not see.
+_MAX_FORWARDER_SPAN = 6
+
+#: A same-named function in another file is a re-export-style wrapper even when
+#: it adds a guard or a log line the graph does not see. It must still call
+#: nothing but the target. Measured median 5 lines, p75 9, p90 18.
+_MAX_SAME_NAME_SPAN = 15
+
+#: Extra rows per target. Wrapper callers are a hint about where to look next,
+#: and the wrapper itself is already listed for the agent to expand.
+MAX_WRAPPER_CALLER_ROWS = 10
+
+_WRAPPER_KINDS = ("function", "method")
+
+
+def _span(node: GraphNode) -> int | None:
+ if node.start_line is None or node.end_line is None:
+ return None
+ return node.end_line - node.start_line + 1
+
+
+def _is_wrapper(node: GraphNode, target: GraphNode, callees: set[str]) -> bool:
+ if node.node_type != "symbol" or node.kind not in _WRAPPER_KINDS:
+ return False
+ span = _span(node)
+ # A caller that resolves any other call does work of its own.
+ if span is None or callees != {target.node_id}:
+ return False
+ if span <= _MAX_FORWARDER_SPAN:
+ return True
+ return (
+ node.name == target.name
+ and node.file_path != target.file_path
+ and span <= _MAX_SAME_NAME_SPAN
+ )
+
+
+def _imported_names(edge: GraphEdge) -> list[str]:
+ try:
+ names = json.loads(edge.imported_names_json or "[]")
+ except (TypeError, ValueError):
+ return []
+ return [str(n) for n in names] if isinstance(names, list) else []
+
+
+async def forwarding_wrapper_callers(
+ session: AsyncSession,
+ repo_id: str,
+ target: GraphNode,
+ caller_ids: list[str],
+ *,
+ limit: int = MAX_WRAPPER_CALLER_ROWS,
+ known_nodes: dict[str, GraphNode] | None = None,
+) -> list[dict[str, Any]]:
+ """Rows for the callers of every forwarding wrapper among ``caller_ids``.
+
+ ``caller_ids`` are the target's direct callers, best first; wrappers are
+ expanded in that order. A row has the direct-caller shape plus
+ ``via_wrapper`` (the wrapper's symbol id). A wrapper no call edge reaches
+ falls back to the files importing it by name or wholesale, shaped like a
+ file-level caller row (``imports: true``): a dynamic import consumed in a
+ callback is the usual reason the call itself went unresolved.
+ ``known_nodes`` saves the caller-node read when the caller already holds them.
+ """
+ if not caller_ids or limit <= 0:
+ return []
+ candidates = known_nodes
+ if candidates is None:
+ candidates = await get_graph_nodes_by_ids(session, repo_id, caller_ids)
+ small = [
+ cid
+ for cid in caller_ids
+ if (n := candidates.get(cid)) is not None
+ and n.kind in _WRAPPER_KINDS
+ and (_span(n) or _MAX_SAME_NAME_SPAN + 1) <= _MAX_SAME_NAME_SPAN
+ ]
+ if not small:
+ return []
+
+ callees: dict[str, set[str]] = {cid: set() for cid in small}
+ res = await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.source_node_id.in_(small),
+ GraphEdge.edge_type == "calls",
+ )
+ )
+ for src, dst in res.all():
+ callees[src].add(dst)
+ wrappers = [cid for cid in small if _is_wrapper(candidates[cid], target, callees[cid])]
+ if not wrappers:
+ return []
+
+ res = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(wrappers),
+ GraphEdge.edge_type == "calls",
+ GraphEdge.confidence >= MIN_CALL_CONFIDENCE,
+ )
+ )
+ inbound: dict[str, list[GraphEdge]] = {w: [] for w in wrappers}
+ for edge in res.scalars().all():
+ inbound[edge.target_node_id].append(edge)
+
+ # The target, its direct callers and the wrappers are already accounted
+ # for; skipping them is also what keeps a wrapper cycle from re-entering.
+ seen = {target.node_id, *caller_ids}
+ picked: list[tuple[GraphEdge, str]] = []
+ unreached: list[str] = []
+ for wrapper_id in wrappers:
+ edges = sorted(inbound[wrapper_id], key=lambda e: (-(e.confidence or 0), e.source_node_id))
+ if not edges:
+ unreached.append(wrapper_id)
+ for edge in edges:
+ if edge.source_node_id in seen:
+ continue
+ seen.add(edge.source_node_id)
+ picked.append((edge, wrapper_id))
+
+ nodes = await get_graph_nodes_by_ids(session, repo_id, [e.source_node_id for e, _ in picked])
+ rows: list[dict[str, Any]] = []
+ for edge, wrapper_id in picked[:limit]:
+ other = nodes.get(edge.source_node_id)
+ row: dict[str, Any] = {
+ "symbol_id": edge.source_node_id,
+ "name": other.name if other else edge.source_node_id.split("::")[-1],
+ "kind": other.kind if other else None,
+ "file": other.file_path if other else edge.source_node_id.split("::")[0],
+ "line": other.start_line if other else None,
+ "confidence": edge.confidence,
+ "edge_type": edge.edge_type,
+ }
+ if edge.resolution_origin:
+ row["via"] = edge.resolution_origin
+ row["via_wrapper"] = wrapper_id
+ rows.append(row)
+
+ if unreached and len(rows) < limit:
+ seen_files = {sid.split("::")[0] for sid in seen}
+ imported = await files_importing(
+ session, repo_id, [candidates[w] for w in unreached], seen_files
+ )
+ for importer, confidence, wrapper_id, named in imported[: limit - len(rows)]:
+ row = {"file": importer, "imports": True, "confidence": confidence}
+ # A wholesale (``*``) import names no symbol: the file is a lead, not a proven caller.
+ if not named:
+ row["wholesale"] = True
+ row["via_wrapper"] = wrapper_id
+ rows.append(row)
+ return rows
+
+
+async def files_importing(
+ session: AsyncSession,
+ repo_id: str,
+ symbols: list[GraphNode],
+ skip_files: set[str],
+) -> list[tuple[str, float | None, str, bool]]:
+ """``(importer, confidence, symbol_id, named)`` for files importing a symbol.
+
+ ``named`` is False when the import is wholesale (``*``), which says only
+ that the file loads the module, not that it uses this symbol.
+
+ One row per importing file, outside ``skip_files``, in a stable order. The
+ file-level edge is all the graph has when the symbol is passed by
+ reference or loaded dynamically rather than called.
+ """
+ by_file: dict[str, list[GraphNode]] = {}
+ for node in symbols:
+ by_file.setdefault(node.file_path, []).append(node)
+ if not by_file:
+ return []
+ res = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(list(by_file)),
+ GraphEdge.edge_type == "imports",
+ )
+ )
+ seen = set(skip_files)
+ out: list[tuple[str, float | None, str, bool]] = []
+ for edge in sorted(res.scalars().all(), key=lambda e: (e.target_node_id, e.source_node_id)):
+ importer = edge.source_node_id
+ if importer in seen:
+ continue
+ names = _imported_names(edge)
+ candidates = by_file[edge.target_node_id]
+ node = next((n for n in candidates if n.name in names), None)
+ named = node is not None
+ if node is None and "*" in names:
+ node = candidates[0]
+ if node is None:
+ continue
+ seen.add(importer)
+ out.append((importer, edge.confidence, node.node_id, named))
+ return out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index b2c6d9e6a..955c7790d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -72,6 +72,7 @@ from repowise.server.mcp_server._helpers import (
is_missing_table,
)
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
#: Where a resolved target path waits between its card being built and the
@@ -369,6 +370,19 @@ async def _resolve_call_graph(
"repowise omission reference; grep remains useful when graph "
"coverage itself may be incomplete."
)
+ elif direction == "in":
+ # Appended after the direct rows and only under the cap, so
+ # the callers_* counts keep meaning direct callers.
+ hop = await forwarding_wrapper_callers(
+ session,
+ repo_id,
+ node,
+ [r["symbol_id"] for r in visible],
+ known_nodes=node_map,
+ )
+ hop = filter_dicts_by_key(hop, "file", exclude_spec)
+ if hop:
+ result_data[key] = visible + hop
continue
if not total:
diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
index d3010e3c2..ee6bbd181 100644
--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
@@ -280,8 +280,9 @@ async def test_context_used_by_and_relations_recover_in_one_bounded_query_shape(
assert "Type000" not in relation_recovered
# The first call also pays the one aggregate behind the empty-callers basis
# and the one layer read behind the scope hint. Both are cached per repo per
- # index commit, so the second call pays neither.
- assert relation_statements <= 22 and used_by_statements <= 20
+ # index commit, so the second call pays neither. The seeded caller is a
+ # two-line forwarder, so the wrapper hop adds its fixed three reads.
+ assert relation_statements <= 25 and used_by_statements <= 20
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_wrapper_callers.py b/tests/unit/server/mcp/test_wrapper_callers.py
new file mode 100644
index 000000000..2d4c031db
--- /dev/null
+++ b/tests/unit/server/mcp/test_wrapper_callers.py
@@ -0,0 +1,289 @@
+"""Callers one hop past a forwarding wrapper (``_wrapper_callers``).
+
+Synthetic graphs in three languages: the hop is added and marked for a real
+wrapper, and withheld for a caller that does other work.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+from repowise.server.mcp_server import _basis, _wrapper_callers
+from repowise.server.mcp_server.tool_context import enrichment
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+
[email protected](autouse=True)
+def _fresh_basis_cache():
+ _basis.reset_cache()
+ yield
+ _basis.reset_cache()
+
+
+def _sym(rid, node_id, *, lines=(10, 30), kind="function", language="typescript", name=None):
+ file_path, _, qual = node_id.partition("::")
+ return GraphNode(
+ id=f"w_{node_id}",
+ repository_id=rid,
+ node_id=node_id,
+ node_type="symbol",
+ name=name or qual.split(".")[-1],
+ file_path=file_path,
+ kind=kind,
+ language=language,
+ start_line=lines[0],
+ end_line=lines[1],
+ created_at=_NOW,
+ )
+
+
+def _edge(rid, source, target, *, edge_type="calls", confidence=0.9, **extra):
+ return GraphEdge(
+ id=f"w_{source}->{target}:{edge_type}",
+ repository_id=rid,
+ source_node_id=source,
+ target_node_id=target,
+ edge_type=edge_type,
+ confidence=confidence,
+ created_at=_NOW,
+ **extra,
+ )
+
+
+async def _callers(session, rid, target, **kw) -> dict:
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await session.get(Repository, rid),
+ target,
+ "symbol",
+ out,
+ want_callers=True,
+ **kw,
+ )
+ return out
+
+
+async def test_ts_same_named_runtime_wrapper_lists_its_callers_marked(session, populated_db):
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "src/poll.ts::prune", lines=(59, 70)),
+ _sym(rid, "src/poll.runtime.ts::prune", lines=(9, 13)),
+ _sym(rid, "src/diag.ts::tick", lines=(100, 140)),
+ _sym(rid, "src/poll.test.ts::__module__", lines=(1, 200), kind="module"),
+ _edge(rid, "src/poll.runtime.ts::prune", "src/poll.ts::prune"),
+ _edge(rid, "src/poll.test.ts::__module__", "src/poll.ts::prune"),
+ _edge(rid, "src/diag.ts::tick", "src/poll.runtime.ts::prune", resolution_origin="import_scoped"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "src/poll.ts::prune")
+ ids = [r.get("symbol_id") for r in out["callers"]]
+ assert set(ids[:2]) == {"src/poll.runtime.ts::prune", "src/poll.test.ts::__module__"}
+ hop = out["callers"][2]
+ assert hop["symbol_id"] == "src/diag.ts::tick"
+ assert hop["file"] == "src/diag.ts"
+ assert hop["edge_type"] == "calls"
+ assert hop["via"] == "import_scoped"
+ assert hop["via_wrapper"] == "src/poll.runtime.ts::prune"
+ assert all("via_wrapper" not in r for r in out["callers"][:2])
+ # Direct-caller counts are untouched by the hop rows.
+ assert "callers_total" not in out
+
+
+async def test_python_pass_through_with_another_name_is_a_wrapper(session, populated_db):
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "pkg/core.py::_load_impl", lines=(5, 40), language="python"),
+ _sym(rid, "pkg/api.py::load", lines=(12, 14), language="python"),
+ _sym(rid, "app/main.py::run", lines=(3, 20), language="python"),
+ _edge(rid, "pkg/api.py::load", "pkg/core.py::_load_impl"),
+ _edge(rid, "app/main.py::run", "pkg/api.py::load"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "pkg/core.py::_load_impl")
+ assert [(r["symbol_id"], r.get("via_wrapper")) for r in out["callers"]] == [
+ ("pkg/api.py::load", None),
+ ("app/main.py::run", "pkg/api.py::load"),
+ ]
+
+
+async def test_go_caller_doing_other_work_is_not_expanded(session, populated_db):
+ """Short but calls something else too, or same-named but long: neither is a wrapper."""
+ rid = populated_db
+ go = {"language": "go"}
+ session.add_all(
+ [
+ _sym(rid, "store/db.go::Open", lines=(10, 50), **go),
+ _sym(rid, "cmd/main.go::handle", lines=(5, 7), **go),
+ _sym(rid, "cmd/main.go::logf", lines=(20, 22), **go),
+ _sym(rid, "srv/db.go::Open", lines=(10, 60), kind="method", **go),
+ _sym(rid, "cmd/run.go::serve", lines=(1, 9), **go),
+ _edge(rid, "cmd/main.go::handle", "store/db.go::Open"),
+ _edge(rid, "cmd/main.go::handle", "cmd/main.go::logf"),
+ _edge(rid, "srv/db.go::Open", "store/db.go::Open"),
+ _edge(rid, "cmd/run.go::serve", "cmd/main.go::handle"),
+ _edge(rid, "cmd/run.go::serve", "srv/db.go::Open"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "store/db.go::Open")
+ assert {r["symbol_id"] for r in out["callers"]} == {"cmd/main.go::handle", "srv/db.go::Open"}
+
+
+async def test_go_method_forwarder_is_expanded(session, populated_db):
+ rid = populated_db
+ go = {"language": "go"}
+ session.add_all(
+ [
+ _sym(rid, "store/db.go::Open", lines=(10, 50), **go),
+ _sym(rid, "store/client.go::Client.Open", lines=(30, 32), kind="method", **go),
+ _sym(rid, "cmd/main.go::main", lines=(1, 30), **go),
+ _edge(rid, "store/client.go::Client.Open", "store/db.go::Open"),
+ _edge(rid, "cmd/main.go::main", "store/client.go::Client.Open"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "store/db.go::Open")
+ assert out["callers"][-1]["symbol_id"] == "cmd/main.go::main"
+ assert out["callers"][-1]["via_wrapper"] == "store/client.go::Client.Open"
+
+
+async def test_wrapper_cycle_adds_nothing_already_listed(session, populated_db):
+ """A forwarder the target calls back: its caller is the target, which is never listed."""
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "a.ts::run", lines=(1, 30)),
+ _sym(rid, "b.ts::run", lines=(1, 4)),
+ _edge(rid, "b.ts::run", "a.ts::run"),
+ _edge(rid, "a.ts::run", "b.ts::run"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "a.ts::run")
+ assert [r["symbol_id"] for r in out["callers"]] == ["b.ts::run"]
+ assert all("via_wrapper" not in r for r in out["callers"])
+
+
+async def test_same_named_caller_that_calls_more_is_not_a_wrapper(session, populated_db):
+ """Same name, other file, short: still not a wrapper once it resolves another call."""
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "lib/impl.ts::save", lines=(1, 40)),
+ _sym(rid, "app/model.ts::save", lines=(10, 18)),
+ _sym(rid, "app/model.ts::validate", lines=(30, 40)),
+ _sym(rid, "app/form.ts::submit", lines=(1, 20)),
+ _edge(rid, "app/model.ts::save", "lib/impl.ts::save"),
+ _edge(rid, "app/model.ts::save", "app/model.ts::validate"),
+ _edge(rid, "app/form.ts::submit", "app/model.ts::save"),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "lib/impl.ts::save")
+ assert [r["symbol_id"] for r in out["callers"]] == ["app/model.ts::save"]
+
+
+async def test_hop_rows_are_capped(session, populated_db):
+ rid = populated_db
+ rows = [
+ _sym(rid, "lib/impl.py::work", lines=(1, 40), language="python"),
+ _sym(rid, "lib/__init__.py::work", lines=(1, 2), language="python"),
+ _edge(rid, "lib/__init__.py::work", "lib/impl.py::work"),
+ ]
+ for i in range(15):
+ rows.append(_sym(rid, f"app/m{i:02}.py::use", lines=(1, 9), language="python"))
+ rows.append(_edge(rid, f"app/m{i:02}.py::use", "lib/__init__.py::work"))
+ session.add_all(rows)
+ await session.flush()
+
+ out = await _callers(session, rid, "lib/impl.py::work")
+ hop = [r for r in out["callers"] if "via_wrapper" in r]
+ assert len(hop) == _wrapper_callers.MAX_WRAPPER_CALLER_ROWS
+ assert [r["symbol_id"] for r in hop] == [f"app/m{i:02}.py::use" for i in range(10)]
+
+ target = await session.get(GraphNode, "w_lib/impl.py::work")
+ capped = await _wrapper_callers.forwarding_wrapper_callers(
+ session, rid, target, ["lib/__init__.py::work"], limit=3
+ )
+ assert len(capped) == 3
+
+
+async def test_unreached_wrapper_falls_back_to_files_importing_it(session, populated_db):
+ """A dynamic import consumed in a callback leaves no call edge; the import edge names the file."""
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "src/poll.ts::prune", lines=(59, 70)),
+ _sym(rid, "src/poll.runtime.ts::prune", lines=(9, 13)),
+ _edge(rid, "src/poll.runtime.ts::prune", "src/poll.ts::prune"),
+ _edge(rid, "src/diag.ts", "src/poll.runtime.ts", edge_type="imports", confidence=1.0,
+ imported_names_json='["*"]'),
+ _edge(rid, "src/other.ts", "src/poll.runtime.ts", edge_type="imports", confidence=1.0,
+ imported_names_json='["unrelated"]'),
+ _edge(rid, "src/cli.ts", "src/poll.runtime.ts", edge_type="imports", confidence=1.0,
+ imported_names_json='["prune"]'),
+ ]
+ )
+ await session.flush()
+
+ out = await _callers(session, rid, "src/poll.ts::prune")
+ named = out["callers"][1]
+ assert named["file"] == "src/cli.ts" and "wholesale" not in named
+ assert out["callers"][-1] == {
+ "file": "src/diag.ts",
+ "imports": True,
+ "confidence": 1.0,
+ "wholesale": True,
+ "via_wrapper": "src/poll.runtime.ts::prune",
+ }
+ assert len(out["callers"]) == 3
+
+
+async def test_output_is_byte_identical_when_no_caller_is_a_wrapper(
+ session, populated_db, monkeypatch
+):
+ rid = populated_db
+ session.add_all(
+ [
+ _sym(rid, "x.py::target", lines=(1, 30), language="python"),
+ _sym(rid, "y.py::big", lines=(1, 80), language="python"),
+ _sym(rid, "z.py::top", lines=(1, 5), language="python"),
+ _edge(rid, "y.py::big", "x.py::target"),
+ _edge(rid, "z.py::top", "y.py::big"),
+ ]
+ )
+ await session.flush()
+
+ with_hop = await _callers(session, rid, "x.py::target")
+
+ async def _none(*_a, **_k):
+ return []
+
+ monkeypatch.setattr(enrichment, "forwarding_wrapper_callers", _none)
+ without = await _callers(session, rid, "x.py::target")
+ assert json.dumps(with_hop, sort_keys=False) == json.dumps(without, sort_keys=False)