Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(web): add repo Stats "By the Numbers" page (#548)
Raghav Chamadiyaa48a9df20cb5
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 92227ee10..94dcb923b 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -56,6 +56,7 @@ from repowise.server.routers import (repos,search,security,+ stats,symbols,webhooks,workspace,@@ -417,6 +418,7 @@ def create_app() -> FastAPI:app.include_router(owners.router)app.include_router(modules.router)app.include_router(overview.router)+ app.include_router(stats.router)app.include_router(files.router)app.include_router(external_systems.router)diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.pynew file mode 100644index 000000000..1c066a588--- /dev/null+++ b/packages/server/src/repowise/server/routers/stats.py@@ -0,0 +1,427 @@+"""/api/repos/{repo_id}/stats/highlights — the "By the Numbers" payload.++A single read-only aggregate that powers the repo Stats page: a showcase of+signals the engine already computes across every layer (graph, git, health,+docs, decisions, dead code) plus a handful of fun superlatives and a derived+"size class" label. Nothing here is new analysis — it stitches together rows+the indexer already wrote, so the page is cheap and never blocks.++Every section is built defensively: a missing table or column degrades that+section to ``None`` / empty rather than 500-ing the whole page, mirroring the+overview-summary contract.+"""++from __future__ import annotations++import json+from typing import Any++from fastapi import APIRouter, Depends, HTTPException+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence import crud+from repowise.core.persistence.models import (+ DecisionRecord,+ GitCommit,+ GitMetadata,+ GraphNode,+ Page,+ WikiSymbol,+)+from repowise.server.deps import get_db_session, verify_api_key++router = APIRouter(+ prefix="/api/repos",+ tags=["stats"],+ dependencies=[Depends(verify_api_key)],+)+++# ---------------------------------------------------------------------------+# Size class — a playful, NLOC-driven label for "how big is this codebase".+# Thresholds are on non-comment lines of code (the health-metric NLOC sum),+# the most honest single proxy for scale across languages.+# ---------------------------------------------------------------------------++_SIZE_CLASSES: tuple[tuple[int, str, str], ...] = (+ (1_000, "Seedling", "A fresh sprout — small enough to hold in your head."),+ (5_000, "Hamlet", "A cozy codebase you could read in an afternoon."),+ (20_000, "Village", "A tidy village — a few neighborhoods, easy to walk."),+ (60_000, "Town", "A proper town with its own districts and main streets."),+ (150_000, "City", "A real city — busy, layered, plenty going on."),+ (500_000, "Metropolis", "A sprawling metropolis with serious infrastructure."),+)+_MEGALOPOLIS = ("Megalopolis", "A vast megalopolis — its own self-contained world.")+++def _size_class(total_nloc: int) -> dict[str, Any]:+ for ceiling, name, blurb in _SIZE_CLASSES:+ if total_nloc < ceiling:+ return {"name": name, "blurb": blurb, "nloc": total_nloc}+ name, blurb = _MEGALOPOLIS+ return {"name": name, "blurb": blurb, "nloc": total_nloc}+++def _iso(dt: Any) -> str | None:+ return dt.isoformat() if dt is not None else None+++async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dict[str, Any]:+ """Graph + NLOC scale signals + the size-class label."""+ file_count = (+ await session.scalar(+ select(func.count(GraphNode.id)).where(+ GraphNode.repository_id == repo_id, GraphNode.node_type == "file"+ )+ )+ or 0+ )+ symbol_count = int(+ await session.scalar(+ select(func.sum(GraphNode.symbol_count)).where(GraphNode.repository_id == repo_id)+ )+ or 0+ )+ entry_point_count = (+ await session.scalar(+ select(func.count(GraphNode.id)).where(+ GraphNode.repository_id == repo_id,+ GraphNode.is_entry_point.is_(True),+ )+ )+ or 0+ )+ total_nloc = sum(int(m.nloc or 0) for m in metrics)++ lang_rows = await session.execute(+ select(GraphNode.language, func.count(GraphNode.id))+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")+ .group_by(GraphNode.language)+ )+ languages = sorted(+ ({"language": lang or "other", "file_count": n} for lang, n in lang_rows),+ key=lambda r: -r["file_count"],+ )+ module_count = len({m.module for m in metrics if m.module})++ return {+ "file_count": file_count,+ "symbol_count": symbol_count,+ "entry_point_count": entry_point_count,+ "module_count": module_count,+ "total_nloc": total_nloc,+ "language_count": len(languages),+ "languages": languages,+ "size_class": _size_class(total_nloc),+ }+++async def _activity(session: AsyncSession, repo_id: str) -> dict[str, Any]:+ """Commit volume, project age, agent-vs-human split, and a monthly series.++ Buckets the bounded ``git_commits`` table in Python so it is portable+ across SQLite/Postgres date functions (same approach as the agent-trend+ endpoint)."""+ rows = (+ await session.execute(+ select(+ GitCommit.committed_at,+ GitCommit.author_email,+ GitCommit.agent_name,+ GitCommit.is_fix,+ ).where(GitCommit.repository_id == repo_id)+ )+ ).all()++ total = 0+ agent_total = 0+ fix_total = 0+ months: dict[str, dict[str, int]] = {}+ agent_names: dict[str, int] = {}+ contributors: set[str] = set()+ first_at: Any = None+ last_at: Any = None++ for committed_at, author_email, agent_name, is_fix in rows:+ total += 1+ if author_email:+ contributors.add(author_email.lower())+ if is_fix:+ fix_total += 1+ if agent_name:+ agent_total += 1+ agent_names[agent_name] = agent_names.get(agent_name, 0) + 1+ if committed_at is not None:+ if first_at is None or committed_at < first_at:+ first_at = committed_at+ if last_at is None or committed_at > last_at:+ last_at = committed_at+ key = committed_at.strftime("%Y-%m")+ b = months.setdefault(key, {"total": 0, "agent": 0})+ b["total"] += 1+ if agent_name:+ b["agent"] += 1++ monthly = [+ {"month": m, "total": b["total"], "agent": b["agent"]} for m, b in sorted(months.items())+ ]+ busiest = max(monthly, key=lambda r: r["total"], default=None)+ age_days = (last_at - first_at).days if (first_at and last_at) else None++ return {+ "total_commits": total,+ "agent_commits": agent_total,+ "agent_pct": round(agent_total / total * 100.0, 1) if total else 0.0,+ "fix_commits": fix_total,+ "fix_pct": round(fix_total / total * 100.0, 1) if total else 0.0,+ "contributor_count": len(contributors),+ "first_commit_at": _iso(first_at),+ "last_commit_at": _iso(last_at),+ "age_days": age_days,+ "busiest_month": busiest,+ "monthly": monthly,+ "agent_names": sorted(+ ({"name": k, "count": v} for k, v in agent_names.items()),+ key=lambda x: -x["count"],+ ),+ }+++async def _people(session: AsyncSession, repo_id: str, all_meta: list[Any]) -> dict[str, Any]:+ """Ownership concentration: top owners, single-owner files, module silos."""+ owners: dict[str, int] = {}+ single_owner_files = 0+ module_owner_files: dict[str, dict[str, int]] = {}+ module_file_totals: dict[str, int] = {}++ for m in all_meta:+ if m.primary_owner_name:+ owners[m.primary_owner_name] = owners.get(m.primary_owner_name, 0) + 1+ if (m.bus_factor or 0) == 1:+ single_owner_files += 1+ parts = m.file_path.split("/")+ module = parts[0] if len(parts) > 1 else "root"+ module_file_totals[module] = module_file_totals.get(module, 0) + 1+ if m.primary_owner_name:+ bucket = module_owner_files.setdefault(module, {})+ bucket[m.primary_owner_name] = bucket.get(m.primary_owner_name, 0) + 1++ total_files = len(all_meta) or 1+ top_owners = sorted(+ ({"name": k, "file_count": v, "pct": v / total_files} for k, v in owners.items()),+ key=lambda x: -x["file_count"],+ )[:8]++ silo_count = 0+ for module, mowners in module_owner_files.items():+ top = max(mowners.values(), default=0)+ if module_file_totals.get(module) and top / module_file_totals[module] > 0.8:+ silo_count += 1++ return {+ "owner_count": len(owners),+ "top_owners": top_owners,+ "single_owner_files": single_owner_files,+ "silo_count": silo_count,+ }+++async def _quality(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dict[str, Any]:+ """Health KPIs + the defect-validation stat + dead code + doc coverage."""+ from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+ from repowise.core.analysis.health.grading import distribution as health_distribution++ summary = await crud.get_health_summary(session, repo_id)+ findings = await crud.get_health_findings(session, repo_id)++ severity = {"critical": 0, "high": 0, "medium": 0, "low": 0}+ for f in findings:+ s = (f.severity or "").lower()+ if s in severity:+ severity[s] += 1++ metric_dicts = [+ {+ "file_path": m.file_path,+ "score": m.score,+ "nloc": m.nloc,+ "has_test_file": m.has_test_file,+ "module": m.module,+ }+ for m in metrics+ ]+ finding_dicts = [+ {+ "file_path": f.file_path,+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ }+ for f in findings+ ]+ try:+ defect_accuracy = compute_defect_accuracy(metric_dicts, finding_dicts)+ except Exception:+ defect_accuracy = None+ try:+ dist = health_distribution(metric_dicts)+ except Exception:+ dist = None++ # Dead code rollup+ dead = await crud.get_dead_code_findings(session, repo_id, status="open")+ deletable_lines = sum(int(f.lines or 0) for f in dead if f.safe_to_delete)+ dead_total = len(dead)++ # Doc coverage (avg page confidence) + page count+ avg_conf = float(+ await session.scalar(select(func.avg(Page.confidence)).where(Page.repository_id == repo_id))+ or 0.0+ )+ page_count = (+ await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0+ )++ # Test coverage: share of health-metric files that have a test file.+ tested = sum(1 for m in metrics if m.has_test_file)+ test_coverage_pct = round(tested / len(metrics) * 100.0, 1) if metrics else None++ return {+ "average_health": summary.get("average_health"),+ "maintainability_average": summary.get("maintainability_average"),+ "performance_average": summary.get("performance_average"),+ "worst_performer_path": summary.get("worst_performer_path"),+ "worst_performer_score": summary.get("worst_performer_score"),+ "open_findings": summary.get("open_findings", len(findings)),+ "severity_breakdown": severity,+ "defect_accuracy": defect_accuracy,+ "distribution": dist,+ "doc_coverage_pct": avg_conf * 100.0,+ "page_count": page_count,+ "test_coverage_pct": test_coverage_pct,+ "dead_code": {"total_findings": dead_total, "deletable_lines": deletable_lines},+ }+++async def _superlatives(+ session: AsyncSession, repo_id: str, metrics: list[Any], all_meta: list[Any]+) -> dict[str, Any]:+ """The fun "biggest / oldest / most" awards, one row each."""+ out: dict[str, Any] = {}++ # Largest file by NLOC+ largest = max(metrics, key=lambda m: m.nloc or 0, default=None)+ if largest is not None and (largest.nloc or 0) > 0:+ out["largest_file"] = {"path": largest.file_path, "nloc": int(largest.nloc)}++ # Most complex symbol+ sym = (+ await session.execute(+ select(WikiSymbol.name, WikiSymbol.file_path, WikiSymbol.complexity_estimate)+ .where(WikiSymbol.repository_id == repo_id)+ .order_by(WikiSymbol.complexity_estimate.desc())+ .limit(1)+ )+ ).first()+ if sym is not None and (sym[2] or 0) > 0:+ out["most_complex_symbol"] = {+ "name": sym[0],+ "file_path": sym[1],+ "complexity": int(sym[2]),+ }++ # Most-changed file + oldest file (from git metadata)+ most_changed = max(all_meta, key=lambda m: m.commit_count_total or 0, default=None)+ if most_changed is not None and (most_changed.commit_count_total or 0) > 0:+ out["most_changed_file"] = {+ "path": most_changed.file_path,+ "commit_count": int(most_changed.commit_count_total),+ }+ dated = [m for m in all_meta if m.first_commit_at is not None]+ if dated:+ oldest = min(dated, key=lambda m: m.first_commit_at)+ out["oldest_file"] = {+ "path": oldest.file_path,+ "first_commit_at": _iso(oldest.first_commit_at),+ }++ # Most central file (highest PageRank file node)+ central = (+ await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank)+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")+ .order_by(GraphNode.pagerank.desc())+ .limit(1)+ )+ ).first()+ if central is not None and (central[1] or 0) > 0:+ out["most_central_file"] = {"path": central[0], "pagerank": round(float(central[1]), 4)}++ # Strongest hidden coupling pair (max co-change count across files)+ best_pair: dict[str, Any] | None = None+ for m in all_meta:+ try:+ partners = json.loads(m.co_change_partners_json or "[]")+ except Exception:+ continue+ for p in partners:+ count = p.get("co_change_count", 0)+ other = p.get("file_path") or p.get("partner")+ if other and (best_pair is None or count > best_pair["count"]):+ best_pair = {"a": m.file_path, "b": other, "count": count}+ if best_pair and best_pair["count"] > 0:+ out["strongest_coupling"] = best_pair++ return out++[email protected]("/{repo_id}/stats/highlights")+async def stats_highlights(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """Everything the Stats ("By the Numbers") page needs, in one call."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ metrics = await crud.get_health_metrics(session, repo_id)+ all_meta = list(+ (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))+ .scalars()+ .all()+ )++ decision_count = (+ await session.scalar(+ select(func.count(DecisionRecord.id)).where(DecisionRecord.repository_id == repo_id)+ )+ or 0+ )+ active_decisions = (+ await session.scalar(+ select(func.count(DecisionRecord.id)).where(+ DecisionRecord.repository_id == repo_id,+ DecisionRecord.status == "active",+ )+ )+ or 0+ )++ return {+ "repo": {+ "id": repo.id,+ "name": repo.name,+ "default_branch": repo.default_branch,+ "head_commit": repo.head_commit,+ },+ "scale": await _scale(session, repo_id, metrics),+ "activity": await _activity(session, repo_id),+ "people": await _people(session, repo_id, all_meta),+ "quality": await _quality(session, repo_id, metrics),+ "knowledge": {+ "decision_count": decision_count,+ "active_decision_count": active_decisions,+ },+ "superlatives": await _superlatives(session, repo_id, metrics, all_meta),+ }diff --git a/packages/types/package.json b/packages/types/package.jsonindex 0e6d8a7ef..fb67a3277 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -27,7 +27,8 @@"./files": "./src/files.ts","./external-systems": "./src/external-systems.ts","./health": "./src/health.ts",- "./coupling": "./src/coupling.ts"+ "./coupling": "./src/coupling.ts",+ "./stats": "./src/stats.ts"},"publishConfig": {"registry": "https://npm.pkg.github.com",diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex e12ed4cee..44f756282 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -27,3 +27,4 @@ export * from "./files.js";export * from "./external-systems.js";export * from "./health.js";export * from "./coupling.js";+export * from "./stats.js";diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.tsnew file mode 100644index 000000000..df94747d3--- /dev/null+++ b/packages/types/src/stats.ts@@ -0,0 +1,155 @@+/**+ * Data contract for the repo Stats ("By the Numbers") page.+ *+ * Mirrors the payload from `GET /api/repos/{repo_id}/stats/highlights`+ * (packages/server/.../routers/stats.py). Every section is independently+ * built server-side and degrades to null/empty rather than failing the page,+ * so most leaf fields are nullable.+ */++export interface StatsSizeClass {+ name: string;+ blurb: string;+ nloc: number;+}++export interface StatsLanguage {+ language: string;+ file_count: number;+}++export interface StatsScale {+ file_count: number;+ symbol_count: number;+ entry_point_count: number;+ module_count: number;+ total_nloc: number;+ language_count: number;+ languages: StatsLanguage[];+ size_class: StatsSizeClass;+}++export interface StatsMonthlyBucket {+ month: string;+ total: number;+ agent: number;+}++export interface StatsAgentName {+ name: string;+ count: number;+}++export interface StatsActivity {+ total_commits: number;+ agent_commits: number;+ agent_pct: number;+ fix_commits: number;+ fix_pct: number;+ contributor_count: number;+ first_commit_at: string | null;+ last_commit_at: string | null;+ age_days: number | null;+ busiest_month: StatsMonthlyBucket | null;+ monthly: StatsMonthlyBucket[];+ agent_names: StatsAgentName[];+}++export interface StatsOwner {+ name: string;+ file_count: number;+ pct: number;+}++export interface StatsPeople {+ owner_count: number;+ top_owners: StatsOwner[];+ single_owner_files: number;+ silo_count: number;+}++export interface StatsSeverityBreakdown {+ critical: number;+ high: number;+ medium: number;+ low: number;+}++export interface StatsDefectAccuracy {+ k: number;+ hits: number;+ precision: number;+ base_rate: number;+ lift: number | null;+ window_days: number;+ scored_files: number;+ defect_files: number;+}++export interface StatsDistributionBand {+ files: number;+ nloc: number;+ pct: number;+}++export interface StatsDistribution {+ total_files: number;+ total_nloc: number;+ bands: {+ healthy: StatsDistributionBand;+ warning: StatsDistributionBand;+ alert: StatsDistributionBand;+ };+}++export interface StatsDeadCode {+ total_findings: number;+ deletable_lines: number;+}++export interface StatsQuality {+ average_health: number | null;+ maintainability_average: number | null;+ performance_average: number | null;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ open_findings: number;+ severity_breakdown: StatsSeverityBreakdown;+ defect_accuracy: StatsDefectAccuracy | null;+ distribution: StatsDistribution | null;+ doc_coverage_pct: number;+ page_count: number;+ test_coverage_pct: number | null;+ dead_code: StatsDeadCode;+}++export interface StatsKnowledge {+ decision_count: number;+ active_decision_count: number;+}++export interface StatsSuperlatives {+ largest_file?: { path: string; nloc: number };+ most_complex_symbol?: { name: string; file_path: string; complexity: number };+ most_changed_file?: { path: string; commit_count: number };+ oldest_file?: { path: string; first_commit_at: string | null };+ most_central_file?: { path: string; pagerank: number };+ strongest_coupling?: { a: string; b: string; count: number };+}++export interface StatsRepo {+ id: string;+ name: string;+ default_branch: string;+ head_commit: string | null;+}++export interface StatsHighlights {+ repo: StatsRepo;+ scale: StatsScale;+ activity: StatsActivity;+ people: StatsPeople;+ quality: StatsQuality;+ knowledge: StatsKnowledge;+ superlatives: StatsSuperlatives;+}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex bf953a813..2cfc0fa7c 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -59,6 +59,8 @@"./chat/*": "./src/chat/*.tsx","./dashboard": "./src/dashboard/index.ts","./dashboard/*": "./src/dashboard/*.tsx",+ "./stats": "./src/stats/index.ts",+ "./stats/*": "./src/stats/*.tsx","./workspace": "./src/workspace/index.ts","./workspace/system-map": "./src/workspace/system-map/index.ts","./workspace/dsm": "./src/workspace/dsm/index.ts",diff --git a/packages/ui/src/stats/activity-trend-chart.tsx b/packages/ui/src/stats/activity-trend-chart.tsxnew file mode 100644index 000000000..c077e4269--- /dev/null+++ b/packages/ui/src/stats/activity-trend-chart.tsx@@ -0,0 +1,75 @@+"use client";++import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";+import type { StatsMonthlyBucket } from "@repowise-dev/types/stats";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";++interface ActivityTrendChartProps {+ monthly: StatsMonthlyBucket[];+ title?: string;+}++/** Stacked monthly commit volume, split into agent-authored vs human. The+ * "when did AI start writing this code" view. */+export function ActivityTrendChart({ monthly, title = "Commits per month" }: ActivityTrendChartProps) {+ if (monthly.length === 0) return null;++ const data = monthly.map((b) => ({+ month: b.month,+ human: Math.max(b.total - b.agent, 0),+ agent: b.agent,+ }));++ return (+ <Card className="h-full">+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">{title}</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <div className="h-[220px] w-full">+ <ResponsiveContainer width="100%" height="100%">+ <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>+ <XAxis+ dataKey="month"+ tick={{ fontSize: 10, fill: "var(--color-text-tertiary)" }}+ tickLine={false}+ axisLine={false}+ interval="preserveStartEnd"+ minTickGap={24}+ />+ <YAxis+ tick={{ fontSize: 10, fill: "var(--color-text-tertiary)" }}+ tickLine={false}+ axisLine={false}+ allowDecimals={false}+ width={40}+ />+ <Tooltip+ cursor={{ fill: "var(--color-bg-muted)", opacity: 0.4 }}+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: 8,+ fontSize: 11,+ color: "var(--color-text-primary)",+ }}+ />+ <Bar dataKey="human" stackId="c" fill="var(--color-accent-primary)" radius={[0, 0, 0, 0]} />+ <Bar dataKey="agent" stackId="c" fill="var(--color-info)" radius={[2, 2, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ </div>+ <div className="mt-2 flex items-center gap-4 text-[11px] text-[var(--color-text-secondary)]">+ <span className="flex items-center gap-1.5">+ <span className="h-2 w-2 rounded-full" style={{ background: "var(--color-accent-primary)" }} />+ Human+ </span>+ <span className="flex items-center gap-1.5">+ <span className="h-2 w-2 rounded-full" style={{ background: "var(--color-info)" }} />+ Agent+ </span>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/packages/ui/src/stats/index.ts b/packages/ui/src/stats/index.tsnew file mode 100644index 000000000..292debe80--- /dev/null+++ b/packages/ui/src/stats/index.ts@@ -0,0 +1,4 @@+export { SizeClassHero } from "./size-class-hero";+export { StatCallout, type StatCalloutProps, type CalloutTone } from "./stat-callout";+export { SuperlativesGrid } from "./superlatives-grid";+export { ActivityTrendChart } from "./activity-trend-chart";diff --git a/packages/ui/src/stats/size-class-hero.tsx b/packages/ui/src/stats/size-class-hero.tsxnew file mode 100644index 000000000..2858392bf--- /dev/null+++ b/packages/ui/src/stats/size-class-hero.tsx@@ -0,0 +1,97 @@+import * as React from "react";+import {+ Sprout,+ Home,+ Building,+ Building2,+ Landmark,+ Globe2,+} from "lucide-react";+import type { StatsScale } from "@repowise-dev/types/stats";+import { formatNumber, formatLOC } from "../lib/format";++const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {+ Seedling: Sprout,+ Hamlet: Home,+ Village: Home,+ Town: Building,+ City: Building2,+ Metropolis: Landmark,+ Megalopolis: Globe2,+};++interface HeroFigure {+ label: string;+ value: string;+}++interface SizeClassHeroProps {+ scale: StatsScale;+ /** Repo name, rendered as the eyebrow above the size-class label. */+ repoName?: string;+}++/**+ * The Stats page centerpiece: a warm-washed banner that names the codebase's+ * "size class" (derived from NLOC) and leads with the headline figures. Built+ * to look great in a screenshot — large type, generous spacing, one accent.+ */+export function SizeClassHero({ scale, repoName }: SizeClassHeroProps) {+ const Icon = SIZE_ICON[scale.size_class.name] ?? Building2;++ const figures: HeroFigure[] = [+ { label: "Lines of code", value: formatLOC(scale.total_nloc) },+ { label: "Files", value: formatNumber(scale.file_count) },+ { label: "Symbols", value: formatNumber(scale.symbol_count) },+ { label: "Languages", value: formatNumber(scale.language_count) },+ ];++ return (+ <div+ className="relative overflow-hidden rounded-2xl border border-[var(--color-border-default)] p-6 sm:p-8"+ style={{ background: "var(--gradient-warm-wash, var(--color-bg-surface))" }}+ >+ <div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">+ <div className="min-w-0">+ {repoName && (+ <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--color-text-tertiary)]">+ {repoName}+ </p>+ )}+ <div className="mt-2 flex items-center gap-3">+ <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-[var(--color-accent-muted,var(--color-bg-elevated))] text-[var(--color-accent-primary)]">+ <Icon className="h-6 w-6" />+ </span>+ <div className="min-w-0">+ <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ This codebase is a+ </p>+ <h2 className="text-3xl font-bold leading-tight text-[var(--color-text-primary)] sm:text-4xl">+ {scale.size_class.name}+ </h2>+ </div>+ </div>+ <p className="mt-3 max-w-md text-sm text-[var(--color-text-secondary)]">+ {scale.size_class.blurb}+ </p>+ </div>++ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:max-w-xl">+ {figures.map((f) => (+ <div+ key={f.label}+ className="rounded-xl border border-[var(--color-border-subtle,var(--color-border-default))] bg-[var(--color-bg-surface)]/70 px-4 py-3 backdrop-blur-sm"+ >+ <p className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)] sm:text-3xl">+ {f.value}+ </p>+ <p className="mt-0.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {f.label}+ </p>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/stats/stat-callout.tsx b/packages/ui/src/stats/stat-callout.tsxnew file mode 100644index 000000000..f33160a71--- /dev/null+++ b/packages/ui/src/stats/stat-callout.tsx@@ -0,0 +1,65 @@+import * as React from "react";+import { cn } from "../lib/cn";++export type CalloutTone = "default" | "accent" | "success" | "warning" | "info";++const TONE_VALUE: Record<CalloutTone, string> = {+ default: "text-[var(--color-text-primary)]",+ accent: "text-[var(--color-accent-primary)]",+ success: "text-[var(--color-success)]",+ warning: "text-[var(--color-warning)]",+ info: "text-[var(--color-info)]",+};++export interface StatCalloutProps {+ /** Small uppercase eyebrow above the figure. */+ label: string;+ /** The headline figure (already formatted). */+ value: React.ReactNode;+ /** One-line context shown under the figure. */+ sub?: React.ReactNode;+ icon?: React.ReactNode;+ tone?: CalloutTone;+ className?: string;+}++/**+ * A large, single-figure callout card — the building block for the punchy+ * "headline" stats (AI authorship %, project age, defect-validation lift, …).+ * Bigger and more emphatic than `StatTile`, tuned for the showcase tabs.+ */+export function StatCallout({+ label,+ value,+ sub,+ icon,+ tone = "default",+ className,+}: StatCalloutProps) {+ return (+ <div+ className={cn(+ "rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4",+ className,+ )}+ >+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {label}+ </p>+ {icon && <span className="text-[var(--color-text-tertiary)]">{icon}</span>}+ </div>+ <p+ className={cn(+ "mt-1.5 text-3xl font-bold leading-none tabular-nums",+ TONE_VALUE[tone],+ )}+ >+ {value}+ </p>+ {sub && (+ <p className="mt-2 text-xs leading-snug text-[var(--color-text-secondary)]">{sub}</p>+ )}+ </div>+ );+}diff --git a/packages/ui/src/stats/superlatives-grid.tsx b/packages/ui/src/stats/superlatives-grid.tsxnew file mode 100644index 000000000..e42d46727--- /dev/null+++ b/packages/ui/src/stats/superlatives-grid.tsx@@ -0,0 +1,123 @@+import * as React from "react";+import {+ FileText,+ GitCommitHorizontal,+ Hourglass,+ Network,+ Workflow,+ Boxes,+} from "lucide-react";+import type { StatsSuperlatives } from "@repowise-dev/types/stats";+import { formatNumber, formatRelativeTimeOrNull, truncatePath } from "../lib/format";++interface AwardRow {+ key: string;+ icon: React.ComponentType<{ className?: string }>;+ title: string;+ primary: string;+ detail: string;+}++function buildAwards(s: StatsSuperlatives): AwardRow[] {+ const rows: AwardRow[] = [];+ if (s.largest_file) {+ rows.push({+ key: "largest",+ icon: FileText,+ title: "Largest file",+ primary: truncatePath(s.largest_file.path, 42),+ detail: `${formatNumber(s.largest_file.nloc)} lines`,+ });+ }+ if (s.most_complex_symbol) {+ rows.push({+ key: "complex",+ icon: Workflow,+ title: "Most complex symbol",+ primary: s.most_complex_symbol.name,+ detail: `complexity ${formatNumber(s.most_complex_symbol.complexity)} · ${truncatePath(+ s.most_complex_symbol.file_path,+ 32,+ )}`,+ });+ }+ if (s.most_changed_file) {+ rows.push({+ key: "changed",+ icon: GitCommitHorizontal,+ title: "Most-changed file",+ primary: truncatePath(s.most_changed_file.path, 42),+ detail: `${formatNumber(s.most_changed_file.commit_count)} commits`,+ });+ }+ if (s.oldest_file) {+ rows.push({+ key: "oldest",+ icon: Hourglass,+ title: "Oldest file",+ primary: truncatePath(s.oldest_file.path, 42),+ detail: `first commit ${formatRelativeTimeOrNull(s.oldest_file.first_commit_at)}`,+ });+ }+ if (s.most_central_file) {+ rows.push({+ key: "central",+ icon: Network,+ title: "Most central file",+ primary: truncatePath(s.most_central_file.path, 42),+ detail: `PageRank ${s.most_central_file.pagerank.toFixed(4)}`,+ });+ }+ if (s.strongest_coupling) {+ rows.push({+ key: "coupling",+ icon: Boxes,+ title: "Strongest hidden coupling",+ primary: `${truncatePath(s.strongest_coupling.a, 26)} ↔ ${truncatePath(+ s.strongest_coupling.b,+ 26,+ )}`,+ detail: `changed together ${formatNumber(s.strongest_coupling.count)}×`,+ });+ }+ return rows;+}++interface SuperlativesGridProps {+ superlatives: StatsSuperlatives;+}++/** A grid of "award" cards — the biggest / oldest / most-tangled records in+ * the repo. Renders only the awards that have data. */+export function SuperlativesGrid({ superlatives }: SuperlativesGridProps) {+ const awards = buildAwards(superlatives);+ if (awards.length === 0) return null;++ return (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {awards.map((a) => {+ const Icon = a.icon;+ return (+ <div+ key={a.key}+ className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4"+ >+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">+ <Icon className="h-4 w-4" />+ <span className="text-[11px] font-medium uppercase tracking-wider">{a.title}</span>+ </div>+ <p+ className="mt-2 truncate text-sm font-semibold text-[var(--color-text-primary)]"+ title={a.primary}+ >+ {a.primary}+ </p>+ <p className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]" title={a.detail}>+ {a.detail}+ </p>+ </div>+ );+ })}+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 351eb8aa5..347b89c23 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -4,6 +4,8 @@ import { Hash } from "lucide-react";import Link from "next/link";import { getOverviewSummary } from "@/lib/api/overview";import { getProviders } from "@/lib/api/providers";+import { getStatsHighlights } from "@/lib/api/stats";+import { StatsTeaserCard } from "@/components/overview/stats-teaser-card";import { Badge } from "@repowise-dev/ui/ui/badge";import { EmptyState, PageShell } from "@repowise-dev/ui/shared";import { HealthOverviewCard } from "@repowise-dev/ui/dashboard/health-overview-card";@@ -34,9 +36,10 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {export default async function OverviewPage({ params }: Props) {const { id } = await params;- const [summary, providers] = await Promise.all([+ const [summary, providers, statsHighlights] = await Promise.all([safeFetch(() => getOverviewSummary(id)),safeFetch(() => getProviders()),+ safeFetch(() => getStatsHighlights(id)),]);if (!summary) notFound();@@ -150,6 +153,7 @@ export default async function OverviewPage({ params }: Props) {}rail={<>+ {statsHighlights && <StatsTeaserCard repoId={id} data={statsHighlights} />}<SavingsMini data={summary.savings} repoId={id} /><AttentionPanel items={attentionItems} repoId={id} previewCount={5} repoName={repo.name} /></>diff --git a/packages/web/src/app/repos/[id]/stats/page.tsx b/packages/web/src/app/repos/[id]/stats/page.tsxnew file mode 100644index 000000000..b88bb5df6--- /dev/null+++ b/packages/web/src/app/repos/[id]/stats/page.tsx@@ -0,0 +1,34 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { BarChart3 } from "lucide-react";+import { getStatsHighlights } from "@/lib/api/stats";+import { PageShell } from "@repowise-dev/ui/shared";+import { StatsTabs } from "@/components/stats/stats-tabs";++export const metadata: Metadata = { title: "Stats" };++interface Props {+ params: Promise<{ id: string }>;+}++export default async function StatsPage({ params }: Props) {+ const { id } = await params;++ let data;+ try {+ data = await getStatsHighlights(id);+ } catch {+ notFound();+ }++ return (+ <PageShell+ title="By the Numbers"+ icon={<BarChart3 className="h-5 w-5" />}+ description="A tour of everything the index knows about this codebase — scale, growth, people, and the signals only repowise computes."+ maxWidth="wide"+ >+ <StatsTabs data={data} />+ </PageShell>+ );+}diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex 9f421e1c0..47dbbce40 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -9,6 +9,7 @@import {Activity,+ BarChart3,BookOpen,Boxes,DollarSign,@@ -78,6 +79,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {{label: "Settings",items: [+ { label: "Stats", href: `${base}/stats`, icon: BarChart3 },{ label: "Usage & savings", href: `${base}/costs`, icon: DollarSign },{ label: "Settings", href: `${base}/settings`, icon: Settings },],diff --git a/packages/web/src/components/overview/stats-teaser-card.tsx b/packages/web/src/components/overview/stats-teaser-card.tsxnew file mode 100644index 000000000..73ed218d3--- /dev/null+++ b/packages/web/src/components/overview/stats-teaser-card.tsx@@ -0,0 +1,71 @@+import Link from "next/link";+import { BarChart3, ArrowRight, Bot } from "lucide-react";+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { Card } from "@repowise-dev/ui/ui/card";+import { formatLOC, formatNumber, formatAgeDays } from "@repowise-dev/ui/lib/format";++interface StatsTeaserCardProps {+ repoId: string;+ data: StatsHighlights;+}++/** Compact overview teaser that headlines the "size class" + a couple of+ * marquee figures and links into the full Stats page. */+export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {+ const { scale, activity } = data;++ const figures: { label: string; value: string }[] = [+ { label: "Lines", value: formatLOC(scale.total_nloc) },+ { label: "Commits", value: formatNumber(activity.total_commits) },+ {+ label: "Age",+ value: activity.age_days != null ? formatAgeDays(activity.age_days) : "—",+ },+ ];++ return (+ <Card className="overflow-hidden">+ <Link+ href={`/repos/${repoId}/stats`}+ className="group block p-4 transition-colors hover:bg-[var(--color-bg-elevated)]"+ >+ <div className="flex items-center justify-between">+ <span className="flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)]">+ <BarChart3 className="h-4 w-4 text-[var(--color-accent-primary)]" />+ By the Numbers+ </span>+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)] transition-transform group-hover:translate-x-0.5" />+ </div>++ <div className="mt-3 flex items-baseline gap-2">+ <span className="text-2xl font-bold text-[var(--color-text-primary)]">+ {scale.size_class.name}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {formatNumber(scale.file_count)} files+ </span>+ </div>++ <div className="mt-3 grid grid-cols-3 gap-2">+ {figures.map((f) => (+ <div key={f.label}>+ <p className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">+ {f.value}+ </p>+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {f.label}+ </p>+ </div>+ ))}+ </div>++ {activity.total_commits > 0 && (+ <p className="mt-3 flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <Bot className="h-3.5 w-3.5 text-[var(--color-info)]" />+ {activity.agent_pct}% of commits agent-authored+ </p>+ )}+ </Link>+ </Card>+ );+}diff --git a/packages/web/src/components/stats/architecture-tab.tsx b/packages/web/src/components/stats/architecture-tab.tsxnew file mode 100644index 000000000..dcfb5f43a--- /dev/null+++ b/packages/web/src/components/stats/architecture-tab.tsx@@ -0,0 +1,55 @@+import { Boxes, Lightbulb, Waypoints, FileCode } from "lucide-react";+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { StatCallout, SuperlativesGrid } from "@repowise-dev/ui/stats";+import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";+import { formatNumber } from "@repowise-dev/ui/lib/format";++export function ArchitectureTab({ data }: { data: StatsHighlights }) {+ const { scale, knowledge, quality, superlatives } = data;++ const langDistribution: Record<string, number> = {};+ for (const l of scale.languages) langDistribution[l.language] = l.file_count;++ return (+ <div className="space-y-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="Modules"+ value={formatNumber(scale.module_count)}+ icon={<Boxes className="h-4 w-4" />}+ sub={`${formatNumber(scale.file_count)} files`}+ />+ <StatCallout+ label="Entry points"+ value={formatNumber(scale.entry_point_count)}+ icon={<Waypoints className="h-4 w-4" />}+ sub="reachable roots in the graph"+ />+ <StatCallout+ label="Decisions"+ value={formatNumber(knowledge.decision_count)}+ icon={<Lightbulb className="h-4 w-4" />}+ sub={`${formatNumber(knowledge.active_decision_count)} active`}+ />+ <StatCallout+ label="Symbols"+ value={formatNumber(scale.symbol_count)}+ icon={<FileCode className="h-4 w-4" />}+ sub={`${formatNumber(scale.language_count)} languages · ${Math.round(+ quality.doc_coverage_pct,+ )}% documented`}+ />+ </div>++ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <LanguageDonut distribution={langDistribution} />+ <div className="lg:col-span-2">+ <h3 className="mb-2 text-sm font-semibold text-[var(--color-text-primary)]">+ Structural records+ </h3>+ <SuperlativesGrid superlatives={superlatives} />+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/stats/by-the-numbers-tab.tsx b/packages/web/src/components/stats/by-the-numbers-tab.tsxnew file mode 100644index 000000000..65a2cab6e--- /dev/null+++ b/packages/web/src/components/stats/by-the-numbers-tab.tsx@@ -0,0 +1,93 @@+import { Bot, CalendarClock, Users, ShieldCheck, Trash2, HeartPulse } from "lucide-react";+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { SizeClassHero, StatCallout, SuperlativesGrid } from "@repowise-dev/ui/stats";+import { formatNumber, formatLOC, formatAgeDays, formatDate } from "@repowise-dev/ui/lib/format";++export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {+ const { scale, activity, quality, people, superlatives } = data;+ const da = quality.defect_accuracy;++ return (+ <div className="space-y-5">+ <SizeClassHero scale={scale} repoName={data.repo.name} />++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="AI authorship"+ value={`${activity.agent_pct}%`}+ tone="info"+ icon={<Bot className="h-4 w-4" />}+ sub={`${formatNumber(activity.agent_commits)} of ${formatNumber(+ activity.total_commits,+ )} commits written by agents`}+ />+ <StatCallout+ label="Project age"+ value={activity.age_days != null ? formatAgeDays(activity.age_days) : "—"}+ icon={<CalendarClock className="h-4 w-4" />}+ sub={+ activity.first_commit_at+ ? `since ${formatDate(activity.first_commit_at)}`+ : "first commit date unknown"+ }+ />+ <StatCallout+ label="Contributors"+ value={formatNumber(activity.contributor_count)}+ icon={<Users className="h-4 w-4" />}+ sub={`${formatNumber(people.owner_count)} hold primary ownership of a file`}+ />+ {da ? (+ <StatCallout+ label="Score finds bugs"+ value={da.lift != null ? `${da.lift}×` : `${Math.round(da.precision * 100)}%`}+ tone="success"+ icon={<ShieldCheck className="h-4 w-4" />}+ sub={`${da.hits}/${da.k} least-healthy files later got a bug fix — ${+ da.lift != null ? `${da.lift}× the base rate` : "above base rate"+ }`}+ />+ ) : (+ <StatCallout+ label="Defect risk"+ value={quality.average_health != null ? `${quality.average_health.toFixed(1)}/10` : "—"}+ tone="accent"+ icon={<HeartPulse className="h-4 w-4" />}+ sub="average health across all files"+ />+ )}+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <StatCallout+ label="Total lines"+ value={formatLOC(scale.total_nloc)}+ sub={`${formatNumber(scale.symbol_count)} symbols across ${formatNumber(+ scale.module_count,+ )} modules`}+ />+ <StatCallout+ label="Knowledge captured"+ value={formatNumber(data.knowledge.decision_count)}+ sub={`architectural decisions · ${formatNumber(quality.page_count)} wiki pages`}+ />+ <StatCallout+ label="Recoverable lines"+ value={formatNumber(quality.dead_code.deletable_lines)}+ tone="warning"+ icon={<Trash2 className="h-4 w-4" />}+ sub={`safe to delete across ${formatNumber(+ quality.dead_code.total_findings,+ )} dead-code findings`}+ />+ </div>++ <div>+ <h3 className="mb-2 text-sm font-semibold text-[var(--color-text-primary)]">+ Records & superlatives+ </h3>+ <SuperlativesGrid superlatives={superlatives} />+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/stats/growth-tab.tsx b/packages/web/src/components/stats/growth-tab.tsxnew file mode 100644index 000000000..e0c6629a7--- /dev/null+++ b/packages/web/src/components/stats/growth-tab.tsx@@ -0,0 +1,74 @@+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { ActivityTrendChart, StatCallout } from "@repowise-dev/ui/stats";+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { formatNumber, formatDate } from "@repowise-dev/ui/lib/format";++function monthLabel(month: string): string {+ // "2026-06" → "Jun 2026"+ const [y, m] = month.split("-");+ const d = new Date(Number(y), Number(m) - 1, 1);+ return new Intl.DateTimeFormat("en-US", { month: "short", year: "numeric" }).format(d);+}++export function GrowthTab({ data }: { data: StatsHighlights }) {+ const { activity } = data;++ return (+ <div className="space-y-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="Total commits"+ value={formatNumber(activity.total_commits)}+ sub={+ activity.first_commit_at && activity.last_commit_at+ ? `${formatDate(activity.first_commit_at)} → ${formatDate(activity.last_commit_at)}`+ : "across the indexed window"+ }+ />+ <StatCallout+ label="Busiest month"+ value={activity.busiest_month ? monthLabel(activity.busiest_month.month) : "—"}+ sub={+ activity.busiest_month+ ? `${formatNumber(activity.busiest_month.total)} commits`+ : "no monthly data"+ }+ />+ <StatCallout+ label="Fix commits"+ value={`${activity.fix_pct}%`}+ tone="warning"+ sub={`${formatNumber(activity.fix_commits)} commits classified as fixes`}+ />+ <StatCallout+ label="Agent commits"+ value={`${activity.agent_pct}%`}+ tone="info"+ sub={`${formatNumber(activity.agent_commits)} agent-authored`}+ />+ </div>++ <ActivityTrendChart monthly={activity.monthly} />++ {activity.agent_names.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Agents at work</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <ul className="divide-y divide-[var(--color-border-subtle,var(--color-border-default))]">+ {activity.agent_names.map((a) => (+ <li key={a.name} className="flex items-center justify-between py-2 text-sm">+ <span className="truncate text-[var(--color-text-primary)]">{a.name}</span>+ <span className="tabular-nums text-[var(--color-text-secondary)]">+ {formatNumber(a.count)} commits+ </span>+ </li>+ ))}+ </ul>+ </CardContent>+ </Card>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/stats/people-tab.tsx b/packages/web/src/components/stats/people-tab.tsxnew file mode 100644index 000000000..c07bdee94--- /dev/null+++ b/packages/web/src/components/stats/people-tab.tsx@@ -0,0 +1,70 @@+import { Users, UserCheck, AlertTriangle } from "lucide-react";+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { StatCallout } from "@repowise-dev/ui/stats";+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { formatNumber } from "@repowise-dev/ui/lib/format";++export function PeopleTab({ data }: { data: StatsHighlights }) {+ const { people, activity } = data;+ const maxFiles = people.top_owners[0]?.file_count ?? 0;++ return (+ <div className="space-y-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="Contributors"+ value={formatNumber(activity.contributor_count)}+ icon={<Users className="h-4 w-4" />}+ sub="distinct commit authors"+ />+ <StatCallout+ label="File owners"+ value={formatNumber(people.owner_count)}+ icon={<UserCheck className="h-4 w-4" />}+ sub="hold primary ownership of ≥1 file"+ />+ <StatCallout+ label="Single-owner files"+ value={formatNumber(people.single_owner_files)}+ tone="warning"+ icon={<AlertTriangle className="h-4 w-4" />}+ sub="bus factor of 1 — knowledge risk"+ />+ <StatCallout+ label="Knowledge silos"+ value={formatNumber(people.silo_count)}+ tone="warning"+ sub="modules >80% owned by one person"+ />+ </div>++ {people.top_owners.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Top contributors by files owned</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <ul className="space-y-2.5">+ {people.top_owners.map((o) => (+ <li key={o.name} className="space-y-1">+ <div className="flex items-center justify-between text-sm">+ <span className="truncate text-[var(--color-text-primary)]">{o.name}</span>+ <span className="tabular-nums text-[var(--color-text-secondary)]">+ {formatNumber(o.file_count)} files · {Math.round(o.pct * 100)}%+ </span>+ </div>+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent-primary)]"+ style={{ width: `${maxFiles ? (o.file_count / maxFiles) * 100 : 0}%` }}+ />+ </div>+ </li>+ ))}+ </ul>+ </CardContent>+ </Card>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/stats/quality-tab.tsx b/packages/web/src/components/stats/quality-tab.tsxnew file mode 100644index 000000000..b200fa12c--- /dev/null+++ b/packages/web/src/components/stats/quality-tab.tsx@@ -0,0 +1,119 @@+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { StatCallout } from "@repowise-dev/ui/stats";+import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { formatNumber, truncatePath } from "@repowise-dev/ui/lib/format";++const BAND_COLOR: Record<string, string> = {+ healthy: "var(--color-success)",+ warning: "var(--color-warning)",+ alert: "var(--color-error)",+};++function score(v: number | null): string {+ return v != null ? `${v.toFixed(1)}/10` : "—";+}++export function QualityTab({ data }: { data: StatsHighlights }) {+ const { quality, scale } = data;+ const dist = quality.distribution;++ const langDistribution: Record<string, number> = {};+ for (const l of scale.languages) langDistribution[l.language] = l.file_count;++ return (+ <div className="space-y-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="Defect risk"+ value={score(quality.average_health)}+ tone="accent"+ sub="bug-predictive headline score"+ />+ <StatCallout+ label="Maintainability"+ value={score(quality.maintainability_average)}+ sub="cohesion, brain methods, DRY"+ />+ <StatCallout+ label="Performance"+ value={score(quality.performance_average)}+ sub="I/O-in-loop / N+1 risk"+ />+ <StatCallout+ label="Test coverage"+ value={quality.test_coverage_pct != null ? `${quality.test_coverage_pct}%` : "—"}+ sub="files with a matching test"+ />+ </div>++ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ {dist && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Health distribution</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <div className="flex h-3 w-full overflow-hidden rounded-full">+ {(["healthy", "warning", "alert"] as const).map((b) =>+ dist.bands[b].pct > 0 ? (+ <div+ key={b}+ style={{ width: `${dist.bands[b].pct}%`, background: BAND_COLOR[b] }}+ title={`${b}: ${dist.bands[b].pct}%`}+ />+ ) : null,+ )}+ </div>+ <div className="mt-3 grid grid-cols-3 gap-2 text-xs">+ {(["healthy", "warning", "alert"] as const).map((b) => (+ <div key={b} className="flex items-center gap-1.5">+ <span+ className="h-2 w-2 rounded-full"+ style={{ background: BAND_COLOR[b] }}+ />+ <span className="capitalize text-[var(--color-text-secondary)]">{b}</span>+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ {dist.bands[b].files}+ </span>+ </div>+ ))}+ </div>+ </CardContent>+ </Card>+ )}++ <LanguageDonut distribution={langDistribution} />+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <StatCallout+ label="Open findings"+ value={formatNumber(quality.open_findings)}+ sub={`${quality.severity_breakdown.critical} critical · ${quality.severity_breakdown.high} high`}+ />+ <StatCallout+ label="Dead code"+ value={formatNumber(quality.dead_code.deletable_lines)}+ tone="warning"+ sub={`recoverable lines · ${formatNumber(quality.dead_code.total_findings)} findings`}+ />+ <StatCallout+ label="Doc coverage"+ value={`${Math.round(quality.doc_coverage_pct)}%`}+ sub={`${formatNumber(quality.page_count)} wiki pages`}+ />+ <StatCallout+ label="Lowest-scoring file"+ value={quality.worst_performer_score != null ? score(quality.worst_performer_score) : "—"}+ tone="warning"+ sub={+ quality.worst_performer_path+ ? truncatePath(quality.worst_performer_path, 30)+ : "no data"+ }+ />+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/stats/stats-tabs.tsx b/packages/web/src/components/stats/stats-tabs.tsxnew file mode 100644index 000000000..f1a7b424a--- /dev/null+++ b/packages/web/src/components/stats/stats-tabs.tsx@@ -0,0 +1,57 @@+"use client";++import { parseAsStringLiteral, useQueryState } from "nuqs";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/tabs";+import { ErrorBoundary } from "@repowise-dev/ui/shared";+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { ByTheNumbersTab } from "./by-the-numbers-tab";+import { GrowthTab } from "./growth-tab";+import { PeopleTab } from "./people-tab";+import { QualityTab } from "./quality-tab";+import { ArchitectureTab } from "./architecture-tab";++const TAB_VALUES = ["numbers", "growth", "people", "quality", "architecture"] as const;++export function StatsTabs({ data }: { data: StatsHighlights }) {+ const [tab, setTab] = useQueryState(+ "tab",+ parseAsStringLiteral(TAB_VALUES).withDefault("numbers"),+ );++ return (+ <Tabs value={tab} onValueChange={(v) => setTab(v as (typeof TAB_VALUES)[number])}>+ <TabsList>+ <TabsTrigger value="numbers">By the Numbers</TabsTrigger>+ <TabsTrigger value="growth">Growth & Activity</TabsTrigger>+ <TabsTrigger value="people">People</TabsTrigger>+ <TabsTrigger value="quality">Code & Quality</TabsTrigger>+ <TabsTrigger value="architecture">Architecture</TabsTrigger>+ </TabsList>+ <TabsContent value="numbers" className="mt-4">+ <ErrorBoundary title="Couldn't load stats">+ <ByTheNumbersTab data={data} />+ </ErrorBoundary>+ </TabsContent>+ <TabsContent value="growth" className="mt-4">+ <ErrorBoundary title="Couldn't load activity">+ <GrowthTab data={data} />+ </ErrorBoundary>+ </TabsContent>+ <TabsContent value="people" className="mt-4">+ <ErrorBoundary title="Couldn't load contributors">+ <PeopleTab data={data} />+ </ErrorBoundary>+ </TabsContent>+ <TabsContent value="quality" className="mt-4">+ <ErrorBoundary title="Couldn't load quality">+ <QualityTab data={data} />+ </ErrorBoundary>+ </TabsContent>+ <TabsContent value="architecture" className="mt-4">+ <ErrorBoundary title="Couldn't load architecture">+ <ArchitectureTab data={data} />+ </ErrorBoundary>+ </TabsContent>+ </Tabs>+ );+}diff --git a/packages/web/src/lib/api/stats.ts b/packages/web/src/lib/api/stats.tsnew file mode 100644index 000000000..c8bca0fb0--- /dev/null+++ b/packages/web/src/lib/api/stats.ts@@ -0,0 +1,7 @@+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { apiGet } from "./client";++/** One-call payload for the repo Stats ("By the Numbers") page. */+export async function getStatsHighlights(repoId: string): Promise<StatsHighlights> {+ return apiGet<StatsHighlights>(`/api/repos/${repoId}/stats/highlights`);+}