Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(symbols): stop the symbol page calling a subclass a caller (#1660)
Raghav Chamadiya025632f5f26d
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex 03c7d7458..b2caec17b 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -899,6 +899,40 @@ async def get_node_degree_counts(}+async def get_node_degree_by_edge_type(+ session: AsyncSession,+ repository_id: str,+ node_id: str,+ *,+ edge_types: list[str] | None = None,+) -> dict[str, dict[str, int]]:+ """Return ``edge_type -> {in_degree, out_degree}`` for one node.++ The breakdown :func:`get_node_degree_counts` collapses. A surface that+ groups a node's neighbours by relation kind needs a total *per kind* — and+ getting there by calling the scalar version once per kind is a query per+ row of the answer.++ Edge types with no edges in either direction are absent rather than zero,+ so the caller can treat the mapping as "what this node actually has".+ """+ counts: dict[str, dict[str, int]] = {}+ for direction, column in (+ ("in_degree", GraphEdge.target_node_id),+ ("out_degree", GraphEdge.source_node_id),+ ):+ q = (+ select(GraphEdge.edge_type, func.count())+ .where(GraphEdge.repository_id == repository_id, column == node_id)+ .group_by(GraphEdge.edge_type)+ )+ if edge_types:+ q = q.where(GraphEdge.edge_type.in_(edge_types))+ for edge_type, n in await session.execute(q):+ counts.setdefault(edge_type, {"in_degree": 0, "out_degree": 0})[direction] = n+ return counts++async def get_node_degree_counts_bulk(session: AsyncSession,repository_id: str,diff --git a/packages/server/src/repowise/server/routers/graph/intelligence.py b/packages/server/src/repowise/server/routers/graph/intelligence.pyindex fc1eab06e..baa641ee2 100644--- a/packages/server/src/repowise/server/routers/graph/intelligence.py+++ b/packages/server/src/repowise/server/routers/graph/intelligence.py@@ -155,31 +155,8 @@ async def get_callers_callees(callees: list[CallerCalleeEntry] = []for e in edges:- is_caller = e.target_node_id == node.node_id- other_id = e.source_node_id if is_caller else e.target_node_id- other = node_map.get(other_id)-- entry = CallerCalleeEntry(- symbol_id=other_id,- # All three columns are nullable while the response fields are not,- # so each needs the value checked and not just the row: a null here- # failed validation for the whole call rather than degrading one- # row of twenty. `symbol_detail` already guarded name and file this- # way; this endpoint guarded none of them.- name=other.name- if other and other.name- else (other_id.split("::")[-1] if "::" in other_id else other_id),- kind=other.kind if other and other.kind else "unknown",- file=other.file_path- if other and other.file_path- else (other_id.split("::")[0] if "::" in other_id else other_id),- start_line=other.start_line if other else None,- edge_type=e.edge_type,- confidence=round(e.confidence or 0.0, 3),- resolution_origin=e.resolution_origin,- )-- if is_caller:+ 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)diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.pyindex 308c0dc60..ed14aeebd 100644--- a/packages/server/src/repowise/server/routers/symbols.py+++ b/packages/server/src/repowise/server/routers/symbols.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+from dataclasses import dataclass, fieldfrom typing import Literalfrom fastapi import APIRouter, Depends, HTTPException, Query@@ -22,6 +23,11 @@ from repowise.core.persistence.models import (from repowise.core.persistence.sql import LIKE_ESCAPE, escape_likefrom repowise.server.deps import get_db_session, verify_api_keyfrom 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,@@ -396,54 +402,8 @@ async def symbol_detail(# comment true: unfiltered, a symbol's inbound containment edge — from its# own declaring file or class, which 34,570 of 34,808 symbols on this repo# have — was served as a caller.- callers: list[dict] = []- callees: list[dict] = []node = await crud.get_graph_node(session, repo_id, symbol_id)- if node is not None:- edges = await crud.get_graph_edges_for_node(- session,- repo_id,- symbol_id,- direction="both",- edge_types=sorted(SYMBOL_USE_EDGE_TYPES),- limit=40,- )- other_ids = {- e.source_node_id if e.source_node_id != symbol_id else e.target_node_id for e in edges- }- node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))- for e in edges:- inbound = e.target_node_id == symbol_id- other_id = e.source_node_id if inbound else e.target_node_id- other = node_map.get(other_id)- entry = {- "symbol_id": other_id,- "name": other.name- if other and other.name- else (other_id.split("::")[-1] if "::" in other_id else other_id),- "kind": other.kind if other and other.kind else "unknown",- "file": other.file_path- if other and other.file_path- else (other_id.split("::")[0] if "::" in other_id else other_id),- "start_line": other.start_line if other else None,- "edge_type": e.edge_type,- "confidence": round(e.confidence or 0.0, 3),- "resolution_origin": e.resolution_origin,- }- (callers if inbound else callees).append(entry)- callers.sort(key=lambda x: (-x["confidence"], x["name"]))- callees.sort(key=lambda x: (-x["confidence"], x["name"]))-- # Scoped to the same edges as `callers`/`callees`, which sit beside these- # two in one `graph` object. Unscoped, every symbol's in-degree carried the- # containment edge from its own declaring file or class.- degrees = (- await crud.get_node_degree_counts(- session, repo_id, symbol_id, edge_types=sorted(SYMBOL_USE_EDGE_TYPES)- )- if node is not None- else {"in_degree": 0, "out_degree": 0}- )+ relations = await _symbol_relations(session, repo_id, symbol_id, present=node is not None)governing = [{"id": d.id, "title": d.title, "status": d.status}@@ -465,10 +425,20 @@ async def symbol_detail("symbol": symbol.model_dump(mode="json"),"graph": {"pagerank": round((node.pagerank if node else 0.0) or 0.0, 6),- "in_degree": degrees["in_degree"],- "out_degree": degrees["out_degree"],- "callers": callers,- "callees": callees,+ # Degree across every use edge type, so it stays a graph metric+ # rather than a second, disagreeing caller count. Summed from the+ # counts the rows were cut from — it is NOT `caller_total`, which+ # is calls only, and a surface wanting "N callers" wants that one.+ "in_degree": relations.in_degree,+ "out_degree": relations.out_degree,+ # Calls only. Every other relation kind is carried by `relations`+ # under its own name, so a subclass is no longer served as a caller.+ "callers": [r.model_dump(mode="json") for r in relations.callers],+ "callees": [r.model_dump(mode="json") for r in relations.callees],+ # True counts. `len(callers)` is the cap, not the answer.+ "caller_total": relations.caller_total,+ "callee_total": relations.callee_total,+ "relations": [g.model_dump(mode="json") for g in relations.groups],},"governing_decisions": governing,"file_context": file_context,@@ -483,6 +453,132 @@ 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.pyindex a070ab36f..2ae2e1a5a 100644--- a/packages/server/src/repowise/server/schemas/intelligence.py+++ b/packages/server/src/repowise/server/schemas/intelligence.py@@ -3,8 +3,14 @@ node metrics and execution flows)."""from __future__ import annotations+from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, Literal+from pydantic import BaseModel+if TYPE_CHECKING: # pragma: no cover - typing only+ from repowise.core.persistence.models import GraphEdge, GraphNode+class SymbolNodeSummary(BaseModel):symbol_id: str@@ -26,6 +32,46 @@ class CallerCalleeEntry(BaseModel):# None on an index built before origins were stamped.resolution_origin: str | None = None+ @classmethod+ def from_edge(+ cls,+ edge: GraphEdge,+ *,+ node_id: str,+ node_map: Mapping[str, Any],+ ) -> CallerCalleeEntry:+ """Build the row for the endpoint *opposite* ``node_id`` on ``edge``.++ The one place a *response-model* row is built from an edge. It used to+ be two: `symbol_detail` and `get_callers_callees` each built the same+ eight fields, and they drifted — the null guards below were added to+ the first and had to be re-added to the second after a null `name`+ failed response validation for a whole call instead of degrading one+ row. All three columns are nullable while the response fields are not,+ so each needs the *value* checked, not just the row.++ `mcp_server/tool_context/enrichment.py` builds a third, deliberately+ different shape for the agent surface (definition line, a confidence+ floor, `via` rather than `resolution_origin`). It is not a copy of+ this and is not folded in here.+ """+ other_id = edge.source_node_id if edge.target_node_id == node_id else edge.target_node_id+ other: GraphNode | None = node_map.get(other_id)+ return cls(+ symbol_id=other_id,+ name=other.name+ if other and other.name+ else (other_id.split("::")[-1] if "::" in other_id else other_id),+ kind=other.kind if other and other.kind else "unknown",+ file=other.file_path+ if other and other.file_path+ else (other_id.split("::")[0] if "::" in other_id else other_id),+ start_line=other.start_line if other else None,+ edge_type=edge.edge_type,+ confidence=round(edge.confidence or 0.0, 3),+ resolution_origin=edge.resolution_origin,+ )+class CallersCalleesResponse(BaseModel):symbol_id: str@@ -37,6 +83,49 @@ class CallersCalleesResponse(BaseModel):truncated: bool+# ---------------------------------------------------------------------------+# Symbol relation vocabulary+# ---------------------------------------------------------------------------++# `SYMBOL_USE_EDGE_TYPES` answers "does something reach this symbol", which is+# the right question for reachability and the wrong one for a reader: a+# subclass reaches its base without ever calling it. Partitioning by what the+# relation *is* lets each kind be counted and named separately, so a symbol+# with 1,516 subclasses and 8 callers no longer serves 39 subclasses and one+# caller under a single "Called by" heading.+#+# `SYMBOL_RELATION_GROUPS` must partition `SYMBOL_USE_EDGE_TYPES` exactly;+# `test_symbol_relations.py` fails if an edge type is added to one and not the+# other, so a new relation kind cannot land unnamed.+SYMBOL_RELATION_GROUPS: dict[str, frozenset[str]] = {+ "call": frozenset({"calls"}),+ "heritage": frozenset({"extends", "implements", "method_implements", "dispatches_to"}),+ "wiring": frozenset({"framework_binds"}),+ "reference": frozenset({"reads", "references"}),+}++#: Reverse index, so a fetched edge can name its own group without a scan.+SYMBOL_RELATION_GROUP_OF: dict[str, str] = {+ edge_type: group+ for group, edge_types in SYMBOL_RELATION_GROUPS.items()+ for edge_type in edge_types+}+++class SymbolRelationGroup(BaseModel):+ """One relation kind, on one side of a symbol, with its true total.++ `total` is counted unbounded while `rows` is capped, so a surface can say+ "12 of 1,516" instead of silently rendering the cap as the count.+ """++ direction: Literal["in", "out"]+ edge_type: str+ group: str+ total: int+ rows: list[CallerCalleeEntry]++class CommunityMember(BaseModel):path: strpagerank: floatdiff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.tsindex 84237231b..a33beb72e 100644--- a/packages/types/src/symbols.ts+++ b/packages/types/src/symbols.ts@@ -91,12 +91,44 @@ export interface SymbolCallEntry {resolution_origin?: ResolutionOriginWire | null;}+/**+ * Which side of the symbol a relation sits on. `in` means the other symbol+ * reaches this one.+ */+export type SymbolRelationDirection = "in" | "out";++/**+ * One relation kind on one side of a symbol, with the count it was cut from.+ *+ * `total` is counted unbounded while `rows` is capped, so a surface reports+ * "10 of 1,516" rather than rendering the cap as if it were the answer.+ * `group` partitions `edge_type` into the four families the engine's+ * `SYMBOL_USE_EDGE_TYPES` covers; `symbol-relations.ts` in `@repowise-dev/ui`+ * is the only place either becomes English.+ */+export interface SymbolRelationGroup<Row = SymbolCallEntry> {+ direction: SymbolRelationDirection;+ edge_type: string;+ group: "heritage" | "wiring" | "reference";+ total: number;+ rows: Row[];+}+export interface SymbolDetailGraph {pagerank: number;in_degree: number;out_degree: number;+ /** `calls` edges only. Every other relation kind is in `relations`. */callers: SymbolCallEntry[];callees: SymbolCallEntry[];+ /** True `calls` counts. `callers.length` is the row cap, not the count.+ * Absent on a backend that predates the split, so a surface must fall back+ * to the array length rather than rendering `undefined`. */+ caller_total?: number;+ callee_total?: number;+ /** Heritage, framework wiring and references, each named and counted+ * separately. Absent on an older backend. */+ relations?: SymbolRelationGroup[];}export interface SymbolFileContext {@@ -141,8 +173,12 @@ export interface SymbolBodyCall {export interface SymbolBodyGraph {in_degree: number;out_degree: number;+ /** `calls` edges only — see `SymbolDetailGraph.callers`. */callers: SymbolBodyCall[];callees: SymbolBodyCall[];+ caller_total?: number;+ callee_total?: number;+ relations?: SymbolRelationGroup<SymbolBodyCall>[];pagerank_percentile?: number | null;betweenness_percentile?: number | null;community_label?: string | null;diff --git a/packages/ui/__tests__/symbols/symbol-relations.test.tsx b/packages/ui/__tests__/symbols/symbol-relations.test.tsxnew file mode 100644index 000000000..b6766e06f--- /dev/null+++ b/packages/ui/__tests__/symbols/symbol-relations.test.tsx@@ -0,0 +1,231 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { SymbolCallGraph } from "../../src/symbols/symbol-call-graph.js";+import { SymbolPage } from "../../src/symbols/symbol-page.js";+import type {+ SymbolBodyCall,+ SymbolDetailResponse,+ SymbolRelationGroup,+} from "@repowise-dev/types/symbols";++const call = (name: string, edge_type = "calls"): SymbolBodyCall => ({+ symbol_id: `src/${name}.py::${name}`,+ name,+ file: `src/${name}.py`,+ edge_type,+ confidence: 0.9,+ resolution_origin: null,+});++const group = (+ overrides: Partial<SymbolRelationGroup<SymbolBodyCall>>,+): SymbolRelationGroup<SymbolBodyCall> => ({+ direction: "in",+ edge_type: "extends",+ group: "heritage",+ total: 1516,+ rows: [call("UserModel", "extends")],+ ...overrides,+});++const routeData = (+ graph: Partial<SymbolDetailResponse["graph"]> = {},+): SymbolDetailResponse => ({+ symbol: {+ id: "s1",+ repository_id: "r",+ file_path: "django/db/models/base.py",+ symbol_id: "django/db/models/base.py::Model",+ name: "Model",+ qualified_name: "Model",+ kind: "class",+ signature: "class Model",+ start_line: 10,+ end_line: 15,+ docstring: null,+ visibility: "public",+ is_async: false,+ complexity_estimate: 3,+ language: "python",+ parent_name: null,+ file_is_hotspot: false,+ },+ graph: {+ pagerank: 0,+ in_degree: 0,+ out_degree: 0,+ callers: [],+ callees: [],+ ...graph,+ },+ governing_decisions: [],+ file_context: {+ file_path: "django/db/models/base.py",+ health_score: 70,+ is_hotspot: false,+ primary_owner: "Ada",+ language: "python",+ },+});++describe("symbol relations", () => {+ it("reports the true caller count, not the row cap", () => {+ // The defect this pins: the server caps rows at 40 and the heading read+ // `Called by (40)` over a symbol with 1,524 inbound edges.+ render(+ <SymbolCallGraph+ centerName="Model"+ callers={[call("save"), call("delete")]}+ callees={[]}+ callerTotal={8}+ />,+ );+ expect(screen.getByText("(8)")).toBeInTheDocument();+ expect(screen.getByText("+6 more")).toBeInTheDocument();+ });++ it("falls back to the row count when the backend sends no total", () => {+ render(+ <SymbolCallGraph centerName="Model" callers={[call("save")]} callees={[]} />,+ );+ expect(screen.getByText("(1)")).toBeInTheDocument();+ expect(screen.queryByText(/more$/)).not.toBeInTheDocument();+ });++ it("names a subclass as extending, never as calling", () => {+ render(+ <SymbolCallGraph+ centerName="Model"+ callers={[call("save")]}+ callees={[]}+ callerTotal={8}+ relations={[group({})]}+ />,+ );+ expect(screen.getByText("Extended by")).toBeInTheDocument();+ expect(screen.getByText("(1,516)")).toBeInTheDocument();+ // The subclass must not appear under the call column's heading.+ expect(screen.getByText("Called by")).toBeInTheDocument();+ expect(screen.getByText("(8)")).toBeInTheDocument();+ });++ it("labels the method case differently from the class case", () => {+ // The wording half of the fix: "Extended by" is class-heritage phrasing+ // and reads as nonsense on a base method answered by implementations.+ render(+ <SymbolCallGraph+ centerName="save"+ callers={[]}+ callees={[]}+ relations={[+ group({ edge_type: "method_implements", total: 4 }),+ group({ edge_type: "implements", direction: "out", total: 1 }),+ ]}+ />,+ );+ expect(screen.getByText("Implementations")).toBeInTheDocument();+ expect(screen.getByText("Implements")).toBeInTheDocument();+ expect(screen.queryByText("Extended by")).not.toBeInTheDocument();+ });++ it("names implementations on the side the edge actually points", () => {+ // `dispatches_to` runs base -> implementation, the opposite of+ // `method_implements`. Labelling both the same way put "Implementations"+ // on the implementation instead of the base, which is the reverse the+ // gate forbids. Verified against a live index: `BaseProvider.generate`+ // carries its dispatch edges outbound.+ render(+ <SymbolCallGraph+ centerName="generate"+ callers={[]}+ callees={[]}+ relations={[+ group({ edge_type: "dispatches_to", direction: "out", total: 19 }),+ group({ edge_type: "method_implements", direction: "in", total: 19 }),+ ]}+ />,+ );+ expect(screen.getAllByText("Implementations")).toHaveLength(2);+ expect(screen.queryByText("Dispatches to")).not.toBeInTheDocument();+ });++ it("explains a relation group once, not once per verb", () => {+ render(+ <SymbolCallGraph+ centerName="Model"+ callers={[]}+ callees={[]}+ relations={[+ group({ edge_type: "extends", total: 2 }),+ group({ edge_type: "implements", total: 1 }),+ ]}+ />,+ );+ expect(screen.getAllByText(/Not a call site/)).toHaveLength(1);+ });++ it("names framework wiring rather than calling it a call", () => {+ render(+ <SymbolCallGraph+ centerName="Repo"+ callers={[]}+ callees={[]}+ relations={[+ group({ edge_type: "framework_binds", group: "wiring", total: 3 }),+ ]}+ />,+ );+ expect(screen.getByText("Wired into")).toBeInTheDocument();+ expect(screen.getByText(/no call site exists/)).toBeInTheDocument();+ });++ it("renders relations end to end from the route payload", () => {+ // The section has been dead for its whole life because nothing asserted it+ // renders. This is the assertion that fails if the endpoint stops sending+ // the key or the normaliser stops forwarding it.+ render(+ <SymbolPage+ data={routeData({+ callers: [+ {+ symbol_id: "django/db/models/query.py::get",+ name: "get",+ kind: "function",+ file: "django/db/models/query.py",+ start_line: 4,+ edge_type: "calls",+ confidence: 0.9,+ resolution_origin: null,+ },+ ],+ caller_total: 8,+ relations: [+ {+ direction: "in",+ edge_type: "extends",+ group: "heritage",+ total: 1516,+ rows: [+ {+ symbol_id: "app/models.py::User",+ name: "User",+ kind: "class",+ file: "app/models.py",+ start_line: 1,+ edge_type: "extends",+ confidence: 0.9,+ resolution_origin: null,+ },+ ],+ },+ ],+ })}+ repoId="r"+ />,+ );+ expect(screen.getByText("Extended by")).toBeInTheDocument();+ expect(screen.getByText("User")).toBeInTheDocument();+ expect(screen.getByText("(1,516)")).toBeInTheDocument();+ expect(screen.getByText("(8)")).toBeInTheDocument();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex ef1f41cd3..2c682ae6e 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -48,6 +48,7 @@"./docs/reader-persona": "./src/docs/reader-persona.ts","./docs/*": "./src/docs/*.tsx","./symbols": "./src/symbols/index.ts",+ "./symbols/normalize-calls": "./src/symbols/normalize-calls.ts","./symbols/*": "./src/symbols/*.tsx","./owners": "./src/owners/index.ts","./owners/*": "./src/owners/*.tsx",diff --git a/packages/ui/src/graph/symbol-relations.ts b/packages/ui/src/graph/symbol-relations.tsnew file mode 100644index 000000000..002301eba--- /dev/null+++ b/packages/ui/src/graph/symbol-relations.ts@@ -0,0 +1,74 @@+import type {+ SymbolRelationDirection,+ SymbolRelationGroup,+} from "@repowise-dev/types/symbols";++/**+ * The one place a symbol-graph `edge_type` becomes a heading a reader sees.+ *+ * The engine's `SYMBOL_USE_EDGE_TYPES` answers "does something reach this+ * symbol", which is the right question for reachability and the wrong one for+ * a page: a subclass reaches its base without calling it. Rendering all seven+ * kinds under "Called by" told a reader that 1,516 Django models call+ * `Model` — and, because the cut was ranked by confidence under one shared+ * cap, hid the 8 symbols that actually do.+ *+ * Kept beside `edge-provenance.ts` for the same reason: a closed vocabulary+ * crossing the language boundary needs exactly one translation, and a Python+ * test pins these keys against the set they are copied from.+ */++/** Heading per edge type, per side. Both halves of a relation are named, since+ * "Extends" and "Extended by" are different facts about the same edge. */+const RELATION_LABELS: Record<string, Record<SymbolRelationDirection, string>> = {+ // Class heritage. The inbound side is the one a reader arrives for: it+ // answers "who builds on this".+ extends: { in: "Extended by", out: "Extends" },+ implements: { in: "Implemented by", out: "Implements" },+ // Method heritage. A base method answered by four implementations wants+ // "Implementations", not "Extended by" — the class phrasing reads as+ // nonsense on a method and is the wording half of this fix.+ //+ // The two point opposite ways and the labels have to follow, not read+ // alike. `method_implements` runs implementation -> base, the direction the+ // source declares. `dispatches_to` runs base -> implementation, because it+ // exists to make an implementation reachable from a call landing on the+ // base; verified on a live index, where `BaseProvider.generate` carries its+ // 19 `dispatches_to` edges outbound.+ method_implements: { in: "Implementations", out: "Implements" },+ dispatches_to: { in: "Implements", out: "Implementations" },+ // Framework wiring: the container injects this, so no parser sees a call+ // site. Runs consumer -> provider, so a fixture's inbound edges are the+ // tests it is wired into (388 of them for `client` on this repo).+ framework_binds: { in: "Wired into", out: "Wired to" },+ reads: { in: "Read by", out: "Reads" },+ references: { in: "Referenced by", out: "References" },+};++/** One sentence per group, shown once beneath its heading. Explains why a+ * relation is not a call, which is the question the grouping raises. */+const GROUP_HINTS: Record<SymbolRelationGroup["group"], string> = {+ heritage: "Inherits or implements. Not a call site.",+ wiring: "Connected by a framework, so no call site exists in the source.",+ reference: "Named without being called, such as a handler in a dispatch table.",+};++export function relationLabel(+ edgeType: string,+ direction: SymbolRelationDirection,+): string {+ const entry = RELATION_LABELS[edgeType];+ if (entry) return entry[direction];+ // An edge type the engine gained and this table has not. Say the raw verb+ // rather than dropping the section: an unnamed relation is still better+ // than one silently filed under "Called by", which is the bug being fixed.+ return direction === "in" ? `${edgeType} (inbound)` : edgeType;+}++export function relationHint(group: SymbolRelationGroup["group"]): string | undefined {+ return GROUP_HINTS[group];+}++/** Edge types this module can name, for the cross-language pin test. */+export const KNOWN_RELATION_EDGE_TYPES: readonly string[] =+ Object.keys(RELATION_LABELS).sort();diff --git a/packages/ui/src/symbols/index.ts b/packages/ui/src/symbols/index.tsindex 20eeb6617..e76e158cb 100644--- a/packages/ui/src/symbols/index.ts+++ b/packages/ui/src/symbols/index.ts@@ -4,4 +4,5 @@ export * from "./symbol-table";export * from "./symbol-drawer";export * from "./symbol-detail-body";export * from "./symbol-call-graph";+export * from "./normalize-calls";export * from "./top-symbols-row";diff --git a/packages/ui/src/symbols/normalize-calls.ts b/packages/ui/src/symbols/normalize-calls.tsnew file mode 100644index 000000000..7df71d132--- /dev/null+++ b/packages/ui/src/symbols/normalize-calls.ts@@ -0,0 +1,45 @@+import type {+ SymbolBodyCall,+ SymbolRelationGroup,+} from "@repowise-dev/types/symbols";++/**+ * The wire shape shared by every endpoint that returns a graph edge as a row:+ * `/symbols/detail`'s `SymbolCallEntry` and `/callers-callees`'s+ * `CallerCalleeEntry` are the same eight fields, built by one server-side+ * helper. Typed structurally so both satisfy it without either importing the+ * other's alias.+ */+type CallEntryWire = Pick<SymbolBodyCall, "symbol_id" | "name" | "file" | "edge_type"> & {+ confidence?: number | null;+ resolution_origin?: SymbolBodyCall["resolution_origin"];+};++/**+ * Map one wire row onto the body's row.+ *+ * Extracted because the route normaliser and the drawer's web wrapper each+ * carried this map, field for field, for two surfaces that render the same+ * component — the duplication that let the two disagree about which edge+ * kinds a "caller" may be.+ */+export function toSymbolBodyCall(c: CallEntryWire): SymbolBodyCall {+ return {+ symbol_id: c.symbol_id,+ name: c.name,+ file: c.file,+ edge_type: c.edge_type,+ // Normalised to null rather than left undefined: `exactOptionalPropertyTypes`+ // treats an explicit undefined as a different type from an absent key.+ confidence: c.confidence ?? null,+ resolution_origin: c.resolution_origin ?? null,+ };+}++/** Map the relation groups, preserving server order (inbound first, then by+ * descending total). Absent on a backend that predates the split. */+export function toSymbolBodyRelations(+ relations: SymbolRelationGroup<CallEntryWire>[] | undefined,+): SymbolRelationGroup<SymbolBodyCall>[] | undefined {+ return relations?.map((r) => ({ ...r, rows: r.rows.map(toSymbolBodyCall) }));+}diff --git a/packages/ui/src/symbols/symbol-call-graph.tsx b/packages/ui/src/symbols/symbol-call-graph.tsxindex 81558db6b..37a129f8e 100644--- a/packages/ui/src/symbols/symbol-call-graph.tsx+++ b/packages/ui/src/symbols/symbol-call-graph.tsx@@ -1,20 +1,41 @@"use client";+import { memo, useMemo } from "react";import { ArrowRight } from "lucide-react";-import type { SymbolBodyCall } from "@repowise-dev/types/symbols";+import type {+ SymbolBodyCall,+ SymbolRelationGroup,+} from "@repowise-dev/types/symbols";import { truncatePath } from "../lib/format";import { originDescriptor } from "../graph/edge-provenance";+import { relationHint, relationLabel } from "../graph/symbol-relations";interface SymbolCallGraphProps {centerName: string;+ /** `calls` edges only. Heritage and wiring arrive in `relations`. */callers: SymbolBodyCall[];callees: SymbolBodyCall[];+ /** True edge counts. `callers.length` is the server's row cap, so falling+ * back to it is what made "Called by (40)" appear over 1,524 edges. */+ callerTotal?: number;+ calleeTotal?: number;+ relations?: SymbolRelationGroup<SymbolBodyCall>[];symbolHref?: (id: string) => string;/** Cap per column so the mini-graph stays compact. */limit?: number;}-function CallNode({+/**+ * Memoised because the drawer's wrapper streams five independent SWR feeds+ * into this subtree, so every feed that resolves re-renders every row —+ * rule 16's shape with a fetch waterfall in place of a token stream.+ *+ * This only bites if the caller keeps the row objects referentially stable.+ * `symbol-drawer-wrapper.tsx` memoises them on their own feed for exactly+ * that reason; building them inside a memo that also depends on git or+ * co-change data re-mints every row and the boundary here does nothing.+ */+const CallNode = memo(function CallNode({entry,symbolHref,}: {@@ -49,68 +70,143 @@ function CallNode({{inner}</a>);+});++function SectionLabel({ children }: { children: React.ReactNode }) {+ return (+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {children}+ </p>+ );+}++/**+ * A labelled list of edges with the count it was cut from. The count is the+ * server's unbounded total, so the footer states a real remainder instead of+ * subtracting one cap from another.+ */+function RelationList({+ label,+ total,+ rows,+ limit,+ hint,+ symbolHref,+}: {+ label: string;+ total: number;+ rows: SymbolBodyCall[];+ limit: number;+ hint?: string | undefined;+ symbolHref?: ((id: string) => string) | undefined;+}) {+ const shown = rows.slice(0, limit);+ const remainder = total - shown.length;+ return (+ // `min-w-0`: a grid track sizes to its content, so a long single-token+ // symbol name defeats the row's `truncate` and widens the page.+ <div className="min-w-0 space-y-1.5">+ <SectionLabel>+ {label} <span className="tabular-nums">({total.toLocaleString()})</span>+ </SectionLabel>+ {hint && (+ <p className="text-[10px] leading-snug text-[var(--color-text-tertiary)]">{hint}</p>+ )}+ {shown.length === 0 ? (+ <p className="text-xs italic text-[var(--color-text-tertiary)]">None</p>+ ) : (+ shown.map((c) => (+ <CallNode+ key={`${c.symbol_id}-${c.edge_type}`}+ entry={c}+ {...(symbolHref ? { symbolHref } : {})}+ />+ ))+ )}+ {remainder > 0 && (+ <p className="text-[10px] tabular-nums text-[var(--color-text-tertiary)]">+ +{remainder.toLocaleString()} more+ </p>+ )}+ </div>+ );}/*** A compact centered call-graph: callers feed into the centered symbol, which- * feeds the callees. Replaces the two flat caller/callee lists with the graph- * shape the data actually describes. Empty columns read as "no edges".+ * feeds the callees. Empty columns read as "no edges".+ *+ * Only `calls` edges reach those two columns. Every other relation the engine+ * resolves — heritage, framework wiring, bare references — is listed beneath+ * under its own verb, because serving them as callers was both wrong and+ * lossy: one confidence-ranked cap across all seven kinds meant `TestCase`,+ * with 3 callers and 868 subclasses, showed 40 subclasses and none of its+ * callers.*/export function SymbolCallGraph({centerName,callers,callees,+ callerTotal,+ calleeTotal,+ relations,symbolHref,limit = 6,}: SymbolCallGraphProps) {- const callersShown = callers.slice(0, limit);- const calleesShown = callees.slice(0, limit);+ // One hint per group, on its first section, so a run of heritage rows is+ // explained once rather than per verb — rule 10 on markers every row carries.+ const sections = useMemo(() => {+ const seen = new Set<string>();+ return (relations ?? []).map((rel) => {+ const first = !seen.has(rel.group);+ seen.add(rel.group);+ return { rel, hint: first ? relationHint(rel.group) : undefined };+ });+ }, [relations]);return (- <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3">- <div className="space-y-1.5">- <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Called by ({callers.length})- </p>- {callersShown.length === 0 ? (- <p className="text-xs italic text-[var(--color-text-tertiary)]">None</p>- ) : (- callersShown.map((c) => (- <CallNode key={`${c.symbol_id}-${c.edge_type}`} entry={c} {...(symbolHref ? { symbolHref } : {})} />- ))- )}- {callers.length > limit && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">- +{callers.length - limit} more- </p>- )}- </div>+ <div className="space-y-4">+ <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3">+ <RelationList+ label="Called by"+ total={callerTotal ?? callers.length}+ rows={callers}+ limit={limit}+ symbolHref={symbolHref}+ />- <div className="flex flex-col items-center gap-1">- <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />- <div className="max-w-[140px] truncate rounded-md border border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/10 px-3 py-2 text-center font-mono text-xs font-semibold text-[var(--color-text-primary)]">- {centerName}+ <div className="flex flex-col items-center gap-1">+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ <div className="max-w-[140px] truncate rounded-md border border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/10 px-3 py-2 text-center font-mono text-xs font-semibold text-[var(--color-text-primary)]">+ {centerName}+ </div>+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" /></div>- <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />- </div>- <div className="space-y-1.5">- <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Calls ({callees.length})- </p>- {calleesShown.length === 0 ? (- <p className="text-xs italic text-[var(--color-text-tertiary)]">None</p>- ) : (- calleesShown.map((c) => (- <CallNode key={`${c.symbol_id}-${c.edge_type}`} entry={c} {...(symbolHref ? { symbolHref } : {})} />- ))- )}- {callees.length > limit && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">- +{callees.length - limit} more- </p>- )}+ <RelationList+ label="Calls"+ total={calleeTotal ?? callees.length}+ rows={callees}+ limit={limit}+ symbolHref={symbolHref}+ /></div>++ {sections.length > 0 && (+ <div className="grid gap-4 border-t border-[var(--color-border-default)] pt-3 sm:grid-cols-2">+ {sections.map(({ rel, hint }) => (+ <RelationList+ key={`${rel.direction}-${rel.edge_type}`}+ label={relationLabel(rel.edge_type, rel.direction)}+ total={rel.total}+ rows={rel.rows}+ limit={limit}+ hint={hint}+ symbolHref={symbolHref}+ />+ ))}+ </div>+ )}</div>);}diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsxindex b57257b1b..1bb138faf 100644--- a/packages/ui/src/symbols/symbol-detail-body.tsx+++ b/packages/ui/src/symbols/symbol-detail-body.tsx@@ -191,6 +191,9 @@ export function SymbolDetailBody({centerName={id.name}callers={graph.callers}callees={graph.callees}+ {...(graph.caller_total != null ? { callerTotal: graph.caller_total } : {})}+ {...(graph.callee_total != null ? { calleeTotal: graph.callee_total } : {})}+ {...(graph.relations ? { relations: graph.relations } : {})}{...(symbolHref ? { symbolHref } : {})}/>)}diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsxindex 28c29af84..c2776e022 100644--- a/packages/ui/src/symbols/symbol-page.tsx+++ b/packages/ui/src/symbols/symbol-page.tsx@@ -9,6 +9,7 @@ import type {} from "@repowise-dev/types/symbols";import { FixHistoryBadge, SYMBOL_FIX_TITLE } from "../git/fix-history-badge";import { SymbolDetailBody } from "./symbol-detail-body";+import { toSymbolBodyCall, toSymbolBodyRelations } from "./normalize-calls";export interface SymbolPageProps {data: SymbolDetailResponse;@@ -68,22 +69,13 @@ export function normalizeSymbolDetailResponse(graph: {in_degree: data.graph.in_degree,out_degree: data.graph.out_degree,- callers: data.graph.callers.map((c) => ({- symbol_id: c.symbol_id,- name: c.name,- file: c.file,- edge_type: c.edge_type,- confidence: c.confidence,- resolution_origin: c.resolution_origin ?? null,- })),- callees: data.graph.callees.map((c) => ({- symbol_id: c.symbol_id,- name: c.name,- file: c.file,- edge_type: c.edge_type,- confidence: c.confidence,- resolution_origin: c.resolution_origin ?? null,- })),+ callers: data.graph.callers.map(toSymbolBodyCall),+ callees: data.graph.callees.map(toSymbolBodyCall),+ caller_total: data.graph.caller_total ?? data.graph.callers.length,+ callee_total: data.graph.callee_total ?? data.graph.callees.length,+ ...(data.graph.relations+ ? { relations: toSymbolBodyRelations(data.graph.relations) ?? [] }+ : {}),},governing_decisions: data.governing_decisions,file_context: {diff --git a/packages/vscode/src/features/hovers.ts b/packages/vscode/src/features/hovers.tsindex baaa0770a..3dfb9dad5 100644--- a/packages/vscode/src/features/hovers.ts+++ b/packages/vscode/src/features/hovers.ts@@ -201,8 +201,11 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {md.isTrusted = { enabledCommands: [Commands.showFileHealth] };if (detail) {md.appendMarkdown(`**${match.name}** · ${detail.symbol.kind}\n\n`);- const callers = detail.graph.in_degree;- const callees = detail.graph.out_degree;+ // Degree counts every relation kind, so it reports subclasses and+ // framework wiring as callers. `caller_total` is calls only; fall back+ // to degree on an index served by an older backend.+ const callers = detail.graph.caller_total ?? detail.graph.in_degree;+ const callees = detail.graph.callee_total ?? detail.graph.out_degree;md.appendMarkdown(`${callers} callers · ${callees} callees\n\n`);const owner = detail.file_context?.primary_owner;if (owner) {diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsxindex 6a1aacc62..a46300d9c 100644--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx@@ -4,6 +4,7 @@ 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 {fileEntityPath,symbolEntityPath,@@ -67,6 +68,23 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {);}, [deadFindings, symbol]);+ // Keyed on `callData` alone so the row objects keep their identity when any+ // of the other four feeds resolves. Folded into the `data` memo below they+ // were re-minted on every one of them, which defeated `CallNode`'s memo+ // 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: (callData?.callers ?? []).map(toSymbolBodyCall),+ callees: (callData?.callees ?? []).map(toSymbolBodyCall),+ caller_total: callData?.caller_count ?? 0,+ callee_total: callData?.callee_count ?? 0,+ }),+ [callData],+ );+const data: SymbolDetailData | null = useMemo(() => {if (!symbol) return null;return {@@ -99,22 +117,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {graph: {in_degree: metrics?.in_degree ?? callData?.caller_count ?? 0,out_degree: metrics?.out_degree ?? callData?.callee_count ?? 0,- callers: (callData?.callers ?? []).map((c) => ({- symbol_id: c.symbol_id,- name: c.name,- file: c.file,- edge_type: c.edge_type,- confidence: c.confidence,- resolution_origin: c.resolution_origin ?? null,- })),- callees: (callData?.callees ?? []).map((c) => ({- symbol_id: c.symbol_id,- name: c.name,- file: c.file,- edge_type: c.edge_type,- confidence: c.confidence,- resolution_origin: c.resolution_origin ?? null,- })),+ ...calls,pagerank_percentile: metrics?.pagerank_percentile ?? null,betweenness_percentile: metrics?.betweenness_percentile ?? null,community_label: metrics?.community_label ?? null,@@ -145,7 +148,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {})),file_context: { language: symbol.language },};- }, [symbol, metrics, callData, git, coChangePayload, overlappingDead]);+ }, [symbol, metrics, calls, callData, git, coChangePayload, overlappingDead]);return (<SymbolDrawerdiff --git a/tests/unit/server/test_symbol_detail_relations.py b/tests/unit/server/test_symbol_detail_relations.pynew file mode 100644index 000000000..ac9f961ff--- /dev/null+++ b/tests/unit/server/test_symbol_detail_relations.py@@ -0,0 +1,179 @@+"""`/api/symbols/detail` must name each relation, not flatten them into calls.++The endpoint served the whole of ``SYMBOL_USE_EDGE_TYPES`` under one+confidence-ranked 40-row cap, so a subclass was presented as a caller and, on+a base class, evicted the real callers entirely. Measured on the live django+index before the fix: ``Model`` has 8 callers and 1,516 subclasses and the cut+served 39 subclasses and 1 caller; ``TestCase`` has 3 callers and 868+subclasses and served none of its callers.++These tests drive the real route, so they fail if the endpoint stops emitting+the key rather than only if the renderer stops reading it. The heritage+section had been dead for its whole life precisely because nothing asserted+the server end.+"""++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 2 callers and 60 subclasses, plus one framework bind.++ 60 exceeds the 40-row call cap on purpose: under the old shared cut the+ two callers could not be served at all.+ """+ async with get_session(session_factory) as session:+ 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/views.py::save", "app/views.py::delete", "app/wire.py::container"]+ nodes += [f"app/sub{i}.py::Sub{i}" for i in range(60)]+ 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) -> GraphEdge:+ return GraphEdge(+ id=_new_uuid(),+ repository_id=repo_id,+ source_node_id=source,+ target_node_id=BASE,+ edge_type=edge_type,+ confidence=confidence,+ )++ # Subclasses outrank the callers on confidence, which is what made the+ # shared cut drop the callers rather than merely reorder them.+ for i in range(60):+ session.add(edge(f"app/sub{i}.py::Sub{i}", "extends", 0.99))+ session.add(edge("app/views.py::save", "calls", 0.5))+ session.add(edge("app/views.py::delete", "calls", 0.5))+ session.add(edge("app/wire.py::container", "framework_binds", 0.9))+++async def _detail(client: AsyncClient, repo_id: str) -> dict:+ resp = await client.get(+ "/api/symbols/detail", params={"repo_id": repo_id, "symbol_id": BASE}+ )+ assert resp.status_code == 200+ return resp.json()["graph"]+++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"])++ graph = await _detail(client, repo["id"])++ assert {r["edge_type"] for r in graph["callers"]} == {"calls"}+ assert graph["callees"] == []+++async def test_heritage_cannot_evict_the_real_callers(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ graph = await _detail(client, repo["id"])++ # 60 higher-confidence subclasses used to consume the whole 40-row cut.+ assert len(graph["callers"]) == 2+ assert graph["caller_total"] == 2+ assert {r["name"] for r in graph["callers"]} == {"save", "delete"}+++async def test_relations_carry_each_kind_with_its_true_total(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ graph = await _detail(client, repo["id"])++ by_type = {(g["direction"], g["edge_type"]): g for g in graph["relations"]}+ assert set(by_type) == {("in", "extends"), ("in", "framework_binds")}++ 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"]) <= 10+ assert {r["edge_type"] for r in extends["rows"]} == {"extends"}++ assert by_type[("in", "framework_binds")]["group"] == "wiring"+ assert by_type[("in", "framework_binds")]["total"] == 1+++async def test_degree_counts_every_relation_kind(client: AsyncClient, app) -> None:+ """Degree stays a graph metric; `caller_total` is the caller count."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ graph = await _detail(client, repo["id"])++ assert graph["in_degree"] == 63 # 60 extends + 2 calls + 1 framework_binds+ assert graph["out_degree"] == 0+ assert graph["caller_total"] == 2+++async def test_a_recursive_call_appears_on_both_sides(client: AsyncClient, app) -> None:+ """A self-edge is counted once per direction, so it must be served twice.++ Served once, its row is a permanent "+1 more" under Calls that no paging+ can reach.+ """+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ await _seed(app.state.session_factory, repo_id)+ async with get_session(app.state.session_factory) as session:+ session.add(+ GraphEdge(+ id=_new_uuid(),+ repository_id=repo_id,+ source_node_id=BASE,+ target_node_id=BASE,+ edge_type="calls",+ confidence=0.9,+ )+ )++ graph = await _detail(client, repo_id)++ assert graph["callee_total"] == len(graph["callees"]) == 1+ assert graph["callees"][0]["symbol_id"] == BASE+ assert graph["caller_total"] == len(graph["callers"]) == 3diff --git a/tests/unit/server/test_symbol_relation_vocabulary.py b/tests/unit/server/test_symbol_relation_vocabulary.pynew file mode 100644index 000000000..b9ea8c415--- /dev/null+++ b/tests/unit/server/test_symbol_relation_vocabulary.py@@ -0,0 +1,56 @@+"""A relation kind must be named on the page, not filed under "Called by".++Three copies of one vocabulary: the engine's ``SYMBOL_USE_EDGE_TYPES``, the+server's ``SYMBOL_RELATION_GROUPS`` partition of it, and the label table in+``packages/ui/src/graph/symbol-relations.ts``. The failure this pins is not+hypothetical — the whole set was rendered under one heading, so ``extends``+was presented as a call for as long as the endpoint existed.++An edge type added to the engine and to neither of the others degrades+silently: it is fetched, grouped by the fallthrough, and captioned with its+raw verb. These tests make it fail loudly at the two places a human would+otherwise have to remember.++Ceiling: a regex read of the TypeScript table's keys. It proves the *key set*+matches, not that the file parses.+"""++from __future__ import annotations++import pathlib+import re++from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES+from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUPS++_LABELS = (+ pathlib.Path(__file__).resolve().parents[3] / "packages/ui/src/graph/symbol-relations.ts"+)+++def _label_table_keys() -> set[str]:+ """The edge types keyed in `RELATION_LABELS`."""+ source = _LABELS.read_text(encoding="utf-8")+ match = re.search(+ r"const RELATION_LABELS: [^=]+= \{(.*?)\n\};", source, re.DOTALL+ )+ assert match, f"RELATION_LABELS is not declared in {_LABELS.name}"+ return set(re.findall(r"^ (\w+): \{", match.group(1), re.MULTILINE))+++def test_groups_partition_the_engine_set() -> None:+ """Every use edge type is in exactly one group, and no group invents one."""+ members = [t for types in SYMBOL_RELATION_GROUPS.values() for t in types]+ assert set(members) == set(SYMBOL_USE_EDGE_TYPES)+ assert len(members) == len(set(members)), "an edge type is in two groups"+++def test_every_non_call_relation_has_a_label() -> None:+ """A relation the page can show is a relation the page can name."""+ non_call = set(SYMBOL_USE_EDGE_TYPES) - SYMBOL_RELATION_GROUPS["call"]+ assert _label_table_keys() == non_call+++def test_calls_are_not_a_labelled_relation() -> None:+ """`calls` renders as the call graph itself, not as a relation section."""+ assert "calls" not in _label_table_keys()