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
refactor(server): split symbol resolution and flow tracing out of the graph intelligence routes (#2604)
Raghav Chamadiya459b7704af25
diff --git a/packages/server/src/repowise/server/routers/graph/intelligence.py b/packages/server/src/repowise/server/routers/graph/intelligence.pyindex 874f7712b..27197ba13 100644--- a/packages/server/src/repowise/server/routers/graph/intelligence.py+++ b/packages/server/src/repowise/server/routers/graph/intelligence.py@@ -33,6 +33,7 @@ from repowise.server.schemas import (GraphMetricsResponse,SymbolNodeSummary,)+from repowise.server.schemas.intelligence import SymbolRelationGroupfrom repowise.server.services.symbol_relations import load_symbol_relationsrouter = APIRouter()@@ -50,34 +51,23 @@ async def get_graph_metrics(if node is None:raise HTTPException(status_code=404, detail=f"Node not found: {node_id}")- # Percentiles computed against all file-type nodes- all_files = await crud.get_all_file_metrics(session, repo_id)- all_pr = [n.pagerank or 0.0 for n in all_files]- all_bw = [n.betweenness or 0.0 for n in all_files]-- # Scoped by layer. This endpoint feeds the same symbol component as- # /api/symbols/detail (the drawer, where that page is the drill-down), so- # an unscoped count here made one symbol report two different degrees- # depending on which of the two the user opened.- degrees = await crud.get_node_degree_counts(- session,- repo_id,- node_id,- edge_types=(- sorted(SYMBOL_USE_EDGE_TYPES)- if node.node_type == "symbol"- else sorted(FILE_DEPENDENCY_EDGE_TYPES)- ),+ pagerank = node.pagerank or 0.0+ betweenness = node.betweenness or 0.0+ kind, file = (node.kind, node.file_path) if node.node_type == "symbol" else (None, None)+ pagerank_percentile, betweenness_percentile = await _file_percentiles(+ session, repo_id, pagerank, betweenness)++ degrees = await _layer_degrees(session, repo_id, node)meta = parse_community_meta(node)return GraphMetricsResponse(target=node_id,node_type=node.node_type or "file",- pagerank=round(node.pagerank or 0.0, 6),- pagerank_percentile=percentile_rank(node.pagerank or 0.0, all_pr),- betweenness=round(node.betweenness or 0.0, 6),- betweenness_percentile=percentile_rank(node.betweenness or 0.0, all_bw),+ pagerank=round(pagerank, 6),+ pagerank_percentile=pagerank_percentile,+ betweenness=round(betweenness, 6),+ betweenness_percentile=betweenness_percentile,betweenness_scored=node.betweenness_commit is not None,community_id=node.community_id or 0,community_label=meta.get("label") or None,@@ -85,8 +75,34 @@ async def get_graph_metrics(in_degree=degrees["in_degree"],out_degree=degrees["out_degree"],entry_point_score=meta.get("entry_point_score"),- kind=node.kind if node.node_type == "symbol" else None,- file=node.file_path if node.node_type == "symbol" else None,+ kind=kind,+ file=file,+ )+++async def _layer_degrees(session: AsyncSession, repo_id: str, node: GraphNode) -> dict[str, int]:+ """In/out degree over the node's own layer: symbol-use or file-dependency edges.++ Same scope as /api/symbols/detail, which renders the same symbol component,+ so a symbol reports one degree whichever of the two surfaces is open.+ """+ is_symbol = node.node_type == "symbol"+ return await crud.get_node_degree_counts(+ session,+ repo_id,+ node.node_id,+ edge_types=sorted(SYMBOL_USE_EDGE_TYPES if is_symbol else FILE_DEPENDENCY_EDGE_TYPES),+ )+++async def _file_percentiles(+ session: AsyncSession, repo_id: str, pagerank: float, betweenness: float+) -> tuple[int, int]:+ """Rank a pagerank and betweenness against every file node in the repo."""+ all_files = await crud.get_all_file_metrics(session, repo_id)+ return (+ percentile_rank(pagerank, [n.pagerank or 0.0 for n in all_files]),+ percentile_rank(betweenness, [n.betweenness or 0.0 for n in all_files]),)@@ -125,62 +141,74 @@ async def get_callers_callees(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)- if node is None or node.node_type != "symbol":- # Fuzzy: try bare name- bare = symbol_id.split("::")[-1] if "::" in symbol_id else symbol_id- result = await session.execute(- select(GraphNode).where(- GraphNode.repository_id == repo_id,- GraphNode.node_type == "symbol",- GraphNode.name == bare,- )- )- rows = list(result.scalars().all())- if not rows:- raise HTTPException(status_code=404, detail=f"Symbol not found: {symbol_id}")- if "::" in symbol_id:- file_hint = symbol_id.split("::")[0]- for r in rows:- if r.file_path == file_hint:- node = r- break- if node is None or node.node_type != "symbol":- rows.sort(key=lambda r: r.node_id)- node = rows[0]-+ node = await _resolve_symbol(session, repo_id, symbol_id)relations = await load_symbol_relations(session, repo_id, node.node_id, present=True, call_row_cap=limit)- 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"))- ]+ groups = [g for g in relations.groups if _wants_group(g, et_filter, direction)]- wants_in = direction in ("callers", "both")- wants_out = direction in ("callees", "both")+ callers, caller_count = (+ (relations.callers, relations.caller_total) if direction != "callees" else ([], 0)+ )+ callees, callee_count = (+ (relations.callees, relations.callee_total) if direction != "callers" else ([], 0)+ )return CallersCalleesResponse(symbol_id=node.node_id,- symbol=SymbolNodeSummary(- symbol_id=node.node_id,- name=node.name or node.node_id,- kind=node.kind or "unknown",- file=node.file_path or node.node_id,- start_line=node.start_line,- signature=node.signature,- ),- 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,+ symbol=_symbol_summary(node),+ callers=callers,+ callees=callees,+ caller_count=caller_count,+ callee_count=callee_count,relations=groups,- truncated=(- (wants_in and len(relations.callers) < relations.caller_total)- or (wants_out and len(relations.callees) < relations.callee_total)- ),+ truncated=len(callers) < caller_count or len(callees) < callee_count,+ )+++async def _resolve_symbol(session: AsyncSession, repo_id: str, symbol_id: str) -> GraphNode:+ """The symbol node with this id, else one sharing its bare name.++ Among same-named symbols, one in the id's own file wins; otherwise the+ lowest node id, so the pick is stable.+ """+ node = await crud.get_graph_node(session, repo_id, symbol_id)+ if node is not None and node.node_type == "symbol":+ return node++ parts = symbol_id.split("::")+ result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "symbol",+ GraphNode.name == parts[-1],+ )+ )+ rows = list(result.scalars().all())+ if not rows:+ raise HTTPException(status_code=404, detail=f"Symbol not found: {symbol_id}")+ if len(parts) > 1:+ in_file = next((r for r in rows if r.file_path == parts[0]), None)+ if in_file is not None:+ return in_file+ return min(rows, key=lambda r: r.node_id)+++def _wants_group(group: SymbolRelationGroup, edge_types: set[str], direction: str) -> bool:+ """Whether a relation group passes the edge-type filter and the direction."""+ if edge_types and group.edge_type not in edge_types:+ return False+ return direction == "both" or (direction == "callers") == (group.direction == "in")+++def _symbol_summary(node: GraphNode) -> SymbolNodeSummary:+ """The response header for a symbol, degrading null columns to its id."""+ return SymbolNodeSummary(+ symbol_id=node.node_id,+ name=node.name or node.node_id,+ kind=node.kind or "unknown",+ file=node.file_path or node.node_id,+ start_line=node.start_line,+ signature=node.signature,)@@ -194,62 +222,66 @@ async def get_execution_flows(_repo: object = Depends(with_repo),) -> ExecutionFlowsResponse:"""Return top entry points with BFS call-path traces."""- entry_nodes: list[tuple[GraphNode, float]] = []-if entry_point:node = await crud.get_graph_node(session, repo_id, entry_point)if node is None:raise HTTPException(status_code=404, detail=f"Entry point not found: {entry_point}")- entry_nodes = [(node, _ep_score(node))]+ entry_nodes = [node]else:- top_nodes = await crud.get_top_entry_points(session, repo_id, min_score=0.0, limit=top_n)- for n in top_nodes:- entry_nodes.append((n, _ep_score(n)))+ entry_nodes = await crud.get_top_entry_points(session, repo_id, min_score=0.0, limit=top_n)if not entry_nodes:return ExecutionFlowsResponse(total_entry_points=0, flows=[])node_cache: dict[str, GraphNode] = {}- flows: list[ExecutionFlowEntry] = []-- for ep_node, ep_score in entry_nodes:- hop_origins: dict[tuple[str, str], str] = {}- termination: dict[str, Any] = {}- trace = await bfs_trace(- session,- repo_id,- ep_node.node_id,- max_depth,- node_cache,- hop_origins,- termination,- )- communities_visited, crosses = await resolve_trace_communities(- session, repo_id, trace, node_cache- )-- # Null rather than a list of nulls on an older index, so a consumer can- # tell "no origins recorded" from "this hop has none".- via = [hop_origins.get(pair) for pair in pairwise(trace)]-- flows.append(- ExecutionFlowEntry(- entry_point=ep_node.node_id,- entry_point_name=ep_node.name or ep_node.node_id.split("::")[-1],- entry_point_score=round(ep_score, 3),- trace=trace,- depth=len(trace) - 1,- crosses_community=crosses,- communities_visited=communities_visited,- termination=termination.get("reason"),- termination_detail=termination.get("detail") or None,- trace_via=via if any(via) else None,- )- )-+ flows = [+ await _trace_flow(session, repo_id, ep_node, max_depth, node_cache)+ for ep_node in entry_nodes+ ]flows.sort(key=lambda f: -f.entry_point_score)return ExecutionFlowsResponse(total_entry_points=len(flows),flows=flows,)+++async def _trace_flow(+ session: AsyncSession,+ repo_id: str,+ ep_node: GraphNode,+ max_depth: int,+ node_cache: dict[str, GraphNode],+) -> ExecutionFlowEntry:+ """BFS the call path from one entry point, with per-hop origins."""+ hop_origins: dict[tuple[str, str], str] = {}+ termination: dict[str, Any] = {}+ trace = await bfs_trace(+ session,+ repo_id,+ ep_node.node_id,+ max_depth,+ node_cache,+ hop_origins,+ termination,+ )+ communities_visited, crosses = await resolve_trace_communities(+ session, repo_id, trace, node_cache+ )++ # Null rather than a list of nulls on an older index, so a consumer can+ # tell "no origins recorded" from "this hop has none".+ via = [hop_origins.get(pair) for pair in pairwise(trace)]++ return ExecutionFlowEntry(+ entry_point=ep_node.node_id,+ entry_point_name=ep_node.name or ep_node.node_id.split("::")[-1],+ entry_point_score=round(_ep_score(ep_node), 3),+ trace=trace,+ depth=len(trace) - 1,+ crosses_community=crosses,+ communities_visited=communities_visited,+ termination=termination.get("reason"),+ termination_detail=termination.get("detail") or None,+ trace_via=via if any(via) else None,+ )diff --git a/tests/fixtures/server/graph_intelligence_bodies.json b/tests/fixtures/server/graph_intelligence_bodies.jsonnew file mode 100644index 000000000..116cd4900--- /dev/null+++ b/tests/fixtures/server/graph_intelligence_bodies.json@@ -0,0 +1,625 @@+{+ "cc_bad_direction": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_bare_name": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_both": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_callees": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 0,+ "callers": [],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_callers": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_edge_filter_hit": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 0,+ "callers": [],+ "relations": [+ {+ "direction": "in",+ "edge_type": "extends",+ "group": "heritage",+ "rows": [+ {+ "confidence": 0.9,+ "edge_type": "extends",+ "file": "src/c.py",+ "kind": "class",+ "name": "Child",+ "resolution_origin": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Child"+ }+ ],+ "total": 1+ }+ ],+ "symbol": {+ "file": "src/c.py",+ "kind": "class",+ "name": "Base",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Base"+ },+ "symbol_id": "src/c.py::Base",+ "truncated": false+ }+ ],+ "cc_edge_filter_miss": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 0,+ "callers": [],+ "relations": [],+ "symbol": {+ "file": "src/c.py",+ "kind": "class",+ "name": "Base",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Base"+ },+ "symbol_id": "src/c.py::Base",+ "truncated": false+ }+ ],+ "cc_file_hint": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/b.py",+ "kind": "method",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/b.py::Tool.helper"+ },+ "symbol_id": "src/b.py::Tool.helper",+ "truncated": false+ }+ ],+ "cc_file_node": [+ 404,+ {+ "detail": "Symbol not found: src/a.py"+ }+ ],+ "cc_hint_miss": [+ 200,+ {+ "callee_count": 1,+ "callees": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ }+ ],+ "caller_count": 1,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "main",+ "resolution_origin": "same_file",+ "start_line": 3,+ "symbol_id": "src/a.py::main"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ },+ "symbol_id": "src/a.py::helper",+ "truncated": false+ }+ ],+ "cc_limit": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 2,+ "callers": [+ {+ "confidence": 0.9,+ "edge_type": "calls",+ "file": "src/a.py",+ "kind": "function",+ "name": "helper",+ "resolution_origin": "import_scoped",+ "start_line": 3,+ "symbol_id": "src/a.py::helper"+ }+ ],+ "relations": [],+ "symbol": {+ "file": "src/b.py",+ "kind": "function",+ "name": "leaf",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/b.py::leaf"+ },+ "symbol_id": "src/b.py::leaf",+ "truncated": true+ }+ ],+ "cc_missing": [+ 404,+ {+ "detail": "Symbol not found: src/a.py::nope"+ }+ ],+ "cc_relations": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 0,+ "callers": [],+ "relations": [+ {+ "direction": "in",+ "edge_type": "extends",+ "group": "heritage",+ "rows": [+ {+ "confidence": 0.9,+ "edge_type": "extends",+ "file": "src/c.py",+ "kind": "class",+ "name": "Child",+ "resolution_origin": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Child"+ }+ ],+ "total": 1+ }+ ],+ "symbol": {+ "file": "src/c.py",+ "kind": "class",+ "name": "Base",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Base"+ },+ "symbol_id": "src/c.py::Base",+ "truncated": false+ }+ ],+ "cc_relations_callees": [+ 200,+ {+ "callee_count": 0,+ "callees": [],+ "caller_count": 0,+ "callers": [],+ "relations": [],+ "symbol": {+ "file": "src/c.py",+ "kind": "class",+ "name": "Base",+ "signature": null,+ "start_line": 3,+ "symbol_id": "src/c.py::Base"+ },+ "symbol_id": "src/c.py::Base",+ "truncated": false+ }+ ],+ "flows_empty_repo": [+ 200,+ {+ "flows": [],+ "total_entry_points": 0+ }+ ],+ "flows_entry": [+ 200,+ {+ "flows": [+ {+ "communities_visited": [+ 1,+ 2+ ],+ "crosses_community": true,+ "depth": 2,+ "entry_point": "src/a.py::main",+ "entry_point_name": "main",+ "entry_point_score": 0.912,+ "termination": "no_callees",+ "termination_detail": null,+ "trace": [+ "src/a.py::main",+ "src/a.py::helper",+ "src/b.py::leaf"+ ],+ "trace_via": [+ "same_file",+ "import_scoped"+ ]+ }+ ],+ "total_entry_points": 1+ }+ ],+ "flows_entry_leaf": [+ 200,+ {+ "flows": [+ {+ "communities_visited": [+ 2+ ],+ "crosses_community": false,+ "depth": 0,+ "entry_point": "src/b.py::leaf",+ "entry_point_name": "leaf",+ "entry_point_score": 0.0,+ "termination": "no_callees",+ "termination_detail": null,+ "trace": [+ "src/b.py::leaf"+ ],+ "trace_via": null+ }+ ],+ "total_entry_points": 1+ }+ ],+ "flows_missing": [+ 404,+ {+ "detail": "Entry point not found: src/a.py::nope"+ }+ ],+ "flows_top": [+ 200,+ {+ "flows": [+ {+ "communities_visited": [+ 1,+ 2+ ],+ "crosses_community": true,+ "depth": 2,+ "entry_point": "src/a.py::main",+ "entry_point_name": "main",+ "entry_point_score": 0.912,+ "termination": "no_callees",+ "termination_detail": null,+ "trace": [+ "src/a.py::main",+ "src/a.py::helper",+ "src/b.py::leaf"+ ],+ "trace_via": [+ "same_file",+ "import_scoped"+ ]+ },+ {+ "communities_visited": [+ 1,+ 2+ ],+ "crosses_community": true,+ "depth": 1,+ "entry_point": "src/a.py::helper",+ "entry_point_name": "helper",+ "entry_point_score": 0.4,+ "termination": "no_callees",+ "termination_detail": null,+ "trace": [+ "src/a.py::helper",+ "src/b.py::leaf"+ ],+ "trace_via": [+ "import_scoped"+ ]+ }+ ],+ "total_entry_points": 2+ }+ ],+ "flows_top_one": [+ 200,+ {+ "flows": [+ {+ "communities_visited": [+ 1+ ],+ "crosses_community": false,+ "depth": 1,+ "entry_point": "src/a.py::main",+ "entry_point_name": "main",+ "entry_point_score": 0.912,+ "termination": "depth_limit",+ "termination_detail": null,+ "trace": [+ "src/a.py::main",+ "src/a.py::helper"+ ],+ "trace_via": [+ "same_file"+ ]+ }+ ],+ "total_entry_points": 1+ }+ ],+ "metrics_file": [+ 200,+ {+ "betweenness": 0.2,+ "betweenness_percentile": 67,+ "betweenness_scored": false,+ "community_id": 1,+ "community_label": null,+ "entry_point_score": null,+ "file": null,+ "in_degree": 0,+ "is_entry_point": false,+ "kind": null,+ "node_type": "file",+ "out_degree": 1,+ "pagerank": 0.4,+ "pagerank_percentile": 67,+ "target": "src/a.py"+ }+ ],+ "metrics_missing": [+ 404,+ {+ "detail": "Node not found: src/nope.py"+ }+ ],+ "metrics_symbol": [+ 200,+ {+ "betweenness": 0.15,+ "betweenness_percentile": 67,+ "betweenness_scored": true,+ "community_id": 1,+ "community_label": "entry",+ "entry_point_score": 0.91234,+ "file": "src/a.py",+ "in_degree": 0,+ "is_entry_point": true,+ "kind": "function",+ "node_type": "symbol",+ "out_degree": 2,+ "pagerank": 0.35,+ "pagerank_percentile": 67,+ "target": "src/a.py::main"+ }+ ]+}\ No newline at end of filediff --git a/tests/unit/server/test_graph_intelligence_endpoints.py b/tests/unit/server/test_graph_intelligence_endpoints.pynew file mode 100644index 000000000..3126c028d--- /dev/null+++ b/tests/unit/server/test_graph_intelligence_endpoints.py@@ -0,0 +1,164 @@+"""Pins every response of `/metrics`, `/callers-callees` and `/execution-flows`.++Covers exact and fuzzy symbol resolution, direction and edge-type filters, row+caps, entry-point selection and the 404 paths, on a small fixture graph.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from httpx import AsyncClient++from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import GraphEdge, GraphNode+from tests.unit.server.conftest import create_test_repo++_MAIN = "src/a.py::main"+_A_HELPER = "src/a.py::helper"+_B_HELPER = "src/b.py::Tool.helper"+_LEAF = "src/b.py::leaf"+_BASE = "src/c.py::Base"+_CHILD = "src/c.py::Child"+++def _symbol(node_id: str, name: str, kind: str, **extra) -> GraphNode:+ return GraphNode(+ node_id=node_id,+ node_type="symbol",+ language="python",+ name=name,+ kind=kind,+ file_path=node_id.split("::")[0],+ start_line=3,+ **extra,+ )+++def _nodes() -> list[GraphNode]:+ files = [+ GraphNode(+ node_id=path,+ node_type="file",+ language="python",+ file_path=path,+ pagerank=pr,+ betweenness=bw,+ community_id=cid,+ )+ for path, pr, bw, cid in (+ ("src/a.py", 0.4, 0.2, 1),+ ("src/b.py", 0.3, 0.1, 2),+ ("src/c.py", 0.1, 0.0, 2),+ )+ ]+ main_meta = '{"label": "entry", "entry_point_score": 0.91234}'+ return [+ *files,+ _symbol(+ _MAIN,+ "main",+ "function",+ pagerank=0.35,+ betweenness=0.15,+ betweenness_commit="abc123",+ community_id=1,+ community_meta_json=main_meta,+ is_entry_point=True,+ signature="def main()",+ ),+ _symbol(+ _A_HELPER,+ "helper",+ "function",+ community_id=1,+ community_meta_json='{"entry_point_score": 0.4}',+ ),+ _symbol(_B_HELPER, "helper", "method", community_id=2),+ _symbol(_LEAF, "leaf", "function", community_id=2),+ _symbol(_BASE, "Base", "class", community_id=2),+ _symbol(_CHILD, "Child", "class", community_id=2),+ ]+++_EDGES = (+ ("src/a.py", "src/b.py", "imports", None),+ (_MAIN, _A_HELPER, "calls", "same_file"),+ (_A_HELPER, _LEAF, "calls", "import_scoped"),+ (_B_HELPER, _LEAF, "calls", "same_file"),+ (_MAIN, _B_HELPER, "calls", "import_scoped"),+ (_CHILD, _BASE, "extends", None),+)+++async def _seed(session_factory, repo_id: str) -> None:+ async with get_session(session_factory) as session:+ for node in _nodes():+ node.repository_id = repo_id+ session.add(node)+ for src, tgt, edge_type, origin in _EDGES:+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id=src,+ target_node_id=tgt,+ imported_names_json="[]",+ edge_type=edge_type,+ confidence=0.9,+ resolution_origin=origin,+ )+ )+++CASES: list[tuple[str, str, dict]] = [+ ("metrics_file", "metrics", {"node_id": "src/a.py"}),+ ("metrics_symbol", "metrics", {"node_id": _MAIN}),+ ("metrics_missing", "metrics", {"node_id": "src/nope.py"}),+ ("cc_both", "callers-callees", {"symbol_id": _A_HELPER}),+ ("cc_callers", "callers-callees", {"symbol_id": _A_HELPER, "direction": "callers"}),+ ("cc_callees", "callers-callees", {"symbol_id": _A_HELPER, "direction": "callees"}),+ ("cc_bad_direction", "callers-callees", {"symbol_id": _A_HELPER, "direction": "up"}),+ ("cc_limit", "callers-callees", {"symbol_id": _LEAF, "limit": 1}),+ ("cc_bare_name", "callers-callees", {"symbol_id": "helper"}),+ ("cc_file_hint", "callers-callees", {"symbol_id": "src/b.py::helper"}),+ ("cc_hint_miss", "callers-callees", {"symbol_id": "src/z.py::helper"}),+ ("cc_file_node", "callers-callees", {"symbol_id": "src/a.py"}),+ ("cc_missing", "callers-callees", {"symbol_id": "src/a.py::nope"}),+ ("cc_relations", "callers-callees", {"symbol_id": _BASE}),+ ("cc_edge_filter_hit", "callers-callees", {"symbol_id": _BASE, "edge_types": "extends"}),+ ("cc_edge_filter_miss", "callers-callees", {"symbol_id": _BASE, "edge_types": "x, "}),+ ("cc_relations_callees", "callers-callees", {"symbol_id": _BASE, "direction": "callees"}),+ ("flows_top", "execution-flows", {}),+ ("flows_top_one", "execution-flows", {"top_n": 1, "max_depth": 1}),+ ("flows_entry", "execution-flows", {"entry_point": _MAIN}),+ ("flows_entry_leaf", "execution-flows", {"entry_point": _LEAF}),+ ("flows_missing", "execution-flows", {"entry_point": "src/a.py::nope"}),+]+++async def capture(client: AsyncClient, app) -> dict[str, tuple[int, object]]:+ """Every case's status and body, plus flows on a repo with no graph."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])+ out: dict[str, tuple[int, object]] = {}+ for name, endpoint, params in CASES:+ resp = await client.get(f"/api/graph/{repo['id']}/{endpoint}", params=params)+ out[name] = (resp.status_code, resp.json())+ empty = await create_test_repo(client)+ resp = await client.get(f"/api/graph/{empty['id']}/execution-flows")+ out["flows_empty_repo"] = (resp.status_code, resp.json())+ return out+++_EXPECTED = Path(__file__).parents[2] / "fixtures" / "server" / "graph_intelligence_bodies.json"+++async def test_endpoint_bodies_are_pinned(client: AsyncClient, app) -> None:+ got = json.loads(json.dumps(await capture(client, app)))+ expected = json.loads(_EXPECTED.read_text(encoding="utf-8"))+ assert sorted(got) == sorted(expected)+ for name, (status, body) in expected.items():+ assert got[name] == [status, body], name