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(stats): add coding-rhythm, momentum, truck factor and cycle signals (#828)
Raghav Chamadiyacc3f1a4b03ce
diff --git a/packages/api-client/src/__fixtures__/hosted/stats-highlights.json b/packages/api-client/src/__fixtures__/hosted/stats-highlights.jsonindex 87c099d95..cda0c985d 100644--- a/packages/api-client/src/__fixtures__/hosted/stats-highlights.json+++ b/packages/api-client/src/__fixtures__/hosted/stats-highlights.json@@ -690,7 +690,212 @@"agent": 0}],- "agent_names": []+ "agent_names": [],+ "punch_card": {+ "matrix": [+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 6,+ 6,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 6,+ 6,+ 6,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 6,+ 6,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 6,+ 6,+ 6,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 6,+ 6,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 6,+ 6,+ 6,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 6,+ 6,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 6,+ 6,+ 6,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 6,+ 6,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 12,+ 6,+ 6,+ 6,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 4,+ 4,+ 4,+ 4,+ 4,+ 4,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1+ ],+ [+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 4,+ 4,+ 4,+ 4,+ 4,+ 4,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1+ ]+ ],+ "peak": {+ "weekday": 2,+ "hour": 14,+ "count": 12+ },+ "busiest_weekday": 2,+ "peak_hour": 14,+ "weekend_pct": 9.6,+ "total": 879+ },+ "velocity": {+ "recent_90d": 412,+ "prior_90d": 318,+ "pct_change": 29.6+ },+ "change_risk_mix": {+ "low": 1240,+ "moderate": 560,+ "high": 200+ }},"people": {"owner_count": 12,@@ -737,7 +942,8 @@}],"single_owner_files": 28,- "silo_count": 4+ "silo_count": 4,+ "truck_factor": 3},"quality": {"average_health": 6.94,@@ -936,5 +1142,17 @@"b": "src/flask/sansio/app.py","count": 3}+ },+ "graph": {+ "cycle_clusters": 7,+ "files_in_cycles": 63,+ "largest_cycle": 21,+ "community_count": 48+ },+ "build": {+ "page_count": 486,+ "total_tokens": 5231044,+ "cost_usd": 0.92,+ "llm_operations": 640}}diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.pyindex ca30f3a03..eaf222331 100644--- a/packages/server/src/repowise/server/routers/stats.py+++ b/packages/server/src/repowise/server/routers/stats.py@@ -32,6 +32,8 @@ from repowise.core.persistence.models import (GitMetadata,GraphMetric,GraphNode,+ GraphNodeMembership,+ LlmCost,Page,WikiSymbol,)@@ -130,6 +132,53 @@ async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dic}+def _punch_card_summary(+ punch: list[list[int]], weekend_commits: int, dated_total: int+) -> dict[str, Any]:+ """Fold the weekday x hour commit matrix into a renderable summary.++ ``matrix`` is 7 rows (0=Monday) x 24 hours in the stored UTC. Also names the+ single hottest cell, the busiest weekday / peak hour (by marginal totals),+ and the weekend share — the human-readable hooks the hero renders."""+ peak = {"weekday": 0, "hour": 0, "count": 0}+ for wd in range(7):+ for hr in range(24):+ if punch[wd][hr] > peak["count"]:+ peak = {"weekday": wd, "hour": hr, "count": punch[wd][hr]}++ weekday_totals = [sum(punch[wd]) for wd in range(7)]+ hour_totals = [sum(punch[wd][hr] for wd in range(7)) for hr in range(24)]+ busiest_weekday = max(range(7), key=lambda wd: weekday_totals[wd]) if dated_total else None+ peak_hour = max(range(24), key=lambda hr: hour_totals[hr]) if dated_total else None++ return {+ "matrix": punch,+ "peak": peak if peak["count"] > 0 else None,+ "busiest_weekday": busiest_weekday,+ "peak_hour": peak_hour,+ "weekend_pct": round(weekend_commits / dated_total * 100.0, 1) if dated_total else 0.0,+ "total": dated_total,+ }+++def _commit_velocity(commit_times: list[Any], last_at: Any) -> dict[str, Any]:+ """Recent-vs-prior commit momentum, anchored to the newest commit.++ Anchoring to ``last_at`` (not wall-clock now) keeps the signal meaningful on+ an index that hasn't been synced today: it compares the 90 days ending at+ the latest commit against the 90 before that. ``pct_change`` is None when the+ prior window is empty (a young repo), so the UI can omit a divide-by-zero+ arrow rather than show a fake spike."""+ if last_at is None or not commit_times:+ return {"recent_90d": 0, "prior_90d": 0, "pct_change": None}+ recent_cut = last_at - timedelta(days=90)+ prior_cut = last_at - timedelta(days=180)+ recent = sum(1 for t in commit_times if t > recent_cut)+ prior = sum(1 for t in commit_times if prior_cut < t <= recent_cut)+ pct_change = round((recent - prior) / prior * 100.0, 1) if prior else None+ return {"recent_90d": recent, "prior_90d": prior, "pct_change": pct_change}++async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str, Any]:"""Commit volume, project age, agent-vs-human split, and a monthly series.@@ -161,6 +210,7 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,GitCommit.lines_added,GitCommit.lines_deleted,GitCommit.files_changed,+ GitCommit.change_risk_level,).where(GitCommit.repository_id == repo_id))).all()@@ -179,6 +229,13 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,first_sha: str | None = Nonelast_at: Any = Nonecommit_days: set[Any] = set()+ # Coding-rhythm punch card: commits bucketed by weekday (0=Mon) x hour (UTC,+ # the stored tz). Plus the raw timestamps for the recent-vs-prior velocity+ # window and a low/moderate/high change-risk tally — all off this one scan.+ punch = [[0] * 24 for _ in range(7)]+ weekend_commits = 0+ commit_times: list[Any] = []+ risk_mix = {"low": 0, "moderate": 0, "high": 0}# Top-2 commits by churn: the repo's very first commit is excluded from# the "biggest commit" award (every import/initial commit would win), so# two candidates are enough to survive dropping it.@@ -186,7 +243,7 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,for row in rows:committed_at, author_name, author_email, agent_name, is_fix = row[:5]- sha, subject, lines_added, lines_deleted, files_changed = row[5:]+ sha, subject, lines_added, lines_deleted, files_changed, change_risk_level = row[5:]total += 1if author_email or author_name:key = resolve(author_name, author_email)@@ -194,6 +251,8 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,contributors.add(key)if is_fix:fix_total += 1+ if change_risk_level in risk_mix:+ risk_mix[change_risk_level] += 1if agent_name:agent_total += 1agent_names[agent_name] = agent_names.get(agent_name, 0) + 1@@ -216,6 +275,11 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,if last_at is None or committed_at > last_at:last_at = committed_atcommit_days.add(committed_at.date())+ commit_times.append(committed_at)+ weekday = committed_at.weekday()+ punch[weekday][committed_at.hour] += 1+ if weekday >= 5:+ weekend_commits += 1key = committed_at.strftime("%Y-%m")b = months.setdefault(key, {"total": 0, "agent": 0})b["total"] += 1@@ -245,6 +309,9 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,]busiest = max(monthly, key=lambda r: r["total"], default=None)+ punch_card = _punch_card_summary(punch, weekend_commits, len(commit_times))+ velocity = _commit_velocity(commit_times, last_at)+# Prefer the whole-history values stamped on the repo at index time; fall# back to the bounded sample when they're absent (older index, non-git# repo). Age runs from the true first commit to the latest commit we have.@@ -277,6 +344,9 @@ async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str,),"biggest_commit": biggest_commit,"longest_streak": longest_streak,+ "punch_card": punch_card,+ "velocity": velocity,+ "change_risk_mix": risk_mix,}@@ -311,11 +381,26 @@ async def _people(session: AsyncSession, repo_id: str, all_meta: list[Any]) -> dif module_file_totals.get(module) and top / module_file_totals[module] > 0.8:silo_count += 1+ # Truck factor: the fewest primary owners who together hold >50% of owned+ # files — "how many people could walk out before the bus problem bites".+ # A factor of 1 means a single person owns most of the codebase.+ owned_total = sum(owners.values())+ truck_factor: int | None = None+ if owned_total:+ cumulative = 0+ truck_factor = 0+ for count in sorted(owners.values(), reverse=True):+ cumulative += count+ truck_factor += 1+ if cumulative * 2 > owned_total:+ break+return {"owner_count": len(owners),"top_owners": top_owners,"single_owner_files": single_owner_files,"silo_count": silo_count,+ "truck_factor": truck_factor,}@@ -536,6 +621,73 @@ async def _dependencies(session: AsyncSession, repo_id: str) -> dict[str, Any] |}+async def _graph(session: AsyncSession, repo_id: str) -> dict[str, Any]:+ """Dependency-cycle and community structure from the graph snapshot.++ Reads the materialized ``graph_node_membership`` rows (no graph rebuild):+ strongly-connected components with ``scc_size > 1`` are import cycles, and+ ``symbol_community_id`` groups the natural neighborhoods. Pure aggregate+ SQL — a couple of GROUP BY scans, never a row pull."""+ scc_rows = (+ await session.execute(+ select(GraphNodeMembership.scc_id, func.count())+ .where(+ GraphNodeMembership.repository_id == repo_id,+ GraphNodeMembership.scc_size > 1,+ )+ .group_by(GraphNodeMembership.scc_id)+ )+ ).all()+ cycle_clusters = len(scc_rows)+ files_in_cycles = sum(int(n) for _, n in scc_rows)+ largest_cycle = max((int(n) for _, n in scc_rows), default=0)++ community_count = (+ await session.scalar(+ select(func.count(func.distinct(GraphNodeMembership.symbol_community_id))).where(+ GraphNodeMembership.repository_id == repo_id,+ GraphNodeMembership.symbol_community_id.is_not(None),+ )+ )+ or 0+ )++ return {+ "cycle_clusters": cycle_clusters,+ "files_in_cycles": files_in_cycles,+ "largest_cycle": largest_cycle,+ "community_count": int(community_count),+ }+++async def _build(session: AsyncSession, repo_id: str) -> dict[str, Any]:+ """The knowledge base's own build stats — the wiki bragging about itself.++ Pages come from the ``wiki_pages`` count; tokens and cost from the+ ``llm_costs`` ledger written during generation. Single aggregate scan;+ every field degrades to 0 when generation was index-only (no LLM spend)."""+ page_count = (+ await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0+ )+ cost_row = (+ await session.execute(+ select(+ func.coalesce(func.sum(LlmCost.input_tokens + LlmCost.output_tokens), 0),+ func.coalesce(func.sum(LlmCost.cost_usd), 0.0),+ func.count(LlmCost.id),+ ).where(LlmCost.repository_id == repo_id)+ )+ ).one()+ total_tokens, cost_usd, op_count = cost_row++ return {+ "page_count": int(page_count),+ "total_tokens": int(total_tokens or 0),+ "cost_usd": round(float(cost_usd or 0.0), 2),+ "llm_operations": int(op_count or 0),+ }++@router.get("/{repo_id}/stats/highlights")async def stats_highlights(repo_id: str,@@ -594,5 +746,7 @@ async def stats_highlights("active_decision_count": active_decisions,},"dependencies": await _dependencies(session, repo_id),+ "graph": await _graph(session, repo_id),+ "build": await _build(session, repo_id),"superlatives": superlatives,}diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.tsindex 5238c589c..9db45a401 100644--- a/packages/types/src/stats.ts+++ b/packages/types/src/stats.ts@@ -40,6 +40,35 @@ export interface StatsAgentName {count: number;}+/** Coding-rhythm heatmap: commit counts by weekday (0=Monday) x hour (0-23,+ * in the stored UTC), with the human-readable hooks the hero renders. */+export interface StatsPunchCard {+ /** 7 rows (Mon..Sun) x 24 columns (hours). */+ matrix: number[][];+ /** Single hottest weekday/hour cell, or null when there are no commits. */+ peak: { weekday: number; hour: number; count: number } | null;+ /** Weekday (0=Mon) and hour with the most commits by marginal total. */+ busiest_weekday: number | null;+ peak_hour: number | null;+ weekend_pct: number;+ total: number;+}++/** Commit momentum: the 90 days ending at the newest commit vs the 90 before. */+export interface StatsVelocity {+ recent_90d: number;+ prior_90d: number;+ /** Percent change recent-vs-prior. Null when the prior window is empty. */+ pct_change: number | null;+}++/** Calibrated just-in-time change-risk tally across the sampled commits. */+export interface StatsChangeRiskMix {+ low: number;+ moderate: number;+ high: number;+}+export interface StatsActivity {total_commits: number;agent_commits: number;@@ -55,6 +84,9 @@ export interface StatsActivity {busiest_month: StatsMonthlyBucket | null;monthly: StatsMonthlyBucket[];agent_names: StatsAgentName[];+ punch_card: StatsPunchCard;+ velocity: StatsVelocity;+ change_risk_mix: StatsChangeRiskMix;}export interface StatsOwner {@@ -68,6 +100,9 @@ export interface StatsPeople {top_owners: StatsOwner[];single_owner_files: number;silo_count: number;+ /** Fewest primary owners who together hold >50% of owned files. 1 means a+ * single person owns most of the codebase. Null when no ownership data. */+ truck_factor: number | null;}export interface StatsSeverityBreakdown {@@ -162,6 +197,24 @@ export interface StatsDependencies {ecosystems: StatsEcosystem[];}+/** Import-graph structure: dependency cycles and natural communities, read+ * from the materialized graph snapshot (no rebuild). */+export interface StatsGraph {+ /** Strongly-connected components with >1 member — circular import clusters. */+ cycle_clusters: number;+ files_in_cycles: number;+ largest_cycle: number;+ community_count: number;+}++/** The knowledge base's own build cost — the wiki bragging about itself. */+export interface StatsBuild {+ page_count: number;+ total_tokens: number;+ cost_usd: number;+ llm_operations: number;+}+export interface StatsRepo {id: string;name: string;@@ -178,5 +231,9 @@ export interface StatsHighlights {knowledge: StatsKnowledge;/** Optional so older payloads (hosted exporters) degrade gracefully. */dependencies?: StatsDependencies | null;+ /** Optional so older payloads (hosted exporters) degrade gracefully. */+ graph?: StatsGraph | null;+ /** Optional so older payloads (hosted exporters) degrade gracefully. */+ build?: StatsBuild | null;superlatives: StatsSuperlatives;}diff --git a/packages/ui/src/stats/index.ts b/packages/ui/src/stats/index.tsindex 6a1cf969c..47cec977d 100644--- a/packages/ui/src/stats/index.ts+++ b/packages/ui/src/stats/index.ts@@ -8,3 +8,4 @@ export {} from "./stat-callout";export { SuperlativesGrid } from "./superlatives-grid";export { ActivityTrendChart } from "./activity-trend-chart";+export { PunchCard } from "./punch-card";diff --git a/packages/ui/src/stats/punch-card.tsx b/packages/ui/src/stats/punch-card.tsxnew file mode 100644index 000000000..ba58cd9cb--- /dev/null+++ b/packages/ui/src/stats/punch-card.tsx@@ -0,0 +1,150 @@+"use client";++import * as React from "react";+import type { StatsPunchCard } from "@repowise-dev/types/stats";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";++const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;+// Axis ticks at the quarter-day marks, labelled in the reader's am/pm idiom.+const HOUR_TICKS: Array<[number, string]> = [+ [0, "12a"],+ [6, "6a"],+ [12, "12p"],+ [18, "6p"],+];++function hourLabel(h: number): string {+ const period = h < 12 ? "AM" : "PM";+ const twelve = h % 12 === 0 ? 12 : h % 12;+ return `${twelve} ${period}`;+}++function weekdayLong(i: number): string {+ return ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][i] ?? "";+}++/**+ * Coding-rhythm heatmap: a GitHub-punch-card of commit volume by weekday x hour.+ * The signature "when does this team actually code" view — nothing else on the+ * stats page shows temporal shape. Cells ramp the accent color by a sqrt-scaled+ * intensity, and hovering a cell reads out its weekday/hour/count live.+ */+export function PunchCard({ data }: { data: StatsPunchCard }) {+ const [hover, setHover] = React.useState<{ wd: number; hr: number; count: number } | null>(null);++ if (!data || data.total === 0 || !data.peak) return null;++ const max = data.peak.count || 1;+ const readout = hover+ ? `${weekdayLong(hover.wd)} · ${hourLabel(hover.hr)} · ${hover.count} commit${+ hover.count === 1 ? "" : "s"+ }`+ : data.busiest_weekday != null && data.peak_hour != null+ ? `Most active on ${weekdayLong(data.busiest_weekday)}s around ${hourLabel(data.peak_hour)}`+ : "Commit activity by weekday and hour";++ return (+ <Card className="h-full">+ <CardHeader className="flex-row items-center justify-between gap-3 pb-3">+ <CardTitle className="text-sm">Coding rhythm</CardTitle>+ <span className="shrink-0 rounded-full bg-[var(--color-bg-muted)] px-2.5 py-1 text-[11px] font-medium tabular-nums text-[var(--color-text-secondary)]">+ {data.weekend_pct}% on weekends+ </span>+ </CardHeader>+ <CardContent className="pt-0">+ <p+ className={`mb-3 text-xs transition-colors ${+ hover+ ? "font-medium text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)]"+ }`}+ >+ {readout}+ </p>++ <div className="overflow-x-auto">+ <div className="min-w-[420px]" onMouseLeave={() => setHover(null)}>+ {WEEKDAYS.map((day, wd) => (+ <div key={day} className="flex items-center gap-1.5">+ <span+ className={`w-8 shrink-0 py-px text-right text-[10px] font-medium uppercase tracking-wide transition-colors ${+ hover?.wd === wd+ ? "text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-tertiary)]"+ }`}+ >+ {day}+ </span>+ <div className="grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))] gap-[3px]">+ {Array.from({ length: 24 }, (_, hr) => {+ const count = data.matrix[wd]?.[hr] ?? 0;+ // sqrt keeps low-but-nonzero hours legible against the peak.+ const intensity = count > 0 ? Math.sqrt(count / max) : 0;+ const isHover = hover?.wd === wd && hover?.hr === hr;+ const dimmed = hover && !isHover && hover.wd !== wd && hover.hr !== hr;+ return (+ <div+ key={hr}+ onMouseEnter={() => setHover({ wd, hr, count })}+ className={`aspect-square rounded-[2px] transition-all duration-100 ${+ isHover+ ? "scale-[1.35] ring-1 ring-[var(--color-accent-primary)]"+ : ""+ }`}+ style={{+ background:+ count > 0 ? "var(--color-accent-primary)" : "var(--color-bg-muted)",+ opacity: isHover+ ? 1+ : count > 0+ ? (dimmed ? 0.5 : 1) * (0.16 + 0.84 * intensity)+ : dimmed+ ? 0.4+ : 1,+ }}+ />+ );+ })}+ </div>+ </div>+ ))}++ {/* Hour axis — ticks aligned to the 24-column grid. */}+ <div className="mt-1.5 flex items-center gap-1.5">+ <span className="w-8 shrink-0" />+ <div className="relative grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))]">+ {HOUR_TICKS.map(([h, label]) => (+ <span+ key={h}+ className="col-span-1 whitespace-nowrap text-[10px] tabular-nums text-[var(--color-text-tertiary)]"+ style={{ gridColumnStart: h + 1 }}+ >+ {label}+ </span>+ ))}+ </div>+ </div>+ </div>+ </div>++ {/* Legend — hours are bucketed in UTC (git records the commit instant,+ not the author's local offset), so we say so rather than imply local+ time. */}+ <div className="mt-3 flex items-center justify-between gap-2 text-[10px] text-[var(--color-text-tertiary)]">+ <span>Hours in UTC</span>+ <div className="flex items-center gap-1.5">+ <span>Less</span>+ {[0.16, 0.44, 0.72, 1].map((o) => (+ <span+ key={o}+ className="h-2.5 w-2.5 rounded-[2px]"+ style={{ background: "var(--color-accent-primary)", opacity: o }}+ />+ ))}+ <span>More</span>+ </div>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/packages/web/src/components/stats/architecture-tab.tsx b/packages/web/src/components/stats/architecture-tab.tsxindex dcfb5f43a..89b650301 100644--- a/packages/web/src/components/stats/architecture-tab.tsx+++ b/packages/web/src/components/stats/architecture-tab.tsx@@ -1,4 +1,4 @@-import { Boxes, Lightbulb, Waypoints, FileCode } from "lucide-react";+import { Boxes, Lightbulb, Waypoints, FileCode, Repeat, Network } 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";@@ -6,13 +6,14 @@ import { formatNumber } from "@repowise-dev/ui/lib/format";export function ArchitectureTab({ data }: { data: StatsHighlights }) {const { scale, knowledge, quality, superlatives } = data;+ const graph = data.graph;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">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3"><StatCalloutlabel="Modules"value={formatNumber(scale.module_count)}@@ -25,12 +26,6 @@ export function ArchitectureTab({ data }: { data: StatsHighlights }) {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`}- /><StatCalloutlabel="Symbols"value={formatNumber(scale.symbol_count)}@@ -39,6 +34,35 @@ export function ArchitectureTab({ data }: { data: StatsHighlights }) {quality.doc_coverage_pct,)}% documented`}/>+ <StatCallout+ label="Decisions"+ value={formatNumber(knowledge.decision_count)}+ icon={<Lightbulb className="h-4 w-4" />}+ sub={`${formatNumber(knowledge.active_decision_count)} active`}+ />+ {graph && (+ <StatCallout+ label="Dependency cycles"+ value={formatNumber(graph.cycle_clusters)}+ tone={graph.cycle_clusters > 0 ? "warning" : "success"}+ icon={<Repeat className="h-4 w-4" />}+ sub={+ graph.cycle_clusters > 0+ ? `largest spans ${formatNumber(graph.largest_cycle)} files · ${formatNumber(+ graph.files_in_cycles,+ )} caught in a loop`+ : "no circular imports — clean layering"+ }+ />+ )}+ {graph && (+ <StatCallout+ label="Neighborhoods"+ value={formatNumber(graph.community_count)}+ icon={<Network className="h-4 w-4" />}+ sub="natural clusters in the import graph"+ />+ )}</div><div className="grid grid-cols-1 gap-4 lg:grid-cols-3">diff --git a/packages/web/src/components/stats/by-the-numbers-tab.tsx b/packages/web/src/components/stats/by-the-numbers-tab.tsxindex 291915a17..0fcb21716 100644--- a/packages/web/src/components/stats/by-the-numbers-tab.tsx+++ b/packages/web/src/components/stats/by-the-numbers-tab.tsx@@ -1,13 +1,30 @@-import { Bot, CalendarClock, Users, ShieldCheck, Trash2, HeartPulse, Package } from "lucide-react";+import {+ Bot,+ CalendarClock,+ Users,+ ShieldCheck,+ Trash2,+ HeartPulse,+ Package,+ TrendingUp,+ TrendingDown,+ Sparkles,+} from "lucide-react";import type { StatsHighlights } from "@repowise-dev/types/stats";import {SizeClassHero,StatCallout,SuperlativesGrid,- NLOC_HINT,+ PunchCard,AGENT_PCT_HINT,} from "@repowise-dev/ui/stats";-import { formatNumber, formatLOC, formatAgeDays, formatDate } from "@repowise-dev/ui/lib/format";+import {+ formatNumber,+ formatAgeDays,+ formatDate,+ formatTokens,+ formatCost,+} from "@repowise-dev/ui/lib/format";const ECOSYSTEM_NAMES: Record<string, string> = {npm: "npm",@@ -21,6 +38,16 @@ export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {const { scale, activity, quality, people, superlatives } = data;const da = quality.defect_accuracy;const deps = data.dependencies;+ const build = data.build;+ const vel = activity.velocity;++ // Momentum: recent-vs-prior commit change, or a plain recent count when there+ // is no prior window to compare against (young repo).+ const rising = vel?.pct_change != null && vel.pct_change >= 0;+ const momentum =+ vel?.pct_change != null+ ? `${rising ? "+" : ""}${vel.pct_change}%`+ : formatNumber(vel?.recent_90d ?? 0);return (<div className="space-y-5">@@ -76,15 +103,120 @@ export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {)}</div>- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">- <StatCallout- label="Lines of code"- value={formatLOC(scale.total_nloc)}- sub={`in the repo today · ${formatNumber(scale.symbol_count)} symbols across ${formatNumber(- scale.module_count,- )} modules`}- hint={NLOC_HINT}- />+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <div className="lg:col-span-2">+ <PunchCard data={activity.punch_card} />+ </div>+ <div className="flex flex-col gap-4">+ {/* Momentum — recent vs prior 90-day commit volume, with a mini+ comparison bar so the card carries its own weight. */}+ <div className="flex flex-1 flex-col justify-between rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Momentum+ </p>+ <span+ className={+ vel?.pct_change == null+ ? "text-[var(--color-text-tertiary)]"+ : rising+ ? "text-[var(--color-success)]"+ : "text-[var(--color-warning)]"+ }+ >+ {vel?.pct_change == null ? null : rising ? (+ <TrendingUp className="h-4 w-4" />+ ) : (+ <TrendingDown className="h-4 w-4" />+ )}+ </span>+ </div>+ <p+ className={`mt-1.5 text-3xl font-bold leading-none tabular-nums ${+ vel?.pct_change == null+ ? "text-[var(--color-text-primary)]"+ : rising+ ? "text-[var(--color-success)]"+ : "text-[var(--color-warning)]"+ }`}+ >+ {momentum}+ </p>+ {vel && vel.pct_change != null ? (+ <div className="mt-4 space-y-2">+ {(+ [+ { label: "Prev 90d", value: vel.prior_90d, accent: false },+ { label: "Last 90d", value: vel.recent_90d, accent: true },+ ] as const+ ).map((r) => {+ const barMax = Math.max(vel.recent_90d, vel.prior_90d, 1);+ return (+ <div key={r.label} className="flex items-center gap-2 text-[11px]">+ <span className="w-14 shrink-0 text-[var(--color-text-tertiary)]">+ {r.label}+ </span>+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-muted)]">+ <div+ className="h-full rounded-full"+ style={{+ width: `${(r.value / barMax) * 100}%`,+ background: r.accent+ ? "var(--color-accent-primary)"+ : "var(--color-text-tertiary)",+ }}+ />+ </div>+ <span className="w-8 shrink-0 text-right tabular-nums text-[var(--color-text-secondary)]">+ {formatNumber(r.value)}+ </span>+ </div>+ );+ })}+ </div>+ ) : (+ <p className="mt-2 text-xs text-[var(--color-text-secondary)]">+ commits in the last 90 days+ </p>+ )}+ </div>++ {/* This wiki, by the numbers — the knowledge base bragging about+ itself. Spread top-to-bottom so it fills the column. */}+ {build && build.page_count > 0 && (+ <div+ className="flex flex-1 flex-col justify-between overflow-hidden rounded-xl border border-[var(--color-border-default)] p-4"+ style={{ background: "var(--gradient-warm-wash, var(--color-bg-surface))" }}+ >+ <div className="flex items-center gap-2">+ <Sparkles className="h-4 w-4 text-[var(--color-accent-primary)]" />+ <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ This wiki, by the numbers+ </p>+ </div>+ <div className="my-3 grid grid-cols-3 gap-2">+ {[+ { v: formatNumber(build.page_count), l: "pages" },+ { v: formatTokens(build.total_tokens), l: "tokens" },+ { v: formatCost(build.cost_usd), l: "to build" },+ ].map((s) => (+ <div key={s.l}>+ <p className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {s.v}+ </p>+ <p className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)]">{s.l}</p>+ </div>+ ))}+ </div>+ <p className="text-[11px] text-[var(--color-text-secondary)]">+ distilled from your codebase in {formatNumber(build.llm_operations)} model calls+ </p>+ </div>+ )}+ </div>+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3"><StatCalloutlabel="Knowledge captured"value={formatNumber(data.knowledge.decision_count)}diff --git a/packages/web/src/components/stats/growth-tab.tsx b/packages/web/src/components/stats/growth-tab.tsxindex b7173bdc6..8bfd63769 100644--- a/packages/web/src/components/stats/growth-tab.tsx+++ b/packages/web/src/components/stats/growth-tab.tsx@@ -10,8 +10,16 @@ function monthLabel(month: string): string {return new Intl.DateTimeFormat("en-US", { month: "short", year: "numeric" }).format(d);}+const RISK_BANDS = [+ { key: "low", label: "Low", color: "var(--color-success)" },+ { key: "moderate", label: "Moderate", color: "var(--color-warning)" },+ { key: "high", label: "High", color: "var(--color-error)" },+] as const;+export function GrowthTab({ data }: { data: StatsHighlights }) {const { activity } = data;+ const risk = activity.change_risk_mix;+ const riskTotal = risk.low + risk.moderate + risk.high;return (<div className="space-y-5">@@ -49,6 +57,42 @@ export function GrowthTab({ data }: { data: StatsHighlights }) {/></div>+ {riskTotal > 0 && (+ <Card>+ <CardHeader className="flex-row items-center justify-between gap-3 pb-3">+ <CardTitle className="text-sm">Change-risk mix</CardTitle>+ <span className="text-[11px] text-[var(--color-text-tertiary)]">+ calibrated per-commit risk across {formatNumber(riskTotal)} commits+ </span>+ </CardHeader>+ <CardContent className="pt-0">+ <div className="flex h-3 w-full overflow-hidden rounded-full">+ {RISK_BANDS.map((b) => {+ const pct = (risk[b.key] / riskTotal) * 100;+ return pct > 0 ? (+ <div+ key={b.key}+ style={{ width: `${pct}%`, background: b.color }}+ title={`${b.label}: ${risk[b.key]} (${Math.round(pct)}%)`}+ />+ ) : null;+ })}+ </div>+ <div className="mt-3 grid grid-cols-3 gap-2 text-xs">+ {RISK_BANDS.map((b) => (+ <div key={b.key} className="flex items-center gap-1.5">+ <span className="h-2 w-2 rounded-full" style={{ background: b.color }} />+ <span className="text-[var(--color-text-secondary)]">{b.label}</span>+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ {formatNumber(risk[b.key])}+ </span>+ </div>+ ))}+ </div>+ </CardContent>+ </Card>+ )}+<ActivityTrendChart monthly={activity.monthly} />{activity.agent_names.length > 0 && (diff --git a/packages/web/src/components/stats/people-tab.tsx b/packages/web/src/components/stats/people-tab.tsxindex c07bdee94..2275ecdc0 100644--- a/packages/web/src/components/stats/people-tab.tsx+++ b/packages/web/src/components/stats/people-tab.tsx@@ -1,4 +1,4 @@-import { Users, UserCheck, AlertTriangle } from "lucide-react";+import { Users, UserCheck, AlertTriangle, Truck } 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";@@ -7,10 +7,24 @@ 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;+ const truck = people.truck_factor;return (<div className="space-y-5">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">+ {truck != null && (+ <StatCallout+ label="Truck factor"+ value={truck}+ tone={truck <= 2 ? "warning" : "default"}+ icon={<Truck className="h-4 w-4" />}+ sub={+ truck === 1+ ? "one person owns most of the code"+ : `lose ${truck} people and >50% of files lose their owner`+ }+ />+ )}<StatCalloutlabel="Contributors"value={formatNumber(activity.contributor_count)}diff --git a/tests/unit/server/test_stats_signals.py b/tests/unit/server/test_stats_signals.pynew file mode 100644index 000000000..e1c388b28--- /dev/null+++ b/tests/unit/server/test_stats_signals.py@@ -0,0 +1,190 @@+"""New "By the Numbers" signals: punch card, commit velocity, change-risk mix,+truck factor, dependency cycles, and the wiki build meta.++The pure summarizers are unit-tested directly; the commit-scan signals go+through ``_activity`` on a seeded ``git_commits`` table so the wiring (SELECT+columns, bucketing) is covered end to end.+"""++from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace++import pytest+from httpx import AsyncClient++from repowise.core.persistence.crud import get_repository, upsert_git_commits_bulk+from repowise.core.persistence.database import get_session+from repowise.server.routers.stats import (+ _activity,+ _commit_velocity,+ _people,+ _punch_card_summary,+)+from tests.unit.server.conftest import create_test_repo+++def _commit(sha: str, dt: datetime, risk: str = "low") -> dict:+ return {+ "sha": sha,+ "author_name": "Jane Doe",+ "author_email": "[email protected]",+ "committed_at": dt,+ "subject": f"commit {sha}",+ "lines_added": 5,+ "lines_deleted": 1,+ "files_changed": 1,+ "dirs_changed": 1,+ "subsystems_changed": 1,+ "entropy": 0.1,+ "is_fix": False,+ "change_risk_score": 1.0,+ "change_risk_level": risk,+ }+++# ---------------------------------------------------------------------------+# Pure summarizers+# ---------------------------------------------------------------------------+++def test_punch_card_summary_peak_and_weekend() -> None:+ punch = [[0] * 24 for _ in range(7)]+ punch[2][14] = 10 # Wednesday 2pm — the peak+ punch[0][9] = 4 # Monday 9am+ punch[5][11] = 3 # Saturday (weekend)+ punch[6][12] = 2 # Sunday (weekend)+ dated = 10 + 4 + 3 + 2++ out = _punch_card_summary(punch, weekend_commits=5, dated_total=dated)++ assert out["peak"] == {"weekday": 2, "hour": 14, "count": 10}+ assert out["busiest_weekday"] == 2+ assert out["peak_hour"] == 14+ assert out["weekend_pct"] == round(5 / dated * 100, 1)+ assert out["total"] == dated+++def test_punch_card_summary_empty() -> None:+ out = _punch_card_summary([[0] * 24 for _ in range(7)], weekend_commits=0, dated_total=0)+ assert out["peak"] is None+ assert out["busiest_weekday"] is None+ assert out["weekend_pct"] == 0.0+++def test_commit_velocity_rising_and_no_prior() -> None:+ anchor = datetime(2026, 6, 1, tzinfo=UTC)+ from datetime import timedelta++ recent = [anchor - timedelta(days=d) for d in (1, 10, 40, 80)] # 4 in last 90d+ prior = [anchor - timedelta(days=d) for d in (100, 150)] # 2 in prior 90d+ out = _commit_velocity(recent + prior, anchor)+ assert out["recent_90d"] == 4+ assert out["prior_90d"] == 2+ assert out["pct_change"] == 100.0 # 4 vs 2++ # No prior window → pct_change is None rather than a divide-by-zero spike.+ young = _commit_velocity(recent, anchor)+ assert young["prior_90d"] == 0+ assert young["pct_change"] is None+++def test_commit_velocity_empty() -> None:+ assert _commit_velocity([], None) == {"recent_90d": 0, "prior_90d": 0, "pct_change": None}+++# ---------------------------------------------------------------------------+# Truck factor (pure logic over _people)+# ---------------------------------------------------------------------------+++def _meta(owner: str, path: str) -> SimpleNamespace:+ return SimpleNamespace(primary_owner_name=owner, bus_factor=1, file_path=path)+++async def test_truck_factor_single_dominant_owner() -> None:+ # One owner holds 8/10 files → truck factor 1.+ metas = [_meta("Ada", f"a{i}.py") for i in range(8)] + [+ _meta("Bob", "b.py"),+ _meta("Cara", "c.py"),+ ]+ out = await _people(None, "repo", metas)+ assert out["truck_factor"] == 1+++async def test_truck_factor_spread_ownership() -> None:+ # Four owners with 3/3/2/2 → need 2 to cross 50% of 10.+ metas = (+ [_meta("Ada", f"a{i}.py") for i in range(3)]+ + [_meta("Bob", f"b{i}.py") for i in range(3)]+ + [_meta("Cara", f"c{i}.py") for i in range(2)]+ + [_meta("Dan", f"d{i}.py") for i in range(2)]+ )+ out = await _people(None, "repo", metas)+ assert out["truck_factor"] == 2+++async def test_truck_factor_none_without_owners() -> None:+ out = await _people(None, "repo", [SimpleNamespace(primary_owner_name=None, bus_factor=0, file_path="x.py")])+ assert out["truck_factor"] is None+++# ---------------------------------------------------------------------------+# End-to-end through _activity on a seeded commits table+# ---------------------------------------------------------------------------+++async def test_activity_punch_card_and_risk_mix(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ rows = [+ # Wednesday 2024-01-03 at 14:00 UTC — weekday 2, hour 14.+ _commit("w1", datetime(2024, 1, 3, 14, 0, tzinfo=UTC), risk="high"),+ _commit("w2", datetime(2024, 1, 3, 14, 30, tzinfo=UTC), risk="high"),+ # Saturday 2024-01-06 at 11:00 — weekend.+ _commit("s1", datetime(2024, 1, 6, 11, 0, tzinfo=UTC), risk="moderate"),+ # Sunday 2024-01-07 at 12:00 — weekend.+ _commit("s2", datetime(2024, 1, 7, 12, 0, tzinfo=UTC), risk="low"),+ ]+ async with get_session(app.state.session_factory) as session:+ await upsert_git_commits_bulk(session, repo["id"], rows)++ async with get_session(app.state.session_factory) as session:+ repo_row = await get_repository(session, repo["id"])+ activity = await _activity(session, repo["id"], repo_row)++ pc = activity["punch_card"]+ assert pc["matrix"][2][14] == 2 # both Wednesday-2pm commits landed in one cell+ assert pc["peak"] == {"weekday": 2, "hour": 14, "count": 2}+ assert pc["weekend_pct"] == 50.0 # 2 of 4 commits on Sat/Sun++ assert activity["change_risk_mix"] == {"low": 1, "moderate": 1, "high": 2}+++async def test_graph_and_build_degrade_to_zero(client: AsyncClient, app) -> None:+ """The graph + build sections return a fully-shaped zero payload on a repo+ with no graph-membership or LLM-cost rows (index-only / brand-new repo)."""+ from repowise.server.routers.stats import _build, _graph++ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ graph = await _graph(session, repo["id"])+ build = await _build(session, repo["id"])++ assert graph == {+ "cycle_clusters": 0,+ "files_in_cycles": 0,+ "largest_cycle": 0,+ "community_count": 0,+ }+ assert build == {+ "page_count": 0,+ "total_tokens": 0,+ "cost_usd": 0.0,+ "llm_operations": 0,+ }