Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

Contributor profiles, module health, reviewer suggestions (#188)

Raghav Chamadiya809cb10f845b
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index b70623c63..1dee89527 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -39,6 +39,8 @@ from repowise.server.routers import (
health,
jobs,
knowledge_map,
+ modules,
+ owners,
pages,
providers,
repos,
@@ -343,5 +345,7 @@ def create_app() -> FastAPI:
app.include_router(blast_radius.router)
app.include_router(knowledge_map.router)
app.include_router(workspace.router)
+ app.include_router(owners.router)
+ app.include_router(modules.router)
return app
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index 52bf8ff5f..36f5565a9 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -18,7 +18,9 @@ from repowise.server.schemas import (
HotspotResponse,
OwnershipEntry,
Paginated,
+ ReviewerSuggestionsResponse,
)
+from repowise.server.services.reviewer_suggestions import suggest_reviewers
router = APIRouter(
prefix="/api/repos",
@@ -207,6 +209,26 @@ async def get_co_changes(
}
+ "/{repo_id}/reviewer-suggestions",
+ response_model=ReviewerSuggestionsResponse,
+)
+async def get_reviewer_suggestions(
+ repo_id: str,
+ paths: list[str] = Query(..., description="Repeat ?paths= for each changed file"),
+ limit: int = Query(10, ge=1, le=50),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> ReviewerSuggestionsResponse:
+ """Suggest reviewers for a PR touching the given file paths.
+
+ Composes signals already produced by the indexer (top authors,
+ co-change partners, 90-day commit counts) — no live git inspection.
+ """
+
+ suggestions = await suggest_reviewers(session, repo_id, paths, limit=limit)
+ return ReviewerSuggestionsResponse(paths=paths, suggestions=suggestions)
+
+
@router.get("/{repo_id}/git-summary", response_model=GitSummaryResponse)
async def get_git_summary(
repo_id: str,
diff --git a/packages/server/src/repowise/server/routers/modules.py b/packages/server/src/repowise/server/routers/modules.py
new file mode 100644
index 000000000..de68c1313
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/modules.py
@@ -0,0 +1,91 @@
+"""/api/repos/{repo_id}/modules — Module Health endpoints.
+
+Per-module rollups of ownership, churn, dead-code, docs, and decisions.
+No core ingestion changes.
+"""
+
+from __future__ import annotations
+
+from urllib.parse import unquote
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ ModuleHealthDetail,
+ ModuleHealthOwner,
+ ModuleHealthSummary,
+ Paginated,
+)
+from repowise.server.services.module_health import (
+ aggregate_modules,
+ detail_extras,
+ summarize,
+)
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["modules"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+ "/{repo_id}/modules/health",
+ response_model=Paginated[ModuleHealthSummary],
+)
+async def list_module_health(
+ repo_id: str,
+ sort: str = Query("health_score", description="health_score | hotspot_count | dead_code_lines | file_count"),
+ limit: int = Query(100, ge=1, le=500),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> Paginated[ModuleHealthSummary]:
+ accs = await aggregate_modules(session, repo_id)
+ rows = [ModuleHealthSummary(**summarize(a)) for a in accs.values()]
+
+ # Default ascending for health_score (worst first); descending for others.
+ if sort == "health_score":
+ rows.sort(key=lambda r: r.health_score)
+ elif sort == "hotspot_count":
+ rows.sort(key=lambda r: r.hotspot_count, reverse=True)
+ elif sort == "dead_code_lines":
+ rows.sort(key=lambda r: r.dead_code_lines, reverse=True)
+ elif sort == "file_count":
+ rows.sort(key=lambda r: r.file_count, reverse=True)
+
+ total = len(rows)
+ page = rows[offset : offset + limit]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[ModuleHealthSummary](
+ items=page,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ )
+
+
+ "/{repo_id}/modules/health/{module_path:path}",
+ response_model=ModuleHealthDetail,
+)
+async def get_module_health(
+ repo_id: str,
+ module_path: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> ModuleHealthDetail:
+ accs = await aggregate_modules(session, repo_id)
+ acc = accs.get(unquote(module_path))
+ if acc is None:
+ raise HTTPException(status_code=404, detail="Module not found")
+
+ base = summarize(acc)
+ extras = detail_extras(acc)
+ return ModuleHealthDetail(
+ **base,
+ owners=[ModuleHealthOwner(**o) for o in extras["owners"]],
+ top_hotspots=extras["top_hotspots"],
+ governing_decisions=extras["governing_decisions"],
+ contributor_count=extras["contributor_count"],
+ )
diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.py
new file mode 100644
index 000000000..57c02455e
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/owners.py
@@ -0,0 +1,212 @@
+"""/api/repos/{repo_id}/owners — Contributor profile endpoints.
+
+The owners directory and per-owner profile is the engineering-leader view:
+"who is doing what, where is the risk, who reviews this code." It composes
+existing GitMetadata + DeadCodeFinding rows; no ingestion changes.
+"""
+
+from __future__ import annotations
+
+from urllib.parse import unquote
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ OwnerCoAuthor,
+ OwnerFileEntry,
+ OwnerListEntry,
+ OwnerModuleRollup,
+ OwnerProfileResponse,
+ Paginated,
+)
+from repowise.server.services.owner_profile import (
+ _OwnerAccumulator,
+ aggregate_owners,
+ module_share,
+ silo_modules,
+)
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["owners"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+# ---------------------------------------------------------------------------
+# Shapers
+# ---------------------------------------------------------------------------
+
+
+def _to_list_entry(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerListEntry:
+ return OwnerListEntry(
+ key=acc.key,
+ name=acc.name,
+ email=acc.email,
+ files_owned=acc.files_owned,
+ hotspots_owned=acc.hotspots_owned,
+ silo_modules=silo_modules(acc, module_totals),
+ dead_code_files_owned=len(acc.dead_code_files),
+ dead_code_lines_owned=acc.dead_code_lines,
+ commit_count_90d=acc.commit_count_90d,
+ last_commit_at=acc.last_commit_at,
+ bus_factor_risk_files=acc.bus_factor_risk_files,
+ )
+
+
+def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerProfileResponse:
+ shares = module_share(acc, module_totals)
+
+ modules = [
+ OwnerModuleRollup(
+ module_path=mod,
+ file_count=acc.module_files.get(mod, 0),
+ hotspot_count=acc.module_hotspots.get(mod, 0),
+ dominant_pct=shares.get(mod, 0.0),
+ )
+ for mod in sorted(
+ acc.module_files,
+ key=lambda m: (acc.module_files[m], acc.module_hotspots.get(m, 0)),
+ reverse=True,
+ )
+ ]
+
+ # Top files by attributed commit count, then churn.
+ top_files: list[OwnerFileEntry] = []
+ sorted_paths = sorted(
+ acc.files_touched,
+ key=lambda fp: (
+ acc.files_touched[fp],
+ (acc.file_meta[fp].churn_percentile or 0.0),
+ ),
+ reverse=True,
+ )[:50]
+ for fp in sorted_paths:
+ m = acc.file_meta[fp]
+ top_files.append(
+ OwnerFileEntry(
+ file_path=fp,
+ commit_count_90d=acc.files_touched[fp],
+ churn_percentile=(m.churn_percentile or 0.0) * 100.0,
+ bus_factor=m.bus_factor or 0,
+ is_hotspot=bool(m.is_hotspot),
+ last_commit_at=m.last_commit_at,
+ primary_owner_commit_pct=m.primary_owner_commit_pct,
+ )
+ )
+
+ co_authors: list[OwnerCoAuthor] = []
+ total_touched = max(len(acc.files_touched), 1)
+ for other_key, shared in acc.coauthor_shared.most_common(25):
+ name, email = acc.coauthor_meta.get(other_key, (other_key, None))
+ co_authors.append(
+ OwnerCoAuthor(
+ name=name,
+ email=email,
+ shared_files=shared,
+ co_change_strength=shared / total_touched,
+ )
+ )
+
+ return OwnerProfileResponse(
+ key=acc.key,
+ name=acc.name,
+ email=acc.email,
+ files_owned=acc.files_owned,
+ hotspots_owned=acc.hotspots_owned,
+ silo_modules=silo_modules(acc, module_totals),
+ dead_code_files_owned=len(acc.dead_code_files),
+ dead_code_lines_owned=acc.dead_code_lines,
+ commit_count_90d=acc.commit_count_90d,
+ last_commit_at=acc.last_commit_at,
+ first_commit_at=acc.first_commit_at,
+ bus_factor_risk_files=acc.bus_factor_risk_files,
+ lines_added_90d_est=int(acc.lines_added_90d_est),
+ lines_deleted_90d_est=int(acc.lines_deleted_90d_est),
+ modules=modules,
+ top_files=top_files,
+ co_authors=co_authors,
+ commit_categories=dict(acc.commit_categories),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Endpoints
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/owners", response_model=Paginated[OwnerListEntry])
+async def list_owners(
+ repo_id: str,
+ q: str = Query("", description="Substring filter on name or email"),
+ sort: str = Query(
+ "files_owned",
+ description="One of: files_owned, hotspots_owned, commit_count_90d, dead_code_lines_owned, bus_factor_risk_files",
+ ),
+ limit: int = Query(50, ge=1, le=500),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> Paginated[OwnerListEntry]:
+ """Directory of contributors with rollup stats — engineering-leader view."""
+
+ accs, module_totals = await aggregate_owners(session, repo_id)
+ entries = [_to_list_entry(a, module_totals) for a in accs.values() if a.key]
+
+ if q:
+ needle = q.lower()
+ entries = [
+ e
+ for e in entries
+ if needle in e.name.lower() or (e.email and needle in e.email.lower())
+ ]
+
+ sort_key = {
+ "files_owned": lambda e: e.files_owned,
+ "hotspots_owned": lambda e: e.hotspots_owned,
+ "commit_count_90d": lambda e: e.commit_count_90d,
+ "dead_code_lines_owned": lambda e: e.dead_code_lines_owned,
+ "bus_factor_risk_files": lambda e: e.bus_factor_risk_files,
+ }.get(sort, lambda e: e.files_owned)
+ entries.sort(key=sort_key, reverse=True)
+
+ total = len(entries)
+ page = entries[offset : offset + limit]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[OwnerListEntry](
+ items=page,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ )
+
+
+ "/{repo_id}/owners/{owner_key:path}",
+ response_model=OwnerProfileResponse,
+)
+async def get_owner(
+ repo_id: str,
+ owner_key: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> OwnerProfileResponse:
+ """Full profile for one contributor.
+
+ ``owner_key`` is either the contributor's email (preferred) or
+ ``name:<display name>`` for entries with no email recorded. URL-encoded
+ by the caller.
+ """
+
+ key = unquote(owner_key).strip().lower() if "@" in owner_key else unquote(owner_key)
+ accs, module_totals = await aggregate_owners(session, repo_id)
+ acc = accs.get(key)
+ if acc is None:
+ # Last-ditch fallback: case-insensitive lookup by name.
+ for cand in accs.values():
+ if cand.name.lower() == key.lower():
+ acc = cand
+ break
+ if acc is None:
+ raise HTTPException(status_code=404, detail="Owner not found")
+ return _to_profile(acc, module_totals)
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 4b71adb15..619513b2e 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -1173,3 +1173,142 @@ class WorkspaceGraphEdge(BaseModel):
class WorkspaceGraphResponse(BaseModel):
nodes: list[WorkspaceGraphNode] = []
edges: list[WorkspaceGraphEdge] = []
+
+
+# ---------------------------------------------------------------------------
+# Owner / Contributor profile
+# ---------------------------------------------------------------------------
+
+
+class OwnerListEntry(BaseModel):
+ """One row in the engineering-leader-facing owners directory."""
+
+ key: str # stable identifier for the URL (email if known, else name)
+ name: str
+ email: str | None
+ files_owned: int
+ hotspots_owned: int
+ silo_modules: int # modules where this owner is >80%
+ dead_code_files_owned: int
+ dead_code_lines_owned: int
+ commit_count_90d: int # sum of per-file 90d commits attributed to this person
+ last_commit_at: datetime | None
+ bus_factor_risk_files: int # files they own where bus_factor <= 1
+
+
+class OwnerModuleRollup(BaseModel):
+ module_path: str
+ file_count: int
+ hotspot_count: int
+ dominant_pct: float # share of files in module owned by this person
+
+
+class OwnerFileEntry(BaseModel):
+ file_path: str
+ commit_count_90d: int
+ churn_percentile: float # 0-100
+ bus_factor: int
+ is_hotspot: bool
+ last_commit_at: datetime | None
+ primary_owner_commit_pct: float | None
+
+
+class OwnerCoAuthor(BaseModel):
+ name: str
+ email: str | None
+ shared_files: int
+ co_change_strength: float # 0-1 fraction
+
+
+class OwnerProfileResponse(BaseModel):
+ key: str
+ name: str
+ email: str | None
+
+ # Headline metrics
+ files_owned: int
+ hotspots_owned: int
+ silo_modules: int
+ dead_code_files_owned: int
+ dead_code_lines_owned: int
+ commit_count_90d: int
+ last_commit_at: datetime | None
+ first_commit_at: datetime | None
+ bus_factor_risk_files: int
+
+ # 90d activity proxies (approximated from file-level totals weighted by
+ # this person's share of commits on each file). They are estimates, not
+ # exact per-author diff sizes — we never indexed per-author byte counts.
+ lines_added_90d_est: int
+ lines_deleted_90d_est: int
+
+ # Breakdowns
+ modules: list[OwnerModuleRollup]
+ top_files: list[OwnerFileEntry]
+ co_authors: list[OwnerCoAuthor]
+
+ # Commit-category mix across files they touch (sum of categories).
+ commit_categories: dict
+
+
+# ---------------------------------------------------------------------------
+# Module Health
+# ---------------------------------------------------------------------------
+
+
+class ModuleHealthOwner(BaseModel):
+ name: str
+ email: str | None
+ file_count: int
+ pct: float
+
+
+class ModuleHealthSummary(BaseModel):
+ """One row in the per-module health rollup."""
+
+ module_path: str
+ file_count: int
+ symbol_count: int
+ hotspot_count: int
+ dead_code_count: int
+ dead_code_lines: int
+ avg_churn_percentile: float # 0-100
+ median_bus_factor: float
+ min_bus_factor: int
+ primary_owner: str | None
+ primary_owner_pct: float
+ is_silo: bool
+ decision_count: int
+ doc_coverage_pct: float
+ # Composite 0–100 — higher = healthier (high docs, distributed ownership,
+ # low dead code, manageable churn). Used to rank modules at a glance.
+ health_score: float
+
+
+class ModuleHealthDetail(ModuleHealthSummary):
+ """Single-module deep view with breakdowns."""
+
+ owners: list[ModuleHealthOwner]
+ top_hotspots: list[str]
+ governing_decisions: list[str] # decision ids
+ contributor_count: int
+
+
+# ---------------------------------------------------------------------------
+# Reviewer Suggestions
+# ---------------------------------------------------------------------------
+
+
+class ReviewerSuggestion(BaseModel):
+ name: str
+ email: str | None
+ score: float # 0-1 composite
+ recent_commits: int # commits in the last 90d across the requested paths
+ owned_paths: list[str]
+ co_change_paths: list[str]
+ reasons: list[str]
+
+
+class ReviewerSuggestionsResponse(BaseModel):
+ paths: list[str]
+ suggestions: list[ReviewerSuggestion]
diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.py
new file mode 100644
index 000000000..552221805
--- /dev/null
+++ b/packages/server/src/repowise/server/services/module_health.py
@@ -0,0 +1,236 @@
+"""Module Health aggregator.
+
+Per-module rollup combining ownership, churn, dead code, docs, and
+decisions. No core ingestion changes — purely composes existing tables.
+
+A "module" is the top-level directory of a file path (matches the existing
+``OwnershipEntry`` convention). For nested module views we expose
+``module_path`` as the path prefix the caller passed in, which can be
+arbitrarily deep.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter, defaultdict
+from dataclasses import dataclass, field
+from statistics import median
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ DecisionRecord,
+ GitMetadata,
+ GraphNode,
+ WikiSymbol,
+)
+
+
+def _module_of(file_path: str) -> str:
+ parts = file_path.split("/", 1)
+ return parts[0] if len(parts) > 1 else "root"
+
+
+def _under_module(file_path: str, module_path: str) -> bool:
+ if module_path in ("", "root"):
+ return "/" not in file_path
+ return file_path == module_path or file_path.startswith(module_path + "/")
+
+
+@dataclass
+class _ModuleAccumulator:
+ module_path: str
+ files: list[GitMetadata] = field(default_factory=list)
+ symbol_count: int = 0
+ doc_covered_symbols: int = 0
+ dead_code_count: int = 0
+ dead_code_lines: int = 0
+ owners: Counter = field(default_factory=Counter)
+ owner_emails: dict[str, str | None] = field(default_factory=dict)
+ contributors: set[str] = field(default_factory=set)
+ decision_ids: list[str] = field(default_factory=list)
+ top_hotspot_paths: list[tuple[float, str]] = field(default_factory=list)
+
+
+def _score(acc: _ModuleAccumulator) -> dict:
+ file_count = len(acc.files)
+ hotspot_count = sum(1 for m in acc.files if m.is_hotspot)
+ dead_pct = (acc.dead_code_count / file_count) if file_count else 0.0
+ doc_pct = (
+ acc.doc_covered_symbols / acc.symbol_count if acc.symbol_count else 0.0
+ )
+
+ bus_factors = [m.bus_factor or 0 for m in acc.files]
+ med_bus = float(median(bus_factors)) if bus_factors else 0.0
+ min_bus = min(bus_factors) if bus_factors else 0
+ avg_churn = (
+ sum(m.churn_percentile or 0.0 for m in acc.files) / file_count * 100.0
+ if file_count
+ else 0.0
+ )
+
+ primary_owner, primary_pct = None, 0.0
+ if acc.owners:
+ name, cnt = acc.owners.most_common(1)[0]
+ primary_owner = name
+ primary_pct = cnt / file_count if file_count else 0.0
+
+ # Composite health (0–100). Higher is better. Weighted:
+ # -25 if siloed (>80% one owner)
+ # -20 * (hotspot_count / file_count)
+ # -25 * dead_pct
+ # -15 * (avg_churn / 100)
+ # +15 * doc_pct
+ # +10 if bus_factor >= 2 median, else -10
+ score = 100.0
+ if primary_pct > 0.8:
+ score -= 25
+ if file_count:
+ score -= 20 * (hotspot_count / file_count)
+ score -= 25 * dead_pct
+ score -= 15 * (avg_churn / 100.0)
+ score += 15 * doc_pct
+ score += 10 if med_bus >= 2 else -10
+ score = max(0.0, min(100.0, score))
+
+ return {
+ "file_count": file_count,
+ "symbol_count": acc.symbol_count,
+ "hotspot_count": hotspot_count,
+ "dead_code_count": acc.dead_code_count,
+ "dead_code_lines": acc.dead_code_lines,
+ "avg_churn_percentile": avg_churn,
+ "median_bus_factor": med_bus,
+ "min_bus_factor": min_bus,
+ "primary_owner": primary_owner,
+ "primary_owner_pct": primary_pct,
+ "is_silo": primary_pct > 0.8,
+ "decision_count": len(acc.decision_ids),
+ "doc_coverage_pct": doc_pct * 100.0,
+ "health_score": score,
+ }
+
+
+async def aggregate_modules(
+ session: AsyncSession, repo_id: str
+) -> dict[str, _ModuleAccumulator]:
+ """Single-pass aggregator. O(files + symbols + dead + decisions)."""
+
+ files = (
+ await session.execute(
+ select(GitMetadata).where(GitMetadata.repository_id == repo_id)
+ )
+ ).scalars().all()
+
+ accs: dict[str, _ModuleAccumulator] = defaultdict(
+ lambda: _ModuleAccumulator(module_path="")
+ )
+
+ for m in files:
+ mod = _module_of(m.file_path)
+ acc = accs[mod]
+ if not acc.module_path:
+ acc.module_path = mod
+ acc.files.append(m)
+ if m.primary_owner_name:
+ acc.owners[m.primary_owner_name] += 1
+ acc.owner_emails.setdefault(m.primary_owner_name, m.primary_owner_email)
+ # Authors -> contributors set
+ try:
+ for a in json.loads(m.top_authors_json or "[]"):
+ if a.get("name"):
+ acc.contributors.add(a["name"])
+ except json.JSONDecodeError:
+ pass
+ if m.is_hotspot:
+ acc.top_hotspot_paths.append(
+ ((m.temporal_hotspot_score or 0.0), m.file_path)
+ )
+
+ # Symbols + docs by module.
+ sym_rows = (
+ await session.execute(
+ select(
+ WikiSymbol.file_path,
+ WikiSymbol.docstring,
+ ).where(WikiSymbol.repository_id == repo_id)
+ )
+ ).all()
+ for path, doc in sym_rows:
+ mod = _module_of(path)
+ acc = accs.get(mod)
+ if acc is None:
+ continue
+ acc.symbol_count += 1
+ if doc and str(doc).strip():
+ acc.doc_covered_symbols += 1
+
+ # Dead-code findings by module.
+ dead_rows = (
+ await session.execute(
+ select(DeadCodeFinding.file_path, DeadCodeFinding.lines).where(
+ DeadCodeFinding.repository_id == repo_id
+ )
+ )
+ ).all()
+ for path, lines in dead_rows:
+ mod = _module_of(path)
+ acc = accs.get(mod)
+ if acc is None:
+ continue
+ acc.dead_code_count += 1
+ acc.dead_code_lines += int(lines or 0)
+
+ # Decisions by affected module.
+ decisions = (
+ await session.execute(
+ select(
+ DecisionRecord.id, DecisionRecord.affected_modules_json
+ ).where(DecisionRecord.repository_id == repo_id)
+ )
+ ).all()
+ for did, modules_json in decisions:
+ try:
+ mods = json.loads(modules_json or "[]")
+ except json.JSONDecodeError:
+ mods = []
+ for mod in mods:
+ acc = accs.get(mod)
+ if acc is not None:
+ acc.decision_ids.append(did)
+
+ return accs
+
+
+def summarize(acc: _ModuleAccumulator) -> dict:
+ """Flatten accumulator to summary fields (matches ModuleHealthSummary)."""
+
+ out = _score(acc)
+ out["module_path"] = acc.module_path
+ return out
+
+
+def detail_extras(acc: _ModuleAccumulator) -> dict:
+ """Extras only present in ModuleHealthDetail."""
+
+ acc.top_hotspot_paths.sort(reverse=True)
+ return {
+ "owners": [
+ {
+ "name": name,
+ "email": acc.owner_emails.get(name),
+ "file_count": cnt,
+ "pct": cnt / len(acc.files) if acc.files else 0.0,
+ }
+ for name, cnt in acc.owners.most_common(20)
+ ],
+ "top_hotspots": [p for _, p in acc.top_hotspot_paths[:10]],
+ "governing_decisions": acc.decision_ids,
+ "contributor_count": len(acc.contributors),
+ }
+
+
+# Avoid unused-import warning — GraphNode is reserved for future fan-in.
+_ = GraphNode
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
new file mode 100644
index 000000000..7ea596f55
--- /dev/null
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -0,0 +1,251 @@
+"""Owner / contributor aggregation service.
+
+Composes a "what does this person do in the codebase" picture from existing
+``GitMetadata`` + ``DeadCodeFinding`` rows. Pure aggregation — no schema
+changes to core ingestion.
+
+A few notes on identity:
+- We key owners by *email when known* (much more stable than name across
+ rename / unicode / encoding differences) and fall back to ``name:<name>``
+ when the GitMetadata row only carries a display name.
+- The exposed ``key`` is URL-safe (we strip ``+`` / ``@`` only at the
+ router layer — the service deals with the canonical form).
+- ``top_authors_json`` is the authoritative source of attribution: it lists
+ every (name, email, commit_count) per file. Walking it is O(files * 50)
+ in the worst case, which is fine for repos in the 10k-file range.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter, defaultdict
+from dataclasses import dataclass, field
+from datetime import datetime
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import DeadCodeFinding, GitMetadata
+
+
+# ---------------------------------------------------------------------------
+# Identity
+# ---------------------------------------------------------------------------
+
+
+def owner_key(name: str | None, email: str | None) -> str:
+ """Return the canonical key for an (name, email) pair.
+
+ Prefer email; fall back to a ``name:`` prefix so we never collide a
+ name with someone else's email.
+ """
+
+ if email:
+ return email.strip().lower()
+ if name:
+ return f"name:{name.strip()}"
+ return ""
+
+
+def _module_of(file_path: str) -> str:
+ parts = file_path.split("/", 1)
+ return parts[0] if len(parts) > 1 else "root"
+
+
+# ---------------------------------------------------------------------------
+# Per-owner accumulators
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _OwnerAccumulator:
+ key: str
+ name: str
+ email: str | None = None
+
+ files_owned: int = 0 # files where this person is primary_owner
+ hotspots_owned: int = 0
+ bus_factor_risk_files: int = 0
+ commit_count_90d: int = 0
+ lines_added_90d_est: float = 0.0
+ lines_deleted_90d_est: float = 0.0
+
+ last_commit_at: datetime | None = None
+ first_commit_at: datetime | None = None
+
+ # file_path -> attributed commit count (90d-ish, from top_authors_json)
+ files_touched: dict[str, int] = field(default_factory=dict)
+ file_meta: dict[str, GitMetadata] = field(default_factory=dict)
+
+ # module rollup
+ module_files: dict[str, int] = field(default_factory=lambda: defaultdict(int))
+ module_hotspots: dict[str, int] = field(default_factory=lambda: defaultdict(int))
+
+ commit_categories: Counter[str] = field(default_factory=Counter)
+
+ dead_code_files: set[str] = field(default_factory=set)
+ dead_code_lines: int = 0
+
+ # co-author tally: other_key -> shared file count
+ coauthor_shared: Counter[str] = field(default_factory=Counter)
+ coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+async def aggregate_owners(
+ session: AsyncSession, repo_id: str
+) -> tuple[dict[str, _OwnerAccumulator], dict[str, int]]:
+ """Walk all GitMetadata rows once, returning per-owner accumulators.
+
+ Hot-path: O(files * top_authors_per_file). top_authors is capped at 50
+ by the indexer, so this is linear in repo size.
+ """
+
+ rows = (
+ await session.execute(
+ select(GitMetadata).where(GitMetadata.repository_id == repo_id)
+ )
+ ).scalars().all()
+
+ accs: dict[str, _OwnerAccumulator] = {}
+ module_totals: dict[str, int] = defaultdict(int)
+
+ def _ensure(name: str, email: str | None) -> _OwnerAccumulator:
+ k = owner_key(name, email)
+ if not k:
+ return _OwnerAccumulator(key="", name=name or "(unknown)", email=email)
+ acc = accs.get(k)
+ if acc is None:
+ acc = _OwnerAccumulator(key=k, name=name or (email or ""), email=email)
+ accs[k] = acc
+ # Promote a richer display name if we learn one later.
+ if name and (not acc.name or acc.name == acc.email):
+ acc.name = name
+ if email and not acc.email:
+ acc.email = email
+ return acc
+
+ # Pass 1: per-file walk.
+ for m in rows:
+ # All authors of this file (capped at 50 by indexer).
+ try:
+ authors = json.loads(m.top_authors_json or "[]")
+ except json.JSONDecodeError:
+ authors = []
+
+ module = _module_of(m.file_path)
+ module_totals[module] += 1
+ categories: dict[str, int] = {}
+ try:
+ categories = json.loads(m.commit_categories_json or "{}")
+ except json.JSONDecodeError:
+ pass
+
+ total_file_commits = sum(int(a.get("commit_count", 0)) for a in authors) or 1
+ added = m.lines_added_90d or 0
+ deleted = m.lines_deleted_90d or 0
+ commits_90d = m.commit_count_90d or 0
+
+ # Track everyone who touched this file — for co-author tallies we
+ # need the full list.
+ touchers: list[_OwnerAccumulator] = []
+ for a in authors:
+ name = a.get("name") or ""
+ email = a.get("email") or None
+ cnt = int(a.get("commit_count", 0))
+ acc = _ensure(name, email)
+ if not acc.key:
+ continue
+ share = cnt / total_file_commits
+ acc.files_touched[m.file_path] = cnt
+ acc.file_meta[m.file_path] = m
+ acc.commit_count_90d += min(cnt, commits_90d) if commits_90d else 0
+ acc.lines_added_90d_est += added * share
+ acc.lines_deleted_90d_est += deleted * share
+ for cat, n in categories.items():
+ acc.commit_categories[cat] += int(n * share)
+ if m.last_commit_at:
+ if acc.last_commit_at is None or m.last_commit_at > acc.last_commit_at:
+ acc.last_commit_at = m.last_commit_at
+ if m.first_commit_at:
+ if acc.first_commit_at is None or m.first_commit_at < acc.first_commit_at:
+ acc.first_commit_at = m.first_commit_at
+ touchers.append(acc)
+
+ # Primary owner — credit them for "files_owned" / hotspots / silo.
+ primary = _ensure(m.primary_owner_name or "", m.primary_owner_email)
+ if primary.key:
+ primary.files_owned += 1
+ primary.module_files[module] += 1
+ if m.is_hotspot:
+ primary.hotspots_owned += 1
+ primary.module_hotspots[module] += 1
+ if (m.bus_factor or 0) <= 1:
+ primary.bus_factor_risk_files += 1
+
+ # Co-author tally — each pair of distinct touchers shares this file.
+ for i, a in enumerate(touchers):
+ for b in touchers[i + 1 :]:
+ if a.key == b.key:
+ continue
+ a.coauthor_shared[b.key] += 1
+ a.coauthor_meta[b.key] = (b.name, b.email)
+ b.coauthor_shared[a.key] += 1
+ b.coauthor_meta[a.key] = (a.name, a.email)
+
+ # Pass 2: dead-code burden by primary_owner.
+ dead_rows = (
+ await session.execute(
+ select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repo_id)
+ )
+ ).scalars().all()
+ for d in dead_rows:
+ if not d.primary_owner:
+ continue
+ # DeadCodeFinding.primary_owner only carries the display name.
+ acc = accs.get(owner_key(d.primary_owner, None))
+ # If no email-keyed bucket exists, also try name lookup against
+ # accumulators whose name matches (best-effort).
+ if acc is None:
+ for cand in accs.values():
+ if cand.name == d.primary_owner:
+ acc = cand
+ break
+ if acc is None:
+ continue
+ acc.dead_code_files.add(d.file_path)
+ acc.dead_code_lines += d.lines or 0
+
+ return accs, dict(module_totals)
+
+
+# ---------------------------------------------------------------------------
+# Shape helpers — turn accumulators into response models.
+# ---------------------------------------------------------------------------
+
+
+def silo_modules(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> int:
+ """Count modules where this owner is >80% of file ownership."""
+
+ siloed = 0
+ for mod, owned in acc.module_files.items():
+ total = module_totals.get(mod, 0)
+ if total > 0 and owned / total > 0.8:
+ siloed += 1
+ return siloed
+
+
+def module_share(
+ acc: _OwnerAccumulator, module_totals: dict[str, int]
+) -> dict[str, float]:
+ """Per-module share of files owned by this person (0–1)."""
+
+ out: dict[str, float] = {}
+ for mod, owned in acc.module_files.items():
+ total = module_totals.get(mod, 0)
+ out[mod] = owned / total if total else 0.0
+ return out
diff --git a/packages/server/src/repowise/server/services/reviewer_suggestions.py b/packages/server/src/repowise/server/services/reviewer_suggestions.py
new file mode 100644
index 000000000..b9f973eb1
--- /dev/null
+++ b/packages/server/src/repowise/server/services/reviewer_suggestions.py
@@ -0,0 +1,149 @@
+"""Reviewer suggestion service.
+
+Given a set of changed file paths, suggest who should review the PR. The
+composite score blends three signals — all already computed during indexing:
+
+ - Ownership: appearance in ``top_authors_json`` of the touched files,
+ weighted by share of file commits.
+ - Co-change: ownership of files that historically co-change with the
+ touched paths (``co_change_partners_json``).
+ - Recency: weight commit count by the file's 90-day activity so people
+ who *just* worked here outrank people who touched the file in 2018.
+
+The output is intentionally short (top 10) — PRs with 30 suggested reviewers
+are no better than zero.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import defaultdict
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import GitMetadata
+from repowise.server.schemas import ReviewerSuggestion
+
+
+# Tunable weights.
+_W_DIRECT = 1.0
+_W_COCHANGE = 0.5
+_W_RECENT = 0.4
+
+
+async def suggest_reviewers(
+ session: AsyncSession,
+ repo_id: str,
+ paths: list[str],
+ limit: int = 10,
+) -> list[ReviewerSuggestion]:
+ if not paths:
+ return []
+
+ # 1) Direct ownership for the touched paths.
+ direct_rows = (
+ await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(paths),
+ )
+ )
+ ).scalars().all()
+
+ # 2) For each touched path, look up its co-change partners (cap to 5
+ # strongest per file to keep the suggestion noise low) and fetch their
+ # GitMetadata as well.
+ cochange_paths: set[str] = set()
+ cochange_partners: dict[str, list[str]] = defaultdict(list)
+ for m in direct_rows:
+ try:
+ partners = json.loads(m.co_change_partners_json or "[]")
+ except json.JSONDecodeError:
+ partners = []
+ partners.sort(key=lambda p: p.get("co_change_count", 0), reverse=True)
+ for p in partners[:5]:
+ other = p.get("file_path")
+ if other:
+ cochange_paths.add(other)
+ cochange_partners[other].append(m.file_path)
+
+ cochange_rows = []
+ if cochange_paths:
+ cochange_rows = (
+ await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(cochange_paths),
+ )
+ )
+ ).scalars().all()
+
+ # Per-author tally.
+ tally: dict[str, dict] = {}
+
+ def _bump(name: str, email: str | None, *, score: float, recent: int, path: str, reason: str, owned: bool) -> None:
+ key = (email or "").strip().lower() or f"name:{name.strip()}"
+ slot = tally.setdefault(
+ key,
+ {
+ "name": name,
+ "email": email,
+ "score": 0.0,
+ "recent_commits": 0,
+ "owned_paths": set(),
+ "co_change_paths": set(),
+ "reasons": set(),
+ },
+ )
+ slot["score"] += score
+ slot["recent_commits"] += recent
+ if owned:
+ slot["owned_paths"].add(path)
+ else:
+ slot["co_change_paths"].add(path)
+ slot["reasons"].add(reason)
+
+ def _process(rows, *, weight: float, owned: bool, reason: str) -> None:
+ for m in rows:
+ try:
+ authors = json.loads(m.top_authors_json or "[]")
+ except json.JSONDecodeError:
+ continue
+ total = sum(int(a.get("commit_count", 0)) for a in authors) or 1
+ commits_90d = m.commit_count_90d or 0
+ for a in authors:
+ cnt = int(a.get("commit_count", 0))
+ share = cnt / total
+ # Recency: commits_90d weighted by share is a rough estimate
+ # of how much each author contributed recently.
+ recent = int(commits_90d * share)
+ score = weight * share + _W_RECENT * (recent / max(commits_90d, 1))
+ _bump(
+ a.get("name", ""),
+ a.get("email") or None,
+ score=score,
+ recent=recent,
+ path=m.file_path,
+ reason=reason,
+ owned=owned,
+ )
+
+ _process(direct_rows, weight=_W_DIRECT, owned=True, reason="touched")
+ _process(cochange_rows, weight=_W_COCHANGE, owned=False, reason="co-change history")
+
+ suggestions = []
+ for slot in tally.values():
+ suggestions.append(
+ ReviewerSuggestion(
+ name=slot["name"],
+ email=slot["email"],
+ score=round(slot["score"], 4),
+ recent_commits=slot["recent_commits"],
+ owned_paths=sorted(slot["owned_paths"])[:10],
+ co_change_paths=sorted(slot["co_change_paths"])[:10],
+ reasons=sorted(slot["reasons"]),
+ )
+ )
+ suggestions.sort(key=lambda s: s.score, reverse=True)
+ return suggestions[:limit]
diff --git a/packages/types/package.json b/packages/types/package.json
index ea790c5b3..9a4803beb 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -20,7 +20,9 @@
"./blast-radius": "./src/blast-radius.ts",
"./jobs": "./src/jobs.ts",
"./settings": "./src/settings.ts",
- "./security": "./src/security.ts"
+ "./security": "./src/security.ts",
+ "./owners": "./src/owners.ts",
+ "./modules": "./src/modules.ts"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com",
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index b03a0975a..6d586c35d 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -20,3 +20,5 @@ export * from "./blast-radius.js";
export * from "./jobs.js";
export * from "./settings.js";
export * from "./security.js";
+export * from "./owners.js";
+export * from "./modules.js";
diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.ts
new file mode 100644
index 000000000..3b13e3bfd
--- /dev/null
+++ b/packages/types/src/modules.ts
@@ -0,0 +1,49 @@
+/**
+ * Module-health types. Mirrors `/api/repos/{id}/modules/health`.
+ *
+ * A "module" is the top-level path prefix in the existing OwnershipEntry
+ * convention — typically a top-level directory.
+ */
+
+export interface ModuleHealthOwner {
+ name: string;
+ email: string | null;
+ file_count: number;
+ pct: number;
+}
+
+export interface ModuleHealthSummary {
+ module_path: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count: number;
+ dead_code_count: number;
+ dead_code_lines: number;
+ avg_churn_percentile: number;
+ median_bus_factor: number;
+ min_bus_factor: number;
+ primary_owner: string | null;
+ primary_owner_pct: number;
+ is_silo: boolean;
+ decision_count: number;
+ doc_coverage_pct: number;
+ /** 0–100 — higher is healthier. */
+ health_score: number;
+}
+
+export interface ModuleHealthDetail extends ModuleHealthSummary {
+ owners: ModuleHealthOwner[];
+ top_hotspots: string[];
+ governing_decisions: string[];
+ contributor_count: number;
+}
+
+export interface ReviewerSuggestion {
+ name: string;
+ email: string | null;
+ score: number;
+ recent_commits: number;
+ owned_paths: string[];
+ co_change_paths: string[];
+ reasons: string[];
+}
diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.ts
new file mode 100644
index 000000000..6d5fb7299
--- /dev/null
+++ b/packages/types/src/owners.ts
@@ -0,0 +1,68 @@
+/**
+ * Owner / contributor profile types — engineering-leader view of who does
+ * what in the codebase. Mirrors the Pydantic models served by
+ * `/api/repos/{id}/owners` and `/api/repos/{id}/owners/{key}`.
+ */
+
+export interface OwnerListEntry {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ bus_factor_risk_files: number;
+}
+
+export interface OwnerModuleRollup {
+ module_path: string;
+ file_count: number;
+ hotspot_count: number;
+ /** Share of this module's files owned by this person (0–1). */
+ dominant_pct: number;
+}
+
+export interface OwnerFileEntry {
+ file_path: string;
+ commit_count_90d: number;
+ /** 0–100 percentile rank. */
+ churn_percentile: number;
+ bus_factor: number;
+ is_hotspot: boolean;
+ last_commit_at: string | null;
+ primary_owner_commit_pct: number | null;
+}
+
+export interface OwnerCoAuthor {
+ name: string;
+ email: string | null;
+ shared_files: number;
+ /** Shared-files / total-files-touched (0–1). */
+ co_change_strength: number;
+}
+
+export interface OwnerProfile {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ first_commit_at: string | null;
+ bus_factor_risk_files: number;
+ /** Estimated, not exact — see Pydantic doc. */
+ lines_added_90d_est: number;
+ lines_deleted_90d_est: number;
+ modules: OwnerModuleRollup[];
+ top_files: OwnerFileEntry[];
+ co_authors: OwnerCoAuthor[];
+ commit_categories: Record<string, number>;
+}
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 5bdbe0177..c3ccd1cb4 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -30,6 +30,10 @@
"./docs/*": "./src/docs/*.tsx",
"./symbols": "./src/symbols/index.ts",
"./symbols/*": "./src/symbols/*.tsx",
+ "./owners": "./src/owners/index.ts",
+ "./owners/*": "./src/owners/*.tsx",
+ "./modules": "./src/modules/index.ts",
+ "./modules/*": "./src/modules/*.tsx",
"./coverage": "./src/coverage/index.ts",
"./coverage/*": "./src/coverage/*.tsx",
"./wiki": "./src/wiki/index.ts",
diff --git a/packages/ui/src/git/index.ts b/packages/ui/src/git/index.ts
index d4b9faf79..be9f41dc8 100644
--- a/packages/ui/src/git/index.ts
+++ b/packages/ui/src/git/index.ts
@@ -12,3 +12,4 @@ export * from "./ownership-treemap.js";
export * from "./risk-distribution-chart.js";
export * from "./hotspot-trend-strip.js";
export * from "./churn-vs-bus-factor-scatter.js";
+export * from "./reviewer-suggestions.js";
diff --git a/packages/ui/src/git/ownership-treemap.tsx b/packages/ui/src/git/ownership-treemap.tsx
index f70c65ed7..3a6baa7d0 100644
--- a/packages/ui/src/git/ownership-treemap.tsx
+++ b/packages/ui/src/git/ownership-treemap.tsx
@@ -6,6 +6,27 @@ import type { OwnershipEntry } from "@repowise-dev/types/git";
interface OwnershipTreemapProps {
entries: OwnershipEntry[];
+ /**
+ * Optional bus-factor lookup keyed by `module_path`. When provided, the
+ * tile border is colored: red for ≤1 (single-owner), amber for 2, green
+ * for ≥3. Silo dashing still wins over the green case so high-share
+ * modules still scream visually.
+ */
+ busFactorByModule?: Record<string, number>;
+ /** Optional click handler — useful for routing to module health detail. */
+ onSelect?: (entry: OwnershipEntry) => void;
+}
+
+function busFactorStroke(bf: number | undefined, isSilo: boolean): {
+ stroke: string;
+ width: number;
+ dash: string;
+} {
+ if (isSilo) return { stroke: "#f59520", width: 2, dash: "4 2" };
+ if (bf === undefined) return { stroke: "none", width: 0, dash: "none" };
+ if (bf <= 1) return { stroke: "#ef4444", width: 2, dash: "none" };
+ if (bf === 2) return { stroke: "#f59520", width: 1.5, dash: "none" };
+ return { stroke: "#22c55e", width: 1, dash: "none" };
}
const OWNER_COLORS = [
@@ -31,9 +52,10 @@ interface TooltipData {
fileCount: number;
pct: number | null;
isSilo: boolean;
+ busFactor: number | null;
}
-export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
+export function OwnershipTreemap({ entries, busFactorByModule, onSelect }: OwnershipTreemapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [dims, setDims] = useState({ width: 600, height: 320 });
const [tooltip, setTooltip] = useState<TooltipData | null>(null);
@@ -52,7 +74,7 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
}, []);
const handleMouseMove = useCallback(
- (e: React.MouseEvent, d: { name: string; owner: string | null; fileCount: number; pct: number | null; isSilo: boolean }) => {
+ (e: React.MouseEvent, d: { name: string; owner: string | null; fileCount: number; pct: number | null; isSilo: boolean; busFactor: number | null }) => {
const rect = containerRef.current?.getBoundingClientRect();
if (!rect) return;
setTooltip({
@@ -111,6 +133,9 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
const h = leaf.y1 - y0;
const showLabel = w > 50 && h > 28;
+ const bf = busFactorByModule?.[d.name];
+ const stroke = busFactorStroke(bf, d.isSilo ?? false);
+ const entry = entries.find((e) => e.module_path === d.name);
return (
<g
key={d.name}
@@ -121,9 +146,12 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
fileCount: leaf.value || 0,
pct: d.pct ?? null,
isSilo: d.isSilo ?? false,
+ busFactor: bf ?? null,
})
}
onMouseLeave={() => setTooltip(null)}
+ onClick={() => entry && onSelect?.(entry)}
+ className={onSelect ? "cursor-pointer" : undefined}
>
<rect
x={x0}
@@ -133,9 +161,9 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
fill={ownerColor(d.owner ?? null)}
opacity={0.8}
rx={3}
- stroke={d.isSilo ? "#f59520" : "none"}
- strokeWidth={d.isSilo ? 2 : 0}
- strokeDasharray={d.isSilo ? "4 2" : "none"}
+ stroke={stroke.stroke}
+ strokeWidth={stroke.width}
+ strokeDasharray={stroke.dash}
className="transition-opacity hover:opacity-100"
/>
{showLabel && (
@@ -181,11 +209,48 @@ export function OwnershipTreemap({ entries }: OwnershipTreemapProps) {
{tooltip.pct != null && ` (${Math.round(tooltip.pct * 100)}%)`}
</p>
<p className="text-[var(--color-text-secondary)]">{tooltip.fileCount} files</p>
+ {tooltip.busFactor != null && (
+ <p
+ className={
+ tooltip.busFactor <= 1
+ ? "text-red-400 font-medium mt-0.5"
+ : tooltip.busFactor === 2
+ ? "text-amber-300 font-medium mt-0.5"
+ : "text-emerald-300 mt-0.5"
+ }
+ >
+ Bus factor: {tooltip.busFactor}
+ </p>
+ )}
{tooltip.isSilo && (
<p className="text-yellow-400 font-medium mt-0.5">Silo risk</p>
)}
</div>
)}
+
+ {busFactorByModule && (
+ <div className="mt-2 flex flex-wrap items-center gap-3 text-[10px] text-[var(--color-text-tertiary)]">
+ <span className="flex items-center gap-1">
+ <span className="inline-block h-2 w-3 rounded-sm border-2" style={{ borderColor: "#ef4444" }} />
+ bus ≤ 1
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="inline-block h-2 w-3 rounded-sm border-2" style={{ borderColor: "#f59520" }} />
+ bus = 2
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="inline-block h-2 w-3 rounded-sm border-2" style={{ borderColor: "#22c55e" }} />
+ bus ≥ 3
+ </span>
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block h-2 w-3 rounded-sm border-2"
+ style={{ borderColor: "#f59520", borderStyle: "dashed" }}
+ />
+ silo (&gt;80% owner)
+ </span>
+ </div>
+ )}
</div>
);
}
diff --git a/packages/ui/src/git/reviewer-suggestions.tsx b/packages/ui/src/git/reviewer-suggestions.tsx
new file mode 100644
index 000000000..9becfa3be
--- /dev/null
+++ b/packages/ui/src/git/reviewer-suggestions.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import { GitPullRequest, Sparkles } from "lucide-react";
+import type { ReviewerSuggestion } from "@repowise-dev/types/modules";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { Badge } from "../ui/badge";
+import { Skeleton } from "../ui/skeleton";
+import { OwnerAvatar } from "../owners/owner-avatar";
+import { cn } from "../lib/cn";
+
+export interface ReviewerSuggestionsProps {
+ suggestions: ReviewerSuggestion[];
+ isLoading?: boolean;
+ /** Optional callback when a suggested reviewer is selected. */
+ onSelect?: (s: ReviewerSuggestion) => void;
+ /** Optional sub-title — used to mention which paths drove the suggestions. */
+ subtitle?: string;
+}
+
+/**
+ * Suggested reviewers for a code change, derived from `top_authors_json` and
+ * `co_change_partners_json` already produced by the indexer. Renders the
+ * top N with a normalized confidence bar so it's clear who is the
+ * "obvious" reviewer vs. a long-tail candidate.
+ */
+export function ReviewerSuggestions({
+ suggestions,
+ isLoading,
+ onSelect,
+ subtitle,
+}: ReviewerSuggestionsProps) {
+ const max = Math.max(0.0001, ...suggestions.map((s) => s.score));
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <GitPullRequest className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ Suggested reviewers
+ </CardTitle>
+ {subtitle && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">{subtitle}</p>
+ )}
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1.5">
+ {isLoading && (
+ <div className="space-y-2">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-12 w-full" />
+ ))}
+ </div>
+ )}
+
+ {!isLoading && suggestions.length === 0 && (
+ <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
+ No reviewer signal for the selected paths yet.
+ </p>
+ )}
+
+ {!isLoading &&
+ suggestions.map((s, i) => {
+ const pct = (s.score / max) * 100;
+ return (
+ <button
+ key={s.email ?? s.name}
+ onClick={() => onSelect?.(s)}
+ className="flex w-full items-center gap-3 rounded-md px-2 py-1.5 text-left hover:bg-[var(--color-bg-elevated)]"
+ >
+ <span className="w-4 text-center text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {i + 1}
+ </span>
+ <OwnerAvatar name={s.name} email={s.email} size="sm" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-xs font-medium text-[var(--color-text-primary)]">
+ {s.name}
+ </span>
+ {i === 0 && (
+ <Badge variant="accent" className="text-[10px]">
+ <Sparkles className="mr-0.5 h-2.5 w-2.5" /> top match
+ </Badge>
+ )}
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-1 text-[10px] text-[var(--color-text-tertiary)]">
+ {s.recent_commits > 0 && (
+ <span>{s.recent_commits} commits / 90d</span>
+ )}
+ {s.owned_paths.length > 0 && (
+ <span>· touches {s.owned_paths.length}</span>
+ )}
+ {s.co_change_paths.length > 0 && (
+ <span>· co-changes {s.co_change_paths.length}</span>
+ )}
+ </div>
+ </div>
+ <div className="h-1 w-16 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className={cn(
+ "h-full",
+ i === 0 ? "bg-[var(--color-accent-primary)]" : "bg-[var(--color-text-tertiary)]/50",
+ )}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ </button>
+ );
+ })}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/modules/index.ts b/packages/ui/src/modules/index.ts
new file mode 100644
index 000000000..e990be9b4
--- /dev/null
+++ b/packages/ui/src/modules/index.ts
@@ -0,0 +1,3 @@
+export * from "./module-health-card.js";
+export * from "./module-health-list.js";
+export * from "./module-health-detail.js";
diff --git a/packages/ui/src/modules/module-health-card.tsx b/packages/ui/src/modules/module-health-card.tsx
new file mode 100644
index 000000000..573becd4a
--- /dev/null
+++ b/packages/ui/src/modules/module-health-card.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { Folder, Flame, Trash2, BookOpen, Users, ShieldAlert, Lightbulb } from "lucide-react";
+import type { ModuleHealthSummary } from "@repowise-dev/types/modules";
+import { Card, CardContent } from "../ui/card";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+
+interface ModuleHealthCardProps {
+ module: ModuleHealthSummary;
+ onClick?: ((m: ModuleHealthSummary) => void) | undefined;
+ compact?: boolean | undefined;
+}
+
+function scoreClass(score: number): string {
+ if (score >= 70) return "text-emerald-300 bg-emerald-500/10 border-emerald-500/40";
+ if (score >= 40) return "text-amber-300 bg-amber-500/10 border-amber-500/40";
+ return "text-red-300 bg-red-500/10 border-red-500/40";
+}
+
+/**
+ * Single module health card — at-a-glance summary of churn, owners, dead
+ * code, docs and decisions for one module. Sized for a 3-column grid.
+ */
+export function ModuleHealthCard({ module, onClick, compact }: ModuleHealthCardProps) {
+ const score = Math.round(module.health_score);
+ return (
+ <Card
+ onClick={() => onClick?.(module)}
+ className={cn(
+ "group transition-all",
+ onClick && "cursor-pointer hover:border-[var(--color-border-hover)]",
+ )}
+ >
+ <CardContent className={compact ? "p-3" : "p-4"}>
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 text-sm font-semibold text-[var(--color-text-primary)]">
+ <Folder className="h-4 w-4 text-[var(--color-text-tertiary)]" />
+ <span className="truncate">{module.module_path}</span>
+ </div>
+ <p className="mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">
+ {module.file_count} files · {module.symbol_count} symbols
+ </p>
+ </div>
+ <div
+ className={cn(
+ "rounded-md border px-2 py-1 text-center",
+ scoreClass(module.health_score),
+ )}
+ title="Composite health score — see module health doc"
+ >
+ <div className="text-lg font-bold leading-none tabular-nums">{score}</div>
+ <div className="text-[9px] uppercase tracking-wider opacity-70">health</div>
+ </div>
+ </div>
+
+ <div className="mt-3 grid grid-cols-3 gap-2 text-xs">
+ <Metric icon={<Flame className="h-3 w-3 text-orange-400" />} label="Hotspots" value={module.hotspot_count} />
+ <Metric icon={<Trash2 className="h-3 w-3 text-rose-400" />} label="Dead lines" value={module.dead_code_lines} />
+ <Metric icon={<BookOpen className="h-3 w-3 text-sky-400" />} label="Doc" value={`${Math.round(module.doc_coverage_pct)}%`} />
+ <Metric icon={<Users className="h-3 w-3 text-violet-400" />} label="Bus med" value={module.median_bus_factor.toFixed(1)} />
+ <Metric icon={<ShieldAlert className="h-3 w-3 text-red-400" />} label="Bus min" value={module.min_bus_factor} />
+ <Metric icon={<Lightbulb className="h-3 w-3 text-yellow-400" />} label="Decisions" value={module.decision_count} />
+ </div>
+
+ <div className="mt-3 flex items-center justify-between text-[11px]">
+ <span className="truncate text-[var(--color-text-secondary)]">
+ {module.primary_owner ?? "—"}
+ {module.primary_owner && (
+ <span className="ml-1 text-[var(--color-text-tertiary)]">
+ {Math.round(module.primary_owner_pct * 100)}%
+ </span>
+ )}
+ </span>
+ <div className="flex items-center gap-1">
+ {module.is_silo && (
+ <Badge variant="outdated" className="text-[10px]">
+ silo
+ </Badge>
+ )}
+ <Badge variant="outline" className="text-[10px]">
+ churn {Math.round(module.avg_churn_percentile)}
+ </Badge>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+function Metric({
+ icon,
+ label,
+ value,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ value: string | number;
+}) {
+ return (
+ <div>
+ <div className="flex items-center gap-0.5 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {icon}
+ {label}
+ </div>
+ <div className="tabular-nums font-semibold text-[var(--color-text-primary)]">{value}</div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/modules/module-health-detail.tsx b/packages/ui/src/modules/module-health-detail.tsx
new file mode 100644
index 000000000..fb16bc5d2
--- /dev/null
+++ b/packages/ui/src/modules/module-health-detail.tsx
@@ -0,0 +1,257 @@
+"use client";
+
+import {
+ Folder,
+ Flame,
+ Trash2,
+ BookOpen,
+ Users,
+ ShieldAlert,
+ Lightbulb,
+ FileWarning,
+} from "lucide-react";
+import type {
+ ModuleHealthDetail as ModuleHealthDetailModel,
+ ModuleHealthOwner,
+} from "@repowise-dev/types/modules";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+import { truncatePath } from "../lib/format";
+import { OwnerAvatar } from "../owners/owner-avatar";
+
+function scoreCls(score: number): string {
+ if (score >= 70) return "text-emerald-300 bg-emerald-500/10 border-emerald-500/40";
+ if (score >= 40) return "text-amber-300 bg-amber-500/10 border-amber-500/40";
+ return "text-red-300 bg-red-500/10 border-red-500/40";
+}
+
+export interface ModuleHealthDetailViewProps {
+ module: ModuleHealthDetailModel;
+ onSelectOwner?: (owner: ModuleHealthOwner) => void;
+ onSelectFile?: (filePath: string) => void;
+ onSelectDecision?: (decisionId: string) => void;
+}
+
+/**
+ * Single-module deep view: composite health score, owner mix, hotspots,
+ * decisions, and headline metrics. Mirrors {@link OwnerProfileView} in
+ * tone — fast to scan, all numbers linked.
+ */
+export function ModuleHealthDetailView({
+ module,
+ onSelectOwner,
+ onSelectFile,
+ onSelectDecision,
+}: ModuleHealthDetailViewProps) {
+ const score = Math.round(module.health_score);
+
+ return (
+ <div className="space-y-6">
+ {/* ── Header ── */}
+ <Card>
+ <CardContent className="p-5">
+ <div className="flex flex-wrap items-start gap-5">
+ <div
+ className={cn(
+ "flex flex-col items-center justify-center rounded-lg border px-4 py-3 text-center min-w-[88px]",
+ scoreCls(module.health_score),
+ )}
+ >
+ <span className="text-3xl font-bold tabular-nums">{score}</span>
+ <span className="text-[10px] uppercase tracking-wider opacity-70">
+ health
+ </span>
+ </div>
+ <div className="flex-1 min-w-0">
+ <h1 className="flex items-center gap-2 text-2xl font-bold text-[var(--color-text-primary)]">
+ <Folder className="h-5 w-5 text-[var(--color-text-tertiary)]" />
+ {module.module_path}
+ </h1>
+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
+ {module.file_count} files · {module.symbol_count} symbols ·{" "}
+ {module.contributor_count} contributors
+ </p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {module.is_silo && <Badge variant="outdated">silo</Badge>}
+ {module.min_bus_factor <= 1 && (
+ <Badge variant="outdated">bus ≤ 1</Badge>
+ )}
+ {module.decision_count > 0 && (
+ <Badge variant="accent">
+ {module.decision_count} decisions
+ </Badge>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
+ <Headline
+ label="Hotspots"
+ value={module.hotspot_count}
+ icon={<Flame className="h-3.5 w-3.5 text-orange-400" />}
+ tone={module.hotspot_count > 0 ? "warn" : undefined}
+ />
+ <Headline
+ label="Dead lines"
+ value={module.dead_code_lines}
+ icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />}
+ tone={module.dead_code_lines > 0 ? "warn" : undefined}
+ />
+ <Headline
+ label="Doc coverage"
+ value={`${Math.round(module.doc_coverage_pct)}%`}
+ icon={<BookOpen className="h-3.5 w-3.5 text-sky-400" />}
+ />
+ <Headline
+ label="Bus med"
+ value={module.median_bus_factor.toFixed(1)}
+ icon={<Users className="h-3.5 w-3.5 text-violet-400" />}
+ />
+ <Headline
+ label="Bus min"
+ value={module.min_bus_factor}
+ icon={<ShieldAlert className="h-3.5 w-3.5 text-red-400" />}
+ tone={module.min_bus_factor <= 1 ? "danger" : undefined}
+ />
+ <Headline
+ label="Avg churn"
+ value={`${Math.round(module.avg_churn_percentile)}`}
+ />
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* ── Body ── */}
+ <div className="grid gap-4 lg:grid-cols-3">
+ <Card className="lg:col-span-2">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <Users className="h-4 w-4" /> Owners
+ </CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ People who primarily own files in this module.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1.5">
+ {module.owners.length === 0 && (
+ <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
+ No ownership signal.
+ </p>
+ )}
+ {module.owners.map((o) => {
+ const pct = Math.round(o.pct * 100);
+ return (
+ <button
+ key={o.email ?? o.name}
+ onClick={() => onSelectOwner?.(o)}
+ className="flex w-full items-center gap-3 rounded-md px-2 py-1.5 text-left hover:bg-[var(--color-bg-elevated)]"
+ >
+ <OwnerAvatar name={o.name} email={o.email} size="sm" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-xs font-medium text-[var(--color-text-primary)]">
+ {o.name}
+ </div>
+ <div className="text-[10px] text-[var(--color-text-tertiary)]">
+ {o.file_count} files
+ </div>
+ </div>
+ <div className="h-1.5 w-32 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className={cn(
+ "h-full",
+ pct > 80 ? "bg-amber-500" : "bg-[var(--color-accent-primary)]",
+ )}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <span className="w-10 text-right text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {pct}%
+ </span>
+ </button>
+ );
+ })}
+ </CardContent>
+ </Card>
+
+ <div className="space-y-4">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <FileWarning className="h-4 w-4 text-orange-400" /> Top hotspots
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1">
+ {module.top_hotspots.length === 0 ? (
+ <p className="py-2 text-center text-xs text-[var(--color-text-tertiary)]">
+ No hotspots in this module.
+ </p>
+ ) : (
+ module.top_hotspots.map((p) => (
+ <button
+ key={p}
+ onClick={() => onSelectFile?.(p)}
+ className="block w-full truncate rounded px-2 py-1 text-left font-mono text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ title={p}
+ >
+ {truncatePath(p, 40)}
+ </button>
+ ))
+ )}
+ </CardContent>
+ </Card>
+
+ {module.governing_decisions.length > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <Lightbulb className="h-4 w-4 text-yellow-400" /> Governing decisions
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1">
+ {module.governing_decisions.map((id) => (
+ <button
+ key={id}
+ onClick={() => onSelectDecision?.(id)}
+ className="block w-full truncate rounded px-2 py-1 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {id.slice(0, 16)}…
+ </button>
+ ))}
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Headline({
+ label,
+ value,
+ icon,
+ tone,
+}: {
+ label: string;
+ value: string | number;
+ icon?: React.ReactNode | undefined;
+ tone?: "warn" | "danger" | undefined;
+}) {
+ const color =
+ tone === "danger"
+ ? "text-red-400"
+ : tone === "warn"
+ ? "text-orange-300"
+ : "text-[var(--color-text-primary)]";
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">
+ <div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {icon}
+ {label}
+ </div>
+ <div className={`mt-1 text-xl font-bold tabular-nums ${color}`}>{value}</div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/modules/module-health-list.tsx b/packages/ui/src/modules/module-health-list.tsx
new file mode 100644
index 000000000..c8b8d9b73
--- /dev/null
+++ b/packages/ui/src/modules/module-health-list.tsx
@@ -0,0 +1,71 @@
+"use client";
+
+import { Folder } from "lucide-react";
+import type { ModuleHealthSummary } from "@repowise-dev/types/modules";
+import { EmptyState } from "../shared/empty-state";
+import { Skeleton } from "../ui/skeleton";
+import { ResultsFooter } from "../shared/results-footer";
+import { ModuleHealthCard } from "./module-health-card";
+
+interface Props {
+ modules: ModuleHealthSummary[];
+ isLoading: boolean;
+ total: number;
+ hasMore: boolean;
+ loadingMore?: boolean | undefined;
+ onLoadMore?: (() => void) | undefined;
+ onSelect?: ((m: ModuleHealthSummary) => void) | undefined;
+}
+
+/**
+ * Grid of {@link ModuleHealthCard}s with empty / loading / pagination
+ * states. Server returns lowest-health-first by default; we leave ordering
+ * to the parent so this stays presentational.
+ */
+export function ModuleHealthList({
+ modules,
+ isLoading,
+ total,
+ hasMore,
+ loadingMore,
+ onLoadMore,
+ onSelect,
+}: Props) {
+ if (isLoading && modules.length === 0) {
+ return (
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-44 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ if (modules.length === 0) {
+ return (
+ <EmptyState
+ icon={<Folder className="h-6 w-6" />}
+ title="No module data yet"
+ description="Module health rolls up after the initial git + dead-code scan completes."
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {modules.map((m) => (
+ <ModuleHealthCard key={m.module_path} module={m} onClick={onSelect} />
+ ))}
+ </div>
+ <ResultsFooter
+ shown={modules.length}
+ total={total}
+ hasMore={hasMore}
+ loading={Boolean(loadingMore)}
+ onLoadMore={onLoadMore ?? (() => {})}
+ noun="module"
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/owners/index.ts b/packages/ui/src/owners/index.ts
new file mode 100644
index 000000000..2d0ae04a6
--- /dev/null
+++ b/packages/ui/src/owners/index.ts
@@ -0,0 +1,4 @@
+export * from "./owner-card.js";
+export * from "./owner-directory.js";
+export * from "./owner-profile.js";
+export * from "./owner-avatar.js";
diff --git a/packages/ui/src/owners/owner-avatar.tsx b/packages/ui/src/owners/owner-avatar.tsx
new file mode 100644
index 000000000..e3162dc3c
--- /dev/null
+++ b/packages/ui/src/owners/owner-avatar.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { cn } from "../lib/cn";
+
+/**
+ * Deterministic colored initials avatar. Falls back to a single character
+ * if we only have an email and no name. Kept self-contained so the hosted
+ * frontend can drop it in without bringing a real avatar service.
+ */
+const PALETTE = [
+ "bg-rose-500/20 text-rose-300",
+ "bg-amber-500/20 text-amber-300",
+ "bg-emerald-500/20 text-emerald-300",
+ "bg-sky-500/20 text-sky-300",
+ "bg-indigo-500/20 text-indigo-300",
+ "bg-fuchsia-500/20 text-fuchsia-300",
+ "bg-orange-500/20 text-orange-300",
+ "bg-teal-500/20 text-teal-300",
+];
+
+function hash(s: string): number {
+ let h = 0;
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
+ return Math.abs(h);
+}
+
+function initials(name: string, email: string | null): string {
+ const source = (name || email || "?").trim();
+ if (!source) return "?";
+ const parts = source.split(/\s+/).filter(Boolean);
+ if (parts.length >= 2) {
+ const a = parts[0]?.[0] ?? "";
+ const b = parts[1]?.[0] ?? "";
+ return (a + b).toUpperCase() || "?";
+ }
+ return source.slice(0, 2).toUpperCase();
+}
+
+export interface OwnerAvatarProps {
+ name: string;
+ email?: string | null;
+ size?: "sm" | "md" | "lg";
+ className?: string;
+}
+
+export function OwnerAvatar({ name, email, size = "md", className }: OwnerAvatarProps) {
+ const key = (email ?? name ?? "?").toLowerCase();
+ const color = PALETTE[hash(key) % PALETTE.length];
+ const sizeCls =
+ size === "sm" ? "h-6 w-6 text-[10px]" : size === "lg" ? "h-12 w-12 text-base" : "h-8 w-8 text-xs";
+ return (
+ <div
+ className={cn(
+ "inline-flex shrink-0 items-center justify-center rounded-full font-semibold tracking-wide",
+ color,
+ sizeCls,
+ className,
+ )}
+ aria-label={name || email || "contributor"}
+ title={name || email || ""}
+ >
+ {initials(name, email ?? null)}
+ </div>
+ );
+}
diff --git a/packages/ui/src/owners/owner-card.tsx b/packages/ui/src/owners/owner-card.tsx
new file mode 100644
index 000000000..8c0cf7671
--- /dev/null
+++ b/packages/ui/src/owners/owner-card.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { Flame, ShieldAlert, Trash2, GitCommit } from "lucide-react";
+import type { OwnerListEntry } from "@repowise-dev/types/owners";
+import { Card } from "../ui/card";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+import { OwnerAvatar } from "./owner-avatar";
+
+interface OwnerCardProps {
+ owner: OwnerListEntry;
+ onSelect?: (owner: OwnerListEntry) => void;
+ highlight?: boolean;
+}
+
+function timeAgo(iso: string | null): string {
+ if (!iso) return "—";
+ const ms = Date.now() - new Date(iso).getTime();
+ if (Number.isNaN(ms) || ms < 0) return "—";
+ const d = Math.floor(ms / 86_400_000);
+ if (d < 1) return "today";
+ if (d < 30) return `${d}d ago`;
+ if (d < 365) return `${Math.floor(d / 30)}mo ago`;
+ return `${Math.floor(d / 365)}y ago`;
+}
+
+/**
+ * Single-row owner card used in the directory list. Highlights silos and
+ * bus-factor risk so engineering leaders can spot concentrated risk fast.
+ */
+export function OwnerCard({ owner, onSelect, highlight }: OwnerCardProps) {
+ const risky = owner.bus_factor_risk_files > 0 || owner.silo_modules > 0;
+ return (
+ <Card
+ onClick={() => onSelect?.(owner)}
+ className={cn(
+ "group cursor-pointer p-4 transition-all hover:border-[var(--color-border-hover)] hover:shadow-[0_0_0_1px_var(--color-border-hover)]",
+ highlight && "ring-1 ring-[var(--color-accent-primary)]/40",
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <OwnerAvatar name={owner.name} email={owner.email} size="md" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center justify-between gap-2">
+ <div className="truncate text-sm font-medium text-[var(--color-text-primary)]">
+ {owner.name}
+ </div>
+ {risky && (
+ <Badge variant="outdated" className="shrink-0 text-[10px]">
+ risk
+ </Badge>
+ )}
+ </div>
+ {owner.email && (
+ <div className="truncate text-[11px] text-[var(--color-text-tertiary)]">
+ {owner.email}
+ </div>
+ )}
+ <div className="mt-3 grid grid-cols-4 gap-2 text-xs">
+ <Stat label="Files" value={owner.files_owned} />
+ <Stat
+ label="Hotspots"
+ value={owner.hotspots_owned}
+ icon={<Flame className="h-3 w-3 text-orange-400" />}
+ tone={owner.hotspots_owned > 0 ? "warn" : undefined}
+ />
+ <Stat
+ label="Bus≤1"
+ value={owner.bus_factor_risk_files}
+ icon={<ShieldAlert className="h-3 w-3 text-red-400" />}
+ tone={owner.bus_factor_risk_files > 0 ? "danger" : undefined}
+ />
+ <Stat
+ label="Dead lines"
+ value={owner.dead_code_lines_owned}
+ icon={<Trash2 className="h-3 w-3 text-rose-400" />}
+ tone={owner.dead_code_lines_owned > 0 ? "muted" : undefined}
+ />
+ </div>
+ <div className="mt-3 flex items-center justify-between text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="flex items-center gap-1">
+ <GitCommit className="h-3 w-3" />
+ {owner.commit_count_90d} commits / 90d
+ </span>
+ <span>last touched {timeAgo(owner.last_commit_at)}</span>
+ </div>
+ </div>
+ </div>
+ </Card>
+ );
+}
+
+function Stat({
+ label,
+ value,
+ icon,
+ tone,
+}: {
+ label: string;
+ value: number;
+ icon?: React.ReactNode | undefined;
+ tone?: "warn" | "danger" | "muted" | undefined;
+}) {
+ const toneCls =
+ tone === "danger"
+ ? "text-red-400"
+ : tone === "warn"
+ ? "text-orange-300"
+ : tone === "muted"
+ ? "text-rose-300/70"
+ : "text-[var(--color-text-primary)]";
+ return (
+ <div>
+ <div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {icon}
+ {label}
+ </div>
+ <div className={cn("tabular-nums font-semibold", toneCls)}>{value}</div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/owners/owner-directory.tsx b/packages/ui/src/owners/owner-directory.tsx
new file mode 100644
index 000000000..1cd354fce
--- /dev/null
+++ b/packages/ui/src/owners/owner-directory.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import { useMemo } from "react";
+import { Users, Search } from "lucide-react";
+import type { OwnerListEntry } from "@repowise-dev/types/owners";
+import { Input } from "../ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
+import { Skeleton } from "../ui/skeleton";
+import { EmptyState } from "../shared/empty-state";
+import { ResultsFooter } from "../shared/results-footer";
+import { OwnerCard } from "./owner-card";
+
+export type OwnerSortKey =
+ | "files_owned"
+ | "hotspots_owned"
+ | "commit_count_90d"
+ | "dead_code_lines_owned"
+ | "bus_factor_risk_files";
+
+const SORT_LABELS: Record<OwnerSortKey, string> = {
+ files_owned: "Files owned",
+ hotspots_owned: "Hotspots owned",
+ commit_count_90d: "Recent commits",
+ dead_code_lines_owned: "Dead-code burden",
+ bus_factor_risk_files: "Bus-factor risk",
+};
+
+export interface OwnerDirectoryFilters {
+ q: string;
+ sort: OwnerSortKey;
+}
+
+export interface OwnerDirectoryProps {
+ owners: OwnerListEntry[];
+ isLoading: boolean;
+ isValidating: boolean;
+ total: number;
+ hasMore: boolean;
+ filters: OwnerDirectoryFilters;
+ onFiltersChange: (next: OwnerDirectoryFilters) => void;
+ onLoadMore: () => void;
+ onSelect: (owner: OwnerListEntry) => void;
+}
+
+export function OwnerDirectory({
+ owners,
+ isLoading,
+ isValidating,
+ total,
+ hasMore,
+ filters,
+ onFiltersChange,
+ onLoadMore,
+ onSelect,
+}: OwnerDirectoryProps) {
+ // Spotlight metrics — drives the strip above the directory grid.
+ const headline = useMemo(() => {
+ const totalFiles = owners.reduce((s, o) => s + o.files_owned, 0);
+ const siloOwners = owners.filter((o) => o.silo_modules > 0).length;
+ const busRiskOwners = owners.filter((o) => o.bus_factor_risk_files > 0).length;
+ const totalDeadLines = owners.reduce((s, o) => s + o.dead_code_lines_owned, 0);
+ return { totalFiles, siloOwners, busRiskOwners, totalDeadLines };
+ }, [owners]);
+
+ return (
+ <div className="space-y-5">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Headline label="Contributors" value={total} />
+ <Headline label="Silo owners" value={headline.siloOwners} tone="warn" />
+ <Headline label="Bus-factor risk" value={headline.busRiskOwners} tone="danger" />
+ <Headline label="Dead lines owned" value={headline.totalDeadLines} />
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative flex-1 min-w-[220px]">
+ <Search className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-[var(--color-text-tertiary)]" />
+ <Input
+ value={filters.q}
+ onChange={(e) => onFiltersChange({ ...filters, q: e.target.value })}
+ placeholder="Filter by name or email…"
+ className="pl-8"
+ />
+ </div>
+ <Select
+ value={filters.sort}
+ onValueChange={(v) => onFiltersChange({ ...filters, sort: v as OwnerSortKey })}
+ >
+ <SelectTrigger className="w-[200px]">
+ <SelectValue placeholder="Sort by" />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(SORT_LABELS).map(([k, label]) => (
+ <SelectItem key={k} value={k}>
+ {label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {isLoading && owners.length === 0 ? (
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-32 w-full" />
+ ))}
+ </div>
+ ) : owners.length === 0 ? (
+ <EmptyState
+ icon={<Users className="h-6 w-6" />}
+ title="No contributors match"
+ description="Adjust the filter or wait for the initial git index to finish."
+ />
+ ) : (
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {owners.map((o) => (
+ <OwnerCard key={o.key} owner={o} onSelect={onSelect} />
+ ))}
+ </div>
+ )}
+
+ <ResultsFooter
+ shown={owners.length}
+ total={total}
+ hasMore={hasMore}
+ loading={isValidating && !isLoading}
+ onLoadMore={onLoadMore}
+ noun="contributor"
+ />
+ </div>
+ );
+}
+
+function Headline({
+ label,
+ value,
+ tone,
+}: {
+ label: string;
+ value: number;
+ tone?: "warn" | "danger";
+}) {
+ const color =
+ tone === "danger" ? "text-red-400" : tone === "warn" ? "text-orange-300" : "text-[var(--color-text-primary)]";
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3">
+ <div className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {label}
+ </div>
+ <div className={`mt-1 text-2xl font-bold tabular-nums ${color}`}>{value}</div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsx
new file mode 100644
index 000000000..96253a269
--- /dev/null
+++ b/packages/ui/src/owners/owner-profile.tsx
@@ -0,0 +1,502 @@
+"use client";
+
+import { useMemo } from "react";
+import {
+ Flame,
+ ShieldAlert,
+ Trash2,
+ GitCommit,
+ Calendar,
+ Users,
+ Folder,
+ TrendingUp,
+} from "lucide-react";
+import type {
+ OwnerProfile,
+ OwnerFileEntry,
+ OwnerModuleRollup,
+ OwnerCoAuthor,
+} from "@repowise-dev/types/owners";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+import { truncatePath } from "../lib/format";
+import { OwnerAvatar } from "./owner-avatar";
+
+const dateFormatter = new Intl.DateTimeFormat(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+});
+
+function fmtDate(iso: string | null): string {
+ if (!iso) return "—";
+ const t = new Date(iso);
+ return Number.isNaN(t.getTime()) ? "—" : dateFormatter.format(t);
+}
+
+function fmtCompact(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
+ return n.toLocaleString();
+}
+
+function timeAgo(iso: string | null): string {
+ if (!iso) return "never";
+ const d = Math.floor((Date.now() - new Date(iso).getTime()) / 86_400_000);
+ if (Number.isNaN(d) || d < 0) return "never";
+ if (d < 1) return "today";
+ if (d < 30) return `${d}d ago`;
+ if (d < 365) return `${Math.floor(d / 30)}mo ago`;
+ return `${Math.floor(d / 365)}y ago`;
+}
+
+export interface OwnerProfileViewProps {
+ owner: OwnerProfile;
+ onSelectFile?: (filePath: string) => void;
+ onSelectModule?: (modulePath: string) => void;
+ onSelectCoAuthor?: (coAuthor: OwnerCoAuthor) => void;
+ /** Optional renderer for the embedded blast-radius / activity preview. */
+ rightRail?: React.ReactNode;
+}
+
+/**
+ * Engineering-leader contributor profile. All data comes from the
+ * /api/repos/{id}/owners/{key} endpoint — no client-side aggregation.
+ *
+ * Layout:
+ * - Header: avatar, headline metrics, time-on-codebase line
+ * - Risk strip: silos / bus-factor / dead-code / hotspots, color-coded
+ * - Two-column body: top files + modules (left), co-authors + categories (right)
+ */
+export function OwnerProfileView({
+ owner,
+ onSelectFile,
+ onSelectModule,
+ onSelectCoAuthor,
+ rightRail,
+}: OwnerProfileViewProps) {
+ const tenureDays = useMemo(() => {
+ if (!owner.first_commit_at) return null;
+ const start = new Date(owner.first_commit_at).getTime();
+ if (Number.isNaN(start)) return null;
+ return Math.max(0, Math.floor((Date.now() - start) / 86_400_000));
+ }, [owner.first_commit_at]);
+
+ const categories = useMemo(
+ () =>
+ Object.entries(owner.commit_categories || {})
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 6),
+ [owner.commit_categories],
+ );
+ const categoryTotal = categories.reduce((s, [, n]) => s + n, 0) || 1;
+
+ return (
+ <div className="space-y-6">
+ {/* ---------- Header ---------- */}
+ <Card>
+ <CardContent className="p-5">
+ <div className="flex flex-wrap items-start gap-5">
+ <OwnerAvatar name={owner.name} email={owner.email} size="lg" />
+ <div className="flex-1 min-w-0">
+ <h1 className="text-2xl font-bold text-[var(--color-text-primary)]">
+ {owner.name}
+ </h1>
+ {owner.email && (
+ <a
+ href={`mailto:${owner.email}`}
+ className="text-sm text-[var(--color-text-secondary)] hover:underline"
+ >
+ {owner.email}
+ </a>
+ )}
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ <Calendar className="inline h-3 w-3 mr-1" />
+ {tenureDays !== null
+ ? `${tenureDays.toLocaleString()} days on this repo`
+ : "tenure unknown"}{" "}
+ · first commit {fmtDate(owner.first_commit_at)} · last touched{" "}
+ {timeAgo(owner.last_commit_at)}
+ </p>
+ </div>
+ </div>
+
+ <div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-6">
+ <Headline label="Files owned" value={owner.files_owned} />
+ <Headline label="Modules" value={owner.modules.length} />
+ <Headline
+ label="Commits / 90d"
+ value={owner.commit_count_90d}
+ icon={<GitCommit className="h-3.5 w-3.5" />}
+ />
+ <Headline
+ label="Lines added (est)"
+ value={fmtCompact(owner.lines_added_90d_est)}
+ tone="add"
+ />
+ <Headline
+ label="Lines deleted (est)"
+ value={fmtCompact(owner.lines_deleted_90d_est)}
+ tone="del"
+ />
+ <Headline label="Co-authors" value={owner.co_authors.length} />
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* ---------- Risk strip ---------- */}
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <RiskTile
+ icon={<Users className="h-4 w-4 text-amber-400" />}
+ label="Silo modules"
+ value={owner.silo_modules}
+ help="modules where this person owns >80% of files"
+ tone={owner.silo_modules > 0 ? "warn" : "ok"}
+ />
+ <RiskTile
+ icon={<ShieldAlert className="h-4 w-4 text-red-400" />}
+ label="Bus-factor risk"
+ value={owner.bus_factor_risk_files}
+ help="files with bus_factor ≤ 1 that they own"
+ tone={owner.bus_factor_risk_files > 0 ? "danger" : "ok"}
+ />
+ <RiskTile
+ icon={<Flame className="h-4 w-4 text-orange-400" />}
+ label="Hotspots owned"
+ value={owner.hotspots_owned}
+ help="high-churn files where they are primary owner"
+ tone={owner.hotspots_owned > 0 ? "warn" : "ok"}
+ />
+ <RiskTile
+ icon={<Trash2 className="h-4 w-4 text-rose-400" />}
+ label="Dead-code burden"
+ value={`${owner.dead_code_files_owned} files · ${fmtCompact(owner.dead_code_lines_owned)} lines`}
+ help="dead code findings whose primary owner is this person"
+ tone={owner.dead_code_files_owned > 0 ? "muted" : "ok"}
+ />
+ </div>
+
+ {/* ---------- Body ---------- */}
+ <div className="grid gap-4 lg:grid-cols-3">
+ <div className="space-y-4 lg:col-span-2">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <Folder className="h-4 w-4" /> Modules
+ </CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Where this person spends their time. Bars show their share of the module.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1.5">
+ {owner.modules.slice(0, 12).map((m) => (
+ <ModuleRow key={m.module_path} mod={m} onClick={() => onSelectModule?.(m.module_path)} />
+ ))}
+ {owner.modules.length === 0 && (
+ <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">
+ No module attribution yet.
+ </p>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <TrendingUp className="h-4 w-4" /> Top files
+ </CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Files this person touches most, ordered by attributed commit count.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <FileTable files={owner.top_files} onSelectFile={onSelectFile} />
+ </CardContent>
+ </Card>
+ </div>
+
+ <div className="space-y-4">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <Users className="h-4 w-4" /> Co-authors
+ </CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ People who edit the same files. Strong overlap = natural reviewer.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-1.5">
+ {owner.co_authors.slice(0, 10).map((c) => (
+ <button
+ key={c.email ?? c.name}
+ onClick={() => onSelectCoAuthor?.(c)}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)]"
+ >
+ <OwnerAvatar name={c.name} email={c.email} size="sm" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium text-[var(--color-text-primary)]">
+ {c.name}
+ </div>
+ <div className="text-[10px] text-[var(--color-text-tertiary)]">
+ {c.shared_files} shared {c.shared_files === 1 ? "file" : "files"} ·{" "}
+ {(c.co_change_strength * 100).toFixed(0)}% overlap
+ </div>
+ </div>
+ <div className="h-1 w-12 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className="h-full bg-[var(--color-accent-primary)]"
+ style={{ width: `${Math.min(100, c.co_change_strength * 100)}%` }}
+ />
+ </div>
+ </button>
+ ))}
+ {owner.co_authors.length === 0 && (
+ <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
+ No co-authors detected.
+ </p>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm">Commit mix</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Classification of commits across files this person touches.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {categories.length === 0 ? (
+ <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
+ No category data.
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {categories.map(([cat, n]) => (
+ <div key={cat}>
+ <div className="flex items-center justify-between text-xs">
+ <span className="capitalize text-[var(--color-text-secondary)]">
+ {cat}
+ </span>
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {n}
+ </span>
+ </div>
+ <div className="mt-1 h-1 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className={cn("h-full", categoryColor(cat))}
+ style={{ width: `${(n / categoryTotal) * 100}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {rightRail}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Building blocks
+// ---------------------------------------------------------------------------
+
+function Headline({
+ label,
+ value,
+ tone,
+ icon,
+}: {
+ label: string;
+ value: string | number;
+ tone?: "add" | "del";
+ icon?: React.ReactNode;
+}) {
+ const color =
+ tone === "add"
+ ? "text-emerald-300"
+ : tone === "del"
+ ? "text-rose-300"
+ : "text-[var(--color-text-primary)]";
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">
+ <div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {icon}
+ {label}
+ </div>
+ <div className={`mt-1 text-xl font-bold tabular-nums ${color}`}>{value}</div>
+ </div>
+ );
+}
+
+function RiskTile({
+ icon,
+ label,
+ value,
+ help,
+ tone,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ value: number | string;
+ help: string;
+ tone: "ok" | "warn" | "danger" | "muted";
+}) {
+ const border =
+ tone === "danger"
+ ? "border-red-500/40 bg-red-500/5"
+ : tone === "warn"
+ ? "border-amber-500/40 bg-amber-500/5"
+ : tone === "muted"
+ ? "border-rose-500/30 bg-rose-500/5"
+ : "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]";
+ return (
+ <div className={cn("rounded-lg border p-3", border)}>
+ <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {icon}
+ {label}
+ </div>
+ <div className="mt-1.5 text-lg font-semibold text-[var(--color-text-primary)]">
+ {value}
+ </div>
+ <p className="mt-1 text-[10px] text-[var(--color-text-tertiary)]">{help}</p>
+ </div>
+ );
+}
+
+function ModuleRow({
+ mod,
+ onClick,
+}: {
+ mod: OwnerModuleRollup;
+ onClick: () => void;
+}) {
+ const share = Math.min(100, Math.max(0, mod.dominant_pct * 100));
+ return (
+ <button
+ onClick={onClick}
+ className="group flex w-full items-center gap-3 rounded-md px-2 py-1.5 hover:bg-[var(--color-bg-elevated)]"
+ >
+ <span className="flex-1 truncate text-left text-xs font-medium text-[var(--color-text-primary)]">
+ {mod.module_path}
+ </span>
+ {mod.hotspot_count > 0 && (
+ <Badge variant="outdated" className="text-[10px]">
+ <Flame className="mr-0.5 h-3 w-3" />
+ {mod.hotspot_count}
+ </Badge>
+ )}
+ <span className="w-12 text-right text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {mod.file_count} files
+ </span>
+ <div className="h-1.5 w-24 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className={cn(
+ "h-full",
+ share > 80 ? "bg-amber-500" : "bg-[var(--color-accent-primary)]",
+ )}
+ style={{ width: `${share}%` }}
+ />
+ </div>
+ <span className="w-10 text-right text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {share.toFixed(0)}%
+ </span>
+ </button>
+ );
+}
+
+function FileTable({
+ files,
+ onSelectFile,
+}: {
+ files: OwnerFileEntry[];
+ onSelectFile?: ((path: string) => void) | undefined;
+}) {
+ if (files.length === 0) {
+ return (
+ <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
+ No file attribution.
+ </p>
+ );
+ }
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full text-xs">
+ <thead className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <tr>
+ <th className="py-1.5 px-2 text-left font-medium">File</th>
+ <th className="py-1.5 px-2 text-right font-medium">Commits / 90d</th>
+ <th className="py-1.5 px-2 text-right font-medium">Churn</th>
+ <th className="py-1.5 px-2 text-right font-medium">Bus</th>
+ <th className="py-1.5 px-2 text-right font-medium">Touched</th>
+ </tr>
+ </thead>
+ <tbody>
+ {files.slice(0, 20).map((f) => (
+ <tr
+ key={f.file_path}
+ onClick={() => onSelectFile?.(f.file_path)}
+ className={cn(
+ "border-t border-[var(--color-border-default)]/40",
+ onSelectFile && "cursor-pointer hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ <td className="py-1.5 px-2 max-w-[320px]">
+ <span className="flex items-center gap-1.5 truncate font-mono text-[11px] text-[var(--color-text-primary)]">
+ {f.is_hotspot && <Flame className="h-3 w-3 shrink-0 text-orange-400" />}
+ {truncatePath(f.file_path, 48)}
+ </span>
+ </td>
+ <td className="py-1.5 px-2 text-right tabular-nums">{f.commit_count_90d}</td>
+ <td className="py-1.5 px-2 text-right tabular-nums">
+ <ChurnPill value={f.churn_percentile} />
+ </td>
+ <td className="py-1.5 px-2 text-right tabular-nums">
+ <BusBadge bf={f.bus_factor} />
+ </td>
+ <td className="py-1.5 px-2 text-right text-[10px] text-[var(--color-text-tertiary)]">
+ {timeAgo(f.last_commit_at)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function ChurnPill({ value }: { value: number }) {
+ const v = Math.round(value);
+ const color =
+ v >= 80 ? "bg-red-500/20 text-red-300" : v >= 50 ? "bg-amber-500/20 text-amber-300" : "bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)]";
+ return (
+ <span className={cn("inline-block rounded px-1.5 py-0.5 text-[10px] tabular-nums", color)}>
+ {v}
+ </span>
+ );
+}
+
+function BusBadge({ bf }: { bf: number }) {
+ const color =
+ bf <= 1 ? "text-red-400" : bf === 2 ? "text-amber-300" : "text-emerald-300";
+ return <span className={cn("font-semibold", color)}>{bf}</span>;
+}
+
+function categoryColor(category: string): string {
+ const map: Record<string, string> = {
+ feat: "bg-emerald-400",
+ fix: "bg-rose-400",
+ refactor: "bg-sky-400",
+ docs: "bg-indigo-400",
+ test: "bg-violet-400",
+ chore: "bg-zinc-400",
+ perf: "bg-amber-400",
+ };
+ return map[category] ?? "bg-[var(--color-accent-primary)]";
+}
diff --git a/packages/ui/src/symbols/symbol-git-panel.tsx b/packages/ui/src/symbols/symbol-git-panel.tsx
index 11a9889d8..1fa7dc35e 100644
--- a/packages/ui/src/symbols/symbol-git-panel.tsx
+++ b/packages/ui/src/symbols/symbol-git-panel.tsx
@@ -4,6 +4,7 @@ import {
AlertTriangle,
Flame,
GitBranch,
+ Lightbulb,
Radius,
Skull,
Users,
@@ -52,8 +53,14 @@ export interface SymbolGitPanelProps {
coChanges?: SymbolGitPanelCoChange[];
/** Dead-code findings whose line range overlaps the symbol. */
deadCode?: SymbolGitPanelDeadFinding[];
+ /** Decision records governing this file / module. Optional. */
+ governingDecisions?: Array<{ id: string; title: string; status: string }>;
/** Optional callback for the "View blast radius" CTA. */
onOpenBlastRadius?: () => void;
+ /** Click handler when an owner name is selected. */
+ onSelectOwner?: (name: string, email?: string | null) => void;
+ /** Click handler for governing decision rows. */
+ onSelectDecision?: (id: string) => void;
}
/**
@@ -68,7 +75,10 @@ export function SymbolGitPanel({
git,
coChanges,
deadCode,
+ governingDecisions,
onOpenBlastRadius,
+ onSelectOwner,
+ onSelectDecision,
}: SymbolGitPanelProps) {
const hasDead = (deadCode?.length ?? 0) > 0;
const visibleCoChanges = (coChanges ?? []).slice(0, 6);
@@ -95,14 +105,25 @@ export function SymbolGitPanel({
<div className="space-y-2">
<div className="flex items-center gap-2">
<Users className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <span className="text-[var(--color-text-secondary)]">
- {git.primary_owner_name ?? "—"}
- {git.primary_owner_commit_pct != null && (
- <span className="ml-1 text-[var(--color-text-tertiary)] tabular-nums">
- ({Math.round(git.primary_owner_commit_pct * 100)}%)
- </span>
- )}
- </span>
+ {git.primary_owner_name ? (
+ <button
+ onClick={() => onSelectOwner?.(git.primary_owner_name!, null)}
+ disabled={!onSelectOwner}
+ className={cn(
+ "text-[var(--color-text-secondary)] text-left",
+ onSelectOwner && "hover:underline hover:text-[var(--color-accent-primary)]",
+ )}
+ >
+ {git.primary_owner_name}
+ {git.primary_owner_commit_pct != null && (
+ <span className="ml-1 text-[var(--color-text-tertiary)] tabular-nums">
+ ({Math.round(git.primary_owner_commit_pct * 100)}%)
+ </span>
+ )}
+ </button>
+ ) : (
+ <span className="text-[var(--color-text-secondary)]">—</span>
+ )}
</div>
{git.recent_owner_name && git.recent_owner_name !== git.primary_owner_name && (
<p className="text-[var(--color-text-tertiary)] pl-5">
@@ -191,6 +212,30 @@ export function SymbolGitPanel({
</div>
)}
+ {governingDecisions && governingDecisions.length > 0 && (
+ <div className="space-y-1.5">
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">
+ <Lightbulb className="h-3 w-3" />
+ Governing decisions
+ </p>
+ <ul className="space-y-1">
+ {governingDecisions.slice(0, 5).map((d) => (
+ <li key={d.id}>
+ <button
+ onClick={() => onSelectDecision?.(d.id)}
+ className="flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <span className="truncate">{d.title}</span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase">
+ {d.status}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
{onOpenBlastRadius && (
<Button
variant="outline"
diff --git a/packages/web/src/app/repos/[id]/blast-radius/page.tsx b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
index 08045f48e..e658a6646 100644
--- a/packages/web/src/app/repos/[id]/blast-radius/page.tsx
+++ b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
@@ -9,9 +9,11 @@ import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { BlastRadiusResults } from "@repowise-dev/ui/blast-radius";
+import { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
import { analyzeBlastRadius } from "@/lib/api/blast-radius";
-import { getHotspots } from "@/lib/api/git";
+import { getHotspots, getReviewerSuggestions } from "@/lib/api/git";
+import { useRouter } from "next/navigation";
export default function BlastRadiusPage() {
const params = useParams<{ id: string }>();
@@ -22,6 +24,19 @@ export default function BlastRadiusPage() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<BlastRadiusResponse | null>(null);
+ const [analyzedPaths, setAnalyzedPaths] = useState<string[]>([]);
+ const router = useRouter();
+
+ // Reviewer suggestions key off the *most recently analyzed* paths so the
+ // panel updates the moment the analyze button is hit.
+ const reviewerKey = analyzedPaths.length
+ ? `reviewer-suggestions:${repoId}:${analyzedPaths.join(",")}`
+ : null;
+ const { data: reviewerResp, isLoading: reviewerLoading } = useSWR(
+ reviewerKey,
+ () => getReviewerSuggestions(repoId, analyzedPaths),
+ { revalidateOnFocus: false },
+ );
// Suggestions: top 8 hotspots so users can prefill with one click instead
// of remembering paths. Falls back gracefully if the call fails.
@@ -66,6 +81,7 @@ export default function BlastRadiusPage() {
max_depth: maxDepth,
});
setResult(data);
+ setAnalyzedPaths(changedFiles);
} catch (err) {
setError(err instanceof Error ? err.message : "Analysis failed.");
} finally {
@@ -172,7 +188,24 @@ export default function BlastRadiusPage() {
</CardContent>
</Card>
- {result && <BlastRadiusResults result={result} />}
+ {result && (
+ <div className="grid gap-4 lg:grid-cols-3">
+ <div className="lg:col-span-2 space-y-4">
+ <BlastRadiusResults result={result} />
+ </div>
+ <div className="space-y-4">
+ <ReviewerSuggestions
+ suggestions={reviewerResp?.suggestions ?? []}
+ isLoading={reviewerLoading}
+ subtitle={`Based on git history of ${analyzedPaths.length} touched ${analyzedPaths.length === 1 ? "path" : "paths"}.`}
+ onSelect={(s) => {
+ const k = s.email ?? `name:${s.name}`;
+ router.push(`/repos/${repoId}/owners/${encodeURIComponent(k)}`);
+ }}
+ />
+ </div>
+ </div>
+ )}
</div>
);
}
diff --git a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
new file mode 100644
index 000000000..3cdf87136
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useParams, useRouter } from "next/navigation";
+import useSWR from "swr";
+import Link from "next/link";
+import { ArrowLeft, Folder } from "lucide-react";
+import { ModuleHealthDetailView } from "@repowise-dev/ui/modules/module-health-detail";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { getModuleHealth } from "@/lib/api/modules";
+import type { ModuleHealthDetail } from "@/lib/api/types";
+
+export default function ModuleHealthPage() {
+ const { id, path } = useParams<{ id: string; path: string }>();
+ const router = useRouter();
+ const modulePath = decodeURIComponent(path);
+
+ const { data, isLoading, error } = useSWR<ModuleHealthDetail>(
+ `module-health:${id}:${modulePath}`,
+ () => getModuleHealth(id, modulePath),
+ { revalidateOnFocus: false },
+ );
+
+ return (
+ <div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">
+ <div className="flex items-center justify-between">
+ <Link
+ href={`/repos/${id}/risk?tab=modules`}
+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ArrowLeft className="h-3 w-3" /> All modules
+ </Link>
+ </div>
+
+ {isLoading && (
+ <div className="space-y-4">
+ <Skeleton className="h-40 w-full" />
+ <div className="grid gap-3 lg:grid-cols-3">
+ <Skeleton className="lg:col-span-2 h-64" />
+ <Skeleton className="h-64" />
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <EmptyState
+ icon={<Folder className="h-6 w-6" />}
+ title="Module not found"
+ description="The requested module path doesn't exist in this repository's index."
+ />
+ )}
+
+ {data && (
+ <ModuleHealthDetailView
+ module={data}
+ onSelectOwner={(o) => {
+ const key = o.email ?? `name:${o.name}`;
+ router.push(`/repos/${id}/owners/${encodeURIComponent(key)}`);
+ }}
+ onSelectFile={(p) =>
+ router.push(`/repos/${id}/wiki/${encodeURIComponent(p)}`)
+ }
+ onSelectDecision={(decisionId) =>
+ router.push(`/repos/${id}/decisions/${encodeURIComponent(decisionId)}`)
+ }
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx
new file mode 100644
index 000000000..da92a7709
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useParams, useRouter } from "next/navigation";
+import useSWR from "swr";
+import Link from "next/link";
+import { ArrowLeft, Users } from "lucide-react";
+import { OwnerProfileView } from "@repowise-dev/ui/owners/owner-profile";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { getOwnerProfile } from "@/lib/api/owners";
+import type { OwnerProfileResponse } from "@/lib/api/types";
+
+export default function OwnerProfilePage() {
+ const { id, owner } = useParams<{ id: string; owner: string }>();
+ const router = useRouter();
+ const ownerKey = decodeURIComponent(owner);
+
+ const { data, isLoading, error } = useSWR<OwnerProfileResponse>(
+ `owner:${id}:${ownerKey}`,
+ () => getOwnerProfile(id, ownerKey),
+ { revalidateOnFocus: false },
+ );
+
+ return (
+ <div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">
+ <div className="flex items-center justify-between">
+ <Link
+ href={`/repos/${id}/owners`}
+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ArrowLeft className="h-3 w-3" /> All contributors
+ </Link>
+ </div>
+
+ {isLoading && (
+ <div className="space-y-4">
+ <Skeleton className="h-32 w-full" />
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-24" />
+ ))}
+ </div>
+ <Skeleton className="h-96 w-full" />
+ </div>
+ )}
+
+ {error && (
+ <EmptyState
+ icon={<Users className="h-6 w-6" />}
+ title="Contributor not found"
+ description="The requested profile doesn't exist in this repository's git history yet."
+ />
+ )}
+
+ {data && (
+ <OwnerProfileView
+ owner={data}
+ onSelectFile={(path) =>
+ router.push(`/repos/${id}/wiki/${encodeURIComponent(path)}`)
+ }
+ onSelectModule={(mod) => router.push(`/repos/${id}/modules/${encodeURIComponent(mod)}`)}
+ onSelectCoAuthor={(c) => {
+ const k = c.email ?? `name:${c.name}`;
+ router.push(`/repos/${id}/owners/${encodeURIComponent(k)}`);
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/owners/page.tsx b/packages/web/src/app/repos/[id]/owners/page.tsx
new file mode 100644
index 000000000..d1ce3ed6b
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/owners/page.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useParams, useRouter } from "next/navigation";
+import useSWRInfinite from "swr/infinite";
+import { Users } from "lucide-react";
+import {
+ OwnerDirectory,
+ type OwnerDirectoryFilters,
+} from "@repowise-dev/ui/owners/owner-directory";
+import { useDebounce } from "@/lib/hooks/use-debounce";
+import { listOwnersPage } from "@/lib/api/owners";
+import type { OwnerListEntry, Paginated } from "@/lib/api/types";
+
+const LIMIT = 30;
+
+export default function OwnersDirectoryPage() {
+ const { id } = useParams<{ id: string }>();
+ const router = useRouter();
+ const [filters, setFilters] = useState<OwnerDirectoryFilters>({
+ q: "",
+ sort: "files_owned",
+ });
+ const debouncedQ = useDebounce(filters.q, 250);
+
+ const key = useMemo(
+ () => JSON.stringify({ q: debouncedQ, sort: filters.sort }),
+ [debouncedQ, filters.sort],
+ );
+
+ const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<
+ Paginated<OwnerListEntry>
+ >(
+ (pageIndex, previous) => {
+ if (previous && !previous.has_more) return null;
+ return `owners:${id}:${key}:${pageIndex}`;
+ },
+ (k) => {
+ const pageIndex = parseInt(k.split(":").pop()!, 10);
+ return listOwnersPage({
+ repoId: id,
+ q: debouncedQ || undefined,
+ sort: filters.sort,
+ limit: LIMIT,
+ offset: pageIndex * LIMIT,
+ });
+ },
+ { revalidateOnFocus: false, revalidateFirstPage: false },
+ );
+
+ const items = useMemo(() => (data ? data.flatMap((p) => p.items) : []), [data]);
+ const total = data && data.length > 0 ? data[0].total : 0;
+ const hasMore = data ? data[data.length - 1].has_more : false;
+
+ 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">
+ <Users className="h-5 w-5 text-[var(--color-accent-primary)]" />
+ Contributors
+ </h1>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Who is doing what — ownership, hotspots, dead-code burden, and bus-factor risk
+ per person. Click any card to open the full profile.
+ </p>
+ </div>
+
+ <OwnerDirectory
+ owners={items}
+ isLoading={isLoading}
+ isValidating={isValidating}
+ total={total}
+ hasMore={hasMore}
+ filters={filters}
+ onFiltersChange={setFilters}
+ onLoadMore={() => setSize(size + 1)}
+ onSelect={(o) =>
+ router.push(`/repos/${id}/owners/${encodeURIComponent(o.key)}`)
+ }
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/risk/page.tsx b/packages/web/src/app/repos/[id]/risk/page.tsx
index 647d13090..268aa3ed2 100644
--- a/packages/web/src/app/repos/[id]/risk/page.tsx
+++ b/packages/web/src/app/repos/[id]/risk/page.tsx
@@ -8,9 +8,10 @@ import { HeatmapTab } from "@/components/risk/heatmap-tab";
import { HotspotsTab } from "@/components/risk/hotspots-tab";
import { DeadCodeTab } from "@/components/risk/dead-code-tab";
import { ImpactTab } from "@/components/risk/impact-tab";
+import { ModulesTab } from "@/components/risk/modules-tab";
import { RiskSummaryStrip } from "@/components/risk/risk-summary-strip";
-const TABS = ["heatmap", "hotspots", "dead-code", "impact"] as const;
+const TABS = ["heatmap", "hotspots", "modules", "dead-code", "impact"] as const;
type TabId = (typeof TABS)[number];
export default function RiskPage() {
@@ -52,6 +53,7 @@ export default function RiskPage() {
<TabsList className="h-auto flex-wrap">
<TabsTrigger value="heatmap">Heatmap</TabsTrigger>
<TabsTrigger value="hotspots">Hotspots</TabsTrigger>
+ <TabsTrigger value="modules">Modules</TabsTrigger>
<TabsTrigger value="dead-code">Dead code</TabsTrigger>
<TabsTrigger value="impact">Impact analyzer</TabsTrigger>
</TabsList>
@@ -62,6 +64,9 @@ export default function RiskPage() {
<TabsContent value="hotspots" className="space-y-6">
<HotspotsTab repoId={repoId} />
</TabsContent>
+ <TabsContent value="modules" className="space-y-6">
+ <ModulesTab repoId={repoId} />
+ </TabsContent>
<TabsContent value="dead-code" className="space-y-6">
<DeadCodeTab repoId={repoId} />
</TabsContent>
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 9f55a7ebe..acbda7a6f 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -22,6 +22,7 @@ import {
Layers,
Link2,
GitMerge,
+ Users,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";
@@ -56,6 +57,7 @@ function repoNavItems(repoId: string): NavItem[] {
{ label: "Risk", href: `/repos/${repoId}/risk`, icon: ShieldAlert },
{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
+ { label: "Contributors", href: `/repos/${repoId}/owners`, icon: Users },
{ label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },
{ label: "Docs", href: `/repos/${repoId}/docs`, icon: BookOpen },
{ label: "Costs", href: `/repos/${repoId}/costs`, icon: DollarSign },
diff --git a/packages/web/src/components/risk/heatmap-tab.tsx b/packages/web/src/components/risk/heatmap-tab.tsx
index 1d3b9c184..a92870a64 100644
--- a/packages/web/src/components/risk/heatmap-tab.tsx
+++ b/packages/web/src/components/risk/heatmap-tab.tsx
@@ -1,8 +1,11 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
+import { useRouter } from "next/navigation";
import useSWR from "swr";
import { OwnershipTreemap } from "@repowise-dev/ui/git/ownership-treemap";
+import { listModuleHealth } from "@/lib/api/modules";
+import type { ModuleHealthSummary } from "@/lib/api/types";
import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";
import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";
import { HotspotTrendStrip } from "@repowise-dev/ui/git/hotspot-trend-strip";
@@ -16,6 +19,7 @@ import type { OwnershipEntry, GitSummaryResponse, HotspotResponse } from "@/lib/
type Granularity = "module" | "file";
export function HeatmapTab({ repoId }: { repoId: string }) {
+ const router = useRouter();
const [granularity, setGranularity] = useState<Granularity>("module");
const { data: entries, isLoading: loadingEntries } = useSWR<OwnershipEntry[]>(
@@ -33,6 +37,21 @@ export function HeatmapTab({ repoId }: { repoId: string }) {
() => getHotspots(repoId, 100),
{ revalidateOnFocus: false },
);
+ // Module-level bus-factor overlay for the treemap. Only needed at module
+ // granularity — file mode uses its own per-row bus factor in tooltips.
+ const { data: moduleHealth } = useSWR(
+ granularity === "module" ? `module-health:${repoId}:all` : null,
+ () => listModuleHealth(repoId, { sort: "file_count", limit: 500 }),
+ { revalidateOnFocus: false },
+ );
+
+ const busFactorByModule = useMemo(() => {
+ const map: Record<string, number> = {};
+ for (const m of (moduleHealth?.items ?? []) as ModuleHealthSummary[]) {
+ map[m.module_path] = Math.round(m.median_bus_factor);
+ }
+ return map;
+ }, [moduleHealth]);
const list = entries ?? [];
@@ -63,12 +82,21 @@ export function HeatmapTab({ repoId }: { repoId: string }) {
</div>
</div>
<p className="text-xs text-[var(--color-text-tertiary)] pt-1">
- Tile size = code volume. Color = ownership concentration; red tiles are silos
- (single owner &gt; 80%).
+ Tile size = code volume. Color = primary owner. Border = bus factor —
+ red ≤1, amber 2, green ≥3. Dashed amber outline marks silo modules
+ (one owner &gt;80%).
</p>
</CardHeader>
<CardContent className="pt-0">
- <OwnershipTreemap entries={list} />
+ <OwnershipTreemap
+ entries={list}
+ busFactorByModule={granularity === "module" ? busFactorByModule : undefined}
+ onSelect={(e) =>
+ router.push(
+ `/repos/${repoId}/modules/${encodeURIComponent(e.module_path)}`,
+ )
+ }
+ />
</CardContent>
</Card>
) : null}
@@ -108,14 +136,23 @@ export function HeatmapTab({ repoId }: { repoId: string }) {
<CardContent className="pt-0">
<ContributorBar owners={summary.top_owners} />
<div className="mt-3 space-y-1.5">
- {summary.top_owners.slice(0, 10).map((o, i) => (
- <div key={o.email || `owner-${i}`} className="flex items-center justify-between text-xs">
- <span className="text-[var(--color-text-secondary)] truncate">{o.name}</span>
- <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
- {Math.round((o.pct ?? 0) * 100)}%
- </span>
- </div>
- ))}
+ {summary.top_owners.slice(0, 10).map((o, i) => {
+ const key = o.email ?? `name:${o.name}`;
+ return (
+ <button
+ key={o.email || `owner-${i}`}
+ onClick={() =>
+ router.push(`/repos/${repoId}/owners/${encodeURIComponent(key)}`)
+ }
+ className="flex w-full items-center justify-between rounded-md px-2 py-1 text-xs hover:bg-[var(--color-bg-elevated)]"
+ >
+ <span className="text-[var(--color-text-secondary)] truncate text-left">{o.name}</span>
+ <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
+ {Math.round((o.pct ?? 0) * 100)}%
+ </span>
+ </button>
+ );
+ })}
</div>
</CardContent>
</Card>
diff --git a/packages/web/src/components/risk/modules-tab.tsx b/packages/web/src/components/risk/modules-tab.tsx
new file mode 100644
index 000000000..68e8c6cf2
--- /dev/null
+++ b/packages/web/src/components/risk/modules-tab.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import useSWRInfinite from "swr/infinite";
+import { useRouter } from "next/navigation";
+import { Folder } from "lucide-react";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@repowise-dev/ui/ui/select";
+import { ModuleHealthList } from "@repowise-dev/ui/modules/module-health-list";
+import { listModuleHealth, type ModuleHealthSortKey } from "@/lib/api/modules";
+import type { ModuleHealthSummary, Paginated } from "@/lib/api/types";
+
+const PAGE = 30;
+const SORT_LABELS: Record<ModuleHealthSortKey, string> = {
+ health_score: "Lowest health first",
+ hotspot_count: "Most hotspots",
+ dead_code_lines: "Most dead code",
+ file_count: "Largest modules",
+};
+
+/**
+ * "Modules" tab on /risk — engineering-leader rollup of churn / ownership /
+ * docs / dead-code / decisions per top-level module.
+ */
+export function ModulesTab({ repoId }: { repoId: string }) {
+ const router = useRouter();
+ const [sort, setSort] = useState<ModuleHealthSortKey>("health_score");
+
+ const { data, isLoading, isValidating, size, setSize } = useSWRInfinite<
+ Paginated<ModuleHealthSummary>
+ >(
+ (pageIndex, previous) => {
+ if (previous && !previous.has_more) return null;
+ return `module-health:${repoId}:${sort}:${pageIndex}`;
+ },
+ (key) => {
+ const pageIndex = parseInt(key.split(":").pop()!, 10);
+ return listModuleHealth(repoId, {
+ sort,
+ limit: PAGE,
+ offset: pageIndex * PAGE,
+ });
+ },
+ { revalidateOnFocus: false, revalidateFirstPage: false },
+ );
+
+ const items = useMemo(() => (data ? data.flatMap((p) => p.items) : []), [data]);
+ const total = data && data.length > 0 ? data[0].total : 0;
+ const hasMore = data ? data[data.length - 1].has_more : false;
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">
+ <Folder className="h-4 w-4" />
+ <span>
+ Health rollup across every top-level module — composite of churn, ownership,
+ docs, dead-code and decisions.
+ </span>
+ </div>
+ <Select value={sort} onValueChange={(v) => setSort(v as ModuleHealthSortKey)}>
+ <SelectTrigger className="w-[200px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(SORT_LABELS).map(([k, label]) => (
+ <SelectItem key={k} value={k}>
+ {label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <ModuleHealthList
+ modules={items}
+ isLoading={isLoading}
+ total={total}
+ hasMore={hasMore}
+ loadingMore={isValidating && !isLoading}
+ onLoadMore={() => setSize(size + 1)}
+ onSelect={(m) =>
+ router.push(`/repos/${repoId}/modules/${encodeURIComponent(m.module_path)}`)
+ }
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/risk/risk-summary-strip.tsx b/packages/web/src/components/risk/risk-summary-strip.tsx
index 52e319c5a..7fb865a25 100644
--- a/packages/web/src/components/risk/risk-summary-strip.tsx
+++ b/packages/web/src/components/risk/risk-summary-strip.tsx
@@ -9,6 +9,8 @@ import { getDeadCodeSummary } from "@/lib/api/dead-code";
import { getDecisionHealth } from "@/lib/api/decisions";
import { listSecurityFindings } from "@/lib/api/security";
+const RISK_BASE = (repoId: string) => `/repos/${repoId}/risk`;
+
/**
* Always-visible 5-card strip atop /repos/[id]/risk. Pulls cached SWR data
* shared with the tab bodies, so switching tabs doesn't trigger refetches.
@@ -49,24 +51,28 @@ export function RiskSummaryStrip({ repoId }: { repoId: string }) {
value={formatNumber(gitSummary?.hotspot_count ?? 0)}
description="high-churn files"
icon={<Flame className="h-4 w-4 text-orange-400" />}
+ href={`${RISK_BASE(repoId)}?tab=hotspots`}
/>
<StatCard
label="Silos"
value={formatNumber(siloCount)}
description="single-owner modules"
icon={<Users className="h-4 w-4 text-amber-400" />}
+ href={`${RISK_BASE(repoId)}?tab=heatmap`}
/>
<StatCard
label="Reclaimable"
value={formatNumber(reclaimable)}
description="lines safe to delete"
icon={<Trash2 className="h-4 w-4 text-rose-400" />}
+ href={`${RISK_BASE(repoId)}?tab=dead-code`}
/>
<StatCard
label="Stale Decisions"
value={formatNumber(staleDecisions)}
description="needing review"
icon={<Lightbulb className="h-4 w-4 text-yellow-400" />}
+ href={`/repos/${repoId}/decisions`}
/>
<StatCard
label="Security"
@@ -77,6 +83,7 @@ export function RiskSummaryStrip({ repoId }: { repoId: string }) {
: "scan not run"
}
icon={<ShieldAlert className="h-4 w-4 text-red-400" />}
+ href={`/repos/${repoId}/security`}
/>
</div>
);
diff --git a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
index 6ed449311..9f5e6ff2a 100644
--- a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
@@ -6,6 +6,7 @@ import useSWR from "swr";
import { SymbolGitPanel } from "@repowise-dev/ui/symbols/symbol-git-panel";
import { getCoChanges, getGitMetadata } from "@/lib/api/git";
import { listDeadCode } from "@/lib/api/dead-code";
+import { listDecisions } from "@/lib/api/decisions";
import type { SymbolResponse } from "@/lib/api/types";
interface Props {
@@ -47,6 +48,15 @@ export function SymbolGitPanelWrapper({ symbol, repoId }: Props) {
{ revalidateOnFocus: false },
);
+ // Decisions governing the module containing this file. Module-scope
+ // matches the existing decision `affected_modules_json` convention.
+ const modulePath = filePath.split("/", 2)[0];
+ const { data: decisions } = useSWR(
+ modulePath ? `decisions:${repoId}:${modulePath}` : null,
+ () => listDecisions(repoId, { module: modulePath, limit: 25 }),
+ { revalidateOnFocus: false },
+ );
+
const overlappingDead = useMemo(() => {
if (!deadFindings) return [];
return deadFindings.filter((f) => {
@@ -90,6 +100,18 @@ export function SymbolGitPanelWrapper({ symbol, repoId }: Props) {
lines: f.lines,
safe_to_delete: f.safe_to_delete,
}))}
+ governingDecisions={(decisions ?? []).map((d) => ({
+ id: d.id,
+ title: d.title,
+ status: d.status,
+ }))}
+ onSelectOwner={(name, email) => {
+ const key = email ?? `name:${name}`;
+ router.push(`/repos/${repoId}/owners/${encodeURIComponent(key)}`);
+ }}
+ onSelectDecision={(id) =>
+ router.push(`/repos/${repoId}/decisions/${encodeURIComponent(id)}`)
+ }
onOpenBlastRadius={() =>
router.push(`/repos/${repoId}/blast-radius?file=${encodeURIComponent(filePath)}`)
}
diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.ts
index 68ac7948f..b80e1513b 100644
--- a/packages/web/src/lib/api/git.ts
+++ b/packages/web/src/lib/api/git.ts
@@ -5,6 +5,7 @@ import type {
HotspotResponse,
OwnershipEntry,
Paginated,
+ ReviewerSuggestionsResponse,
} from "./types";
export async function getGitMetadata(
@@ -82,6 +83,21 @@ export async function getCoChanges(
});
}
+export async function getReviewerSuggestions(
+ repoId: string,
+ paths: string[],
+ limit = 10,
+): Promise<ReviewerSuggestionsResponse> {
+ // FastAPI repeats `?paths=` per entry; URLSearchParams handles that for
+ // us when we hand it tuples.
+ const sp = new URLSearchParams();
+ for (const p of paths) sp.append("paths", p);
+ sp.append("limit", String(limit));
+ return apiGet<ReviewerSuggestionsResponse>(
+ `/api/repos/${repoId}/reviewer-suggestions?${sp.toString()}`,
+ );
+}
+
export async function getGitSummary(
repoId: string,
topOwnersLimit?: number,
diff --git a/packages/web/src/lib/api/modules.ts b/packages/web/src/lib/api/modules.ts
new file mode 100644
index 000000000..ca2d9bebb
--- /dev/null
+++ b/packages/web/src/lib/api/modules.ts
@@ -0,0 +1,31 @@
+import { apiGet } from "./client";
+import type {
+ ModuleHealthDetail,
+ ModuleHealthSummary,
+ Paginated,
+} from "./types";
+
+export type ModuleHealthSortKey =
+ | "health_score"
+ | "hotspot_count"
+ | "dead_code_lines"
+ | "file_count";
+
+export async function listModuleHealth(
+ repoId: string,
+ options: { sort?: ModuleHealthSortKey; limit?: number; offset?: number } = {},
+): Promise<Paginated<ModuleHealthSummary>> {
+ return apiGet<Paginated<ModuleHealthSummary>>(
+ `/api/repos/${repoId}/modules/health`,
+ options,
+ );
+}
+
+export async function getModuleHealth(
+ repoId: string,
+ modulePath: string,
+): Promise<ModuleHealthDetail> {
+ return apiGet<ModuleHealthDetail>(
+ `/api/repos/${repoId}/modules/health/${encodeURIComponent(modulePath)}`,
+ );
+}
diff --git a/packages/web/src/lib/api/owners.ts b/packages/web/src/lib/api/owners.ts
new file mode 100644
index 000000000..f570a944f
--- /dev/null
+++ b/packages/web/src/lib/api/owners.ts
@@ -0,0 +1,37 @@
+import { apiGet } from "./client";
+import type {
+ OwnerListEntry,
+ OwnerProfileResponse,
+ Paginated,
+} from "./types";
+
+export type OwnerSortKey =
+ | "files_owned"
+ | "hotspots_owned"
+ | "commit_count_90d"
+ | "dead_code_lines_owned"
+ | "bus_factor_risk_files";
+
+export interface ListOwnersParams {
+ repoId: string;
+ q?: string;
+ sort?: OwnerSortKey;
+ limit?: number;
+ offset?: number;
+}
+
+export async function listOwnersPage(
+ params: ListOwnersParams,
+): Promise<Paginated<OwnerListEntry>> {
+ const { repoId, ...rest } = params;
+ return apiGet<Paginated<OwnerListEntry>>(`/api/repos/${repoId}/owners`, rest);
+}
+
+export async function getOwnerProfile(
+ repoId: string,
+ ownerKey: string,
+): Promise<OwnerProfileResponse> {
+ return apiGet<OwnerProfileResponse>(
+ `/api/repos/${repoId}/owners/${encodeURIComponent(ownerKey)}`,
+ );
+}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 41bca28ac..677cf4753 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -829,3 +829,121 @@ export interface WorkspaceGraphResponse {
nodes: WorkspaceGraphNode[];
edges: WorkspaceGraphEdge[];
}
+
+// ---------------------------------------------------------------------------
+// Owner / contributor profile
+// ---------------------------------------------------------------------------
+
+export interface OwnerListEntry {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ bus_factor_risk_files: number;
+}
+
+export interface OwnerModuleRollup {
+ module_path: string;
+ file_count: number;
+ hotspot_count: number;
+ dominant_pct: number;
+}
+
+export interface OwnerFileEntry {
+ file_path: string;
+ commit_count_90d: number;
+ churn_percentile: number;
+ bus_factor: number;
+ is_hotspot: boolean;
+ last_commit_at: string | null;
+ primary_owner_commit_pct: number | null;
+}
+
+export interface OwnerCoAuthor {
+ name: string;
+ email: string | null;
+ shared_files: number;
+ co_change_strength: number;
+}
+
+export interface OwnerProfileResponse {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ first_commit_at: string | null;
+ bus_factor_risk_files: number;
+ lines_added_90d_est: number;
+ lines_deleted_90d_est: number;
+ modules: OwnerModuleRollup[];
+ top_files: OwnerFileEntry[];
+ co_authors: OwnerCoAuthor[];
+ commit_categories: Record<string, number>;
+}
+
+// ---------------------------------------------------------------------------
+// Module health
+// ---------------------------------------------------------------------------
+
+export interface ModuleHealthOwner {
+ name: string;
+ email: string | null;
+ file_count: number;
+ pct: number;
+}
+
+export interface ModuleHealthSummary {
+ module_path: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count: number;
+ dead_code_count: number;
+ dead_code_lines: number;
+ avg_churn_percentile: number;
+ median_bus_factor: number;
+ min_bus_factor: number;
+ primary_owner: string | null;
+ primary_owner_pct: number;
+ is_silo: boolean;
+ decision_count: number;
+ doc_coverage_pct: number;
+ health_score: number;
+}
+
+export interface ModuleHealthDetail extends ModuleHealthSummary {
+ owners: ModuleHealthOwner[];
+ top_hotspots: string[];
+ governing_decisions: string[];
+ contributor_count: number;
+}
+
+// ---------------------------------------------------------------------------
+// Reviewer suggestions
+// ---------------------------------------------------------------------------
+
+export interface ReviewerSuggestion {
+ name: string;
+ email: string | null;
+ score: number;
+ recent_commits: number;
+ owned_paths: string[];
+ co_change_paths: string[];
+ reasons: string[];
+}
+
+export interface ReviewerSuggestionsResponse {
+ paths: string[];
+ suggestions: ReviewerSuggestion[];
+}
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index 7e80e599a..1f4415e9f 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -33,6 +33,8 @@ def _create_test_app():
graph,
health,
jobs,
+ modules,
+ owners,
pages,
repos,
search,
@@ -70,6 +72,8 @@ def _create_test_app():
app.include_router(webhooks.router)
app.include_router(git.router)
app.include_router(dead_code.router)
+ app.include_router(owners.router)
+ app.include_router(modules.router)
return app
diff --git a/tests/unit/server/test_modules_health.py b/tests/unit/server/test_modules_health.py
new file mode 100644
index 000000000..206b6926c
--- /dev/null
+++ b/tests/unit/server/test_modules_health.py
@@ -0,0 +1,76 @@
+"""Tests for /api/repos/{id}/modules/health."""
+
+from __future__ import annotations
+
+import json
+from urllib.parse import quote
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/main.py",
+ commit_count_total=50,
+ commit_count_90d=20,
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.9,
+ top_authors_json=json.dumps(
+ [{"name": "Alice", "email": "[email protected]", "commit_count": 45}]
+ ),
+ is_hotspot=True,
+ churn_percentile=0.9,
+ bus_factor=1,
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/utils.py",
+ commit_count_total=10,
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.6,
+ top_authors_json=json.dumps(
+ [{"name": "Alice", "email": "[email protected]", "commit_count": 6}]
+ ),
+ is_hotspot=False,
+ churn_percentile=0.3,
+ bus_factor=2,
+ )
+
+
+async def test_list_module_health(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/modules/health")
+ assert resp.status_code == 200
+ payload = resp.json()
+ assert payload["total"] >= 1
+ src = next(m for m in payload["items"] if m["module_path"] == "src")
+ assert src["file_count"] == 2
+ assert src["hotspot_count"] == 1
+ assert 0 <= src["health_score"] <= 100
+
+
+async def test_get_module_health_detail(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/modules/health/{quote('src')}")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["module_path"] == "src"
+ assert data["file_count"] == 2
+ assert any(o["name"] == "Alice" for o in data["owners"])
diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.py
new file mode 100644
index 000000000..a39f40794
--- /dev/null
+++ b/tests/unit/server/test_owners.py
@@ -0,0 +1,110 @@
+"""Tests for /api/repos/{id}/owners — contributor profile endpoints."""
+
+from __future__ import annotations
+
+import json
+from urllib.parse import quote
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/main.py",
+ commit_count_total=50,
+ commit_count_90d=20,
+ commit_count_30d=5,
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.7,
+ top_authors_json=json.dumps(
+ [
+ {"name": "Alice", "email": "[email protected]", "commit_count": 35},
+ {"name": "Bob", "email": "[email protected]", "commit_count": 15},
+ ]
+ ),
+ co_change_partners_json=json.dumps(
+ [{"file_path": "src/utils.py", "co_change_count": 8}]
+ ),
+ is_hotspot=True,
+ is_stable=False,
+ churn_percentile=0.9,
+ bus_factor=1,
+ contributor_count=2,
+ lines_added_90d=300,
+ lines_deleted_90d=100,
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/utils.py",
+ commit_count_total=10,
+ commit_count_90d=2,
+ primary_owner_name="Bob",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.9,
+ top_authors_json=json.dumps(
+ [
+ {"name": "Bob", "email": "[email protected]", "commit_count": 9},
+ {"name": "Alice", "email": "[email protected]", "commit_count": 1},
+ ]
+ ),
+ is_hotspot=False,
+ churn_percentile=0.2,
+ bus_factor=3,
+ contributor_count=2,
+ )
+
+
+async def test_list_owners(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/owners")
+ assert resp.status_code == 200
+ payload = resp.json()
+ assert payload["total"] == 2
+ names = {item["name"] for item in payload["items"]}
+ assert names == {"Alice", "Bob"}
+
+ alice = next(i for i in payload["items"] if i["name"] == "Alice")
+ assert alice["files_owned"] == 1
+ assert alice["hotspots_owned"] == 1
+ assert alice["bus_factor_risk_files"] == 1
+
+
+async def test_get_owner_profile(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ key = quote("[email protected]", safe="")
+ resp = await client.get(f"/api/repos/{repo['id']}/owners/{key}")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["name"] == "Alice"
+ assert data["files_owned"] == 1
+ assert data["hotspots_owned"] == 1
+ # Alice touched both files (she's in top_authors of utils too).
+ paths = {f["file_path"] for f in data["top_files"]}
+ assert "src/main.py" in paths
+ assert "src/utils.py" in paths
+ # Bob should appear as a co-author.
+ coauthors = {c["name"] for c in data["co_authors"]}
+ assert "Bob" in coauthors
+
+
+async def test_get_owner_profile_not_found(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/owners/ghost@nowhere")
+ assert resp.status_code == 404
diff --git a/tests/unit/server/test_reviewer_suggestions.py b/tests/unit/server/test_reviewer_suggestions.py
new file mode 100644
index 000000000..2f241a682
--- /dev/null
+++ b/tests/unit/server/test_reviewer_suggestions.py
@@ -0,0 +1,79 @@
+"""Tests for /api/repos/{id}/reviewer-suggestions."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/main.py",
+ commit_count_total=50,
+ commit_count_90d=20,
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ top_authors_json=json.dumps(
+ [
+ {"name": "Alice", "email": "[email protected]", "commit_count": 40},
+ {"name": "Bob", "email": "[email protected]", "commit_count": 10},
+ ]
+ ),
+ co_change_partners_json=json.dumps(
+ [{"file_path": "src/utils.py", "co_change_count": 6}]
+ ),
+ is_hotspot=True,
+ churn_percentile=0.9,
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/utils.py",
+ commit_count_total=20,
+ commit_count_90d=5,
+ primary_owner_name="Carol",
+ primary_owner_email="[email protected]",
+ top_authors_json=json.dumps(
+ [{"name": "Carol", "email": "[email protected]", "commit_count": 20}]
+ ),
+ is_hotspot=False,
+ churn_percentile=0.3,
+ )
+
+
+async def test_reviewer_suggestions(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/reviewer-suggestions",
+ params=[("paths", "src/main.py")],
+ )
+ assert resp.status_code == 200
+ payload = resp.json()
+ names = [s["name"] for s in payload["suggestions"]]
+ # Alice (direct) should be ranked first; Carol comes in via co-change.
+ assert names[0] == "Alice"
+ assert "Carol" in names
+
+
+async def test_reviewer_suggestions_empty_paths(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/reviewer-suggestions",
+ params=[("paths", "")],
+ )
+ # FastAPI accepts empty string as path; result should be empty.
+ assert resp.status_code == 200
+ assert resp.json()["suggestions"] == []