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
Graph UX overhaul: signal enrichment, architecture endpoint, scope×overlay toolbar (#183)
Raghav Chamadiya6b8edc80d728
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 805c2055f..cb42dc4d6 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -500,9 +500,17 @@ async def _run_ingestion(try:with ProcessPoolExecutor(max_workers=workers) as pool:tasks = [loop.run_in_executor(pool, _parse_one, item) for item in fi_and_bytes]- # Use as_completed via asyncio.as_completed to report per-file progress.- # We need to preserve (task → fi_and_bytes index) for source_map so we- # wrap tasks in a list and drain with gather instead.+ # Tick the parse-progress bar as each worker finishes —+ # ``asyncio.gather`` would otherwise hold every event back+ # until the last file is done, which on PowerToys-scale+ # repos looked like a hang at ``0/N`` for many minutes.+ # Per-task done-callbacks fire on the event loop thread and+ # preserve gather's ordered results, so the aggregation+ # loop below still indexes ``fi_and_bytes`` correctly.+ if progress is not None:+ _parse_tick = lambda _fut: progress.on_item_done("parse") # noqa: E731+ for fut in tasks:+ fut.add_done_callback(_parse_tick)parse_results = await asyncio.gather(*tasks, return_exceptions=True)except Exception as pool_exc:logger.warning(@@ -535,9 +543,9 @@ async def _run_ingestion(parsed_files.append(result)source_map[fi.path] = sourcegraph_builder.add_file(result)- # Report per-file progress if we used the process pool (fallback already reported above).- if _use_process_pool and progress:- progress.on_item_done("parse")+ # Process-pool path already ticked per-file via the done-callback+ # attached above; only the fallback path ticks here (handled in+ # its own loop). No tick needed in aggregation._phase_done(progress, "parse")diff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.pyindex fb0671fb0..febe4a983 100644--- a/packages/server/src/repowise/server/routers/graph.py+++ b/packages/server/src/repowise/server/routers/graph.py@@ -11,6 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import (DeadCodeFinding,+ DecisionRecord,GitMetadata,GraphEdge,GraphNode,@@ -27,6 +28,9 @@ from repowise.server.mcp_server._graph_utils import (resolve_trace_communities,)from repowise.server.schemas import (+ ArchitectureEdgeResponse,+ ArchitectureGraphResponse,+ ArchitectureNodeResponse,CallerCalleeEntry,CallersCalleesResponse,CommunityDetailResponse,@@ -52,6 +56,10 @@ from repowise.server.schemas import (SymbolNodeSummary,)+# Cap on full-graph export; above this we return top-N by PageRank with truncated=True.+# Sized to fit a modern client-side force layout without hitching.+_FULL_GRAPH_NODE_CAP = 5000+router = APIRouter(prefix="/api/graph",tags=["graph"],@@ -80,6 +88,135 @@ async def _get_documented_paths(session: AsyncSession, repo_id: str) -> set[str]return {row.target_path for row in result.all() if row.target_path}+# ---------------------------------------------------------------------------+# Cross-link signal collection — single reusable join layer+# ---------------------------------------------------------------------------+++class NodeSignals:+ """Per-node cross-link signals (git, dead-code, decisions, docs)."""++ __slots__ = (+ "is_hotspot",+ "churn_percentile",+ "is_dead",+ "dead_confidence",+ "has_decision",+ "primary_owner",+ "has_doc",+ )++ def __init__(self) -> None:+ self.is_hotspot: bool = False+ self.churn_percentile: float | None = None+ self.is_dead: bool = False+ self.dead_confidence: float | None = None+ self.has_decision: bool = False+ self.primary_owner: str | None = None+ self.has_doc: bool = False+++_EMPTY_SIGNALS = NodeSignals()+++async def _collect_node_signals(+ session: AsyncSession,+ repo_id: str,+ node_ids: list[str] | None = None,+) -> dict[str, NodeSignals]:+ """Join git metadata, dead-code findings, decisions, and docs into one map.++ When *node_ids* is provided, queries are scoped to that subset; otherwise+ we fetch repo-wide. Returns ``{node_id: NodeSignals}``. Missing keys imply+ default (all-false) signals.+ """+ signals: dict[str, NodeSignals] = {}++ def _entry(path: str) -> NodeSignals:+ existing = signals.get(path)+ if existing is None:+ existing = NodeSignals()+ signals[path] = existing+ return existing++ # Git metadata: hotspot + churn + owner+ git_q = select(GitMetadata).where(GitMetadata.repository_id == repo_id)+ if node_ids is not None:+ git_q = git_q.where(GitMetadata.file_path.in_(node_ids))+ for gm in (await session.execute(git_q)).scalars():+ s = _entry(gm.file_path)+ s.is_hotspot = bool(gm.is_hotspot)+ s.churn_percentile = gm.churn_percentile+ s.primary_owner = gm.primary_owner_name++ # Dead-code findings (only open, unreachable_file)+ dead_q = select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.kind == "unreachable_file",+ )+ if node_ids is not None:+ dead_q = dead_q.where(DeadCodeFinding.file_path.in_(node_ids))+ for f in (await session.execute(dead_q)).scalars():+ s = _entry(f.file_path)+ s.is_dead = True+ s.dead_confidence = f.confidence++ # Decisions: each decision lists affected files in JSON+ dec_q = select(DecisionRecord.affected_files_json).where(+ DecisionRecord.repository_id == repo_id,+ DecisionRecord.status.in_(("active", "proposed")),+ )+ decision_paths: set[str] = set()+ for (raw,) in (await session.execute(dec_q)).all():+ if not raw:+ continue+ try:+ parsed = json.loads(raw)+ except (json.JSONDecodeError, ValueError):+ continue+ if isinstance(parsed, list):+ for p in parsed:+ if isinstance(p, str):+ decision_paths.add(p)+ if node_ids is not None:+ decision_paths &= set(node_ids)+ for p in decision_paths:+ _entry(p).has_decision = True++ # Docs (Page.target_path)+ doc_q = select(Page.target_path).where(Page.repository_id == repo_id)+ if node_ids is not None:+ doc_q = doc_q.where(Page.target_path.in_(node_ids))+ for (path,) in (await session.execute(doc_q)).all():+ if path:+ _entry(path).has_doc = True++ return signals+++def _to_graph_node(n: GraphNode, signals: NodeSignals) -> GraphNodeResponse:+ """Build a GraphNodeResponse from a GraphNode + its collected signals."""+ return GraphNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ has_doc=signals.has_doc,+ is_hotspot=signals.is_hotspot,+ churn_percentile=signals.churn_percentile,+ is_dead=signals.is_dead,+ dead_confidence=signals.dead_confidence,+ has_decision=signals.has_decision,+ primary_owner=signals.primary_owner,+ )++# ---------------------------------------------------------------------------# Module graph# ---------------------------------------------------------------------------@@ -132,6 +269,10 @@ async def module_graph()page_coverage: dict[str, float] = {row.target_path: row.confidence for row in page_result.all()}+ # Collect signals once for all file nodes; aggregate per module below.+ all_node_ids = [n.node_id for n in nodes]+ signals = await _collect_node_signals(session, repo_id, all_node_ids)+node_to_module: dict[str, str] = {}module_nodes: list[ModuleNodeResponse] = []for module_id, module_file_nodes in modules.items():@@ -141,6 +282,22 @@ async def module_graph(covered = sum(1 for n in module_file_nodes if page_coverage.get(n.node_id, 0.0) >= 0.7)doc_coverage_pct = covered / max(file_count, 1)+ hotspot_count = 0+ dead_count = 0+ has_decision = False+ owner_tally: dict[str, int] = {}+ for n in module_file_nodes:+ sig = signals.get(n.node_id, _EMPTY_SIGNALS)+ if sig.is_hotspot:+ hotspot_count += 1+ if sig.is_dead:+ dead_count += 1+ if sig.has_decision:+ has_decision = True+ if sig.primary_owner:+ owner_tally[sig.primary_owner] = owner_tally.get(sig.primary_owner, 0) + 1+ primary_owner = max(owner_tally, key=owner_tally.get) if owner_tally else None+for n in module_file_nodes:node_to_module[n.node_id] = module_id@@ -151,6 +308,10 @@ async def module_graph(symbol_count=symbol_count,avg_pagerank=avg_pagerank,doc_coverage_pct=doc_coverage_pct,+ hotspot_count=hotspot_count,+ dead_count=dead_count,+ has_decision=has_decision,+ primary_owner=primary_owner,))@@ -247,23 +408,9 @@ async def ego_graph(git_row = git_result.scalar_one_or_none()git_meta = GitMetadataResponse.from_orm(git_row) if git_row else None- documented = await _get_documented_paths(session, repo_id)+ signals = await _collect_node_signals(session, repo_id, list(ego_node_ids))- node_responses = [- GraphNodeResponse(- node_id=n.node_id,- node_type=n.node_type,- language=n.language,- symbol_count=n.symbol_count,- pagerank=n.pagerank,- betweenness=n.betweenness,- community_id=n.community_id,- is_test=n.is_test,- is_entry_point=n.is_entry_point,- has_doc=n.node_id in documented,- )- for n in node_rows- ]+ node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in node_rows]return EgoGraphResponse(nodes=node_responses,@@ -328,23 +475,9 @@ async def entry_points_graph()nodes = node_result.scalars().all()- documented = await _get_documented_paths(session, repo_id)+ signals = await _collect_node_signals(session, repo_id, list(reachable))- node_responses = [- GraphNodeResponse(- node_id=n.node_id,- node_type=n.node_type,- language=n.language,- symbol_count=n.symbol_count,- pagerank=n.pagerank,- betweenness=n.betweenness,- community_id=n.community_id,- is_test=n.is_test,- is_entry_point=n.is_entry_point,- has_doc=n.node_id in documented,- )- for n in nodes- ]+ node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in nodes]link_responses = [GraphEdgeResponse(@@ -356,7 +489,116 @@ async def entry_points_graph(if e.source_node_id in reachable and e.target_node_id in reachable]- return GraphExportResponse(nodes=node_responses, links=link_responses)+ return GraphExportResponse(+ nodes=node_responses,+ links=link_responses,+ total_node_count=len(node_responses),+ )+++# ---------------------------------------------------------------------------+# Architecture graph — community super-nodes+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/architecture", response_model=ArchitectureGraphResponse)+async def architecture_graph(+ repo_id: str,+ min_members: int = Query(+ 2, ge=1, description="Drop communities smaller than this from the view."+ ),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> ArchitectureGraphResponse:+ """High-level architecture view: one node per detected community.++ Edges between communities are weighted by the number of underlying file+ edges that cross the boundary. Each super-node also carries signal counts+ (hotspots, dead files, decisions, doc coverage) so the architecture view+ surfaces health at a glance.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ all_nodes = await crud.get_all_file_metrics(session, repo_id)+ if not all_nodes:+ return ArchitectureGraphResponse(nodes=[], edges=[])++ # Group file nodes by community+ buckets: dict[int, list[GraphNode]] = {}+ node_to_community: dict[str, int] = {}+ for n in all_nodes:+ cid = n.community_id if n.community_id is not None else 0+ buckets.setdefault(cid, []).append(n)+ node_to_community[n.node_id] = cid++ # Pull cross-link signals once for the whole repo so super-nodes can+ # aggregate hotspot/dead/decision counts without N round-trips.+ signals = await _collect_node_signals(session, repo_id, [n.node_id for n in all_nodes])++ arch_nodes: list[ArchitectureNodeResponse] = []+ for cid, members in buckets.items():+ if len(members) < min_members:+ continue+ top = max(members, key=lambda m: m.pagerank or 0.0)+ hotspot_count = 0+ dead_count = 0+ has_decision = False+ doc_hits = 0+ langs: dict[str, int] = {}+ for m in members:+ sig = signals.get(m.node_id, _EMPTY_SIGNALS)+ if sig.is_hotspot:+ hotspot_count += 1+ if sig.is_dead:+ dead_count += 1+ if sig.has_decision:+ has_decision = True+ if sig.has_doc:+ doc_hits += 1+ if m.language:+ langs[m.language] = langs.get(m.language, 0) + 1+ top_langs = [lang for lang, _ in sorted(langs.items(), key=lambda kv: -kv[1])[:3]]+ avg_pr = sum(m.pagerank or 0.0 for m in members) / max(len(members), 1)++ arch_nodes.append(+ ArchitectureNodeResponse(+ community_id=cid,+ label=community_label(top),+ cohesion=community_cohesion(top),+ member_count=len(members),+ top_file=top.node_id,+ avg_pagerank=avg_pr,+ hotspot_count=hotspot_count,+ dead_count=dead_count,+ has_decision=has_decision,+ doc_coverage_pct=doc_hits / max(len(members), 1),+ languages=top_langs,+ )+ )++ arch_nodes.sort(key=lambda a: -a.member_count)+ kept_communities = {a.community_id for a in arch_nodes}++ # Collapse cross-community edges+ edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))+ edge_counts: dict[tuple[int, int], int] = {}+ for e in edge_result.scalars():+ src_c = node_to_community.get(e.source_node_id)+ tgt_c = node_to_community.get(e.target_node_id)+ if src_c is None or tgt_c is None or src_c == tgt_c:+ continue+ if src_c not in kept_communities or tgt_c not in kept_communities:+ continue+ key = (src_c, tgt_c)+ edge_counts[key] = edge_counts.get(key, 0) + 1++ arch_edges = [+ ArchitectureEdgeResponse(source=s, target=t, edge_count=c)+ for (s, t), c in edge_counts.items()+ ]++ return ArchitectureGraphResponse(nodes=arch_nodes, edges=arch_edges)# ---------------------------------------------------------------------------@@ -461,9 +703,10 @@ async def dead_code_graph(neighbor_nodes = []all_node_ids = dead_node_ids | neighbor_ids- documented = await _get_documented_paths(session, repo_id)+ signals = await _collect_node_signals(session, repo_id, list(all_node_ids))def _to_dead_node(n: GraphNode, confidence_group: str) -> DeadCodeGraphNodeResponse:+ sig = signals.get(n.node_id, _EMPTY_SIGNALS)return DeadCodeGraphNodeResponse(node_id=n.node_id,node_type=n.node_type,@@ -474,7 +717,13 @@ async def dead_code_graph(community_id=n.community_id,is_test=n.is_test,is_entry_point=n.is_entry_point,- has_doc=n.node_id in documented,+ has_doc=sig.has_doc,+ is_hotspot=sig.is_hotspot,+ churn_percentile=sig.churn_percentile,+ is_dead=sig.is_dead,+ dead_confidence=sig.dead_confidence,+ has_decision=sig.has_decision,+ primary_owner=sig.primary_owner,confidence_group=confidence_group,)@@ -573,9 +822,10 @@ async def hot_files_graph(neighbor_nodes = []all_node_ids = hot_node_ids | neighbor_ids- documented = await _get_documented_paths(session, repo_id)+ signals = await _collect_node_signals(session, repo_id, list(all_node_ids))def _to_hot_node(n: GraphNode, commit_count: int) -> HotFilesNodeResponse:+ sig = signals.get(n.node_id, _EMPTY_SIGNALS)return HotFilesNodeResponse(node_id=n.node_id,node_type=n.node_type,@@ -586,7 +836,13 @@ async def hot_files_graph(community_id=n.community_id,is_test=n.is_test,is_entry_point=n.is_entry_point,- has_doc=n.node_id in documented,+ has_doc=sig.has_doc,+ is_hotspot=sig.is_hotspot,+ churn_percentile=sig.churn_percentile,+ is_dead=sig.is_dead,+ dead_confidence=sig.dead_confidence,+ has_decision=sig.has_decision,+ primary_owner=sig.primary_owner,commit_count=commit_count,)@@ -648,36 +904,40 @@ async def search_nodes(@router.get("/{repo_id}", response_model=GraphExportResponse)async def export_graph(repo_id: str,+ limit: int = Query(+ _FULL_GRAPH_NODE_CAP,+ ge=1,+ le=100_000,+ description="Maximum nodes to return (top-N by PageRank). Set very high to fetch all.",+ ),session: AsyncSession = Depends(get_db_session), # noqa: B008) -> GraphExportResponse:- """Export the full dependency graph in D3 force-directed format."""+ """Export the full dependency graph in D3 force-directed format.++ Large repos are capped to top-N nodes by PageRank with ``truncated=True``;+ clients should surface a banner and let the user request unrestricted load.+ """repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")- node_result = await session.execute(select(GraphNode).where(GraphNode.repository_id == repo_id))- nodes = node_result.scalars().all()+ node_result = await session.execute(+ select(GraphNode)+ .where(GraphNode.repository_id == repo_id)+ .order_by(GraphNode.pagerank.desc())+ )+ all_nodes = node_result.scalars().all()+ total_node_count = len(all_nodes)+ truncated = total_node_count > limit+ nodes = all_nodes[:limit] if truncated else all_nodes+ kept_ids = {n.node_id for n in nodes}edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))edges = edge_result.scalars().all()- documented = await _get_documented_paths(session, repo_id)+ signals = await _collect_node_signals(session, repo_id, list(kept_ids) if truncated else None)- node_responses = [- GraphNodeResponse(- node_id=n.node_id,- node_type=n.node_type,- language=n.language,- symbol_count=n.symbol_count,- pagerank=n.pagerank,- betweenness=n.betweenness,- community_id=n.community_id,- is_test=n.is_test,- is_entry_point=n.is_entry_point,- has_doc=n.node_id in documented,- )- for n in nodes- ]+ node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in nodes]link_responses = [GraphEdgeResponse(@@ -686,9 +946,15 @@ async def export_graph(imported_names=_parse_imported_names(e.imported_names_json),)for e in edges+ if e.source_node_id in kept_ids and e.target_node_id in kept_ids]- return GraphExportResponse(nodes=node_responses, links=link_responses)+ return GraphExportResponse(+ nodes=node_responses,+ links=link_responses,+ truncated=truncated,+ total_node_count=total_node_count,+ )# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.pyindex f8a8ae3c7..30b16867a 100644--- a/packages/server/src/repowise/server/schemas.py+++ b/packages/server/src/repowise/server/schemas.py@@ -288,6 +288,13 @@ class GraphNodeResponse(BaseModel):is_test: bool = Falseis_entry_point: bool = Falsehas_doc: bool = False+ # Cross-link signals (populated by _collect_node_signals)+ is_hotspot: bool = False+ churn_percentile: float | None = None+ is_dead: bool = False+ dead_confidence: float | None = None+ has_decision: bool = False+ primary_owner: str | None = Noneclass GraphEdgeResponse(BaseModel):@@ -299,6 +306,36 @@ class GraphEdgeResponse(BaseModel):class GraphExportResponse(BaseModel):nodes: list[GraphNodeResponse]links: list[GraphEdgeResponse]+ # When the graph is too large to return in full, the server caps the response+ # to top-N nodes by PageRank. Clients should surface a banner.+ truncated: bool = False+ total_node_count: int | None = None+++# Architecture / community super-node graph+class ArchitectureNodeResponse(BaseModel):+ community_id: int+ label: str+ cohesion: float+ member_count: int+ top_file: str+ avg_pagerank: float+ hotspot_count: int = 0+ dead_count: int = 0+ has_decision: bool = False+ doc_coverage_pct: float = 0.0+ languages: list[str] = []+++class ArchitectureEdgeResponse(BaseModel):+ source: int+ target: int+ edge_count: int+++class ArchitectureGraphResponse(BaseModel):+ nodes: list[ArchitectureNodeResponse]+ edges: list[ArchitectureEdgeResponse]# ---------------------------------------------------------------------------@@ -499,6 +536,10 @@ class ModuleNodeResponse(BaseModel):symbol_count: intavg_pagerank: floatdoc_coverage_pct: float+ hotspot_count: int = 0+ dead_count: int = 0+ has_decision: bool = False+ primary_owner: str | None = Noneclass ModuleEdgeResponse(BaseModel):@@ -548,7 +589,13 @@ class DeadCodeGraphNodeResponse(BaseModel):is_test: bool = Falseis_entry_point: bool = Falsehas_doc: bool = False- confidence_group: str # "certain" | "likely"+ is_hotspot: bool = False+ churn_percentile: float | None = None+ is_dead: bool = False+ dead_confidence: float | None = None+ has_decision: bool = False+ primary_owner: str | None = None+ confidence_group: str # "certain" | "likely" | "neighbor"class DeadCodeGraphResponse(BaseModel):@@ -572,6 +619,12 @@ class HotFilesNodeResponse(BaseModel):is_test: bool = Falseis_entry_point: bool = Falsehas_doc: bool = False+ is_hotspot: bool = False+ churn_percentile: float | None = None+ is_dead: bool = False+ dead_confidence: float | None = None+ has_decision: bool = False+ primary_owner: str | None = Nonecommit_count: intdiff --git a/packages/types/src/graph.ts b/packages/types/src/graph.tsindex 1c60409a5..320ea03ce 100644--- a/packages/types/src/graph.ts+++ b/packages/types/src/graph.ts@@ -26,6 +26,14 @@ export interface GraphNode {is_test: boolean;is_entry_point: boolean;has_doc: boolean;+ /** Cross-link signals — added in Phase A enrichment. All optional for+ * back-compat with older backends; consumers should default to false/null. */+ is_hotspot?: boolean;+ churn_percentile?: number | null;+ is_dead?: boolean;+ dead_confidence?: number | null;+ has_decision?: boolean;+ primary_owner?: string | null;}export interface GraphLink {@@ -41,6 +49,38 @@ export interface GraphLink {export interface GraphExport {nodes: GraphNode[];links: GraphLink[];+ /** Server flagged response as capped (top-N by PageRank). UI should banner. */+ truncated?: boolean;+ total_node_count?: number;+}++// ---------------------------------------------------------------------------+// Architecture (community super-node) graph+// ---------------------------------------------------------------------------++export interface ArchitectureNode {+ community_id: number;+ label: string;+ cohesion: number;+ member_count: number;+ top_file: string;+ avg_pagerank: number;+ hotspot_count: number;+ dead_count: number;+ has_decision: boolean;+ doc_coverage_pct: number;+ languages: string[];+}++export interface ArchitectureEdge {+ source: number;+ target: number;+ edge_count: number;+}++export interface ArchitectureGraph {+ nodes: ArchitectureNode[];+ edges: ArchitectureEdge[];}// ---------------------------------------------------------------------------@@ -102,6 +142,10 @@ export interface ModuleNode {symbol_count: number;avg_pagerank: number;doc_coverage_pct: number;+ hotspot_count?: number;+ dead_count?: number;+ has_decision?: boolean;+ primary_owner?: string | null;}export interface ModuleEdge {diff --git a/packages/ui/src/graph/graph-community-panel.tsx b/packages/ui/src/graph/graph-community-panel.tsxindex 09ca652c9..969488175 100644--- a/packages/ui/src/graph/graph-community-panel.tsx+++ b/packages/ui/src/graph/graph-community-panel.tsx@@ -24,7 +24,7 @@ export function GraphCommunityPanel({onClose,}: GraphCommunityPanelProps) {return (- <div className="absolute right-0 top-0 bottom-0 w-full sm:w-[360px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-10 flex flex-col shadow-lg shadow-black/20">+ <div className="absolute right-0 top-0 bottom-0 w-full sm:w-[360px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-20 flex flex-col shadow-lg shadow-black/20">{/* Header */}<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-default)]"><div className="min-w-0">diff --git a/packages/ui/src/graph/graph-context-drawer.tsx b/packages/ui/src/graph/graph-context-drawer.tsxnew file mode 100644index 000000000..153a77a6d--- /dev/null+++ b/packages/ui/src/graph/graph-context-drawer.tsx@@ -0,0 +1,261 @@+"use client";++/**+ * GraphContextDrawer — single tabbed right-side surface for the selected node.+ *+ * Replaces the previously parallel right-panels (doc / inspection / community+ * / ego) with one coordinated drawer keyed by ``selectedNodeId``. The drawer+ * is intentionally presentational and shape-agnostic — callers pass tab bodies+ * as ``render`` functions, which lets `packages/web` wire in its own data hooks+ * and lets the hosted frontend plug in different implementations.+ *+ * Design intent:+ * - One source of truth for which node is selected+ * - Tab order is stable; tabs gracefully no-op when their data is unavailable+ * - Header surfaces signal badges via the shared `NodeBadges` component so+ * the user sees doc / hotspot / dead / decision state at a glance+ * - Actions tab carries deep links to the rest of the product (wiki, git,+ * risk, decisions, file viewer) — wired by the caller+ */++import * as React from "react";+import { X } from "lucide-react";+import { cn } from "../lib/cn";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";+import { NodeBadges, type NodeSignalInput } from "./node-badges";++export type GraphDrawerTabId =+ | "overview"+ | "docs"+ | "git"+ | "symbols"+ | "neighborhood"+ | "actions";++export interface GraphDrawerTab {+ id: GraphDrawerTabId;+ label: string;+ /** Render the tab body. May return null to indicate "nothing to show". */+ render: () => React.ReactNode;+ /** Hide the tab trigger entirely (e.g. symbols tab for non-symbol nodes). */+ hidden?: boolean;+ /** Disable the tab trigger but keep it visible (e.g. loading state). */+ disabled?: boolean;+}++export interface GraphContextDrawerProps {+ /** Currently selected node id; ``null`` collapses the drawer. */+ nodeId: string | null;+ /** Display title — usually the file basename. */+ title?: string;+ /** Optional path/subtitle shown under the title. */+ subtitle?: string;+ /** Signals to render as badges in the header row. */+ signals?: NodeSignalInput;+ tabs: GraphDrawerTab[];+ defaultTab?: GraphDrawerTabId;+ onClose: () => void;+ /** Width in pixels; defaults to 380. */+ width?: number;+ className?: string;+}++const DEFAULT_TAB_ORDER: GraphDrawerTabId[] = [+ "overview",+ "docs",+ "git",+ "symbols",+ "neighborhood",+ "actions",+];++export function GraphContextDrawer({+ nodeId,+ title,+ subtitle,+ signals,+ tabs,+ defaultTab = "overview",+ onClose,+ width = 380,+ className,+}: GraphContextDrawerProps) {+ const visibleTabs = React.useMemo(() => {+ const byId = new Map(tabs.filter((t) => !t.hidden).map((t) => [t.id, t]));+ // Stable canonical order; unknown tab ids appended after.+ const ordered: GraphDrawerTab[] = [];+ for (const id of DEFAULT_TAB_ORDER) {+ const t = byId.get(id);+ if (t) {+ ordered.push(t);+ byId.delete(id);+ }+ }+ return ordered.concat(Array.from(byId.values()));+ }, [tabs]);++ const initialTab = React.useMemo(() => {+ if (visibleTabs.some((t) => t.id === defaultTab && !t.disabled)) return defaultTab;+ return visibleTabs.find((t) => !t.disabled)?.id ?? defaultTab;+ }, [visibleTabs, defaultTab]);++ const [active, setActive] = React.useState<GraphDrawerTabId>(initialTab);+ React.useEffect(() => {+ setActive(initialTab);+ }, [nodeId, initialTab]);++ // Close on Escape so the drawer matches the rest of the graph UI shortcuts.+ React.useEffect(() => {+ if (!nodeId) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, [nodeId, onClose]);++ if (!nodeId) return null;++ return (+ <aside+ className={cn(+ "relative flex h-full flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)]",+ "shadow-xl shadow-black/10",+ className,+ )}+ style={{ width }}+ role="complementary"+ aria-label="Selected node context"+ >+ <header className="flex items-start gap-2 border-b border-[var(--color-border-default)] p-3">+ <div className="min-w-0 flex-1">+ {title && (+ <p className="truncate font-mono text-[12px] font-semibold text-[var(--color-text-primary)]">+ {title}+ </p>+ )}+ {subtitle && (+ <p className="truncate text-[10px] text-[var(--color-text-tertiary)]">+ {subtitle}+ </p>+ )}+ {signals && (+ <NodeBadges signals={signals} className="mt-1.5" />+ )}+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close panel"+ className="shrink-0 rounded p-1 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-4 w-4" />+ </button>+ </header>++ <Tabs+ value={active}+ onValueChange={(v) => setActive(v as GraphDrawerTabId)}+ className="flex min-h-0 flex-1 flex-col"+ >+ <TabsList className="mx-3 mt-2 h-auto w-auto flex-wrap justify-start bg-transparent p-0 gap-1">+ {visibleTabs.map((tab) => (+ <TabsTrigger+ key={tab.id}+ value={tab.id}+ disabled={tab.disabled}+ className="rounded-md px-2 py-1 text-[11px] font-medium data-[state=active]:bg-[var(--color-bg-inset)] data-[state=active]:text-[var(--color-text-primary)]"+ >+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>++ <div className="min-h-0 flex-1 overflow-auto">+ {visibleTabs.map((tab) => (+ <TabsContent+ key={tab.id}+ value={tab.id}+ className="m-0 h-full p-3 outline-none"+ >+ {tab.render()}+ </TabsContent>+ ))}+ </div>+ </Tabs>+ </aside>+ );+}++// ---------------------------------------------------------------------------+// Actions tab — reusable deep-link list.+// ---------------------------------------------------------------------------++export interface GraphDrawerAction {+ id: string;+ label: string;+ description?: string;+ icon?: React.ReactNode;+ href?: string;+ onClick?: () => void;+ disabled?: boolean;+}++export interface GraphDrawerActionsProps {+ actions: GraphDrawerAction[];+}++export function GraphDrawerActions({ actions }: GraphDrawerActionsProps) {+ if (actions.length === 0) {+ return (+ <p className="text-[11px] text-[var(--color-text-tertiary)]">+ No actions available for this node.+ </p>+ );+ }+ return (+ <ul className="flex flex-col gap-1.5">+ {actions.map((a) => {+ const inner = (+ <span className="flex items-start gap-2">+ {a.icon && <span className="mt-0.5 shrink-0">{a.icon}</span>}+ <span className="min-w-0 flex-1">+ <span className="block text-[12px] font-medium text-[var(--color-text-primary)]">+ {a.label}+ </span>+ {a.description && (+ <span className="block text-[11px] text-[var(--color-text-tertiary)]">+ {a.description}+ </span>+ )}+ </span>+ </span>+ );+ const cls = cn(+ "block rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-3 py-2 text-left transition-colors",+ a.disabled+ ? "cursor-not-allowed opacity-50"+ : "hover:border-[var(--color-accent-graph)]/40 hover:bg-[var(--color-bg-surface)]",+ );+ return (+ <li key={a.id}>+ {a.href && !a.disabled ? (+ <a href={a.href} className={cls}>+ {inner}+ </a>+ ) : (+ <button+ type="button"+ onClick={a.onClick}+ disabled={a.disabled}+ className={cn(cls, "w-full")}+ >+ {inner}+ </button>+ )}+ </li>+ );+ })}+ </ul>+ );+}diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex fdb8979f6..22072600d 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -73,6 +73,10 @@ export interface GraphFlowProps {communityId: number;onClose: () => void;}) => ReactNode;+ /** Fired when the community detail panel transitions to open. Lets the+ * hosting page dismiss any competing right-rail panel (doc panel etc.)+ * so the right side is a single sidebar. */+ onCommunityPanelOpen?: (communityId: number) => void;}export function GraphFlow(props: GraphFlowProps) {@@ -98,6 +102,7 @@ export function GraphFlow(props: GraphFlowProps) {onNodeViewDocs,renderPathFinder,renderCommunityPanel,+ onCommunityPanelOpen,} = props;const sigmaRef = useRef<SigmaCanvasHandle>(null);@@ -182,6 +187,17 @@ export function GraphFlow(props: GraphFlowProps) {const [communityPanelId, setCommunityPanelId] = useState<number | null>(null);const [activeCommunities, setActiveCommunities] = useState<Set<number> | null>(null);+ // Wrap the setter so legend-driven opens notify the host page; this lets+ // the page dismiss competing right-rail panels (doc panel) and keep the+ // right side a single coordinated surface.+ const openCommunityPanel = useCallback(+ (cid: number) => {+ setCommunityPanelId(cid);+ onCommunityPanelOpen?.(cid);+ },+ [onCommunityPanelOpen],+ );+// ---- Derived state ----const isModuleView = viewMode === "module";const isUnified = viewMode === "unified";@@ -1044,7 +1060,7 @@ export function GraphFlow(props: GraphFlowProps) {colorMode={colorMode}viewMode={viewMode}{...(communityLabels ? { communityLabels } : {})}- onCommunityClick={setCommunityPanelId}+ onCommunityClick={openCommunityPanel}activeCommunities={activeCommunities ?? undefined}onCommunityToggle={handleCommunityToggle}onToggleAllCommunities={handleToggleAllCommunities}diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex 5e8680732..0597d20ef 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -12,7 +12,6 @@ import {Skull,Flame,LayoutGrid,- Layers,Workflow,Search,X,@@ -29,6 +28,46 @@ export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles"export type LayoutMode = "hierarchical" | "force";export type GraphTheme = "light" | "dark";+/**+ * Orthogonal model:+ * Scope ("which subset of nodes do we render?")+ * × Overlays ("which signals do we highlight on top?")+ *+ * The legacy ViewMode is preserved as the wire/state format so existing+ * callers and query-param routing keep working. The helpers below convert+ * freely in both directions.+ */+export type Scope = "architecture" | "modules" | "full";+export type Overlay = "dead" | "hot";++export function scopeOverlaysToViewMode(scope: Scope, overlays: ReadonlySet<Overlay>): ViewMode {+ const hasDead = overlays.has("dead");+ const hasHot = overlays.has("hot");+ if (hasDead && hasHot) return "unified";+ if (hasDead) return "dead";+ if (hasHot) return "hotfiles";+ if (scope === "modules") return "module";+ return scope; // "architecture" | "full"+}++export function viewModeToScopeOverlays(view: ViewMode): { scope: Scope; overlays: Set<Overlay> } {+ switch (view) {+ case "module":+ return { scope: "modules", overlays: new Set() };+ case "architecture":+ return { scope: "architecture", overlays: new Set() };+ case "dead":+ return { scope: "full", overlays: new Set(["dead"]) };+ case "hotfiles":+ return { scope: "full", overlays: new Set(["hot"]) };+ case "unified":+ return { scope: "full", overlays: new Set(["dead", "hot"]) };+ case "full":+ default:+ return { scope: "full", overlays: new Set() };+ }+}+interface GraphToolbarProps {viewMode: ViewMode;onViewChange: (mode: ViewMode) => void;@@ -52,13 +91,17 @@ interface GraphToolbarProps {onGraphThemeChange: (theme: GraphTheme) => void;}-const VIEW_MODES: { id: ViewMode; icon: typeof Boxes; label: string }[] = [- { id: "module", icon: Boxes, label: "Modules" },- { id: "full", icon: LayoutGrid, label: "Full Graph" },- { id: "architecture", icon: GitFork, label: "Architecture" },- { id: "dead", icon: Skull, label: "Dead Code" },- { id: "hotfiles", icon: Flame, label: "Hot Files" },- { id: "unified", icon: Layers, label: "Unified" },+// Scope = which subset of nodes are drawn. Mutually exclusive.+const SCOPES: { id: Scope; icon: typeof Boxes; label: string; hint: string }[] = [+ { id: "architecture", icon: GitFork, label: "Architecture", hint: "Detected communities" },+ { id: "modules", icon: Boxes, label: "Modules", hint: "Folder / package rollup" },+ { id: "full", icon: LayoutGrid, label: "Full", hint: "All files and symbols" },+];++// Overlays = additive signal highlights that compose with any scope.+const OVERLAYS: { id: Overlay; icon: typeof Skull; label: string }[] = [+ { id: "dead", icon: Skull, label: "Dead" },+ { id: "hot", icon: Flame, label: "Hot" },];const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [@@ -94,22 +137,39 @@ export const GraphToolbar = memo(function GraphToolbar({graphTheme,onGraphThemeChange,}: GraphToolbarProps) {+ // Derive scope + overlays from the legacy ViewMode so this component remains+ // the single source of truth — callers can continue to round-trip the+ // wire-format ``viewMode`` value through query params without translation.+ const { scope: activeScope, overlays: activeOverlays } = viewModeToScopeOverlays(viewMode);++ const setScope = (next: Scope) => {+ onViewChange(scopeOverlaysToViewMode(next, activeOverlays));+ };++ const toggleOverlay = (id: Overlay) => {+ const next = new Set(activeOverlays);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ onViewChange(scopeOverlaysToViewMode(activeScope, next));+ };+return (<div className="flex flex-col gap-1.5 items-end">+ {/* Scope (mutually exclusive) */}<div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">- {VIEW_MODES.map((m) => {+ {SCOPES.map((m) => {const Icon = m.icon;- const isActive = viewMode === m.id;+ const isActive = activeScope === m.id;return (<buttonkey={m.id}- onClick={() => onViewChange(m.id)}+ onClick={() => setScope(m.id)}className={`flex items-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${isActive? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"}`}- title={m.label}+ title={m.hint}aria-label={m.label}aria-pressed={isActive}>@@ -120,6 +180,31 @@ export const GraphToolbar = memo(function GraphToolbar({})}</div>+ {/* Overlays (additive signal chips) */}+ <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">+ {OVERLAYS.map((o) => {+ const Icon = o.icon;+ const isActive = activeOverlays.has(o.id);+ return (+ <button+ key={o.id}+ onClick={() => toggleOverlay(o.id)}+ className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium transition-all ${+ isActive+ ? "bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"+ }`}+ title={`Overlay: ${o.label}`}+ aria-label={`Overlay: ${o.label}`}+ aria-pressed={isActive}+ >+ <Icon className="w-3 h-3" />+ <span className="hidden lg:inline">{o.label}</span>+ </button>+ );+ })}+ </div>+<div className="flex gap-1.5 items-center"><div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">{LAYOUT_MODES.map((m) => {diff --git a/packages/ui/src/graph/graph-tooltip.tsx b/packages/ui/src/graph/graph-tooltip.tsxindex 3d43511ae..3f989c3e9 100644--- a/packages/ui/src/graph/graph-tooltip.tsx+++ b/packages/ui/src/graph/graph-tooltip.tsx@@ -2,10 +2,11 @@"use client";import { useEffect, useRef } from "react";-import { FileText, Folder, ArrowRight, X, Zap, FlaskConical, BookOpen, Code2 } from "lucide-react";+import { FileText, Folder, ArrowRight, X, BookOpen, Code2 } from "lucide-react";import { formatNumber } from "../lib/format";import { languageColor } from "../lib/confidence";import type { FileNodeData, ModuleNodeData } from "./elk-layout";+import { NodeBadges } from "./node-badges";interface GraphTooltipProps {nodeId: string;@@ -168,28 +169,18 @@ export function GraphTooltip({</div>)}- {/* Badges row */}- <div className="flex items-center gap-1.5 pt-1 flex-wrap">- {d.isEntryPoint && (- <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-accent-graph)]/10 text-[var(--color-accent-graph)] px-1.5 py-0.5 text-[10px] font-medium">- <Zap className="w-2.5 h-2.5" /> Entry Point- </span>- )}- {d.isTest && (- <span className="inline-flex items-center gap-1 rounded-md bg-purple-500/10 text-purple-400 px-1.5 py-0.5 text-[10px] font-medium">- <FlaskConical className="w-2.5 h-2.5" /> Test- </span>- )}- {d.hasDoc ? (- <span className="inline-flex items-center gap-1 rounded-md bg-green-500/10 text-green-400 px-1.5 py-0.5 text-[10px] font-medium">- <BookOpen className="w-2.5 h-2.5" /> Documented- </span>- ) : (- <span className="inline-flex items-center gap-1 rounded-md bg-slate-500/10 text-slate-400 px-1.5 py-0.5 text-[10px] font-medium">- <BookOpen className="w-2.5 h-2.5" /> No docs- </span>- )}- </div>+ {/* Badges row — single shared component used by tooltip + drawer */}+ <NodeBadges+ className="pt-1"+ signals={{+ isEntryPoint: d.isEntryPoint,+ isTest: d.isTest,+ hasDoc: d.hasDoc,+ isHotspot: (d as { isHotspot?: boolean }).isHotspot,+ isDead: (d as { isDead?: boolean }).isDead,+ hasDecision: (d as { hasDecision?: boolean }).hasDecision,+ }}+ /></>);})()}diff --git a/packages/ui/src/graph/graph-truncation-banner.tsx b/packages/ui/src/graph/graph-truncation-banner.tsxnew file mode 100644index 000000000..4be37bbce--- /dev/null+++ b/packages/ui/src/graph/graph-truncation-banner.tsx@@ -0,0 +1,71 @@+"use client";++/**+ * GraphTruncationBanner — shown when the server capped the full-graph+ * response to top-N by PageRank. Communicates the cap to the user and offers+ * an escape hatch ("load all").+ *+ * Lives in `packages/ui` so the hosted frontend can reuse it.+ */++import { AlertTriangle } from "lucide-react";+import { Button } from "../ui/button";+import { cn } from "../lib/cn";+import { formatNumber } from "../lib/format";++export interface GraphTruncationBannerProps {+ shown: number;+ total: number;+ onLoadAll?: () => void;+ /** When known, suggests a healthier scope to switch to. */+ onSwitchToArchitecture?: () => void;+ className?: string;+}++export function GraphTruncationBanner({+ shown,+ total,+ onLoadAll,+ onSwitchToArchitecture,+ className,+}: GraphTruncationBannerProps) {+ return (+ <div+ role="status"+ aria-live="polite"+ className={cn(+ "flex items-center gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",+ className,+ )}+ >+ <AlertTriangle className="h-4 w-4 shrink-0" />+ <p className="min-w-0 flex-1">+ Showing <span className="font-semibold tabular-nums">{formatNumber(shown)}</span> of{" "}+ <span className="font-semibold tabular-nums">{formatNumber(total)}</span> nodes — the+ full graph was capped for performance.+ </p>+ <div className="flex shrink-0 items-center gap-2">+ {onSwitchToArchitecture && (+ <Button+ size="sm"+ variant="ghost"+ onClick={onSwitchToArchitecture}+ className="h-7 px-2 text-[11px] text-amber-200 hover:bg-amber-500/20 hover:text-amber-100"+ >+ Switch to Architecture+ </Button>+ )}+ {onLoadAll && (+ <Button+ size="sm"+ variant="ghost"+ onClick={onLoadAll}+ className="h-7 px-2 text-[11px] text-amber-200 hover:bg-amber-500/20 hover:text-amber-100"+ >+ Load all+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.tsindex da288e38f..c02d974ae 100644--- a/packages/ui/src/graph/index.ts+++ b/packages/ui/src/graph/index.ts@@ -7,6 +7,9 @@ export * from "./graph-community-panel.js";export * from "./graph-inspection-panel.js";export * from "./path-finder-panel.js";export * from "./centrality-leaderboard.js";+export * from "./node-badges.js";+export * from "./graph-context-drawer.js";+export * from "./graph-truncation-banner.js";export * from "./graph-flow.js";export * from "./context.js";export * from "./elk-layout.js";diff --git a/packages/ui/src/graph/node-badges.tsx b/packages/ui/src/graph/node-badges.tsxnew file mode 100644index 000000000..a4283bec9--- /dev/null+++ b/packages/ui/src/graph/node-badges.tsx@@ -0,0 +1,99 @@+"use client";++/**+ * NodeBadges — single source of truth for signal badge rendering.+ *+ * Used by the tooltip, the context drawer, the legend hint, and any future+ * surface that needs to communicate "this file is hot / dead / documented /+ * decision-anchored / entry-point / test" in a compact row of chips.+ *+ * Accepts a loose signals object so callers can pass in either a Sigma node+ * attribute bag, a raw backend GraphNode, or a hand-rolled subset.+ */++import { BookOpen, FlaskConical, Flame, Skull, Stamp, Zap } from "lucide-react";+import { cn } from "../lib/cn";++export interface NodeSignalInput {+ isHotspot?: boolean | null | undefined;+ isDead?: boolean | null | undefined;+ hasDoc?: boolean | null | undefined;+ hasDecision?: boolean | null | undefined;+ isEntryPoint?: boolean | null | undefined;+ isTest?: boolean | null | undefined;+}++export interface BadgeDef {+ key: keyof NodeSignalInput;+ label: string;+ Icon: typeof Flame;+ /** Tailwind palette segments — kept here so the canvas-side dot renderer+ * in sigma/* can stay in sync via the `BADGE_COLORS` export below. */+ tone: "danger" | "warn" | "success" | "info" | "accent" | "neutral";+}++export const BADGE_DEFS: readonly BadgeDef[] = [+ { key: "isHotspot", label: "Hotspot", Icon: Flame, tone: "danger" },+ { key: "isDead", label: "Dead", Icon: Skull, tone: "neutral" },+ { key: "hasDecision", label: "Decision", Icon: Stamp, tone: "warn" },+ { key: "hasDoc", label: "Documented", Icon: BookOpen, tone: "success" },+ { key: "isEntryPoint", label: "Entry", Icon: Zap, tone: "accent" },+ { key: "isTest", label: "Test", Icon: FlaskConical, tone: "info" },+] as const;++/** Hex colors mirrored on the Sigma canvas dot renderer (see sigma-canvas). */+export const BADGE_COLORS: Record<BadgeDef["tone"], string> = {+ danger: "#ef4444",+ warn: "#f59520",+ success: "#22c55e",+ info: "#a78bfa",+ accent: "#60a5fa",+ neutral: "#94a3b8",+};++const TONE_CLASSES: Record<BadgeDef["tone"], string> = {+ danger: "bg-red-500/10 text-red-400",+ warn: "bg-amber-500/10 text-amber-400",+ success: "bg-green-500/10 text-green-400",+ info: "bg-purple-500/10 text-purple-400",+ accent: "bg-sky-500/10 text-sky-400",+ neutral: "bg-slate-500/10 text-slate-400",+};++export interface NodeBadgesProps {+ signals: NodeSignalInput;+ /** When omitted, all true signals render. Pass to filter (e.g. drawer-only). */+ only?: Array<BadgeDef["key"]>;+ size?: "xs" | "sm";+ className?: string;+}++export function NodeBadges({ signals, only, size = "xs", className }: NodeBadgesProps) {+ const defs = only+ ? BADGE_DEFS.filter((d) => only.includes(d.key))+ : BADGE_DEFS;+ const active = defs.filter((d) => Boolean(signals[d.key]));+ if (active.length === 0) return null;++ const sizeClass =+ size === "sm" ? "text-[11px] px-2 py-0.5" : "text-[10px] px-1.5 py-0.5";+ const iconSize = size === "sm" ? "w-3 h-3" : "w-2.5 h-2.5";++ return (+ <div className={cn("inline-flex flex-wrap items-center gap-1", className)}>+ {active.map(({ key, label, Icon, tone }) => (+ <span+ key={key}+ className={cn(+ "inline-flex items-center gap-1 rounded-md font-medium",+ TONE_CLASSES[tone],+ sizeClass,+ )}+ >+ <Icon className={iconSize} />+ {label}+ </span>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.tsindex b22c192e1..4dea22acc 100644--- a/packages/ui/src/graph/sigma/graphology-adapter.ts+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts@@ -159,12 +159,25 @@ export function fileGraphToGraphology(originalColor: color,};- if (options?.signals?.hotNodeIds?.has(node.node_id)) {+ // Signal data may come from two sources: explicit overlay sets+ // (legacy unified-graph flow) or enriched node payloads from Phase A.+ // We OR them so adapters work with both backends.+ if (+ node.is_hotspot ||+ options?.signals?.hotNodeIds?.has(node.node_id)+ ) {attrs.isHotspot = true;}- if (options?.signals?.deadNodeIds?.has(node.node_id)) {+ if (+ node.is_dead ||+ options?.signals?.deadNodeIds?.has(node.node_id)+ ) {attrs.isDead = true;}+ attrs.churnPercentile = node.churn_percentile ?? null;+ attrs.deadConfidence = node.dead_confidence ?? null;+ attrs.hasDecision = node.has_decision ?? false;+ attrs.primaryOwner = node.primary_owner ?? null;result.addNode(node.node_id, attrs);}diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.tsindex c8ef1f728..2010606e5 100644--- a/packages/ui/src/graph/sigma/types.ts+++ b/packages/ui/src/graph/sigma/types.ts@@ -41,6 +41,12 @@ export interface SigmaNodeAttributes {isDead?: boolean | undefined;commitCount?: number | undefined;+ // Cross-link signals from enriched backend payloads+ churnPercentile?: number | null | undefined;+ deadConfidence?: number | null | undefined;+ hasDecision?: boolean | undefined;+ primaryOwner?: string | null | undefined;+// Interaction state (mutated by reducers at render time)hidden?: boolean | undefined;zIndex?: number | undefined;diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.tsindex d2112e6b4..0145025e3 100644--- a/packages/ui/src/graph/sigma/use-sigma.ts+++ b/packages/ui/src/graph/sigma/use-sigma.ts@@ -183,6 +183,9 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {}if (attrs.isDead) color = desaturateColor(color, 0.6);if (attrs.isHotspot) color = tintColor(color, "#f97316", 0.4);+ // Decision-anchored files get a subtle amber tint so they're+ // discoverable on the canvas without dominating it.+ if (attrs.hasDecision) color = tintColor(color, "#f59e0b", 0.25);if (attrs.color === color) return attrs;return { ...attrs, color };},diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxindex 5e39ad313..e03529eb5 100644--- a/packages/web/src/app/repos/[id]/graph/page.tsx+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -1,12 +1,12 @@"use client";-import { use, useCallback, useMemo, useState } from "react";+import { use, useCallback, useState } from "react";import useSWR from "swr";import { useQueryState } from "nuqs";import { useSearchParams } from "next/navigation";import { GraphFlow } from "@/components/graph/graph-flow";import { GraphDocPanel } from "@/components/graph/graph-doc-panel";-import { CentralityLeaderboard, type CentralityNode } from "@repowise-dev/ui/graph/centrality-leaderboard";+import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";import { getGraph } from "@/lib/api/graph";import type { GraphExportResponse } from "@/lib/api/types";@@ -35,17 +35,6 @@ export default function GraphPage({{ revalidateOnFocus: false, revalidateOnReconnect: false },);- const centralityNodes: CentralityNode[] = useMemo(() => {- if (!graphData) return [];- return graphData.nodes.map((n) => ({- node_id: n.node_id,- label: n.node_id.split("/").slice(-1)[0],- pagerank: n.pagerank,- betweenness: n.betweenness,- language: n.language,- }));- }, [graphData]);-// Click a file node → open doc panelconst handleNodeClick = useCallback((nodeId: string, nodeType: string) => {@@ -68,6 +57,12 @@ export default function GraphPage({[setSelectedNode],);+ // When the community panel opens from the legend, dismiss the doc panel+ // so the two never stack on the right rail. Single-sidebar UX.+ const handleCommunityPanelOpen = useCallback(() => {+ setDocNodeId(null);+ }, []);+return (<div className="flex flex-col h-full">{/* Header */}@@ -80,6 +75,22 @@ export default function GraphPage({</p></div>+ {/* Truncation banner — shown when the server capped the full graph */}+ {graphData?.truncated && graphData.total_node_count != null && (+ <div className="shrink-0 px-4 sm:px-6 pt-3">+ <GraphTruncationBanner+ shown={graphData.nodes.length}+ total={graphData.total_node_count}+ onSwitchToArchitecture={() => {+ const url = new URL(window.location.href);+ url.searchParams.set("viewMode", "architecture");+ window.history.replaceState({}, "", url.toString());+ window.location.reload();+ }}+ />+ </div>+ )}+{/* Graph area */}<div className="flex-1 overflow-hidden p-3"><div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">@@ -89,9 +100,10 @@ export default function GraphPage({initialSelectedNode={initialNode}onNodeClick={handleNodeClick}onNodeViewDocs={handleNodeViewDocs}+ onCommunityPanelOpen={handleCommunityPanelOpen}/>- {/* Doc panel — shows on file click */}+ {/* Doc panel — shows on file click. Single right-rail surface. */}{docNodeId && (<GraphDocPanelrepoId={repoId}@@ -99,19 +111,6 @@ export default function GraphPage({onClose={() => setDocNodeId(null)}/>)}-- {/* Centrality leaderboard — collapsible right rail */}- {centralityNodes.length > 0 && !docNodeId && (- <div className="absolute top-3 right-3 z-10 max-h-[calc(100%-1.5rem)] flex">- <CentralityLeaderboard- nodes={centralityNodes}- onSelect={(n) => {- setDocNodeId(n.node_id);- void setSelectedNode(n.node_id);- }}- />- </div>- )}</div></div></div>diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsxindex dde85afb3..be60e9dfe 100644--- a/packages/web/src/components/graph/graph-flow.tsx+++ b/packages/web/src/components/graph/graph-flow.tsx@@ -31,9 +31,20 @@ export interface GraphFlowProps {initialSelectedNode?: string | null;onNodeClick?: GraphFlowShellProps["onNodeClick"];onNodeViewDocs?: GraphFlowShellProps["onNodeViewDocs"];+ /** Fired when the community detail panel opens (legend click).+ * Page uses this to dismiss the doc panel so the right rail stays+ * to a single surface. */+ onCommunityPanelOpen?: (communityId: number) => void;}-export function GraphFlow({ repoId, initialViewMode, initialSelectedNode, onNodeClick, onNodeViewDocs }: GraphFlowProps) {+export function GraphFlow({+ repoId,+ initialViewMode,+ initialSelectedNode,+ onNodeClick,+ onNodeViewDocs,+ onCommunityPanelOpen,+}: GraphFlowProps) {const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "module");const [modulePath, setModulePath] = useState<string[]>([]);const [hasExpandedModules, setHasExpandedModules] = useState(false);@@ -83,6 +94,7 @@ export function GraphFlow({ repoId, initialViewMode, initialSelectedNode, onNodeonExpandedModulesChange={(expanded) => setHasExpandedModules(expanded.size > 0)}onNodeClick={onNodeClick}onNodeViewDocs={onNodeViewDocs}+ onCommunityPanelOpen={onCommunityPanelOpen}renderPathFinder={(props) => (<PathFinderPanelrepoId={repoId}diff --git a/packages/web/src/lib/api/graph.ts b/packages/web/src/lib/api/graph.tsindex e90638eb1..707f49fd2 100644--- a/packages/web/src/lib/api/graph.ts+++ b/packages/web/src/lib/api/graph.ts@@ -1,5 +1,6 @@import { apiGet } from "./client";import type {+ ArchitectureGraphResponse,CallersCalleesResponse,CommunityDetailResponse,CommunitySummaryItem,@@ -50,6 +51,21 @@ export async function getArchitectureGraph(repoId: string): Promise<GraphExportRreturn apiGet<GraphExportResponse>(`/api/graph/${repoId}/entry-points`);}+/**+ * Community super-node view: one node per detected community, with+ * cross-community edges. Endpoint introduced in Phase A of the graph+ * UX overhaul; rendering surface is incremental and the legacy+ * entry-point view above remains the default until adapter support lands.+ */+export async function getArchitectureCommunityGraph(+ repoId: string,+ minMembers = 2,+): Promise<ArchitectureGraphResponse> {+ return apiGet<ArchitectureGraphResponse>(`/api/graph/${repoId}/architecture`, {+ min_members: minMembers,+ });+}+export async function getDeadCodeGraph(repoId: string): Promise<DeadCodeGraphResponse> {return apiGet<DeadCodeGraphResponse>(`/api/graph/${repoId}/dead-nodes`);}diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.tsindex b849f5a60..7c94fecc1 100644--- a/packages/web/src/lib/api/types.ts+++ b/packages/web/src/lib/api/types.ts@@ -187,6 +187,13 @@ export interface GraphNodeResponse {is_test: boolean;is_entry_point: boolean;has_doc: boolean;+ // Phase A: cross-link signals (all optional for back-compat)+ is_hotspot?: boolean;+ churn_percentile?: number | null;+ is_dead?: boolean;+ dead_confidence?: number | null;+ has_decision?: boolean;+ primary_owner?: string | null;}export interface GraphEdgeResponse {@@ -198,6 +205,35 @@ export interface GraphEdgeResponse {export interface GraphExportResponse {nodes: GraphNodeResponse[];links: GraphEdgeResponse[];+ /** Server set this true when the response was capped to top-N by PageRank. */+ truncated?: boolean;+ total_node_count?: number;+}++// Architecture super-node graph (Phase A)+export interface ArchitectureNodeResponse {+ community_id: number;+ label: string;+ cohesion: number;+ member_count: number;+ top_file: string;+ avg_pagerank: number;+ hotspot_count: number;+ dead_count: number;+ has_decision: boolean;+ doc_coverage_pct: number;+ languages: string[];+}++export interface ArchitectureEdgeResponse {+ source: number;+ target: number;+ edge_count: number;+}++export interface ArchitectureGraphResponse {+ nodes: ArchitectureNodeResponse[];+ edges: ArchitectureEdgeResponse[];}export interface GraphPathResponse {diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.pyindex 32f6589d6..77a94e88f 100644--- a/tests/unit/server/test_graph.py+++ b/tests/unit/server/test_graph.py@@ -2,11 +2,14 @@from __future__ import annotations+import json+import pytestfrom httpx import AsyncClientfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_session+from repowise.core.persistence.models import DeadCodeFinding, DecisionRecordfrom tests.unit.server.conftest import create_test_repo@@ -115,3 +118,128 @@ async def test_dependency_path_no_path(client: AsyncClient, app) -> None:assert ctx["reverse_path"]["exists"] is True # main -> utils existsassert ctx["disconnected"] is Falseassert "suggestion" in ctx+++# ---------------------------------------------------------------------------+# Cross-link signal enrichment (Phase A)+# ---------------------------------------------------------------------------+++async def _attach_signals(session_factory, repo_id: str) -> None:+ """Attach hotspot, dead-code, and decision signals to src/main.py."""+ async with get_session(session_factory) as session:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path="src/main.py",+ is_hotspot=True,+ churn_percentile=0.95,+ primary_owner_name="Alice",+ commit_count_30d=10,+ commit_count_90d=20,+ )+ session.add(+ DeadCodeFinding(+ repository_id=repo_id,+ file_path="src/utils.py",+ kind="unreachable_file",+ status="open",+ confidence=0.9,+ )+ )+ session.add(+ DecisionRecord(+ repository_id=repo_id,+ title="Adopt FastAPI",+ status="active",+ source="cli",+ affected_files_json=json.dumps(["src/main.py"]),+ )+ )+ await session.flush()+++async def test_export_graph_carries_cross_link_signals(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])+ await _attach_signals(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}")+ assert resp.status_code == 200+ data = resp.json()+ assert data["truncated"] is False+ assert data["total_node_count"] == 2++ by_id = {n["node_id"]: n for n in data["nodes"]}+ main = by_id["src/main.py"]+ utils = by_id["src/utils.py"]++ assert main["is_hotspot"] is True+ assert main["churn_percentile"] == pytest.approx(0.95)+ assert main["primary_owner"] == "Alice"+ assert main["has_decision"] is True+ assert main["is_dead"] is False++ assert utils["is_dead"] is True+ assert utils["dead_confidence"] == pytest.approx(0.9)+ assert utils["is_hotspot"] is False+ assert utils["has_decision"] is False+++async def test_export_graph_truncation(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}", params={"limit": 1})+ assert resp.status_code == 200+ data = resp.json()+ assert data["truncated"] is True+ assert data["total_node_count"] == 2+ assert len(data["nodes"]) == 1+ # Top-N by PageRank: main.py (0.8) outranks utils.py (0.3)+ assert data["nodes"][0]["node_id"] == "src/main.py"+ # Edges pointing to filtered-out nodes must be dropped+ assert data["links"] == []+++async def test_architecture_graph(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])+ await _attach_signals(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}/architecture")+ assert resp.status_code == 200+ data = resp.json()++ # Both seeded nodes share community 0+ assert len(data["nodes"]) == 1+ super_node = data["nodes"][0]+ assert super_node["community_id"] == 0+ assert super_node["member_count"] == 2+ assert super_node["hotspot_count"] == 1+ assert super_node["dead_count"] == 1+ assert super_node["has_decision"] is True+ assert "python" in super_node["languages"]+ # Same-community edges are collapsed away+ assert data["edges"] == []+++async def test_module_graph_aggregates_signals(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])+ await _attach_signals(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}/modules")+ assert resp.status_code == 200+ data = resp.json()+ by_id = {m["module_id"]: m for m in data["nodes"]}+ src = by_id["src"]+ assert src["file_count"] == 2+ assert src["hotspot_count"] == 1+ assert src["dead_count"] == 1+ assert src["has_decision"] is True+ assert src["primary_owner"] == "Alice"