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
Review fixes, health score breakdown, module grid collapse (#148)
Swati Ahuja32078c74620b
diff --git a/.github/workflows/publish-internal.yml b/.github/workflows/publish-internal.ymlindex 4b3d6bdc8..ec30126a5 100644--- a/.github/workflows/publish-internal.yml+++ b/.github/workflows/publish-internal.yml@@ -54,6 +54,7 @@ jobs:run: |npm run type-check --workspace @repowise-dev/typesnpm run type-check --workspace @repowise-dev/ui+ npm run test --workspace @repowise-dev/typesnpm run test --workspace @repowise-dev/ui- name: Compute prerelease versiondiff --git a/.gitignore b/.gitignoreindex ba6f582f8..ab475a8e9 100644--- a/.gitignore+++ b/.gitignore@@ -26,7 +26,7 @@ share/python-wheels/venv/ENV/env/-+/papers/# uv.uv/diff --git a/package-lock.json b/package-lock.jsonindex 451d931c6..e1983c29a 100644--- a/package-lock.json+++ b/package-lock.json@@ -4135,6 +4135,15 @@"integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==","license": "MIT"},+ "node_modules/@sigma/edge-curve": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@sigma/edge-curve/-/edge-curve-3.1.0.tgz",+ "integrity": "sha512-OFWkfAXEsm+X8l1K4K49cC0psB0gQ+gqxKA08HG5piNPdzrDZ5gG9Gza6htZ5AirOVwd/4/uq/gPpD5En+H+3Q==",+ "license": "MIT",+ "peerDependencies": {+ "sigma": ">=3.0.0-beta.10"+ }+ },"node_modules/@standard-schema/spec": {"version": "1.0.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",@@ -8166,6 +8175,15 @@"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==","license": "MIT"},+ "node_modules/events": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.x"+ }+ },"node_modules/expect-type": {"version": "1.3.0","resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",@@ -8630,6 +8648,57 @@"dev": true,"license": "ISC"},+ "node_modules/graphology": {+ "version": "0.26.0",+ "resolved": "https://registry.npmjs.org/graphology/-/graphology-0.26.0.tgz",+ "integrity": "sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==",+ "license": "MIT",+ "dependencies": {+ "events": "^3.3.0"+ },+ "peerDependencies": {+ "graphology-types": ">=0.24.0"+ }+ },+ "node_modules/graphology-layout-forceatlas2": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/graphology-layout-forceatlas2/-/graphology-layout-forceatlas2-0.10.1.tgz",+ "integrity": "sha512-ogzBeF1FvWzjkikrIFwxhlZXvD2+wlY54lqhsrWprcdPjopM2J9HoMweUmIgwaTvY4bUYVimpSsOdvDv1gPRFQ==",+ "license": "MIT",+ "dependencies": {+ "graphology-utils": "^2.1.0"+ },+ "peerDependencies": {+ "graphology-types": ">=0.19.0"+ }+ },+ "node_modules/graphology-layout-noverlap": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/graphology-layout-noverlap/-/graphology-layout-noverlap-0.4.2.tgz",+ "integrity": "sha512-13WwZSx96zim6l1dfZONcqLh3oqyRcjIBsqz2c2iJ3ohgs3605IDWjldH41Gnhh462xGB1j6VGmuGhZ2FKISXA==",+ "license": "MIT",+ "dependencies": {+ "graphology-utils": "^2.3.0"+ },+ "peerDependencies": {+ "graphology-types": ">=0.19.0"+ }+ },+ "node_modules/graphology-types": {+ "version": "0.24.8",+ "resolved": "https://registry.npmjs.org/graphology-types/-/graphology-types-0.24.8.tgz",+ "integrity": "sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q==",+ "license": "MIT"+ },+ "node_modules/graphology-utils": {+ "version": "2.5.2",+ "resolved": "https://registry.npmjs.org/graphology-utils/-/graphology-utils-2.5.2.tgz",+ "integrity": "sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==",+ "license": "MIT",+ "peerDependencies": {+ "graphology-types": ">=0.23.0"+ }+ },"node_modules/hachure-fill": {"version": "0.5.2","resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",@@ -13013,6 +13082,16 @@"dev": true,"license": "ISC"},+ "node_modules/sigma": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/sigma/-/sigma-3.0.3.tgz",+ "integrity": "sha512-5H0zFlx6/NTQpqBg4Rm569ZOpnBOXMaS25UQThIWMU3XyzI5AhmorK/gnl87BvJBLhQd0tW4C0LIp3enWzMoNw==",+ "license": "MIT",+ "dependencies": {+ "events": "^3.3.0",+ "graphology-utils": "^2.5.2"+ }+ },"node_modules/sonner": {"version": "2.0.7","resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",@@ -14655,6 +14734,7 @@"@radix-ui/react-tabs": "^1.1.13","@radix-ui/react-tooltip": "^1.2.8","@repowise-dev/types": "*",+ "@sigma/edge-curve": "^3.1.0","@xyflow/react": "^12.10.2","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -14662,11 +14742,16 @@"d3-hierarchy": "^3.1.2","framer-motion": "^11.11.0","fuse.js": "^7.0.0",+ "graphology": "^0.26.0",+ "graphology-layout-forceatlas2": "^0.10.1",+ "graphology-layout-noverlap": "^0.4.2",+ "graphology-types": "^0.24.8","lucide-react": "^1.7.0","mermaid": "^11.4.0","react-markdown": "^10.1.0","recharts": "^3.8.1","remark-gfm": "^4.0.1",+ "sigma": "^3.0.3","tailwind-merge": "^3.5.0"},"devDependencies": {diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.pyindex 3f10fb2ba..b9c3852f9 100644--- a/packages/core/src/repowise/core/analysis/communities.py+++ b/packages/core/src/repowise/core/analysis/communities.py@@ -101,10 +101,26 @@ def _suppress_graspologic_output():# ---------------------------------------------------------------------------+def _directory_fallback(nodes: list[str]) -> dict[str, int]:+ """Group nodes by first-level directory when graph-based community detection fails."""+ dir_to_id: dict[str, int] = {}+ result: dict[str, int] = {}+ next_id = 1+ for path in nodes:+ parts = path.split("/")+ dir_key = parts[0] if len(parts) > 1 else "__root__"+ if dir_key not in dir_to_id:+ dir_to_id[dir_key] = next_id+ next_id += 1+ result[path] = dir_to_id[dir_key]+ return result++def _partition(G: nx.Graph) -> tuple[dict, str]:"""Run community detection. Returns ({node: community_id}, algorithm_name).- Tries Leiden (graspologic) first, falls back to Louvain (networkx).+ Tries Leiden (graspologic) first, falls back to Louvain (networkx),+ then to directory-based grouping as a last resort."""try:from graspologic.partition import leiden@@ -116,13 +132,19 @@ def _partition(G: nx.Graph) -> tuple[dict, str]:pass# Fallback: networkx Louvain- kwargs: dict = {"seed": 42, "threshold": 1e-4}- if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:- kwargs["max_level"] = 10-- communities = nx.community.louvain_communities(G, **kwargs)- assignment = {node: cid for cid, nodes in enumerate(communities) for node in nodes}- return assignment, "louvain"+ try:+ kwargs: dict = {"seed": 42, "threshold": 1e-4}+ if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:+ kwargs["max_level"] = 10++ communities = nx.community.louvain_communities(G, **kwargs)+ assignment = {node: cid for cid, nodes in enumerate(communities) for node in nodes}+ return assignment, "louvain"+ except Exception as exc:+ log.warning("louvain_failed_using_directory_fallback", error=str(exc))++ # Final fallback: directory-based grouping+ return _directory_fallback(list(G.nodes())), "directory"# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.pyindex 632d8ad94..dd9faeed9 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py@@ -981,7 +981,7 @@ def _add_rust_router_edges(# files are never imported via PHP/JS imports, so the static graph reports# ``in_degree=0`` and the dead-code analyzer flags them as unreachable.#-# We attach an ``external:typo3-core`` synthetic source to each convention+# We attach a ``framework:typo3-core`` synthetic source to each convention# file present in an extension. ``Configuration/JavaScriptModules.php`` is# also parsed to add edges to the JS modules it registers (CKEditor plugins,# backend modules, etc.).@@ -1155,7 +1155,7 @@ def _add_typo3_edges("""Add framework edges for each detected TYPO3 extension.Edges added:- - ``external:typo3-core`` → each convention file present in the extension.+ - ``framework:typo3-core`` → each convention file present in the extension.- ``Configuration/JavaScriptModules.php`` → each JS file it registers."""count = 0diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.pyindex e068ec4db..9b0c80077 100644--- a/packages/core/src/repowise/core/ingestion/graph.py+++ b/packages/core/src/repowise/core/ingestion/graph.py@@ -436,10 +436,12 @@ class GraphBuilder:async def persist(self, db_path: Path, repo_id: str) -> None:"""Persist the graph to an SQLite database."""import aiosqlite+ import sqlite3pr = self.pagerank()bc = self.betweenness_centrality()scc_map = self._build_scc_map()+ cd = self.community_detection()g = self.graph()async with aiosqlite.connect(db_path) as db:@@ -453,6 +455,7 @@ class GraphBuilder:pagerank REAL,betweenness REAL,scc_id INTEGER,+ community_id INTEGER DEFAULT 0,PRIMARY KEY (repo_id, path));CREATE TABLE IF NOT EXISTS graph_edges (@@ -464,6 +467,13 @@ class GraphBuilder:);""")+ try:+ await db.execute(+ "ALTER TABLE graph_nodes ADD COLUMN community_id INTEGER DEFAULT 0"+ )+ except sqlite3.OperationalError:+ pass+node_rows = [(repo_id,@@ -474,11 +484,12 @@ class GraphBuilder:pr.get(path, 0.0),bc.get(path, 0.0),scc_map.get(path, 0),+ cd.get(path, cd.get(data.get("file_path", ""), 0)),)for path, data in g.nodes(data=True)]await db.executemany(- "INSERT OR REPLACE INTO graph_nodes VALUES (?,?,?,?,?,?,?,?)",+ "INSERT OR REPLACE INTO graph_nodes VALUES (?,?,?,?,?,?,?,?,?)",node_rows,)diff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.pyindex bc8e0c4f7..fb0671fb0 100644--- a/packages/server/src/repowise/server/routers/graph.py+++ b/packages/server/src/repowise/server/routers/graph.py@@ -59,6 +59,11 @@ router = APIRouter()+def _escape_like(s: str) -> str:+ """Escape special characters for SQL LIKE patterns."""+ return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")++def _parse_imported_names(raw: str | None) -> list[str]:if not raw:return []@@ -93,11 +98,32 @@ async def module_graph(node_result = await session.execute(select(GraphNode).where(GraphNode.repository_id == repo_id))nodes = node_result.scalars().all()- # Group nodes by first path segment+ # Group nodes by first path segment, detecting monorepo roots+ first_level: dict[str, list[GraphNode]] = {}+ for n in nodes:+ parts = n.node_id.split("/")+ seg = parts[0] if len(parts) > 1 else n.node_id+ first_level.setdefault(seg, []).append(n)++ total = len(nodes) or 1+ monorepo_roots: set[str] = set()+ for seg, seg_nodes in first_level.items():+ # When a single top-level directory contains >70% of all files, treat it+ # as a monorepo root and group by the *second* path segment instead.+ # Threshold chosen empirically: catches src/-heavy repos without+ # splitting balanced monorepos like packages/a + packages/b (each ~50%).+ if len(seg_nodes) / total > 0.70:+ monorepo_roots.add(seg)+modules: dict[str, list[GraphNode]] = {}for n in nodes:parts = n.node_id.split("/")- module = parts[0] if len(parts) > 1 else n.node_id+ if len(parts) <= 1:+ module = n.node_id+ elif parts[0] in monorepo_roots and len(parts) > 2:+ module = parts[0] + "/" + parts[1]+ else:+ module = parts[0]modules.setdefault(module, []).append(n)# Fetch page confidence for doc coverage@@ -602,7 +628,7 @@ async def search_nodes(select(GraphNode).where(GraphNode.repository_id == repo_id,- GraphNode.node_id.ilike(f"%{q}%"),+ GraphNode.node_id.ilike(f"%{_escape_like(q)}%"),).order_by(GraphNode.symbol_count.desc(), GraphNode.pagerank.desc()).limit(limit)diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex 9b6e4fe75..eae476637 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -26,6 +26,9 @@ from repowise.server.schemas import (WorkspaceContractsResponse,WorkspaceContractSummary,WorkspaceCrossRepoSummary,+ WorkspaceGraphEdge,+ WorkspaceGraphNode,+ WorkspaceGraphResponse,WorkspaceRepoEntry,WorkspaceResponse,)@@ -46,6 +49,32 @@ def _require_workspace(ws_config: object) -> None:raise HTTPException(status_code=404, detail="Not running in workspace mode")+def _query_top_language(db_path: Path) -> str:+ """Return the most common language across graph_nodes in a repo's wiki.db."""+ if not db_path.exists():+ return "unknown"+ try:+ with sqlite3.connect(str(db_path)) as conn:+ row = conn.execute(+ "SELECT language, COUNT(*) AS cnt FROM graph_nodes "+ "WHERE language IS NOT NULL AND language != '' "+ "GROUP BY language ORDER BY cnt DESC LIMIT 1"+ ).fetchone()+ return row[0] if row else "unknown"+ except Exception:+ return "unknown"+++def _compute_health_score(file_count: int, doc_coverage_pct: float, hotspot_count: int) -> int:+ """Derive a 0-100 health score from available repo metrics."""+ if file_count == 0:+ return 0+ coverage_component = doc_coverage_pct * 0.6+ hotspot_ratio = min(hotspot_count / max(file_count, 1), 1.0)+ hotspot_component = (1.0 - hotspot_ratio) * 100 * 0.4+ return max(0, min(100, round(coverage_component + hotspot_component)))++def _query_repo_stats(db_path: Path) -> dict:"""Query basic stats from a repo's wiki.db using raw sqlite3.@@ -299,3 +328,108 @@ async def get_co_changes(],total=total,)+++# ---------------------------------------------------------------------------+# GET /api/workspace/graph+# ---------------------------------------------------------------------------++[email protected]("/graph", response_model=WorkspaceGraphResponse)+async def get_workspace_graph(+ request: Request,+ ws_config=Depends(get_workspace_config),+ enricher=Depends(get_cross_repo_enricher),+):+ """Cross-repo graph: repos as mega-nodes, contracts/co-changes as edges."""+ _require_workspace(ws_config)++ ws_root = getattr(request.app.state, "workspace_root", None)+ ws_root_path = Path(ws_root) if ws_root else None++ # Build nodes from repo metadata+ repo_id_map: dict[str, str] = {} # alias → repo_id+ nodes: list[WorkspaceGraphNode] = []+ for r in ws_config.repos:+ stats: dict = {}+ top_language = "unknown"+ if ws_root_path:+ repo_path = (ws_root_path / r.path).resolve()+ db_path = repo_path / ".repowise" / "wiki.db"+ stats = _query_repo_stats(db_path)+ top_language = _query_top_language(db_path)+ rid = stats.get("repo_id") or r.alias+ repo_id_map[r.alias] = rid+ nodes.append(+ WorkspaceGraphNode(+ repo_id=rid,+ name=r.alias,+ file_count=stats.get("file_count", 0),+ coverage_pct=stats.get("doc_coverage_pct", 0.0),+ health_score=_compute_health_score(+ stats.get("file_count", 0),+ stats.get("doc_coverage_pct", 0.0),+ stats.get("hotspot_count", 0),+ ),+ top_language=top_language,+ )+ )++ # Build edges+ edges: list[WorkspaceGraphEdge] = []+ seen_edges: set[tuple[str, str, str]] = set()++ if enricher is not None:+ # Contract-based edges: each link connects two repos+ links = list(getattr(enricher, "_contract_links", []))+ for lk in links:+ p_repo = lk.get("provider_repo", "")+ c_repo = lk.get("consumer_repo", "")+ if not p_repo or not c_repo or p_repo == c_repo:+ continue+ p_id = repo_id_map.get(p_repo, p_repo)+ c_id = repo_id_map.get(c_repo, c_repo)+ key = (min(p_id, c_id), max(p_id, c_id), "contract")+ if key in seen_edges:+ continue+ seen_edges.add(key)+ edges.append(+ WorkspaceGraphEdge(+ source=p_id,+ target=c_id,+ type="contract",+ strength=lk.get("confidence", 0.8),+ label=lk.get("contract_type"),+ )+ )++ # Co-change-based edges: aggregate per repo-pair+ co_changes = list(getattr(enricher, "_co_changes", []))+ pair_strengths: dict[tuple[str, str], list[float]] = {}+ for cc in co_changes:+ s_repo = cc.get("source_repo", "")+ t_repo = cc.get("target_repo", "")+ if not s_repo or not t_repo or s_repo == t_repo:+ continue+ s_id = repo_id_map.get(s_repo, s_repo)+ t_id = repo_id_map.get(t_repo, t_repo)+ pair_key = (min(s_id, t_id), max(s_id, t_id))+ pair_strengths.setdefault(pair_key, []).append(cc.get("strength", 0.0))++ for (src, tgt), strengths in pair_strengths.items():+ key = (src, tgt, "co_change")+ if key in seen_edges:+ continue+ seen_edges.add(key)+ avg_strength = sum(strengths) / len(strengths)+ edges.append(+ WorkspaceGraphEdge(+ source=src,+ target=tgt,+ type="co_change",+ strength=round(avg_strength, 3),+ label=f"{len(strengths)} co-changes",+ )+ )++ return WorkspaceGraphResponse(nodes=nodes, edges=edges)diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.pyindex 35fe75b22..f3cb64699 100644--- a/packages/server/src/repowise/server/schemas.py+++ b/packages/server/src/repowise/server/schemas.py@@ -1009,3 +1009,25 @@ class WorkspaceCoChangeEntry(BaseModel):class WorkspaceCoChangesResponse(BaseModel):co_changes: list[WorkspaceCoChangeEntry]total: int+++class WorkspaceGraphNode(BaseModel):+ repo_id: str+ name: str+ file_count: int = 0+ coverage_pct: float = 0.0+ health_score: int = 0+ top_language: str = "unknown"+++class WorkspaceGraphEdge(BaseModel):+ source: str+ target: str+ type: str # "contract" or "co_change"+ strength: float = 0.0+ label: str | None = None+++class WorkspaceGraphResponse(BaseModel):+ nodes: list[WorkspaceGraphNode] = []+ edges: list[WorkspaceGraphEdge] = []diff --git a/packages/types/__tests__/contracts.test.ts b/packages/types/__tests__/contracts.test.tsindex 6a8420fbb..c9925969a 100644--- a/packages/types/__tests__/contracts.test.ts+++ b/packages/types/__tests__/contracts.test.ts@@ -147,9 +147,9 @@ describe("Heritage relation shape", () => {});describe("SecurityFinding canonical shape", () => {- it("severity is the three-literal union widened to string", () => {+ it("severity is the three-literal union with string & {} for autocomplete", () => {expectTypeOf<SecuritySeverity>().toEqualTypeOf<- "high" | "med" | "low" | string+ "high" | "med" | "low" | (string & {})>();});@@ -168,7 +168,7 @@ describe("SecurityFinding canonical shape", () => {});describe("Canonical Hotspot key shape", () => {- it("uses file_path, not path — raw {path} entries must be adapted", () => {+ it("uses file_path, not path — raw {path} entries must be adapted", () => {expectTypeOf<Hotspot>().toHaveProperty("file_path").toEqualTypeOf<string>();// Some downstream backends emit `path`. A `{ path: ... }` object should// NOT satisfy Hotspot; this is the contract that forces an adapter call.diff --git a/packages/types/package.json b/packages/types/package.jsonindex bfdc88c35..ea790c5b3 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -4,6 +4,7 @@"private": true,"description": "Canonical TypeScript data contracts for the Repowise dashboard (packages/web) and downstream consumers of the same engine artifacts.","type": "module",+ "files": ["src"],"main": "./src/index.ts","types": "./src/index.ts","exports": {diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.tsindex 6bd639506..2c97d12ba 100644--- a/packages/types/src/dead-code.ts+++ b/packages/types/src/dead-code.ts@@ -7,7 +7,7 @@* optional so consumer adapters don't lose information when normalising.*/-export type DeadCodeStatus = "open" | "wont_fix" | "deleted" | string;+export type DeadCodeStatus = "open" | "wont_fix" | "deleted" | (string & {});export interface DeadCodeFinding {id: string;diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 62f8c3087..a7dd16a1e 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -57,7 +57,7 @@ export interface DecisionCreateInput {}export interface DecisionStatusUpdate {- status: DecisionStatus | string;+ status: DecisionStatus;superseded_by?: string;}diff --git a/packages/types/src/docs.ts b/packages/types/src/docs.tsindex 4658330b6..6e0f1a48f 100644--- a/packages/types/src/docs.ts+++ b/packages/types/src/docs.ts@@ -7,7 +7,7 @@* adapters cast through the types below before passing data to components.*/-export type FreshnessStatus = "fresh" | "stale" | "outdated" | string;+export type FreshnessStatus = "fresh" | "stale" | "outdated" | (string & {});export interface DocPage {id: string;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 5145ecf47..c62611ae9 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -1,5 +1,5 @@/**- * @repowise-dev/types — canonical TypeScript data contracts for the Repowise+ * @repowise-dev/types — canonical TypeScript data contracts for the Repowise* dashboard (`packages/web`) and any downstream consumer that renders the* same engine artifacts.*diff --git a/packages/types/src/security.ts b/packages/types/src/security.tsindex de4e7554e..13e6453ae 100644--- a/packages/types/src/security.ts+++ b/packages/types/src/security.ts@@ -6,7 +6,7 @@* already used by the OSS web `listSecurityFindings` API client.*/-export type SecuritySeverity = "high" | "med" | "low" | string;+export type SecuritySeverity = "high" | "med" | "low" | (string & {});export interface SecurityFinding {id: number;diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.tsindex 0448887d4..761478537 100644--- a/packages/types/src/symbols.ts+++ b/packages/types/src/symbols.ts@@ -17,9 +17,9 @@ export type SymbolKind =| "module"| "variable"| "type"- | string;+ | (string & {});-export type SymbolVisibility = "public" | "private" | "protected" | string;+export type SymbolVisibility = "public" | "private" | "protected" | (string & {});/** Renamed `CodeSymbol` to avoid shadowing the global `Symbol`. */export interface CodeSymbol {diff --git a/packages/ui/__tests__/graph/constants.test.ts b/packages/ui/__tests__/graph/constants.test.tsnew file mode 100644index 000000000..73d0f4920--- /dev/null+++ b/packages/ui/__tests__/graph/constants.test.ts@@ -0,0 +1,54 @@+import { describe, it, expect } from "vitest";+import {+ getScaledNodeSize,+ EDGE_COLORS,+ COMMUNITY_COLORS,+ getCommunityColor,+ NODE_BASE_SIZES,+} from "../../src/graph/sigma/constants";++describe("getScaledNodeSize", () => {+ it("returns base size for small graphs", () => {+ expect(getScaledNodeSize(6, 100)).toBe(6);+ expect(getScaledNodeSize(10, 500)).toBe(10);+ });++ it("scales down for large graphs", () => {+ const base = NODE_BASE_SIZES.file;+ expect(getScaledNodeSize(base, 1000)).toBeLessThan(base);+ expect(getScaledNodeSize(base, 5000)).toBeLessThan(getScaledNodeSize(base, 1000));+ expect(getScaledNodeSize(base, 15000)).toBeLessThan(getScaledNodeSize(base, 5000));+ });++ it("never returns less than the minimum floor", () => {+ expect(getScaledNodeSize(1, 100000)).toBeGreaterThanOrEqual(1);+ });+});++describe("EDGE_COLORS", () => {+ it("has colors for all edge types", () => {+ const expectedTypes = ["import", "crossCommunity", "internal", "dynamic", "lowConfidence"];+ for (const t of expectedTypes) {+ expect(EDGE_COLORS).toHaveProperty(t);+ expect(EDGE_COLORS[t as keyof typeof EDGE_COLORS]).toMatch(/^#[0-9a-fA-F]{6}$/);+ }+ });+});++describe("COMMUNITY_COLORS", () => {+ it("has 24 colors", () => {+ expect(COMMUNITY_COLORS).toHaveLength(24);+ });++ it("getCommunityColor wraps around correctly", () => {+ expect(getCommunityColor(0)).toBe(COMMUNITY_COLORS[0]);+ expect(getCommunityColor(24)).toBe(COMMUNITY_COLORS[0]);+ expect(getCommunityColor(1)).toBe(COMMUNITY_COLORS[1]);+ });++ it("all entries are valid hex colors", () => {+ for (const c of COMMUNITY_COLORS) {+ expect(c).toMatch(/^#[0-9a-fA-F]{6}$/);+ }+ });+});diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsxindex 42549b53c..df2958a6c 100644--- a/packages/ui/__tests__/graph/graph-flow.test.tsx+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx@@ -2,26 +2,6 @@ import { describe, it, expect, vi } from "vitest";import { render, screen } from "@testing-library/react";import { GraphFlow } from "../../src/graph/graph-flow.js";-// Mock @xyflow/react — the real implementation needs a measured DOM that-// jsdom doesn't provide; we just want to assert the shell composes the-// surrounding chrome correctly.-vi.mock("@xyflow/react", () => ({- ReactFlow: ({ children }: { children?: React.ReactNode }) => (- <div data-testid="react-flow-mock">{children}</div>- ),- ReactFlowProvider: ({ children }: { children?: React.ReactNode }) => <>{children}</>,- MiniMap: () => null,- Controls: () => null,- Background: () => null,- BackgroundVariant: { Dots: "dots" },- useReactFlow: () => ({ getNode: () => undefined, fitView: vi.fn() }),-}));--// elk-layout / use-elk-layout do real DOM work; stub them out.-vi.mock("../../src/graph/use-elk-layout.js", () => ({- useModuleElkLayout: () => ({ nodes: [], edges: [], isLayouting: false }),- useFileElkLayout: () => ({ nodes: [], edges: [], isLayouting: false }),-}));describe("GraphFlow shell", () => {it("renders the empty state when no nodes are layouted", () => {diff --git a/packages/ui/__tests__/graph/graphology-adapter.test.ts b/packages/ui/__tests__/graph/graphology-adapter.test.tsnew file mode 100644index 000000000..fd96de310--- /dev/null+++ b/packages/ui/__tests__/graph/graphology-adapter.test.ts@@ -0,0 +1,133 @@+import { describe, it, expect } from "vitest";+import { fileGraphToGraphology, moduleGraphToGraphology } from "../../src/graph/sigma/graphology-adapter";+import type { GraphExport, GraphNode, GraphLink, ModuleGraph, ModuleNode, ModuleEdge, CommunitySummaryItem } from "@repowise-dev/types/graph";++function makeNode(overrides: Partial<GraphNode> & { node_id: string }): GraphNode {+ return {+ node_type: "file",+ language: "typescript",+ symbol_count: 0,+ pagerank: 0,+ betweenness: 0,+ community_id: 0,+ is_test: false,+ is_entry_point: false,+ has_doc: false,+ ...overrides,+ };+}++function makeFileGraph(+ nodes: GraphNode[] = [],+ links: GraphLink[] = [],+): GraphExport {+ return { nodes, links };+}++function makeModuleGraph(+ nodes: ModuleNode[] = [],+ edges: ModuleEdge[] = [],+): ModuleGraph {+ return { nodes, edges };+}++describe("fileGraphToGraphology", () => {+ it("handles an empty graph", () => {+ const g = fileGraphToGraphology(makeFileGraph());+ expect(g.order).toBe(0);+ expect(g.size).toBe(0);+ });++ it("adds nodes with no edges", () => {+ const g = fileGraphToGraphology(+ makeFileGraph([+ makeNode({+ node_id: "src/app.ts",+ symbol_count: 5,+ pagerank: 0.1,+ betweenness: 0.05,+ is_entry_point: true,+ }),+ ]),+ );+ expect(g.order).toBe(1);+ expect(g.size).toBe(0);+ expect(g.hasNode("src/app.ts")).toBe(true);+ });++ it("adds nodes with community data", () => {+ const g = fileGraphToGraphology(+ makeFileGraph([+ makeNode({+ node_id: "src/a.ts",+ symbol_count: 3,+ pagerank: 0.2,+ betweenness: 0.1,+ community_id: 2,+ has_doc: true,+ }),+ ]),+ );+ const attrs = g.getNodeAttributes("src/a.ts");+ expect(attrs.communityId).toBe(2);+ expect(attrs.hasDoc).toBe(true);+ });++ it("handles duplicate edges gracefully", () => {+ const nodes = [+ makeNode({ node_id: "a" }),+ makeNode({ node_id: "b" }),+ ];+ const links: GraphLink[] = [+ { source: "a", target: "b", imported_names: ["foo"] },+ { source: "a", target: "b", imported_names: ["bar"] },+ ];+ const g = fileGraphToGraphology(makeFileGraph(nodes, links));+ expect(g.order).toBe(2);+ expect(g.size).toBe(1);+ });++ it("handles nodes with missing optional fields", () => {+ const g = fileGraphToGraphology(+ makeFileGraph([makeNode({ node_id: "src/minimal.ts" })]),+ );+ expect(g.order).toBe(1);+ const attrs = g.getNodeAttributes("src/minimal.ts");+ expect(attrs.nodeType).toBe("file");+ });+});++describe("moduleGraphToGraphology", () => {+ it("handles an empty graph", () => {+ const g = moduleGraphToGraphology(makeModuleGraph());+ expect(g.order).toBe(0);+ expect(g.size).toBe(0);+ });++ it("adds module nodes with no edges", () => {+ const g = moduleGraphToGraphology(+ makeModuleGraph([+ { module_id: "src", file_count: 10, symbol_count: 50, avg_pagerank: 0.5, doc_coverage_pct: 0.8 },+ ]),+ );+ expect(g.order).toBe(1);+ expect(g.hasNode("src")).toBe(true);+ expect(g.getNodeAttributes("src").nodeType).toBe("module");+ });++ it("maps community colors from community summaries", () => {+ const g = moduleGraphToGraphology(+ makeModuleGraph([+ { module_id: "src/auth", file_count: 5, symbol_count: 20, avg_pagerank: 0.3, doc_coverage_pct: 0.5 },+ ]),+ {+ communities: [+ { community_id: 3, top_file: "src/auth/login.ts", label: "auth", cohesion: 0.8, member_count: 5 },+ ],+ },+ );+ expect(g.order).toBe(1);+ const attrs = g.getNodeAttributes("src/auth");+ expect(attrs.communityId).toBe(3);+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 5febb7b21..2e9f55dad 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -1,11 +1,11 @@{"name": "@repowise-dev/ui",- "version": "0.0.1",- "private": true,+ "version": "0.1.0","description": "Shared visualization components for the Repowise dashboard (packages/web) and downstream consumers. Domains: graph, git, dead-code, decisions, docs, symbols, coverage, wiki, chat, dashboard, workspace, jobs, blast-radius, plus shared primitives and hooks.","type": "module","main": "./src/index.ts","types": "./src/index.ts",+ "files": ["src", "styles"],"sideEffects": ["./styles/globals.css","**/*.css"@@ -54,7 +54,8 @@"./ui/*": "./src/ui/*.tsx","./lib/cn": "./src/lib/cn.ts","./lib/confidence": "./src/lib/confidence.ts",- "./lib/format": "./src/lib/format.ts"+ "./lib/format": "./src/lib/format.ts",+ "./lib/page-types": "./src/lib/page-types.ts"},"publishConfig": {"registry": "https://npm.pkg.github.com",@@ -77,18 +78,25 @@"@radix-ui/react-tabs": "^1.1.13","@radix-ui/react-tooltip": "^1.2.8","@repowise-dev/types": "*",+ "@sigma/edge-curve": "^3.1.0","@xyflow/react": "^12.10.2","class-variance-authority": "^0.7.1",- "fuse.js": "^7.0.0","clsx": "^2.1.1","d3-force": "^3.0.0",+ "elkjs": "^0.11.1","d3-hierarchy": "^3.1.2","framer-motion": "^11.11.0",+ "fuse.js": "^7.0.0",+ "graphology": "^0.26.0",+ "graphology-layout-forceatlas2": "^0.10.1",+ "graphology-layout-noverlap": "^0.4.2",+ "graphology-types": "^0.24.8","lucide-react": "^1.7.0","mermaid": "^11.4.0","react-markdown": "^10.1.0","recharts": "^3.8.1","remark-gfm": "^4.0.1",+ "sigma": "^3.0.3","tailwind-merge": "^3.5.0"},"peerDependencies": {diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsxindex 38f39401c..c0ca23234 100644--- a/packages/ui/src/chat/artifacts.tsx+++ b/packages/ui/src/chat/artifacts.tsx@@ -33,6 +33,7 @@ import type {} from "@repowise-dev/types/chat";import { ChatMarkdown } from "./chat-markdown";import { MermaidDiagram } from "../wiki/mermaid-diagram";+import { getPageTypeLabel } from "../lib/page-types";// ---------------------------------------------------------------------------// Shared atoms@@ -264,7 +265,7 @@ export function SearchResultsRenderer({{r.title}</div><div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">- {r.page_type}+ {getPageTypeLabel(r.page_type)}{typeof r.relevance_score === "number" && (<> · score {(r.relevance_score as number).toFixed(2)}</>)}diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsxindex 762874223..e0483681a 100644--- a/packages/ui/src/chat/chat-interface.tsx+++ b/packages/ui/src/chat/chat-interface.tsx@@ -73,6 +73,8 @@ export interface ChatInterfaceProps {assistantAvatarSrc?: string;/** Forwarded to `SourceCitations` for href customisation. */buildCitationHref?: (source: SourceReference) => string;+ /** Forwarded to `SourceCitations` for route-agnostic link generation. */+ linkPrefix?: string;/** Logo shown above the empty-state heading. */emptyStateLogoSrc?: string;/** Override default suggestion chips. */@@ -91,6 +93,7 @@ export function ChatInterface({historySlot,assistantAvatarSrc,buildCitationHref,+ linkPrefix,emptyStateLogoSrc = "/repowise-logo.png",suggestions = DEFAULT_SUGGESTIONS,}: ChatInterfaceProps) {@@ -230,6 +233,7 @@ export function ChatInterface({onViewArtifact={handleViewArtifact}{...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}{...(buildCitationHref ? { buildCitationHref } : {})}+ {...(linkPrefix ? { linkPrefix } : {})}/>))}{error && (diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsxindex 040535fe3..8f57aa746 100644--- a/packages/ui/src/chat/chat-message.tsx+++ b/packages/ui/src/chat/chat-message.tsx@@ -15,6 +15,8 @@ interface ChatMessageProps {assistantAvatarSrc?: string;/** Forwarded to `SourceCitations` so consumers can customise the link path. */buildCitationHref?: (source: SourceReference) => string;+ /** Forwarded to `SourceCitations` for route-agnostic link generation. */+ linkPrefix?: string;}export function ChatMessage({@@ -23,6 +25,7 @@ export function ChatMessage({onViewArtifact,assistantAvatarSrc = "/repowise-logo.png",buildCitationHref,+ linkPrefix,}: ChatMessageProps) {const isUser = message.role === "user";@@ -93,6 +96,7 @@ export function ChatMessage({<SourceCitationstoolCalls={message.toolCalls}repoId={repoId}+ {...(linkPrefix ? { linkPrefix } : {})}{...(buildCitationHref ? { buildHref: buildCitationHref } : {})}/>)}diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsxindex 0b64cc32d..e0335442c 100644--- a/packages/ui/src/chat/conversation-history.tsx+++ b/packages/ui/src/chat/conversation-history.tsx@@ -10,6 +10,7 @@import { useState } from "react";import { History, Plus, Trash2 } from "lucide-react";import { cn } from "../lib/cn";+import { formatRelativeTime } from "../lib/format";import type { Conversation } from "@repowise-dev/types/chat";export interface ConversationHistoryProps {@@ -23,18 +24,6 @@ export interface ConversationHistoryProps {className?: string;}-function formatRelativeTime(dateStr: string): string {- const diff = Date.now() - new Date(dateStr).getTime();- const mins = Math.floor(diff / 60000);- if (mins < 1) return "just now";- if (mins < 60) return `${mins}m ago`;- const hours = Math.floor(mins / 60);- if (hours < 24) return `${hours}h ago`;- const days = Math.floor(hours / 24);- if (days < 7) return `${days}d ago`;- return new Date(dateStr).toLocaleDateString();-}-export function ConversationHistory({conversations,isLoading = false,diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsxindex 049ec3a1d..86ba3b553 100644--- a/packages/ui/src/chat/source-citations.tsx+++ b/packages/ui/src/chat/source-citations.tsx@@ -1,14 +1,8 @@"use client";import { useMemo } from "react";-import {- FileText,- FolderOpen,- Globe,- Sparkles,- LayoutGrid,- ArrowUpRight,-} from "lucide-react";+import { ArrowUpRight } from "lucide-react";+import { getPageTypeIcon } from "../lib/page-types";import type { ChatUIToolCall } from "@repowise-dev/types/chat";export interface SourceReference {@@ -131,38 +125,33 @@ export function extractSources(return sources;}-const TYPE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {- repo_overview: Globe,- architecture_diagram: LayoutGrid,- module_page: FolderOpen,- symbol_spotlight: Sparkles,-};-function SourceIcon({ pageType, className }: { pageType: string; className?: string }) {- const Icon = TYPE_ICON[pageType] ?? FileText;+ const Icon = getPageTypeIcon(pageType);return <Icon {...(className ? { className } : {})} />;}interface SourceCitationsProps {toolCalls: ChatUIToolCall[];repoId: string;+ linkPrefix?: string;/**- * Builds the navigation URL for a citation. Defaults to OSS web's- * `/repos/{repoId}/wiki/{pageId}` shape; hosted-frontend supplies its own- * (e.g. `/s/{shortId}/wiki/{pageId}`) so this component stays- * framework-neutral.+ * Builds the navigation URL for a citation. Defaults to+ * `{linkPrefix}/wiki/{pageId}` (or `/repos/{repoId}/wiki/{pageId}`).+ * Hosted-frontend can supply its own or just pass `linkPrefix`.*/buildHref?: (source: SourceReference) => string;}-const defaultBuildHref = (s: SourceReference, repoId: string) =>- `/repos/${repoId}/wiki/${encodeURIComponent(s.pageId)}`;+const defaultBuildHref = (s: SourceReference, prefix: string) =>+ `${prefix}/wiki/${encodeURIComponent(s.pageId)}`;export function SourceCitations({toolCalls,repoId,+ linkPrefix,buildHref,}: SourceCitationsProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;const sources = useMemo(() => extractSources(toolCalls, repoId),[toolCalls, repoId],@@ -179,7 +168,7 @@ export function SourceCitations({{sources.map((source, idx) => (<akey={source.id}- href={buildHref ? buildHref(source) : defaultBuildHref(source, repoId)}+ href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[10px] text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] transition-all"><span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[9px] font-bold text-[var(--color-text-tertiary)] group-hover:bg-[var(--color-accent-primary)] group-hover:text-white shrink-0 transition-colors">diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsxindex 07c512ea3..99ffaae2a 100644--- a/packages/ui/src/chat/tool-call-block.tsx+++ b/packages/ui/src/chat/tool-call-block.tsx@@ -41,7 +41,7 @@ export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps)</span>{toolCall.summary && !isRunning && (<span className="text-[var(--color-text-tertiary)] truncate ml-1">- — {toolCall.summary}+ — {toolCall.summary}</span>)}<span className="ml-auto flex items-center gap-1">diff --git a/packages/ui/src/coverage/freshness-table.tsx b/packages/ui/src/coverage/freshness-table.tsxindex 771400456..28d51f542 100644--- a/packages/ui/src/coverage/freshness-table.tsx+++ b/packages/ui/src/coverage/freshness-table.tsx@@ -13,6 +13,7 @@ import {formatConfidence,formatRelativeTime,} from "../lib/format";+import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";import type { DocPage } from "@repowise-dev/types/docs";type Filter = "all" | "fresh" | "stale" | "outdated";@@ -117,7 +118,12 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {><td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[220px] max-w-[480px]"><div className="truncate" title={page.target_path}>{page.target_path}</div>- <div className="truncate text-[var(--color-text-tertiary)]" title={page.page_type}>{page.page_type}</div>+ {(() => { const TypeIcon = getPageTypeIcon(page.page_type); return (+ <div className="flex items-center gap-1 truncate text-[var(--color-text-tertiary)]" title={page.page_type}>+ <TypeIcon className="h-3 w-3 shrink-0" />+ <span>{getPageTypeLabel(page.page_type)}</span>+ </div>+ ); })()}</td><td className="px-4 py-2.5"><span@@ -160,7 +166,7 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {onClick={() => handleRegenerate(page.id)}className="h-6 px-2 text-xs">- {regenerating.has(page.id) ? "…" : "Regenerate"}+ {regenerating.has(page.id) ? "…" : "Regenerate"}</Button>)}</td>diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsxindex 570f359ec..64c95df02 100644--- a/packages/ui/src/dashboard/attention-panel.tsx+++ b/packages/ui/src/dashboard/attention-panel.tsx@@ -49,25 +49,27 @@ const TYPE_LABELS = {interface AttentionPanelProps {items: AttentionItem[];repoId: string;+ linkPrefix?: string;}-function getDefaultHref(item: AttentionItem, repoId: string): string {+function getDefaultHref(item: AttentionItem, prefix: string): string {switch (item.type) {case "stale_decision":case "proposed_decision":- return `/repos/${repoId}/decisions`;+ return `${prefix}/decisions`;case "knowledge_silo":- return `/repos/${repoId}/ownership`;+ return `${prefix}/ownership`;case "ungoverned_hotspot":- return `/repos/${repoId}/hotspots`;+ return `${prefix}/hotspots`;case "dead_code":- return `/repos/${repoId}/dead-code`;+ return `${prefix}/dead-code`;default:- return `/repos/${repoId}`;+ return prefix;}}-export function AttentionPanel({ items, repoId }: AttentionPanelProps) {+export function AttentionPanel({ items, repoId, linkPrefix }: AttentionPanelProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;if (items.length === 0) {return (<Card>@@ -97,7 +99,7 @@ export function AttentionPanel({ items, repoId }: AttentionPanelProps) {<div className="space-y-1">{items.slice(0, 8).map((item) => {const Icon = ICON_MAP[item.type];- const href = item.href ?? getDefaultHref(item, repoId);+ const href = item.href ?? getDefaultHref(item, prefix);return (<akey={item.id}diff --git a/packages/ui/src/dashboard/community-summary-grid.tsx b/packages/ui/src/dashboard/community-summary-grid.tsxindex 53256af5c..a9877f2a8 100644--- a/packages/ui/src/dashboard/community-summary-grid.tsx+++ b/packages/ui/src/dashboard/community-summary-grid.tsx@@ -116,6 +116,8 @@ function DetailPanel({ detail, isLoading, onClose }: DetailPanelProps) {export interface CommunitySummaryGridProps {communities: CommunitySummaryItem[];+ repoId?: string;+ linkPrefix?: string;/** Already-resolved details keyed by community_id. The wrapper fetches in* parallel (or lazily) and forwards. Missing entries render skeletons. */details?: Record<number, CommunityDetail | null>;@@ -127,20 +129,30 @@ export interface CommunitySummaryGridProps {export function CommunitySummaryGrid({communities,+ repoId,+ linkPrefix,details = {},loadingDetailId = null,onExpand,}: CommunitySummaryGridProps) {+ const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);const [expandedId, setExpandedId] = useState<number | null>(null);if (communities.length === 0) return null;return (<Card><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium flex items-center gap-2">- <Network className="h-4 w-4" />- Architecture Communities ({communities.length})- </CardTitle>+ <div className="flex items-center justify-between">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <Network className="h-4 w-4" />+ Architecture Communities ({communities.length})+ </CardTitle>+ {prefix && (+ <a href={`${prefix}/graph?colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ View in Graph →+ </a>+ )}+ </div></CardHeader><CardContent className="p-0"><div className="divide-y divide-[var(--color-border-default)]">diff --git a/packages/ui/src/dashboard/decisions-timeline.tsx b/packages/ui/src/dashboard/decisions-timeline.tsxindex 20e804c62..4985a71c7 100644--- a/packages/ui/src/dashboard/decisions-timeline.tsx+++ b/packages/ui/src/dashboard/decisions-timeline.tsx@@ -1,12 +1,14 @@-import { Landmark } from "lucide-react";+import { Landmark, Lightbulb } from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { Badge } from "../ui/badge";+import { EmptyState } from "../shared/empty-state";import { formatRelativeTime } from "../lib/format";import type { DecisionRecord } from "@repowise-dev/types/decisions";interface DecisionsTimelineProps {decisions: DecisionRecord[];repoId: string;+ linkPrefix?: string;}const STATUS_COLORS: Record<string, string> = {@@ -23,20 +25,19 @@ const STATUS_BADGE_VARIANT: Record<string, string> = {superseded: "text-[var(--color-text-tertiary)] border-[var(--color-text-tertiary)]/30",};-export function DecisionsTimeline({ decisions, repoId }: DecisionsTimelineProps) {+export function DecisionsTimeline({ decisions, repoId, linkPrefix }: DecisionsTimelineProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;const recent = decisions.slice(0, 6);if (recent.length === 0) {return (<Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm flex items-center gap-2">- <Landmark className="h-4 w-4 text-[var(--color-text-secondary)]" />- Recent Decisions- </CardTitle>- </CardHeader>- <CardContent className="pt-0">- <p className="text-xs text-[var(--color-text-tertiary)]">No decisions recorded</p>+ <CardContent className="p-0">+ <EmptyState+ icon={<Lightbulb className="h-8 w-8" />}+ title="No decisions recorded"+ description="No architectural decisions have been detected in this repository."+ /></CardContent></Card>);@@ -51,7 +52,7 @@ export function DecisionsTimeline({ decisions, repoId }: DecisionsTimelineProps)Recent Decisions</span><a- href={`/repos/${repoId}/decisions`}+ href={`${prefix}/decisions`}className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal">View all@@ -66,7 +67,7 @@ export function DecisionsTimeline({ decisions, repoId }: DecisionsTimelineProps){recent.map((d) => (<akey={d.id}- href={`/repos/${repoId}/decisions/${d.id}`}+ href={`${prefix}/decisions/${d.id}`}className="flex items-start gap-3 pl-0 group relative"><span@@ -86,7 +87,7 @@ export function DecisionsTimeline({ decisions, repoId }: DecisionsTimelineProps)</div><span className="text-[10px] text-[var(--color-text-tertiary)]">{formatRelativeTime(d.created_at)}- {d.source && ` · ${d.source.replace("_", " ")}`}+ {d.source && ` · ${d.source.replace("_", " ")}`}</span></div></a>diff --git a/packages/ui/src/dashboard/dependency-heatmap.tsx b/packages/ui/src/dashboard/dependency-heatmap.tsxindex 7d1718bb7..23939fa97 100644--- a/packages/ui/src/dashboard/dependency-heatmap.tsx+++ b/packages/ui/src/dashboard/dependency-heatmap.tsx@@ -1,6 +1,8 @@"use client";import { useMemo, useRef, useEffect } from "react";+import { Grid3X3 } from "lucide-react";+import { EmptyState } from "../shared/empty-state";import type { ModuleGraph } from "@repowise-dev/types/graph";interface DependencyHeatmapProps {@@ -116,7 +118,17 @@ export function DependencyHeatmap({ moduleGraph }: DependencyHeatmapProps) {}}, [modules, matrix, maxCount]);- if (modules.length < 2) return null;+ if (modules.length < 2) {+ return (+ <div className="overflow-x-auto">+ <EmptyState+ icon={<Grid3X3 className="h-8 w-8" />}+ title="No dependency data"+ description="Not enough modules to generate a dependency heatmap."+ />+ </div>+ );+ }return (<div className="overflow-x-auto">diff --git a/packages/ui/src/dashboard/execution-flows-panel.tsx b/packages/ui/src/dashboard/execution-flows-panel.tsxindex efcfdc1bf..db550fb15 100644--- a/packages/ui/src/dashboard/execution-flows-panel.tsx+++ b/packages/ui/src/dashboard/execution-flows-panel.tsx@@ -1,15 +1,17 @@"use client";import { useState } from "react";-import { ChevronRight, ChevronDown } from "lucide-react";+import { ChevronRight, ChevronDown, Workflow } from "lucide-react";import { Badge } from "../ui/badge";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { cn } from "../lib/cn";+import { EmptyState } from "../shared/empty-state";import type { ExecutionFlowEntry } from "@repowise-dev/types/graph";interface ExecutionFlowsPanelProps {flows: ExecutionFlowEntry[];repoId: string;+ linkPrefix?: string;}function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {@@ -84,13 +86,31 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {);}-export function ExecutionFlowsPanel({ flows, repoId: _repoId }: ExecutionFlowsPanelProps) {- if (flows.length === 0) return null;+export function ExecutionFlowsPanel({ flows, repoId, linkPrefix }: ExecutionFlowsPanelProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;+ if (flows.length === 0) {+ return (+ <Card>+ <CardContent className="p-0">+ <EmptyState+ icon={<Workflow className="h-8 w-8" />}+ title="No execution flows"+ description="No execution flow data is available for this repository."+ />+ </CardContent>+ </Card>+ );+ }return (<Card><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Execution Flows</CardTitle>+ <div className="flex items-center justify-between">+ <CardTitle className="text-sm font-medium">Execution Flows</CardTitle>+ <a href={`${prefix}/graph?viewMode=architecture`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ View in Graph →+ </a>+ </div></CardHeader><CardContent className="p-0"><div className="divide-y divide-[var(--color-border-default)]">diff --git a/packages/ui/src/dashboard/health-score-ring.tsx b/packages/ui/src/dashboard/health-score-ring.tsxindex 9fa3b4a97..7273dfed3 100644--- a/packages/ui/src/dashboard/health-score-ring.tsx+++ b/packages/ui/src/dashboard/health-score-ring.tsx@@ -2,10 +2,20 @@import { useEffect, useState } from "react";import { motion } from "framer-motion";+import { HelpCircle } from "lucide-react";++export interface HealthScoreComponent {+ key: string;+ label: string;+ weight: number;+ score: number;+ detail: string;+}interface HealthScoreRingProps {score: number;size?: number;+ components?: HealthScoreComponent[];}function getScoreColor(score: number): string {@@ -22,8 +32,9 @@ function getScoreLabel(score: number): string {return "Critical";}-export function HealthScoreRing({ score, size = 160 }: HealthScoreRingProps) {+export function HealthScoreRing({ score, size = 160, components }: HealthScoreRingProps) {const [mounted, setMounted] = useState(false);+ const [breakdownOpen, setBreakdownOpen] = useState(false);useEffect(() => setMounted(true), []);const strokeWidth = 10;@@ -31,46 +42,105 @@ export function HealthScoreRing({ score, size = 160 }: HealthScoreRingProps) {const circumference = 2 * Math.PI * radius;const progress = mounted ? (score / 100) * circumference : 0;const color = getScoreColor(score);+ const hasBreakdown = components && components.length > 0;return (- <div className="relative flex items-center justify-center" style={{ width: size, height: size }}>- <svg width={size} height={size} className="-rotate-90">- <circle- cx={size / 2}- cy={size / 2}- r={radius}- fill="none"- stroke="var(--color-border-default)"- strokeWidth={strokeWidth}- />- <motion.circle- cx={size / 2}- cy={size / 2}- r={radius}- fill="none"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeDasharray={circumference}- initial={{ strokeDashoffset: circumference }}- animate={{ strokeDashoffset: circumference - progress }}- transition={{ duration: 1.2, ease: "easeOut" }}- />- </svg>- <div className="absolute inset-0 flex flex-col items-center justify-center">- <motion.span- className="text-3xl font-bold tabular-nums"- style={{ color }}- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ delay: 0.3 }}- >- {score}- </motion.span>- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {getScoreLabel(score)}- </span>+ <div className="flex flex-col items-center gap-2">+ <div className="relative flex items-center justify-center" style={{ width: size, height: size }}>+ <svg width={size} height={size} className="-rotate-90">+ <circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke="var(--color-border-default)"+ strokeWidth={strokeWidth}+ />+ <motion.circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeDasharray={circumference}+ initial={{ strokeDashoffset: circumference }}+ animate={{ strokeDashoffset: circumference - progress }}+ transition={{ duration: 1.2, ease: "easeOut" }}+ />+ </svg>+ <div className="absolute inset-0 flex flex-col items-center justify-center">+ <motion.span+ className="text-3xl font-bold tabular-nums"+ style={{ color }}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ delay: 0.3 }}+ >+ {score}+ </motion.span>+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {getScoreLabel(score)}+ </span>+ </div></div>+ {hasBreakdown && (+ <button+ type="button"+ onClick={() => setBreakdownOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition"+ aria-expanded={breakdownOpen}+ aria-controls="health-score-breakdown"+ >+ <HelpCircle className="h-3 w-3" aria-hidden />+ {breakdownOpen ? "Hide breakdown" : "Why this score?"}+ </button>+ )}+ {breakdownOpen && hasBreakdown && (+ <div+ id="health-score-breakdown"+ className="w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs space-y-2"+ >+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Score = weighted average of {components.length} components+ </p>+ <ul className="space-y-2">+ {components.map((c) => {+ const barColor =+ c.score >= 75+ ? "var(--color-success)"+ : c.score >= 50+ ? "var(--color-warning)"+ : "var(--color-error)";+ return (+ <li key={c.key} className="space-y-1">+ <div className="flex items-baseline justify-between gap-3">+ <span className="text-[var(--color-text-primary)]">+ {c.label}{" "}+ <span className="text-[var(--color-text-tertiary)]">+ ({Math.round(c.weight * 100)}%)+ </span>+ </span>+ <span className="tabular-nums text-[var(--color-text-secondary)]">+ {Math.round(c.score)}/100+ </span>+ </div>+ <div className="h-1 w-full overflow-hidden rounded-full bg-[var(--color-bg-surface)]">+ <div+ className="h-full transition-[width] duration-300"+ style={{ width: `${c.score}%`, background: barColor }}+ />+ </div>+ {c.detail && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">{c.detail}</p>+ )}+ </li>+ );+ })}+ </ul>+ </div>+ )}</div>);}diff --git a/packages/ui/src/dashboard/hotspots-mini.tsx b/packages/ui/src/dashboard/hotspots-mini.tsxindex 64a135957..996a462ea 100644--- a/packages/ui/src/dashboard/hotspots-mini.tsx+++ b/packages/ui/src/dashboard/hotspots-mini.tsx@@ -1,11 +1,13 @@import { Flame } from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { EmptyState } from "../shared/empty-state";import { truncatePath } from "../lib/format";import type { Hotspot } from "@repowise-dev/types/git";interface HotspotsMiniProps {hotspots: Hotspot[];repoId: string;+ linkPrefix?: string;}function getChurnColor(percentile: number): string {@@ -14,20 +16,19 @@ function getChurnColor(percentile: number): string {return "var(--color-accent-primary)";}-export function HotspotsMini({ hotspots, repoId }: HotspotsMiniProps) {+export function HotspotsMini({ hotspots, repoId, linkPrefix }: HotspotsMiniProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;const top = hotspots.slice(0, 5);if (top.length === 0) {return (<Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm flex items-center gap-2">- <Flame className="h-4 w-4 text-red-500" />- Top Hotspots- </CardTitle>- </CardHeader>- <CardContent className="pt-0">- <p className="text-xs text-[var(--color-text-tertiary)]">No hotspot data</p>+ <CardContent className="p-0">+ <EmptyState+ icon={<Flame className="h-8 w-8" />}+ title="No hotspot data"+ description="No churn or complexity hotspots detected in this repository."+ /></CardContent></Card>);@@ -42,7 +43,7 @@ export function HotspotsMini({ hotspots, repoId }: HotspotsMiniProps) {Top Hotspots</span><a- href={`/repos/${repoId}/hotspots`}+ href={`${prefix}/hotspots`}className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal">View all@@ -52,7 +53,11 @@ export function HotspotsMini({ hotspots, repoId }: HotspotsMiniProps) {<CardContent className="pt-0"><div className="space-y-2">{top.map((h) => (- <div key={h.file_path} className="flex items-center gap-3">+ <a+ key={h.file_path}+ href={`${prefix}/graph?node=${encodeURIComponent(h.file_path)}`}+ className="flex items-center gap-3 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"+ ><div className="w-16 shrink-0"><div className="h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden"><div@@ -75,7 +80,7 @@ export function HotspotsMini({ hotspots, repoId }: HotspotsMiniProps) {{Math.round(h.churn_percentile)}%</span></div>- </div>+ </a>))}</div></CardContent>diff --git a/packages/ui/src/dashboard/index.ts b/packages/ui/src/dashboard/index.tsindex 770a84554..6d038e896 100644--- a/packages/ui/src/dashboard/index.ts+++ b/packages/ui/src/dashboard/index.ts@@ -6,6 +6,7 @@ export * from "./health-score-ring.js";export * from "./hotspots-mini.js";export * from "./language-donut.js";export * from "./module-minimap.js";+export * from "./module-overview-grid.js";export * from "./ownership-treemap.js";export * from "./active-job-banner.js";export * from "./quick-actions.js";diff --git a/packages/ui/src/dashboard/module-minimap.tsx b/packages/ui/src/dashboard/module-minimap.tsxindex e1fc3e395..1365311b0 100644--- a/packages/ui/src/dashboard/module-minimap.tsx+++ b/packages/ui/src/dashboard/module-minimap.tsx@@ -11,6 +11,7 @@ interface ModuleMinimapProps {nodes: ModuleNode[];edges: ModuleEdge[];repoId: string;+ linkPrefix?: string;}interface SimNode extends d3Force.SimulationNodeDatum {@@ -27,7 +28,8 @@ interface SimLink {edgeCount: number;}-export function ModuleMinimap({ nodes, edges, repoId }: ModuleMinimapProps) {+export function ModuleMinimap({ nodes, edges, repoId, linkPrefix }: ModuleMinimapProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;const containerRef = useRef<HTMLDivElement>(null);const [simNodes, setSimNodes] = useState<SimNode[]>([]);const [simLinks, setSimLinks] = useState<Array<{ source: SimNode; target: SimNode; edgeCount: number }>>([]);@@ -116,7 +118,7 @@ export function ModuleMinimap({ nodes, edges, repoId }: ModuleMinimapProps) {Architecture</span><a- href={`/repos/${repoId}/graph`}+ href={`${prefix}/graph`}className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal">Full graph@@ -173,7 +175,7 @@ export function ModuleMinimap({ nodes, edges, repoId }: ModuleMinimapProps) {<TooltipContent side="top" className="text-xs"><p className="font-medium font-mono">{node.id}</p><p className="text-[var(--color-text-tertiary)]">- {node.fileCount} files · {node.symbolCount} symbols · {Math.round(node.docCoverage)}% docs+ {node.fileCount} files · {node.symbolCount} symbols · {Math.round(node.docCoverage)}% docs</p></TooltipContent></Tooltip>diff --git a/packages/ui/src/dashboard/module-overview-grid.tsx b/packages/ui/src/dashboard/module-overview-grid.tsxnew file mode 100644index 000000000..a98641273--- /dev/null+++ b/packages/ui/src/dashboard/module-overview-grid.tsx@@ -0,0 +1,135 @@+"use client";++import { useMemo, useState } from "react";+import { Network, ChevronDown, ChevronUp } from "lucide-react";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { cn } from "../lib/cn";+import { formatNumber } from "../lib/format";+import type { ModuleNode, ModuleEdge } from "@repowise-dev/types/graph";++interface ModuleOverviewGridProps {+ nodes: ModuleNode[];+ edges: ModuleEdge[];+ repoId: string;+ linkPrefix?: string;+ /** Number of columns in the first visible row. Defaults to 4. */+ initialVisibleCols?: number;+}++export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVisibleCols = 4 }: ModuleOverviewGridProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;+ const [expanded, setExpanded] = useState(false);+ const modules = useMemo(() => {+ const edgeCounts = new Map<string, number>();+ for (const e of edges) {+ edgeCounts.set(e.source, (edgeCounts.get(e.source) ?? 0) + e.edge_count);+ edgeCounts.set(e.target, (edgeCounts.get(e.target) ?? 0) + e.edge_count);+ }++ return [...nodes]+ .sort((a, b) => b.file_count - a.file_count)+ .map((n) => ({+ ...n,+ label: n.module_id.split("/").pop() ?? n.module_id,+ depCount: edgeCounts.get(n.module_id) ?? 0,+ }));+ }, [nodes, edges]);++ if (modules.length === 0) return null;++ const hasMore = modules.length > initialVisibleCols;+ const visibleModules = expanded ? modules : modules.slice(0, initialVisibleCols);++ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm flex items-center justify-between">+ <span className="flex items-center gap-2">+ <Network className="h-4 w-4 text-[var(--color-text-secondary)]" />+ Architecture+ <span className="text-[10px] font-normal text-[var(--color-text-tertiary)]">+ {modules.length} modules+ </span>+ </span>+ <a+ href={`${prefix}/graph`}+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"+ >+ Full graph →+ </a>+ </CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">+ {visibleModules.map((m) => {+ const coverageColor =+ m.doc_coverage_pct >= 70+ ? "bg-green-500"+ : m.doc_coverage_pct >= 30+ ? "bg-yellow-500"+ : "bg-red-500";++ return (+ <a+ key={m.module_id}+ href={`${prefix}/graph?node=${encodeURIComponent(m.module_id)}`}+ className="group rounded-lg border border-[var(--color-border-default)] p-3 hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ <p className="text-xs font-medium text-[var(--color-text-primary)] truncate mb-2" title={m.module_id}>+ {m.label}+ </p>+ <div className="space-y-1.5">+ <div className="flex items-center justify-between text-[10px] text-[var(--color-text-tertiary)]">+ <span>{formatNumber(m.file_count)} files</span>+ <span>{formatNumber(m.symbol_count)} sym</span>+ </div>+ <div className="h-1.5 rounded-full bg-[var(--color-bg-overlay)] overflow-hidden">+ <div+ className={cn("h-full rounded-full transition-all", coverageColor)}+ style={{ width: `${Math.max(2, m.doc_coverage_pct)}%` }}+ />+ </div>+ <div className="flex items-center justify-between text-[10px]">+ <span className={cn(+ m.doc_coverage_pct >= 70+ ? "text-green-500"+ : m.doc_coverage_pct >= 30+ ? "text-yellow-500"+ : "text-red-500",+ )}>+ {Math.round(m.doc_coverage_pct)}% docs+ </span>+ {m.depCount > 0 && (+ <span className="text-[var(--color-text-tertiary)]">+ {formatNumber(m.depCount)} deps+ </span>+ )}+ </div>+ </div>+ </a>+ );+ })}+ </div>+ {hasMore && (+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="mt-2 w-full flex items-center justify-center gap-1 rounded-md border border-[var(--color-border-default)] py-1.5 text-[11px] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ {expanded ? (+ <>+ <ChevronUp className="h-3 w-3" />+ Show less+ </>+ ) : (+ <>+ <ChevronDown className="h-3 w-3" />+ Show all {modules.length} modules+ </>+ )}+ </button>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/packages/ui/src/dashboard/ownership-treemap.tsx b/packages/ui/src/dashboard/ownership-treemap.tsxindex 9a1b14928..05d8bb598 100644--- a/packages/ui/src/dashboard/ownership-treemap.tsx+++ b/packages/ui/src/dashboard/ownership-treemap.tsx@@ -129,7 +129,7 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {className="text-[10px] fill-white pointer-events-none"opacity={0.9}>- {d.name.length > w / 6 ? d.name.slice(0, Math.floor(w / 6)) + "…" : d.name}+ {d.name.length > w / 6 ? d.name.slice(0, Math.floor(w / 6)) + "…" : d.name}</text>)}<TooltipContent side="top" className="text-xs">@@ -138,7 +138,7 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {Owner: {d.owner ?? "none"} ({d.ownerPct ? Math.round(d.ownerPct * 100) : 0}%)</p><p className="text-[var(--color-text-tertiary)]">- {d.value} files{d.isSilo ? " • Knowledge silo" : ""}+ {d.value} files{d.isSilo ? " • Knowledge silo" : ""}</p></TooltipContent></Tooltip>diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsxindex 986110057..bea5295a6 100644--- a/packages/ui/src/decisions/decisions-table.tsx+++ b/packages/ui/src/decisions/decisions-table.tsx@@ -1,7 +1,6 @@"use client";import * as React from "react";-import Link from "next/link";import { Badge } from "../ui/badge";import type {DecisionRecord,@@ -40,6 +39,8 @@ export interface DecisionsTableProps {onFiltersChange: (filters: DecisionsTableFilters) => void;/** Used to build the "View" link target for each row. */repoId: string;+ linkPrefix?: string;+ LinkComponent?: React.ElementType<{ href: string; className?: string; children: React.ReactNode }>;/** Truthy when the most recent fetch errored; an inline retry is rendered. */error?: unknown;/** Truthy while a fetch is in flight; suppresses the empty-state message. */@@ -53,10 +54,14 @@ export function DecisionsTable({filters,onFiltersChange,repoId,+ linkPrefix,+ LinkComponent = "a",error,isLoading,onRetry,}: DecisionsTableProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;+ const Link = LinkComponent;return (<div className="space-y-4">{/* Filters */}@@ -115,7 +120,7 @@ export function DecisionsTable({><td className="px-4 py-2.5 min-w-[240px] max-w-[520px]"><Link- href={`/repos/${repoId}/decisions/${d.id}`}+ href={`${prefix}/decisions/${d.id}`}className="font-medium text-[var(--color-accent-primary)] hover:underline block truncate"title={d.title}>@@ -157,7 +162,7 @@ export function DecisionsTable({) : d.staleness_score > 0 ? (<span className="text-[var(--color-text-tertiary)]">{Math.round(d.staleness_score * 100)}%</span>) : (- <span className="text-[var(--color-text-tertiary)]">—</span>+ <span className="text-[var(--color-text-tertiary)]">—</span>)}</td></tr>diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsxindex c3979be4d..fb2fa6911 100644--- a/packages/ui/src/docs/docs-tree.tsx+++ b/packages/ui/src/docs/docs-tree.tsx@@ -4,15 +4,12 @@ import { useState, useMemo } from "react";import {ChevronDown,ChevronRight,- FileText,FolderOpen,Folder,- Globe,- LayoutGrid,- Sparkles,Search,Filter,} from "lucide-react";+import { getPageTypeIcon, getPageTypeLabel, ALL_PAGE_TYPES } from "../lib/page-types";import { cn } from "../lib/cn";import { statusBadgeClasses, type FreshnessStatus } from "../lib/confidence";import type { DocPage } from "@repowise-dev/types/docs";@@ -40,15 +37,8 @@ interface DocsTreeProps {// Page type icons// ----------------------------------------------------------------------------const PAGE_TYPE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {- repo_overview: Globe,- architecture_diagram: LayoutGrid,- module_page: FolderOpen,- symbol_spotlight: Sparkles,-};-function PageIcon({ pageType, className }: { pageType: string; className?: string }) {- const Icon = PAGE_TYPE_ICON[pageType] ?? FileText;+ const Icon = getPageTypeIcon(pageType);return <Icon {...(className ? { className } : {})} />;}@@ -173,7 +163,7 @@ function buildTree(pages: DocPage[]): TreeNode[] {// Filter helpers// ----------------------------------------------------------------------------type TypeFilter = "all" | "file_page" | "module_page" | "symbol_spotlight" | "repo_overview";+type TypeFilter = "all" | typeof ALL_PAGE_TYPES[number];type FreshnessFilter = "all" | "fresh" | "stale" | "outdated";function matchesFilters(@@ -405,7 +395,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc<div className="space-y-1.5"><div className="flex items-center gap-1 flex-wrap"><span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium w-10">Type</span>- {(["all", "file_page", "module_page", "symbol_spotlight", "repo_overview"] as TypeFilter[]).map((t) => (+ {(["all", ...ALL_PAGE_TYPES] as TypeFilter[]).map((t) => (<buttonkey={t}onClick={() => setTypeFilter(t)}@@ -416,7 +406,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc: "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",)}>- {t === "all" ? "All" : t.replace(/_/g, " ").replace("page", "").trim() || "file"}+ {t === "all" ? "All" : getPageTypeLabel(t)}</button>))}</div>@@ -445,7 +435,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc{/* Stats line */}<div className="flex items-center justify-between text-[10px] text-[var(--color-text-tertiary)]"><span>{totalPages} pages</span>- <span>{freshCount} fresh · {totalPages - freshCount} need attention</span>+ <span>{freshCount} fresh · {totalPages - freshCount} need attention</span></div></div>diff --git a/packages/ui/src/git/bus-factor-panel.tsx b/packages/ui/src/git/bus-factor-panel.tsxindex 8e95cdede..2c2fdb54c 100644--- a/packages/ui/src/git/bus-factor-panel.tsx+++ b/packages/ui/src/git/bus-factor-panel.tsx@@ -7,6 +7,8 @@ import {Tooltip,ResponsiveContainer,} from "recharts";+import { Users } from "lucide-react";+import { EmptyState } from "../shared/empty-state";import { truncatePath } from "../lib/format";import type { Hotspot } from "@repowise-dev/types/git";@@ -15,6 +17,16 @@ interface BusFactorPanelProps {}export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {+ if (!hotspots || hotspots.length === 0) {+ return (+ <EmptyState+ icon={<Users className="h-8 w-8" />}+ title="No bus factor data"+ description="No ownership data is available for this repository."+ />+ );+ }+const high = hotspots.filter((h) => h.bus_factor >= 3).length;const medium = hotspots.filter((h) => h.bus_factor === 2).length;const low = hotspots.filter((h) => h.bus_factor <= 1).length;@@ -48,7 +60,7 @@ export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {}}formatter={(value, name) => {const n = typeof value === "number" ? value : 0;- const label = name === "high" ? "Safe (≥3)" : name === "medium" ? "Warning (2)" : "Risk (≤1)";+ const label = name === "high" ? "Safe (≥3)" : name === "medium" ? "Warning (2)" : "Risk (≤1)";return [`${n} files`, label];}}/>@@ -59,13 +71,13 @@ export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {</ResponsiveContainer><div className="flex items-center gap-4 mt-2 text-[10px] text-[var(--color-text-tertiary)]"><span className="flex items-center gap-1">- <span className="inline-block h-2 w-2 rounded-sm bg-green-500" /> Safe (≥3): {high}+ <span className="inline-block h-2 w-2 rounded-sm bg-green-500" /> Safe (≥3): {high}</span><span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm bg-yellow-500" /> Warning (2): {medium}</span><span className="flex items-center gap-1">- <span className="inline-block h-2 w-2 rounded-sm bg-red-500" /> Risk (≤1): {low}+ <span className="inline-block h-2 w-2 rounded-sm bg-red-500" /> Risk (≤1): {low}</span></div></div>diff --git a/packages/ui/src/git/churn-histogram.tsx b/packages/ui/src/git/churn-histogram.tsxindex 4bb38460f..e2a9be7e1 100644--- a/packages/ui/src/git/churn-histogram.tsx+++ b/packages/ui/src/git/churn-histogram.tsx@@ -9,6 +9,8 @@ import {ResponsiveContainer,Cell,} from "recharts";+import { GitCommitHorizontal } from "lucide-react";+import { EmptyState } from "../shared/empty-state";import type { Hotspot } from "@repowise-dev/types/git";interface ChurnHistogramProps {@@ -23,6 +25,16 @@ const BUCKET_COLORS = [const BUCKET_FALLBACK = "#8b5cf6";export function ChurnHistogram({ hotspots }: ChurnHistogramProps) {+ if (!hotspots || hotspots.length === 0) {+ return (+ <EmptyState+ icon={<GitCommitHorizontal className="h-8 w-8" />}+ title="No churn data"+ description="No file churn data is available for this repository."+ />+ );+ }+const buckets = Array<number>(10).fill(0);for (const h of hotspots) {const idx = Math.min(9, Math.floor(h.churn_percentile / 10));@@ -30,7 +42,7 @@ export function ChurnHistogram({ hotspots }: ChurnHistogramProps) {}const data = buckets.map((count, i) => ({- range: `${i * 10}–${(i + 1) * 10}`,+ range: `${i * 10}–${(i + 1) * 10}`,count,}));diff --git a/packages/ui/src/git/commit-category-donut.tsx b/packages/ui/src/git/commit-category-donut.tsxindex 2469fc15d..53c3cfda4 100644--- a/packages/ui/src/git/commit-category-donut.tsx+++ b/packages/ui/src/git/commit-category-donut.tsx@@ -1,6 +1,8 @@"use client";+import { PieChart as PieChartIcon } from "lucide-react";import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";+import { EmptyState } from "../shared/empty-state";interface CommitCategoryDonutProps {categories: Record<string, number>;@@ -23,7 +25,15 @@ export function CommitCategoryDonut({ categories }: CommitCategoryDonutProps) {})).filter((d) => d.value > 0);const total = data.reduce((sum, d) => sum + d.value, 0);- if (total === 0) return null;+ if (total === 0) {+ return (+ <EmptyState+ icon={<PieChartIcon className="h-8 w-8" />}+ title="No commit data"+ description="No commit category data is available for this repository."+ />+ );+ }const dominant = data.reduce((a, b) => (a.value >= b.value ? a : b));diff --git a/packages/ui/src/git/contributor-network.tsx b/packages/ui/src/git/contributor-network.tsxindex f92710a2f..af1954b4c 100644--- a/packages/ui/src/git/contributor-network.tsx+++ b/packages/ui/src/git/contributor-network.tsx@@ -121,7 +121,7 @@ export function ContributorNetwork({ hotspots }: ContributorNetworkProps) {text.setAttribute("dy", String(n.radius + 12));text.setAttribute("fill", "var(--color-text-secondary)");text.setAttribute("font-size", "9");- text.textContent = n.id.length > 15 ? n.id.slice(0, 15) + "…" : n.id;+ text.textContent = n.id.length > 15 ? n.id.slice(0, 15) + "…" : n.id;group.appendChild(text);const title = document.createElementNS(ns, "title");diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsxindex a339b21cd..9116c741e 100644--- a/packages/ui/src/git/hotspot-table.tsx+++ b/packages/ui/src/git/hotspot-table.tsx@@ -1,10 +1,11 @@"use client";import { useState, useMemo } from "react";-import { TrendingUp, TrendingDown, Search, Flame, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";+import { TrendingUp, TrendingDown, Search, Flame, ArrowUpDown, ArrowUp, ArrowDown, GitBranch, BookOpen, Radius } from "lucide-react";import { Badge } from "../ui/badge";import { Input } from "../ui/input";import { EmptyState } from "../shared/empty-state";+import { RowActions } from "../shared/row-actions";import { ChurnBar } from "./churn-bar";import { formatLOC } from "../lib/format";import { cn } from "../lib/cn";@@ -12,6 +13,8 @@ import type { Hotspot } from "@repowise-dev/types/git";interface HotspotTableProps {hotspots: Hotspot[];+ repoId?: string;+ linkPrefix?: string;}type Filter = "all" | "hot" | "risk" | "accelerating";@@ -30,7 +33,8 @@ function ariaSortFor(column: SortKey, sortKey: SortKey, sortDir: SortDir): "nonereturn sortDir === "asc" ? "ascending" : "descending";}-export function HotspotTable({ hotspots }: HotspotTableProps) {+export function HotspotTable({ hotspots, repoId, linkPrefix }: HotspotTableProps) {+ const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);const [search, setSearch] = useState("");const [filter, setFilter] = useState<Filter>("all");const [sortKey, setSortKey] = useState<SortKey>("trend");@@ -88,7 +92,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {return (<EmptyStatetitle="No hotspots found"- description="All files look stable — great work!"+ description="All files look stable — great work!"/>);}@@ -106,7 +110,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {<div className="relative"><Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><Input- placeholder="Search files or owners…"+ placeholder="Search files or owners…"value={search}onChange={(e) => setSearch(e.target.value)}className="pl-8 h-8 w-full sm:w-56 text-xs"@@ -173,7 +177,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {Bus Factor</th><th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24 hidden lg:table-cell">- Lines ±90d+ Lines ±90d</th><th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">Owner@@ -226,7 +230,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {</span></>) : (- <span className="text-[var(--color-text-tertiary)]">—</span>+ <span className="text-[var(--color-text-tertiary)]">—</span>)}</span></td>@@ -249,11 +253,22 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {<span className="text-red-400">-{formatLOC(h.lines_deleted_90d)}</span></td><td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">- {h.primary_owner ?? "—"}+ {h.primary_owner ?? "—"}</td>- <td className="px-3 py-2.5 flex items-center gap-1">- {h.is_hotspot && <Badge variant="outdated">Hot</Badge>}- {h.is_stable && <Badge variant="fresh">Stable</Badge>}+ <td className="px-3 py-2.5">+ <div className="flex items-center gap-1">+ {h.is_hotspot && <Badge variant="outdated">Hot</Badge>}+ {h.is_stable && <Badge variant="fresh">Stable</Badge>}+ {prefix && (+ <RowActions+ actions={[+ { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(h.file_path)}` },+ { icon: BookOpen, label: "Docs", href: `${prefix}/docs?file=${encodeURIComponent(h.file_path)}` },+ { icon: Radius, label: "Blast Radius", href: `${prefix}/blast-radius?file=${encodeURIComponent(h.file_path)}` },+ ]}+ />+ )}+ </div></td></tr>);diff --git a/packages/ui/src/git/ownership-table.tsx b/packages/ui/src/git/ownership-table.tsxindex db47a9687..3fb7869bb 100644--- a/packages/ui/src/git/ownership-table.tsx+++ b/packages/ui/src/git/ownership-table.tsx@@ -1,21 +1,25 @@"use client";import { useState, useMemo } from "react";-import { Search } from "lucide-react";+import { Search, GitBranch, Flame } from "lucide-react";import { Badge } from "../ui/badge";import { Input } from "../ui/input";import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";import { EmptyState } from "../shared/empty-state";+import { RowActions } from "../shared/row-actions";import { cn } from "../lib/cn";import type { OwnershipEntry } from "@repowise-dev/types/git";interface OwnershipTableProps {entries: OwnershipEntry[];+ repoId?: string;+ linkPrefix?: string;}type Filter = "all" | "silo";-export function OwnershipTable({ entries }: OwnershipTableProps) {+export function OwnershipTable({ entries, repoId, linkPrefix }: OwnershipTableProps) {+ const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);const [search, setSearch] = useState("");const [filter, setFilter] = useState<Filter>("all");@@ -55,7 +59,7 @@ export function OwnershipTable({ entries }: OwnershipTableProps) {<div className="relative"><Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><Input- placeholder="Search modules or owners…"+ placeholder="Search modules or owners…"value={search}onChange={(e) => setSearch(e.target.value)}className="pl-8 h-8 w-full sm:w-56 text-xs"@@ -124,7 +128,7 @@ export function OwnershipTable({ entries }: OwnershipTableProps) {</td><td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] max-w-[200px]"><span className="block truncate" title={entry.primary_owner ?? undefined}>- {entry.primary_owner ?? "—"}+ {entry.primary_owner ?? "—"}</span></td><td className="px-4 py-2.5">@@ -141,23 +145,33 @@ export function OwnershipTable({ entries }: OwnershipTableProps) {</span></div>) : (- <span className="text-[var(--color-text-tertiary)]">—</span>+ <span className="text-[var(--color-text-tertiary)]">—</span>)}</td><td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">{entry.file_count}</td><td className="px-4 py-2.5">- {entry.is_silo && (- <Tooltip>- <TooltipTrigger asChild>- <span>- <Badge variant="stale">Silo</Badge>- </span>- </TooltipTrigger>- <TooltipContent>Bus factor risk</TooltipContent>- </Tooltip>- )}+ <div className="flex items-center gap-1">+ {entry.is_silo && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Badge variant="stale">Silo</Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent>Bus factor risk</TooltipContent>+ </Tooltip>+ )}+ {prefix && (+ <RowActions+ actions={[+ { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(entry.module_path)}` },+ { icon: Flame, label: "Hotspots", href: `${prefix}/hotspots` },+ ]}+ />+ )}+ </div></td></tr>))}diff --git a/packages/ui/src/git/ownership-treemap.tsx b/packages/ui/src/git/ownership-treemap.tsxindex f61945209..f70c65ed7 100644--- a/packages/ui/src/git/ownership-treemap.tsx+++ b/packages/ui/src/git/ownership-treemap.tsx@@ -149,7 +149,7 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {fontFamily="var(--font-geist-mono)"pointerEvents="none">- {d.name.length > w / 7 ? d.name.slice(0, Math.floor(w / 7)) + "…" : d.name}+ {d.name.length > w / 7 ? d.name.slice(0, Math.floor(w / 7)) + "…" : d.name}</text><textx={x0 + 6}@@ -177,7 +177,7 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {><p className="font-mono font-medium text-[var(--color-text-primary)]">{tooltip.name}</p><p className="text-[var(--color-text-secondary)] mt-0.5">- Owner: {tooltip.owner ?? "—"}+ Owner: {tooltip.owner ?? "—"}{tooltip.pct != null && ` (${Math.round(tooltip.pct * 100)}%)`}</p><p className="text-[var(--color-text-secondary)]">{tooltip.fileCount} files</p>diff --git a/packages/ui/src/graph/context.ts b/packages/ui/src/graph/context.tsindex 8c07b4f71..f15c23090 100644--- a/packages/ui/src/graph/context.ts+++ b/packages/ui/src/graph/context.ts@@ -1,30 +1,50 @@"use client";import { createContext, useContext } from "react";-import type { ColorMode } from "./graph-toolbar";+import type { ColorMode, ViewMode, LayoutMode, GraphTheme } from "./graph-toolbar";++export type Signal = "dead" | "hot" | "architecture" | "hideTests";export interface GraphContextValue {highlightedPath: Set<string>;highlightedEdges: Set<string>;colorMode: ColorMode;- riskScores: Map<string, number>;+ viewMode: ViewMode;hoveredNodeId: string | null;connectedNodeIds: Set<string>;connectedEdgeIds: Set<string>;selectedNodeId: string | null;searchDimmedNodes: Set<string> | null;+ communityDimmedNodes: Set<string> | null;+ layoutMode: LayoutMode;+ graphTheme: GraphTheme;+ maxPagerank: number;+ medianPagerank: number;+ expandedModules: Set<string>;+ activeSignals: Set<Signal>;+ egoDepth: number;+ visibleEdgeTypes: Set<string>;}const defaultValue: GraphContextValue = {highlightedPath: new Set(),highlightedEdges: new Set(),colorMode: "language",- riskScores: new Map(),+ viewMode: "module",hoveredNodeId: null,connectedNodeIds: new Set(),connectedEdgeIds: new Set(),selectedNodeId: null,searchDimmedNodes: null,+ communityDimmedNodes: null,+ layoutMode: "force",+ graphTheme: "light",+ maxPagerank: 0,+ medianPagerank: 0,+ expandedModules: new Set(),+ activeSignals: new Set(),+ egoDepth: 0,+ visibleEdgeTypes: new Set(["import", "crossCommunity", "internal", "dynamic", "lowConfidence"]),};export const GraphContext = createContext<GraphContextValue>(defaultValue);diff --git a/packages/ui/src/graph/edges/dependency-edge.tsx b/packages/ui/src/graph/edges/dependency-edge.tsxdeleted file mode 100644index ecfb585be..000000000--- a/packages/ui/src/graph/edges/dependency-edge.tsx+++ /dev/null@@ -1,104 +0,0 @@-"use client";--import { memo, useContext } from "react";-import {- getBezierPath,- type EdgeProps,-} from "@xyflow/react";-import { GraphContext } from "../context";-import type { DependencyEdgeData } from "../elk-layout";--function DependencyEdgeInner({- id,- sourceX,- sourceY,- targetX,- targetY,- sourcePosition,- targetPosition,- source,- target,- data,-}: EdgeProps) {- const d = (data ?? { importedNames: [], edgeCount: 1 }) as DependencyEdgeData;- const ctx = useContext(GraphContext);-- const isOnPath = ctx.highlightedEdges.has(id);- const hasActivePath = ctx.highlightedPath.size > 0;- const isDimmed = hasActivePath && !isOnPath;- const isDynamic = d.importedNames.length === 0;-- // Hover-aware: highlight edges connected to hovered node- const isHoverHighlighted = ctx.connectedEdgeIds.has(id);- const hasHover = ctx.hoveredNodeId !== null;- const isHoverDimmed = hasHover && !isHoverHighlighted && !hasActivePath;-- const [edgePath] = getBezierPath({- sourceX,- sourceY,- targetX,- targetY,- sourcePosition,- targetPosition,- });-- const strokeWidth = Math.max(1, Math.min(6, 1 + Math.sqrt(d.edgeCount) * 0.8));-- let stroke: string;- let opacity: number;- let dashArray: string | undefined;- let animation: string | undefined;-- if (isOnPath) {- stroke = "var(--color-accent-graph)";- opacity = 1;- dashArray = "6 4";- animation = "graph-marching-ants 0.6s linear infinite";- } else if (isDimmed) {- stroke = "rgba(200, 215, 230, 0.25)";- opacity = 0.5;- } else if (isHoverHighlighted) {- stroke = "#93c5fd";- opacity = 1;- } else if (isHoverDimmed) {- stroke = "rgba(200, 215, 230, 0.15)";- opacity = 0.4;- } else if (isDynamic) {- stroke = "rgba(200, 215, 230, 0.5)";- opacity = 1;- dashArray = "4 4";- } else {- stroke = "rgba(200, 215, 230, 0.55)";- opacity = 1;- }-- const tooltip = d.importedNames.length > 0- ? d.importedNames.slice(0, 10).join(", ") + (d.importedNames.length > 10 ? ` (+${d.importedNames.length - 10} more)` : "")- : `${d.edgeCount} connection${d.edgeCount > 1 ? "s" : ""}`;-- return (- <g>- {/* Invisible wider path for easier hover */}- <path- d={edgePath}- fill="none"- stroke="transparent"- strokeWidth={Math.max(12, strokeWidth + 8)}- >- <title>{tooltip}</title>- </path>- <path- d={edgePath}- fill="none"- stroke={stroke}- strokeWidth={isHoverHighlighted && !isOnPath ? strokeWidth + 0.5 : strokeWidth}- strokeOpacity={opacity}- strokeDasharray={dashArray}- style={{ animation, pointerEvents: "none" }}- className="transition-all duration-200"- />- </g>- );-}--export const DependencyEdge = memo(DependencyEdgeInner);diff --git a/packages/ui/src/graph/elk-layout.ts b/packages/ui/src/graph/elk-layout.tsindex 89e6cc6f7..0e9171199 100644--- a/packages/ui/src/graph/elk-layout.ts+++ b/packages/ui/src/graph/elk-layout.ts@@ -1,5 +1,5 @@/**- * ELK layout engine — transforms graph API data into React Flow nodes/edges.+ * ELK layout engine — computes node positions for the Sigma canvas.** Uses elkjs for deterministic hierarchical layout with compound nodes* representing directories.@@ -7,7 +7,6 @@import ELK from "elkjs/lib/elk.bundled.js";import type { ElkNode, ElkExtendedEdge } from "elkjs";-import type { Node, Edge } from "@xyflow/react";import type {GraphNode as GraphNodeResponse,GraphLink as GraphEdgeResponse,@@ -27,6 +26,7 @@ const elk = new ELK();// ---- Types ----export interface FileNodeData {+ nodeType: "file";label: string;fullPath: string;language: string;@@ -37,10 +37,13 @@ export interface FileNodeData {isTest: boolean;isEntryPoint: boolean;hasDoc: boolean;+ isHotspot?: boolean | undefined;+ isDead?: boolean | undefined;[key: string]: unknown;}export interface ModuleNodeData {+ nodeType: "module";label: string;fullPath: string;fileCount: number;@@ -54,15 +57,25 @@ export interface ModuleNodeData {hasDoc?: boolean;isEntryPoint?: boolean;isTest?: boolean;+ dominantCommunityId?: number | undefined;[key: string]: unknown;}export interface DependencyEdgeData {importedNames: string[];edgeCount: number;+ confidence?: number | undefined;[key: string]: unknown;}+export interface GraphEdge {+ id: string;+ source: string;+ target: string;+ type?: string | undefined;+ data?: Record<string, unknown> | undefined;+}+// ---- Helpers ----/** Extract directory path from a file node_id (everything before the last /). */@@ -85,10 +98,10 @@ function ancestorDirs(dir: string): string[] {/** Deduplicate edges: group by (source, target) pair, merge imported_names, sum count. */function deduplicateEdges(edges: GraphEdgeResponse[],-): { source: string; target: string; importedNames: string[]; edgeCount: number }[] {+): { source: string; target: string; importedNames: string[]; edgeCount: number; confidence: number | undefined }[] {const map = new Map<string,- { source: string; target: string; importedNames: string[]; edgeCount: number }+ { source: string; target: string; importedNames: string[]; edgeCount: number; confidence: number | undefined }>();for (const e of edges) {const key = `${e.source}→${e.target}`;@@ -96,12 +109,16 @@ function deduplicateEdges(if (existing) {existing.importedNames.push(...e.imported_names);existing.edgeCount++;+ if (e.confidence != null) {+ existing.confidence = Math.max(existing.confidence ?? 0, e.confidence);+ }} else {map.set(key, {source: e.source,target: e.target,importedNames: [...e.imported_names],edgeCount: 1,+ confidence: e.confidence,});}}@@ -137,16 +154,29 @@ export function groupNodesAsModules(return { moduleNodes: [], moduleEdges: [], fileEntries: new Map() };}+ // Auto-detect monorepo: if >50% of root-level nodes live under packages/,+ // group by second segment (packages/<name>) instead of first segment.+ const isMonorepo = !prefix &&+ scopedNodes.filter((n) => n.node_id.startsWith("packages/")).length > scopedNodes.length * 0.5;+// Group by next path segment after the prefixconst modules = new Map<string, GraphNodeResponse[]>();const nodeToModule = new Map<string, string>();for (const n of scopedNodes) {const rest = prefix ? n.node_id.slice(slash.length) : n.node_id;- const slashIdx = rest.indexOf("/");- const moduleId = slashIdx >= 0- ? (prefix ? slash + rest.slice(0, slashIdx) : rest.slice(0, slashIdx))- : (prefix ? slash + rest : rest); // file at this level++ let moduleId: string;+ if (isMonorepo && rest.startsWith("packages/")) {+ const afterPkg = rest.slice("packages/".length);+ const idx = afterPkg.indexOf("/");+ moduleId = idx >= 0 ? "packages/" + afterPkg.slice(0, idx) : rest;+ } else {+ const slashIdx = rest.indexOf("/");+ moduleId = slashIdx >= 0+ ? (prefix ? slash + rest.slice(0, slashIdx) : rest.slice(0, slashIdx))+ : (prefix ? slash + rest : rest);+ }const list = modules.get(moduleId) ?? [];list.push(n);@@ -206,19 +236,45 @@ export function groupNodesAsModules(return { moduleNodes, moduleEdges, fileEntries };}-// ---- Layout for file-level graph ----+// ---- Pure position computation (for Sigma bridge) ----++export interface ElkPositionResult {+ positions: Map<string, { x: number; y: number; width: number; height: number }>;+ groups: Map<string, { x: number; y: number; width: number; height: number }>;+}-export async function layoutFileGraph(+function flattenPositions(+ elkNode: ElkNode,+ offsetX = 0,+ offsetY = 0,+ positions: Map<string, { x: number; y: number; width: number; height: number }>,+ groups: Map<string, { x: number; y: number; width: number; height: number }>,+) {+ if (!elkNode.children) return;+ for (const child of elkNode.children) {+ const x = (child.x ?? 0) + offsetX;+ const y = (child.y ?? 0) + offsetY;+ const w = child.width ?? 0;+ const h = child.height ?? 0;+ if (child.id.startsWith("dir:")) {+ groups.set(child.id, { x, y, width: w, height: h });+ flattenPositions(child, x, y, positions, groups);+ } else {+ positions.set(child.id, { x, y, width: w, height: h });+ }+ }+}++export async function computeElkFilePositions(nodes: GraphNodeResponse[],edges: GraphEdgeResponse[],-): Promise<{ nodes: Node[]; edges: Edge[] }> {- if (nodes.length === 0) return { nodes: [], edges: [] };+): Promise<ElkPositionResult> {+ if (nodes.length === 0) return { positions: new Map(), groups: new Map() };const nodeSet = new Set(nodes.map((n) => n.node_id));const validEdges = edges.filter((e) => nodeSet.has(e.source) && nodeSet.has(e.target));const dedupedEdges = deduplicateEdges(validEdges);- // Build directory hierarchyconst dirSet = new Set<string>();for (const n of nodes) {const dir = dirOf(n.node_id);@@ -229,10 +285,8 @@ export async function layoutFileGraph(}}- // Sort dirs so parents come before childrenconst dirs = Array.from(dirSet).sort();- // Build ELK compound graphconst elkGraph: ElkNode = {id: "root",layoutOptions: {@@ -250,7 +304,6 @@ export async function layoutFileGraph(edges: [],};- // Create dir nodes as groupsconst dirElkNodes = new Map<string, ElkNode>();for (const dir of dirs) {const parts = dir.split("/");@@ -266,7 +319,6 @@ export async function layoutFileGraph(dirElkNodes.set(dir, elkNode);}- // Nest dir nodes into their parentsfor (const dir of dirs) {const parentDir = dirOf(dir);const parentElk = parentDir ? dirElkNodes.get(parentDir) : null;@@ -278,7 +330,6 @@ export async function layoutFileGraph(}}- // Add file nodes (sized by pagerank importance)for (const n of nodes) {const scale = 1 + Math.min(0.6, n.pagerank * 25);const elkFileNode: ElkNode = {@@ -296,7 +347,6 @@ export async function layoutFileGraph(}}- // Add edges — ELK needs hierarchical edge formatconst elkEdges: ElkExtendedEdge[] = dedupedEdges.map((e, i) => ({id: `e${i}`,sources: [e.source],@@ -304,122 +354,98 @@ export async function layoutFileGraph(}));elkGraph.edges = elkEdges;- // Compute layoutconst layout = await elk.layout(elkGraph);- // Flatten layout into React Flow nodes- const rfNodes: Node[] = [];- const rfEdges: Edge[] = [];-- function extractNodes(- elkNode: ElkNode,- parentId?: string,- offsetX = 0,- offsetY = 0,- ) {- if (!elkNode.children) return;- for (const child of elkNode.children) {- const x = (child.x ?? 0) + offsetX;- const y = (child.y ?? 0) + offsetY;- const isDir = child.id.startsWith("dir:");-- if (isDir) {- const dirPath = child.id.slice(4);- const label = child.labels?.[0]?.text ?? dirPath;- rfNodes.push({- id: child.id,- type: "moduleGroup",- position: { x: child.x ?? 0, y: child.y ?? 0 },- ...(parentId ? { parentId, extent: "parent" as const } : {}),- style: {- width: child.width,- height: child.height,- },- data: {- label,- fullPath: dirPath,- fileCount: child.children?.filter((c) => !c.id.startsWith("dir:")).length ?? 0,- } satisfies Record<string, unknown>,- });- // Recurse into children- extractNodes(child, child.id);- } else {- const apiNode = nodes.find((n) => n.node_id === child.id);- if (apiNode) {- rfNodes.push({- id: child.id,- type: "fileNode",- position: { x: child.x ?? 0, y: child.y ?? 0 },- ...(parentId ? { parentId, extent: "parent" as const } : {}),- data: {- label: child.labels?.[0]?.text ?? apiNode.node_id,- fullPath: apiNode.node_id,- language: apiNode.language,- symbolCount: apiNode.symbol_count,- pagerank: apiNode.pagerank,- betweenness: apiNode.betweenness,- communityId: apiNode.community_id,- isTest: apiNode.is_test,- isEntryPoint: apiNode.is_entry_point,- hasDoc: apiNode.has_doc,- // View-specific fields (dead code, hot files)- ...("confidence_group" in apiNode && { confidenceGroup: (apiNode as Record<string, unknown>).confidence_group }),- ...("commit_count" in apiNode && { commitCount: (apiNode as Record<string, unknown>).commit_count }),- } satisfies FileNodeData,- });- }- }+ const positions = new Map<string, { x: number; y: number; width: number; height: number }>();+ const groups = new Map<string, { x: number; y: number; width: number; height: number }>();+ flattenPositions(layout, 0, 0, positions, groups);++ return { positions, groups };+}++export async function computeElkModulePositions(+ moduleNodes: ModuleNodeResponse[],+ moduleEdges: ModuleEdgeResponse[],+): Promise<Map<string, { x: number; y: number }>> {+ if (moduleNodes.length === 0) return new Map();++ const moduleIds = new Set(moduleNodes.map((m) => m.module_id));++ // Build all ancestor directories for compound node nesting+ const dirSet = new Set<string>();+ for (const m of moduleNodes) {+ const ancestors = ancestorDirs(dirOf(m.module_id));+ for (const a of ancestors) {+ if (!moduleIds.has(a)) dirSet.add(a);}}+ const dirs = Array.from(dirSet).sort();- extractNodes(layout);-- // Build React Flow edges- for (const e of dedupedEdges) {- rfEdges.push({- id: `${e.source}→${e.target}`,- source: e.source,- target: e.target,- type: "dependency",- data: {- importedNames: e.importedNames,- edgeCount: e.edgeCount,- } satisfies DependencyEdgeData,+ // Create ELK compound nodes for each directory+ const dirElkNodes = new Map<string, ElkNode>();+ for (const dir of dirs) {+ dirElkNodes.set(dir, {+ id: `dir:${dir}`,+ labels: [{ text: dir.split("/").pop() ?? dir }],+ layoutOptions: {+ "elk.padding": "[top=35,left=12,bottom=12,right=12]",+ },+ children: [],});}- return { nodes: rfNodes, edges: rfEdges };-}+ // Nest directories into their parents+ const rootChildren: ElkNode[] = [];+ for (const dir of dirs) {+ const parentDir = dirOf(dir);+ const parentElk = parentDir ? dirElkNodes.get(parentDir) : null;+ const elkNode = dirElkNodes.get(dir)!;+ if (parentElk) {+ parentElk.children!.push(elkNode);+ } else {+ rootChildren.push(elkNode);+ }+ }-// ---- Layout for module-level graph ----+ // Place module nodes into their parent directory (or root)+ for (const m of moduleNodes) {+ const elkNode: ElkNode = {+ id: m.module_id,+ width: MODULE_NODE_WIDTH,+ height: MODULE_NODE_HEIGHT,+ labels: [{ text: m.module_id.split("/").pop() ?? m.module_id }],+ };+ const parentDir = dirOf(m.module_id);+ const parentElk = parentDir ? dirElkNodes.get(parentDir) : null;+ if (parentElk) {+ parentElk.children!.push(elkNode);+ } else {+ rootChildren.push(elkNode);+ }+ }-export async function layoutModuleGraph(- moduleNodes: ModuleNodeResponse[],- moduleEdges: ModuleEdgeResponse[],- fileEntries?: Map<string, GraphNodeResponse>,-): Promise<{ nodes: Node[]; edges: Edge[] }> {- if (moduleNodes.length === 0) return { nodes: [], edges: [] };+ // Remove empty compound nodes (directories with no children)+ function pruneEmpty(node: ElkNode): boolean {+ if (!node.children) return true;+ node.children = node.children.filter(pruneEmpty);+ return node.children.length > 0 || !node.id.startsWith("dir:");+ }+ rootChildren.forEach(pruneEmpty);const elkGraph: ElkNode = {id: "root",layoutOptions: {"elk.algorithm": "layered","elk.direction": "DOWN",- "elk.layered.spacing.nodeNodeBetweenLayers": "80",- "elk.layered.spacing.edgeNodeBetweenLayers": "40",- "elk.spacing.nodeNode": "40",- "elk.spacing.componentComponent": "60",+ "elk.layered.spacing.nodeNodeBetweenLayers": "60",+ "elk.layered.spacing.edgeNodeBetweenLayers": "30",+ "elk.spacing.nodeNode": "25",+ "elk.spacing.componentComponent": "50",+ "elk.hierarchyHandling": "INCLUDE_CHILDREN","elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",+ "elk.padding": "[top=25,left=20,bottom=20,right=20]",},- children: moduleNodes.map((m) => {- const isFile = fileEntries?.has(m.module_id) ?? false;- return {- id: m.module_id,- width: isFile ? FILE_NODE_WIDTH : MODULE_NODE_WIDTH,- height: isFile ? FILE_NODE_HEIGHT : MODULE_NODE_HEIGHT,- labels: [{ text: m.module_id }],- };- }),+ children: rootChildren,edges: moduleEdges.map((e, i) => ({id: `me${i}`,sources: [e.source],@@ -429,70 +455,20 @@ export async function layoutModuleGraph(const layout = await elk.layout(elkGraph);- const rfNodes: Node[] = (layout.children ?? []).map((child) => {- const apiNode = moduleNodes.find((m) => m.module_id === child.id)!;- const fileEntry = fileEntries?.get(child.id);- const isFile = !!fileEntry;- const label = child.id.split("/").pop() ?? child.id;-- if (isFile) {- // Render as a FileNode- return {- id: child.id,- type: "fileNode",- position: { x: child.x ?? 0, y: child.y ?? 0 },- data: {- label,- fullPath: child.id,- language: fileEntry.language,- symbolCount: fileEntry.symbol_count,- pagerank: fileEntry.pagerank,- betweenness: fileEntry.betweenness,- communityId: fileEntry.community_id,- isTest: fileEntry.is_test,- isEntryPoint: fileEntry.is_entry_point,- hasDoc: fileEntry.has_doc,- ...("confidence_group" in fileEntry && { confidenceGroup: (fileEntry as Record<string, unknown>).confidence_group }),- ...("commit_count" in fileEntry && { commitCount: (fileEntry as Record<string, unknown>).commit_count }),- } satisfies FileNodeData,- };+ const positions = new Map<string, { x: number; y: number }>();+ const extractPositions = (node: ElkNode, ox = 0, oy = 0) => {+ for (const child of node.children ?? []) {+ const x = (child.x ?? 0) + ox;+ const y = (child.y ?? 0) + oy;+ if (child.id.startsWith("dir:")) {+ extractPositions(child, x, y);+ } else {+ positions.set(child.id, { x, y });+ }}+ };+ extractPositions(layout);- return {- id: child.id,- type: "moduleGroup",- position: { x: child.x ?? 0, y: child.y ?? 0 },- data: {- label,- fullPath: child.id,- fileCount: apiNode.file_count,- symbolCount: apiNode.symbol_count,- avgPagerank: apiNode.avg_pagerank,- docCoveragePct: apiNode.doc_coverage_pct,- } satisfies ModuleNodeData,- };- });-- // Deduplicate module edges- const edgeMap = new Map<string, number>();- for (const e of moduleEdges) {- const key = `${e.source}→${e.target}`;- edgeMap.set(key, (edgeMap.get(key) ?? 0) + e.edge_count);- }-- const rfEdges: Edge[] = Array.from(edgeMap.entries()).map(([key, count]) => {- const [source = "", target = ""] = key.split("→");- return {- id: key,- source,- target,- type: "dependency",- data: {- importedNames: [],- edgeCount: count,- } satisfies DependencyEdgeData,- };- });-- return { nodes: rfNodes, edges: rfEdges };+ return positions;}+diff --git a/packages/ui/src/graph/graph-context-menu.tsx b/packages/ui/src/graph/graph-context-menu.tsxindex 5c637f2a9..4f8dc7991 100644--- a/packages/ui/src/graph/graph-context-menu.tsx+++ b/packages/ui/src/graph/graph-context-menu.tsx@@ -1,5 +1,6 @@"use client";+import { memo } from "react";import { FileText, Search, Route, ArrowRightFromLine, ArrowLeftToLine } from "lucide-react";interface GraphContextMenuProps {@@ -13,7 +14,7 @@ interface GraphContextMenuProps {onPathTo: () => void;}-export function GraphContextMenu({+export const GraphContextMenu = memo(function GraphContextMenu({x,y,nodeId,@@ -69,4 +70,4 @@ export function GraphContextMenu({</button></div>);-}+});diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex 99a3bdc9b..fdb8979f6 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -8,97 +8,60 @@ import {useRef,type ReactNode,} from "react";-import {- ReactFlow,- MiniMap,- Controls,- Background,- BackgroundVariant,- ReactFlowProvider,- useReactFlow,- type NodeMouseHandler,- type Node,-} from "@xyflow/react";-import "@xyflow/react/dist/style.css";-import { Loader2, ChevronRight, Home } from "lucide-react";+import { ChevronRight, Home } from "lucide-react";import Fuse from "fuse.js";import { Skeleton } from "../ui/skeleton";import { EmptyState } from "../shared/empty-state";-import { ModuleGroupNode } from "./nodes/module-group-node";-import { FileNode } from "./nodes/file-node";-import { DependencyEdge } from "./edges/dependency-edge";-import { GraphProvider, type GraphContextValue } from "./context";-import { GraphTooltip } from "./graph-tooltip";-import { groupNodesAsModules, type FileNodeData } from "./elk-layout";-import { useModuleElkLayout, useFileElkLayout } from "./use-elk-layout";-import { GraphToolbar, type ColorMode, type ViewMode } from "./graph-toolbar";+import { GraphProvider, type GraphContextValue, type Signal } from "./context";+import { groupNodesAsModules, type FileNodeData, type ModuleNodeData } from "./elk-layout";++const EMPTY_STRING_SET = new Set<string>();+import { useExpandedModules } from "./use-expanded-modules";+import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme } from "./graph-toolbar";import { GraphLegend } from "./graph-legend";import { GraphContextMenu } from "./graph-context-menu";-import { languageColor } from "../lib/confidence";+import { GraphInspectionPanel } from "./graph-inspection-panel";import type {GraphExport,ModuleGraph,ExecutionFlows,CommunitySummaryItem,} from "@repowise-dev/types/graph";--// ---- Node/Edge types ------const nodeTypes = {- moduleGroup: ModuleGroupNode,- fileNode: FileNode,-};--const edgeTypes = {- dependency: DependencyEdge,-};--// ---- Props ----+import { SigmaCanvas, type SigmaCanvasHandle } from "./sigma/sigma-canvas";+import {+ fileGraphToGraphology,+ moduleGraphToGraphology,+ groupFilesAsModules,+} from "./sigma/graphology-adapter";+import { useEgoFilter } from "./sigma/use-ego-filter";+import {+ NODE_BASE_SIZES,+ EDGE_COLORS,+ getScaledNodeSize,+ getNodeMass,+ languageColor as sigmaLanguageColor,+} from "./sigma/constants";export interface GraphFlowProps {- /** Top-level module rollup; only fetched/needed for the module view at root. */moduleGraph: ModuleGraph | undefined;isLoadingModuleGraph: boolean;-- /** Full file-level graph; needed for drill-down and the "full" view. */fullGraph: GraphExport | undefined;isLoadingFullGraph: boolean;-- /** Architecture view graph. */architectureGraph: GraphExport | undefined;isLoadingArchitectureGraph: boolean;-- /** Dead-code view graph. */deadCodeGraph: GraphExport | undefined;isLoadingDeadCodeGraph: boolean;-- /** Hot-files view graph. */hotFilesGraph: GraphExport | undefined;isLoadingHotFilesGraph: boolean;-- /** Community list — used for legend labels and detail panel lookup. */communities?: CommunitySummaryItem[];-- /** Execution-flows data — used for the side panel and trace highlighting. */executionFlows?: ExecutionFlows;-- /**- * Called when a view-mode change requires the consumer to (re)load- * datasets that aren't already supplied. The shell does NOT fetch — the- * wrapper observes this and triggers SWR / mutate as needed.- */+ initialViewMode?: ViewMode;+ initialSelectedNode?: string | null;onViewModeChange?: (mode: ViewMode) => void;- /** Same idea for drill-down. The shell exposes the current module path. */onModulePathChange?: (path: string[]) => void;-- /** Node-level interactions surfaced to the consumer. */+ onExpandedModulesChange?: (expanded: Set<string>) => void;onNodeClick?: (nodeId: string, nodeType: string) => void | Promise<void>;onNodeViewDocs?: (nodeId: string) => void;-- /**- * Render the path-finder sub-panel. The shell only decides when to mount- * it and provides path-finder context (initial from/to, callbacks).- */renderPathFinder?: (props: {initialFrom: string;initialTo: string;@@ -106,20 +69,13 @@ export interface GraphFlowProps {onClear: () => void;onClose: () => void;}) => ReactNode;-- /**- * Render the community detail panel. The shell only owns the- * `communityId` selection state.- */renderCommunityPanel?: (props: {communityId: number;onClose: () => void;}) => ReactNode;}-// ---- Inner component (needs ReactFlowProvider) ------function GraphFlowInner(props: GraphFlowProps) {+export function GraphFlow(props: GraphFlowProps) {const {moduleGraph,isLoadingModuleGraph,@@ -133,41 +89,72 @@ function GraphFlowInner(props: GraphFlowProps) {isLoadingHotFilesGraph,communities,executionFlows,+ initialViewMode,+ initialSelectedNode,onViewModeChange,onModulePathChange,+ onExpandedModulesChange,onNodeClick,onNodeViewDocs,renderPathFinder,renderCommunityPanel,} = props;- const reactFlow = useReactFlow();+ const sigmaRef = useRef<SigmaCanvasHandle>(null);+ const focusTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);- // State — read initial colorMode from URL if present- const [viewMode, setViewMode] = useState<ViewMode>("module");+ // ---- Core state ----+ const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "module");const [colorMode, setColorMode] = useState<ColorMode>(() => {if (typeof window !== "undefined") {const params = new URLSearchParams(window.location.search);const cm = params.get("colorMode");if (cm === "community" || cm === "language" || cm === "risk") return cm;}- return "language";+ return "community";});- const [hideTests, setHideTests] = useState(false);const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());const [showPathFinder, setShowPathFinder] = useState(false);+ const [layoutMode, setLayoutMode] = useState<LayoutMode>("force");+ const [graphTheme, setGraphTheme] = useState<GraphTheme>("light");++ const [egoDepth, setEgoDepth] = useState(0);++ const [visibleEdgeTypes, setVisibleEdgeTypes] = useState<Set<string>>(+ () => new Set(["import", "crossCommunity"]),+ );- // Drill-down: stack of module prefixes. e.g. ["packages", "packages/web"]+ // Signal overlays (replaces separate view modes for dead/hot/arch)+ const [activeSignals, setActiveSignals] = useState<Set<Signal>>(() => {+ if (typeof window !== "undefined") {+ const params = new URLSearchParams(window.location.search);+ const vm = params.get("viewMode");+ if (vm === "dead") return new Set<Signal>(["dead"]);+ if (vm === "hotfiles") return new Set<Signal>(["hot"]);+ if (vm === "unified") return new Set<Signal>(["dead", "hot"]);+ }+ return new Set<Signal>();+ });+ const hideTests = activeSignals.has("hideTests");++ // Expand/collapse modules (replaces drill-down for most use cases)+ const { expandedModules, toggleModule, collapseAll } = useExpandedModules();+ const hasExpandedModules = expandedModules.size > 0;++ // Legacy drill-down (breadcrumb nav, kept for deep-dive via context menu)const [modulePath, setModulePath] = useState<string[]>([]);const currentPrefix = modulePath.length > 0 ? (modulePath[modulePath.length - 1] ?? "") : "";const isDrilledDown = modulePath.length > 0;- // Notify consumer of module-path changes (so it can fetch full graph etc.)useEffect(() => {onModulePathChange?.(modulePath);}, [modulePath, onModulePathChange]);+ useEffect(() => {+ onExpandedModulesChange?.(expandedModules);+ }, [expandedModules, onExpandedModulesChange]);+// Context menuconst [ctxMenu, setCtxMenu] = useState<{x: number; y: number; nodeId: string; nodeType: string;@@ -177,24 +164,27 @@ function GraphFlowInner(props: GraphFlowProps) {const [pathFrom, setPathFrom] = useState("");const [pathTo, setPathTo] = useState("");- // Hover & selection tracking+ // Hover & selectionconst [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);- const [selectedNodeScreen, setSelectedNodeScreen] = useState<{ x: number; y: number } | null>(null);- // Graph search+ // Searchconst [searchQuery, setSearchQuery] = useState("");const [searchDimmedNodes, setSearchDimmedNodes] = useState<Set<string> | null>(null);+ const [searchResults, setSearchResults] = useState<string[]>([]);+ const [searchResultIndex, setSearchResultIndex] = useState(0);- // Execution flow highlighting+ // Execution flowsconst [activeFlowIdx, setActiveFlowIdx] = useState<number | null>(null);const [showFlows, setShowFlows] = useState(false);- // Community panel selection+ // Community panel & filteringconst [communityPanelId, setCommunityPanelId] = useState<number | null>(null);+ const [activeCommunities, setActiveCommunities] = useState<Set<number> | null>(null);- // ---- Data selection (consumer supplies the data; shell picks the right slice) ----+ // ---- Derived state ----const isModuleView = viewMode === "module";+ const isUnified = viewMode === "unified";const communityLabels = useMemo(() => {if (!communities) return undefined;@@ -203,18 +193,17 @@ function GraphFlowInner(props: GraphFlowProps) {return m;}, [communities]);- // ---- Derived data ------ // When drilled down, re-group nodes as sub-modules at the current prefix+ // Drill-down dataconst drillDownData = useMemo(() => {if (!isDrilledDown || !fullGraph) return null;return groupNodesAsModules(fullGraph.nodes, fullGraph.links, currentPrefix);}, [isDrilledDown, fullGraph, currentPrefix]);- // File-level graph data — only for non-module views+ // File-level graph data for non-module viewsconst fileGraphData = useMemo(() => {switch (viewMode) {case "full":+ case "unified":return fullGraph ? { nodes: fullGraph.nodes, links: fullGraph.links } : undefined;case "architecture":return architectureGraph@@ -233,101 +222,295 @@ function GraphFlowInner(props: GraphFlowProps) {}}, [viewMode, fullGraph, architectureGraph, deadCodeGraph, hotFilesGraph]);- // ---- Layout selection ----- const moduleLayoutInput = useMemo(() => {- if (!isModuleView) return { nodes: undefined, edges: undefined, fileEntries: undefined };- if (!isDrilledDown) {- return { nodes: moduleGraph?.nodes, edges: moduleGraph?.edges, fileEntries: undefined };+ // Loading state+ const isLoading =+ (isModuleView && !isDrilledDown) ? isLoadingModuleGraph :+ isDrilledDown ? isLoadingFullGraph :+ viewMode === "full" || viewMode === "unified" ? isLoadingFullGraph :+ viewMode === "architecture" ? isLoadingArchitectureGraph :+ viewMode === "dead" ? isLoadingDeadCodeGraph :+ viewMode === "hotfiles" ? isLoadingHotFilesGraph : false;++ // Signal overlay node sets+ const hotNodeIds = useMemo(() => {+ if (!hotFilesGraph) return new Set<string>();+ return new Set(hotFilesGraph.nodes.map((n) => n.node_id));+ }, [hotFilesGraph]);++ const deadNodeIds = useMemo(() => {+ if (!deadCodeGraph) return new Set<string>();+ return new Set(deadCodeGraph.nodes.map((n) => n.node_id));+ }, [deadCodeGraph]);++ const hasDeadSignal = activeSignals.has("dead");+ const hasHotSignal = activeSignals.has("hot");++ // Pre-build indexes for O(1) module expansion lookups (Fix 1.1)+ const fullGraphIndexes = useMemo(() => {+ if (!fullGraph) return null;+ const moduleChildIndex = new Map<string, typeof fullGraph.nodes>();+ const nodeEdgeIndex = new Map<string, typeof fullGraph.links>();++ for (const node of fullGraph.nodes) {+ const parts = node.node_id.split("/");+ for (let depth = 1; depth < parts.length; depth++) {+ const prefix = parts.slice(0, depth).join("/");+ let children = moduleChildIndex.get(prefix);+ if (!children) { children = []; moduleChildIndex.set(prefix, children); }+ children.push(node);+ }}- return {- nodes: drillDownData?.moduleNodes,- edges: drillDownData?.moduleEdges,- fileEntries: drillDownData?.fileEntries,- };- }, [isModuleView, isDrilledDown, moduleGraph, drillDownData]);+ for (const link of fullGraph.links) {+ let srcEdges = nodeEdgeIndex.get(link.source);+ if (!srcEdges) { srcEdges = []; nodeEdgeIndex.set(link.source, srcEdges); }+ srcEdges.push(link);+ let tgtEdges = nodeEdgeIndex.get(link.target);+ if (!tgtEdges) { tgtEdges = []; nodeEdgeIndex.set(link.target, tgtEdges); }+ tgtEdges.push(link);+ }+ return { moduleChildIndex, nodeEdgeIndex };+ }, [fullGraph]);++ // Build Graphology graph for Sigma rendering+ const sigmaGraph = useMemo(() => {+ if (isModuleView) {+ if (isDrilledDown && fullGraph) {+ return groupFilesAsModules(fullGraph, { prefix: currentPrefix });+ }- const {- nodes: moduleNodes,- edges: moduleEdges,- isLayouting: moduleLayouting,- } = useModuleElkLayout(moduleLayoutInput.nodes, moduleLayoutInput.edges, moduleLayoutInput.fileEntries);+ if (!moduleGraph) return null;- const {- nodes: fileNodes,- edges: fileEdges,- isLayouting: fileLayouting,- } = useFileElkLayout(- !isModuleView ? fileGraphData?.nodes : undefined,- !isModuleView ? fileGraphData?.links : undefined,- );+ if (expandedModules.size === 0 || !fullGraph || !fullGraphIndexes) {+ return moduleGraphToGraphology(moduleGraph, communities ? { communities } : {});+ }- const currentNodes = isModuleView ? moduleNodes : fileNodes;- const currentEdges = isModuleView ? moduleEdges : fileEdges;+ const graph = moduleGraphToGraphology(moduleGraph, communities ? { communities } : {});++ for (const moduleId of expandedModules) {+ if (!graph.hasNode(moduleId)) continue;++ const modAttrs = graph.getNodeAttributes(moduleId);+ const modX = modAttrs.x;+ const modY = modAttrs.y;++ graph.dropNode(moduleId);++ const childNodes = fullGraphIndexes.moduleChildIndex.get(moduleId) ?? [];++ const nodeCount = fullGraph.nodes.length;+ const jitter = 30;++ for (const node of childNodes) {+ if (graph.hasNode(node.node_id)) continue;+ const baseSize = node.is_entry_point+ ? NODE_BASE_SIZES.entryPoint+ : node.is_test ? NODE_BASE_SIZES.test : NODE_BASE_SIZES.file;+ let size = getScaledNodeSize(baseSize, nodeCount);+ size *= Math.min(1 + node.pagerank * 2, 2);+ const color = sigmaLanguageColor(node.language);++ graph.addNode(node.node_id, {+ x: modX + (Math.random() - 0.5) * jitter,+ y: modY + (Math.random() - 0.5) * jitter,+ size,+ color,+ label: node.node_id.split("/").pop() ?? node.node_id,+ nodeType: "file",+ fullPath: node.node_id,+ language: node.language,+ communityId: node.community_id,+ pagerank: node.pagerank,+ betweenness: node.betweenness,+ isTest: node.is_test,+ isEntryPoint: node.is_entry_point,+ hasDoc: node.has_doc,+ symbolCount: node.symbol_count,+ mass: getNodeMass("file", nodeCount),+ originalColor: color,+ });+ }- // Filter hidden tests- const filteredNodes = useMemo(() => {- if (!hideTests) return currentNodes;- return currentNodes.filter((n) => {- if (n.type === "fileNode") {- return !(n.data as { isTest?: boolean }).isTest;+ const childIds = new Set(childNodes.map((n) => n.node_id));+ const seenEdges = new Set<string>();+ for (const childId of childIds) {+ const edges = fullGraphIndexes.nodeEdgeIndex.get(childId) ?? [];+ for (const link of edges) {+ const edgeKey = link.source + "→" + link.target;+ if (seenEdges.has(edgeKey)) continue;+ seenEdges.add(edgeKey);++ const srcInModule = childIds.has(link.source);+ const tgtInModule = childIds.has(link.target);++ if (srcInModule && tgtInModule) {+ if (!graph.hasEdge(edgeKey) && graph.hasNode(link.source) && graph.hasNode(link.target)) {+ graph.addEdgeWithKey(edgeKey, link.source, link.target, {+ size: 0.4,+ color: EDGE_COLORS.internal,+ type: "curved",+ curvature: 0.15,+ edgeKind: "internal",+ importedNames: link.imported_names,+ edgeCount: 1,+ });+ }+ } else if (srcInModule && graph.hasNode(link.target)) {+ if (!graph.hasEdge(edgeKey)) {+ graph.addEdgeWithKey(edgeKey, link.source, link.target, {+ size: 0.5,+ color: EDGE_COLORS.import,+ type: "curved",+ curvature: 0.15,+ edgeKind: "import",+ importedNames: link.imported_names,+ edgeCount: 1,+ });+ }+ } else if (tgtInModule && graph.hasNode(link.source)) {+ if (!graph.hasEdge(edgeKey)) {+ graph.addEdgeWithKey(edgeKey, link.source, link.target, {+ size: 0.5,+ color: EDGE_COLORS.import,+ type: "curved",+ curvature: 0.15,+ edgeKind: "import",+ importedNames: link.imported_names,+ edgeCount: 1,+ });+ }+ }+ }+ }}- return true;- });- }, [currentNodes, hideTests]);- const isLoading =- (isModuleView && !isDrilledDown) ? isLoadingModuleGraph :- isDrilledDown ? isLoadingFullGraph :- viewMode === "full" ? isLoadingFullGraph :- viewMode === "architecture" ? isLoadingArchitectureGraph :- viewMode === "dead" ? isLoadingDeadCodeGraph :- viewMode === "hotfiles" ? isLoadingHotFilesGraph : false;- const isLayouting = isModuleView ? moduleLayouting : fileLayouting;-- // Compute connected nodes/edges for hover highlighting- const { connectedNodeIds, connectedEdgeIds } = useMemo(() => {- if (!hoveredNodeId) return { connectedNodeIds: new Set<string>(), connectedEdgeIds: new Set<string>() };- const nodeIds = new Set<string>([hoveredNodeId]);- const edgeIds = new Set<string>();- for (const edge of currentEdges) {- if (edge.source === hoveredNodeId || edge.target === hoveredNodeId) {- edgeIds.add(edge.id);- nodeIds.add(edge.source);- nodeIds.add(edge.target);+ return graph;+ }++ const graphData = fileGraphData;+ if (!graphData) return null;++ const signals: { hotNodeIds?: Set<string>; deadNodeIds?: Set<string> } = {};+ if (hasHotSignal || isUnified) signals.hotNodeIds = hotNodeIds;+ if (hasDeadSignal || isUnified) signals.deadNodeIds = deadNodeIds;++ return fileGraphToGraphology(+ { nodes: graphData.nodes, links: graphData.links },+ { signals },+ );+ }, [isModuleView, isDrilledDown, fullGraph, currentPrefix, moduleGraph, communities, expandedModules, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, fullGraphIndexes]);++ const { hiddenNodes, isActive: isEgoActive, visibleCount: egoVisibleCount } = useEgoFilter({+ graph: sigmaGraph,+ selectedNodeId,+ depth: egoDepth,+ });++ // Node data maps (sorted metrics moved into GraphInspectionPanel)+ const sigmaNodeMaps = useMemo(() => {+ if (!sigmaGraph) return null;++ const fileMap = new Map<string, FileNodeData>();+ const modMap = new Map<string, ModuleNodeData>();++ sigmaGraph.forEachNode((nodeId, attrs) => {+ if (attrs.nodeType === "file") {+ const fileData: FileNodeData = {+ nodeType: "file",+ label: attrs.label,+ fullPath: attrs.fullPath,+ language: attrs.language,+ symbolCount: attrs.symbolCount,+ pagerank: attrs.pagerank,+ betweenness: attrs.betweenness,+ communityId: attrs.communityId,+ isTest: attrs.isTest,+ isEntryPoint: attrs.isEntryPoint,+ hasDoc: attrs.hasDoc,+ };+ if (attrs.isHotspot) fileData.isHotspot = true;+ if (attrs.isDead) fileData.isDead = true;+ fileMap.set(nodeId, fileData);+ } else if (attrs.nodeType === "module") {+ modMap.set(nodeId, {+ nodeType: "module",+ label: attrs.label,+ fullPath: attrs.fullPath,+ fileCount: attrs.fileCount ?? 0,+ symbolCount: attrs.symbolCount,+ avgPagerank: attrs.avgPagerank ?? 0,+ docCoveragePct: attrs.docCoveragePct ?? 0,+ dominantCommunityId: attrs.dominantCommunityId,+ });}+ });++ return { fileMap, modMap };+ }, [sigmaGraph]);++ const effectiveNodeDataMap = sigmaNodeMaps?.fileMap ?? new Map<string, FileNodeData>();+ const effectiveModuleDataMap = sigmaNodeMaps?.modMap ?? new Map<string, ModuleNodeData>();++ // Community dimming+ const communityDimmedNodes = useMemo(() => {+ if (!activeCommunities) return null;+ const dimmed = new Set<string>();+ if (sigmaGraph) {+ sigmaGraph.forEachNode((nodeId, attrs) => {+ if (attrs.nodeType === "file" && !activeCommunities.has(attrs.communityId)) {+ dimmed.add(nodeId);+ }+ });}- return { connectedNodeIds: nodeIds, connectedEdgeIds: edgeIds };- }, [hoveredNodeId, currentEdges]);+ return dimmed.size > 0 ? dimmed : null;+ }, [activeCommunities, sigmaGraph]);- // Fuse search index over visible nodes+ // Searchconst fuseIndex = useMemo(() => {- const items = filteredNodes.map((n) => ({ id: n.id, label: (n.data as { label?: string }).label ?? n.id }));+ if (!sigmaGraph) return new Fuse<{ id: string; label: string }>([], { keys: ["id", "label"], threshold: 0.4 });+ const items: { id: string; label: string }[] = [];+ sigmaGraph.forEachNode((id, attrs) => {+ if (hideTests && attrs.isTest) return;+ items.push({ id, label: attrs.label });+ });return new Fuse(items, { keys: ["id", "label"], threshold: 0.4 });- }, [filteredNodes]);+ }, [sigmaGraph, hideTests]);- // Search: compute dimmed set when query is active+ const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);useEffect(() => {if (!searchQuery || searchQuery.length < 2) {+ clearTimeout(searchTimerRef.current);setSearchDimmedNodes(null);+ setSearchResults([]);+ setSearchResultIndex(0);return;}- const results = fuseIndex.search(searchQuery);- const matchIds = new Set(results.map((r) => r.item.id));- const dimmed = new Set<string>();- for (const n of filteredNodes) {- if (!matchIds.has(n.id)) dimmed.add(n.id);- }- setSearchDimmedNodes(dimmed);-- if (results.length > 0 && results.length <= 20) {- const matchedRfNodes = results- .map((r) => reactFlow.getNode(r.item.id))- .filter(Boolean) as Node[];- if (matchedRfNodes.length > 0) {- reactFlow.fitView({ nodes: matchedRfNodes, padding: 0.4, duration: 500 });+ clearTimeout(searchTimerRef.current);+ searchTimerRef.current = setTimeout(() => {+ const results = fuseIndex.search(searchQuery);+ const matchIds = new Set(results.map((r) => r.item.id));+ const ids = results.map((r) => r.item.id);+ const dimmed = new Set<string>();++ if (sigmaGraph) {+ sigmaGraph.forEachNode((nodeId) => {+ if (!matchIds.has(nodeId)) dimmed.add(nodeId);+ });}- }- }, [searchQuery, fuseIndex, filteredNodes, reactFlow]);++ setSearchDimmedNodes(dimmed);+ setSearchResults(ids);+ setSearchResultIndex(0);++ if (ids.length === 1) {+ setSelectedNodeId(ids[0]!);+ }++ if (ids.length > 0 && ids.length <= 20) {+ sigmaRef.current?.focusNode(ids[0]!);+ }+ }, 150);+ return () => clearTimeout(searchTimerRef.current);+ }, [searchQuery, fuseIndex, sigmaGraph]);// Execution flow highlightinguseEffect(() => {@@ -355,88 +538,72 @@ function GraphFlowInner(props: GraphFlowProps) {onViewModeChange?.("full");}- setTimeout(() => {- const traceNodes = flow.trace- .map((id) => reactFlow.getNode(id))- .filter(Boolean) as Node[];- if (traceNodes.length > 0) {- reactFlow.fitView({ nodes: traceNodes, padding: 0.3, duration: 600 });- }+ clearTimeout(focusTimerRef.current);+ focusTimerRef.current = setTimeout(() => {+ const firstNode = flow.trace[0];+ if (firstNode) sigmaRef.current?.focusNode(firstNode);}, 800);+ return () => clearTimeout(focusTimerRef.current);// eslint-disable-next-line react-hooks/exhaustive-deps}, [activeFlowIdx, executionFlows]);- // Context value+ // Context value (hover fields use static empty sets — highlighting handled by Sigma reducers)const ctxValue = useMemo<GraphContextValue>(() => ({highlightedPath,highlightedEdges,colorMode,- riskScores: new Map(),+ viewMode,hoveredNodeId,- connectedNodeIds,- connectedEdgeIds,+ connectedNodeIds: EMPTY_STRING_SET,+ connectedEdgeIds: EMPTY_STRING_SET,selectedNodeId,searchDimmedNodes,+ communityDimmedNodes,+ layoutMode,+ graphTheme,+ maxPagerank: 0,+ medianPagerank: 0,+ expandedModules,+ activeSignals,+ egoDepth,+ visibleEdgeTypes,}),- [highlightedPath, highlightedEdges, colorMode, hoveredNodeId, connectedNodeIds, connectedEdgeIds, selectedNodeId, searchDimmedNodes],+ [highlightedPath, highlightedEdges, colorMode, viewMode, hoveredNodeId, selectedNodeId, searchDimmedNodes, communityDimmedNodes, layoutMode, graphTheme, expandedModules, activeSignals, egoDepth, visibleEdgeTypes],);// ---- Handlers ----- const handleNodeClick: NodeMouseHandler = useCallback(- (event, node) => {- if (node.type === "moduleGroup" && isModuleView) {- setModulePath((prev) => [...prev, node.id]);- setSelectedNodeId(null);- return;- }- if (colorMode === "community" && node.type === "fileNode") {- const nodeData = node.data as FileNodeData;- if (nodeData?.communityId !== undefined) {- setCommunityPanelId(nodeData.communityId);- }- }-- const mEvent = event as unknown as React.MouseEvent;- if (selectedNodeId === node.id) {- setSelectedNodeId(null);- setSelectedNodeScreen(null);+ const handleSigmaDoubleClick = useCallback(+ (nodeId: string, nodeType: string) => {+ if (nodeType === "module") {+ toggleModule(nodeId);} else {- setSelectedNodeId(node.id);- setSelectedNodeScreen({ x: mEvent.clientX, y: mEvent.clientY });+ onNodeViewDocs?.(nodeId);}},- [isModuleView, selectedNodeId, colorMode],+ [onNodeViewDocs, toggleModule],);- const handleNodeMouseEnter: NodeMouseHandler = useCallback(- (_event, node) => { setHoveredNodeId(node.id); },- [],- );-- const handleNodeMouseLeave: NodeMouseHandler = useCallback(- () => { setHoveredNodeId(null); },- [],- );-- const handleNodeDoubleClick: NodeMouseHandler = useCallback(- (_event, node) => {- if (node.type !== "moduleGroup") {- onNodeViewDocs?.(node.id);+ const handleSigmaNodeClick = useCallback(+ (nodeId: string, _nodeType: string) => {+ if (selectedNodeId === nodeId) {+ setSelectedNodeId(null);+ setEgoDepth(0);+ } else {+ setSelectedNodeId(nodeId);}},- [onNodeViewDocs],+ [selectedNodeId],);- const handleNodeContextMenu: NodeMouseHandler = useCallback(- (event, node) => {- event.preventDefault();+ const handleSigmaNodeContextMenu = useCallback(+ (event: MouseEvent, nodeId: string, nodeType: string) => {setCtxMenu({- x: (event as unknown as React.MouseEvent).clientX,- y: (event as unknown as React.MouseEvent).clientY,- nodeId: node.id,- nodeType: node.type ?? "fileNode",+ x: event.clientX,+ y: event.clientY,+ nodeId,+ nodeType: nodeType === "module" ? "moduleGroup" : "fileNode",});},[],@@ -456,6 +623,48 @@ function GraphFlowInner(props: GraphFlowProps) {};}, [ctxMenu]);+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ const target = e.target as HTMLElement;+ if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) return;++ switch (e.key) {+ case "f":+ e.preventDefault();+ sigmaRef.current?.fitView();+ break;+ case "Escape":+ setSelectedNodeId(null);+ setEgoDepth(0);+ setSearchQuery("");+ setCtxMenu(null);+ setCommunityPanelId(null);+ break;+ case "1":+ setColorMode("language");+ break;+ case "2":+ setColorMode("community");+ break;+ case "3":+ setColorMode("risk");+ break;+ case "/":+ e.preventDefault();+ document.querySelector<HTMLInputElement>('[aria-label="Search graph nodes"]')?.focus();+ break;+ }++ if ((e.metaKey || e.ctrlKey) && e.key === "k") {+ e.preventDefault();+ document.querySelector<HTMLInputElement>('[aria-label="Search graph nodes"]')?.focus();+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, []);+const handlePathFound = useCallback((pathNodes: string[]) => {setHighlightedPath(new Set(pathNodes));@@ -470,16 +679,14 @@ function GraphFlowInner(props: GraphFlowProps) {setModulePath([]);onViewModeChange?.("full");}- setTimeout(() => {- const pathRfNodes = pathNodes- .map((id) => reactFlow.getNode(id))- .filter(Boolean) as Node[];- if (pathRfNodes.length > 0) {- reactFlow.fitView({ nodes: pathRfNodes, padding: 0.3, duration: 600 });+ clearTimeout(focusTimerRef.current);+ focusTimerRef.current = setTimeout(() => {+ if (pathNodes.length > 0) {+ sigmaRef.current?.focusNode(pathNodes[0]!);}}, 800);},- [viewMode, reactFlow, onViewModeChange],+ [viewMode, onViewModeChange],);const handlePathClear = useCallback(() => {@@ -488,19 +695,137 @@ function GraphFlowInner(props: GraphFlowProps) {}, []);const handleFitView = useCallback(() => {- reactFlow.fitView({ padding: 0.15, duration: 400 });- }, [reactFlow]);+ sigmaRef.current?.fitView();+ }, []);const handleViewChange = useCallback((v: ViewMode) => {setViewMode(v);+ setLayoutMode("force");setModulePath([]);setHighlightedPath(new Set());setHighlightedEdges(new Set());setSelectedNodeId(null);- setSelectedNodeScreen(null);onViewModeChange?.(v);}, [onViewModeChange]);+ const handleLayoutModeChange = useCallback((mode: LayoutMode) => {+ setLayoutMode(mode);+ }, []);++ const handleGraphThemeChange = useCallback((theme: GraphTheme) => {+ setGraphTheme(theme);+ }, []);++ const handleSignalToggle = useCallback((signal: Signal) => {+ setActiveSignals((prev) => {+ const next = new Set(prev);+ if (next.has(signal)) next.delete(signal);+ else next.add(signal);+ return next;+ });+ }, []);++ const handleEdgeTypeToggle = useCallback((edgeType: string) => {+ setVisibleEdgeTypes((prev) => {+ const next = new Set(prev);+ if (next.has(edgeType)) {+ if (next.size > 1) next.delete(edgeType);+ } else {+ next.add(edgeType);+ }+ return next;+ });+ }, []);++ const panToNode = useCallback((nodeId: string) => {+ sigmaRef.current?.focusNode(nodeId);+ }, []);++ const initialNodeApplied = useRef(false);+ useEffect(() => {+ if (initialNodeApplied.current || !initialSelectedNode || !sigmaGraph) return;+ if (sigmaGraph.hasNode(initialSelectedNode)) {+ initialNodeApplied.current = true;+ setSelectedNodeId(initialSelectedNode);+ setTimeout(() => panToNode(initialSelectedNode), 300);+ }+ }, [initialSelectedNode, sigmaGraph, panToNode]);++ const handleSearchKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {+ if (searchResults.length === 0) {+ if (e.key === "Escape") { setSearchQuery(""); }+ return;+ }+ switch (e.key) {+ case "ArrowDown": {+ e.preventDefault();+ const next = (searchResultIndex + 1) % searchResults.length;+ setSearchResultIndex(next);+ panToNode(searchResults[next]!);+ break;+ }+ case "ArrowUp": {+ e.preventDefault();+ const prev = (searchResultIndex - 1 + searchResults.length) % searchResults.length;+ setSearchResultIndex(prev);+ panToNode(searchResults[prev]!);+ break;+ }+ case "Enter": {+ e.preventDefault();+ const id = searchResults[searchResultIndex];+ if (id) { setSelectedNodeId(id); panToNode(id); }+ break;+ }+ case "Escape":+ setSearchQuery("");+ break;+ }+ }, [searchResults, searchResultIndex, panToNode]);++ // Community filter handlers+ const allCommunityIds = useMemo(() => {+ const ids = new Set<number>();+ if (sigmaGraph) {+ sigmaGraph.forEachNode((_nodeId, attrs) => {+ if (attrs.nodeType === "file") ids.add(attrs.communityId);+ });+ }+ return ids;+ }, [sigmaGraph]);++ const handleCommunityToggle = useCallback((cid: number) => {+ setActiveCommunities((prev) => {+ const current = prev ?? new Set(allCommunityIds);+ const next = new Set(current);+ if (next.has(cid)) next.delete(cid); else next.add(cid);+ if (next.size === allCommunityIds.size) return null;+ return next;+ });+ }, [allCommunityIds]);++ const handleToggleAllCommunities = useCallback((selectAll: boolean) => {+ setActiveCommunities(selectAll ? null : new Set<number>());+ }, []);++ const handleInspectNavigate = useCallback((nodeId: string) => {+ setSelectedNodeId(nodeId);+ panToNode(nodeId);+ }, [panToNode]);++ const handleInspectFindPath = useCallback(() => {+ if (selectedNodeId) {+ setPathFrom(selectedNodeId);+ setShowPathFinder(true);+ }+ }, [selectedNodeId]);++ const handleInspectExpandModule = useCallback(() => {+ if (selectedNodeId) {+ toggleModule(selectedNodeId);+ }+ }, [selectedNodeId, toggleModule]);+// Breadcrumbconst handleBreadcrumbClick = useCallback((index: number) => {if (index < 0) {@@ -537,112 +862,64 @@ function GraphFlowInner(props: GraphFlowProps) {setCtxMenu(null);}, [ctxMenu]);- // After layout completes, zoom to entry-point nodes for a readable first view- const hasFocusedRef = useRef(false);-- useEffect(() => {- if (isLayouting || filteredNodes.length === 0 || hasFocusedRef.current) return;- hasFocusedRef.current = true;-- const timer = setTimeout(() => {- switch (viewMode) {- case "dead":- case "hotfiles":- case "architecture": {- reactFlow.fitView({ padding: 0.3, duration: 600, maxZoom: 1.5 });- return;- }- case "module": {- reactFlow.fitView({ padding: 0.2, duration: 600, maxZoom: 1 });- return;- }- default:- break;- }- reactFlow.fitView({ padding: 0.15, duration: 600, maxZoom: 0.6 });- }, 100);-- return () => clearTimeout(timer);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [isLayouting, filteredNodes, reactFlow]);-- // Reset focus flag when view mode changes- useEffect(() => {- hasFocusedRef.current = false;- }, [viewMode]);-- const minimapNodeColor = useCallback(- (node: Node) => {- if (node.type === "moduleGroup") {- const pct = (node.data as { docCoveragePct?: number }).docCoveragePct;- if (pct != null) return pct >= 0.7 ? "#22c55e" : pct >= 0.3 ? "#f59520" : "#ef4444";- return "#3b82f6";- }- const lang = (node.data as { language?: string }).language;- return lang ? languageColor(lang) : "#8b5cf6";- },- [],- );-if (isLoading) return <Skeleton className="h-full w-full rounded-lg" />;return (<GraphProvider value={ctxValue}>- <div className="relative w-full h-full" style={{ touchAction: "none" }} aria-label="Dependency graph">- {isLayouting && (- <div className="absolute inset-0 z-50 flex items-center justify-center bg-[var(--color-bg-root)]/60 backdrop-blur-sm rounded-lg">- <div className="flex items-center gap-3 text-sm text-[var(--color-text-secondary)]">- <Loader2 className="w-5 h-5 animate-spin text-[var(--color-accent-graph)]" />- Computing layout...- </div>- </div>- )}-- {filteredNodes.length === 0 && !isLayouting ? (+ <div className="relative w-full h-full" style={{ touchAction: "none", ...(graphTheme === "dark" ? { background: "#0f0f1a" } : {}) }} aria-label="Dependency graph">+ {sigmaGraph ? (+ <SigmaCanvas+ ref={sigmaRef}+ graph={sigmaGraph}+ layoutMode={layoutMode}+ viewMode={viewMode}+ selectedNodeId={selectedNodeId}+ hoveredNodeId={hoveredNodeId}+ highlightedPath={highlightedPath}+ highlightedEdges={highlightedEdges}+ searchDimmedNodes={searchDimmedNodes}+ communityDimmedNodes={communityDimmedNodes}+ colorMode={colorMode}+ activeSignals={activeSignals}+ graphTheme={graphTheme}+ fileNodes={fileGraphData?.nodes}+ fileEdges={fileGraphData?.links}+ moduleNodes={isModuleView ? moduleGraph?.nodes : undefined}+ moduleEdges={isModuleView ? moduleGraph?.edges : undefined}+ onNodeClick={handleSigmaNodeClick}+ onNodeDoubleClick={handleSigmaDoubleClick}+ onNodeHover={setHoveredNodeId}+ onNodeContextMenu={handleSigmaNodeContextMenu}+ onStageClick={() => setSelectedNodeId(null)}+ hiddenNodes={isEgoActive ? hiddenNodes : undefined}+ visibleEdgeTypes={visibleEdgeTypes}+ />+ ) : !isLoading ? (<div className="flex items-center justify-center h-full"><EmptyStatetitle="No graph data"description="Check that the backend is running and this repo has been indexed."/></div>- ) : (- <ReactFlow- nodes={filteredNodes}- edges={currentEdges}- nodeTypes={nodeTypes}- edgeTypes={edgeTypes}- onNodeClick={handleNodeClick}- onNodeDoubleClick={handleNodeDoubleClick}- onNodeContextMenu={handleNodeContextMenu}- onNodeMouseEnter={handleNodeMouseEnter}- onNodeMouseLeave={handleNodeMouseLeave}- onPaneClick={() => { setSelectedNodeId(null); setSelectedNodeScreen(null); }}- fitView- fitViewOptions={{ padding: 0.3, maxZoom: 1.2 }}- minZoom={0.05}- maxZoom={4}- proOptions={{ hideAttribution: true }}- className="!bg-transparent"- nodesDraggable={false}- defaultEdgeOptions={{ type: "dependency" }}- >- <Background variant={BackgroundVariant.Dots} gap={16} size={0.5} color="rgba(255,255,255,0.03)" />- <Controls- showInteractive={false}- className="!border-[var(--color-border-default)] !bg-[var(--color-bg-elevated)] !shadow-lg !shadow-black/20 [&>button]:!border-[var(--color-border-default)] [&>button]:!bg-[var(--color-bg-elevated)] [&>button]:!text-[var(--color-text-secondary)] [&>button:hover]:!bg-[var(--color-bg-overlay)] [&>button:hover]:!text-[var(--color-text-primary)]"- />- <MiniMap- nodeColor={minimapNodeColor}- maskColor="rgba(0, 0, 0, 0.6)"- className="!bg-[var(--color-bg-surface)] !border-[var(--color-border-default)] !shadow-lg !shadow-black/20 !rounded-lg !hidden sm:!block"- pannable- zoomable- />- </ReactFlow>- )}+ ) : null}- {/* Breadcrumb — shown when drilled into a module */}- {isModuleView && isDrilledDown && (+ {/* Ego indicator or breadcrumb */}+ {isEgoActive && selectedNodeId ? (+ <div className="absolute top-3 left-3 z-10">+ <div className="flex items-center gap-2 rounded-lg border border-[var(--color-accent-graph)]/30 bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20">+ <span className="text-[10px] text-[var(--color-accent-graph)]">+ Showing {egoVisibleCount} nodes within {egoDepth} hop{egoDepth === 1 ? "" : "s"} of{" "}+ <span className="font-mono font-medium">{selectedNodeId.split("/").pop()}</span>+ </span>+ <button+ onClick={() => setEgoDepth(0)}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] text-[10px]"+ >+ Clear+ </button>+ </div>+ </div>+ ) : isModuleView && isDrilledDown ? (<div className="absolute top-3 left-3 z-10"><div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20"><button@@ -674,7 +951,7 @@ function GraphFlowInner(props: GraphFlowProps) {})}</div></div>- )}+ ) : null}{/* Toolbar */}<div className="absolute top-3 right-3 z-10">@@ -684,7 +961,13 @@ function GraphFlowInner(props: GraphFlowProps) {colorMode={colorMode}onColorModeChange={setColorMode}hideTests={hideTests}- onHideTestsChange={setHideTests}+ onHideTestsChange={(v) => {+ setActiveSignals(prev => {+ const next = new Set(prev);+ v ? next.add("hideTests") : next.delete("hideTests");+ return next;+ });+ }}onFitView={handleFitView}showPathFinder={showPathFinder}onTogglePathFinder={() => setShowPathFinder((s) => !s)}@@ -692,10 +975,17 @@ function GraphFlowInner(props: GraphFlowProps) {onToggleFlows={() => { setShowFlows((s) => !s); setActiveFlowIdx(null); }}searchQuery={searchQuery}onSearchChange={setSearchQuery}+ searchMatchCount={searchResults.length}+ searchTotalCount={sigmaGraph?.order ?? 0}+ onSearchKeyDown={handleSearchKeyDown}+ layoutMode={layoutMode}+ onLayoutModeChange={handleLayoutModeChange}+ graphTheme={graphTheme}+ onGraphThemeChange={handleGraphThemeChange}/></div>- {/* Path Finder — rendered via consumer slot (data-coupled) */}+ {/* Path Finder */}{showPathFinder && renderPathFinder && (<div className="absolute top-14 right-3 z-10">{renderPathFinder({@@ -749,11 +1039,17 @@ function GraphFlowInner(props: GraphFlowProps) {{/* Legend */}<div className="absolute bottom-3 left-3 z-10"><GraphLegend- nodeCount={filteredNodes.length}- edgeCount={currentEdges.length}+ nodeCount={sigmaGraph?.order ?? 0}+ edgeCount={sigmaGraph?.size ?? 0}colorMode={colorMode}viewMode={viewMode}{...(communityLabels ? { communityLabels } : {})}+ onCommunityClick={setCommunityPanelId}+ activeCommunities={activeCommunities ?? undefined}+ onCommunityToggle={handleCommunityToggle}+ onToggleAllCommunities={handleToggleAllCommunities}+ visibleEdgeTypes={visibleEdgeTypes}+ onEdgeTypeToggle={handleEdgeTypeToggle}/></div>@@ -771,34 +1067,34 @@ function GraphFlowInner(props: GraphFlowProps) {/>)}- {/* Community detail panel — rendered via consumer slot */}+ {/* Community detail panel */}{communityPanelId !== null && renderCommunityPanel &&renderCommunityPanel({communityId: communityPanelId,onClose: () => setCommunityPanelId(null),})}- {/* Node detail tooltip */}- {selectedNodeId && selectedNodeScreen && (() => {- const rfNode = filteredNodes.find((n) => n.id === selectedNodeId);- if (!rfNode) return null;- const onExplore = rfNode.type === "moduleGroup" && isModuleView- ? () => {- setModulePath((prev) => [...prev, selectedNodeId]);- setSelectedNodeId(null);- setSelectedNodeScreen(null);- }- : undefined;+ {/* Inspection panel — works for both file and module nodes */}+ {selectedNodeId && (() => {+ const fileNd = effectiveNodeDataMap.get(selectedNodeId);+ const modNd = effectiveModuleDataMap.get(selectedNodeId);+ const nd = fileNd ?? modNd;+ if (!nd) return null;return (- <GraphTooltip+ <GraphInspectionPanelnodeId={selectedNodeId}- nodeType={rfNode.type ?? "fileNode"}- data={rfNode.data as Record<string, unknown>}- x={selectedNodeScreen.x}- y={selectedNodeScreen.y}- onClose={() => { setSelectedNodeId(null); setSelectedNodeScreen(null); }}- onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); setSelectedNodeId(null); setSelectedNodeScreen(null); }}- {...(onExplore ? { onExplore } : {})}+ data={nd}+ graph={sigmaGraph}+ allNodes={effectiveNodeDataMap}+ communityLabel={fileNd ? communityLabels?.get(fileNd.communityId) : undefined}+ onClose={() => { setSelectedNodeId(null); }}+ onNavigateToNode={handleInspectNavigate}+ onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); }}+ onFindPath={handleInspectFindPath}+ onExpandModule={modNd ? handleInspectExpandModule : undefined}+ egoDepth={egoDepth}+ onEgoDepthChange={setEgoDepth}+ egoVisibleCount={egoVisibleCount}/>);})()}@@ -807,12 +1103,3 @@ function GraphFlowInner(props: GraphFlowProps) {);}-// ---- Public component ------export function GraphFlow(props: GraphFlowProps) {- return (- <ReactFlowProvider>- <GraphFlowInner {...props} />- </ReactFlowProvider>- );-}diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsxnew file mode 100644index 000000000..5ad8ce505--- /dev/null+++ b/packages/ui/src/graph/graph-inspection-panel.tsx@@ -0,0 +1,437 @@+"use client";++import { useMemo, memo } from "react";+import {+ X,+ FileText,+ Folder,+ Zap,+ FlaskConical,+ BookOpen,+ ArrowDownToLine,+ ArrowUpFromLine,+ Route,+ Network,+ Code2,+} from "lucide-react";+import { ScrollArea } from "../ui/scroll-area";+import { languageColor } from "../lib/confidence";+import { formatNumber } from "../lib/format";+import type { FileNodeData, ModuleNodeData } from "./elk-layout";+import type Graph from "graphology";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./sigma/types";+import { COMMUNITY_COLORS } from "./sigma/constants";++interface NeighborInfo {+ id: string;+ label: string;+ communityId: number;+ direction: "importer" | "import";+}++export interface GraphInspectionPanelProps {+ nodeId: string;+ data: FileNodeData | ModuleNodeData;+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ allNodes: Map<string, FileNodeData>;+ communityLabel?: string | undefined;+ onClose: () => void;+ onNavigateToNode: (nodeId: string) => void;+ onViewDocs?: () => void;+ onViewSymbols?: () => void;+ onFindPath?: (() => void) | undefined;+ onShowEgoGraph?: (() => void) | undefined;+ onExpandModule?: (() => void) | undefined;+ egoDepth?: number | undefined;+ onEgoDepthChange?: ((depth: number) => void) | undefined;+ egoVisibleCount?: number | undefined;+}++function isModuleData(data: FileNodeData | ModuleNodeData): data is ModuleNodeData {+ return data.nodeType === "module";+}++function percentileOf(value: number, sorted: number[]): number {+ if (sorted.length === 0) return 0;+ let count = 0;+ for (const v of sorted) {+ if (v < value) count++;+ else break;+ }+ return Math.round((count / sorted.length) * 100);+}++export const GraphInspectionPanel = memo(function GraphInspectionPanel({+ nodeId,+ data,+ graph,+ allNodes,+ communityLabel,+ onClose,+ onNavigateToNode,+ onViewDocs,+ onViewSymbols,+ onFindPath,+ onShowEgoGraph,+ onExpandModule,+ egoDepth,+ onEgoDepthChange,+ egoVisibleCount,+}: GraphInspectionPanelProps) {+ const neighbors = useMemo(() => {+ if (!graph || !graph.hasNode(nodeId)) return [];+ const result: NeighborInfo[] = [];+ const seen = new Set<string>();+ graph.forEachOutEdge(nodeId, (_edge, _attrs, _source, target) => {+ if (seen.has(target)) return;+ seen.add(target);+ const nd = allNodes.get(target);+ result.push({+ id: target,+ label: target.split("/").pop() ?? target,+ communityId: nd?.communityId ?? 0,+ direction: "import",+ });+ });+ graph.forEachInEdge(nodeId, (_edge, _attrs, source) => {+ if (seen.has(source)) return;+ seen.add(source);+ const nd = allNodes.get(source);+ result.push({+ id: source,+ label: source.split("/").pop() ?? source,+ communityId: nd?.communityId ?? 0,+ direction: "importer",+ });+ });+ return result;+ }, [nodeId, graph, allNodes]);++ const { sortedPageranks, sortedBetweenness } = useMemo(() => {+ const prs: number[] = [];+ const bts: number[] = [];+ allNodes.forEach((nd) => {+ prs.push(nd.pagerank);+ bts.push(nd.betweenness);+ });+ prs.sort((a, b) => a - b);+ bts.sort((a, b) => a - b);+ return { sortedPageranks: prs, sortedBetweenness: bts };+ }, [allNodes]);++ const isMod = isModuleData(data);+ const inDegree = neighbors.filter((n) => n.direction === "importer").length;+ const outDegree = neighbors.filter((n) => n.direction === "import").length;+ const pagerankPct = !isMod ? percentileOf((data as FileNodeData).pagerank, sortedPageranks) : 0;+ const betweennessPct = !isMod ? percentileOf((data as FileNodeData).betweenness, sortedBetweenness) : 0;++ const headerIcon = isMod+ ? <Folder className="w-4 h-4 text-[var(--color-text-secondary)] mt-0.5 shrink-0" />+ : <FileText className="w-4 h-4 text-[var(--color-text-secondary)] mt-0.5 shrink-0" />;++ return (+ <div+ className="absolute right-0 top-0 bottom-0 w-full sm:w-[300px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-20 flex flex-col shadow-xl shadow-black/20 animate-in slide-in-from-right duration-200"+ >+ {/* Header */}+ <div className="flex items-start gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">+ {headerIcon}+ <div className="min-w-0 flex-1">+ <p className="text-sm font-semibold text-[var(--color-text-primary)] truncate">+ {nodeId.split("/").pop()}+ </p>+ <p className="text-[10px] text-[var(--color-text-tertiary)] truncate mt-0.5" title={data.fullPath}>+ {data.fullPath}+ </p>+ </div>+ <button+ onClick={onClose}+ className="p-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors shrink-0"+ >+ <X className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ </button>+ </div>++ <ScrollArea className="flex-1">+ <div className="p-4 space-y-4">+ {isMod ? (+ <ModuleMetadata data={data as ModuleNodeData} inDegree={inDegree} outDegree={outDegree} />+ ) : (+ <FileMetadata+ data={data as FileNodeData}+ pagerankPct={pagerankPct}+ betweennessPct={betweennessPct}+ inDegree={inDegree}+ outDegree={outDegree}+ communityLabel={communityLabel}+ />+ )}++ {/* Neighbors */}+ {neighbors.length > 0 && (+ <div className="border-t border-[var(--color-border-default)] pt-3">+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ {isMod ? "Connected Modules" : "Neighbors"} ({neighbors.length})+ </p>+ <div className="space-y-0.5 max-h-48 overflow-y-auto">+ {neighbors.map((n) => (+ <button+ key={n.id}+ onClick={() => onNavigateToNode(n.id)}+ className="w-full text-left flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-[var(--color-bg-elevated)] transition-colors group"+ >+ <span+ className="w-0.5 h-5 rounded-full shrink-0"+ style={{ background: COMMUNITY_COLORS[n.communityId % COMMUNITY_COLORS.length] }}+ />+ <div className="min-w-0 flex-1">+ <p className="text-[11px] font-mono text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate">+ {n.label}+ </p>+ </div>+ <span className="text-[9px] text-[var(--color-text-tertiary)] shrink-0">+ {n.direction === "importer" ? "imports this" : "imported"}+ </span>+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ </ScrollArea>++ {onEgoDepthChange && (+ <div className="px-4 py-3 border-t border-[var(--color-border-default)]">+ <div className="flex items-center justify-between mb-1.5">+ <span className="text-[10px] font-medium text-[var(--color-text-secondary)]">+ Ego Graph+ </span>+ {egoDepth != null && egoDepth > 0 && egoVisibleCount != null && (+ <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums">+ {egoVisibleCount} nodes+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <span className="text-[9px] text-[var(--color-text-tertiary)] w-4 text-right tabular-nums">+ {egoDepth ?? 0}+ </span>+ <input+ type="range"+ min={0}+ max={5}+ value={egoDepth ?? 0}+ onChange={(e) => onEgoDepthChange(parseInt(e.target.value, 10))}+ className="flex-1 h-1 accent-[var(--color-accent-graph)] cursor-pointer"+ aria-label="Ego graph depth"+ />+ <span className="text-[9px] text-[var(--color-text-tertiary)]">5</span>+ </div>+ <p className="text-[9px] text-[var(--color-text-tertiary)] mt-1">+ {(egoDepth ?? 0) === 0+ ? "Slide to filter by hop distance"+ : `Showing nodes within ${egoDepth} hop${egoDepth === 1 ? "" : "s"}`}+ </p>+ </div>+ )}++ {/* Actions */}+ <div className="border-t border-[var(--color-border-default)] p-3 grid grid-cols-2 gap-2">+ {isMod && onExpandModule && (+ <button+ onClick={onExpandModule}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-accent-graph)]/10 hover:bg-[var(--color-accent-graph)]/20 border border-[var(--color-accent-graph)]/30 px-2 py-1.5 text-[10px] font-medium text-[var(--color-accent-graph)] transition-colors col-span-2"+ >+ <Network className="w-3 h-3" /> Expand Module+ </button>+ )}+ {onViewDocs && (+ <button+ onClick={onViewDocs}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <BookOpen className="w-3 h-3" /> View Docs+ </button>+ )}+ {!isMod && onViewSymbols && (+ <button+ onClick={onViewSymbols}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Code2 className="w-3 h-3" /> Symbols+ </button>+ )}+ {onFindPath && (+ <button+ onClick={onFindPath}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Route className="w-3 h-3" /> Find Path+ </button>+ )}+ {!isMod && onShowEgoGraph && (+ <button+ onClick={onShowEgoGraph}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Network className="w-3 h-3" /> Ego Graph+ </button>+ )}+ </div>+ </div>+ );+});++function FileMetadata({+ data,+ pagerankPct,+ betweennessPct,+ inDegree,+ outDegree,+ communityLabel,+}: {+ data: FileNodeData;+ pagerankPct: number;+ betweennessPct: number;+ inDegree: number;+ outDegree: number;+ communityLabel?: string | undefined;+}) {+ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Language</span>+ <span className="flex items-center gap-1.5">+ <span className="w-2 h-2 rounded-full" style={{ background: languageColor(data.language) }} />+ <span className="font-medium text-[var(--color-text-primary)] capitalize">{data.language}</span>+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Symbols</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(data.symbolCount)}+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Pagerank</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ Top {100 - pagerankPct}%+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Betweenness</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ Top {100 - betweennessPct}%+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Community</span>+ <span className="flex items-center gap-1.5">+ <span+ className="w-2 h-2 rounded-full"+ style={{ background: COMMUNITY_COLORS[data.communityId % COMMUNITY_COLORS.length] }}+ />+ <span className="font-medium text-[var(--color-text-primary)]">+ {communityLabel ?? `#${data.communityId}`}+ </span>+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Degree</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums flex items-center gap-2">+ <span className="flex items-center gap-0.5" title="In-degree (importers)">+ <ArrowDownToLine className="w-3 h-3 text-[var(--color-text-tertiary)]" />{inDegree}+ </span>+ <span className="flex items-center gap-0.5" title="Out-degree (imports)">+ <ArrowUpFromLine className="w-3 h-3 text-[var(--color-text-tertiary)]" />{outDegree}+ </span>+ </span>+ </div>++ <div className="flex items-center gap-1.5 pt-1 flex-wrap">+ {data.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>+ )}+ {data.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>+ )}+ {data.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>+ </div>+ );+}++function ModuleMetadata({+ data,+ inDegree,+ outDegree,+}: {+ data: ModuleNodeData;+ inDegree: number;+ outDegree: number;+}) {+ const docPct = Math.round((data.docCoveragePct ?? 0) * 100);+ const docColor = docPct >= 70 ? "#22c55e" : docPct >= 30 ? "#f59e0b" : "#ef4444";++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Files</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(data.fileCount)}+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Symbols</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(data.symbolCount)}+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Avg Pagerank</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {data.avgPagerank.toFixed(4)}+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Doc Coverage</span>+ <span className="flex items-center gap-1.5">+ <span className="w-2 h-2 rounded-full" style={{ background: docColor }} />+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">{docPct}%</span>+ </span>+ </div>++ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Connections</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums flex items-center gap-2">+ <span className="flex items-center gap-0.5" title="Depends on this">+ <ArrowDownToLine className="w-3 h-3 text-[var(--color-text-tertiary)]" />{inDegree}+ </span>+ <span className="flex items-center gap-0.5" title="This depends on">+ <ArrowUpFromLine className="w-3 h-3 text-[var(--color-text-tertiary)]" />{outDegree}+ </span>+ </span>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsxindex e8d06be62..80377c228 100644--- a/packages/ui/src/graph/graph-legend.tsx+++ b/packages/ui/src/graph/graph-legend.tsx@@ -1,19 +1,11 @@"use client";-import { useState } from "react";+import { useState, memo } from "react";import { ChevronDown, ChevronUp } from "lucide-react";import { LANGUAGE_COLORS } from "../lib/confidence";+import { EDGE_COLORS, getCommunityColor } from "./sigma/constants";import type { ColorMode, ViewMode } from "./graph-toolbar";-const COMMUNITY_SAMPLE = [- { color: "#6366f1", label: "Community 1" },- { color: "#ec4899", label: "Community 2" },- { color: "#10b981", label: "Community 3" },- { color: "#f59e0b", label: "Community 4" },- { color: "#3b82f6", label: "Community 5" },- { color: "#a855f7", label: "Community 6" },-];-const LANGUAGE_LEGEND = [{ lang: "python", color: LANGUAGE_COLORS.python, label: "Python" },{ lang: "typescript", color: LANGUAGE_COLORS.typescript, label: "TypeScript" },@@ -30,14 +22,26 @@ interface GraphLegendProps {colorMode: ColorMode;viewMode: ViewMode;communityLabels?: Map<number, string>;+ onCommunityClick?: (communityId: number) => void;+ activeCommunities?: Set<number> | undefined;+ onCommunityToggle?: (communityId: number) => void;+ onToggleAllCommunities?: (selectAll: boolean) => void;+ visibleEdgeTypes?: Set<string> | undefined;+ onEdgeTypeToggle?: ((edgeType: string) => void) | undefined;}-export function GraphLegend({+export const GraphLegend = memo(function GraphLegend({nodeCount,edgeCount,colorMode,viewMode,communityLabels,+ onCommunityClick,+ activeCommunities,+ onCommunityToggle,+ onToggleAllCommunities,+ visibleEdgeTypes,+ onEdgeTypeToggle,}: GraphLegendProps) {const [expanded, setExpanded] = useState(false);@@ -74,28 +78,74 @@ export function GraphLegend({</div>))}- {colorMode === "community" &&- (communityLabels && communityLabels.size > 0- ? Array.from(communityLabels.entries())- .slice(0, 8)- .map(([cid, label], i) => (- <div key={cid} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">- <span- className="w-2 h-2 rounded-full shrink-0"- style={{ background: COMMUNITY_SAMPLE[i % COMMUNITY_SAMPLE.length]?.color ?? "#888" }}- />- <span className="truncate">{label}</span>- </div>- ))- : COMMUNITY_SAMPLE.map((c, i) => (- <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">- <span- className="w-2 h-2 rounded-full shrink-0"- style={{ background: c.color }}- />- <span>{c.label}</span>- </div>- )))}+ {colorMode === "community" && (() => {+ const entries = communityLabels && communityLabels.size > 0+ ? Array.from(communityLabels.entries()).slice(0, 8)+ : null;+ const allSelected = !activeCommunities || (entries+ ? entries.every(([cid]) => activeCommunities.has(cid))+ : true);+ return (+ <>+ {onToggleAllCommunities && entries && (+ <button+ onClick={() => onToggleAllCommunities(!allSelected)}+ className="text-[9px] text-[var(--color-accent-graph)] hover:underline mb-0.5"+ >+ {allSelected ? "Deselect All" : "Select All"}+ </button>+ )}+ {entries+ ? entries.map(([cid, label], i) => {+ const color = getCommunityColor(cid);+ const checked = !activeCommunities || activeCommunities.has(cid);+ return (+ <div+ key={cid}+ className={`flex items-center gap-2 text-[var(--color-text-tertiary)]${+ onCommunityClick+ ? " cursor-pointer rounded px-1 -mx-1 hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"+ : ""+ }`}+ >+ {onCommunityToggle && (+ <button+ onClick={(e) => { e.stopPropagation(); onCommunityToggle(cid); }}+ className="shrink-0 w-[10px] h-[10px] rounded-sm border"+ style={{+ borderColor: color,+ background: checked ? color : "transparent",+ }}+ aria-label={`Toggle community ${label}`}+ />+ )}+ {!onCommunityToggle && (+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{ background: color }}+ />+ )}+ <span+ className="truncate"+ onClick={() => onCommunityClick?.(cid)}+ >+ {label}+ </span>+ </div>+ );+ })+ : Array.from({ length: 6 }, (_, i) => (+ <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{ background: getCommunityColor(i) }}+ />+ <span>Community {i + 1}</span>+ </div>+ ))}+ </>+ );+ })()}{colorMode === "risk" && (<>@@ -114,15 +164,49 @@ export function GraphLegend({</>)}+ {onEdgeTypeToggle && visibleEdgeTypes && (+ <>+ <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium pt-1.5 border-t border-[var(--color-border-default)] mt-1.5">+ Edges+ </p>+ {([+ { type: "import", label: "Imports", color: EDGE_COLORS.import },+ { type: "crossCommunity", label: "Cross-community", color: EDGE_COLORS.crossCommunity },+ { type: "internal", label: "Internal", color: EDGE_COLORS.internal },+ { type: "dynamic", label: "Dynamic", color: EDGE_COLORS.dynamic },+ { type: "lowConfidence", label: "Low confidence", color: EDGE_COLORS.lowConfidence },+ ] as const).map((et) => {+ const checked = visibleEdgeTypes.has(et.type);+ return (+ <div key={et.type} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">+ <button+ onClick={() => onEdgeTypeToggle(et.type)}+ className="shrink-0 w-[10px] h-[10px] rounded-sm border"+ style={{+ borderColor: et.color,+ background: checked ? et.color : "transparent",+ }}+ aria-label={`Toggle ${et.label} edges`}+ />+ <span className={checked ? "" : "line-through opacity-50"}>+ {et.label}+ </span>+ </div>+ );+ })}+ </>+ )}+{viewMode !== "module" && viewMode !== "full" && (<p className="text-[9px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">{viewMode === "dead" && "Showing unreachable files"}{viewMode === "hotfiles" && "Most-committed files (30d)"}{viewMode === "architecture" && "Entry-point reachable (3 hops)"}+ {viewMode === "unified" && "Unified: community + risk signals"}</p>)}</div>)}</div>);-}+});diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex fbe8bcff9..5e8680732 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -12,14 +12,22 @@ import {Skull,Flame,LayoutGrid,+ Layers,Workflow,Search,X,+ GitBranch,+ Waypoints,+ Sun,+ Moon,} from "lucide-react";+import { memo } from "react";import { Button } from "../ui/button";export type ColorMode = "language" | "community" | "risk";-export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles";+export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";+export type LayoutMode = "hierarchical" | "force";+export type GraphTheme = "light" | "dark";interface GraphToolbarProps {viewMode: ViewMode;@@ -35,6 +43,13 @@ interface GraphToolbarProps {onToggleFlows: () => void;searchQuery: string;onSearchChange: (q: string) => void;+ searchMatchCount?: number;+ searchTotalCount?: number;+ onSearchKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;+ layoutMode: LayoutMode;+ onLayoutModeChange: (mode: LayoutMode) => void;+ graphTheme: GraphTheme;+ onGraphThemeChange: (theme: GraphTheme) => void;}const VIEW_MODES: { id: ViewMode; icon: typeof Boxes; label: string }[] = [@@ -43,6 +58,7 @@ const VIEW_MODES: { id: ViewMode; icon: typeof Boxes; label: string }[] = [{ 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" },];const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [@@ -51,7 +67,12 @@ const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [{ id: "risk", icon: Shield, label: "Risk" },];-export function GraphToolbar({+const LAYOUT_MODES: { id: LayoutMode; icon: typeof GitBranch; label: string }[] = [+ { id: "force", icon: Waypoints, label: "Force (FA2)" },+ { id: "hierarchical", icon: GitBranch, label: "Hierarchical" },+];++export const GraphToolbar = memo(function GraphToolbar({viewMode,onViewChange,colorMode,@@ -65,6 +86,13 @@ export function GraphToolbar({onToggleFlows,searchQuery,onSearchChange,+ searchMatchCount,+ searchTotalCount,+ onSearchKeyDown,+ layoutMode,+ onLayoutModeChange,+ graphTheme,+ onGraphThemeChange,}: GraphToolbarProps) {return (<div className="flex flex-col gap-1.5 items-end">@@ -93,6 +121,29 @@ export function GraphToolbar({</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) => {+ const Icon = m.icon;+ const isActive = layoutMode === m.id;+ return (+ <button+ key={m.id}+ onClick={() => onLayoutModeChange(m.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={m.label}+ aria-label={m.label}+ aria-pressed={isActive}+ >+ <Icon className="w-3 h-3" />+ </button>+ );+ })}+ </div>+<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">{COLOR_MODES.map((m) => {const Icon = m.icon;@@ -117,6 +168,17 @@ export function GraphToolbar({</div><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">+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onGraphThemeChange(graphTheme === "light" ? "dark" : "light")}+ className={`h-7 w-7 p-0 ${graphTheme === "dark" ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ title={graphTheme === "dark" ? "Light graph theme" : "Dark graph theme"}+ aria-label={graphTheme === "dark" ? "Light graph theme" : "Dark graph theme"}+ aria-pressed={graphTheme === "dark"}+ >+ {graphTheme === "dark" ? <Sun className="w-3.5 h-3.5" /> : <Moon className="w-3.5 h-3.5" />}+ </Button><Buttonsize="sm"variant="ghost"@@ -170,10 +232,16 @@ export function GraphToolbar({type="text"value={searchQuery}onChange={(e) => onSearchChange(e.target.value)}+ onKeyDown={onSearchKeyDown}placeholder="Search nodes…"aria-label="Search graph nodes"className="bg-transparent text-[11px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none w-28 lg:w-40"/>+ {searchQuery && searchMatchCount != null && searchTotalCount != null && (+ <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums whitespace-nowrap">+ {searchMatchCount} / {searchTotalCount}+ </span>+ )}{searchQuery && (<buttononClick={() => onSearchChange("")}@@ -187,4 +255,4 @@ export function GraphToolbar({</div></div>);-}+});diff --git a/packages/ui/src/graph/graph-tooltip.tsx b/packages/ui/src/graph/graph-tooltip.tsxindex 6a879b37e..3d43511ae 100644--- a/packages/ui/src/graph/graph-tooltip.tsx+++ b/packages/ui/src/graph/graph-tooltip.tsx@@ -1,7 +1,8 @@+/** @deprecated Use GraphInspectionPanel instead — this tooltip is no longer mounted by GraphFlow. */"use client";import { useEffect, useRef } from "react";-import { FileText, Folder, ArrowRight, X, Zap, FlaskConical, BookOpen } from "lucide-react";+import { FileText, Folder, ArrowRight, X, Zap, FlaskConical, BookOpen, Code2 } from "lucide-react";import { formatNumber } from "../lib/format";import { languageColor } from "../lib/confidence";import type { FileNodeData, ModuleNodeData } from "./elk-layout";@@ -14,6 +15,7 @@ interface GraphTooltipProps {y: number;onClose: () => void;onViewDocs: () => void;+ onViewSymbol?: () => void;onExplore?: () => void;}@@ -31,6 +33,7 @@ export function GraphTooltip({y,onClose,onViewDocs,+ onViewSymbol,onExplore,}: GraphTooltipProps) {const ref = useRef<HTMLDivElement>(null);@@ -240,6 +243,15 @@ export function GraphTooltip({<BookOpen className="w-3 h-3" />View Docs</button>+ {isFile && onViewSymbol && (+ <button+ onClick={onViewSymbol}+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Code2 className="w-3 h-3" />+ View Symbol+ </button>+ )}{onExplore && (<buttononClick={onExplore}diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.tsindex 08752a634..52f4641f7 100644--- a/packages/ui/src/graph/index.ts+++ b/packages/ui/src/graph/index.ts@@ -2,14 +2,15 @@ export * from "./graph-context-menu.js";export * from "./graph-ego-sidebar.js";export * from "./graph-legend.js";export * from "./graph-toolbar.js";-export * from "./graph-tooltip.js";export * from "./graph-doc-panel.js";export * from "./graph-community-panel.js";+export * from "./graph-inspection-panel.js";export * from "./path-finder-panel.js";export * from "./graph-flow.js";export * from "./context.js";export * from "./elk-layout.js";-export * from "./use-elk-layout.js";-export { FileNode } from "./nodes/file-node.js";-export { ModuleGroupNode } from "./nodes/module-group-node.js";-export { DependencyEdge } from "./edges/dependency-edge.js";+export * from "./use-expanded-modules.js";+export * from "./sigma/sigma-canvas.js";+export * from "./sigma/types.js";+export * from "./sigma/graphology-adapter.js";+export * from "./sigma/constants.js";diff --git a/packages/ui/src/graph/nodes/file-node.tsx b/packages/ui/src/graph/nodes/file-node.tsxdeleted file mode 100644index d545d3f76..000000000--- a/packages/ui/src/graph/nodes/file-node.tsx+++ /dev/null@@ -1,109 +0,0 @@-"use client";--import { memo, useContext } from "react";-import { Handle, Position, type NodeProps } from "@xyflow/react";-import { FileText } from "lucide-react";-import { GraphContext } from "../context";-import { languageColor } from "../../lib/confidence";-import type { FileNodeData } from "../elk-layout";--const COMMUNITY_COLORS = [- "#6366f1", "#ec4899", "#10b981", "#f59e0b", "#3b82f6", "#a855f7",- "#14b8a6", "#f97316", "#84cc16", "#06b6d4", "#e11d48", "#8b5cf6",- "#22c55e", "#eab308", "#0ea5e9", "#d946ef", "#ef4444", "#78716c",- "#64748b", "#0891b2", "#059669", "#b45309", "#7c3aed", "#db2777",-];--function riskColor(score: number): string {- if (score <= 0.3) return "#22c55e";- if (score <= 0.7) return "#f59520";- return "#ef4444";-}--function FileNodeInner({ id, data }: NodeProps) {- const d = data as FileNodeData;- const ctx = useContext(GraphContext);-- const isOnPath = ctx.highlightedPath.has(id);- const hasActivePath = ctx.highlightedPath.size > 0;- const isDimmed = hasActivePath && !isOnPath;- const isSearchDimmed = ctx.searchDimmedNodes?.has(id) ?? false;- const isSelected = ctx.selectedNodeId === id;- const isHovered = ctx.hoveredNodeId === id;- const hasHover = ctx.hoveredNodeId !== null;- const isConnected = ctx.connectedNodeIds.has(id);- const isHoverDimmed = hasHover && !isConnected && !hasActivePath;-- // Determine node accent color based on color mode- let accentColor: string;- switch (ctx.colorMode) {- case "risk": {- const score = ctx.riskScores.get(d.fullPath) ?? (d.pagerank * 3);- accentColor = riskColor(Math.min(1, score));- break;- }- case "community":- accentColor = COMMUNITY_COLORS[d.communityId % COMMUNITY_COLORS.length] ?? "#6366f1";- break;- case "language":- default:- accentColor = languageColor(d.language);- break;- }-- // Compute opacity- const searchDimmed = isSearchDimmed && !isOnPath && !isSelected;- let opacity = 1;- if (isDimmed) opacity = 0.15;- else if (searchDimmed) opacity = 0.12;- else if (isHoverDimmed) opacity = 0.35;-- return (- <div- className="rounded-lg px-2 py-1.5 transition-all duration-200 cursor-pointer"- style={{- border: `2px solid ${accentColor}`,- background: `linear-gradient(135deg, ${accentColor}50 0%, #1e293b 100%)`,- opacity,- transform: isHovered || isSelected ? "scale(1.05)" : "scale(1)",- boxShadow: isOnPath- ? `0 0 24px ${accentColor}80`- : isSelected- ? `0 4px 20px rgba(0,0,0,0.5), 0 0 0 3px ${accentColor}`- : isHovered- ? `0 4px 16px rgba(0,0,0,0.4), 0 0 16px ${accentColor}40`- : `0 2px 8px rgba(0,0,0,0.4)`,- animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,- borderStyle: d.isTest ? "dashed" : undefined,- }}- aria-label={d.fullPath}- >- <Handle- type="target"- position={Position.Top}- className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"- />-- {/* Same layout as module node: icon + label + badge */}- <div className="flex items-center gap-2">- <FileText className="w-3 h-3 shrink-0" style={{ color: accentColor }} />- <span className="text-[11px] font-medium text-[var(--color-text-primary)] truncate">- {d.label}- </span>- {d.isEntryPoint && (- <span className="ml-auto shrink-0 text-[8px] font-bold uppercase px-1 py-0.5 rounded" style={{ background: `${accentColor}30`, color: accentColor }}>- EP- </span>- )}- </div>-- <Handle- type="source"- position={Position.Bottom}- className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"- />- </div>- );-}--export const FileNode = memo(FileNodeInner);diff --git a/packages/ui/src/graph/nodes/module-group-node.tsx b/packages/ui/src/graph/nodes/module-group-node.tsxdeleted file mode 100644index ae1de9ae0..000000000--- a/packages/ui/src/graph/nodes/module-group-node.tsx+++ /dev/null@@ -1,103 +0,0 @@-"use client";--import { memo, useContext } from "react";-import { Handle, Position, type NodeProps } from "@xyflow/react";-import { Folder } from "lucide-react";-import { GraphContext } from "../context";-import type { ModuleNodeData } from "../elk-layout";--const COMMUNITY_COLORS = [- "#6366f1", "#ec4899", "#10b981", "#f59e0b", "#3b82f6", "#a855f7",- "#14b8a6", "#f97316", "#84cc16", "#06b6d4", "#e11d48", "#8b5cf6",- "#22c55e", "#eab308", "#0ea5e9", "#d946ef", "#ef4444", "#78716c",- "#64748b", "#0891b2", "#059669", "#b45309", "#7c3aed", "#db2777",-];--function ModuleGroupNodeInner({ id, data }: NodeProps) {- const d = data as ModuleNodeData;- const ctx = useContext(GraphContext);- const docPct = d.docCoveragePct ?? 0;-- // Color mode determines the accent/border color- let accentColor: string;- switch (ctx.colorMode) {- case "risk": {- if (docPct >= 0.7) accentColor = "var(--color-node-documented)";- else if (docPct >= 0.3) accentColor = "var(--color-risk-medium)";- else accentColor = "var(--color-risk-high)";- break;- }- case "community": {- let hash = 0;- for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;- accentColor = COMMUNITY_COLORS[Math.abs(hash) % COMMUNITY_COLORS.length] ?? "#6366f1";- break;- }- case "language":- default:- accentColor = "var(--color-accent-graph)";- break;- }-- const isOnPath = ctx.highlightedPath.has(id);- const hasActivePath = ctx.highlightedPath.size > 0;- const isDimmed = hasActivePath && !isOnPath;- const isSelected = ctx.selectedNodeId === id;- const isHovered = ctx.hoveredNodeId === id;- const hasHover = ctx.hoveredNodeId !== null;- const isConnected = ctx.connectedNodeIds.has(id);- const isHoverDimmed = hasHover && !isConnected && !hasActivePath;-- const isSearchDimmed = ctx.searchDimmedNodes?.has(id) ?? false;- const searchDimmed = isSearchDimmed && !isOnPath && !isSelected;-- let opacity = 1;- if (isDimmed) opacity = 0.15;- else if (searchDimmed) opacity = 0.12;- else if (isHoverDimmed) opacity = 0.35;-- return (- <div- className="rounded-lg px-2 py-1.5 transition-all duration-200 cursor-pointer"- style={{- border: `2px solid ${accentColor}`,- background: `linear-gradient(135deg, ${accentColor}50 0%, #1e293b 100%)`,- opacity,- transform: isHovered || isSelected ? "scale(1.05)" : "scale(1)",- boxShadow: isOnPath- ? `0 0 24px var(--color-accent-graph)`- : isSelected- ? `0 4px 20px rgba(0,0,0,0.5), 0 0 0 3px ${accentColor}`- : isHovered- ? `0 4px 16px rgba(0,0,0,0.4), 0 0 16px ${accentColor}40`- : `0 2px 8px rgba(0,0,0,0.4)`,- animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,- }}- >- <Handle- type="target"- position={Position.Top}- className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"- />-- {/* Header row: icon + label + file count */}- <div className="flex items-center gap-2">- <Folder className="w-3 h-3 shrink-0" style={{ color: accentColor }} />- <span className="text-[11px] font-medium text-[var(--color-text-primary)] truncate">- {d.label}- </span>- <span className="ml-auto text-[9px] text-[var(--color-text-tertiary)] tabular-nums shrink-0">- {d.fileCount ?? 0}- </span>- </div>-- <Handle- type="source"- position={Position.Bottom}- className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"- />- </div>- );-}--export const ModuleGroupNode = memo(ModuleGroupNodeInner);diff --git a/packages/ui/src/graph/sigma/constants.ts b/packages/ui/src/graph/sigma/constants.tsnew file mode 100644index 000000000..b3484bd9c--- /dev/null+++ b/packages/ui/src/graph/sigma/constants.ts@@ -0,0 +1,133 @@+import { LANGUAGE_COLORS, languageColor } from "../../lib/confidence";++// Re-export for convenience+export { LANGUAGE_COLORS, languageColor };++// ---- Community palette (24 perceptually-optimized colors for dark backgrounds) ----++export const COMMUNITY_COLORS = [+ "#FF6B6B", "#4ECDC4", "#FFE66D", "#AA96DA", "#F38181",+ "#A8E6CF", "#87CEEB", "#F4A460", "#98FB98", "#FF69B4",+ "#20B2AA", "#FFA07A", "#9370DB", "#3CB371", "#FF7F50",+ "#6495ED", "#DAA520", "#00CED1", "#FF1493", "#32CD32",+ "#BA55D3", "#FF8C00", "#7B68EE", "#48D1CC",+];++export function getCommunityColor(communityId: number): string {+ return COMMUNITY_COLORS[communityId % COMMUNITY_COLORS.length] ?? "#6366f1";+}++// ---- Node base sizes ----++export const NODE_BASE_SIZES = {+ module: 16,+ file: 6,+ entryPoint: 10,+ test: 4,+} as const;++/**+ * Adaptive node sizing — scales down for large graphs to prevent overlap.+ */+export function getScaledNodeSize(baseSize: number, nodeCount: number): number {+ if (nodeCount > 10000) return Math.max(1, baseSize * 0.4);+ if (nodeCount > 5000) return Math.max(1.5, baseSize * 0.5);+ if (nodeCount > 2000) return Math.max(2, baseSize * 0.65);+ if (nodeCount > 500) return Math.max(2.5, baseSize * 0.8);+ return baseSize;+}++/**+ * FA2 mass by node type — modules are heavier to create clear spatial separation.+ */+export function getNodeMass(+ nodeType: "file" | "module",+ nodeCount: number,+): number {+ const baseMassMultiplier = nodeCount > 5000 ? 2 : nodeCount > 1000 ? 1.5 : 1;+ return nodeType === "module"+ ? 5 * baseMassMultiplier+ : 3 * baseMassMultiplier;+}++// ---- Edge colors by semantic type ----++export const EDGE_COLORS = {+ import: "#1d4ed8",+ crossCommunity: "#7c3aed",+ internal: "#2d5a3d",+ dynamic: "#6b7280",+ lowConfidence: "#475569",+} as const;++export const EDGE_SIZE_MULTIPLIERS = {+ import: 0.6,+ crossCommunity: 0.8,+ internal: 0.4,+ dynamic: 0.3,+ lowConfidence: 0.3,+} as const;++// ---- ForceAtlas2 adaptive settings ----++export function getFA2Settings(nodeCount: number): Record<string, unknown> {+ const isSmall = nodeCount < 500;+ const isMedium = nodeCount >= 500 && nodeCount < 2000;+ const isLarge = nodeCount >= 2000 && nodeCount < 10000;++ return {+ gravity: isSmall ? 0.8 : isMedium ? 0.5 : isLarge ? 0.3 : 0.2,+ scalingRatio: isSmall ? 12 : isMedium ? 20 : isLarge ? 30 : 40,+ slowDown: isSmall ? 10 : isMedium ? 12 : isLarge ? 15 : 20,+ barnesHutOptimize: nodeCount > 200,+ barnesHutTheta: isLarge ? 0.8 : 0.6,+ strongGravityMode: false,+ outboundAttractionDistribution: true,+ linLogMode: false,+ adjustSizes: true,+ edgeWeightInfluence: 1,+ };+}++/**+ * How long FA2 should run before stopping (ms).+ */+export function getLayoutDuration(nodeCount: number): number {+ if (nodeCount > 10000) return 20000;+ if (nodeCount > 5000) return 15000;+ if (nodeCount > 2000) return 12000;+ if (nodeCount > 1000) return 10000;+ if (nodeCount > 500) return 8000;+ return 5000;+}++// ---- Noverlap post-layout settings ----++export const NOVERLAP_SETTINGS = {+ maxIterations: 20,+ ratio: 1.1,+ margin: 10,+ expansion: 1.05,+} as const;++// ---- Edge rendering thresholds ----++export const CURVED_EDGE_THRESHOLD = 3000;++// ---- Label rendering ----++export const LABEL_FONT = "JetBrains Mono, ui-monospace, monospace";+export const LABEL_SIZE = 11;+export const LABEL_DENSITY = 0.15;+export const LABEL_GRID_CELL_SIZE = 80;+export const LABEL_RENDERED_SIZE_THRESHOLD = 6;++// ---- Surface depth system (for panels, tooltips, controls) ----++export const SURFACE_COLORS = {+ void: "#06060a",+ deep: "#0a0a10",+ surface: "#101018",+ elevated: "#16161f",+ hover: "#1c1c28",+} as const;diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.tsnew file mode 100644index 000000000..b22c192e1--- /dev/null+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts@@ -0,0 +1,362 @@+import Graph from "graphology";+import type {+ GraphExport,+ GraphNode,+ GraphLink,+ ModuleGraph,+ ModuleNode,+ ModuleEdge,+ CommunitySummaryItem,+} from "@repowise-dev/types/graph";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";+import {+ NODE_BASE_SIZES,+ EDGE_COLORS,+ EDGE_SIZE_MULTIPLIERS,+ CURVED_EDGE_THRESHOLD,+ getScaledNodeSize,+ getNodeMass,+ getCommunityColor,+ languageColor,+} from "./constants";+import { groupNodesAsModules } from "../elk-layout";++function simpleHash(str: string): number {+ let hash = 5381;+ for (let i = 0; i < str.length; i++) {+ hash = ((hash << 5) + hash + (str.charCodeAt(i) ?? 0)) | 0;+ }+ return Math.abs(hash);+}++function classifyEdge(+ link: GraphLink,+ nodeMap: Map<string, GraphNode>,+): SigmaEdgeAttributes["edgeKind"] {+ if (link.confidence !== undefined && link.confidence < 0.5)+ return "lowConfidence";+ if (link.imported_names.length === 0) return "dynamic";+ const sourceNode = nodeMap.get(link.source);+ const targetNode = nodeMap.get(link.target);+ if (+ sourceNode &&+ targetNode &&+ sourceNode.community_id === targetNode.community_id+ )+ return "internal";+ if (+ sourceNode &&+ targetNode &&+ sourceNode.community_id !== targetNode.community_id+ )+ return "crossCommunity";+ return "import";+}++function computeEdgeSize(+ edgeKind: SigmaEdgeAttributes["edgeKind"],+ nodeCount: number,+): number {+ const baseScale =+ nodeCount > 10000+ ? 0.15+ : nodeCount > 5000+ ? 0.25+ : nodeCount > 2000+ ? 0.35+ : nodeCount > 1000+ ? 0.5+ : nodeCount > 500+ ? 0.7+ : 1.0;+ return baseScale * EDGE_SIZE_MULTIPLIERS[edgeKind];+}++function smartLabel(fullPath: string): string {+ const parts = fullPath.split("/");+ if (parts.length >= 2) return parts.slice(-2).join("/");+ return parts[parts.length - 1] ?? fullPath;+}++function computeEdgeCurvature(edgeKey: string): number {+ const hash = simpleHash(edgeKey);+ return 0.12 + (hash % 80) / 1000;+}++export function fileGraphToGraphology(+ graph: GraphExport,+ options?: {+ signals?: { hotNodeIds?: Set<string>; deadNodeIds?: Set<string> };+ nodeCount?: number;+ },+): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {+ const result = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();+ const nodeCount = options?.nodeCount ?? graph.nodes.length;++ // Build lookup maps+ const nodeMap = new Map<string, GraphNode>();+ const communityNodes = new Map<number, GraphNode[]>();+ for (const node of graph.nodes) {+ nodeMap.set(node.node_id, node);+ const list = communityNodes.get(node.community_id) ?? [];+ list.push(node);+ communityNodes.set(node.community_id, list);+ }++ // Warm-start positioning with golden-angle radial distribution+ const goldenAngle = Math.PI * (3 - Math.sqrt(5));+ const spread = Math.sqrt(nodeCount) * 40;+ const sortedCommunities = Array.from(communityNodes.keys()).sort(+ (a, b) => a - b,+ );+ const communityCount = sortedCommunities.length;+ const jitter = Math.sqrt(nodeCount) * 3;++ for (let i = 0; i < sortedCommunities.length; i++) {+ const communityId = sortedCommunities[i]!;+ const members = communityNodes.get(communityId)!;++ const angle = i * goldenAngle;+ const radius = spread * Math.sqrt((i + 1) / communityCount);+ const centroidX = radius * Math.cos(angle);+ const centroidY = radius * Math.sin(angle);++ for (const node of members) {+ const hash = simpleHash(node.node_id);+ const x = centroidX + ((hash % 1000) / 1000 - 0.5) * jitter;+ const y = centroidY + (((hash >> 10) % 1000) / 1000 - 0.5) * jitter;++ let baseSize: number;+ if (node.is_entry_point) {+ baseSize = NODE_BASE_SIZES.entryPoint;+ } else if (node.is_test) {+ baseSize = NODE_BASE_SIZES.test;+ } else {+ baseSize = NODE_BASE_SIZES.file;+ }+ let size = getScaledNodeSize(baseSize, nodeCount);+ size *= Math.min(1 + node.pagerank * 2, 2);++ const color = languageColor(node.language);++ const attrs: SigmaNodeAttributes = {+ x,+ y,+ size,+ color,+ label: smartLabel(node.node_id),+ nodeType: "file",+ fullPath: node.node_id,+ language: node.language,+ communityId: node.community_id,+ pagerank: node.pagerank,+ betweenness: node.betweenness,+ isTest: node.is_test,+ isEntryPoint: node.is_entry_point,+ hasDoc: node.has_doc,+ symbolCount: node.symbol_count,+ mass: getNodeMass("file", nodeCount),+ originalColor: color,+ };++ if (options?.signals?.hotNodeIds?.has(node.node_id)) {+ attrs.isHotspot = true;+ }+ if (options?.signals?.deadNodeIds?.has(node.node_id)) {+ attrs.isDead = true;+ }++ result.addNode(node.node_id, attrs);+ }+ }++ // Classify edges in one O(E) pass, then bucket by kind (avoids O(E log E) sort)+ const kindBuckets: Record<SigmaEdgeAttributes["edgeKind"], GraphLink[]> = {+ crossCommunity: [],+ import: [],+ internal: [],+ dynamic: [],+ lowConfidence: [],+ };+ const edgeKindMap = new Map<GraphLink, SigmaEdgeAttributes["edgeKind"]>();+ for (const link of graph.links) {+ const kind = classifyEdge(link, nodeMap);+ edgeKindMap.set(link, kind);+ kindBuckets[kind].push(link);+ }+ const orderedLinks = (+ kindBuckets.crossCommunity+ .concat(kindBuckets.import)+ .concat(kindBuckets.internal)+ .concat(kindBuckets.dynamic)+ .concat(kindBuckets.lowConfidence)+ );++ const maxEdgesPerNode = nodeCount > 1000 ? 25 : Infinity;+ const edgesPerSource = new Map<string, number>();++ for (const link of orderedLinks) {+ if (!result.hasNode(link.source) || !result.hasNode(link.target)) continue;+ const edgeKey = link.source + "→" + link.target;+ if (result.hasEdge(edgeKey)) continue;++ const srcCount = edgesPerSource.get(link.source) ?? 0;+ if (srcCount >= maxEdgesPerNode) continue;+ edgesPerSource.set(link.source, srcCount + 1);++ const edgeKind = edgeKindMap.get(link) ?? classifyEdge(link, nodeMap);++ const useCurved = nodeCount <= CURVED_EDGE_THRESHOLD;+ const edgeAttrs: SigmaEdgeAttributes = {+ size: computeEdgeSize(edgeKind, nodeCount),+ color: EDGE_COLORS[edgeKind],+ type: useCurved ? "curved" : "line",+ curvature: useCurved ? computeEdgeCurvature(edgeKey) : 0,+ edgeKind,+ importedNames: link.imported_names,+ edgeCount: 1,+ };++ if (link.confidence !== undefined) {+ edgeAttrs.confidence = link.confidence;+ }++ result.addEdgeWithKey(edgeKey, link.source, link.target, edgeAttrs);+ }++ return result;+}++export function moduleGraphToGraphology(+ graph: ModuleGraph,+ options?: {+ communities?: CommunitySummaryItem[];+ nodeCount?: number;+ },+): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {+ const result = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();+ const nodeCount = options?.nodeCount ?? graph.nodes.length;++ // Build community lookup: map module_id to community_id+ const moduleCommunity = new Map<string, number>();+ if (options?.communities) {+ for (const community of options.communities) {+ for (const mod of graph.nodes) {+ if (community.top_file === mod.module_id ||+ community.top_file.startsWith(mod.module_id + "/")) {+ moduleCommunity.set(mod.module_id, community.community_id);+ }+ }+ }+ }+ // Fill in missing modules with deterministic hash+ for (const mod of graph.nodes) {+ if (!moduleCommunity.has(mod.module_id)) {+ moduleCommunity.set(mod.module_id, simpleHash(mod.module_id) % 24);+ }+ }++ // Group modules by community for warm-start positioning+ const communityModules = new Map<number, ModuleNode[]>();+ for (const mod of graph.nodes) {+ const cid = moduleCommunity.get(mod.module_id) ?? 0;+ const list = communityModules.get(cid) ?? [];+ list.push(mod);+ communityModules.set(cid, list);+ }++ // Grid-based warm-start: communities in a grid, modules jittered around centroids+ const sortedCommunities = Array.from(communityModules.keys()).sort(+ (a, b) => a - b,+ );+ const communityCount = sortedCommunities.length;+ const cols = Math.max(Math.ceil(Math.sqrt(communityCount)), 1);+ const cellSize = Math.sqrt(nodeCount) * 80;+ const jitter = cellSize * 0.3;++ for (let i = 0; i < sortedCommunities.length; i++) {+ const communityId = sortedCommunities[i]!;+ const members = communityModules.get(communityId)!;++ const col = i % cols;+ const row = Math.floor(i / cols);+ const centroidX = (col - (cols - 1) / 2) * cellSize;+ const centroidY = (row - (Math.ceil(communityCount / cols) - 1) / 2) * cellSize;++ for (const mod of members) {+ const x = centroidX + (Math.random() - 0.5) * jitter;+ const y = centroidY + (Math.random() - 0.5) * jitter;++ const baseSize = getScaledNodeSize(NODE_BASE_SIZES.module, nodeCount);+ const size = baseSize * (0.5 + Math.min(Math.log2(Math.max(mod.file_count, 1)) * 0.3, 1.5));+ const color = getCommunityColor(communityId);++ result.addNode(mod.module_id, {+ x,+ y,+ size,+ color,+ label: smartLabel(mod.module_id),+ nodeType: "module",+ fullPath: mod.module_id,+ language: "",+ communityId,+ pagerank: mod.avg_pagerank,+ betweenness: 0,+ isTest: false,+ isEntryPoint: false,+ hasDoc: mod.doc_coverage_pct > 0,+ symbolCount: mod.symbol_count,+ fileCount: mod.file_count,+ avgPagerank: mod.avg_pagerank,+ docCoveragePct: mod.doc_coverage_pct,+ dominantCommunityId: communityId,+ mass: getNodeMass("module", nodeCount),+ originalColor: color,+ });+ }+ }++ // Add edges+ for (const edge of graph.edges) {+ if (!result.hasNode(edge.source) || !result.hasNode(edge.target)) continue;+ const edgeKey = edge.source + "→" + edge.target;+ if (result.hasEdge(edgeKey)) continue;++ const sourceCid = moduleCommunity.get(edge.source) ?? 0;+ const targetCid = moduleCommunity.get(edge.target) ?? 0;+ const edgeKind: SigmaEdgeAttributes["edgeKind"] =+ sourceCid === targetCid ? "internal" : "crossCommunity";++ const baseScale =+ nodeCount > 5000 ? 0.4 : nodeCount > 1000 ? 0.6 : 1.0;++ result.addEdgeWithKey(edgeKey, edge.source, edge.target, {+ size:+ baseScale *+ EDGE_SIZE_MULTIPLIERS[edgeKind] *+ (1 + Math.log2(edge.edge_count)),+ color: EDGE_COLORS[edgeKind],+ type: "curved",+ curvature: computeEdgeCurvature(edgeKey),+ edgeKind,+ importedNames: [],+ edgeCount: edge.edge_count,+ });+ }++ return result;+}++export function groupFilesAsModules(+ graph: GraphExport,+ options?: { prefix?: string },+): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {+ const { moduleNodes, moduleEdges } = groupNodesAsModules(+ graph.nodes,+ graph.links,+ options?.prefix ?? "",+ );++ return moduleGraphToGraphology({ nodes: moduleNodes, edges: moduleEdges });+}diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsxnew file mode 100644index 000000000..71d2c9b14--- /dev/null+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx@@ -0,0 +1,214 @@+"use client";++import {+ useRef,+ useState,+ useCallback,+ forwardRef,+ useImperativeHandle,+ useEffect,+} from "react";+import type Graph from "graphology";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";+import type { ColorMode, ViewMode } from "../graph-toolbar";+import type { Signal } from "../context";+import type {+ GraphNode as GraphNodeResponse,+ GraphLink as GraphEdgeResponse,+ ModuleNode as ModuleNodeResponse,+ ModuleEdge as ModuleEdgeResponse,+} from "@repowise-dev/types/graph";+import { useSigmaRenderer } from "./use-sigma";+import { useFA2Layout } from "./use-fa2-layout";+import { useElkSigmaLayout } from "./use-elk-sigma-layout";+import { SigmaControls } from "./sigma-controls";+import { SigmaMinimap } from "./sigma-minimap";++export interface SigmaCanvasProps {+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ layoutMode: "force" | "hierarchical";+ viewMode: ViewMode;+ selectedNodeId: string | null;+ hoveredNodeId: string | null;+ highlightedPath: Set<string>;+ highlightedEdges: Set<string>;+ searchDimmedNodes: Set<string> | null;+ communityDimmedNodes: Set<string> | null;+ colorMode: ColorMode;+ activeSignals: Set<Signal>;+ graphTheme: "light" | "dark";+ fileNodes?: GraphNodeResponse[] | undefined;+ fileEdges?: GraphEdgeResponse[] | undefined;+ moduleNodes?: ModuleNodeResponse[] | undefined;+ moduleEdges?: ModuleEdgeResponse[] | undefined;+ onNodeClick?: ((nodeId: string, nodeType: string) => void) | undefined;+ onNodeHover?: ((nodeId: string | null) => void) | undefined;+ onNodeContextMenu?:+ | ((event: MouseEvent, nodeId: string, nodeType: string) => void)+ | undefined;+ onNodeDoubleClick?: ((nodeId: string, nodeType: string) => void) | undefined;+ onStageClick?: (() => void) | undefined;+ hiddenNodes?: Set<string> | undefined;+ visibleEdgeTypes?: Set<string> | undefined;+}++export interface SigmaCanvasHandle {+ focusNode: (nodeId: string) => void;+ fitView: () => void;+ zoomIn: () => void;+ zoomOut: () => void;+}++export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(+ function SigmaCanvas(props, ref) {+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const containerCallback = useCallback((node: HTMLDivElement | null) => {+ setContainer(node);+ }, []);++ const { sigma, focusNode, fitView, zoomIn, zoomOut } = useSigmaRenderer({+ container,+ graph: props.graph,+ selectedNodeId: props.selectedNodeId,+ hoveredNodeId: props.hoveredNodeId,+ highlightedPath: props.highlightedPath,+ highlightedEdges: props.highlightedEdges,+ searchDimmedNodes: props.searchDimmedNodes,+ communityDimmedNodes: props.communityDimmedNodes,+ colorMode: props.colorMode,+ activeSignals: props.activeSignals,+ graphTheme: props.graphTheme,+ hiddenNodes: props.hiddenNodes,+ visibleEdgeTypes: props.visibleEdgeTypes,+ });++ const { isRunning: isLayoutRunning, toggle: toggleLayout } = useFA2Layout({+ graph: props.graph,+ sigma,+ enabled: props.layoutMode === "force",+ });++ const { isComputing: isElkComputing } = useElkSigmaLayout({+ graph: props.graph,+ sigma,+ enabled: props.layoutMode === "hierarchical",+ fileNodes: props.fileNodes,+ fileEdges: props.fileEdges,+ moduleNodes: props.moduleNodes,+ moduleEdges: props.moduleEdges,+ viewMode: props.viewMode,+ });++ // Keep callback refs up to date so Sigma event handlers always use latest props+ const onNodeClickRef = useRef(props.onNodeClick);+ const onStageClickRef = useRef(props.onStageClick);+ const onNodeHoverRef = useRef(props.onNodeHover);+ const onNodeContextMenuRef = useRef(props.onNodeContextMenu);+ const onNodeDoubleClickRef = useRef(props.onNodeDoubleClick);+ useEffect(() => {+ onNodeClickRef.current = props.onNodeClick;+ onStageClickRef.current = props.onStageClick;+ onNodeHoverRef.current = props.onNodeHover;+ onNodeContextMenuRef.current = props.onNodeContextMenu;+ onNodeDoubleClickRef.current = props.onNodeDoubleClick;+ });++ // Wire Sigma events+ useEffect(() => {+ if (!sigma) return;++ const handleClickNode = ({ node }: { node: string }) => {+ const graph = sigma.getGraph();+ const attrs = graph.getNodeAttributes(node);+ onNodeClickRef.current?.(node, attrs.nodeType);+ };++ const handleClickStage = () => {+ onStageClickRef.current?.();+ };++ const handleEnterNode = ({ node }: { node: string }) => {+ onNodeHoverRef.current?.(node);+ if (container)+ container.style.cursor = "pointer";+ };++ const handleLeaveNode = () => {+ onNodeHoverRef.current?.(null);+ if (container) container.style.cursor = "grab";+ };++ const handleRightClickNode = ({+ node,+ event,+ }: {+ node: string;+ event: { original: MouseEvent | TouchEvent };+ }) => {+ event.original.preventDefault();+ if (event.original instanceof MouseEvent) {+ const graph = sigma.getGraph();+ const attrs = graph.getNodeAttributes(node);+ onNodeContextMenuRef.current?.(event.original, node, attrs.nodeType);+ }+ };++ const handleDoubleClickNode = ({ node }: { node: string }) => {+ const graph = sigma.getGraph();+ const attrs = graph.getNodeAttributes(node);+ onNodeDoubleClickRef.current?.(node, attrs.nodeType);+ };++ sigma.on("clickNode", handleClickNode);+ sigma.on("clickStage", handleClickStage);+ sigma.on("enterNode", handleEnterNode);+ sigma.on("leaveNode", handleLeaveNode);+ sigma.on("rightClickNode", handleRightClickNode);+ sigma.on("doubleClickNode", handleDoubleClickNode);++ return () => {+ sigma.off("clickNode", handleClickNode);+ sigma.off("clickStage", handleClickStage);+ sigma.off("enterNode", handleEnterNode);+ sigma.off("leaveNode", handleLeaveNode);+ sigma.off("rightClickNode", handleRightClickNode);+ sigma.off("doubleClickNode", handleDoubleClickNode);+ };+ }, [sigma, container]);++ useImperativeHandle(ref, () => ({+ focusNode,+ fitView,+ zoomIn,+ zoomOut,+ }));++ return (+ <div className="relative w-full h-full">+ <div+ ref={containerCallback}+ className="w-full h-full"+ style={{+ background:+ props.graphTheme === "dark" ? "#0f0f1a" : "transparent",+ cursor: "grab",+ }}+ />+ <SigmaControls+ onZoomIn={zoomIn}+ onZoomOut={zoomOut}+ onFitView={fitView}+ onFocusSelected={+ props.selectedNodeId+ ? () => focusNode(props.selectedNodeId!)+ : undefined+ }+ isLayoutRunning={props.layoutMode === "force" ? isLayoutRunning : isElkComputing}+ onToggleLayout={props.layoutMode === "force" ? toggleLayout : undefined}+ graphTheme={props.graphTheme}+ />+ <SigmaMinimap sigma={sigma} graphTheme={props.graphTheme} />+ </div>+ );+ },+);diff --git a/packages/ui/src/graph/sigma/sigma-controls.tsx b/packages/ui/src/graph/sigma/sigma-controls.tsxnew file mode 100644index 000000000..2966ba79c--- /dev/null+++ b/packages/ui/src/graph/sigma/sigma-controls.tsx@@ -0,0 +1,97 @@+"use client";++import { ZoomIn, ZoomOut, Maximize, Focus, Play, Pause } from "lucide-react";+import { Button } from "../../ui/button";++interface SigmaControlsProps {+ onZoomIn: () => void;+ onZoomOut: () => void;+ onFitView: () => void;+ onFocusSelected?: (() => void) | undefined;+ isLayoutRunning: boolean;+ onToggleLayout?: (() => void) | undefined;+ graphTheme: "light" | "dark";+}++export function SigmaControls({+ onZoomIn,+ onZoomOut,+ onFitView,+ onFocusSelected,+ isLayoutRunning,+ onToggleLayout,+ graphTheme,+}: SigmaControlsProps) {+ const isDark = graphTheme === "dark";+ const btnClass = isDark+ ? "h-7 w-7 p-0 border-white/10 bg-[#1a1a2e] text-white/60 hover:bg-[#252540] hover:text-white shadow-lg shadow-black/40"+ : "h-7 w-7 p-0 border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)] shadow-lg shadow-black/20";++ return (+ <div className="absolute bottom-3 right-3 z-10 flex flex-col gap-1">+ <Button+ size="sm"+ variant="outline"+ onClick={onZoomIn}+ className={btnClass}+ title="Zoom in"+ aria-label="Zoom in"+ >+ <ZoomIn className="w-3.5 h-3.5" />+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={onZoomOut}+ className={btnClass}+ title="Zoom out"+ aria-label="Zoom out"+ >+ <ZoomOut className="w-3.5 h-3.5" />+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={onFitView}+ className={btnClass}+ title="Fit view"+ aria-label="Fit view"+ >+ <Maximize className="w-3.5 h-3.5" />+ </Button>+ {onFocusSelected && (+ <Button+ size="sm"+ variant="outline"+ onClick={onFocusSelected}+ className={btnClass}+ title="Focus selected"+ aria-label="Focus selected"+ >+ <Focus className="w-3.5 h-3.5" />+ </Button>+ )}+ {onToggleLayout && (+ <Button+ size="sm"+ variant="outline"+ onClick={onToggleLayout}+ className={btnClass}+ title={isLayoutRunning ? "Stop layout" : "Run layout"}+ aria-label={isLayoutRunning ? "Stop layout" : "Run layout"}+ >+ {isLayoutRunning ? (+ <Pause className="w-3.5 h-3.5" />+ ) : (+ <Play className="w-3.5 h-3.5" />+ )}+ </Button>+ )}+ {isLayoutRunning && (+ <div className="text-[9px] text-center text-[var(--color-accent-graph)] animate-pulse whitespace-nowrap">+ Layout optimizing...+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/graph/sigma/sigma-minimap.tsx b/packages/ui/src/graph/sigma/sigma-minimap.tsxnew file mode 100644index 000000000..454c4ff01--- /dev/null+++ b/packages/ui/src/graph/sigma/sigma-minimap.tsx@@ -0,0 +1,92 @@+"use client";++import { useRef, useEffect } from "react";+import type Sigma from "sigma";++interface SigmaMinimapProps {+ sigma: Sigma | null;+ graphTheme: "light" | "dark";+}++export function SigmaMinimap({ sigma, graphTheme }: SigmaMinimapProps) {+ const canvasRef = useRef<HTMLCanvasElement>(null);++ useEffect(() => {+ if (!sigma) return;++ const canvas = canvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ const draw = () => {+ const width = canvas.width;+ const height = canvas.height;+ const graph = sigma.getGraph();++ ctx.clearRect(0, 0, width, height);++ if (graph.order === 0) return;++ let minX = Infinity;+ let maxX = -Infinity;+ let minY = Infinity;+ let maxY = -Infinity;++ graph.forEachNode((_node, attrs) => {+ if (attrs.x < minX) minX = attrs.x;+ if (attrs.x > maxX) maxX = attrs.x;+ if (attrs.y < minY) minY = attrs.y;+ if (attrs.y > maxY) maxY = attrs.y;+ });++ const rangeX = maxX - minX || 1;+ const rangeY = maxY - minY || 1;+ const padding = 8;+ const drawW = width - padding * 2;+ const drawH = height - padding * 2;++ graph.forEachNode((_node, attrs) => {+ const px = padding + ((attrs.x - minX) / rangeX) * drawW;+ const py = padding + ((attrs.y - minY) / rangeY) * drawH;+ ctx.fillStyle = (attrs.color as string) || "#6b7280";+ ctx.beginPath();+ ctx.arc(px, py, 1.5, 0, Math.PI * 2);+ ctx.fill();+ });++ const camera = sigma.getCamera();+ const state = camera.getState();+ const vw = (1 / (state.ratio || 1)) * 0.3;+ const vh = (1 / (state.ratio || 1)) * 0.3;+ const vx = padding + ((state.x - minX) / rangeX) * drawW - (vw * drawW) / 2;+ const vy = padding + ((state.y - minY) / rangeY) * drawH - (vh * drawH) / 2;++ ctx.strokeStyle = graphTheme === "dark" ? "rgba(255,255,255,0.3)" : "rgba(0,0,0,0.3)";+ ctx.lineWidth = 1;+ ctx.strokeRect(vx, vy, vw * drawW, vh * drawH);+ };++ sigma.on("afterRender", draw);+ draw();++ return () => {+ sigma.off("afterRender", draw);+ };+ }, [sigma, graphTheme]);++ const isDark = graphTheme === "dark";++ return (+ <canvas+ ref={canvasRef}+ width={120}+ height={80}+ className={`absolute bottom-3 left-3 z-10 rounded-lg border hidden sm:block ${+ isDark+ ? "bg-[#1a1a2e] border-white/10 shadow-lg shadow-black/40"+ : "bg-[var(--color-bg-surface)] border-[var(--color-border-default)] shadow-lg shadow-black/20"+ }`}+ />+ );+}diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.tsnew file mode 100644index 000000000..c8ef1f728--- /dev/null+++ b/packages/ui/src/graph/sigma/types.ts@@ -0,0 +1,82 @@+/**+ * Sigma-specific attribute types for Graphology graph instances.+ *+ * These extend the base Repowise types (GraphNode, ModuleNode) with+ * rendering attributes that Sigma.js needs: position, size, color,+ * and interaction state.+ */++export interface SigmaNodeAttributes {+ // Position (required by Sigma)+ x: number;+ y: number;++ // Rendering+ size: number;+ color: string;+ label: string;++ // Identity+ nodeType: "file" | "module";+ fullPath: string;+ language: string;++ // Graph metrics (from GraphNode)+ communityId: number;+ pagerank: number;+ betweenness: number;+ isTest: boolean;+ isEntryPoint: boolean;+ hasDoc: boolean;+ symbolCount: number;++ // Module-specific (from ModuleNode, only set when nodeType === "module")+ fileCount?: number | undefined;+ avgPagerank?: number | undefined;+ docCoveragePct?: number | undefined;+ dominantCommunityId?: number | undefined;++ // Signal overlays (set by adapter based on signal data)+ isHotspot?: boolean | undefined;+ isDead?: boolean | undefined;+ commitCount?: number | undefined;++ // Interaction state (mutated by reducers at render time)+ hidden?: boolean | undefined;+ zIndex?: number | undefined;+ highlighted?: boolean | undefined;++ // ForceAtlas2 mass parameter (higher = more repulsion)+ mass?: number | undefined;++ // For dimming/restoring original color+ originalColor?: string | undefined;+}++export interface SigmaEdgeAttributes {+ size: number;+ color: string;++ // Sigma edge program type ("curved" for small graphs, "line" for large)+ type: "curved" | "line";++ // Random curvature for visual variety (0.12-0.20)+ curvature: number;++ // Semantic classification of the edge+ edgeKind:+ | "import"+ | "crossCommunity"+ | "internal"+ | "dynamic"+ | "lowConfidence";++ // Original data+ importedNames: string[];+ edgeCount: number;+ confidence?: number | undefined;++ // Interaction state+ hidden?: boolean | undefined;+ zIndex?: number | undefined;+}diff --git a/packages/ui/src/graph/sigma/use-ego-filter.ts b/packages/ui/src/graph/sigma/use-ego-filter.tsnew file mode 100644index 000000000..a20353765--- /dev/null+++ b/packages/ui/src/graph/sigma/use-ego-filter.ts@@ -0,0 +1,65 @@+import { useMemo } from "react";+import type Graph from "graphology";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";++export interface UseEgoFilterOptions {+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ selectedNodeId: string | null;+ depth: number;+}++export interface UseEgoFilterReturn {+ egoNodes: Set<string>;+ hiddenNodes: Set<string>;+ isActive: boolean;+ visibleCount: number;+}++export function useEgoFilter(options: UseEgoFilterOptions): UseEgoFilterReturn {+ const { graph, selectedNodeId, depth } = options;++ return useMemo(() => {+ if (+ depth === 0 ||+ !selectedNodeId ||+ !graph ||+ !graph.hasNode(selectedNodeId)+ ) {+ return {+ egoNodes: new Set<string>(),+ hiddenNodes: new Set<string>(),+ isActive: false,+ visibleCount: 0,+ };+ }++ const visited = new Set<string>([selectedNodeId]);+ let frontier = [selectedNodeId];+ for (let d = 0; d < depth; d++) {+ const nextFrontier: string[] = [];+ for (const node of frontier) {+ for (const neighbor of graph.neighbors(node)) {+ if (!visited.has(neighbor)) {+ visited.add(neighbor);+ nextFrontier.push(neighbor);+ }+ }+ }+ frontier = nextFrontier;+ }++ const hiddenNodes = new Set<string>();+ graph.forEachNode((nodeId) => {+ if (!visited.has(nodeId)) {+ hiddenNodes.add(nodeId);+ }+ });++ return {+ egoNodes: visited,+ hiddenNodes,+ isActive: true,+ visibleCount: visited.size,+ };+ }, [graph, selectedNodeId, depth]);+}diff --git a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts b/packages/ui/src/graph/sigma/use-elk-sigma-layout.tsnew file mode 100644index 000000000..de66ebbae--- /dev/null+++ b/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts@@ -0,0 +1,108 @@+"use client";++import { useRef, useEffect, useCallback, useState } from "react";+import type Sigma from "sigma";+import type Graph from "graphology";+import type {+ GraphNode as GraphNodeResponse,+ GraphLink as GraphEdgeResponse,+ ModuleNode as ModuleNodeResponse,+ ModuleEdge as ModuleEdgeResponse,+} from "@repowise-dev/types/graph";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";+import type { ViewMode } from "../graph-toolbar";+import {+ computeElkFilePositions,+ computeElkModulePositions,+} from "../elk-layout";++export interface UseElkSigmaLayoutOptions {+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ sigma: Sigma | null;+ enabled: boolean;+ fileNodes?: GraphNodeResponse[] | undefined;+ fileEdges?: GraphEdgeResponse[] | undefined;+ moduleNodes?: ModuleNodeResponse[] | undefined;+ moduleEdges?: ModuleEdgeResponse[] | undefined;+ viewMode: ViewMode;+ onSkipped?: (reason: string) => void;+}++export interface UseElkSigmaLayoutReturn {+ isComputing: boolean;+ recompute: () => void;+}++export function useElkSigmaLayout(+ options: UseElkSigmaLayoutOptions,+): UseElkSigmaLayoutReturn {+ const [isComputing, setIsComputing] = useState(false);+ const computeIdRef = useRef(0);++ const {+ graph,+ sigma,+ enabled,+ fileNodes,+ fileEdges,+ moduleNodes,+ moduleEdges,+ viewMode,+ } = options;++ const compute = useCallback(() => {+ if (!graph || graph.order === 0 || !sigma) return;++ const computeId = ++computeIdRef.current;+ setIsComputing(true);++ const run = async () => {+ try {+ if (viewMode === "module" && moduleNodes && moduleEdges) {+ const positions = await computeElkModulePositions(+ moduleNodes,+ moduleEdges,+ );+ if (computeIdRef.current !== computeId) return;+ graph.forEachNode((nodeId) => {+ const pos = positions.get(nodeId);+ if (pos) {+ graph.setNodeAttribute(nodeId, "x", pos.x);+ graph.setNodeAttribute(nodeId, "y", pos.y);+ }+ });+ } else if (fileNodes && fileEdges) {+ const result = await computeElkFilePositions(fileNodes, fileEdges);+ if (computeIdRef.current !== computeId) return;+ graph.forEachNode((nodeId) => {+ const pos = result.positions.get(nodeId);+ if (pos) {+ graph.setNodeAttribute(nodeId, "x", pos.x);+ graph.setNodeAttribute(nodeId, "y", pos.y);+ }+ });+ }+ sigma.refresh();+ sigma.getCamera().animatedReset({ duration: 500 });+ } finally {+ if (computeIdRef.current === computeId) {+ setIsComputing(false);+ }+ }+ };++ void run();+ }, [graph, sigma, fileNodes, fileEdges, moduleNodes, moduleEdges, viewMode]);++ useEffect(() => {+ if (enabled && graph && graph.order > 0) {+ if (graph.order > 500) {+ options.onSkipped?.("Graph too large for hierarchical layout (>500 nodes)");+ return;+ }+ compute();+ }+ }, [enabled, graph, compute, options.onSkipped]);++ return { isComputing, recompute: compute };+}diff --git a/packages/ui/src/graph/sigma/use-fa2-layout.ts b/packages/ui/src/graph/sigma/use-fa2-layout.tsnew file mode 100644index 000000000..0663c5d95--- /dev/null+++ b/packages/ui/src/graph/sigma/use-fa2-layout.ts@@ -0,0 +1,179 @@+import { useRef, useEffect, useCallback, useState } from "react";+import type Sigma from "sigma";+import type Graph from "graphology";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";+import {+ getFA2Settings,+ getLayoutDuration,+ NOVERLAP_SETTINGS,+} from "./constants";++type FA2LayoutType = import("graphology-layout-forceatlas2/worker").default;++export interface UseFA2LayoutOptions {+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ sigma: Sigma | null;+ enabled: boolean;+}++export interface UseFA2LayoutReturn {+ isRunning: boolean;+ start: () => void;+ stop: () => void;+ toggle: () => void;+}++export function useFA2Layout(+ options: UseFA2LayoutOptions,+): UseFA2LayoutReturn {+ const layoutRef = useRef<FA2LayoutType | null>(null);+ const layoutTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const cancelledRef = useRef(false);+ const [isRunning, setIsRunning] = useState(false);++ const convergenceIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);++ const killLayout = useCallback(() => {+ cancelledRef.current = true;+ if (layoutTimeoutRef.current) {+ clearTimeout(layoutTimeoutRef.current);+ layoutTimeoutRef.current = null;+ }+ if (convergenceIntervalRef.current) {+ clearInterval(convergenceIntervalRef.current);+ convergenceIntervalRef.current = null;+ }+ if (layoutRef.current) {+ layoutRef.current.kill();+ layoutRef.current = null;+ }+ }, []);++ const runLayout = useCallback(+ (graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>) => {+ killLayout();+ cancelledRef.current = false;++ (async () => {+ const [{ default: FA2Layout }, { default: forceAtlas2 }] =+ await Promise.all([+ import("graphology-layout-forceatlas2/worker"),+ import("graphology-layout-forceatlas2"),+ ]);++ if (cancelledRef.current) return;++ const inferred = forceAtlas2.inferSettings(graph);+ const settings = { ...inferred, ...getFA2Settings(graph.order) };++ const layout = new FA2Layout(graph, { settings });+ layoutRef.current = layout;+ layout.start();+ setIsRunning(true);++ const finishLayout = async () => {+ if (convergenceIntervalRef.current) {+ clearInterval(convergenceIntervalRef.current);+ convergenceIntervalRef.current = null;+ }+ if (layoutTimeoutRef.current) {+ clearTimeout(layoutTimeoutRef.current);+ layoutTimeoutRef.current = null;+ }+ layout.stop();+ layout.kill();+ layoutRef.current = null;++ const { default: noverlap } = await import(+ "graphology-layout-noverlap"+ );+ noverlap.assign(graph, NOVERLAP_SETTINGS);+ options.sigma?.refresh();+ setIsRunning(false);+ };++ // Convergence detection: sample 50 nodes every 500ms+ const sampleSize = Math.min(50, graph.order);+ const nodeIds = graph.nodes().slice(0, sampleSize);+ let prevPositions = nodeIds.map((id) => {+ const a = graph.getNodeAttributes(id);+ return { x: a.x, y: a.y };+ });++ convergenceIntervalRef.current = setInterval(() => {+ if (cancelledRef.current) return;+ const currentPositions = nodeIds.map((id) => {+ const a = graph.getNodeAttributes(id);+ return { x: a.x, y: a.y };+ });+ let totalDelta = 0;+ for (let i = 0; i < nodeIds.length; i++) {+ const dx = currentPositions[i]!.x - prevPositions[i]!.x;+ const dy = currentPositions[i]!.y - prevPositions[i]!.y;+ totalDelta += Math.sqrt(dx * dx + dy * dy);+ }+ const avgDelta = totalDelta / nodeIds.length;+ prevPositions = currentPositions;+ if (avgDelta < 0.5) {+ finishLayout();+ }+ }, 500);++ // Hard cap timeout as fallback+ layoutTimeoutRef.current = setTimeout(() => {+ finishLayout();+ }, getLayoutDuration(graph.order));+ })();+ },+ [killLayout, options.sigma],+ );++ // Start layout when enabled and graph is ready+ useEffect(() => {+ if (options.enabled && options.graph && options.graph.order > 0) {+ runLayout(options.graph);+ } else {+ killLayout();+ setIsRunning(false);+ }+ return () => {+ killLayout();+ };+ }, [options.enabled, options.graph, runLayout, killLayout]);++ const start = useCallback(() => {+ if (options.graph && options.graph.order > 0) {+ runLayout(options.graph);+ }+ }, [options.graph, runLayout]);++ const stop = useCallback(() => {+ killLayout();+ if (options.graph) {+ const g = options.graph;+ const s = options.sigma;+ import("graphology-layout-noverlap").then(({ default: noverlap }) => {+ noverlap.assign(g, NOVERLAP_SETTINGS);+ s?.refresh();+ });+ }+ setIsRunning(false);+ }, [killLayout, options.graph, options.sigma]);++ const toggle = useCallback(() => {+ if (isRunning) {+ stop();+ } else {+ start();+ }+ }, [isRunning, start, stop]);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ killLayout();+ };+ }, [killLayout]);++ return { isRunning, start, stop, toggle };+}diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.tsnew file mode 100644index 000000000..d2112e6b4--- /dev/null+++ b/packages/ui/src/graph/sigma/use-sigma.ts@@ -0,0 +1,449 @@+import { useRef, useEffect, useCallback, useState } from "react";+import type Sigma from "sigma";+import type Graph from "graphology";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";+import type { ColorMode } from "../graph-toolbar";+import type { Signal } from "../context";+import {+ LABEL_FONT,+ LABEL_SIZE,+ LABEL_DENSITY,+ LABEL_GRID_CELL_SIZE,+ LABEL_RENDERED_SIZE_THRESHOLD,+ getCommunityColor,+ languageColor,+} from "./constants";++// ---- Color helpers (kept minimal — avoid regex in hot paths) ----++function hexToRgb(hex: string): [number, number, number] {+ const v = parseInt(hex.slice(1), 16);+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];+}++function rgbToHex(r: number, g: number, b: number): string {+ return "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);+}++const THEME_COLORS = {+ dark: { bg: [18, 18, 28] as const, text: "#f5f5f7", subtitle: "#888888", tooltip: "#12121c" },+ light: { bg: [250, 250, 252] as const, text: "#1a1a2e", subtitle: "#666666", tooltip: "#ffffff" },+};++let activeBg: readonly [number, number, number] = THEME_COLORS.dark.bg;++const dimColorCache = new Map<string, string>();+const brightenColorCache = new Map<string, string>();++function clearColorCaches() {+ dimColorCache.clear();+ brightenColorCache.clear();+}++function dimColor(hex: string, amount: number): string {+ const key = hex + amount;+ const cached = dimColorCache.get(key);+ if (cached) return cached;+ const [r, g, b] = hexToRgb(hex);+ const result = rgbToHex(+ Math.round(activeBg[0] + (r - activeBg[0]) * amount),+ Math.round(activeBg[1] + (g - activeBg[1]) * amount),+ Math.round(activeBg[2] + (b - activeBg[2]) * amount),+ );+ dimColorCache.set(key, result);+ return result;+}++function brightenColor(hex: string, factor: number): string {+ const key = hex + factor;+ const cached = brightenColorCache.get(key);+ if (cached) return cached;+ const [r, g, b] = hexToRgb(hex);+ const result = rgbToHex(+ Math.round(r + ((255 - r) * (factor - 1)) / factor),+ Math.round(g + ((255 - g) * (factor - 1)) / factor),+ Math.round(b + ((255 - b) * (factor - 1)) / factor),+ );+ brightenColorCache.set(key, result);+ return result;+}++function desaturateColor(hex: string, amount: number): string {+ const [r, g, b] = hexToRgb(hex);+ const gray = 0.299 * r + 0.587 * g + 0.114 * b;+ return rgbToHex(+ Math.round(r + (gray - r) * amount),+ Math.round(g + (gray - g) * amount),+ Math.round(b + (gray - b) * amount),+ );+}++function tintColor(hex: string, tintHex: string, amount: number): string {+ const [r, g, b] = hexToRgb(hex);+ const [tr, tg, tb] = hexToRgb(tintHex);+ return rgbToHex(+ Math.round(r + (tr - r) * amount),+ Math.round(g + (tg - g) * amount),+ Math.round(b + (tb - b) * amount),+ );+}++export interface UseSigmaOptions {+ container: HTMLDivElement | null;+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;+ selectedNodeId: string | null;+ hoveredNodeId: string | null;+ highlightedPath: Set<string>;+ highlightedEdges: Set<string>;+ searchDimmedNodes: Set<string> | null;+ communityDimmedNodes: Set<string> | null;+ colorMode: ColorMode;+ activeSignals: Set<Signal>;+ graphTheme: "light" | "dark";+ hiddenNodes?: Set<string> | undefined;+ visibleEdgeTypes?: Set<string> | undefined;+}++export interface UseSigmaReturn {+ sigma: Sigma | null;+ focusNode: (nodeId: string) => void;+ fitView: () => void;+ zoomIn: () => void;+ zoomOut: () => void;+}++export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {+ const newBg = (THEME_COLORS[options.graphTheme] ?? THEME_COLORS.dark).bg;+ if (newBg !== activeBg) {+ activeBg = newBg;+ clearColorCaches();+ }++ const sigmaRef = useRef<Sigma | null>(null);+ const [sigmaReady, setSigmaReady] = useState<Sigma | null>(null);+ const selectedRef = useRef<string | null>(null);+ const highlightedPathRef = useRef<Set<string>>(new Set());+ const highlightedEdgesRef = useRef<Set<string>>(new Set());+ const searchDimmedRef = useRef<Set<string> | null>(null);+ const communityDimmedRef = useRef<Set<string> | null>(null);+ const hiddenNodesRef = useRef<Set<string> | undefined>(undefined);+ const graphRef = useRef<Graph<+ SigmaNodeAttributes,+ SigmaEdgeAttributes+ > | null>(null);++ // Sync interaction state refs (no color work here — that's in the graph effect)+ useEffect(() => {+ selectedRef.current = options.selectedNodeId;+ highlightedPathRef.current = options.highlightedPath;+ highlightedEdgesRef.current = options.highlightedEdges;+ searchDimmedRef.current = options.searchDimmedNodes;+ communityDimmedRef.current = options.communityDimmedNodes;+ hiddenNodesRef.current = options.hiddenNodes;+ sigmaRef.current?.refresh();+ }, [+ options.selectedNodeId,+ options.highlightedPath,+ options.highlightedEdges,+ options.searchDimmedNodes,+ options.communityDimmedNodes,+ options.hiddenNodes,+ ]);++ // Pre-hide edges by type on the graphology graph (batch: 1 event instead of N)+ useEffect(() => {+ const graph = options.graph;+ if (!graph || graph.size === 0) return;+ const visibleTypes = options.visibleEdgeTypes;+ graph.updateEachEdgeAttributes(+ (_edge, attrs) => {+ const shouldHide = visibleTypes ? !visibleTypes.has(attrs.edgeKind) : false;+ if (attrs.hidden === shouldHide) return attrs;+ return { ...attrs, hidden: shouldHide };+ },+ { attributes: ["hidden"] },+ );+ }, [options.visibleEdgeTypes, options.graph]);++ // Pre-apply node colors on the graphology graph (batch: 1 event instead of N)+ useEffect(() => {+ const graph = options.graph;+ if (!graph || graph.order === 0) return;+ const cm = options.colorMode;+ graph.updateEachNodeAttributes(+ (_node, attrs) => {+ let color: string;+ if (cm === "language") {+ color = languageColor(attrs.language || "other");+ } else if (cm === "community") {+ color = getCommunityColor(attrs.communityId);+ } else {+ const risk = attrs.pagerank * 3;+ color = risk > 0.7 ? "#ef4444" : risk > 0.3 ? "#f59e0b" : "#22c55e";+ }+ if (attrs.isDead) color = desaturateColor(color, 0.6);+ if (attrs.isHotspot) color = tintColor(color, "#f97316", 0.4);+ if (attrs.color === color) return attrs;+ return { ...attrs, color };+ },+ { attributes: ["color"] },+ );+ }, [options.colorMode, options.graph]);++ // Initialize Sigma (dynamic import to avoid SSR WebGL crash)+ useEffect(() => {+ const container = options.container;+ if (!container) return;++ let cancelled = false;+ let sigmaInstance: Sigma | null = null;++ (async () => {+ const [{ default: SigmaConstructor }, { default: EdgeCurveProgram }, sigmaRendering, graphologyModule] =+ await Promise.all([+ import("sigma"),+ import("@sigma/edge-curve"),+ import("sigma/rendering"),+ import("graphology"),+ ]);+ const EdgeLineProgram = sigmaRendering.EdgeLineProgram;++ if (cancelled) return;++ const graph =+ options.graph ?? new graphologyModule.default() as Graph<SigmaNodeAttributes, SigmaEdgeAttributes>;+ graphRef.current = options.graph;++ const sigma = new SigmaConstructor(graph, container, {+ renderLabels: true,+ labelFont: LABEL_FONT,+ labelSize: LABEL_SIZE,+ labelDensity: LABEL_DENSITY,+ labelGridCellSize: LABEL_GRID_CELL_SIZE,+ labelRenderedSizeThreshold: LABEL_RENDERED_SIZE_THRESHOLD,+ labelColor: { color: "#e4e4ed" },+ defaultNodeColor: "#6b7280",+ defaultEdgeColor: "#2a2a3a",+ defaultEdgeType: "curved",+ edgeProgramClasses: {+ curved: EdgeCurveProgram,+ line: EdgeLineProgram,+ },+ minCameraRatio: 0.002,+ maxCameraRatio: 50,+ hideEdgesOnMove: true,+ zIndex: true,++ defaultDrawNodeHover: (context, data, settings) => {+ const label = data.label;+ if (!label) return;++ const theme = THEME_COLORS[options.graphTheme] ?? THEME_COLORS.dark;+ const extra = data as Record<string, unknown>;+ const fullPath = (extra.fullPath as string) ?? undefined;++ const primarySize = settings.labelSize || 11;+ const secondarySize = 9;+ const font = settings.labelFont || "JetBrains Mono, monospace";+ context.font = `500 ${primarySize}px ${font}`;+ const labelWidth = context.measureText(label).width;++ let showPath = false;+ let pathWidth = 0;+ if (fullPath && fullPath !== label) {+ context.font = `400 ${secondarySize}px ${font}`;+ pathWidth = context.measureText(fullPath).width;+ showPath = true;+ }++ const nodeSize = data.size || 8;+ const paddingX = 10;+ const paddingY = 5;+ const lineGap = showPath ? 3 : 0;+ const width = Math.max(labelWidth, pathWidth) + paddingX * 2;+ const height =+ primarySize + (showPath ? lineGap + secondarySize : 0) + paddingY * 2;+ const radius = 5;+ const x = data.x;+ const y = data.y - nodeSize - 12 - height / 2;++ context.fillStyle = theme.tooltip;+ context.beginPath();+ context.roundRect(x - width / 2, y - height / 2, width, height, radius);+ context.fill();+ context.lineWidth = 2;+ context.strokeStyle = data.color || "#6366f1";+ context.stroke();++ context.textAlign = "center";+ context.textBaseline = "middle";++ const labelY = showPath ? y - (lineGap + secondarySize) / 2 : y;+ context.fillStyle = theme.text;+ context.font = `500 ${primarySize}px ${font}`;+ context.fillText(label, x, labelY);++ if (showPath) {+ context.fillStyle = theme.subtitle;+ context.font = `400 ${secondarySize}px ${font}`;+ context.fillText(+ fullPath!,+ x,+ labelY + primarySize / 2 + lineGap + secondarySize / 2,+ );+ }++ context.beginPath();+ context.arc(data.x, data.y, nodeSize + 4, 0, Math.PI * 2);+ context.strokeStyle = data.color || "#6366f1";+ context.lineWidth = 2;+ context.globalAlpha = 0.5;+ context.stroke();+ context.globalAlpha = 1;+ },++ // --- nodeReducer: ONLY handles interaction state (selection, search, path) ---+ // Colors and sizes are pre-set on the graphology graph by the effect above.+ nodeReducer: (node, data) => {+ if (data.hidden) return data;++ const hiddenSet = hiddenNodesRef.current;+ if (hiddenSet?.has(node)) return { ...data, hidden: true };++ const selected = selectedRef.current;+ const pathNodes = highlightedPathRef.current;+ const searchDimmed = searchDimmedRef.current;+ const communityDimmed = communityDimmedRef.current;++ // Fast path: nothing active — return data unchanged, zero allocation+ if (!selected && pathNodes.size === 0 && !searchDimmed && !communityDimmed) {+ return data;+ }++ if (searchDimmed?.has(node)) {+ return { ...data, color: dimColor(data.color, 0.12), size: (data.size || 6) * 0.5, zIndex: 0 };+ }++ if (communityDimmed?.has(node)) {+ return { ...data, color: dimColor(data.color, 0.1), size: (data.size || 6) * 0.5, zIndex: 0 };+ }++ if (pathNodes.size > 0) {+ if (pathNodes.has(node)) {+ return { ...data, zIndex: 2, highlighted: true };+ }+ return { ...data, color: dimColor(data.color, 0.15), size: (data.size || 6) * 0.5, zIndex: 0 };+ }++ if (selected) {+ const graph = graphRef.current;+ if (graph) {+ if (node === selected) {+ return { ...data, size: (data.size || 6) * 1.8, zIndex: 2, highlighted: true };+ }+ if (graph.hasEdge(node, selected) || graph.hasEdge(selected, node)) {+ return { ...data, size: (data.size || 6) * 1.3, zIndex: 1 };+ }+ return { ...data, color: dimColor(data.color, 0.25), size: (data.size || 6) * 0.6, zIndex: 0 };+ }+ }++ return data;+ },++ // --- edgeReducer: interaction state only ---+ // Edge visibility by type is pre-set on the graph. No idle dimming.+ edgeReducer: (edge, data) => {+ if (data.hidden) return data;++ const selected = selectedRef.current;+ const pathEdges = highlightedEdgesRef.current;+ const pathNodes = highlightedPathRef.current;++ // Fast path: nothing active — zero allocation+ if (!selected && pathEdges.size === 0) return data;++ const graph = graphRef.current;++ if (pathEdges.size > 0) {+ if (pathEdges.has(edge)) {+ return { ...data, color: "#f59e0b", size: Math.max(3, (data.size || 1) * 3), zIndex: 2 };+ }+ if (pathNodes.size > 0 && graph) {+ const [source, target] = graph.extremities(edge);+ if (source && target && pathNodes.has(source) && pathNodes.has(target)) {+ return data;+ }+ }+ return { ...data, color: dimColor(data.color, 0.08), size: 0.2, zIndex: 0 };+ }++ if (selected && graph) {+ const [source, target] = graph.extremities(edge);+ const isConnected = source === selected || target === selected;+ if (isConnected) {+ return { ...data, color: brightenColor(data.color, 1.5), size: Math.max(3, (data.size || 1) * 4), zIndex: 2 };+ }+ return { ...data, color: dimColor(data.color, 0.1), size: 0.3, zIndex: 0 };+ }++ return data;+ },+ });++ sigmaInstance = sigma;+ sigmaRef.current = sigma;+ setSigmaReady(sigma);+ })();++ return () => {+ cancelled = true;+ if (sigmaInstance) {+ sigmaInstance.kill();+ sigmaInstance = null;+ }+ sigmaRef.current = null;+ setSigmaReady(null);+ };+ }, [options.container]);++ // Update graph when it changes+ useEffect(() => {+ const sigma = sigmaRef.current;+ if (!sigma || !options.graph) return;+ graphRef.current = options.graph;+ sigma.setGraph(options.graph);+ sigma.getCamera().animatedReset({ duration: 500 });+ }, [options.graph]);++ const focusNode = useCallback((nodeId: string) => {+ const sigma = sigmaRef.current;+ const graph = graphRef.current;+ if (!sigma || !graph || !graph.hasNode(nodeId)) return;+ const attrs = graph.getNodeAttributes(nodeId);+ sigma.getCamera().animate(+ { x: attrs.x, y: attrs.y, ratio: 0.15 },+ { duration: 400 },+ );+ }, []);++ const fitView = useCallback(() => {+ sigmaRef.current?.getCamera().animatedReset({ duration: 300 });+ }, []);++ const zoomIn = useCallback(() => {+ sigmaRef.current?.getCamera().animatedZoom({ duration: 200 });+ }, []);++ const zoomOut = useCallback(() => {+ sigmaRef.current?.getCamera().animatedUnzoom({ duration: 200 });+ }, []);++ return {+ sigma: sigmaReady,+ focusNode,+ fitView,+ zoomIn,+ zoomOut,+ };+}diff --git a/packages/ui/src/graph/use-elk-layout.ts b/packages/ui/src/graph/use-elk-layout.tsdeleted file mode 100644index f325af983..000000000--- a/packages/ui/src/graph/use-elk-layout.ts+++ /dev/null@@ -1,130 +0,0 @@-"use client";--import { useState, useEffect, useRef } from "react";-import type { Node, Edge } from "@xyflow/react";-import type {- GraphNode as GraphNodeResponse,- GraphLink as GraphEdgeResponse,- ModuleNode as ModuleNodeResponse,- ModuleEdge as ModuleEdgeResponse,-} from "@repowise-dev/types/graph";-import { layoutFileGraph, layoutModuleGraph } from "./elk-layout";--interface ElkLayoutResult {- nodes: Node[];- edges: Edge[];- isLayouting: boolean;-}--/** Compute ELK layout for a file-level graph (ego, architecture, full, dead, hot). */-export function useFileElkLayout(- graphNodes: GraphNodeResponse[] | undefined,- graphEdges: GraphEdgeResponse[] | undefined,-): ElkLayoutResult {- const [nodes, setNodes] = useState<Node[]>([]);- const [edges, setEdges] = useState<Edge[]>([]);- const [isLayouting, setIsLayouting] = useState(false);- const cacheKey = useRef("");-- useEffect(() => {- if (!graphNodes || !graphEdges || graphNodes.length === 0) {- setNodes([]);- setEdges([]);- cacheKey.current = "";- return;- }-- const key = `${graphNodes.length}:${graphEdges.length}:${graphNodes[0]?.node_id}`;- if (key === cacheKey.current) return;- cacheKey.current = key;-- setIsLayouting(true);- layoutFileGraph(graphNodes, graphEdges)- .then(({ nodes: n, edges: e }) => {- setNodes(n);- setEdges(e);- })- .catch(() => {- const cols = Math.ceil(Math.sqrt(graphNodes.length));- setNodes(- graphNodes.map((node, i) => ({- id: node.node_id,- type: "fileNode",- position: { x: (i % cols) * 200, y: Math.floor(i / cols) * 80 },- data: {- label: node.node_id.split("/").pop() ?? node.node_id,- fullPath: node.node_id,- language: node.language,- symbolCount: node.symbol_count,- pagerank: node.pagerank,- betweenness: node.betweenness,- communityId: node.community_id,- isTest: node.is_test,- isEntryPoint: node.is_entry_point,- hasDoc: node.has_doc,- ...("confidence_group" in node && { confidenceGroup: (node as Record<string, unknown>).confidence_group }),- ...("commit_count" in node && { commitCount: (node as Record<string, unknown>).commit_count }),- },- })),- );- setEdges([]);- })- .finally(() => setIsLayouting(false));- }, [graphNodes, graphEdges]);-- return { nodes, edges, isLayouting };-}--/** Compute ELK layout for a module-level graph. Supports mixed modules + files via fileEntries. */-export function useModuleElkLayout(- moduleNodes: ModuleNodeResponse[] | undefined,- moduleEdges: ModuleEdgeResponse[] | undefined,- fileEntries?: Map<string, GraphNodeResponse>,-): ElkLayoutResult {- const [nodes, setNodes] = useState<Node[]>([]);- const [edges, setEdges] = useState<Edge[]>([]);- const [isLayouting, setIsLayouting] = useState(false);- const cacheKey = useRef("");-- useEffect(() => {- if (!moduleNodes || !moduleEdges || moduleNodes.length === 0) {- setNodes([]);- setEdges([]);- cacheKey.current = "";- return;- }-- const key = `mod:${moduleNodes.length}:${moduleEdges.length}:${moduleNodes[0]?.module_id}`;- if (key === cacheKey.current) return;- cacheKey.current = key;-- setIsLayouting(true);- layoutModuleGraph(moduleNodes, moduleEdges, fileEntries)- .then(({ nodes: n, edges: e }) => {- setNodes(n);- setEdges(e);- })- .catch(() => {- const cols = Math.ceil(Math.sqrt(moduleNodes.length));- setNodes(- moduleNodes.map((m, i) => ({- id: m.module_id,- type: "moduleGroup",- position: { x: (i % cols) * 240, y: Math.floor(i / cols) * 100 },- data: {- label: m.module_id.split("/").pop() ?? m.module_id,- fullPath: m.module_id,- fileCount: m.file_count,- symbolCount: m.symbol_count,- avgPagerank: m.avg_pagerank,- docCoveragePct: m.doc_coverage_pct,- },- })),- );- setEdges([]);- })- .finally(() => setIsLayouting(false));- }, [moduleNodes, moduleEdges, fileEntries]);-- return { nodes, edges, isLayouting };-}diff --git a/packages/ui/src/graph/use-expanded-modules.ts b/packages/ui/src/graph/use-expanded-modules.tsnew file mode 100644index 000000000..59bb46c70--- /dev/null+++ b/packages/ui/src/graph/use-expanded-modules.ts@@ -0,0 +1,26 @@+"use client";++import { useState, useCallback } from "react";++export function useExpandedModules() {+ const [expandedModules, setExpandedModules] = useState<Set<string>>(new Set());++ const toggleModule = useCallback((moduleId: string) => {+ setExpandedModules((prev) => {+ const next = new Set(prev);+ if (next.has(moduleId)) next.delete(moduleId);+ else next.add(moduleId);+ return next;+ });+ }, []);++ const collapseAll = useCallback(() => {+ setExpandedModules(new Set());+ }, []);++ const expandAll = useCallback((moduleIds: string[]) => {+ setExpandedModules(new Set(moduleIds));+ }, []);++ return { expandedModules, toggleModule, collapseAll, expandAll };+}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex b884c68d4..de704211d 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -1,8 +1,8 @@/**- * @repowise-dev/ui — shared visualization components.+ * @repowise-dev/ui — shared visualization components.** Consumers should import via subpath (`@repowise-dev/ui/graph`,- * `@repowise-dev/ui/chat`, etc.) rather than the barrel below — the barrel+ * `@repowise-dev/ui/chat`, etc.) rather than the barrel below — the barrel* exists so the package resolves cleanly in IDEs and tooling that probes* the root entry point.*/diff --git a/packages/ui/src/lib/confidence.ts b/packages/ui/src/lib/confidence.tsindex 4dddd7a97..0df325de0 100644--- a/packages/ui/src/lib/confidence.ts+++ b/packages/ui/src/lib/confidence.ts@@ -4,7 +4,8 @@* Freshness: "fresh" | "stale" | "outdated"*/-export type FreshnessStatus = "fresh" | "stale" | "outdated";+import type { FreshnessStatus } from "@repowise-dev/types/docs";+export type { FreshnessStatus };export function scoreToStatus(score: number): FreshnessStatus {if (score >= 0.8) return "fresh";@@ -20,6 +21,7 @@ export function statusColor(status: FreshnessStatus): string {case "stale":return "var(--color-confidence-stale)";case "outdated":+ default:return "var(--color-confidence-outdated)";}}@@ -32,6 +34,7 @@ export function statusTextClass(status: FreshnessStatus): string {case "stale":return "text-yellow-500";case "outdated":+ default:return "text-red-500";}}@@ -44,6 +47,7 @@ export function statusBadgeClasses(status: FreshnessStatus): string {case "stale":return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";case "outdated":+ default:return "bg-red-500/10 text-red-500 border-red-500/20";}}@@ -56,6 +60,7 @@ export function statusLabel(status: FreshnessStatus): string {case "stale":return "Stale";case "outdated":+ default:return "Outdated";}}diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.tsnew file mode 100644index 000000000..aaac13f7c--- /dev/null+++ b/packages/ui/src/lib/page-types.ts@@ -0,0 +1,41 @@+import type { ComponentType } from "react";+import {+ Globe,+ LayoutGrid,+ FolderOpen,+ Sparkles,+ FileText,+ FileCode,+ RefreshCw,+ ArrowLeftRight,+ Server,+ GitCommit,+} from "lucide-react";++export interface PageTypeConfig {+ label: string;+ icon: ComponentType<{ className?: string }>;+}++export const PAGE_TYPE_CONFIG: Record<string, PageTypeConfig> = {+ repo_overview: { label: "Overview", icon: Globe },+ architecture_diagram: { label: "Architecture", icon: LayoutGrid },+ module_page: { label: "Module", icon: FolderOpen },+ symbol_spotlight: { label: "Symbol", icon: Sparkles },+ file_page: { label: "File", icon: FileText },+ api_contract: { label: "API Contract", icon: FileCode },+ scc_page: { label: "SCC", icon: RefreshCw },+ cross_package: { label: "Cross-Package", icon: ArrowLeftRight },+ infra_page: { label: "Infra", icon: Server },+ diff_summary: { label: "Diff Summary", icon: GitCommit },+};++export const ALL_PAGE_TYPES = Object.keys(PAGE_TYPE_CONFIG);++export function getPageTypeIcon(pageType: string): ComponentType<{ className?: string }> {+ return PAGE_TYPE_CONFIG[pageType]?.icon ?? FileText;+}++export function getPageTypeLabel(pageType: string): string {+ return PAGE_TYPE_CONFIG[pageType]?.label ?? pageType.replace(/_/g, " ");+}diff --git a/packages/ui/src/shared/api-error.tsx b/packages/ui/src/shared/api-error.tsxindex 29f9bb1f3..20beccf38 100644--- a/packages/ui/src/shared/api-error.tsx+++ b/packages/ui/src/shared/api-error.tsx@@ -1,5 +1,5 @@import { AlertTriangle, RefreshCw } from "lucide-react";-import { Button } from "@repowise-dev/ui/ui/button";+import { Button } from "../ui/button";interface ApiErrorProps {title?: string;diff --git a/packages/ui/src/shared/breadcrumb.tsx b/packages/ui/src/shared/breadcrumb.tsxnew file mode 100644index 000000000..d346b7b0b--- /dev/null+++ b/packages/ui/src/shared/breadcrumb.tsx@@ -0,0 +1,50 @@+"use client";++import { ChevronRight } from "lucide-react";++export interface BreadcrumbSegment {+ label: string;+ href?: string;+}++interface BreadcrumbProps {+ segments: BreadcrumbSegment[];+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+}++export function Breadcrumb({ segments, LinkComponent = "a" }: BreadcrumbProps) {+ if (segments.length === 0) return null;++ const Link = LinkComponent;++ return (+ <nav aria-label="Breadcrumb" className="flex items-center gap-1 text-sm">+ {segments.map((segment, i) => {+ const isLast = i === segments.length - 1;+ return (+ <span key={i} className="flex items-center gap-1">+ {i > 0 && (+ <ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />+ )}+ {isLast || !segment.href ? (+ <span className="text-[var(--color-text-primary)] font-medium truncate">+ {segment.label}+ </span>+ ) : (+ <Link+ href={segment.href}+ className="text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors truncate"+ >+ {segment.label}+ </Link>+ )}+ </span>+ );+ })}+ </nav>+ );+}diff --git a/packages/ui/src/shared/empty-state.tsx b/packages/ui/src/shared/empty-state.tsxindex e7e86d67b..8607594f6 100644--- a/packages/ui/src/shared/empty-state.tsx+++ b/packages/ui/src/shared/empty-state.tsx@@ -1,6 +1,6 @@import * as React from "react";import { cn } from "../lib/cn";-import { Button } from "@repowise-dev/ui/ui/button";+import { Button } from "../ui/button";interface EmptyStateProps {icon?: React.ReactNode;diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex 77c17aff0..5a9cdbac3 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -1,3 +1,5 @@export * from "./api-error.js";+export * from "./breadcrumb.js";export * from "./empty-state.js";export * from "./stat-card.js";+export { RowActions, type RowAction } from "./row-actions";diff --git a/packages/ui/src/shared/row-actions.tsx b/packages/ui/src/shared/row-actions.tsxnew file mode 100644index 000000000..dd7a9d8c5--- /dev/null+++ b/packages/ui/src/shared/row-actions.tsx@@ -0,0 +1,31 @@+import * as React from "react";+import { cn } from "../lib/cn";++export interface RowAction {+ icon: React.ComponentType<{ className?: string }>;+ label: string;+ href: string;+}++interface RowActionsProps {+ actions: RowAction[];+ className?: string;+}++export function RowActions({ actions, className }: RowActionsProps) {+ return (+ <div className={cn("flex items-center gap-1", className)}>+ {actions.map((action) => (+ <a+ key={action.label}+ href={action.href}+ title={action.label}+ className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ <action.icon className="h-3 w-3" />+ <span className="hidden lg:inline">{action.label}</span>+ </a>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/shared/stat-card.tsx b/packages/ui/src/shared/stat-card.tsxindex 417e95a68..c0f93bb9e 100644--- a/packages/ui/src/shared/stat-card.tsx+++ b/packages/ui/src/shared/stat-card.tsx@@ -1,6 +1,6 @@import * as React from "react";import { cn } from "../lib/cn";-import { Card, CardContent } from "@repowise-dev/ui/ui/card";+import { Card, CardContent } from "../ui/card";interface StatCardProps {label: string;@@ -19,9 +19,10 @@ export function StatCard({trend,icon,className,+ href,}: StatCardProps) {- return (- <Card className={cn("transition-colors hover:border-[var(--color-border-hover)]", className)}>+ const card = (+ <Card className={cn("transition-colors hover:border-[var(--color-border-hover)]", href && "cursor-pointer", className)}><CardContent className="p-4"><div className="flex items-start justify-between"><div className="space-y-1">@@ -58,4 +59,14 @@ export function StatCard({</CardContent></Card>);++ if (href) {+ return (+ <a href={href} className="block no-underline">+ {card}+ </a>+ );+ }++ return card;}diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsxindex a1349249e..61ccd7d4c 100644--- a/packages/ui/src/symbols/symbol-table.tsx+++ b/packages/ui/src/symbols/symbol-table.tsx@@ -1,13 +1,14 @@"use client";import { useState, useCallback, useMemo, type ReactNode } from "react";-import { ChevronUp, ChevronDown, ChevronsUpDown, TrendingUp } from "lucide-react";+import { ChevronUp, ChevronDown, ChevronsUpDown, TrendingUp, GitBranch, BookOpen } from "lucide-react";import { Input } from "../ui/input";import { Button } from "../ui/button";import { Badge } from "../ui/badge";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";import { Skeleton } from "../ui/skeleton";import { EmptyState } from "../shared/empty-state";+import { RowActions } from "../shared/row-actions";import { truncatePath } from "../lib/format";import { cn } from "../lib/cn";import type { CodeSymbol } from "@repowise-dev/types/symbols";@@ -35,6 +36,8 @@ export interface SymbolTableProps {onLanguageChange: (v: string) => void;onLoadMore: () => void;onSelect: (sym: CodeSymbol) => void;+ repoId?: string;+ linkPrefix?: string;/** Drawer slot for the selected row. Wrapper passes a `<SymbolDrawer>` mounted with its own data. */drawer?: ReactNode;}@@ -75,8 +78,11 @@ export function SymbolTable({onLanguageChange,onLoadMore,onSelect,+ repoId,+ linkPrefix,drawer,}: SymbolTableProps) {+ const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);const [sortCol, setSortCol] = useState<SortCol>("importance");const [sortDir, setSortDir] = useState<SortDir>("desc");@@ -246,6 +252,16 @@ export function SymbolTable({{sym.complexity_estimate}</span></td>+ {prefix && (+ <td className="px-2 py-2.5" onClick={(e) => e.stopPropagation()}>+ <RowActions+ actions={[+ { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(sym.file_path)}` },+ { icon: BookOpen, label: "Docs", href: `${prefix}/docs?file=${encodeURIComponent(sym.file_path)}` },+ ]}+ />+ </td>+ )}</tr>))}</tbody>diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsxindex 6fbdf49ad..38f6597c2 100644--- a/packages/ui/src/workspace/co-change-table.tsx+++ b/packages/ui/src/workspace/co-change-table.tsx@@ -68,7 +68,7 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {)}{!compact && (<td className="py-2 text-xs text-[var(--color-text-tertiary)]" title={cc.last_date ? new Date(cc.last_date).toLocaleString() : undefined}>- {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}+ {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}</td>)}</tr>diff --git a/packages/ui/src/workspace/index.ts b/packages/ui/src/workspace/index.tsindex e9703c10c..1766461b5 100644--- a/packages/ui/src/workspace/index.ts+++ b/packages/ui/src/workspace/index.ts@@ -5,3 +5,5 @@ export * from "./cross-repo-summary.js";export * from "./package-deps-table.js";export * from "./repo-card.js";export * from "./repo-card-compact.js";+export * from "./workspace-graph.js";+export * from "./workspace-graph-node.js";diff --git a/packages/ui/src/workspace/repo-card.tsx b/packages/ui/src/workspace/repo-card.tsxindex 9c2bc0f5b..4f39844c9 100644--- a/packages/ui/src/workspace/repo-card.tsx+++ b/packages/ui/src/workspace/repo-card.tsx@@ -6,6 +6,7 @@ import type { GitSummary } from "@repowise-dev/types/git";interface RepoCardProps {repoId: string;+ linkPrefix?: string;alias: string;name: string;path: string;@@ -16,6 +17,7 @@ interface RepoCardProps {export function RepoCard({repoId,+ linkPrefix,alias,name,path,@@ -23,6 +25,7 @@ export function RepoCard({stats,gitSummary,}: RepoCardProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;const card = (<Card className={`group transition-colors ${repoId ? "hover:border-[var(--color-accent-primary)]/30 cursor-pointer" : "opacity-60"}`}><CardContent className="p-4">@@ -38,7 +41,7 @@ export function RepoCard({</Badge>)}</div>- <p className="text-xs text-[var(--color-text-tertiary)] font-mono mt-0.5 truncate" title={`${alias} · ${path}`}>+ <p className="text-xs text-[var(--color-text-tertiary)] font-mono mt-0.5 truncate" title={`${alias} · ${path}`}>{alias} · {path}</p></div>@@ -51,19 +54,19 @@ export function RepoCard({<div className="flex items-center gap-1.5"><FileText className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="text-xs text-[var(--color-text-secondary)]">- {stats?.file_count ?? "—"} files+ {stats?.file_count ?? "—"} files</span></div><div className="flex items-center gap-1.5"><BarChart3 className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="text-xs text-[var(--color-text-secondary)]">- {stats ? `${Math.round(stats.doc_coverage_pct)}% docs` : "—"}+ {stats ? `${Math.round(stats.doc_coverage_pct)}% docs` : "—"}</span></div><div className="flex items-center gap-1.5"><Flame className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="text-xs text-[var(--color-text-secondary)]">- {gitSummary?.hotspot_count ?? "—"} hotspots+ {gitSummary?.hotspot_count ?? "—"} hotspots</span></div></div>@@ -74,7 +77,7 @@ export function RepoCard({if (!repoId) return card;return (- <a href={`/repos/${repoId}/overview`}>+ <a href={`${prefix}/overview`}>{card}</a>);diff --git a/packages/ui/src/workspace/workspace-graph-node.tsx b/packages/ui/src/workspace/workspace-graph-node.tsxnew file mode 100644index 000000000..ba485d31f--- /dev/null+++ b/packages/ui/src/workspace/workspace-graph-node.tsx@@ -0,0 +1,125 @@+"use client";++import { memo } from "react";+import { Handle, Position, type NodeProps } from "@xyflow/react";+import { FileText, BarChart3 } from "lucide-react";+import { languageColor } from "../lib/confidence";++export interface WorkspaceGraphNodeData {+ repoId: string;+ name: string;+ fileCount: number;+ coveragePct: number;+ healthScore: number;+ topLanguage: string;+}++function healthColor(score: number): string {+ if (score >= 70) return "#22c55e";+ if (score >= 40) return "#f59e0b";+ return "#ef4444";+}++function HealthRing({ score, size = 36 }: { score: number; size?: number }) {+ const r = (size - 4) / 2;+ const circ = 2 * Math.PI * r;+ const offset = circ * (1 - score / 100);+ const color = healthColor(score);++ return (+ <svg width={size} height={size} className="shrink-0">+ <circle+ cx={size / 2}+ cy={size / 2}+ r={r}+ fill="none"+ stroke="rgba(255,255,255,0.1)"+ strokeWidth={3}+ />+ <circle+ cx={size / 2}+ cy={size / 2}+ r={r}+ fill="none"+ stroke={color}+ strokeWidth={3}+ strokeDasharray={circ}+ strokeDashoffset={offset}+ strokeLinecap="round"+ transform={`rotate(-90 ${size / 2} ${size / 2})`}+ />+ <text+ x={size / 2}+ y={size / 2}+ textAnchor="middle"+ dominantBaseline="central"+ fill={color}+ fontSize={10}+ fontWeight={700}+ >+ {score}+ </text>+ </svg>+ );+}++function WorkspaceGraphNodeInner({ data }: NodeProps) {+ const d = data as unknown as WorkspaceGraphNodeData;+ const langColor = languageColor(d.topLanguage);++ return (+ <div+ className="rounded-xl cursor-pointer transition-shadow duration-200 hover:shadow-xl"+ style={{+ width: 160,+ minHeight: 100,+ background: `linear-gradient(135deg, ${langColor}25 0%, rgba(30,41,59,0.95) 60%)`,+ border: `2px solid ${langColor}60`,+ boxShadow: `0 2px 12px rgba(0,0,0,0.3), 0 0 0 1px ${langColor}20`,+ padding: "10px 12px",+ }}+ >+ <Handle+ type="target"+ position={Position.Top}+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"+ />++ <div className="text-[12px] font-bold text-[var(--color-text-primary)] truncate text-center mb-2">+ {d.name}+ </div>++ <div className="flex items-center gap-2.5">+ <HealthRing score={d.healthScore} />+ <div className="flex-1 min-w-0 space-y-1">+ <div className="flex items-center gap-1 text-[10px] text-[var(--color-text-secondary)]">+ <FileText className="w-3 h-3 shrink-0" />+ <span>{d.fileCount} files</span>+ </div>+ <div className="flex items-center gap-1 text-[10px] text-[var(--color-text-secondary)]">+ <BarChart3 className="w-3 h-3 shrink-0" />+ <span>{Math.round(d.coveragePct)}% cov</span>+ </div>+ </div>+ </div>++ <div+ className="mt-2 text-[9px] font-medium px-1.5 py-0.5 rounded-full text-center"+ style={{+ background: `${langColor}30`,+ color: langColor,+ }}+ >+ {d.topLanguage}+ </div>++ <Handle+ type="source"+ position={Position.Bottom}+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"+ />+ </div>+ );+}++export const WorkspaceGraphNode = memo(WorkspaceGraphNodeInner);diff --git a/packages/ui/src/workspace/workspace-graph.tsx b/packages/ui/src/workspace/workspace-graph.tsxnew file mode 100644index 000000000..710658001--- /dev/null+++ b/packages/ui/src/workspace/workspace-graph.tsx@@ -0,0 +1,156 @@+"use client";++import { useMemo, useCallback } from "react";+import {+ ReactFlow,+ Controls,+ Background,+ BackgroundVariant,+ ReactFlowProvider,+ type Node,+ type Edge,+} from "@xyflow/react";+import "@xyflow/react/dist/style.css";+import {+ forceSimulation,+ forceManyBody,+ forceLink,+ forceCollide,+ forceCenter,+} from "d3-force";+import { WorkspaceGraphNode, type WorkspaceGraphNodeData } from "./workspace-graph-node";++export interface WorkspaceGraphData {+ nodes: Array<{+ repo_id: string;+ name: string;+ file_count: number;+ coverage_pct: number;+ health_score: number;+ top_language: string;+ }>;+ edges: Array<{+ source: string;+ target: string;+ type: "contract" | "co_change";+ strength: number;+ label: string | null;+ }>;+}++export interface WorkspaceGraphProps {+ data: WorkspaceGraphData;+ onRepoClick?: (repoId: string) => void;+}++const nodeTypes = { workspaceRepo: WorkspaceGraphNode };++interface SimNode {+ id: string;+ x?: number;+ y?: number;+ vx?: number;+ vy?: number;+}++function computeLayout(data: WorkspaceGraphData): { nodes: Node[]; edges: Edge[] } {+ if (data.nodes.length === 0) return { nodes: [], edges: [] };++ const nodeSet = new Set(data.nodes.map((n) => n.repo_id));+ const simNodes: SimNode[] = data.nodes.map((n) => ({ id: n.repo_id }));+ const simLinks = data.edges+ .filter((e) => nodeSet.has(e.source) && nodeSet.has(e.target))+ .map((e) => ({ source: e.source, target: e.target }));++ /* eslint-disable @typescript-eslint/no-explicit-any */+ const sim = forceSimulation(simNodes as any[])+ .force("charge", forceManyBody().strength(-400))+ .force(+ "link",+ forceLink(simLinks as any[])+ .id((d: any) => d.id)+ .distance(200),+ )+ .force("collide", forceCollide(100))+ .force("center", forceCenter(0, 0))+ .stop();+ /* eslint-enable @typescript-eslint/no-explicit-any */++ for (let i = 0; i < 100; i++) sim.tick();++ const rfNodes: Node[] = simNodes.map((sn) => {+ const apiNode = data.nodes.find((n) => n.repo_id === sn.id)!;+ return {+ id: sn.id,+ type: "workspaceRepo",+ position: { x: sn.x ?? 0, y: sn.y ?? 0 },+ data: {+ repoId: apiNode.repo_id,+ name: apiNode.name,+ fileCount: apiNode.file_count,+ coveragePct: apiNode.coverage_pct,+ healthScore: apiNode.health_score,+ topLanguage: apiNode.top_language,+ } satisfies WorkspaceGraphNodeData,+ };+ });++ const rfEdges: Edge[] = data.edges+ .filter((e) => nodeSet.has(e.source) && nodeSet.has(e.target))+ .map((e, i) => ({+ id: `ws-edge-${i}`,+ source: e.source,+ target: e.target,+ label: e.label ?? undefined,+ style: {+ strokeWidth: 1 + e.strength * 4,+ stroke: e.type === "contract" ? "#3b82f6" : "#8b5cf6",+ strokeDasharray: e.type === "co_change" ? "6 3" : undefined,+ },+ labelStyle: { fontSize: 10, fill: "var(--color-text-tertiary)" },+ }));++ return { nodes: rfNodes, edges: rfEdges };+}++function WorkspaceGraphInner({ data, onRepoClick }: WorkspaceGraphProps) {+ const { nodes, edges } = useMemo(() => computeLayout(data), [data]);++ const handleNodeClick = useCallback(+ (_: React.MouseEvent, node: Node) => {+ const d = node.data as unknown as WorkspaceGraphNodeData;+ onRepoClick?.(d.repoId);+ },+ [onRepoClick],+ );++ return (+ <ReactFlow+ nodes={nodes}+ edges={edges}+ nodeTypes={nodeTypes}+ onNodeClick={handleNodeClick}+ fitView+ fitViewOptions={{ padding: 0.3, maxZoom: 1.2 }}+ minZoom={0.3}+ maxZoom={2}+ proOptions={{ hideAttribution: true }}+ nodesDraggable+ className="!bg-transparent"+ >+ <Background variant={BackgroundVariant.Dots} gap={20} size={0.5} color="rgba(255,255,255,0.03)" />+ <Controls+ showInteractive={false}+ className="!border-[var(--color-border-default)] !bg-[var(--color-bg-elevated)] !shadow-lg [&>button]:!border-[var(--color-border-default)] [&>button]:!bg-[var(--color-bg-elevated)] [&>button]:!text-[var(--color-text-secondary)] [&>button:hover]:!bg-[var(--color-bg-overlay)] [&>button:hover]:!text-[var(--color-text-primary)]"+ />+ </ReactFlow>+ );+}++export function WorkspaceGraph(props: WorkspaceGraphProps) {+ return (+ <ReactFlowProvider>+ <WorkspaceGraphInner {...props} />+ </ReactFlowProvider>+ );+}diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex 8c9b205d4..ab7cde6b3 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -21,6 +21,9 @@ export default defineConfig({"@repowise-dev/types/dead-code": path.resolve(__dirname, "../types/src/dead-code.ts"),"@repowise-dev/types/symbols": path.resolve(__dirname, "../types/src/symbols.ts"),"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),+ "@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),+ "@repowise-dev/types/jobs": path.resolve(__dirname, "../types/src/jobs.ts"),+ "@repowise-dev/types/settings": path.resolve(__dirname, "../types/src/settings.ts"),},},});diff --git a/packages/web/next.config.ts b/packages/web/next.config.tsindex e40d3305c..21530cd0c 100644--- a/packages/web/next.config.ts+++ b/packages/web/next.config.ts@@ -4,7 +4,7 @@ const nextConfig: NextConfig = {output: "standalone",transpilePackages: ["@repowise-dev/ui", "@repowise-dev/types"],experimental: {- optimizePackageImports: ["lucide-react", "recharts", "d3"],+ optimizePackageImports: ["lucide-react", "recharts"],},images: {unoptimized: true,diff --git a/packages/web/package.json b/packages/web/package.jsonindex d32ae53fb..2f6b529c3 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -13,35 +13,11 @@"dependencies": {"@repowise-dev/types": "*","@repowise-dev/ui": "*",- "@radix-ui/react-accordion": "^1.2.0",- "@radix-ui/react-dialog": "^1.1.0",- "@radix-ui/react-dropdown-menu": "^2.1.0",- "@radix-ui/react-label": "^2.1.8",- "@radix-ui/react-popover": "^1.1.0",- "@radix-ui/react-progress": "^1.1.8",- "@radix-ui/react-scroll-area": "^1.2.0",- "@radix-ui/react-select": "^2.1.0",- "@radix-ui/react-separator": "^1.1.0",- "@radix-ui/react-slider": "^1.3.6",- "@radix-ui/react-slot": "^1.1.0",- "@radix-ui/react-switch": "^1.2.6",- "@radix-ui/react-tabs": "^1.1.0",- "@radix-ui/react-toggle": "^1.1.0",- "@radix-ui/react-toggle-group": "^1.1.0",- "@radix-ui/react-tooltip": "^1.1.0",- "@xyflow/react": "^12.10.2",- "class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.0.0",- "d3": "^7.9.0",- "d3-force": "^3.0.0",- "d3-hierarchy": "^3.1.2",- "elkjs": "^0.11.1","framer-motion": "^11.11.0",- "fuse.js": "^7.0.0","geist": "^1.3.0","lucide-react": "^0.460.0",- "mermaid": "^11.4.0","next": "~15.5.15","next-mdx-remote": "^6.0.0","nuqs": "^2.2.0",diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsxindex 57ee1f0ed..21866ca9a 100644--- a/packages/web/src/app/layout.tsx+++ b/packages/web/src/app/layout.tsx@@ -15,7 +15,7 @@ import "@/styles/globals.css";export const metadata: Metadata = {title: {default: "repowise",- template: "%s — repowise",+ template: "%s — repowise",},description: "Open-source codebase documentation engine",};@@ -37,7 +37,7 @@ export default async function RootLayout({if (reposResult.status === "fulfilled") repos = reposResult.value;if (wsResult.status === "fulfilled") workspace = wsResult.value;} catch {- // API not available — show empty sidebar+ // API not available — show empty sidebar}return (diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsxindex f8071191f..9bf4105da 100644--- a/packages/web/src/app/page.tsx+++ b/packages/web/src/app/page.tsx@@ -38,12 +38,12 @@ export default async function DashboardPage() {const jobList = jobs.status === "fulfilled" ? jobs.value : [];const workspace = ws.status === "fulfilled" ? ws.value : null;- // Workspace mode → workspace dashboard+ // Workspace mode → workspace dashboardif (workspace?.is_workspace) {redirect("/workspace");}- // Single repo → go straight to its overview+ // Single repo → go straight to its overviewif (repoList.length === 1) {redirect(`/repos/${repoList[0].id}/overview`);}@@ -97,7 +97,7 @@ export default async function DashboardPage() {<StatCardlabel="Fresh Pages"value={formatNumber(freshPages)}- description="Confidence ≥ 80%"+ description="Confidence ≥ 80%"icon={<CheckCircle2 className="h-4 w-4 text-green-500" />}/><StatCard@@ -108,7 +108,7 @@ export default async function DashboardPage() {/><StatCardlabel="Dead Code"- value={deadCode > 0 ? formatNumber(deadCode) : "—"}+ value={deadCode > 0 ? formatNumber(deadCode) : "—"}description={deadCode > 0 ? "Unused exports" : "Analyze to detect"}icon={<Skull className="h-4 w-4 text-[var(--color-text-tertiary)]" />}/>@@ -230,7 +230,7 @@ export default async function DashboardPage() {</Badge></div><p className="text-xs text-[var(--color-text-tertiary)] mt-0.5">- {job.model_name} · {formatRelativeTime(job.updated_at)}+ {job.model_name} · {formatRelativeTime(job.updated_at)}</p></div></Link>diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsxindex 53673c22c..6d381325b 100644--- a/packages/web/src/app/repos/[id]/costs/page.tsx+++ b/packages/web/src/app/repos/[id]/costs/page.tsx@@ -108,7 +108,7 @@ export default function CostsPage() {))}</div>- {/* Chart — only when grouping by day */}+ {/* Chart — only when grouping by day */}{by === "day" && (<Card><CardHeader className="pb-2">@@ -131,7 +131,7 @@ export default function CostsPage() {interval="preserveStartEnd"minTickGap={24}tickFormatter={(v: string) => {- // ISO date "YYYY-MM-DD" → "M/D"+ // ISO date "YYYY-MM-DD" → "M/D"const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);return m ? `${Number(m[2])}/${Number(m[3])}` : v;}}diff --git a/packages/web/src/app/repos/[id]/coverage/loading.tsx b/packages/web/src/app/repos/[id]/coverage/loading.tsxindex ca45f6c5e..0f5bde30c 100644--- a/packages/web/src/app/repos/[id]/coverage/loading.tsx+++ b/packages/web/src/app/repos/[id]/coverage/loading.tsx@@ -1,23 +1,3 @@-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";--export default function CoverageLoading() {- return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- <div>- <Skeleton className="h-7 w-36" />- <Skeleton className="h-4 w-52 mt-1.5" />- </div>- <div className="grid grid-cols-1 gap-6 md:grid-cols-3">- <div className="flex items-center justify-center">- <Skeleton className="h-44 w-44 rounded-full" />- </div>- <div className="md:col-span-2 grid grid-cols-3 gap-3 content-center">- {Array.from({ length: 3 }).map((_, i) => (- <Skeleton key={i} className="h-20 rounded-lg" />- ))}- </div>- </div>- <Skeleton className="h-[350px] rounded-lg" />- </div>- );+export default function CoverageRedirectLoading() {+ return null;}diff --git a/packages/web/src/app/repos/[id]/coverage/page.tsx b/packages/web/src/app/repos/[id]/coverage/page.tsxindex 7422e3d84..567b21981 100644--- a/packages/web/src/app/repos/[id]/coverage/page.tsx+++ b/packages/web/src/app/repos/[id]/coverage/page.tsx@@ -1,100 +1,10 @@-import type { Metadata } from "next";-import { FileCheck } from "lucide-react";-import { CoverageDonut } from "@repowise-dev/ui/coverage/coverage-donut";-import { FreshnessTableWithRegenerate } from "@/components/coverage/freshness-table-wrapper";-import { StatCard } from "@repowise-dev/ui/shared/stat-card";-import { listPages } from "@/lib/api/pages";-import { formatNumber } from "@repowise-dev/ui/lib/format";+import { redirect } from "next/navigation";-export const metadata: Metadata = { title: "Coverage" };--export default async function CoveragePage({+export default async function CoverageRedirect({params,}: {params: Promise<{ id: string }>;}) {const { id } = await params;-- let pages: Awaited<ReturnType<typeof listPages>> = [];-- try {- pages = await listPages(id, { limit: 500 });- } catch {- // API unavailable- }-- const total = pages.length;-- const fresh = pages.filter((p) => p.freshness_status === "fresh").length;- const stale = pages.filter((p) => p.freshness_status === "stale").length;- const outdated = pages.filter((p) => p.freshness_status === "outdated").length;- const freshPct = pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0;-- return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- <div>- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">- <FileCheck className="h-5 w-5 text-[var(--color-accent-primary)]" />- Documentation Coverage- </h1>- <p className="text-sm text-[var(--color-text-secondary)]">- Freshness breakdown across {formatNumber(total)} wiki pages.- </p>- </div>-- <div className="flex flex-col gap-6 lg:flex-row lg:items-start">- {/* Donut */}- <div className="flex flex-col items-center gap-4 lg:w-56 shrink-0">- <CoverageDonut fresh={fresh} stale={stale} outdated={outdated} />- <p className="text-sm text-[var(--color-text-secondary)]">- {freshPct}% of pages are fresh- </p>- </div>-- {/* Stat cards */}- <div className="flex-1 grid grid-cols-1 gap-3 sm:grid-cols-3">- <StatCard- label="Fresh"- value={formatNumber(fresh)}- description={`${pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0}% of pages`}- />- <StatCard- label="Stale"- value={formatNumber(stale)}- description={`${pages.length > 0 ? Math.round((stale / pages.length) * 100) : 0}% of pages`}- />- <StatCard- label="Outdated"- value={formatNumber(outdated)}- description={`${pages.length > 0 ? Math.round((outdated / pages.length) * 100) : 0}% of pages`}- />- </div>- </div>-- {/* Freshness distribution bar */}- {pages.length > 0 && (- <div>- <p className="text-xs text-[var(--color-text-tertiary)] mb-1.5">Distribution</p>- <div className="h-3 rounded-full overflow-hidden flex">- <div className="bg-green-500" style={{ width: `${(fresh / pages.length) * 100}%` }} />- <div className="bg-yellow-500" style={{ width: `${(stale / pages.length) * 100}%` }} />- <div className="bg-red-500" style={{ width: `${(outdated / pages.length) * 100}%` }} />- </div>- <div className="flex gap-4 mt-1.5 text-xs text-[var(--color-text-tertiary)]">- <span className="flex items-center gap-1">- <span className="h-2 w-2 rounded-full bg-green-500" /> Fresh- </span>- <span className="flex items-center gap-1">- <span className="h-2 w-2 rounded-full bg-yellow-500" /> Stale- </span>- <span className="flex items-center gap-1">- <span className="h-2 w-2 rounded-full bg-red-500" /> Outdated- </span>- </div>- </div>- )}-- <FreshnessTableWithRegenerate pages={pages} />- </div>- );+ redirect(`/repos/${id}/docs/coverage`);}diff --git a/packages/web/src/app/repos/[id]/dead-code/page.tsx b/packages/web/src/app/repos/[id]/dead-code/page.tsxindex c936b3914..2bdc71093 100644--- a/packages/web/src/app/repos/[id]/dead-code/page.tsx+++ b/packages/web/src/app/repos/[id]/dead-code/page.tsx@@ -27,7 +27,7 @@ export default function DeadCodePage() {setAnalyzing(true);try {await analyzeDeadCode(id);- toast.success("Analysis started — results will appear shortly.");+ toast.success("Analysis started — results will appear shortly.");} catch (err) {toast.error(err instanceof Error ? `Couldn't start analysis: ${err.message}` : "Couldn't start analysis",@@ -56,7 +56,7 @@ export default function DeadCodePage() {onClick={handleAnalyze}disabled={analyzing}>- {analyzing ? "Starting…" : "Analyze"}+ {analyzing ? "Starting…" : "Analyze"}</Button></div></div>diff --git a/packages/web/src/app/repos/[id]/docs/coverage/loading.tsx b/packages/web/src/app/repos/[id]/docs/coverage/loading.tsxnew file mode 100644index 000000000..ca45f6c5e--- /dev/null+++ b/packages/web/src/app/repos/[id]/docs/coverage/loading.tsx@@ -0,0 +1,23 @@+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";++export default function CoverageLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">+ <div>+ <Skeleton className="h-7 w-36" />+ <Skeleton className="h-4 w-52 mt-1.5" />+ </div>+ <div className="grid grid-cols-1 gap-6 md:grid-cols-3">+ <div className="flex items-center justify-center">+ <Skeleton className="h-44 w-44 rounded-full" />+ </div>+ <div className="md:col-span-2 grid grid-cols-3 gap-3 content-center">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-lg" />+ ))}+ </div>+ </div>+ <Skeleton className="h-[350px] rounded-lg" />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx b/packages/web/src/app/repos/[id]/docs/coverage/page.tsxnew file mode 100644index 000000000..7422e3d84--- /dev/null+++ b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx@@ -0,0 +1,100 @@+import type { Metadata } from "next";+import { FileCheck } from "lucide-react";+import { CoverageDonut } from "@repowise-dev/ui/coverage/coverage-donut";+import { FreshnessTableWithRegenerate } from "@/components/coverage/freshness-table-wrapper";+import { StatCard } from "@repowise-dev/ui/shared/stat-card";+import { listPages } from "@/lib/api/pages";+import { formatNumber } from "@repowise-dev/ui/lib/format";++export const metadata: Metadata = { title: "Coverage" };++export default async function CoveragePage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;++ let pages: Awaited<ReturnType<typeof listPages>> = [];++ try {+ pages = await listPages(id, { limit: 500 });+ } catch {+ // API unavailable+ }++ const total = pages.length;++ const fresh = pages.filter((p) => p.freshness_status === "fresh").length;+ const stale = pages.filter((p) => p.freshness_status === "stale").length;+ const outdated = pages.filter((p) => p.freshness_status === "outdated").length;+ const freshPct = pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <FileCheck className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Documentation Coverage+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Freshness breakdown across {formatNumber(total)} wiki pages.+ </p>+ </div>++ <div className="flex flex-col gap-6 lg:flex-row lg:items-start">+ {/* Donut */}+ <div className="flex flex-col items-center gap-4 lg:w-56 shrink-0">+ <CoverageDonut fresh={fresh} stale={stale} outdated={outdated} />+ <p className="text-sm text-[var(--color-text-secondary)]">+ {freshPct}% of pages are fresh+ </p>+ </div>++ {/* Stat cards */}+ <div className="flex-1 grid grid-cols-1 gap-3 sm:grid-cols-3">+ <StatCard+ label="Fresh"+ value={formatNumber(fresh)}+ description={`${pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0}% of pages`}+ />+ <StatCard+ label="Stale"+ value={formatNumber(stale)}+ description={`${pages.length > 0 ? Math.round((stale / pages.length) * 100) : 0}% of pages`}+ />+ <StatCard+ label="Outdated"+ value={formatNumber(outdated)}+ description={`${pages.length > 0 ? Math.round((outdated / pages.length) * 100) : 0}% of pages`}+ />+ </div>+ </div>++ {/* Freshness distribution bar */}+ {pages.length > 0 && (+ <div>+ <p className="text-xs text-[var(--color-text-tertiary)] mb-1.5">Distribution</p>+ <div className="h-3 rounded-full overflow-hidden flex">+ <div className="bg-green-500" style={{ width: `${(fresh / pages.length) * 100}%` }} />+ <div className="bg-yellow-500" style={{ width: `${(stale / pages.length) * 100}%` }} />+ <div className="bg-red-500" style={{ width: `${(outdated / pages.length) * 100}%` }} />+ </div>+ <div className="flex gap-4 mt-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-green-500" /> Fresh+ </span>+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-yellow-500" /> Stale+ </span>+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-red-500" /> Outdated+ </span>+ </div>+ </div>+ )}++ <FreshnessTableWithRegenerate pages={pages} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/docs/layout.tsx b/packages/web/src/app/repos/[id]/docs/layout.tsxnew file mode 100644index 000000000..1cb0d4d9a--- /dev/null+++ b/packages/web/src/app/repos/[id]/docs/layout.tsx@@ -0,0 +1,50 @@+"use client";++import Link from "next/link";+import { usePathname, useParams } from "next/navigation";+import { BookOpen, BarChart3 } from "lucide-react";+import { cn } from "@/lib/utils/cn";++const tabs = [+ { label: "Explorer", segment: "", icon: BookOpen },+ { label: "Coverage", segment: "/coverage", icon: BarChart3 },+] as const;++export default function DocsLayout({ children }: { children: React.ReactNode }) {+ const pathname = usePathname();+ const { id } = useParams<{ id: string }>();+ const basePath = `/repos/${id}/docs`;++ return (+ <div className="flex flex-col h-full">+ <div className="shrink-0 border-b border-[var(--color-border-default)] px-4 sm:px-6">+ <nav className="flex gap-1 -mb-px" aria-label="Docs tabs">+ {tabs.map((tab) => {+ const href = `${basePath}${tab.segment}`;+ const isActive =+ tab.segment === ""+ ? pathname === basePath+ : pathname.startsWith(href);+ const Icon = tab.icon;+ return (+ <Link+ key={tab.segment}+ href={href}+ className={cn(+ "inline-flex items-center gap-1.5 px-3 py-2.5 text-sm font-medium border-b-2 transition-colors",+ isActive+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"+ : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:border-[var(--color-border-default)]",+ )}+ >+ <Icon className="h-4 w-4" />+ {tab.label}+ </Link>+ );+ })}+ </nav>+ </div>+ <div className="flex-1 min-h-0">{children}</div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxindex 0bf6b2646..5156d4575 100644--- a/packages/web/src/app/repos/[id]/graph/page.tsx+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -2,15 +2,25 @@import { use, useCallback, useState } from "react";import { useQueryState } from "nuqs";+import { useSearchParams } from "next/navigation";import { GraphFlow } from "@/components/graph/graph-flow";import { GraphDocPanel } from "@/components/graph/graph-doc-panel";+const VALID_VIEW_MODES = new Set(["module", "full", "architecture", "dead", "hotfiles", "unified"]);+export default function GraphPage({params,}: {params: Promise<{ id: string }>;}) {const { id: repoId } = use(params);+ const searchParams = useSearchParams();++ const viewModeParam = searchParams.get("viewMode");+ const initialViewMode = VALID_VIEW_MODES.has(viewModeParam ?? "")+ ? (viewModeParam as "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified")+ : undefined;+ const initialNode = searchParams.get("node");const [, setSelectedNode] = useQueryState("node");const [docNodeId, setDocNodeId] = useState<string | null>(null);@@ -54,6 +64,8 @@ export default function GraphPage({<div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative"><GraphFlowrepoId={repoId}+ initialViewMode={initialNode ? "full" : initialViewMode}+ initialSelectedNode={initialNode}onNodeClick={handleNodeClick}onNodeViewDocs={handleNodeViewDocs}/>diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsxindex 546f43170..643377e74 100644--- a/packages/web/src/app/repos/[id]/hotspots/page.tsx+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx@@ -51,13 +51,13 @@ export default async function HotspotsPage({Hotspots</h1><p className="text-sm text-[var(--color-text-secondary)]">- High-churn files — where the most risky code lives.+ High-churn files — where the most risky code lives.</p></div>{loadError && hotspots.length === 0 && (<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">- Couldn't load hotspots. The data may not be ready yet — try running a sync first.+ Couldn't load hotspots. The data may not be ready yet — try running a sync first.</div>)}@@ -87,7 +87,7 @@ export default async function HotspotsPage({<StatCardlabel="Bus Factor Risk"value={formatNumber(busFactorRiskCount)}- description="files with factor ≤ 1"+ description="files with factor ≤ 1"icon={<Shield className="h-4 w-4 text-red-400" />}/></div>@@ -136,7 +136,7 @@ export default async function HotspotsPage({{/* Table + sidebar */}<div className="grid grid-cols-1 gap-6 xl:grid-cols-4"><div className="xl:col-span-3">- <HotspotTable hotspots={hotspots} />+ <HotspotTable hotspots={hotspots} repoId={id} /></div>{/* Top owners leaderboard */}diff --git a/packages/web/src/app/repos/[id]/layout.tsx b/packages/web/src/app/repos/[id]/layout.tsxindex 8cd73800a..1f4c8818e 100644--- a/packages/web/src/app/repos/[id]/layout.tsx+++ b/packages/web/src/app/repos/[id]/layout.tsx@@ -2,6 +2,7 @@ import { redirect } from "next/navigation";import { getRepo } from "@/lib/api/repos";import { ActiveJobBannerWrapper as ActiveJobBanner } from "@/components/dashboard/active-job-banner-wrapper";import { PageTransition } from "@/components/layout/page-transition";+import { RepoBreadcrumb } from "@/components/layout/repo-breadcrumb";interface RepoLayoutProps {children: React.ReactNode;@@ -10,16 +11,17 @@ interface RepoLayoutProps {export default async function RepoLayout({ children, params }: RepoLayoutProps) {const { id } = await params;+ let repoName = id;try {- await getRepo(id);+ const repo = await getRepo(id);+ repoName = repo.name;} catch {- // Repo doesn't exist in this database (e.g. stale URL from a previous- // project). Redirect to the dashboard so the user sees what's available.redirect("/");}return (<><ActiveJobBanner repoId={id} />+ <RepoBreadcrumb repoName={repoName} /><PageTransition>{children}</PageTransition></>);diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 96ca5a5b8..fb2c95f5b 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -1,6 +1,6 @@import type { Metadata } from "next";import { notFound } from "next/navigation";-import { Hash, Activity } from "lucide-react";+import { Hash } from "lucide-react";import { getRepo, getRepoStats } from "@/lib/api/repos";import { getGitSummary, getHotspots, getOwnership } from "@/lib/api/git";import { getDeadCodeSummary, listDeadCode } from "@/lib/api/dead-code";@@ -14,20 +14,15 @@ import { StatCard } from "@repowise-dev/ui/shared/stat-card";import { HealthScoreRing } from "@repowise-dev/ui/dashboard/health-score-ring";import { AttentionPanel } from "@repowise-dev/ui/dashboard/attention-panel";import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";-import { OwnershipTreemap } from "@repowise-dev/ui/dashboard/ownership-treemap";import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";import { computeHealthScore, buildAttentionItems, aggregateLanguages } from "@/lib/utils/health-score";import { HotspotsMini } from "@repowise-dev/ui/dashboard/hotspots-mini";import { DecisionsTimeline } from "@repowise-dev/ui/dashboard/decisions-timeline";-import { ModuleMinimap } from "@repowise-dev/ui/dashboard/module-minimap";+import { ModuleOverviewGrid } from "@repowise-dev/ui/dashboard/module-overview-grid";import { CommunitySummaryGridWrapper as CommunitySummaryGrid } from "@/components/dashboard/community-summary-grid-wrapper";import { ExecutionFlowsPanel } from "@repowise-dev/ui/dashboard/execution-flows-panel";-import { DependencyHeatmap } from "@repowise-dev/ui/dashboard/dependency-heatmap";import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";-import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";-import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";import { CommitCategorySparkline } from "@repowise-dev/ui/git/commit-category-sparkline";-import { OwnershipTreemap as OwnershipTreemapGit } from "@repowise-dev/ui/git/ownership-treemap";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { formatNumber } from "@repowise-dev/ui/lib/format";import type {@@ -50,7 +45,7 @@ interface Props {params: Promise<{ id: string }>;}-// Each fetch wrapped to return null on failure — the dashboard degrades gracefully+// Each fetch wrapped to return null on failure — the dashboard degrades gracefullyasync function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {try {return await fn();@@ -65,7 +60,7 @@ export default async function OverviewPage({ params }: Props) {const repo = await safeFetch(() => getRepo(id));if (!repo) notFound();- // Fetch all data in parallel — each independently failable+ // Fetch all data in parallel — each independently failableconst [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap, communities, executionFlows] =await Promise.all([safeFetch(() => getRepoStats(id)),@@ -116,9 +111,9 @@ export default async function OverviewPage({ params }: Props) {return (<div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- {/* ── Hero: Health Score + Repo Info + Quick Actions ── */}+ {/* ── Hero: Health Score + Repo Info + Quick Actions ── */}<div className="flex flex-col sm:flex-row items-start gap-6">- <HealthScoreRing score={healthScore} />+ <HealthScoreRing score={healthScore.score} components={healthScore.components} /><div className="flex-1 min-w-0 space-y-3"><div>@@ -155,41 +150,46 @@ export default async function OverviewPage({ params }: Props) {<div className="grid grid-cols-2 gap-2 sm:grid-cols-5"><StatCardlabel="Files"- value={stats ? formatNumber(stats.file_count) : "—"}+ value={stats ? formatNumber(stats.file_count) : "–"}+ href={`/repos/${id}/graph`}className="!p-0 [&>div]:!p-3"/><StatCardlabel="Symbols"- value={stats ? formatNumber(stats.symbol_count) : "—"}+ value={stats ? formatNumber(stats.symbol_count) : "–"}+ href={`/repos/${id}/symbols`}className="!p-0 [&>div]:!p-3"/><StatCardlabel="Entry Points"- value={stats ? formatNumber(stats.entry_point_count) : "—"}+ value={stats ? formatNumber(stats.entry_point_count) : "–"}+ href={`/repos/${id}/graph?viewMode=architecture`}className="!p-0 [&>div]:!p-3"/><StatCardlabel="Doc Coverage"- value={stats ? `${Math.round(stats.doc_coverage_pct)}%` : "—"}+ value={stats ? `${Math.round(stats.doc_coverage_pct)}%` : "–"}+ href={`/repos/${id}/docs/coverage`}className="!p-0 [&>div]:!p-3"/><StatCardlabel="Dead Exports"- value={stats ? formatNumber(stats.dead_export_count) : "—"}+ value={stats ? formatNumber(stats.dead_export_count) : "–"}description={deadCodeSummary? `${formatNumber(deadCodeSummary.deletable_lines)} deletable lines`: undefined}+ href={`/repos/${id}/dead-code`}className="!p-0 [&>div]:!p-3"/></div></div></div>- {/* ── Main Grid ── */}+ {/* ── Main Grid ── */}<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- {/* Left column — Attention + Hotspots */}+ {/* Left column — Attention + Hotspots */}<div className="space-y-4 lg:col-span-2"><AttentionPanel items={attentionItems} repoId={id} /><div className="grid grid-cols-1 gap-4 md:grid-cols-2">@@ -207,16 +207,19 @@ export default async function OverviewPage({ params }: Props) {</div></div>- {/* Right column — Visualizations */}+ {/* Right column — Visualizations */}<div className="space-y-4"><LanguageDonut distribution={langDistribution} />- {ownership && ownership.length > 0 && (- <OwnershipTreemap entries={ownership} />- )}+ <a+ href={`/repos/${id}/graph?colorMode=language`}+ className="block text-[10px] text-[var(--color-accent-primary)] hover:underline text-right -mt-1"+ >+ View in Graph →+ </a></div></div>- {/* ── Git Insights ── */}+ {/* ── Git Insights ── */}{hotspots && hotspots.length > 0 && (() => {const aggregatedCategories: Record<string, number> = {};for (const h of hotspots) {@@ -226,109 +229,54 @@ export default async function OverviewPage({ params }: Props) {}const hasCategories = Object.values(aggregatedCategories).some((v) => v > 0);- return (+ return hasCategories ? (<div className="space-y-4">- <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">- Git Insights- </h2>-- {/* Commit category sparkline (full width) */}- {hasCategories && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Commit Activity</CardTitle>- </CardHeader>- <CardContent>- <CommitCategorySparkline categories={aggregatedCategories} />- <div className="flex items-center gap-4 mt-2 text-[10px] text-[var(--color-text-tertiary)]">- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#5b9cf6" }} /> Feature</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#ef4444" }} /> Fix</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#a855f7" }} /> Refactor</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#f59520" }} /> Dependency</span>- </div>- </CardContent>- </Card>- )}-- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- {/* Churn Histogram */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Churn Distribution</CardTitle>- </CardHeader>- <CardContent>- <ChurnHistogram hotspots={hotspots} />- </CardContent>- </Card>-- {/* Commit Category Donut */}- {hasCategories && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Commit Categories</CardTitle>- </CardHeader>- <CardContent className="flex items-center justify-center">- <CommitCategoryDonut categories={aggregatedCategories} />- </CardContent>- </Card>- )}-- {/* Bus Factor */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Bus Factor</CardTitle>- </CardHeader>- <CardContent>- <BusFactorPanel hotspots={hotspots} />- </CardContent>- </Card>+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">+ Git Insights+ </h2>+ <a href={`/repos/${id}/hotspots`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ View all →+ </a></div>-- {/* Ownership Treemap (git-level, file granularity) */}- {ownership && ownership.length > 0 && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Ownership Map</CardTitle>- </CardHeader>- <CardContent>- <OwnershipTreemapGit entries={ownership} />- </CardContent>- </Card>- )}- </div>- );- })()}-- {/* ── Module Architecture Map + Dependency Heatmap ── */}- {moduleGraph && moduleGraph.nodes.length > 0 && (- <div className="space-y-4">- <ModuleMinimap- nodes={moduleGraph.nodes}- edges={moduleGraph.edges}- repoId={id}- />- {moduleGraph.nodes.length >= 2 && (<Card><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Dependency Heatmap</CardTitle>- <p className="text-xs text-[var(--color-text-tertiary)]">- Module-to-module dependency density — brighter cells indicate more connections- </p>+ <CardTitle className="text-sm font-medium">Commit Activity</CardTitle></CardHeader><CardContent>- <DependencyHeatmap moduleGraph={moduleGraph} />+ <CommitCategorySparkline categories={aggregatedCategories} />+ <div className="flex items-center gap-4 mt-2 text-[10px] text-[var(--color-text-tertiary)]">+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#5b9cf6" }} /> Feature</span>+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#ef4444" }} /> Fix</span>+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#a855f7" }} /> Refactor</span>+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "#f59520" }} /> Dependency</span>+ </div></CardContent></Card>- )}- </div>+ </div>+ ) : null;+ })()}++ {/* ── Architecture ── */}+ {moduleGraph && moduleGraph.nodes.length > 0 && (+ <ModuleOverviewGrid+ nodes={moduleGraph.nodes}+ edges={moduleGraph.edges}+ repoId={id}+ />)}- {/* ── Graph Intelligence: Communities & Execution Flows ── */}+ {/* ── Graph Intelligence: Communities & Execution Flows ── */}{((communities && communities.length > 0) || (executionFlows && executionFlows.flows.length > 0)) && (<div className="space-y-4">- <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">- Graph Intelligence- </h2>+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">+ Graph Intelligence+ </h2>+ <a href={`/repos/${id}/graph?colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ View all →+ </a>+ </div><div className="grid grid-cols-1 gap-4 lg:grid-cols-2">{communities && communities.length > 0 && (<CommunitySummaryGrid communities={communities} repoId={id} />@@ -340,110 +288,103 @@ export default async function OverviewPage({ params }: Props) {</div>)}- {/* ── Knowledge Map ── */}- {knowledgeMap && (+ {/* ── Ownership & Knowledge ── */}+ {(hotspots || knowledgeMap) && (<div className="space-y-4">- <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">- Knowledge Map- </h2>+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">+ Ownership & Knowledge+ </h2>+ <a href={`/repos/${id}/ownership`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ View all →+ </a>+ </div><div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ {hotspots && hotspots.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Bus Factor</CardTitle>+ </CardHeader>+ <CardContent>+ <BusFactorPanel hotspots={hotspots} />+ </CardContent>+ </Card>+ )}- {/* Top Owners */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Top Owners</CardTitle>- </CardHeader>- <CardContent>- {knowledgeMap.top_owners.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">No ownership data available.</p>- ) : (- <ul className="space-y-2">- {knowledgeMap.top_owners.slice(0, 5).map((owner) => (- <li key={owner.email} className="flex items-center justify-between gap-2">- <div className="min-w-0">- <p className="text-xs font-medium text-[var(--color-text-primary)] truncate">- {owner.name || owner.email}- </p>- {owner.name && (- <p className="text-[10px] text-[var(--color-text-tertiary)] truncate">{owner.email}</p>- )}- </div>- <div className="text-right shrink-0">- <span className="text-xs font-mono text-[var(--color-text-secondary)]">- {formatNumber(owner.files_owned)} files- </span>- <span className="ml-2 text-[10px] text-[var(--color-text-tertiary)]">- {owner.percentage}%- </span>- </div>- </li>- ))}- </ul>- )}- </CardContent>- </Card>+ {knowledgeMap && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Knowledge Silos</CardTitle>+ </CardHeader>+ <CardContent>+ {knowledgeMap.knowledge_silos.length === 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">No silos detected — good bus factor!</p>+ ) : (+ <div className="space-y-1">+ <p className="text-xs text-[var(--color-text-secondary)] mb-2">+ {formatNumber(knowledgeMap.knowledge_silos.length)} file+ {knowledgeMap.knowledge_silos.length === 1 ? "" : "s"} with >80% single-owner concentration+ </p>+ <ul className="space-y-1">+ {knowledgeMap.knowledge_silos.slice(0, 3).map((silo) => (+ <li key={silo.file_path}>+ <a+ href={`/repos/${id}/graph?node=${encodeURIComponent(silo.file_path)}`}+ className="flex items-center justify-between gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate min-w-0">+ {silo.file_path}+ </p>+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">+ {Math.round(silo.owner_pct * 100)}%+ </span>+ </a>+ </li>+ ))}+ {knowledgeMap.knowledge_silos.length > 3 && (+ <li>+ <a href={`/repos/${id}/ownership`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ +{knowledgeMap.knowledge_silos.length - 3} more+ </a>+ </li>+ )}+ </ul>+ </div>+ )}+ </CardContent>+ </Card>+ )}- {/* Knowledge Silos */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Knowledge Silos</CardTitle>- </CardHeader>- <CardContent>- {knowledgeMap.knowledge_silos.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">No silos detected — good bus factor!</p>- ) : (- <div className="space-y-1">- <p className="text-xs text-[var(--color-text-secondary)] mb-2">- {formatNumber(knowledgeMap.knowledge_silos.length)} file- {knowledgeMap.knowledge_silos.length === 1 ? "" : "s"} with >80% single-owner concentration- </p>- <ul className="space-y-1">- {knowledgeMap.knowledge_silos.slice(0, 3).map((silo) => (- <li key={silo.file_path} className="flex items-center justify-between gap-2">- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate min-w-0">- {silo.file_path}- </p>- <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">- {Math.round(silo.owner_pct * 100)}%- </span>+ {knowledgeMap && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Onboarding Targets</CardTitle>+ </CardHeader>+ <CardContent>+ {knowledgeMap.onboarding_targets.length === 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">No graph data available.</p>+ ) : (+ <ul className="space-y-2">+ {knowledgeMap.onboarding_targets.slice(0, 5).map((target) => (+ <li key={target.path}>+ <a+ href={`/repos/${id}/graph?node=${encodeURIComponent(target.path)}`}+ className="block -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors space-y-0.5"+ >+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">+ {target.path}+ </p>+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ pagerank {target.pagerank.toFixed(4)} · {formatNumber(target.doc_words)} doc words+ </p>+ </a></li>))}- {knowledgeMap.knowledge_silos.length > 3 && (- <li className="text-[10px] text-[var(--color-text-tertiary)]">- +{knowledgeMap.knowledge_silos.length - 3} more- </li>- )}</ul>- </div>- )}- </CardContent>- </Card>-- {/* Onboarding Targets */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Onboarding Targets</CardTitle>- </CardHeader>- <CardContent>- {knowledgeMap.onboarding_targets.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">No graph data available.</p>- ) : (- <ul className="space-y-2">- {knowledgeMap.onboarding_targets.slice(0, 5).map((target) => (- <li key={target.path} className="space-y-0.5">- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">- {target.path}- </p>- <p className="text-[10px] text-[var(--color-text-tertiary)]">- pagerank {target.pagerank.toFixed(4)} · {formatNumber(target.doc_words)} doc words- </p>- </li>- ))}- </ul>- )}- </CardContent>- </Card>-+ )}+ </CardContent>+ </Card>+ )}</div></div>)}diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsxindex c6803cd97..90a758cdd 100644--- a/packages/web/src/app/repos/[id]/ownership/page.tsx+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx@@ -9,7 +9,6 @@ import { OwnershipTable } from "@repowise-dev/ui/git/ownership-table";import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";import { OwnershipTreemap } from "@repowise-dev/ui/git/ownership-treemap";import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";-import { ContributorNetwork } from "@repowise-dev/ui/git/contributor-network";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { getOwnership, getGitSummary, getHotspots } from "@/lib/api/git";@@ -53,7 +52,7 @@ export default function OwnershipPage() {Code Ownership</h1><p className="text-sm text-[var(--color-text-secondary)]">- Who owns what — silo detection and bus factor risk.+ Who owns what — silo detection and bus factor risk.</p></div>@@ -79,7 +78,7 @@ export default function OwnershipPage() {<StatCardlabel="Bus Factor Risk"value={formatNumber(busFactorRiskCount)}- description="files with factor ≤ 1"+ description="files with factor ≤ 1"icon={<Shield className="h-4 w-4 text-red-400" />}/></div>@@ -151,21 +150,6 @@ export default function OwnershipPage() {)}</div>- {/* Contributor Network */}- {hotspotData && hotspotData.length > 0 && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Contributor Network</CardTitle>- <p className="text-xs text-[var(--color-text-tertiary)]">- Contributors linked by shared file ownership — larger nodes own more files- </p>- </CardHeader>- <CardContent className="pt-0">- <ContributorNetwork hotspots={hotspotData} />- </CardContent>- </Card>- )}-{/* Detail table */}{loadingEntries ? (<div className="space-y-2">@@ -174,7 +158,7 @@ export default function OwnershipPage() {))}</div>) : (- <OwnershipTable entries={entries ?? []} />+ <OwnershipTable entries={entries ?? []} repoId={id} />)}</div>);diff --git a/packages/web/src/app/repos/[id]/page.tsx b/packages/web/src/app/repos/[id]/page.tsxindex 648f98c95..da05478f4 100644--- a/packages/web/src/app/repos/[id]/page.tsx+++ b/packages/web/src/app/repos/[id]/page.tsx@@ -13,7 +13,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {const { id } = await params;try {const repo = await getRepo(id);- return { title: `${repo.name} — Chat` };+ return { title: `${repo.name} — Chat` };} catch {return { title: "Repository" };}diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxindex e11c73907..c7904159a 100644--- a/packages/web/src/app/repos/[id]/settings/page.tsx+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -17,7 +17,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {const { id } = await params;try {const repo = await getRepo(id);- return { title: `${repo.name} — Settings` };+ return { title: `${repo.name} — Settings` };} catch {return { title: "Settings" };}diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsxindex 77e16903d..278d1d20b 100644--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx@@ -151,7 +151,7 @@ export default async function WikiPageRoute({ params }: Props) {<span>Generated {formatRelativeTime(page.updated_at)}</span><Separator orientation="vertical" className="h-4 hidden sm:block" /><span className="font-mono">- {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out</span>{versionList.length > 0 && (<>diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsxindex c040043d5..1693bc1e1 100644--- a/packages/web/src/app/workspace/co-changes/page.tsx+++ b/packages/web/src/app/workspace/co-changes/page.tsx@@ -33,7 +33,7 @@ export default function CoChangesPage() {</h1></div><p className="text-sm text-[var(--color-text-secondary)]">- Files across repositories that frequently change together — implicit coupling detected from git history.+ Files across repositories that frequently change together — implicit coupling detected from git history.</p></div>@@ -41,7 +41,7 @@ export default function CoChangesPage() {<div className="grid grid-cols-2 gap-3 lg:grid-cols-3"><StatCardlabel="Total Co-Change Pairs"- value={data?.total ?? "—"}+ value={data?.total ?? "—"}icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}/><StatCard@@ -50,10 +50,10 @@ export default function CoChangesPage() {data?.co_changes? new Set(data.co_changes.map((cc) =>- [cc.source_repo, cc.target_repo].sort().join("↔"),+ [cc.source_repo, cc.target_repo].sort().join("↔"),),).size- : "—"+ : "—"}icon={<GitMerge className="h-4 w-4 text-purple-400" />}/>@@ -66,7 +66,7 @@ export default function CoChangesPage() {data.co_changes.length) *100,)}%`- : "—"+ : "—"}icon={<GitMerge className="h-4 w-4 text-orange-400" />}/>diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsxindex e146c9aa4..3d2c06299 100644--- a/packages/web/src/app/workspace/contracts/page.tsx+++ b/packages/web/src/app/workspace/contracts/page.tsx@@ -67,17 +67,17 @@ export default function ContractsPage() {<div className="grid grid-cols-2 gap-3 lg:grid-cols-4"><StatCardlabel="Total Contracts"- value={data?.total_contracts ?? "—"}+ value={data?.total_contracts ?? "—"}icon={<Link2 className="h-4 w-4" />}/><StatCardlabel="Matched Links"- value={data?.total_links ?? "—"}+ value={data?.total_links ?? "—"}icon={<Link2 className="h-4 w-4 text-green-400" />}/><StatCardlabel="Unmatched"- value={isLoading ? "—" : unmatchedCount}+ value={isLoading ? "—" : unmatchedCount}description="No matching provider or consumer"icon={<Link2 className="h-4 w-4 text-yellow-400" />}/>@@ -86,7 +86,7 @@ export default function ContractsPage() {value={data?.by_type? Object.values(data.by_type).reduce((a, b) => a + b, 0)- : "—"+ : "—"}description={data?.by_typediff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsxindex 6987c7134..ef6016392 100644--- a/packages/web/src/app/workspace/page.tsx+++ b/packages/web/src/app/workspace/page.tsx@@ -18,6 +18,7 @@ import { CrossRepoSummary } from "@repowise-dev/ui/workspace/cross-repo-summary"import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";import { ContractTypeBadge } from "@repowise-dev/ui/workspace/contract-type-badge";import { formatNumber } from "@repowise-dev/ui/lib/format";+import { WorkspaceGraphSection } from "./workspace-graph-section";export const metadata: Metadata = { title: "Workspace" };@@ -141,6 +142,9 @@ export default async function WorkspaceDashboardPage() {</div></section>+ {/* Cross-Repo Graph */}+ <WorkspaceGraphSection repoCount={wsRepos.length} />+{/* Cross-Repo Intelligence */}{(workspace?.cross_repo_summary || workspace?.contract_summary) && (<section>diff --git a/packages/web/src/app/workspace/workspace-graph-section.tsx b/packages/web/src/app/workspace/workspace-graph-section.tsxnew file mode 100644index 000000000..796741353--- /dev/null+++ b/packages/web/src/app/workspace/workspace-graph-section.tsx@@ -0,0 +1,83 @@+"use client";++import { useEffect, useState } from "react";+import { useRouter } from "next/navigation";+import { Network, Loader2 } from "lucide-react";+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { WorkspaceGraph, type WorkspaceGraphData } from "@repowise-dev/ui/workspace/workspace-graph";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { getWorkspaceGraph } from "@/lib/api/workspace";++interface WorkspaceGraphSectionProps {+ repoCount: number;+}++export function WorkspaceGraphSection({ repoCount }: WorkspaceGraphSectionProps) {+ const router = useRouter();+ const [data, setData] = useState<WorkspaceGraphData | null>(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ if (repoCount < 2) {+ setLoading(false);+ return;+ }+ getWorkspaceGraph()+ .then(setData)+ .catch(() => setData(null))+ .finally(() => setLoading(false));+ }, [repoCount]);++ if (repoCount < 2) {+ return (+ <section>+ <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">+ Cross-Repo Graph+ </h2>+ <EmptyState+ icon={<Network className="h-8 w-8" />}+ title="Not enough repositories"+ description="Add at least 2 repositories to see cross-repo relationships."+ />+ </section>+ );+ }++ return (+ <section>+ <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">+ Cross-Repo Graph+ </h2>+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <Network className="h-4 w-4 text-[var(--color-accent-primary)]" />+ Workspace Overview+ </CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <div className="h-[450px] rounded-lg overflow-hidden border border-[var(--color-border-default)]">+ {loading ? (+ <div className="flex items-center justify-center h-full">+ <Loader2 className="w-5 h-5 animate-spin text-[var(--color-text-tertiary)]" />+ </div>+ ) : data && data.nodes.length >= 2 ? (+ <WorkspaceGraph+ data={data}+ onRepoClick={(repoId) => router.push(`/repos/${repoId}/graph`)}+ />+ ) : (+ <div className="flex items-center justify-center h-full">+ <EmptyState+ icon={<Network className="h-8 w-8" />}+ title="No graph data"+ description="Repository data is still being indexed."+ />+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ </section>+ );+}diff --git a/packages/web/src/components/dashboard/community-summary-grid-wrapper.tsx b/packages/web/src/components/dashboard/community-summary-grid-wrapper.tsxindex e751051a9..a6eb1c213 100644--- a/packages/web/src/components/dashboard/community-summary-grid-wrapper.tsx+++ b/packages/web/src/components/dashboard/community-summary-grid-wrapper.tsx@@ -27,6 +27,7 @@ export function CommunitySummaryGridWrapper({ communities, repoId }: Props) {return (<CommunitySummaryGridShellcommunities={communities}+ repoId={repoId}details={details}loadingDetailId={isLoading ? activeId : null}onExpand={(id) => setActiveId(id)}diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/web/src/components/dead-code/finding-row.tsxindex 204b29039..cfd9927e7 100644--- a/packages/web/src/components/dead-code/finding-row.tsx+++ b/packages/web/src/components/dead-code/finding-row.tsx@@ -2,9 +2,11 @@import { useState } from "react";import { toast } from "sonner";+import { GitBranch, Code2 } from "lucide-react";import { Button } from "@repowise-dev/ui/ui/button";import { Badge } from "@repowise-dev/ui/ui/badge";import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";+import { RowActions } from "@repowise-dev/ui/shared/row-actions";import { formatConfidence } from "@repowise-dev/ui/lib/format";import { patchDeadCodeFinding } from "@/lib/api/dead-code";import { cn } from "@/lib/utils/cn";@@ -33,6 +35,7 @@ const STATUS_LABELS: Record<string, { title: string; description: string; confirinterface FindingRowProps {finding: DeadCodeFindingResponse;+ repoId: string;selected: boolean;onToggle: (id: string) => void;onUpdate: (updated: DeadCodeFindingResponse) => void;@@ -45,7 +48,7 @@ const STATUS_COLORS: Record<string, string> = {false_positive: "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] border-[var(--color-border-default)]",};-export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRowProps) {+export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: FindingRowProps) {const [pending, setPending] = useState(false);const [confirmStatus, setConfirmStatus] = useState<string | null>(null);@@ -123,7 +126,7 @@ export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRow</span></td><td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">- {finding.primary_owner ?? "—"}+ {finding.primary_owner ?? "—"}</td><td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden md:table-cell">{finding.lines}@@ -146,6 +149,13 @@ export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRow</span></td><td className="px-4 py-2.5">+ <div className="flex items-center gap-1 flex-wrap justify-end">+ <RowActions+ actions={[+ { icon: GitBranch, label: "Graph", href: `/repos/${repoId}/graph?node=${encodeURIComponent(finding.file_path)}` },+ ...(finding.symbol_name ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/symbols` }] : []),+ ]}+ />{finding.status === "open" && (<div className="flex items-center gap-1 flex-wrap justify-end"><Button@@ -180,6 +190,7 @@ export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRow</Button></div>)}+ </div></td>{confirmConfig && (<ConfirmDialogdiff --git a/packages/web/src/components/dead-code/findings-table.tsx b/packages/web/src/components/dead-code/findings-table.tsxindex 4161608d2..975f5bccb 100644--- a/packages/web/src/components/dead-code/findings-table.tsx+++ b/packages/web/src/components/dead-code/findings-table.tsx@@ -149,7 +149,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {onClick={() => setBulkConfirmOpen(true)}className="text-green-500 border-green-500/30 hover:bg-green-500/10">- {bulkPending ? "Resolving…" : `Resolve ${selected.size} selected`}+ {bulkPending ? "Resolving…" : `Resolve ${selected.size} selected`}</Button>)}</div>@@ -233,6 +233,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {<FindingRowkey={f.id}finding={f}+ repoId={repoId}selected={selected.has(f.id)}onToggle={toggleSelect}onUpdate={handleUpdate}diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsxindex 320a5dcc2..e5dbbe2ac 100644--- a/packages/web/src/components/decisions/decision-detail.tsx+++ b/packages/web/src/components/decisions/decision-detail.tsx@@ -119,7 +119,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {{/* Stale warning */}{decision.staleness_score > 0.5 && (<div className="rounded-md border border-amber-400/30 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:bg-amber-900/20 dark:text-amber-200">- This decision may be stale — affected files have changed significantly since it was recorded.+ This decision may be stale — affected files have changed significantly since it was recorded.</div>)}diff --git a/packages/web/src/components/decisions/decisions-table-wrapper.tsx b/packages/web/src/components/decisions/decisions-table-wrapper.tsxindex d9c0fcf97..6496fce01 100644--- a/packages/web/src/components/decisions/decisions-table-wrapper.tsx+++ b/packages/web/src/components/decisions/decisions-table-wrapper.tsx@@ -2,6 +2,7 @@import * as React from "react";import useSWR from "swr";+import Link from "next/link";import {DecisionsTable,type DecisionsTableFilters,@@ -41,6 +42,7 @@ export function DecisionsTableWrapper({filters={filters}onFiltersChange={setFilters}repoId={repoId}+ LinkComponent={Link}error={error}isLoading={isLoading}onRetry={() => mutate()}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 426681592..b91c16d07 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -290,7 +290,7 @@ export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {</span><span>v{page.version}</span><span className="font-mono">- {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out</span></div>@@ -342,7 +342,7 @@ export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {</div></div>- {/* Right sidebar — Graph Intelligence */}+ {/* Right sidebar — Graph Intelligence */}{hasTargetPath && sidebarOpen && (<div className="hidden lg:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 w-[240px] overflow-auto"><DocsSidebar repoId={repoId} targetPath={page.target_path} />diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsxindex 35f348130..dde85afb3 100644--- a/packages/web/src/components/graph/graph-flow.tsx+++ b/packages/web/src/components/graph/graph-flow.tsx@@ -23,25 +23,27 @@ import type {CommunitySummaryItem,} from "@repowise-dev/types/graph";+type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";+export interface GraphFlowProps {repoId: string;+ initialViewMode?: ViewMode;+ initialSelectedNode?: string | null;onNodeClick?: GraphFlowShellProps["onNodeClick"];onNodeViewDocs?: GraphFlowShellProps["onNodeViewDocs"];}-export function GraphFlow({ repoId, onNodeClick, onNodeViewDocs }: GraphFlowProps) {- // Track view-mode + drill-down so we can suppress fetches we don't need.- const [viewMode, setViewMode] = useState<- "module" | "full" | "architecture" | "dead" | "hotfiles"- >("module");+export function GraphFlow({ repoId, initialViewMode, initialSelectedNode, onNodeClick, onNodeViewDocs }: GraphFlowProps) {+ const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "module");const [modulePath, setModulePath] = useState<string[]>([]);+ const [hasExpandedModules, setHasExpandedModules] = useState(false);const isDrilledDown = modulePath.length > 0;const isModuleView = viewMode === "module";const { graph: moduleGraph, isLoading: moduleLoading } = useModuleGraph(- isModuleView && !isDrilledDown ? repoId : null,+ isModuleView ? repoId : null,);- const needsFullGraph = isDrilledDown || viewMode === "full";+ const needsFullGraph = isDrilledDown || viewMode === "full" || viewMode === "unified" || hasExpandedModules;const { graph: fullGraph, isLoading: fullLoading } = useGraph(needsFullGraph ? repoId : null,);@@ -74,8 +76,11 @@ export function GraphFlow({ repoId, onNodeClick, onNodeViewDocs }: GraphFlowPropisLoadingHotFilesGraph={hotLoading}communities={communities as CommunitySummaryItem[] | undefined}executionFlows={executionFlowsData as ExecutionFlows | undefined}+ initialViewMode={initialViewMode}+ initialSelectedNode={initialSelectedNode}onViewModeChange={setViewMode}onModulePathChange={setModulePath}+ onExpandedModulesChange={(expanded) => setHasExpandedModules(expanded.size > 0)}onNodeClick={onNodeClick}onNodeViewDocs={onNodeViewDocs}renderPathFinder={(props) => (diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsxindex ef4bc2a19..d420fa25a 100644--- a/packages/web/src/components/layout/mobile-nav.tsx+++ b/packages/web/src/components/layout/mobile-nav.tsx@@ -15,7 +15,6 @@ import {Search,GitBranch,Code2,- BarChart3,Users,Flame,Trash2,@@ -44,12 +43,11 @@ const GLOBAL_NAV = [function repoNavItems(repoId: string) {return [{ label: "Overview", href: `/repos/${repoId}/overview`, icon: Activity },- { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare },+ { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },{ label: "Docs", href: `/repos/${repoId}/docs`, icon: BookOpen },{ label: "Search", href: `/repos/${repoId}/search`, icon: Search },{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },- { label: "Coverage", href: `/repos/${repoId}/coverage`, icon: BarChart3 },{ label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },{ label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },{ label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },@@ -60,7 +58,7 @@ function repoNavItems(repoId: string) {}const WORKSPACE_NAV = [- { label: "Overview", href: "/workspace", icon: Layers },+ { label: "Overview", href: "/workspace", icon: Layers, exact: true as const },{ label: "Contracts", href: "/workspace/contracts", icon: Link2 },{ label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },];@@ -187,10 +185,9 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {<nav className="space-y-1">{WORKSPACE_NAV.map((item) => {const Icon = item.icon;- const isActive =- item.href === "/workspace"- ? pathname === "/workspace"- : pathname.startsWith(`${item.href}`);+ const isActive = (item as { exact?: boolean }).exact+ ? pathname === item.href+ : pathname.startsWith(`${item.href}`);return (<Linkkey={item.href}@@ -242,9 +239,9 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {<div className="ml-3.5 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">{navItems.map((item) => {const Icon = item.icon;- const isActive =- pathname === item.href ||- pathname.startsWith(`${item.href}/`);+ const isActive = (item as { exact?: boolean }).exact+ ? pathname === item.href+ : pathname === item.href || pathname.startsWith(`${item.href}/`);return (<Linkkey={item.href}diff --git a/packages/web/src/components/layout/repo-breadcrumb.tsx b/packages/web/src/components/layout/repo-breadcrumb.tsxnew file mode 100644index 000000000..2febf7b0f--- /dev/null+++ b/packages/web/src/components/layout/repo-breadcrumb.tsx@@ -0,0 +1,53 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import { Breadcrumb } from "@repowise-dev/ui/shared/breadcrumb";+import type { BreadcrumbSegment } from "@repowise-dev/ui/shared/breadcrumb";++const SEGMENT_LABELS: Record<string, string> = {+ overview: "Overview",+ docs: "Docs",+ coverage: "Coverage",+ search: "Search",+ graph: "Graph",+ symbols: "Symbols",+ ownership: "Ownership",+ hotspots: "Hotspots",+ "dead-code": "Dead Code",+ "blast-radius": "Blast Radius",+ decisions: "Decisions",+ costs: "Costs",+ settings: "Settings",+};++export function RepoBreadcrumb({ repoName }: { repoName: string }) {+ const pathname = usePathname();+ const match = pathname.match(/^\/repos\/([^/]+)(.*)/);+ if (!match) return null;++ const repoId = match[1];+ const rest = match[2]?.replace(/^\//, "").split("/").filter(Boolean) ?? [];++ const segments: BreadcrumbSegment[] = [+ { label: "Dashboard", href: "/" },+ { label: repoName, href: `/repos/${repoId}` },+ ];++ let currentPath = `/repos/${repoId}`;+ for (const seg of rest) {+ currentPath += `/${seg}`;+ segments.push({+ label: SEGMENT_LABELS[seg] || seg,+ href: currentPath,+ });+ }++ if (segments.length <= 2) return null;++ return (+ <div className="px-4 sm:px-6 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">+ <Breadcrumb segments={segments} LinkComponent={Link} />+ </div>+ );+}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex fbbdb8b12..c6b5b4221 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -13,7 +13,6 @@ import {MessageSquare,Search,Code2,- BarChart3,Users,Flame,Trash2,@@ -39,6 +38,7 @@ interface NavItem {label: string;href: string;icon: React.ComponentType<{ className?: string }>;+ exact?: boolean;}const GLOBAL_NAV: NavItem[] = [@@ -47,7 +47,7 @@ const GLOBAL_NAV: NavItem[] = [];const WORKSPACE_NAV: NavItem[] = [- { label: "Overview", href: "/workspace", icon: Layers },+ { label: "Overview", href: "/workspace", icon: Layers, exact: true },{ label: "Contracts", href: "/workspace/contracts", icon: Link2 },{ label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },];@@ -56,12 +56,11 @@ const WORKSPACE_NAV: NavItem[] = [function repoNavItems(repoId: string): NavItem[] {return [{ label: "Overview", href: `/repos/${repoId}/overview`, icon: Activity },- { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare },+ { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },{ label: "Docs", href: `/repos/${repoId}/docs`, icon: BookOpen },{ label: "Search", href: `/repos/${repoId}/search`, icon: Search },{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },- { label: "Coverage", href: `/repos/${repoId}/coverage`, icon: BarChart3 },{ label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },{ label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },{ label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },@@ -158,7 +157,7 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {))}</nav>- {/* Workspace nav — only shown in workspace mode */}+ {/* Workspace nav — only shown in workspace mode */}{isWorkspace && (<>{!isIconOnly && (@@ -175,11 +174,7 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {<SidebarNavItemkey={item.href}item={item}- isActive={- item.href === "/workspace"- ? pathname === "/workspace"- : pathname.startsWith(`${item.href}`)- }+ isActive={item.exact ? pathname === item.href : pathname.startsWith(`${item.href}`)}iconOnly={isIconOnly}/>))}@@ -255,7 +250,7 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {<SidebarNavItemkey={item.href}item={item}- isActive={pathname === item.href || pathname.startsWith(`${item.href}/`)}+ isActive={item.exact ? pathname === item.href : (pathname === item.href || pathname.startsWith(`${item.href}/`))}size="sm"iconOnly={false}/>diff --git a/packages/web/src/components/repos/add-repo-dialog.tsx b/packages/web/src/components/repos/add-repo-dialog.tsxindex 31c74cc1a..c17f62435 100644--- a/packages/web/src/components/repos/add-repo-dialog.tsx+++ b/packages/web/src/components/repos/add-repo-dialog.tsx@@ -145,7 +145,7 @@ export function AddRepoDialog({ variant = "default" }: Props) {Cancel</Button><Button type="submit" disabled={submitting || !name.trim() || !localPath.trim()}>- {submitting ? "Adding…" : "Add Repository"}+ {submitting ? "Adding…" : "Add Repository"}</Button></DialogFooter></form>diff --git a/packages/web/src/components/repos/coordinator-health-panel.tsx b/packages/web/src/components/repos/coordinator-health-panel.tsxindex efb7842e1..68de2cc7c 100644--- a/packages/web/src/components/repos/coordinator-health-panel.tsx+++ b/packages/web/src/components/repos/coordinator-health-panel.tsx@@ -43,8 +43,8 @@ export function CoordinatorHealthPanel({ repoId, initial }: Props) {}}- const fmt = (v: number | null) => (v === null ? "—" : String(v));- const fmtPct = (v: number | null) => (v === null ? "—" : `${v.toFixed(1)}%`);+ const fmt = (v: number | null) => (v === null ? "—" : String(v));+ const fmtPct = (v: number | null) => (v === null ? "—" : `${v.toFixed(1)}%`);return (<div className="space-y-3">@@ -65,7 +65,7 @@ export function CoordinatorHealthPanel({ repoId, initial }: Props) {</>) : (<p className="text-xs text-[var(--color-text-secondary)]">- {error ?? "No data — click Refresh to load."}+ {error ?? "No data — click Refresh to load."}</p>)}{error && (@@ -79,7 +79,7 @@ export function CoordinatorHealthPanel({ repoId, initial }: Props) {disabled={loading}><RefreshCw className={`h-3.5 w-3.5 mr-1.5 ${loading ? "animate-spin" : ""}`} />- {loading ? "Checking…" : "Refresh"}+ {loading ? "Checking…" : "Refresh"}</Button></div>);diff --git a/packages/web/src/components/repos/operations-panel.tsx b/packages/web/src/components/repos/operations-panel.tsxindex a1536771d..b4e91d9df 100644--- a/packages/web/src/components/repos/operations-panel.tsx+++ b/packages/web/src/components/repos/operations-panel.tsx@@ -41,7 +41,7 @@ export function OperationsPanel({ repoId, repoName }: Props) {try {const job = await syncRepo(repoId);setActiveJobId(job.id);- toast.info(`Sync started — ${repoName}`);+ toast.info(`Sync started — ${repoName}`);} catch (e) {toast.error("Sync failed", {description: e instanceof Error ? e.message : "Unknown error",@@ -57,7 +57,7 @@ export function OperationsPanel({ repoId, repoName }: Props) {try {const job = await fullResyncRepo(repoId);setActiveJobId(job.id);- toast.info(`Full resync started — ${repoName}`);+ toast.info(`Full resync started — ${repoName}`);} catch (e) {toast.error("Resync failed", {description: e instanceof Error ? e.message : "Unknown error",@@ -115,7 +115,7 @@ export function OperationsPanel({ repoId, repoName }: Props) {className="flex-1"><Zap className="h-3.5 w-3.5 mr-1.5" />- {loading === "sync" ? "Starting…" : "Sync"}+ {loading === "sync" ? "Starting…" : "Sync"}</Button><Buttonvariant="outline"@@ -125,7 +125,7 @@ export function OperationsPanel({ repoId, repoName }: Props) {className="flex-1"><RefreshCw className="h-3.5 w-3.5 mr-1.5" />- {loading === "resync" ? "Starting…" : "Full Resync"}+ {loading === "resync" ? "Starting…" : "Full Resync"}</Button><Buttonvariant="ghost"diff --git a/packages/web/src/components/search/command-palette.tsx b/packages/web/src/components/search/command-palette.tsxindex 5b292f973..78e21cba0 100644--- a/packages/web/src/components/search/command-palette.tsx+++ b/packages/web/src/components/search/command-palette.tsx@@ -63,7 +63,7 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {<Command.Inputvalue={query}onValueChange={setQuery}- placeholder="Search pages, navigate repos…"+ placeholder="Search pages, navigate repos…"className="flex-1 bg-transparent text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"/><kbd className="hidden sm:inline-flex items-center rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)] font-mono">@@ -73,7 +73,7 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {<Command.List className="max-h-[60dvh] overflow-y-auto py-2"><Command.Empty className="px-4 py-8 text-center text-sm text-[var(--color-text-tertiary)]">- {isLoading ? "Searching…" : "No results found."}+ {isLoading ? "Searching…" : "No results found."}</Command.Empty>{/* Quick navigation */}@@ -172,8 +172,8 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {</Command.List><div className="border-t border-[var(--color-border-default)] px-4 py-2 flex items-center gap-4 text-xs text-[var(--color-text-tertiary)]">- <span>↑↓ navigate</span>- <span>↵ select</span>+ <span>↑↓ navigate</span>+ <span>↵ select</span><span>esc close</span></div></div>diff --git a/packages/web/src/components/search/search-bar.tsx b/packages/web/src/components/search/search-bar.tsxindex 352b183fa..328d67a5a 100644--- a/packages/web/src/components/search/search-bar.tsx+++ b/packages/web/src/components/search/search-bar.tsx@@ -28,7 +28,7 @@ export function SearchBar({<Inputvalue={query}onChange={(e) => onQueryChange(e.target.value)}- placeholder="Search wiki pages…"+ placeholder="Search wiki pages…"className="pl-9"autoFocus/>diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsxindex 28caa7fd6..2b0df6a92 100644--- a/packages/web/src/components/search/search-result-card.tsx+++ b/packages/web/src/components/search/search-result-card.tsx@@ -1,6 +1,7 @@import Link from "next/link";import { Badge } from "@repowise-dev/ui/ui/badge";import { truncatePath } from "@repowise-dev/ui/lib/format";+import { getPageTypeLabel } from "@repowise-dev/ui/lib/page-types";import { cn } from "@/lib/utils/cn";import type { SearchResultResponse } from "@/lib/api/types";@@ -41,7 +42,7 @@ export function SearchResultCard({ result, query, repoId }: SearchResultCardProp{result.title}</h3><div className="flex items-center gap-1.5 shrink-0">- <Badge variant="default">{result.page_type.replace(/_/g, " ")}</Badge>+ <Badge variant="default">{getPageTypeLabel(result.page_type)}</Badge><spanclassName={cn("inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium tabular-nums",diff --git a/packages/web/src/components/settings/connection-section.tsx b/packages/web/src/components/settings/connection-section.tsxindex fd6cf986b..3adc2e599 100644--- a/packages/web/src/components/settings/connection-section.tsx+++ b/packages/web/src/components/settings/connection-section.tsx@@ -87,7 +87,7 @@ export function ConnectionSection() {<Inputid="api-key"type="password"- placeholder="Optional — only required if REPOWISE_API_KEY is set on the server"+ placeholder="Optional — only required if REPOWISE_API_KEY is set on the server"value={apiKey}onChange={(e) => setApiKey(e.target.value)}onBlur={save}@@ -112,7 +112,7 @@ export function ConnectionSection() {{health && (<span className="flex items-center gap-1.5 text-sm text-[var(--color-fresh)]"><CheckCircle className="h-4 w-4" />- Connected · v{health.version} · DB {health.db}+ Connected · v{health.version} · DB {health.db}</span>)}{error && (diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxindex c935d74b0..cd6835460 100644--- a/packages/web/src/components/settings/provider-section.tsx+++ b/packages/web/src/components/settings/provider-section.tsx@@ -176,12 +176,12 @@ export function ProviderSection() {{embedderVars.map((v) => (<code key={v} className="font-mono">{v}</code>))}{" "}- — set <code className="font-mono">REPOWISE_EMBEDDER={embedder}</code> on the server.+ — set <code className="font-mono">REPOWISE_EMBEDDER={embedder}</code> on the server.</p>)}{embedder === "mock" && (<p className="text-xs text-[var(--color-text-tertiary)]">- Using mock embedder — semantic search disabled. Set{" "}+ Using mock embedder — semantic search disabled. Set{" "}<code className="font-mono">REPOWISE_EMBEDDER=gemini</code> or{" "}<code className="font-mono">REPOWISE_EMBEDDER=openai</code> for real RAG.</p>@@ -210,14 +210,14 @@ export function ProviderSection() {disabled={testStatus === "testing"}className="text-sm px-3 py-1.5 rounded-md border border-[var(--color-border)] hover:bg-[var(--color-bg-secondary)] disabled:opacity-50 transition-colors">- {testStatus === "testing" ? "Testing…" : "Test connection"}+ {testStatus === "testing" ? "Testing…" : "Test connection"}</button>{testStatus === "ok" && (- <span className="text-sm text-green-600 dark:text-green-400">✓ Server healthy</span>+ <span className="text-sm text-green-600 dark:text-green-400">✓ Server healthy</span>)}{testStatus === "error" && (<span className="text-sm text-red-600 dark:text-red-400">- ✗ {testError || "Connection failed"}+ ✗ {testError || "Connection failed"}</span>)}</div>diff --git a/packages/web/src/components/symbols/symbol-table-wrapper.tsx b/packages/web/src/components/symbols/symbol-table-wrapper.tsxindex 56ed4ecba..d914e7055 100644--- a/packages/web/src/components/symbols/symbol-table-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-table-wrapper.tsx@@ -76,6 +76,7 @@ export function SymbolTableWrapper({ repoId }: Props) {<SymbolTableitems={items}importanceScores={importanceScores}+ repoId={repoId}isLoading={isLoading}isValidating={isValidating}hasMore={hasMore}diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.tsindex 41f7b56f5..9d3d97f20 100644--- a/packages/web/src/lib/api/types.ts+++ b/packages/web/src/lib/api/types.ts@@ -714,3 +714,25 @@ export interface WorkspaceCoChangesResponse {co_changes: WorkspaceCoChangeEntry[];total: number;}++export interface WorkspaceGraphNode {+ repo_id: string;+ name: string;+ file_count: number;+ coverage_pct: number;+ health_score: number;+ top_language: string;+}++export interface WorkspaceGraphEdge {+ source: string;+ target: string;+ type: "contract" | "co_change";+ strength: number;+ label: string | null;+}++export interface WorkspaceGraphResponse {+ nodes: WorkspaceGraphNode[];+ edges: WorkspaceGraphEdge[];+}diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.tsindex 4f24f0206..082c4b359 100644--- a/packages/web/src/lib/api/workspace.ts+++ b/packages/web/src/lib/api/workspace.ts@@ -3,6 +3,7 @@ import type {WorkspaceResponse,WorkspaceContractsResponse,WorkspaceCoChangesResponse,+ WorkspaceGraphResponse,} from "./types";export async function getWorkspace(): Promise<WorkspaceResponse> {@@ -36,3 +37,7 @@ export async function getWorkspaceCoChanges(opts?: {if (opts?.limit != null) params.limit = String(opts.limit);return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);}++export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {+ return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");+}diff --git a/packages/web/src/lib/utils/health-score.ts b/packages/web/src/lib/utils/health-score.tsindex 00881d902..18f585d78 100644--- a/packages/web/src/lib/utils/health-score.ts+++ b/packages/web/src/lib/utils/health-score.ts@@ -1,3 +1,10 @@+import type { HealthScoreComponent } from "@repowise-dev/ui/dashboard/health-score-ring";++export interface HealthScoreResult {+ score: number;+ components: HealthScoreComponent[];+}+/** Compute composite health score from available repo data */export function computeHealthScore(params: {docCoveragePct: number;@@ -8,7 +15,7 @@ export function computeHealthScore(params: {totalFiles: number;siloCount: number;totalModules: number;-}): number {+}): HealthScoreResult {const {docCoveragePct,freshnessScore,@@ -28,7 +35,7 @@ export function computeHealthScore(params: {// Dead code: lower is better, weight 20%const deadRatio = symbolCount > 0 ? deadExportCount / symbolCount : 0;- const deadScore = Math.max(0, (1 - deadRatio * 5) * 100); // 20% dead = 0 score+ const deadScore = Math.max(0, (1 - deadRatio * 5) * 100);// Hotspot density: lower is better, weight 15%const hotspotRatio = totalFiles > 0 ? hotspotCount / totalFiles : 0;@@ -46,7 +53,46 @@ export function computeHealthScore(params: {siloScore * 0.15);- return Math.max(0, Math.min(100, composite));+ return {+ score: Math.max(0, Math.min(100, composite)),+ components: [+ {+ key: "doc_coverage",+ label: "Doc Coverage",+ weight: 0.25,+ score: Math.round(docScore),+ detail: `${Math.round(docCoveragePct)}% of symbols documented`,+ },+ {+ key: "freshness",+ label: "Freshness",+ weight: 0.25,+ score: Math.round(freshScore),+ detail: `Based on doc-to-code drift analysis`,+ },+ {+ key: "dead_code",+ label: "Dead Code",+ weight: 0.20,+ score: Math.round(deadScore),+ detail: `${deadExportCount} dead exports out of ${symbolCount} symbols`,+ },+ {+ key: "hotspot_density",+ label: "Hotspot Density",+ weight: 0.15,+ score: Math.round(hotspotScore),+ detail: `${hotspotCount} hotspots across ${totalFiles} files`,+ },+ {+ key: "knowledge_silos",+ label: "Knowledge Silos",+ weight: 0.15,+ score: Math.round(siloScore),+ detail: `${siloCount} silo${siloCount === 1 ? "" : "s"} out of ${totalModules} modules`,+ },+ ],+ };}/** Aggregate language distribution from graph nodes */diff --git a/packages/web/src/styles/globals.css b/packages/web/src/styles/globals.cssindex d44eb3c9c..cf81f1dee 100644--- a/packages/web/src/styles/globals.css+++ b/packages/web/src/styles/globals.css@@ -1,7 +1,7 @@/** packages/web — global stylesheet.*- * Tokens, base styles, prose and React Flow theming live in+ * Tokens, base styles, prose and graph theming live in* `@repowise-dev/ui/styles.css`. App-specific overrides go below the import.*/