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): stop get_context calling a subclass and a fixture a caller (#1663)

Raghav Chamadiya2c90d9595d20
diff --git a/packages/api-client/src/types/intelligence.ts b/packages/api-client/src/types/intelligence.ts
index d694fa525..509481b8d 100644
--- a/packages/api-client/src/types/intelligence.ts
+++ b/packages/api-client/src/types/intelligence.ts
@@ -2,6 +2,11 @@
// Graph Intelligence
// ---------------------------------------------------------------------------
+// Imported rather than re-declared: `group` is a closed vocabulary pinned to
+// the engine's edge-type set by a Python test, and a local copy here would be
+// its third.
+import type { SymbolRelationGroup } from "@repowise-dev/types/symbols";
+
export interface SymbolNodeSummary {
symbol_id: string;
name: string;
@@ -26,11 +31,16 @@ export interface CallerCalleeEntry {
export interface CallersCalleesResponse {
symbol_id: string;
symbol: SymbolNodeSummary;
+ /** `calls` edges only. Every other relation kind is in `relations`. */
callers: CallerCalleeEntry[];
callees: CallerCalleeEntry[];
+ /** True totals, not the number of rows served. */
caller_count: number;
callee_count: number;
truncated: boolean;
+ /** Heritage, framework wiring and references, each named and counted.
+ * Absent on a backend that predates the split. */
+ relations?: SymbolRelationGroup<CallerCalleeEntry>[];
}
export interface CommunityMember {
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 6ea86bc43..77058c984 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
@@ -39,11 +39,12 @@ from repowise.core.persistence.models import (
Repository,
)
from repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path_list
+from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF
# Minimum confidence for call edges to filter false positives
_MIN_CALL_CONFIDENCE = 0.7
-# Edge types that count as a "caller"/"callee" relationship. Sorted so the
+# Every edge type meaning "something reaches this symbol". Sorted so the
# generated SQL is stable; the shared view is the source of truth.
#
# The private copy this replaced omitted `method_implements`, so a Go type
@@ -57,7 +58,29 @@ _MIN_CALL_CONFIDENCE = 0.7
# exactly one edge across all 42 indexes, and what it admits is a `__module__`
# entry in an Express handler's caller list. Taking the shared view whole is
# still right: hand-trimming a member here is how the private sets started.
-_CALL_EDGE_TYPES = sorted(SYMBOL_USE_EDGE_TYPES)
+#
+# It is the right set for *degree* and the wrong one for `callers`: a subclass
+# reaches its base without ever calling it. Only `calls` populates
+# callers/callees now; `_RELATION_EDGE_TYPES` carries the rest, named.
+_SYMBOL_USE_EDGE_TYPES = sorted(SYMBOL_USE_EDGE_TYPES)
+
+#: The one edge type that is literally a call. Everything else that reaches a
+#: symbol is reported by kind under `relations` instead of being poured into
+#: `callers`. Measured on this repo's own index: 9.1% of rows served under
+#: `callers` were not calls, and on 705 symbols *every* row was not a call — a
+#: pytest fixture was reported as having 388 callers, with a note telling the
+#: agent to grep for a call site that does not exist.
+#:
+#: `tool_symbol._expand_callees` imports this for its `callee_bodies` walk, so
+#: widening it again would serve base-class and framework-wiring *source* as
+#: callees for three hops. Keep it meaning what it is named.
+_CALL_EDGE_TYPES = ["calls"]
+
+#: Rows carried per relation kind. Deliberately far below the call cap: the
+#: agent question these answer is "what else reaches this, and how", which the
+#: kind and the honest total answer. Naming them costs less than the
+#: mislabelled rows it removes — measured net −27% on the affected symbols.
+_RELATION_ROW_CAP = 5
# Degree reported for a FILE. `file_signals` states it as "N files depend on
# this", so it is counted over file dependencies rather than every adjacent
@@ -82,25 +105,36 @@ def _unique_by_symbol(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
return out
-async def _count_call_neighbors(
+async def _count_neighbors_by_edge_type(
session: AsyncSession, repo_id: str, node_id: str, *, inbound: bool
-) -> int:
- """Count distinct caller (inbound) / callee (outbound) symbols above the
- confidence floor — the TRUE total, independent of the display limit.
+) -> dict[str, int]:
+ """Count distinct inbound (or outbound) symbols per edge type, above the
+ confidence floor — the TRUE totals, independent of the display limit.
Without this the callers list capped silently at the limit and reported
``truncated: false``, which misled an agent doing a find-all-callers sweep
on a high-fan-in symbol into thinking 20 was the whole set (S2 dogfood).
+
+ `crud.get_node_degree_by_edge_type` answers the same shape for the REST
+ symbol page and is deliberately **not** reused: it counts edges with no
+ confidence floor, while this surface counts distinct symbols above 0.7. Two
+ symbols can be joined by more than one edge, so borrowing it would make the
+ total exceed what the rows can ever show and re-arm the bug above. The
+ rows and the totals have to be cut by the same rule.
"""
matched = GraphEdge.target_node_id if inbound else GraphEdge.source_node_id
other = GraphEdge.source_node_id if inbound else GraphEdge.target_node_id
- stmt = select(func.count(distinct(other))).where(
- GraphEdge.repository_id == repo_id,
- matched == node_id,
- GraphEdge.edge_type.in_(_CALL_EDGE_TYPES),
- GraphEdge.confidence >= _MIN_CALL_CONFIDENCE,
+ stmt = (
+ select(GraphEdge.edge_type, func.count(distinct(other)))
+ .where(
+ GraphEdge.repository_id == repo_id,
+ matched == node_id,
+ GraphEdge.edge_type.in_(_SYMBOL_USE_EDGE_TYPES),
+ GraphEdge.confidence >= _MIN_CALL_CONFIDENCE,
+ )
+ .group_by(GraphEdge.edge_type)
)
- return int((await session.execute(stmt)).scalar() or 0)
+ return {edge_type: int(n or 0) for edge_type, n in await session.execute(stmt)}
async def _resolve_call_graph(
@@ -157,39 +191,22 @@ async def _resolve_call_graph(
)
return
- direction = "both"
- if want_callers and not want_callees:
- direction = "callers"
- elif want_callees and not want_callers:
- direction = "callees"
-
- edges = await get_graph_edges_for_node(
- session,
- repo_id,
- node.node_id,
- direction=direction,
- edge_types=_CALL_EDGE_TYPES,
- limit=limit,
+ # Totals per edge type, per direction, before any rows. They say which
+ # relation kinds exist at all, so nothing is fetched speculatively, and
+ # they are the numbers reported — the rows are cut from the same rule.
+ totals_in = (
+ await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=True)
+ if want_callers
+ else {}
)
-
- # Hydrate other nodes
- other_ids = list(
- {e.source_node_id if e.target_node_id == node.node_id else e.target_node_id for e in edges}
+ totals_out = (
+ await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=False)
+ if want_callees
+ else {}
)
- node_map = await get_graph_nodes_by_ids(session, repo_id, other_ids)
-
- callers: list[dict[str, Any]] = []
- callees: list[dict[str, Any]] = []
-
- for e in edges:
- # Filter out low-confidence edges (false positives from Tier 3 global resolution)
- if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
- continue
- is_caller = e.target_node_id == node.node_id
- other_id = e.source_node_id if is_caller else e.target_node_id
+ def _entry(edge: GraphEdge, other_id: str, *, with_edge_type: bool) -> dict[str, Any]:
other_node = node_map.get(other_id)
-
entry: dict[str, Any] = {
"symbol_id": other_id,
"name": other_node.name
@@ -203,52 +220,147 @@ async def _resolve_call_graph(
# straight to the call-site neighbourhood instead of grepping
# for it (the S1 dogfood's most common follow-up).
"line": other_node.start_line if other_node else None,
- "confidence": e.confidence,
- "edge_type": e.edge_type,
+ "confidence": edge.confidence,
}
+ # Omitted on a relation row: the group above it names the edge type
+ # once, so repeating it per row is `"method_implements"` five times for
+ # nothing. Kept on callers/callees, which have no group to carry it.
+ if with_edge_type:
+ entry["edge_type"] = edge.edge_type
# Which resolution strategy produced the edge. Absent on an index built
# before origins were stamped, so it is added only when present.
- if e.resolution_origin:
- entry["via"] = e.resolution_origin
- if is_caller:
- callers.append(entry)
- else:
- callees.append(entry)
-
- callers = filter_dicts_by_key(callers, "file", exclude_spec)
- callees = filter_dicts_by_key(callees, "file", exclude_spec)
-
- # Sort by confidence DESC
- callers.sort(key=lambda x: -(x.get("confidence") or 0))
- callees.sort(key=lambda x: -(x.get("confidence") or 0))
-
- # One entry per neighbouring symbol, highest-confidence edge kept. Two
- # symbols can be joined by more than one edge — in Go a struct routinely
- # both `calls` an interface's methods and `method_implements` it — and the
- # truncation check below compares this length against a COUNT(DISTINCT),
- # so counting edges here reports "not truncated" while real callers are
- # missing. That is the S2 dogfood failure `_count_call_neighbors` exists
- # to prevent, so the two sides have to count the same thing.
- callers = _unique_by_symbol(callers)
- callees = _unique_by_symbol(callees)
+ if edge.resolution_origin:
+ entry["via"] = edge.resolution_origin
+ return entry
+
+ # One fetch per edge type present, each capped on its own. A single fetch
+ # over every use edge type shared one confidence-ranked cap, so the
+ # commonest kind could evict the rest — the failure #1660 measured on
+ # django, where `Model` served 39 subclasses and 1 of its 8 callers. It is
+ # mild on this repo (6 rows lost, all where `extends` ties `calls` at 0.9)
+ # but it is the same mechanism and it is repo-dependent.
+ present = sorted(set(totals_in) | set(totals_out))
+ edges_by_type: dict[str, list[GraphEdge]] = {}
+ for edge_type in present:
+ want_in = want_callers and edge_type in totals_in
+ want_out = want_callees and edge_type in totals_out
+ if not (want_in or want_out):
+ continue
+ edges_by_type[edge_type] = await get_graph_edges_for_node(
+ session,
+ repo_id,
+ node.node_id,
+ direction=("both" if want_in and want_out else ("callers" if want_in else "callees")),
+ edge_types=[edge_type],
+ limit=limit if edge_type == "calls" else _RELATION_ROW_CAP,
+ )
- if want_callers:
- result_data["callers"] = callers
- total = await _count_call_neighbors(session, repo_id, node.node_id, inbound=True)
- if total > len(callers):
- result_data["callers_total"] = total
- result_data["callers_truncated"] = True
- result_data["_callers_note"] = (
- f"Showing top {len(callers)} of {total} callers by confidence. The "
- f"graph view caps here; for the complete set (e.g. a signature change) "
- f"grep '{node.name}('."
+ # Hydrated once for every edge type at once: the neighbour lookup is the
+ # expensive half and it does not care which relation asked.
+ node_map = await get_graph_nodes_by_ids(
+ session,
+ repo_id,
+ list(
+ {
+ e.source_node_id if e.target_node_id == node.node_id else e.target_node_id
+ for edges in edges_by_type.values()
+ for e in edges
+ }
+ ),
+ )
+
+ relations: list[dict[str, Any]] = []
+ for edge_type, edges in edges_by_type.items():
+ inbound: list[dict[str, Any]] = []
+ outbound: list[dict[str, Any]] = []
+ # A self-edge — a recursive call — matches both direction queries, so
+ # it comes back twice. Dedupe on the edge, then place it on every side
+ # it touches: it used to be appended to `callers` twice and to
+ # `callees` never, and only `_unique_by_symbol` hid the duplicate.
+ for e in {edge.id: edge for edge in edges}.values():
+ # Low-confidence edges are false positives from Tier 3 global
+ # resolution, and the totals above exclude them too.
+ if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
+ continue
+ is_call = edge_type == "calls"
+ if e.target_node_id == node.node_id:
+ inbound.append(_entry(e, e.source_node_id, with_edge_type=is_call))
+ if e.source_node_id == node.node_id:
+ outbound.append(_entry(e, e.target_node_id, with_edge_type=is_call))
+
+ for direction, rows, totals in (
+ ("in", inbound, totals_in),
+ ("out", outbound, totals_out),
+ ):
+ rows = filter_dicts_by_key(rows, "file", exclude_spec)
+ rows.sort(key=lambda x: -(x.get("confidence") or 0))
+ # One entry per neighbouring symbol, highest-confidence edge kept.
+ # The truncation check compares this length against a
+ # COUNT(DISTINCT), so counting edges here would report "not
+ # truncated" while real callers are missing (the S2 dogfood).
+ rows = _unique_by_symbol(rows)
+ total = totals.get(edge_type, 0)
+
+ if edge_type == "calls":
+ key = "callers" if direction == "in" else "callees"
+ if (direction == "in" and not want_callers) or (
+ direction == "out" and not want_callees
+ ):
+ continue
+ result_data[key] = rows
+ if total > len(rows):
+ result_data[f"{key}_total"] = total
+ result_data[f"{key}_truncated"] = True
+ if direction == "in":
+ result_data["_callers_note"] = (
+ f"Showing top {len(rows)} of {total} callers by confidence. "
+ f"The graph view caps here; for the complete set (e.g. a "
+ f"signature change) grep '{node.name}('."
+ )
+ continue
+
+ if not total:
+ continue
+ # Keyed per edge type, not per group: "extends" and "implements"
+ # are different sentences and an agent needs to know which it is
+ # in. `group` is the shared vocabulary #1660 pinned, imported
+ # rather than re-listed so a new edge type cannot land unnamed.
+ relations.append(
+ {
+ "edge_type": edge_type,
+ "group": SYMBOL_RELATION_GROUP_OF[edge_type],
+ "direction": direction,
+ "total": total,
+ "rows": rows,
+ }
)
+
+ # `calls` may be absent entirely, and an omitted key reads as "not asked
+ # for" rather than "none" — the distinction an agent needs before deciding
+ # nothing calls this.
+ if want_callers:
+ result_data.setdefault("callers", [])
if want_callees:
- result_data["callees"] = callees
- total = await _count_call_neighbors(session, repo_id, node.node_id, inbound=False)
- if total > len(callees):
- result_data["callees_total"] = total
- result_data["callees_truncated"] = True
+ result_data.setdefault("callees", [])
+
+ if relations:
+ relations.sort(key=lambda r: (r["direction"], -r["total"], r["edge_type"]))
+ result_data["relations"] = relations
+ # Without this an empty `callers` beside a populated `relations` reads
+ # as a graph failure rather than the answer. This is the 705-symbol
+ # case on our own index: the old code answered it with 50 rows of
+ # framework wiring under "callers" and a note saying to grep for a
+ # call site that does not exist.
+ # Keyed on the *count*, not on `callers` being empty: an exclusion spec
+ # can filter every row while callers still exist, and then "Nothing
+ # calls X" would contradict the `_callers_note` telling the agent to go
+ # and grep for them.
+ inbound_kinds = [r for r in relations if r["direction"] == "in"]
+ if want_callers and not totals_in.get("calls") and inbound_kinds:
+ reached = ", ".join(f"{r['total']} {r['edge_type']}" for r in inbound_kinds)
+ result_data["_call_graph_note"] = (
+ f"Nothing calls '{node.name}'; it is reached by {reached}. See `relations`."
+ )
async def _resolve_file_level_callers(
@@ -353,7 +465,12 @@ async def _resolve_metrics(
repo_id,
node.node_id,
edge_types=(
- _CALL_EDGE_TYPES if node.node_type == "symbol" else _FILE_DEPENDENCY_EDGE_TYPES
+ # Degree is "how connected is this symbol", so it stays over every
+ # use edge type even though `callers` narrowed to calls. Matching
+ # `routers/graph/intelligence.py`, which reports the same number.
+ _SYMBOL_USE_EDGE_TYPES
+ if node.node_type == "symbol"
+ else _FILE_DEPENDENCY_EDGE_TYPES
),
)
diff --git a/packages/server/src/repowise/server/routers/graph/intelligence.py b/packages/server/src/repowise/server/routers/graph/intelligence.py
index baa641ee2..41de6233f 100644
--- a/packages/server/src/repowise/server/routers/graph/intelligence.py
+++ b/packages/server/src/repowise/server/routers/graph/intelligence.py
@@ -27,13 +27,13 @@ from repowise.server.mcp_server._graph_utils import (
)
from repowise.server.routers.graph._common import with_repo
from repowise.server.schemas import (
- CallerCalleeEntry,
CallersCalleesResponse,
ExecutionFlowEntry,
ExecutionFlowsResponse,
GraphMetricsResponse,
SymbolNodeSummary,
)
+from repowise.server.services.symbol_relations import load_symbol_relations
router = APIRouter()
@@ -94,18 +94,35 @@ async def get_callers_callees(
repo_id: str,
symbol_id: str = Query(..., description="Symbol node ID (path::Name)"),
direction: str = Query("both", description="callers, callees, or both"),
- edge_types: str = Query("calls", description="Comma-separated edge types"),
+ edge_types: str = Query(
+ "", description="Optional comma-separated filter on `relations` kinds; empty means all"
+ ),
limit: int = Query(20, ge=1, le=100),
session: AsyncSession = Depends(get_db_session),
_repo: object = Depends(with_repo),
) -> CallersCalleesResponse:
- """Find who calls a symbol and what it calls. Also works for class hierarchy."""
+ """Who calls a symbol, what it calls, and every other relation it has.
+
+ Shares `load_symbol_relations` with `/api/symbols/detail`, so the drawer
+ this feeds and the routed symbol page cannot disagree about what reaches a
+ symbol. Two things changed when they were joined:
+
+ - `callers`/`callees` are `calls` edges only. They used to be whatever
+ `edge_types` asked for, under one heading, so a subclass could be served
+ as a caller. Heritage and framework wiring are in `relations`, named.
+ - `caller_count`/`callee_count` are the true totals, not the number of
+ rows served. They were `len(callers)`, capped at `limit`, and
+ `symbol-drawer-wrapper.tsx` renders them as `caller_total` — so a symbol
+ with 275 callers reported 20.
+
+ `edge_types` now filters `relations` rather than deciding what counts as a
+ caller. No client in this repo passes it; both `useCallersCallees` call
+ sites omit it.
+ """
if direction not in ("callers", "callees", "both"):
direction = "both"
- et_list = [t.strip() for t in edge_types.split(",") if t.strip()]
- if not et_list:
- et_list = ["calls"]
+ et_filter = {t.strip() for t in edge_types.split(",") if t.strip()}
# Resolve symbol: exact then fuzzy
node = await crud.get_graph_node(session, repo_id, symbol_id)
@@ -132,38 +149,18 @@ async def get_callers_callees(
rows.sort(key=lambda r: r.node_id)
node = rows[0]
- edges = await crud.get_graph_edges_for_node(
- session,
- repo_id,
- node.node_id,
- direction=direction,
- edge_types=et_list,
- limit=limit,
+ relations = await load_symbol_relations(
+ session, repo_id, node.node_id, present=True, call_row_cap=limit
)
-
- # Hydrate connected nodes
- other_ids: set[str] = set()
- for e in edges:
- if e.source_node_id != node.node_id:
- other_ids.add(e.source_node_id)
- if e.target_node_id != node.node_id:
- other_ids.add(e.target_node_id)
-
- node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))
-
- callers: list[CallerCalleeEntry] = []
- callees: list[CallerCalleeEntry] = []
-
- for e in edges:
- entry = CallerCalleeEntry.from_edge(e, node_id=node.node_id, node_map=node_map)
- if e.target_node_id == node.node_id:
- callers.append(entry)
- else:
- callees.append(entry)
-
- callers.sort(key=lambda x: (-x.confidence, x.name))
- callees.sort(key=lambda x: (-x.confidence, x.name))
-
+ groups = [
+ g
+ for g in relations.groups
+ if (not et_filter or g.edge_type in et_filter)
+ and (direction == "both" or (direction == "callers") == (g.direction == "in"))
+ ]
+
+ wants_in = direction in ("callers", "both")
+ wants_out = direction in ("callees", "both")
return CallersCalleesResponse(
symbol_id=node.node_id,
symbol=SymbolNodeSummary(
@@ -174,11 +171,15 @@ async def get_callers_callees(
start_line=node.start_line,
signature=node.signature,
),
- callers=callers if direction in ("callers", "both") else [],
- callees=callees if direction in ("callees", "both") else [],
- caller_count=len(callers),
- callee_count=len(callees),
- truncated=(len(callers) >= limit or len(callees) >= limit),
+ callers=relations.callers if wants_in else [],
+ callees=relations.callees if wants_out else [],
+ caller_count=relations.caller_total if wants_in else 0,
+ callee_count=relations.callee_total if wants_out else 0,
+ relations=groups,
+ truncated=(
+ (wants_in and len(relations.callers) < relations.caller_total)
+ or (wants_out and len(relations.callees) < relations.callee_total)
+ ),
)
diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.py
index ed14aeebd..c63903c70 100644
--- a/packages/server/src/repowise/server/routers/symbols.py
+++ b/packages/server/src/repowise/server/routers/symbols.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import json
-from dataclasses import dataclass, field
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -11,7 +10,6 @@ from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import iso_utc
-from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
from repowise.core.persistence import crud
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import (
@@ -23,15 +21,11 @@ from repowise.core.persistence.models import (
from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import Paginated, SymbolImportanceComponents, SymbolResponse
-from repowise.server.schemas.intelligence import (
- SYMBOL_RELATION_GROUP_OF,
- CallerCalleeEntry,
- SymbolRelationGroup,
-)
from repowise.server.services.symbol_ranking import (
compute_components,
rank_symbols,
)
+from repowise.server.services.symbol_relations import load_symbol_relations
router = APIRouter(
prefix="/api/symbols",
@@ -403,7 +397,7 @@ async def symbol_detail(
# own declaring file or class, which 34,570 of 34,808 symbols on this repo
# have — was served as a caller.
node = await crud.get_graph_node(session, repo_id, symbol_id)
- relations = await _symbol_relations(session, repo_id, symbol_id, present=node is not None)
+ relations = await load_symbol_relations(session, repo_id, symbol_id, present=node is not None)
governing = [
{"id": d.id, "title": d.title, "status": d.status}
@@ -453,132 +447,6 @@ async def symbol_detail(
}
-#: Rows served per relation kind per direction. Calls get the larger cap
-#: because they are the reason most readers open the page; the rest exist to
-#: be *named and counted*, and a caller who wants all 1,516 subclasses has the
-#: graph page for it.
-_CALL_ROW_CAP = 40
-_RELATION_ROW_CAP = 10
-
-
-@dataclass
-class _SymbolRelations:
- """Callers/callees plus every other relation kind, each counted honestly."""
-
- callers: list[CallerCalleeEntry] = field(default_factory=list)
- callees: list[CallerCalleeEntry] = field(default_factory=list)
- caller_total: int = 0
- callee_total: int = 0
- groups: list[SymbolRelationGroup] = field(default_factory=list)
- #: Degree across every use edge type, summed from the same counts the
- #: rows were cut from rather than re-queried, so the two cannot disagree.
- in_degree: int = 0
- out_degree: int = 0
-
-
-async def _symbol_relations(
- session: AsyncSession,
- repo_id: str,
- symbol_id: str,
- *,
- present: bool,
-) -> _SymbolRelations:
- """Fetch this symbol's relations, each kind counted and capped on its own.
-
- One fetch per edge type rather than one for all of
- `SYMBOL_USE_EDGE_TYPES`, because a shared cap ranked by confidence lets the
- commonest kind evict every other. Measured on the live django index:
- `Model` has 8 callers and 1,516 subclasses, and the single 40-row cut
- served 39 subclasses and 1 caller; `TestCase` has 3 callers and 868
- subclasses and served none of its callers at all. Grouping alone does not
- fix it — `extends` would still evict `implements` inside one heritage cap,
- leaving "Implemented by (5)" over an empty list, which is the same lie one
- level down.
-
- Cost is unchanged for the common symbol. Only edge types the counts show
- are present get fetched, and most symbols have exactly one, so this is the
- same query count as the single-fetch version it replaces.
- """
- out = _SymbolRelations()
- if not present:
- return out
-
- # Every total in two queries, before any rows. They say which edge types
- # exist at all, so nothing is fetched speculatively, and they are the
- # numbers the surface reports.
- totals = await crud.get_node_degree_by_edge_type(
- session, repo_id, symbol_id, edge_types=sorted(SYMBOL_USE_EDGE_TYPES)
- )
- if not totals:
- return out
- out.in_degree = sum(t["in_degree"] for t in totals.values())
- out.out_degree = sum(t["out_degree"] for t in totals.values())
-
- edges_by_type: dict[str, list] = {}
- for edge_type in sorted(totals):
- edges_by_type[edge_type] = await crud.get_graph_edges_for_node(
- session,
- repo_id,
- symbol_id,
- direction="both",
- edge_types=[edge_type],
- limit=_CALL_ROW_CAP if edge_type == "calls" else _RELATION_ROW_CAP,
- )
-
- # Hydrated once for every edge type at once: the neighbour lookup is the
- # expensive half and it does not care which relation asked.
- other_ids = {
- e.source_node_id if e.target_node_id == symbol_id else e.target_node_id
- for edges in edges_by_type.values()
- for e in edges
- }
- node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))
-
- for edge_type, edges in edges_by_type.items():
- inbound: list[CallerCalleeEntry] = []
- outbound: list[CallerCalleeEntry] = []
- # A self-edge — a recursive call — matches both of the direction
- # queries, so it comes back twice. It is also counted once in each
- # direction by the totals, so it belongs on both sides exactly once:
- # dedupe first, then place each edge on every side it touches. Served
- # once, its row is a permanent "+1 more" no paging can reach.
- for e in {edge.id: edge for edge in edges}.values():
- entry = CallerCalleeEntry.from_edge(e, node_id=symbol_id, node_map=node_map)
- if e.target_node_id == symbol_id:
- inbound.append(entry)
- if e.source_node_id == symbol_id:
- outbound.append(entry)
- for rows in (inbound, outbound):
- rows.sort(key=lambda r: (-r.confidence, r.name))
-
- if edge_type == "calls":
- out.callers = inbound
- out.callees = outbound
- out.caller_total = totals["calls"]["in_degree"]
- out.callee_total = totals["calls"]["out_degree"]
- continue
-
- # Keyed per edge type, not per group: "Extended by" and "Implemented
- # by" are different sentences and a reader needs to know which they
- # are in.
- for direction, rows in (("in", inbound), ("out", outbound)):
- total = totals[edge_type]["in_degree" if direction == "in" else "out_degree"]
- if not total:
- continue
- out.groups.append(
- SymbolRelationGroup(
- direction=direction,
- edge_type=edge_type,
- group=SYMBOL_RELATION_GROUP_OF[edge_type],
- total=total,
- rows=rows,
- )
- )
-
- out.groups.sort(key=lambda g: (g.direction, -g.total, g.edge_type))
- return out
-
-
def _symbol_fix_count(git_meta: object | None, symbol_id: str) -> int | None:
"""How many counted bug fixes landed in *symbol_id*, or ``None`` if unknown.
diff --git a/packages/server/src/repowise/server/schemas/intelligence.py b/packages/server/src/repowise/server/schemas/intelligence.py
index 2ae2e1a5a..aa9825d42 100644
--- a/packages/server/src/repowise/server/schemas/intelligence.py
+++ b/packages/server/src/repowise/server/schemas/intelligence.py
@@ -73,16 +73,6 @@ class CallerCalleeEntry(BaseModel):
)
-class CallersCalleesResponse(BaseModel):
- symbol_id: str
- symbol: SymbolNodeSummary
- callers: list[CallerCalleeEntry]
- callees: list[CallerCalleeEntry]
- caller_count: int
- callee_count: int
- truncated: bool
-
-
# ---------------------------------------------------------------------------
# Symbol relation vocabulary
# ---------------------------------------------------------------------------
@@ -126,6 +116,24 @@ class SymbolRelationGroup(BaseModel):
rows: list[CallerCalleeEntry]
+class CallersCalleesResponse(BaseModel):
+ symbol_id: str
+ symbol: SymbolNodeSummary
+ #: `calls` edges only. Every other relation kind is in `relations`, so a
+ #: subclass is never served as a caller.
+ callers: list[CallerCalleeEntry]
+ callees: list[CallerCalleeEntry]
+ #: True totals, not the number of rows served. `symbol-drawer-wrapper.tsx`
+ #: renders these as `caller_total`, and they used to be `len(callers)`
+ #: capped at the request limit.
+ caller_count: int
+ callee_count: int
+ truncated: bool
+ #: Defaulted so a client reading an older server sees an absent group list
+ #: rather than a validation error.
+ relations: list[SymbolRelationGroup] = []
+
+
class CommunityMember(BaseModel):
path: str
pagerank: float
diff --git a/packages/server/src/repowise/server/services/symbol_relations.py b/packages/server/src/repowise/server/services/symbol_relations.py
new file mode 100644
index 000000000..6a6b302dd
--- /dev/null
+++ b/packages/server/src/repowise/server/services/symbol_relations.py
@@ -0,0 +1,150 @@
+"""One symbol's relations, each kind counted and capped on its own.
+
+Shared by `/api/symbols/detail` (the routed symbol page) and
+`/api/graph/{repo}/callers-callees` (the symbol drawer). It lived in
+`routers/symbols.py` while only the first surface used it; the drawer then had
+honest call counts but no heritage, so the two surfaces disagreed about what
+reaches a symbol. Grouping in the client would have been a second copy of the
+vocabulary, which is the failure mode this whole area keeps re-creating.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
+from repowise.core.persistence import crud
+from repowise.server.schemas.intelligence import (
+ SYMBOL_RELATION_GROUP_OF,
+ CallerCalleeEntry,
+ SymbolRelationGroup,
+)
+
+#: Rows served per relation kind per direction. Calls get the larger cap
+#: because they are the reason most readers open the page; the rest exist to
+#: be *named and counted*, and a caller who wants all 1,516 subclasses has the
+#: graph page for it.
+CALL_ROW_CAP = 40
+RELATION_ROW_CAP = 10
+
+
+@dataclass
+class SymbolRelations:
+ """Callers/callees plus every other relation kind, each counted honestly."""
+
+ callers: list[CallerCalleeEntry] = field(default_factory=list)
+ callees: list[CallerCalleeEntry] = field(default_factory=list)
+ caller_total: int = 0
+ callee_total: int = 0
+ groups: list[SymbolRelationGroup] = field(default_factory=list)
+ #: Degree across every use edge type, summed from the same counts the
+ #: rows were cut from rather than re-queried, so the two cannot disagree.
+ in_degree: int = 0
+ out_degree: int = 0
+
+
+async def load_symbol_relations(
+ session: AsyncSession,
+ repo_id: str,
+ symbol_id: str,
+ *,
+ present: bool,
+ call_row_cap: int = CALL_ROW_CAP,
+ relation_row_cap: int = RELATION_ROW_CAP,
+) -> SymbolRelations:
+ """Fetch this symbol's relations, each kind counted and capped on its own.
+
+ One fetch per edge type rather than one for all of
+ `SYMBOL_USE_EDGE_TYPES`, because a shared cap ranked by confidence lets the
+ commonest kind evict every other. Measured on the live django index:
+ `Model` has 8 callers and 1,516 subclasses, and the single 40-row cut
+ served 39 subclasses and 1 caller; `TestCase` has 3 callers and 868
+ subclasses and served none of its callers at all. Grouping alone does not
+ fix it — `extends` would still evict `implements` inside one heritage cap,
+ leaving "Implemented by (5)" over an empty list, which is the same lie one
+ level down.
+
+ Cost is unchanged for the common symbol. Only edge types the counts show
+ are present get fetched, and most symbols have exactly one, so this is the
+ same query count as the single-fetch version it replaces.
+ """
+ out = SymbolRelations()
+ if not present:
+ return out
+
+ # Every total in two queries, before any rows. They say which edge types
+ # exist at all, so nothing is fetched speculatively, and they are the
+ # numbers the surface reports.
+ totals = await crud.get_node_degree_by_edge_type(
+ session, repo_id, symbol_id, edge_types=sorted(SYMBOL_USE_EDGE_TYPES)
+ )
+ if not totals:
+ return out
+ out.in_degree = sum(t["in_degree"] for t in totals.values())
+ out.out_degree = sum(t["out_degree"] for t in totals.values())
+
+ edges_by_type: dict[str, list] = {}
+ for edge_type in sorted(totals):
+ edges_by_type[edge_type] = await crud.get_graph_edges_for_node(
+ session,
+ repo_id,
+ symbol_id,
+ direction="both",
+ edge_types=[edge_type],
+ limit=call_row_cap if edge_type == "calls" else relation_row_cap,
+ )
+
+ # Hydrated once for every edge type at once: the neighbour lookup is the
+ # expensive half and it does not care which relation asked.
+ other_ids = {
+ e.source_node_id if e.target_node_id == symbol_id else e.target_node_id
+ for edges in edges_by_type.values()
+ for e in edges
+ }
+ node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))
+
+ for edge_type, edges in edges_by_type.items():
+ inbound: list[CallerCalleeEntry] = []
+ outbound: list[CallerCalleeEntry] = []
+ # A self-edge — a recursive call — matches both of the direction
+ # queries, so it comes back twice. It is also counted once in each
+ # direction by the totals, so it belongs on both sides exactly once:
+ # dedupe first, then place each edge on every side it touches. Served
+ # once, its row is a permanent "+1 more" no paging can reach.
+ for e in {edge.id: edge for edge in edges}.values():
+ entry = CallerCalleeEntry.from_edge(e, node_id=symbol_id, node_map=node_map)
+ if e.target_node_id == symbol_id:
+ inbound.append(entry)
+ if e.source_node_id == symbol_id:
+ outbound.append(entry)
+ for rows in (inbound, outbound):
+ rows.sort(key=lambda r: (-r.confidence, r.name))
+
+ if edge_type == "calls":
+ out.callers = inbound
+ out.callees = outbound
+ out.caller_total = totals["calls"]["in_degree"]
+ out.callee_total = totals["calls"]["out_degree"]
+ continue
+
+ # Keyed per edge type, not per group: "Extended by" and "Implemented
+ # by" are different sentences and a reader needs to know which they
+ # are in.
+ for direction, rows in (("in", inbound), ("out", outbound)):
+ total = totals[edge_type]["in_degree" if direction == "in" else "out_degree"]
+ if not total:
+ continue
+ out.groups.append(
+ SymbolRelationGroup(
+ direction=direction,
+ edge_type=edge_type,
+ group=SYMBOL_RELATION_GROUP_OF[edge_type],
+ total=total,
+ rows=rows,
+ )
+ )
+
+ out.groups.sort(key=lambda g: (g.direction, -g.total, g.edge_type))
+ return out
diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.ts
index bda30b18d..0b6b6fe9b 100644
--- a/packages/types/src/graph.ts
+++ b/packages/types/src/graph.ts
@@ -11,6 +11,10 @@
* `GraphExport` below before passing data to components.
*/
+// The relation vocabulary lives beside the symbol types that define it, so
+// `CallersCallees` below borrows it rather than restating the group union.
+import type { SymbolRelationGroup } from "./symbols";
+
// ---------------------------------------------------------------------------
// Core node + link
// ---------------------------------------------------------------------------
@@ -306,11 +310,16 @@ export interface CallerCalleeEntry {
export interface CallersCallees {
symbol_id: string;
symbol: SymbolNodeSummary;
+ /** `calls` edges only. Every other relation kind is in `relations`. */
callers: CallerCalleeEntry[];
callees: CallerCalleeEntry[];
+ /** True totals, not the number of rows served. */
caller_count: number;
callee_count: number;
truncated: boolean;
+ /** Heritage, framework wiring and references, each named and counted.
+ * Absent on a backend that predates the split. */
+ relations?: SymbolRelationGroup<CallerCalleeEntry>[];
}
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
index a46300d9c..dcdcd95da 100644
--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
@@ -4,7 +4,10 @@ import { useMemo } from "react";
import { useRouter } from "next/navigation";
import useSWR from "swr";
import { SymbolDrawer } from "@repowise-dev/ui/symbols/symbol-drawer";
-import { toSymbolBodyCall } from "@repowise-dev/ui/symbols/normalize-calls";
+import {
+ toSymbolBodyCall,
+ toSymbolBodyRelations,
+} from "@repowise-dev/ui/symbols/normalize-calls";
import {
fileEntityPath,
symbolEntityPath,
@@ -74,13 +77,17 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {
// boundary entirely — the rows are what that boundary exists to protect.
const calls = useMemo(
() => ({
- // `/callers-callees` defaults to `edge_types=calls`, so these rows are
- // calls already. The counts are the endpoint's unbounded totals rather
- // than the row arrays, which are cut at the request limit.
+ // `/callers-callees` serves `calls` edges only, so these rows are calls
+ // already. The counts are the endpoint's unbounded totals rather than
+ // the row arrays, which are cut at the request limit.
callers: (callData?.callers ?? []).map(toSymbolBodyCall),
callees: (callData?.callees ?? []).map(toSymbolBodyCall),
caller_total: callData?.caller_count ?? 0,
callee_total: callData?.callee_count ?? 0,
+ // Heritage and framework wiring. The drawer had honest call counts but
+ // no relations while the routed page had both, so the same symbol read
+ // differently depending on which surface you opened it from.
+ relations: toSymbolBodyRelations(callData?.relations),
}),
[callData],
);
diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.py
index d98b8da07..5dfd5e655 100644
--- a/tests/unit/server/mcp/test_context.py
+++ b/tests/unit/server/mcp/test_context.py
@@ -598,10 +598,22 @@ async def test_one_caller_joined_by_two_edge_types_is_listed_once(setup_mcp, ses
t = result["targets"][target_id]
matching = [c for c in t.get("callers", []) if c["symbol_id"] == caller_id]
assert len(matching) == 1, matching
- # Highest-confidence edge survives the collapse.
- assert matching[0]["edge_type"] == "method_implements"
+ # The two edges are different relations, so they are reported separately
+ # rather than collapsed onto whichever had the higher confidence: the call
+ # is a call, and satisfying the interface is heritage.
+ assert matching[0]["edge_type"] == "calls"
assert not t.get("callers_truncated")
+ impl = [
+ r
+ for r in t.get("relations", [])
+ if r["edge_type"] == "method_implements" and r["direction"] == "in"
+ ]
+ assert len(impl) == 1, t.get("relations")
+ assert impl[0]["group"] == "heritage"
+ assert impl[0]["total"] == 1
+ assert [r["symbol_id"] for r in impl[0]["rows"]] == [caller_id]
+
@pytest.mark.asyncio
async def test_high_fan_in_callers_signal_truncation(setup_mcp, session):
diff --git a/tests/unit/server/mcp/test_context_relations.py b/tests/unit/server/mcp/test_context_relations.py
new file mode 100644
index 000000000..992a30fa0
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_relations.py
@@ -0,0 +1,163 @@
+"""`get_context` must not report a subclass or a fixture as a caller.
+
+The agent surface carried the identical defect the symbol page shipped with:
+`_CALL_EDGE_TYPES` was the whole of `SYMBOL_USE_EDGE_TYPES`, poured straight
+into `callers`/`callees`. Measured on repowise's own index before the fix:
+9.1% of all rows served under `callers` were not calls, and on **705 symbols
+every single row was not a call**. The pytest fixture `client` was reported as
+having 388 callers, with a note telling the agent to grep for a call site that
+does not exist.
+
+These drive the real `get_context` tool rather than the helper, so they fail
+if the tool stops emitting the key and not only if the helper changes.
+"""
+
+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)
+
+BASE = "app/models.py::Model"
+FIXTURE = "tests/conftest.py::client"
+
+
+async def _seed(session) -> None:
+ """A base class with 2 callers and 60 subclasses, and a fixture with none.
+
+ 60 exceeds the 50-row call cap on purpose, and the subclasses outrank the
+ callers on confidence, so under the old shared cut the callers were not
+ merely reordered — they could not be served at all.
+ """
+ repo = (await session.execute(select(Repository))).scalars().first()
+ node_ids = [BASE, FIXTURE, "app/views.py::save", "app/views.py::delete"]
+ node_ids += [f"app/sub{i}.py::Sub{i}" for i in range(60)]
+ node_ids += [f"tests/test_{i}.py::test_{i}" for i in range(3)]
+ for node_id in node_ids:
+ session.add(
+ GraphNode(
+ id=f"rel_{node_id}",
+ repository_id=repo.id,
+ node_id=node_id,
+ node_type="symbol",
+ name=node_id.split("::")[-1],
+ file_path=node_id.split("::")[0],
+ kind="class" if "Sub" in node_id else "function",
+ start_line=1,
+ end_line=5,
+ created_at=_NOW,
+ )
+ )
+
+ def edge(source: str, target: str, edge_type: str, confidence: float) -> GraphEdge:
+ session.add(
+ GraphEdge(
+ id=f"rel_{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 i in range(60):
+ edge(f"app/sub{i}.py::Sub{i}", BASE, "extends", 0.99)
+ edge("app/views.py::save", BASE, "calls", 0.8)
+ edge("app/views.py::delete", BASE, "calls", 0.8)
+ for i in range(3):
+ edge(f"tests/test_{i}.py::test_{i}", FIXTURE, "framework_binds", 0.9)
+ await session.flush()
+
+
+async def _ctx(target: str) -> dict:
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context([target], include=["callers", "callees"], compact=False)
+ return result["targets"][target]
+
+
+async def test_callers_are_calls_only(setup_mcp, session):
+ await _seed(session)
+
+ t = await _ctx(BASE)
+
+ assert {c["edge_type"] for c in t["callers"]} == {"calls"}
+
+
+async def test_heritage_cannot_evict_the_real_callers(setup_mcp, session):
+ """60 higher-confidence subclasses used to consume the whole 50-row cut."""
+ await _seed(session)
+
+ t = await _ctx(BASE)
+
+ assert {c["name"] for c in t["callers"]} == {"save", "delete"}
+ assert not t.get("callers_truncated"), "2 of 2 callers is not a truncation"
+
+
+async def test_relations_name_each_kind_with_its_true_total(setup_mcp, session):
+ await _seed(session)
+
+ t = await _ctx(BASE)
+
+ by_type = {(r["direction"], r["edge_type"]): r for r in t["relations"]}
+ assert set(by_type) == {("in", "extends")}
+ extends = by_type[("in", "extends")]
+ assert extends["group"] == "heritage"
+ assert extends["total"] == 60, "the total must be the count, not the row cap"
+ assert 0 < len(extends["rows"]) <= 5
+ # The group names the edge type once. Repeating it per row was
+ # "method_implements" five times for nothing, on a token-budgeted payload.
+ assert all("edge_type" not in r for r in extends["rows"])
+ # Callers keep it: they have no group above them to carry it.
+ assert all(c["edge_type"] == "calls" for c in (await _ctx(BASE))["callers"])
+
+
+async def test_a_fixture_nothing_calls_reports_no_callers(setup_mcp, session):
+ """The 705-symbol case, and the sharpest one.
+
+ The old code answered this with rows of framework wiring under `callers`,
+ a `callers_total`, and a note instructing the agent to grep for a call
+ site that does not exist.
+ """
+ await _seed(session)
+
+ t = await _ctx(FIXTURE)
+
+ assert t["callers"] == []
+ assert "callers_total" not in t
+ assert "_callers_note" not in t
+
+ wiring = [r for r in t["relations"] if r["edge_type"] == "framework_binds"]
+ assert len(wiring) == 1
+ assert wiring[0]["group"] == "wiring"
+ assert wiring[0]["total"] == 3
+ # An empty `callers` beside a populated `relations` otherwise reads as a
+ # graph failure rather than as the answer.
+ assert "framework_binds" in t["_call_graph_note"]
+ assert "Nothing calls" in t["_call_graph_note"]
+
+
+async def test_degree_still_counts_every_relation_kind(setup_mcp, session):
+ """Degree is "how connected", so it stays over every use edge type even
+ though `callers` narrowed to calls."""
+ await _seed(session)
+
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context([BASE], include=["metrics"], compact=False)
+ metrics = result["targets"][BASE]["metrics"]
+
+ assert metrics["in_degree"] == 62 # 60 extends + 2 calls
+ assert metrics["out_degree"] == 0
diff --git a/tests/unit/server/mcp/test_symbol_callee_depth.py b/tests/unit/server/mcp/test_symbol_callee_depth.py
index 1b25802cd..dd212965e 100644
--- a/tests/unit/server/mcp/test_symbol_callee_depth.py
+++ b/tests/unit/server/mcp/test_symbol_callee_depth.py
@@ -246,3 +246,62 @@ async def test_excluded_callees_are_dropped(session, repository, chain) -> None:
root = await _root(session, repository.id)
block = await _expand_callees(session, repository.id, root, chain, 3, spec)
assert block is None
+
+
+async def test_a_base_class_is_not_served_as_a_callee(
+ session, repository, chain
+) -> None:
+ """The walk follows `calls`, not everything that reaches a symbol.
+
+ `_expand_callees` imports `_CALL_EDGE_TYPES` from `tool_context.enrichment`,
+ which used to be the whole of `SYMBOL_USE_EDGE_TYPES`. So a base class an
+ implementation extends, and a framework-bound fixture, were served as
+ "callees" **with their source bodies**, for up to three hops, against a
+ 24,000-char budget. Widening that constant again would silently regress
+ this, so it is pinned from this side too.
+ """
+ rid = repository.id
+ for i, (name, edge_type) in enumerate((("Base", "extends"), ("wire", "framework_binds"))):
+ sid = f"{_FILE}::{name}"
+ session.add(
+ WikiSymbol(
+ id=f"nc{i}",
+ repository_id=rid,
+ file_path=_FILE,
+ symbol_id=sid,
+ name=name,
+ qualified_name=f"chain.{name}",
+ kind="class",
+ signature=f"class {name}",
+ start_line=1,
+ end_line=2,
+ language="python",
+ )
+ )
+ session.add(
+ GraphNode(
+ id=f"nn{i}",
+ repository_id=rid,
+ node_id=sid,
+ node_type="symbol",
+ name=name,
+ file_path=_FILE,
+ language="python",
+ )
+ )
+ session.add(
+ GraphEdge(
+ id=f"ne{i}",
+ repository_id=rid,
+ source_node_id=f"{_FILE}::f0",
+ target_node_id=sid,
+ edge_type=edge_type,
+ confidence=0.99,
+ )
+ )
+ await session.flush()
+
+ root = await _root(session, rid)
+ block = await _expand_callees(session, rid, root, chain, 2, None)
+
+ assert [c["symbol_id"] for c in block["callees"]] == [f"{_FILE}::f1"]
diff --git a/tests/unit/server/test_callers_callees_relations.py b/tests/unit/server/test_callers_callees_relations.py
new file mode 100644
index 000000000..fcb069bbb
--- /dev/null
+++ b/tests/unit/server/test_callers_callees_relations.py
@@ -0,0 +1,164 @@
+"""`/callers-callees` must agree with `/api/symbols/detail`.
+
+The drawer this endpoint feeds and the routed symbol page render the same
+component, and they disagreed: the page named every relation kind after #1660
+while the drawer had only callers and callees. Both now go through
+`load_symbol_relations`, so a divergence is a shared-helper change rather than
+a drift between two hand-written loops.
+
+Also pinned here: `caller_count` is the true total. It was `len(callers)`,
+capped at `limit`, and `symbol-drawer-wrapper.tsx` renders it as
+`caller_total` — so a symbol with 275 callers reported 20.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphEdge, GraphNode, WikiSymbol, _new_uuid
+from tests.unit.server.conftest import create_test_repo
+
+BASE = "app/models.py::Model"
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ """A base class with 30 callers, 60 subclasses and one framework bind."""
+ async with get_session(session_factory) as session:
+ # `/api/symbols/detail` resolves the symbol row first, so the
+ # cross-surface comparison below needs one.
+ session.add(
+ WikiSymbol(
+ id=_new_uuid(),
+ repository_id=repo_id,
+ file_path="app/models.py",
+ symbol_id=BASE,
+ name="Model",
+ qualified_name="app.models.Model",
+ kind="class",
+ signature="class Model",
+ start_line=1,
+ end_line=10,
+ visibility="public",
+ language="python",
+ )
+ )
+ nodes = [BASE, "app/wire.py::container"]
+ nodes += [f"app/sub{i}.py::Sub{i}" for i in range(60)]
+ nodes += [f"app/call{i}.py::call_{i}" for i in range(30)]
+ for node_id in nodes:
+ session.add(
+ GraphNode(
+ id=_new_uuid(),
+ repository_id=repo_id,
+ node_id=node_id,
+ node_type="symbol",
+ name=node_id.split("::")[-1],
+ file_path=node_id.split("::")[0],
+ kind="class" if "Sub" in node_id else "function",
+ start_line=1,
+ )
+ )
+
+ def edge(source: str, edge_type: str, confidence: float) -> None:
+ session.add(
+ GraphEdge(
+ id=_new_uuid(),
+ repository_id=repo_id,
+ source_node_id=source,
+ target_node_id=BASE,
+ edge_type=edge_type,
+ confidence=confidence,
+ )
+ )
+
+ for i in range(60):
+ edge(f"app/sub{i}.py::Sub{i}", "extends", 0.99)
+ # 0.5 on purpose: this surface applies no confidence floor, while the
+ # MCP one filters below 0.7. So these 30 are 30 callers here and zero
+ # to an agent — a real remaining divergence (backlog B8), pinned here
+ # rather than left to be discovered as a bug.
+ for i in range(30):
+ edge(f"app/call{i}.py::call_{i}", "calls", 0.5)
+ edge("app/wire.py::container", "framework_binds", 0.9)
+
+
+async def _fetch(client: AsyncClient, repo_id: str, **params) -> dict:
+ resp = await client.get(
+ f"/api/graph/{repo_id}/callers-callees",
+ params={"symbol_id": BASE, **params},
+ )
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+async def test_callers_are_calls_only(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ body = await _fetch(client, repo["id"])
+
+ assert {r["edge_type"] for r in body["callers"]} == {"calls"}
+ assert body["callees"] == []
+
+
+async def test_caller_count_is_the_true_total_not_the_row_cap(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ body = await _fetch(client, repo["id"], limit=20)
+
+ assert len(body["callers"]) == 20, "rows honour the request limit"
+ assert body["caller_count"] == 30, "the count is the truth, not the page size"
+ assert body["truncated"] is True
+
+
+async def test_relations_carry_the_kinds_the_drawer_was_missing(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ body = await _fetch(client, repo["id"])
+
+ by_type = {(g["direction"], g["edge_type"]): g for g in body["relations"]}
+ assert set(by_type) == {("in", "extends"), ("in", "framework_binds")}
+ assert by_type[("in", "extends")]["group"] == "heritage"
+ assert by_type[("in", "extends")]["total"] == 60
+ assert by_type[("in", "framework_binds")]["group"] == "wiring"
+
+
+async def test_the_drawer_and_the_symbol_page_agree(client: AsyncClient, app) -> None:
+ """The whole point of sharing the helper, asserted rather than assumed."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ drawer = await _fetch(client, repo["id"], limit=40)
+ resp = await client.get(
+ "/api/symbols/detail", params={"repo_id": repo["id"], "symbol_id": BASE}
+ )
+ page = resp.json()["graph"]
+
+ assert drawer["caller_count"] == page["caller_total"]
+ assert [(g["direction"], g["edge_type"], g["total"]) for g in drawer["relations"]] == [
+ (g["direction"], g["edge_type"], g["total"]) for g in page["relations"]
+ ]
+
+
+async def test_edge_types_filters_relations(client: AsyncClient, app) -> None:
+ """The param no longer decides what counts as a caller."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ body = await _fetch(client, repo["id"], edge_types="extends")
+
+ assert {g["edge_type"] for g in body["relations"]} == {"extends"}
+ assert {r["edge_type"] for r in body["callers"]} == {"calls"}