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.

feat(ui): rebuild Commits and Contributors on the section design language (#1121)

Raghav Chamadiya8cc864b978d3
diff --git a/package-lock.json b/package-lock.json
index e9b0a44ad..b98bcce92 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -18717,7 +18717,7 @@
},
"packages/vscode": {
"name": "repowise",
- "version": "0.5.0",
+ "version": "0.6.0",
"license": "AGPL-3.0-or-later",
"devDependencies": {
"@repowise-dev/api-client": "*",
diff --git a/packages/ui/src/commits/code-evolution-chart.tsx b/packages/ui/src/commits/code-evolution-chart.tsx
index 6f790b7fd..dd6d8f965 100644
--- a/packages/ui/src/commits/code-evolution-chart.tsx
+++ b/packages/ui/src/commits/code-evolution-chart.tsx
@@ -38,19 +38,33 @@ interface CategoryMeta {
blurb: string;
}
-// Drawn bottom-to-top in this order; "feature" anchors the base so the growth
-// band reads as the foundation the rest of the work sits on. Colours route
-// through semantic design tokens (theme-aware, no raw hex) and are picked so
-// the mapping reads intuitively: green = new capability, red = fixes, etc.
+// Drawn bottom-to-top in STACK_ORDER; "feature" anchors the base so the growth
+// band reads as the foundation the rest of the work sits on.
+//
+// Two hues, then neutrals. This used to paint Feature in --color-success and
+// Fix in --color-error, which reads intuitively for about a second and then
+// costs more than it gives: those two tokens carry a health band on every
+// other surface in the app, so a reader arriving from Code Health has been
+// trained that green means good and red means bad. Here they mean "new
+// capability" and "bug fix", and a quarter of commits being fixes is not
+// thereby bad. Seven hues on the largest graphic on the page also set the
+// ceiling for everything under it, leaving the review-priority pills in the
+// table competing with the chart instead of leading.
+//
+// Fix keeps the accent because it is the series this chart exists to show;
+// Feature takes the plum secondary, a pairing globals.css already sanctions
+// (--color-savings-distill / --color-savings-mcp are exactly these two). The
+// rest are context, so they recede — which is also the honest encoding, since
+// the categories were never equally interesting.
const CATEGORY_META: Record<CommitCategory, CategoryMeta> = {
- feature: { label: "Feature", color: "var(--color-success)", blurb: "new capability" },
- fix: { label: "Fix", color: "var(--color-error)", blurb: "bug / regression" },
- refactor: { label: "Refactor", color: "var(--color-accent-primary)", blurb: "reshape / perf" },
- docs: { label: "Docs", color: "var(--color-info)", blurb: "documentation" },
- test: { label: "Test", color: "var(--color-amber)", blurb: "tests / coverage" },
- deps: { label: "Deps", color: "var(--color-caution)", blurb: "dependency bumps" },
- chore: { label: "Chore", color: "var(--color-text-tertiary)", blurb: "tooling / CI / release" },
- other: { label: "Other", color: "var(--color-border-active)", blurb: "unclassified" },
+ feature: { label: "Feature", color: "var(--color-accent-secondary)", blurb: "new capability" },
+ fix: { label: "Fix", color: "var(--color-ramp-1)", blurb: "bug / regression" },
+ refactor: { label: "Refactor", color: "var(--color-ramp-3)", blurb: "reshape / perf" },
+ docs: { label: "Docs", color: "var(--color-neutral-1)", blurb: "documentation" },
+ test: { label: "Test", color: "var(--color-ramp-5)", blurb: "tests / coverage" },
+ deps: { label: "Deps", color: "var(--color-neutral-2)", blurb: "dependency bumps" },
+ chore: { label: "Chore", color: "var(--color-neutral-3)", blurb: "tooling / CI / release" },
+ other: { label: "Other", color: "var(--color-bg-inset)", blurb: "unclassified" },
};
const STACK_ORDER: CommitCategory[] = [
@@ -197,20 +211,19 @@ export function CodeEvolutionChart({
if (evolution.buckets.length === 0) return null;
+ // No card and no heading of its own. The section that renders this already
+ // supplies both, so the bordered box was a box inside a section and "Code
+ // Evolution" was a second title for a chart the section had just named.
+ // What survives is the narrative line, which says something the section
+ // title cannot: what this particular repo's arc actually looks like.
return (
- <div
- className={cn(
- "rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 sm:p-5",
- className,
- )}
- >
- <div className="mb-3 flex flex-wrap items-start justify-between gap-3">
+ <div className={cn("flex flex-col gap-3", className)}>
+ <div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
- <GitBranch className="h-4 w-4 text-[var(--color-accent-primary)]" />
- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
- Code Evolution
- </h3>
+ <p className="text-[13px] font-medium text-[var(--color-text-primary)]">
+ {narrative ?? "How this repo's commit mix shifts over time."}
+ </p>
<TooltipProvider delayDuration={150}>
<UiTooltip>
<TooltipTrigger asChild>
@@ -230,10 +243,6 @@ export function CodeEvolutionChart({
</UiTooltip>
</TooltipProvider>
</div>
- <p className="mt-1 text-xs text-[var(--color-text-secondary)]">
- {narrative ??
- "How this repo's commit mix shifts over time."}
- </p>
</div>
<div className="flex items-center rounded-lg border border-[var(--color-border-default)] p-0.5 text-xs">
diff --git a/packages/ui/src/commits/commit-risk-scatter.tsx b/packages/ui/src/commits/commit-risk-scatter.tsx
index f1486b278..03e31faef 100644
--- a/packages/ui/src/commits/commit-risk-scatter.tsx
+++ b/packages/ui/src/commits/commit-risk-scatter.tsx
@@ -29,6 +29,12 @@ const PRIORITY_LABEL: Record<ReviewPriority, string> = {
const PRIORITY_ORDER: ReviewPriority[] = ["low", "moderate", "high"];
+/** Two decimals, so an SVG coordinate serialises identically on both sides
+ * of hydration. Well past sub-pixel on a 480-unit viewBox. */
+function round2(n: number): number {
+ return Math.round(n * 100) / 100;
+}
+
export function CommitRiskScatter({
commits,
onSelect,
@@ -52,6 +58,8 @@ export function CommitRiskScatter({
churn: (c.lines_added || 0) + (c.lines_deleted || 0),
entropy: c.entropy || 0,
}));
+ // Keep SVG coordinates short enough that the server and the client agree
+ // on their string form. See the note at the call site.
const xMaxLogRaw = Math.max(
1,
...sized.map((s) => Math.log10(1 + s.churn)),
@@ -61,7 +69,7 @@ export function CommitRiskScatter({
points: sized.map((s) => ({
...s,
// Bigger dot = more files touched, sqrt so area (not radius) scales.
- r: 3 + Math.min(9, Math.sqrt(s.commit.files_changed || 0)),
+ r: round2(3 + Math.min(9, Math.sqrt(s.commit.files_changed || 0))),
_x: Math.log10(1 + s.churn) / xMaxLogRaw,
_y: s.entropy / yMaxRaw,
})),
@@ -162,8 +170,14 @@ export function CommitRiskScatter({
</text>
{ordered.map((p) => {
- const cx = padding.left + p._x * innerW;
- const cy = padding.top + innerH - p._y * innerH;
+ // Rounded, not raw. A full-precision float round-trips through
+ // React's server renderer as a slightly different string than the
+ // client produces for the same number (…0089482 vs …00894822),
+ // which is a hydration mismatch on every dot once this chart is
+ // rendered from a server component. Two decimals is well past
+ // sub-pixel on a 480-unit viewBox.
+ const cx = round2(padding.left + p._x * innerW);
+ const cy = round2(padding.top + innerH - p._y * innerH);
const isHover = hover === p.commit.sha;
return (
<circle
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 41b3de4d0..82532e1c9 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -4,7 +4,6 @@ import { useMemo, useState } from "react";
import { Bug, Search } from "lucide-react";
import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
-import { ChurnBar } from "../git/churn-bar";
import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
@@ -56,7 +55,11 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [
{c.short_sha}
</span>
{c.is_fix && <Bug className="h-3 w-3 shrink-0 text-[var(--color-error)]" />}
- <span className="truncate text-xs text-[var(--color-text-primary)]" title={c.subject}>
+ {/* Wraps rather than truncates. This is the primary column, and an
+ ellipsis here reports a layout decision to the reader as a shorter
+ commit message: "release: v0.4.0, language-support upgrades across
+ all Goo…" is the page hiding the part that says which. */}
+ <span className="min-w-0 text-xs text-[var(--color-text-primary)] [text-wrap:pretty]">
{c.subject || "(no subject)"}
</span>
</div>
@@ -104,11 +107,15 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [
{
key: "risk",
header: "Risk",
- headerClassName: "w-40",
+ headerClassName: "w-28",
+ // No ChurnBar. The cell was carrying the same fact three times over (a
+ // filled bar, the percentile, and the pill), and because the queue sorts
+ // by risk the bar was full-width and semantic-red on every visible row —
+ // decoration that could not vary, drawn in the loudest colour available.
+ // The number and the pill say it, and only one of them needs ink.
render: (c) => (
<div className="flex items-center gap-2">
- <ChurnBar percentile={c.risk_percentile} className="w-16" />
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">
+ <span className="w-8 text-xs tabular-nums text-[var(--color-text-tertiary)]">
{Math.round(c.risk_percentile)}%
</span>
<PriorityBadge priority={c.review_priority as ReviewPriority} />
diff --git a/packages/ui/src/commits/commits-lede.tsx b/packages/ui/src/commits/commits-lede.tsx
new file mode 100644
index 000000000..5e772ff92
--- /dev/null
+++ b/packages/ui/src/commits/commits-lede.tsx
@@ -0,0 +1,119 @@
+import * as React from "react";
+import type { CommitStats } from "@repowise-dev/types/git";
+import { PageLede } from "../shared/page-lede";
+import { ReadsColumn, type ReadItem } from "../overview/reads-column";
+
+export interface CommitsLedeProps {
+ stats: CommitStats;
+ /** `/repos/{id}`, for the read-column drill-ins. */
+ base: string;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+function pct(part: number, whole: number): number {
+ return whole > 0 ? Math.round((part / whole) * 100) : 0;
+}
+
+/**
+ * What the commit history looks like, as one figure and a sentence.
+ *
+ * Replaces four `MetricCard`s of equal weight, which gave the page nothing to
+ * lead with: "Commits 4,912 / High priority 1,637 / Fix commits 1,204 / Avg
+ * entropy 0.42" is four numbers at 24px, one of them a bare 0.42 whose
+ * two-word caption ("change diffusion") did not say what it measured or which
+ * direction was bad.
+ *
+ * The headline is the review backlog rather than the commit count, because
+ * that is the thing this page exists to work through. Every figure here is
+ * server-computed over the whole history: reducing the loaded page instead
+ * would under-count fixes and, since the feed defaults to risk-sorted and is
+ * therefore entirely top-tercile, would report the high-priority share as
+ * roughly 100%.
+ *
+ * No median score: `CommitStats` does not carry one, and deriving it from the
+ * histogram bins would be an estimate printed as a measurement.
+ */
+export function CommitsLede({ stats, base, LinkComponent }: CommitsLedeProps) {
+ const total = stats.total_commits;
+ const highPct = pct(stats.high_priority_count, total);
+ const fixPct = pct(stats.fix_commit_count, total);
+ const agentPct = pct(stats.agent_commit_count, total);
+
+ const reads: ReadItem[] = [
+ {
+ key: "fixes",
+ label: "Fix commits",
+ value: stats.fix_commit_count.toLocaleString(),
+ unit: `${fixPct}%`,
+ why: "Commits whose subject reads as a bug fix rather than new work.",
+ href: `${base}/hotspots`,
+ },
+ ];
+ if (stats.agent_commit_count > 0) {
+ reads.push({
+ key: "agent",
+ label: "Written by an agent",
+ value: stats.agent_commit_count.toLocaleString(),
+ unit: `${agentPct}%`,
+ why: "Read from commit trailers, so it counts what was declared.",
+ href: `${base}/commits`,
+ });
+ }
+ reads.push({
+ key: "entropy",
+ label: "Change diffusion",
+ value: stats.avg_entropy.toFixed(2),
+ unit: "bits",
+ // Shannon entropy of the per-file churn distribution, in bits, and
+ // deliberately not normalised (see _entropy in change_risk/features.py).
+ // It has no 1.0 ceiling: k equally-changed files score log2(k), so this
+ // repo's 2.08 is roughly four files' worth of spread.
+ why: "Shannon entropy of a commit's churn across its files. Zero is a single file, and every extra bit is a doubling of how widely the change spread.",
+ href: `${base}/coupling`,
+ });
+ if (stats.high_cut != null) {
+ reads.push({
+ key: "cut",
+ label: "Review threshold",
+ value: stats.high_cut.toFixed(1),
+ unit: "out of 10",
+ why: "Score a commit has to clear to land in this repo's top tercile.",
+ href: `${base}/risk`,
+ });
+ }
+
+ // No StatRibbon here, deliberately. `CommitStats` carries six measured
+ // figures and the lede plus this column already spend all six, so a ribbon
+ // under them could only restate what is directly above it — which is the
+ // box soup this redesign exists to remove, wearing hairlines instead of
+ // borders. The contributor page keeps its ribbon because that payload has
+ // figures left over.
+ return (
+ <div className="flex flex-col gap-6 sm:gap-8">
+ <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">
+ <PageLede
+ label="Needs review"
+ value={stats.high_priority_count.toLocaleString()}
+ unit={`of ${total.toLocaleString()} scored`}
+ >
+ <p>
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {stats.high_priority_count.toLocaleString()} commits
+ </strong>{" "}
+ sit in this repo&apos;s top risk tercile, which is {highPct}% of the{" "}
+ {total.toLocaleString()} scored. The cut is drawn against this
+ codebase&apos;s own history rather than a global curve, so a quiet repo
+ still fills its top band
+ {stats.high_cut != null
+ ? `, and here it starts at ${stats.high_cut.toFixed(1)} out of 10`
+ : ""}
+ . What pushes a commit up is size and spread together: a large change
+ confined to one area scores below a smaller one scattered across a
+ dozen files.
+ </p>
+ </PageLede>
+ <ReadsColumn items={reads} LinkComponent={LinkComponent} />
+ </section>
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.ts
index d8b188556..a395eca0c 100644
--- a/packages/ui/src/commits/index.ts
+++ b/packages/ui/src/commits/index.ts
@@ -1,4 +1,5 @@
export * from "./code-evolution-chart";
+export * from "./commits-lede";
export * from "./commit-table";
export * from "./commit-detail-card";
export * from "./risk-driver-breakdown";
diff --git a/packages/ui/src/commits/priority-badge.tsx b/packages/ui/src/commits/priority-badge.tsx
index ea92f187d..7cf3e2a9b 100644
--- a/packages/ui/src/commits/priority-badge.tsx
+++ b/packages/ui/src/commits/priority-badge.tsx
@@ -2,13 +2,26 @@ import { cn } from "../lib/cn";
import type { ReviewPriority } from "@repowise-dev/types/git";
// Colours track review attention, not absolute danger: "Below typical" and
-// "Typical" are calm (this commit is not unusual for the repo); only "Elevated"
-// — the top third of the repo's own distribution — draws the eye.
+// "Typical" are calm (this commit is not unusual for the repo); only
+// "Elevated", the top third of the repo's own distribution, draws the eye.
+//
+// All three lost their fill. The queue defaults to risk-sorted, so the first
+// screen is by construction almost entirely "Elevated": a tinted amber pill on
+// every row stopped marking anything and just turned the leftmost column into
+// a block of colour competing with the subjects beside it. A dot plus a word
+// carries the same three-way distinction at a fraction of the ink, and the
+// pill still reads as elevated when one turns up further down a date-sorted
+// page, which is where it actually needs to catch the eye.
const STYLES: Record<ReviewPriority, string> = {
- high: "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border-[var(--color-warning)]/25",
- moderate:
- "bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)] border-[var(--color-border-default)]",
- low: "bg-[var(--color-success)]/15 text-[var(--color-success)] border-[var(--color-success)]/25",
+ high: "text-[var(--color-warning)]",
+ moderate: "text-[var(--color-text-tertiary)]",
+ low: "text-[var(--color-text-tertiary)]",
+};
+
+const DOTS: Record<ReviewPriority, string> = {
+ high: "bg-[var(--color-warning)]",
+ moderate: "bg-[var(--color-border-hover)]",
+ low: "bg-[var(--color-success)]/60",
};
// Repo-relative tercile wording — where the commit sits in *its own repo's*
@@ -35,12 +48,16 @@ export function PriorityBadge({
return (
<span
className={cn(
- "inline-flex items-center rounded border px-1.5 py-0.5 text-xs font-medium tabular-nums",
+ "inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-medium",
STYLES[priority],
className,
)}
title="Review priority relative to this repo's own commit-risk distribution"
>
+ <span
+ aria-hidden
+ className={cn("h-1.5 w-1.5 shrink-0 rounded-full", DOTS[priority])}
+ />
{LABELS[priority]}
</span>
);
diff --git a/packages/ui/src/lib/github.ts b/packages/ui/src/lib/github.ts
new file mode 100644
index 000000000..c868ab57b
--- /dev/null
+++ b/packages/ui/src/lib/github.ts
@@ -0,0 +1,63 @@
+/**
+ * Resolving GitHub identities out of the things git actually records.
+ *
+ * Both helpers are deliberately conservative: they return null for anything
+ * they cannot prove, because the caller's fallback (initials) is a perfectly
+ * good default rather than an error state. Guessing wrong is worse than not
+ * guessing — a wrong avatar attributes someone else's face to a commit.
+ */
+
+/** `https://avatars.githubusercontent.com/...` for a login, at a given px size. */
+export function githubAvatarUrl(login: string, size: number): string {
+ return `https://avatars.githubusercontent.com/${encodeURIComponent(login)}?size=${size}`;
+}
+
+/**
+ * Parses the owner (user or org) out of a git remote URL.
+ *
+ * Handles the three forms a remote actually takes: HTTPS, SSH scp-style, and
+ * `ssh://`. Returns null for anything that is not GitHub, which is the signal
+ * to render initials instead of reaching for an avatar that does not exist.
+ */
+export function githubOwnerFromRemote(remote: string | null | undefined): string | null {
+ if (!remote) return null;
+ const trimmed = remote.trim().replace(/\.git$/, "");
+ const patterns = [
+ /^https?:\/\/(?:[^@]+@)?github\.com\/([^/]+)\/[^/]+$/i,
+ /^git@github\.com:([^/]+)\/[^/]+$/i,
+ /^ssh:\/\/git@github\.com\/([^/]+)\/[^/]+$/i,
+ ];
+ for (const re of patterns) {
+ const m = trimmed.match(re);
+ if (m?.[1]) return m[1];
+ }
+ return null;
+}
+
+/**
+ * Parses a GitHub login out of a commit author email, for the two noreply
+ * forms GitHub issues:
+ *
+ * [email protected] (current)
+ * [email protected] (pre-2017)
+ *
+ * Only noreply addresses, on purpose. The alternative for a real address is
+ * Gravatar, which means hashing a contributor's email and sending it to a
+ * third party from the viewer's browser: on a private repo that hands the
+ * contributor roster to someone who was never asked, and an MD5 of a known
+ * corporate address is trivially reversible. A noreply address already
+ * encodes a public username, so resolving it leaks nothing that was not
+ * already public.
+ *
+ * Coverage is therefore partial by design — good on open-source history,
+ * near zero on a repo where everyone commits from their work address. That is
+ * fine: initials are the default state, not a failure.
+ */
+export function githubLoginFromEmail(email: string | null | undefined): string | null {
+ if (!email) return null;
+ const m = email
+ .trim()
+ .toLowerCase()
+ .match(/^(?:\d+\+)?([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})@users\.noreply\.github\.com$/);
+ return m?.[1] ?? null;
+}
diff --git a/packages/ui/src/lib/ramp.ts b/packages/ui/src/lib/ramp.ts
new file mode 100644
index 000000000..a6a85b34d
--- /dev/null
+++ b/packages/ui/src/lib/ramp.ts
@@ -0,0 +1,55 @@
+/**
+ * The accent ramp, as CSS var references.
+ *
+ * One place so a stacked bar, a histogram and an area chart all step through
+ * the same five values. The values themselves live in `styles/globals.css`,
+ * per theme — see the comment there for why the light and dark ramps are not
+ * the same mix percentages.
+ *
+ * Use `RAMP` for ordered shares of a whole, where position means magnitude.
+ * For unrelated categories reach for `CATEGORICAL` instead: two hues the
+ * token system already sanctions together, then neutrals. A qualitative
+ * palette of five unrelated hues is what this exists to avoid.
+ */
+
+export const RAMP = [
+ "var(--color-ramp-1)",
+ "var(--color-ramp-2)",
+ "var(--color-ramp-3)",
+ "var(--color-ramp-4)",
+ "var(--color-ramp-5)",
+] as const;
+
+export const NEUTRALS = [
+ "var(--color-neutral-1)",
+ "var(--color-neutral-2)",
+ "var(--color-neutral-3)",
+] as const;
+
+/** The long tail past the end of the ramp: present, but not a step. */
+export const RAMP_TAIL = "var(--color-bg-inset)";
+
+/**
+ * Ramp step for position `i`. Anything past the last step returns the tail,
+ * so a caller can map an arbitrarily long sorted list without bounds checks
+ * and without inventing colours it does not have.
+ */
+export function rampStep(i: number): string {
+ return RAMP[i] ?? RAMP_TAIL;
+}
+
+/**
+ * Two hues then neutrals, for a small set of unrelated categories.
+ *
+ * The pairing is not invented here: `--color-savings-distill` and
+ * `--color-savings-mcp` are already accent-fill and accent-secondary, so the
+ * token system has settled that these two read as distinct without either
+ * standing in for a health band. Everything after position 2 recedes, which
+ * is the honest encoding when the trailing categories are context rather
+ * than subject.
+ */
+export const CATEGORICAL = [
+ "var(--color-ramp-1)",
+ "var(--color-accent-secondary)",
+ ...NEUTRALS,
+] as const;
diff --git a/packages/ui/src/overview/health-lede.tsx b/packages/ui/src/overview/health-lede.tsx
index d8de012ad..9be9c823f 100644
--- a/packages/ui/src/overview/health-lede.tsx
+++ b/packages/ui/src/overview/health-lede.tsx
@@ -1,4 +1,5 @@
import * as React from "react";
+import { LedeLink, PageLede } from "../shared/page-lede";
export interface HealthLedeProps {
/** Defect-risk headline, 1–10. Null until the first health run. */
@@ -48,8 +49,6 @@ export function HealthLede({
href,
LinkComponent,
}: HealthLedeProps) {
- const A = LinkComponent ?? "a";
-
if (score == null) {
return (
<div className="flex flex-col gap-2">
@@ -84,32 +83,19 @@ export function HealthLede({
}`;
return (
- <div className="flex flex-col">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Code health
- </p>
-
- <div className="mt-2.5 flex flex-wrap items-baseline gap-x-3 gap-y-1">
- <span
- className="text-[44px] font-semibold leading-none tracking-tight tabular-nums sm:text-5xl"
- style={{ color: band.color }}
- >
- {score.toFixed(1)}
- </span>
- <span className="text-xs text-[var(--color-text-tertiary)]">out of 10</span>
- <span
- className="rounded-full border px-2.5 py-0.5 text-[11px] font-medium"
- style={{
- color: band.color,
- borderColor: `color-mix(in srgb, ${band.color} 40%, transparent)`,
- background: `color-mix(in srgb, ${band.color} 9%, transparent)`,
- }}
- >
- {band.label}
- </span>
- </div>
-
- <p className="mt-3.5 max-w-[54ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <PageLede
+ label="Code health"
+ value={score.toFixed(1)}
+ valueColor={band.color}
+ unit="out of 10"
+ band={band}
+ action={
+ <LedeLink href={href} LinkComponent={LinkComponent}>
+ Full health report
+ </LedeLink>
+ }
+ >
+ <p>
This codebase scores{" "}
<strong className="font-semibold text-[var(--color-text-primary)]">
{score.toFixed(1)} out of 10
@@ -132,13 +118,6 @@ export function HealthLede({
</>
)}
</p>
-
- <A
- href={href}
- className="mt-4 inline-flex w-fit items-center gap-1 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
- >
- Full health report <span aria-hidden>→</span>
- </A>
- </div>
+ </PageLede>
);
}
diff --git a/packages/ui/src/overview/reads-column.tsx b/packages/ui/src/overview/reads-column.tsx
index d0c3924e0..8649f2e86 100644
--- a/packages/ui/src/overview/reads-column.tsx
+++ b/packages/ui/src/overview/reads-column.tsx
@@ -46,7 +46,7 @@ export function ReadsColumn({
LinkComponent,
}: {
items: ReadItem[];
- LinkComponent?: React.ElementType;
+ LinkComponent?: React.ElementType | undefined;
}) {
const A = LinkComponent ?? "a";
if (items.length === 0) return null;
diff --git a/packages/ui/src/overview/repo-avatar.tsx b/packages/ui/src/overview/repo-avatar.tsx
index 9c061e189..9a34d7a78 100644
--- a/packages/ui/src/overview/repo-avatar.tsx
+++ b/packages/ui/src/overview/repo-avatar.tsx
@@ -1,26 +1,10 @@
import * as React from "react";
+import { githubAvatarUrl, githubOwnerFromRemote } from "../lib/github";
-/**
- * Parses the owner (GitHub user or org) out of a git remote URL.
- *
- * Handles the three forms a remote actually takes: HTTPS, SSH scp-style, and
- * `ssh://`. Returns null for anything that is not GitHub, which is the signal
- * to render initials instead of reaching for an avatar that does not exist.
- */
-export function githubOwnerFromRemote(remote: string | null | undefined): string | null {
- if (!remote) return null;
- const trimmed = remote.trim().replace(/\.git$/, "");
- const patterns = [
- /^https?:\/\/(?:[^@]+@)?github\.com\/([^/]+)\/[^/]+$/i,
- /^git@github\.com:([^/]+)\/[^/]+$/i,
- /^ssh:\/\/git@github\.com\/([^/]+)\/[^/]+$/i,
- ];
- for (const re of patterns) {
- const m = trimmed.match(re);
- if (m?.[1]) return m[1];
- }
- return null;
-}
+// Re-exported because `overview/index.ts` and the existing tests import it
+// from here. The implementation moved to `lib/github` so the owner avatar can
+// share it instead of growing a second copy of the same parsing.
+export { githubOwnerFromRemote };
export interface RepoAvatarProps {
/** Repo name, for the initials fallback. */
@@ -65,7 +49,7 @@ export function RepoAvatar({ name, remoteUrl, size = 40, className }: RepoAvatar
</span>
{owner && (
<img
- src={`https://avatars.githubusercontent.com/${encodeURIComponent(owner)}?size=${size * 2}`}
+ src={githubAvatarUrl(owner, size * 2)}
alt=""
width={size}
height={size}
diff --git a/packages/ui/src/overview/section.tsx b/packages/ui/src/overview/section.tsx
index 1d75c2d99..0825fe6ca 100644
--- a/packages/ui/src/overview/section.tsx
+++ b/packages/ui/src/overview/section.tsx
@@ -68,7 +68,7 @@ export function SectionLink({
}: {
href: string;
children: React.ReactNode;
- LinkComponent?: React.ElementType;
+ LinkComponent?: React.ElementType | undefined;
}) {
const A = LinkComponent ?? "a";
return (
diff --git a/packages/ui/src/owners/index.ts b/packages/ui/src/owners/index.ts
index 3b4ad6399..1112b27f5 100644
--- a/packages/ui/src/owners/index.ts
+++ b/packages/ui/src/owners/index.ts
@@ -1,5 +1,5 @@
-export * from "./owner-card";
export * from "./owner-directory";
+export * from "./owner-table";
export * from "./ownership-distribution-bar";
export * from "./owner-profile";
export * from "./owner-avatar";
diff --git a/packages/ui/src/owners/owner-avatar.tsx b/packages/ui/src/owners/owner-avatar.tsx
index e3162dc3c..5a9f7e5ea 100644
--- a/packages/ui/src/owners/owner-avatar.tsx
+++ b/packages/ui/src/owners/owner-avatar.tsx
@@ -1,28 +1,30 @@
-"use client";
-
+import * as React from "react";
import { cn } from "../lib/cn";
+import { githubAvatarUrl, githubLoginFromEmail } from "../lib/github";
/**
- * 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.
+ * Contributor mark: a real GitHub avatar where we can prove one, initials
+ * everywhere else.
+ *
+ * Three decisions worth keeping:
+ *
+ * 1. **Not a client component.** There is no state and no handler here, so the
+ * directive only forced every parent that renders a list of these to ship
+ * them to the browser. Dropping it lets the owner rows render on the server.
+ *
+ * 2. **Initials sit *underneath* the image**, the same trick as `RepoAvatar`.
+ * The obvious implementation swaps in a fallback from `onError`, which needs
+ * `useState` and therefore re-introduces the client boundary above. Instead
+ * an `alt=""` image that 404s paints nothing and the layer beneath shows
+ * through. No JavaScript, same outcome.
+ *
+ * 3. **One accent, not eight hues.** This used to pick from a rose / amber /
+ * emerald / sky / … palette hashed off the email, which spent eight colours
+ * on a distinction that carries no meaning — two contributors being
+ * different colours tells you nothing about either. It also hard-coded the
+ * `-300` text ramp, tuned for dark mode, and rendered it unchanged on the
+ * cream light background.
*/
-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();
@@ -36,30 +38,51 @@ function initials(name: string, email: string | null): string {
return source.slice(0, 2).toUpperCase();
}
+const SIZE_PX = { sm: 24, md: 32, lg: 48 } as const;
+
export interface OwnerAvatarProps {
name: string;
email?: string | null;
- size?: "sm" | "md" | "lg";
+ size?: keyof typeof SIZE_PX;
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";
+ const px = SIZE_PX[size];
+ const login = githubLoginFromEmail(email);
+ const label = name || email || "contributor";
+
return (
- <div
+ <span
className={cn(
- "inline-flex shrink-0 items-center justify-center rounded-full font-semibold tracking-wide",
- color,
- sizeCls,
+ "relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full",
+ "border border-[var(--color-border-default)] bg-[var(--color-accent-muted)]",
className,
)}
- aria-label={name || email || "contributor"}
- title={name || email || ""}
+ style={{ width: px, height: px }}
+ aria-label={label}
+ title={label}
>
- {initials(name, email ?? null)}
- </div>
+ <span
+ className="font-semibold leading-none tracking-wide text-[var(--color-accent-primary)]"
+ style={{ fontSize: Math.max(9, Math.floor(px / 2.9)) }}
+ >
+ {initials(name, email ?? null)}
+ </span>
+ {login && (
+ <img
+ // 2x for retina. Requested only when a noreply address proved a
+ // login, so a repo with no GitHub-hosted history touches no network.
+ src={githubAvatarUrl(login, px * 2)}
+ alt=""
+ width={px}
+ height={px}
+ loading="lazy"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ className="absolute inset-0 h-full w-full object-cover"
+ />
+ )}
+ </span>
);
}
diff --git a/packages/ui/src/owners/owner-card.tsx b/packages/ui/src/owners/owner-card.tsx
deleted file mode 100644
index 7c26dcb87..000000000
--- a/packages/ui/src/owners/owner-card.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-"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 { formatRelativeTimeOrNull } from "../lib/format";
-import { OwnerAvatar } from "./owner-avatar";
-
-interface OwnerCardProps {
- owner: OwnerListEntry;
- onSelect?: (owner: OwnerListEntry) => void;
- highlight?: boolean;
-}
-
-/**
- * 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-xs 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-[var(--color-warning)]" />}
- 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-[var(--color-error)]" />}
- 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-[var(--color-text-tertiary)]" />}
- tone={owner.dead_code_lines_owned > 0 ? "muted" : undefined}
- />
- </div>
- <div className="mt-3 flex items-center justify-between text-xs 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 {formatRelativeTimeOrNull(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-[var(--color-error)]"
- : tone === "warn"
- ? "text-[var(--color-warning)]"
- : tone === "muted"
- ? "text-[var(--color-text-tertiary)]"
- : "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
index 06fb997b3..f46a50b6e 100644
--- a/packages/ui/src/owners/owner-directory.tsx
+++ b/packages/ui/src/owners/owner-directory.tsx
@@ -1,30 +1,20 @@
"use client";
-import { useMemo } from "react";
+import * as React 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";
+import { PageLede } from "../shared/page-lede";
+import { OverviewSection, SectionLink } from "../overview/section";
+import { ReadsColumn, type ReadItem } from "../overview/reads-column";
+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
+import { OwnerTable, type OwnerSortKey } from "./owner-table";
import { OwnershipDistributionBar } from "./ownership-distribution-bar";
-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 type { OwnerSortKey };
export interface OwnerDirectoryFilters {
q: string;
@@ -33,9 +23,9 @@ export interface OwnerDirectoryFilters {
export interface OwnerDirectoryProps {
owners: OwnerListEntry[];
- /** Optional full owner set for the distribution bar (e.g. fetched via
- * listAllOwners when the contributor count is small). Falls back to
- * `owners` when omitted. */
+ /** Optional full owner set for the distribution bar and the lede (e.g.
+ * fetched via listAllOwners when the contributor count is small). Falls
+ * back to `owners` when omitted. */
distributionOwners?: OwnerListEntry[];
isLoading: boolean;
isValidating: boolean;
@@ -45,8 +35,32 @@ export interface OwnerDirectoryProps {
onFiltersChange: (next: OwnerDirectoryFilters) => void;
onLoadMore: () => void;
onSelect: (owner: OwnerListEntry) => void;
+ /** Preferred over `onSelect`: gives every row a real URL. */
+ hrefFor?: (owner: OwnerListEntry) => string;
+ /** Base path for the section jump links, e.g. `/repos/42`. */
+ base?: string;
+ LinkComponent?: React.ElementType | undefined;
}
+const INACTIVE_DAYS = 90;
+
+function daysSince(iso: string | null): number | null {
+ if (!iso) return null;
+ const t = Date.parse(iso);
+ if (Number.isNaN(t)) return null;
+ return (Date.now() - t) / 86_400_000;
+}
+
+/**
+ * Who knows what, as a lede plus one table.
+ *
+ * This page used to open on four bordered counters — one of them "Bus-factor
+ * risk: 12" in red — above a 3-up grid of contributor cards. The counters told
+ * a reader to worry without saying what about, and the grid could not answer
+ * the question people actually arrive with, which is how two contributors
+ * compare: that needs the figures in a column, which a card grid makes
+ * impossible. Both are now one figure with a sentence, and one aligned table.
+ */
export function OwnerDirectory({
owners,
distributionOwners,
@@ -58,110 +72,261 @@ export function OwnerDirectory({
onFiltersChange,
onLoadMore,
onSelect,
+ hrefFor,
+ base,
+ LinkComponent,
}: OwnerDirectoryProps) {
- const barOwners = distributionOwners ?? owners;
- // 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]);
+ // The lede is a claim about the whole repo, so it is computed off the full
+ // set when the caller has one. Computed off the loaded page instead, "68% of
+ // files" would silently mean "68% of the 30 rows currently rendered" and
+ // would change as you scrolled — a figure that moves while the data does not
+ // is a wrong figure, not a live one.
+ const source = distributionOwners ?? owners;
+ const complete = distributionOwners != null || (!hasMore && filters.q === "");
+
+ const summary = React.useMemo(() => {
+ const sorted = [...source].sort((a, b) => b.files_owned - a.files_owned);
+ const totalFiles = sorted.reduce((s, o) => s + o.files_owned, 0);
+ const top3 = sorted.slice(0, 3).reduce((s, o) => s + o.files_owned, 0);
+ const soleFiles = sorted.reduce((s, o) => s + o.bus_factor_risk_files, 0);
+ const soleFilesInactive = sorted.reduce((s, o) => {
+ const d = daysSince(o.last_commit_at);
+ return d != null && d > INACTIVE_DAYS ? s + o.bus_factor_risk_files : s;
+ }, 0);
+ const siloOwners = sorted.filter((o) => o.silo_modules > 0).length;
+ const siloModules = sorted.reduce((s, o) => s + o.silo_modules, 0);
+ const deadLines = sorted.reduce((s, o) => s + o.dead_code_lines_owned, 0);
+ const deadOwners = sorted.filter((o) => o.dead_code_lines_owned > 0).length;
+ const deadFiles = sorted.reduce((s, o) => s + o.dead_code_files_owned, 0);
+ const active = sorted.filter((o) => o.commit_count_90d > 0).length;
+ const hotspots = sorted.reduce((s, o) => s + o.hotspots_owned, 0);
+ const commits90d = sorted.reduce((s, o) => s + o.commit_count_90d, 0);
+ return {
+ deadFiles,
+ hotspots,
+ commits90d,
+ topName: sorted[0]?.name ?? null,
+ topFiles: sorted[0]?.files_owned ?? 0,
+ totalFiles,
+ top3Pct: totalFiles > 0 ? Math.round((top3 / totalFiles) * 100) : 0,
+ soleFiles,
+ soleFilesInactive,
+ siloOwners,
+ siloModules,
+ deadLines,
+ deadOwners,
+ active,
+ };
+ }, [source]);
+
+ // Built rather than declared: a repo with no dead code and no silos should
+ // get a shorter column, not four rows of zeroes. An empty state that says
+ // "0" is claiming a measurement; omitting the row says there is nothing to
+ // report, which is what is true.
+ const reads: ReadItem[] = [];
+ if (summary.soleFiles > 0) {
+ reads.push({
+ key: "sole",
+ label: "Sole-owned files",
+ value: summary.soleFiles.toLocaleString(),
+ ...(summary.totalFiles > 0
+ ? { unit: `of ${summary.totalFiles.toLocaleString()}` }
+ : {}),
+ why:
+ summary.soleFilesInactive > 0
+ ? `One author, no second reader. ${summary.soleFilesInactive.toLocaleString()} belong to someone who has not committed in ${INACTIVE_DAYS} days.`
+ : "One author and no second reader, though all of them belong to someone still active.",
+ href: base ? `${base}/ownership` : "#",
+ });
+ }
+ if (summary.siloModules > 0) {
+ reads.push({
+ key: "silo",
+ label: "Silo modules",
+ value: summary.siloModules.toLocaleString(),
+ unit: `${summary.siloOwners} ${summary.siloOwners === 1 ? "person" : "people"}`,
+ why: "A single person owns more than 80% of the module.",
+ href: base ? `${base}/modules` : "#",
+ });
+ }
+ reads.push({
+ key: "active",
+ label: "Active this quarter",
+ value: summary.active.toLocaleString(),
+ unit: `of ${total.toLocaleString()}`,
+ why: `Committed in the last ${INACTIVE_DAYS} days. The rest are history, not staffing.`,
+ href: base ? `${base}/commits` : "#",
+ });
+ if (summary.deadLines > 0) {
+ reads.push({
+ key: "dead",
+ label: "Dead lines owned",
+ value: summary.deadLines.toLocaleString(),
+ unit: `${summary.deadOwners} ${summary.deadOwners === 1 ? "person" : "people"}`,
+ why: "Unreachable code still attributed to whoever wrote it.",
+ href: base ? `${base}/dead-code` : "#",
+ });
+ }
+
+ // Deliberately disjoint from `reads` above. The first cut of this row
+ // restated Active, Sole-owned and Silo modules from the column immediately
+ // beside it, so three of five cells were the same figure twice on one
+ // screen. StatRibbon drops empty-valued entries itself, so an unmeasured
+ // figure leaves no gap.
+ const ribbon: RibbonStat[] = [
+ {
+ label: "Contributors",
+ value: total.toLocaleString(),
+ hint: "Distinct commit authors in the indexed history",
+ },
+ {
+ label: "Files attributed",
+ value: summary.totalFiles > 0 ? summary.totalFiles.toLocaleString() : "",
+ },
+ {
+ label: "Hotspots owned",
+ value: summary.hotspots > 0 ? summary.hotspots.toLocaleString() : "",
+ hint: "Owned files that are also high-churn",
+ },
+ {
+ label: "Commits 90d",
+ value: summary.commits90d > 0 ? summary.commits90d.toLocaleString() : "",
+ },
+ {
+ label: "Dead-code files",
+ value: summary.deadFiles > 0 ? summary.deadFiles.toLocaleString() : "",
+ hint: "Files carrying unreachable code, counted separately from the line total",
+ },
+ ];
return (
- <div className="space-y-5">
- {barOwners.length > 0 && (
- <OwnershipDistributionBar
- owners={barOwners}
- totalContributors={total}
- onSelect={onSelect}
- />
+ <div className="flex flex-col gap-6 sm:gap-8">
+ {summary.totalFiles > 0 && (
+ <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">
+ <PageLede
+ label="Knowledge concentration"
+ value={`${summary.top3Pct}%`}
+ band={{ label: summary.top3Pct >= 60 ? "Concentrated" : "Spread" }}
+ {...(complete ? {} : { unit: "of the contributors loaded so far" })}
+ >
+ <p>
+ The top three of {total.toLocaleString()} contributors own{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {summary.top3Pct}%
+ </strong>{" "}
+ of the {summary.totalFiles.toLocaleString()} attributed files
+ {summary.topName
+ ? `, with ${summary.topName} on ${summary.topFiles.toLocaleString()} of them`
+ : ""}
+ . Ownership is attributed by who wrote the surviving lines, not by who
+ committed last, so a formatting sweep does not hand someone a file they
+ have never read.
+ {summary.soleFiles > 0 && (
+ <>
+ {" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {summary.soleFiles.toLocaleString()}
+ </strong>{" "}
+ of those files have a single author and no second reader, which is
+ where the knowledge actually walks out.
+ </>
+ )}
+ </p>
+ </PageLede>
+ {reads.length > 0 && <ReadsColumn items={reads} LinkComponent={LinkComponent} />}
+ </section>
)}
- <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>
+ {/* Same guard as the lede. Before an index lands, every figure here is
+ zero and StatRibbon's empty-value filter leaves a single "Contributors
+ 0" cell stranded in a five-column row. Nothing measured, nothing
+ drawn. */}
+ {summary.totalFiles > 0 && (
+ <StatRibbon stats={ribbon} LinkComponent={LinkComponent} />
+ )}
+
+ {source.length > 0 && (
+ <OverviewSection
+ title="How ownership is spread"
+ description="Share of attributed files per contributor, largest first, with the long tail collapsed into one segment."
+ {...(base
+ ? {
+ action: (
+ <SectionLink href={`${base}/ownership`} LinkComponent={LinkComponent}>
+ Ownership map
+ </SectionLink>
+ ),
+ }
+ : {})}
+ >
+ <OwnershipDistributionBar
+ owners={source}
+ totalContributors={total}
+ {...(hrefFor ? { hrefFor } : { onSelect })}
+ {...(LinkComponent ? { LinkComponent } : {})}
+ />
+ </OverviewSection>
+ )}
- <div className="flex flex-wrap items-center gap-2">
- <div className="relative flex-1 min-w-[220px]">
+ <OverviewSection
+ title="Everyone"
+ description="A dot marks sole-owned files held by someone who has stopped committing, so a clean column means nothing to chase."
+ action={
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {total.toLocaleString()} {total === 1 ? "contributor" : "contributors"}
+ </span>
+ }
+ >
+ <div className="relative max-w-sm">
<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…"
+ aria-label="Filter contributors 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>
- );
-}
+ {isLoading && owners.length === 0 ? (
+ // Row-height skeletons, not tiles: a skeleton whose shape misses the
+ // real layout reflows when content lands, which reads as slower than
+ // showing nothing.
+ <div className="flex flex-col gap-px">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Skeleton key={i} className="h-[54px] w-full" />
+ ))}
+ </div>
+ ) : owners.length === 0 ? (
+ <EmptyState
+ icon={<Users className="h-6 w-6" />}
+ title="No contributors match"
+ description={
+ filters.q
+ ? "Nothing matches that filter. Clear it to see everyone."
+ : "Contributors land with the first git index."
+ }
+ />
+ ) : (
+ <OwnerTable
+ owners={owners}
+ sort={filters.sort}
+ onSortChange={(sort) => onFiltersChange({ ...filters, sort })}
+ hrefFor={hrefFor}
+ onSelect={hrefFor ? undefined : onSelect}
+ LinkComponent={LinkComponent}
+ />
+ )}
-function Headline({
- label,
- value,
- tone,
-}: {
- label: string;
- value: number;
- tone?: "warn" | "danger";
-}) {
- const color =
- tone === "danger" ? "text-[var(--color-error)]" : tone === "warn" ? "text-[var(--color-warning)]" : "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>
+ <ResultsFooter
+ shown={owners.length}
+ total={total}
+ hasMore={hasMore}
+ loading={isValidating && !isLoading}
+ onLoadMore={onLoadMore}
+ noun="contributor"
+ />
+ </OverviewSection>
</div>
);
}
diff --git a/packages/ui/src/owners/owner-table.tsx b/packages/ui/src/owners/owner-table.tsx
new file mode 100644
index 000000000..327e4813a
--- /dev/null
+++ b/packages/ui/src/owners/owner-table.tsx
@@ -0,0 +1,208 @@
+import * as React from "react";
+import type { OwnerListEntry } from "@repowise-dev/types/owners";
+import { formatRelativeTimeOrNull } from "../lib/format";
+import { OwnerAvatar } from "./owner-avatar";
+
+export type OwnerSortKey =
+ | "files_owned"
+ | "hotspots_owned"
+ | "commit_count_90d"
+ | "dead_code_lines_owned"
+ | "bus_factor_risk_files";
+
+interface Column {
+ key: OwnerSortKey | null;
+ label: string;
+ /** One line explaining what the column counts, on hover. */
+ hint?: string;
+ numeric: boolean;
+}
+
+// Sole-owned files are `bus_factor_risk_files` under a name a person would
+// use. "Bus factor" is jargon that names the metaphor rather than the fact.
+const COLUMNS: Column[] = [
+ { key: "files_owned", label: "Files owned", hint: "Files where this person wrote most of the surviving lines", numeric: true },
+ { key: "hotspots_owned", label: "Hotspots", hint: "Owned files that are also high-churn", numeric: true },
+ { key: "bus_factor_risk_files", label: "Sole owner", hint: "Owned files nobody else has touched", numeric: true },
+ { key: "dead_code_lines_owned", label: "Dead lines", hint: "Unreachable lines still attributed here", numeric: true },
+ { key: "commit_count_90d", label: "Commits 90d", numeric: true },
+ { key: null, label: "Last touched", numeric: false },
+];
+
+export interface OwnerTableProps {
+ owners: OwnerListEntry[];
+ sort: OwnerSortKey;
+ onSortChange?: ((key: OwnerSortKey) => void) | undefined;
+ /** Link target per row. Preferred over `onSelect`: it keeps the table a
+ * server component and gives every row a real URL to middle-click. */
+ hrefFor?: ((owner: OwnerListEntry) => string) | undefined;
+ onSelect?: ((owner: OwnerListEntry) => void) | undefined;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+/**
+ * The contributor directory as hairline rows.
+ *
+ * This replaced a 3-up grid of bordered cards, for three reasons. Cards forced
+ * `truncate` on both the name and the email, so a long name was reported to
+ * the reader as a shorter name — a layout decision presented as missing data.
+ * A grid also makes the one thing people come here to do impossible: compare
+ * two contributors on the same measure, which needs the figures in a column.
+ * And N contributors meant N bordered boxes at identical weight, so nothing
+ * led.
+ *
+ * Colour stays off the counts. A number being large is not the same as a
+ * number being bad, and green/amber/red belong to health bands. Sole
+ * ownership gets a quiet marker instead, and only when it is non-zero: a
+ * badge every row carries says nothing, so a clean column means nothing to
+ * chase.
+ */
+export function OwnerTable({
+ owners,
+ sort,
+ onSortChange,
+ hrefFor,
+ onSelect,
+ LinkComponent,
+}: OwnerTableProps) {
+ const A = LinkComponent ?? "a";
+
+ return (
+ <div className="-mx-[var(--page-pad)] overflow-x-auto px-[var(--page-pad)] sm:mx-0 sm:px-0">
+ <table className="w-full border-collapse text-[13.5px]">
+ <thead>
+ <tr>
+ <th
+ scope="col"
+ className="border-b border-[var(--color-border-default)] pb-2 pr-3 text-left font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"
+ >
+ Contributor
+ </th>
+ {COLUMNS.map((c) => {
+ const active = c.key != null && c.key === sort;
+ const head = (
+ <span title={c.hint} className={c.hint ? "cursor-help" : undefined}>
+ {c.label}
+ </span>
+ );
+ return (
+ <th
+ key={c.label}
+ scope="col"
+ aria-sort={active ? "descending" : undefined}
+ className={`whitespace-nowrap border-b border-[var(--color-border-default)] px-3 pb-2 font-mono text-[10px] font-normal uppercase tracking-[0.12em] ${
+ c.numeric ? "text-right" : "text-left"
+ } ${active ? "text-[var(--color-text-primary)]" : "text-[var(--color-text-tertiary)]"}`}
+ >
+ {c.key && onSortChange ? (
+ <button
+ type="button"
+ onClick={() => onSortChange(c.key as OwnerSortKey)}
+ className="tracking-[0.12em] hover:text-[var(--color-text-primary)]"
+ >
+ {head}
+ {active && <span aria-hidden> ↓</span>}
+ </button>
+ ) : (
+ head
+ )}
+ </th>
+ );
+ })}
+ </tr>
+ </thead>
+ <tbody>
+ {owners.map((o) => {
+ const displayName = o.name || o.email || "unknown";
+ const href = hrefFor?.(o);
+ return (
+ <tr
+ key={o.key}
+ onClick={onSelect ? () => onSelect(o) : undefined}
+ className={`border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] ${
+ onSelect ? "cursor-pointer" : ""
+ }`}
+ >
+ <td className="py-2.5 pr-3 align-top">
+ <span className="flex items-start gap-2.5">
+ <OwnerAvatar name={o.name} email={o.email} size="sm" className="mt-0.5" />
+ <span className="min-w-0">
+ {/* No truncation: if a name needs an ellipsis the
+ layout is wrong, and this column has the room.
+ The anchor sits on the name rather than wrapping the
+ row — a row-sized link means nesting a table inside a
+ cell, which unpicks the column alignment the table
+ exists for. */}
+ {href ? (
+ <A
+ href={href}
+ className="block font-medium text-[var(--color-text-primary)] no-underline hover:text-[var(--color-accent-primary)] [text-wrap:pretty]"
+ >
+ {displayName}
+ </A>
+ ) : (
+ <span className="block font-medium text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {displayName}
+ </span>
+ )}
+ {o.email && o.email !== o.name && (
+ <span className="mt-0.5 block font-mono text-[11.5px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {o.email}
+ </span>
+ )}
+ </span>
+ </span>
+ </td>
+ <Num value={o.files_owned} emphasis />
+ <Num value={o.hotspots_owned} />
+ <Num
+ value={o.bus_factor_risk_files}
+ // Sole ownership alone marks nearly every row on a real
+ // repo, and a badge every row carries says nothing. The
+ // signal is sole ownership held by someone who has stopped
+ // committing: that is knowledge with no second reader and
+ // nobody left to ask.
+ marker={o.bus_factor_risk_files > 0 && o.commit_count_90d === 0}
+ markerTitle="Sole-owned files held by someone inactive for 90 days"
+ />
+ <Num value={o.dead_code_lines_owned} />
+ <Num value={o.commit_count_90d} />
+ <td className="whitespace-nowrap py-2.5 pl-3 align-top text-[var(--color-text-tertiary)]">
+ {formatRelativeTimeOrNull(o.last_commit_at) ?? "—"}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function Num({
+ value,
+ emphasis,
+ marker,
+ markerTitle,
+}: {
+ value: number;
+ emphasis?: boolean;
+ marker?: boolean;
+ markerTitle?: string;
+}) {
+ return (
+ <td
+ className={`whitespace-nowrap px-3 py-2.5 text-right align-top tabular-nums ${
+ emphasis ? "font-semibold text-[var(--color-text-primary)]" : ""
+ }`}
+ >
+ {value > 0 ? value.toLocaleString() : <span className="text-[var(--color-text-tertiary)]">—</span>}
+ {marker && (
+ <span
+ title={markerTitle}
+ className="ml-1.5 inline-block h-[5px] w-[5px] shrink-0 rounded-full bg-[var(--color-warning)] align-middle"
+ />
+ )}
+ </td>
+ );
+}
diff --git a/packages/ui/src/owners/ownership-distribution-bar.tsx b/packages/ui/src/owners/ownership-distribution-bar.tsx
index 9515fd56e..0a7bc66b4 100644
--- a/packages/ui/src/owners/ownership-distribution-bar.tsx
+++ b/packages/ui/src/owners/ownership-distribution-bar.tsx
@@ -1,184 +1,149 @@
-"use client";
-
-import { useMemo } from "react";
-import { ShieldAlert } from "lucide-react";
+import * as React from "react";
import type { OwnerListEntry } from "@repowise-dev/types/owners";
-import { cn } from "../lib/cn";
+import { RAMP_TAIL, rampStep } from "../lib/ramp";
interface OwnershipDistributionBarProps {
owners: OwnerListEntry[];
/** Repo-wide contributor count (may exceed the loaded `owners`). */
totalContributors: number;
onSelect?: (owner: OwnerListEntry) => void;
+ /** Router link for the drill-in; defaults to a plain anchor. */
+ hrefFor?: (owner: OwnerListEntry) => string;
+ LinkComponent?: React.ElementType | undefined;
}
-// Solid categorical fills (Tailwind utilities, not raw hex — gate-safe and
-// theme-consistent). Static literals so the JIT emits them.
-const BAR_PALETTE = [
- "bg-rose-400",
- "bg-amber-400",
- "bg-emerald-400",
- "bg-sky-400",
- "bg-indigo-400",
- "bg-fuchsia-400",
- "bg-orange-400",
- "bg-teal-400",
- "bg-violet-400",
- "bg-cyan-400",
-];
-
-const TOP_N = 10;
-const LEGEND_N = 6;
-
-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 colorFor(key: string): string {
- return BAR_PALETTE[hash(key) % BAR_PALETTE.length] as string;
-}
+// Five ramp steps, then the tail. The old version drew ten segments in ten
+// unrelated hues, which spent the page's entire colour budget on a
+// distinction that carries no information: two contributors being rose and
+// teal tells you nothing about either. Position in the ramp means share, so
+// the bar now reads left to right as "most owned to least".
+const TOP_N = 5;
interface Segment {
- owner: OwnerListEntry;
+ owner: OwnerListEntry | null;
+ label: string;
files: number;
pct: number;
- color: string;
- busRisk: boolean;
+ fill: string;
}
/**
- * Knowledge distribution — a single proportional bar of how owned files spread
- * across the top contributors, with the long tail collapsed into "others". It
- * turns the directory's bus-factor / silo numbers into a shape: a bar dominated
- * by one or two segments is a concentration (knowledge) risk; an even spread is
- * healthy. Segments and legend entries drill into the owner profile.
+ * How owned files spread across contributors, as one proportional bar.
+ *
+ * The point is the shape: a bar dominated by one or two segments is a
+ * concentration risk, an even spread is healthy. Segments and legend entries
+ * drill into the owner profile.
+ *
+ * A server component. It had no state, and the previous `onSelect`-only API
+ * forced every parent to be a client component just to route a click. It now
+ * takes `hrefFor` as well, so a server-rendered page links and only a page
+ * that genuinely needs the callback pays for hydration.
*/
export function OwnershipDistributionBar({
owners,
totalContributors,
onSelect,
+ hrefFor,
+ LinkComponent,
}: OwnershipDistributionBarProps) {
- const { segments, othersFiles, othersCount, totalFiles, top3Pct, busRiskCount } =
- useMemo(() => {
- const sorted = [...owners].sort((a, b) => b.files_owned - a.files_owned);
- const total = sorted.reduce((s, o) => s + o.files_owned, 0) || 1;
- const top = sorted.slice(0, TOP_N);
- const segs: Segment[] = top.map((o) => ({
- owner: o,
- files: o.files_owned,
- pct: (o.files_owned / total) * 100,
- color: colorFor((o.email ?? o.key ?? o.name ?? "?").toLowerCase()),
- busRisk: o.bus_factor_risk_files > 0,
- }));
- const otherFiles = total - top.reduce((s, o) => s + o.files_owned, 0);
- const top3 = sorted.slice(0, 3).reduce((s, o) => s + o.files_owned, 0);
- return {
- segments: segs,
- othersFiles: otherFiles,
- othersCount: Math.max(0, sorted.length - top.length),
- totalFiles: total,
- top3Pct: Math.round((top3 / total) * 100),
- busRiskCount: owners.filter((o) => o.bus_factor_risk_files > 0).length,
- };
- }, [owners]);
+ const sorted = [...owners].sort((a, b) => b.files_owned - a.files_owned);
+ const totalFiles = sorted.reduce((s, o) => s + o.files_owned, 0);
+ if (sorted.length === 0 || totalFiles === 0) return null;
- if (owners.length === 0 || totalFiles === 0) return null;
+ const top = sorted.slice(0, TOP_N);
+ const restFiles = totalFiles - top.reduce((s, o) => s + o.files_owned, 0);
+ const restCount = Math.max(0, totalContributors - top.length);
- return (
- <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 sm:p-5">
- <div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
- Knowledge distribution
- </h3>
- <p className="text-xs text-[var(--color-text-secondary)]">
- Top 3 contributors own{" "}
- <span
- className={cn(
- "font-semibold tabular-nums",
- top3Pct >= 60
- ? "text-[var(--color-error)]"
- : top3Pct >= 40
- ? "text-[var(--color-warning)]"
- : "text-[var(--color-text-primary)]",
- )}
- >
- {top3Pct}%
- </span>{" "}
- of owned files
- {busRiskCount > 0 && (
- <>
- {" · "}
- <span className="inline-flex items-center gap-1 text-[var(--color-error)]">
- <ShieldAlert className="h-3.5 w-3.5" />
- {busRiskCount} carry bus-factor risk
- </span>
- </>
- )}
- </p>
- </div>
+ const segments: Segment[] = top.map((o, i) => ({
+ owner: o,
+ label: o.name || o.email || "unknown",
+ files: o.files_owned,
+ pct: (o.files_owned / totalFiles) * 100,
+ fill: rampStep(i),
+ }));
+ if (restFiles > 0 && restCount > 0) {
+ segments.push({
+ owner: null,
+ label: `${restCount.toLocaleString()} others`,
+ files: restFiles,
+ pct: (restFiles / totalFiles) * 100,
+ fill: RAMP_TAIL,
+ });
+ }
+
+ const A = LinkComponent ?? "a";
- {/* Proportional bar. Tiny segments still get a sliver via min-width. */}
- <div className="flex h-9 w-full overflow-hidden rounded-lg">
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex h-2.5 w-full overflow-hidden rounded-[3px]">
{segments.map((s) => (
- <button
- key={s.owner.key}
- type="button"
- onClick={onSelect ? () => onSelect(s.owner) : undefined}
- className={cn(
- "group relative h-full min-w-[3px] border-r border-[var(--color-bg-surface)] transition-opacity hover:opacity-90 last:border-r-0",
- s.color,
- onSelect ? "cursor-pointer" : "cursor-default",
- )}
- style={{ width: `${s.pct}%` }}
- title={`${s.owner.name || s.owner.email || "unknown"} — ${s.files} files (${s.pct.toFixed(1)}%)${s.busRisk ? " · bus-factor risk" : ""}`}
- aria-label={`${s.owner.name || s.owner.email}: ${s.files} files`}
- >
- {s.busRisk && (
- <span className="absolute inset-x-0 top-0 h-1 bg-[var(--color-error)]" />
- )}
- </button>
- ))}
- {othersFiles > 0 && (
- <div
- className="h-full min-w-[3px] bg-[var(--color-bg-wash)]"
- style={{ width: `${(othersFiles / totalFiles) * 100}%` }}
- title={`${othersCount} other contributors — ${othersFiles} files`}
+ <span
+ key={s.owner?.key ?? "__rest"}
+ className="h-full min-w-[3px] border-r border-[var(--color-bg-root)] last:border-r-0"
+ style={{ width: `${s.pct}%`, background: s.fill }}
+ title={`${s.label}: ${s.files.toLocaleString()} files (${s.pct.toFixed(1)}%)`}
/>
- )}
+ ))}
</div>
- {/* Legend: the loudest few owners, each a drill-in. */}
- <div className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">
- {segments.slice(0, LEGEND_N).map((s) => (
- <button
- key={s.owner.key}
- type="button"
- onClick={onSelect ? () => onSelect(s.owner) : undefined}
- className={cn(
- "flex items-center gap-1.5 text-xs",
- onSelect && "hover:text-[var(--color-text-primary)]",
- )}
- >
- <span className={cn("h-2.5 w-2.5 shrink-0 rounded-[3px]", s.color)} />
- <span className="max-w-[140px] truncate text-[var(--color-text-secondary)]">
- {s.owner.name || s.owner.email || "unknown"}
- </span>
- {s.busRisk && <ShieldAlert className="h-3 w-3 shrink-0 text-[var(--color-error)]" />}
- <span className="tabular-nums text-[var(--color-text-tertiary)]">
- {Math.round(s.pct)}%
- </span>
- </button>
- ))}
- {othersCount > 0 && (
- <span className="flex items-center gap-1.5 text-xs">
- <span className="h-2.5 w-2.5 shrink-0 rounded-[3px] bg-[var(--color-bg-wash)]" />
- <span className="text-[var(--color-text-tertiary)]">
- {othersCount} more
+ {/* Legend. Names wrap rather than truncate — the old one capped each
+ entry at 140px, so a long name was reported to the reader as a
+ shorter name. */}
+ <div className="flex flex-wrap gap-x-5 gap-y-1.5 text-xs">
+ {segments.map((s) => {
+ const body = (
+ <>
+ <span
+ aria-hidden
+ className="mt-[5px] h-2 w-2 shrink-0 rounded-[2px]"
+ style={{ background: s.fill }}
+ />
+ <span className="text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {s.label}
+ </span>
+ <span className="shrink-0 font-mono tabular-nums text-[var(--color-text-tertiary)]">
+ {Math.round(s.pct)}%
+ </span>
+ </>
+ );
+ const cls = "flex items-start gap-1.5 text-left";
+ if (!s.owner) {
+ return (
+ <span key="__rest" className={cls}>
+ {body}
+ </span>
+ );
+ }
+ if (hrefFor) {
+ return (
+ <A
+ key={s.owner.key}
+ href={hrefFor(s.owner)}
+ className={`${cls} no-underline hover:text-[var(--color-text-primary)]`}
+ >
+ {body}
+ </A>
+ );
+ }
+ if (onSelect) {
+ const owner = s.owner;
+ return (
+ <button
+ key={owner.key}
+ type="button"
+ onClick={() => onSelect(owner)}
+ className={`${cls} hover:text-[var(--color-text-primary)]`}
+ >
+ {body}
+ </button>
+ );
+ }
+ return (
+ <span key={s.owner.key} className={cls}>
+ {body}
</span>
- </span>
- )}
+ );
+ })}
</div>
</div>
);
diff --git a/packages/ui/src/shared/page-lede.tsx b/packages/ui/src/shared/page-lede.tsx
new file mode 100644
index 000000000..fe0889d10
--- /dev/null
+++ b/packages/ui/src/shared/page-lede.tsx
@@ -0,0 +1,111 @@
+import * as React from "react";
+
+export interface PageLedeBand {
+ label: string;
+ /** Omit for a neutral chip. Only pass a colour when it carries a band —
+ * a health grade, a risk tercile — never to brighten a plain count. */
+ color?: string | undefined;
+}
+
+export interface PageLedeProps {
+ /** Mono micro-label above the figure. */
+ label: string;
+ /** The figure itself, pre-formatted. */
+ value: string;
+ /** Colour for the figure. Same rule as `band.color`. */
+ valueColor?: string | undefined;
+ /** Trailing unit, quiet and small: "out of 10", "of 5,485 files". */
+ unit?: string | undefined;
+ band?: PageLedeBand | undefined;
+ /** The sentence that makes the figure mean something. Load-bearing. */
+ children: React.ReactNode;
+ /** Optional jump into the page that owns the subject. */
+ action?: React.ReactNode;
+}
+
+/**
+ * The shape a page leads with: one figure large enough to lead, a band chip
+ * where a band exists, and the plain-English sentence that makes the figure
+ * readable.
+ *
+ * Extracted from `HealthLede`, which still composes it — the arrangement was
+ * being copied by every surface that adopted the section style, and three
+ * hand-rolled copies is how the 44 / 48 / 52 sizes drift apart.
+ *
+ * The prose is not decoration. "329 risks" reads as alarming; "329 static
+ * performance risks across 100% of scanned lines, which we rate 9.9 out of
+ * 10" reads as informative. Same number.
+ */
+export function PageLede({
+ label,
+ value,
+ valueColor,
+ unit,
+ band,
+ children,
+ action,
+}: PageLedeProps) {
+ return (
+ <div className="flex flex-col">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {label}
+ </p>
+
+ <div className="mt-2.5 flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <span
+ className="text-[44px] font-semibold leading-none tracking-tight tabular-nums sm:text-5xl"
+ style={valueColor ? { color: valueColor } : undefined}
+ >
+ {value}
+ </span>
+ {unit && <span className="text-xs text-[var(--color-text-tertiary)]">{unit}</span>}
+ {band && (
+ <span
+ className="rounded-full border px-2.5 py-0.5 text-[11px] font-medium"
+ style={
+ band.color
+ ? {
+ color: band.color,
+ borderColor: `color-mix(in srgb, ${band.color} 40%, transparent)`,
+ background: `color-mix(in srgb, ${band.color} 9%, transparent)`,
+ }
+ : {
+ color: "var(--color-text-secondary)",
+ borderColor: "var(--color-border-hover)",
+ }
+ }
+ >
+ {band.label}
+ </span>
+ )}
+ </div>
+
+ <div className="mt-3.5 max-w-[54ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {children}
+ </div>
+
+ {action && <div className="mt-4">{action}</div>}
+ </div>
+ );
+}
+
+/** The standard action under a lede. */
+export function LedeLink({
+ href,
+ children,
+ LinkComponent,
+}: {
+ href: string;
+ children: React.ReactNode;
+ LinkComponent?: React.ElementType | undefined;
+}) {
+ const A = LinkComponent ?? "a";
+ return (
+ <A
+ href={href}
+ className="inline-flex w-fit items-center gap-1 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ {children} <span aria-hidden>→</span>
+ </A>
+ );
+}
diff --git a/packages/ui/src/shared/page-shell.tsx b/packages/ui/src/shared/page-shell.tsx
index 4085cbe62..677482af8 100644
--- a/packages/ui/src/shared/page-shell.tsx
+++ b/packages/ui/src/shared/page-shell.tsx
@@ -42,7 +42,11 @@ export function PageShell({
{title}
</h1>
{description && (
- <p className="text-sm text-[var(--color-text-secondary)]">{description}</p>
+ // Capped at a readable measure. Unbounded, this ran the full
+ // 1280 on a wide viewport, which is roughly 160 characters.
+ <p className="max-w-[68ch] text-sm text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {description}
+ </p>
)}
</div>
{actions && <div className="flex shrink-0 items-center gap-2">{actions}</div>}
diff --git a/packages/ui/src/shared/results-footer.tsx b/packages/ui/src/shared/results-footer.tsx
index 17f43eb49..b7f8fc962 100644
--- a/packages/ui/src/shared/results-footer.tsx
+++ b/packages/ui/src/shared/results-footer.tsx
@@ -40,7 +40,8 @@ export function ResultsFooter({
return (
<div
className={cn(
- "flex items-center justify-between gap-3 border-t border-[var(--color-border)] px-3 py-2 text-xs text-[var(--color-text-secondary)]",
+ // --color-border does not exist; this hairline has never painted.
+ "flex items-center justify-between gap-3 border-t border-[var(--color-border-default)] px-3 py-2 text-xs text-[var(--color-text-secondary)]",
className,
)}
>
diff --git a/packages/ui/src/stats/stat-ribbon.tsx b/packages/ui/src/stats/stat-ribbon.tsx
index ee8c93e0e..a82182d3c 100644
--- a/packages/ui/src/stats/stat-ribbon.tsx
+++ b/packages/ui/src/stats/stat-ribbon.tsx
@@ -27,7 +27,7 @@ export function StatRibbon({
}: {
stats: RibbonStat[];
/** Router link for `href` entries; defaults to a plain anchor. */
- LinkComponent?: React.ElementType;
+ LinkComponent?: React.ElementType | undefined;
}) {
const shown = stats.filter((s) => s.value);
if (shown.length === 0) return null;
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index e543d4a98..9511bc2d4 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -94,6 +94,26 @@
--color-accent-muted: rgba(245, 149, 32, 0.12);
--color-accent-secondary: #58436c;
+ /* Accent ramp — the one sanctioned way to colour a proportion: ordered
+ shares of a whole (a stacked bar, a histogram, an area chart), stepped
+ from the accent toward the page ground. Sequential, so position in the
+ ramp means magnitude; NOT for unrelated categories, which want either the
+ accent/secondary pair or plain neutrals.
+
+ Defined per theme rather than as one set of color-mix percentages,
+ because the mix that recedes gracefully into near-black disappears
+ entirely into cream. Light also starts a step down from full #f59520,
+ which is louder than it needs to be on a warm paper ground. */
+ --color-ramp-1: #e08a12;
+ --color-ramp-2: color-mix(in srgb, var(--color-accent-fill) 76%, var(--color-bg-inset));
+ --color-ramp-3: color-mix(in srgb, var(--color-accent-fill) 56%, var(--color-bg-inset));
+ --color-ramp-4: color-mix(in srgb, var(--color-accent-fill) 40%, var(--color-bg-inset));
+ --color-ramp-5: color-mix(in srgb, var(--color-accent-fill) 26%, var(--color-bg-inset));
+ /* Supporting cast beside an accent series. Same idea, no hue. */
+ --color-neutral-1: color-mix(in srgb, var(--color-text-tertiary) 62%, var(--color-bg-inset));
+ --color-neutral-2: color-mix(in srgb, var(--color-text-tertiary) 40%, var(--color-bg-inset));
+ --color-neutral-3: color-mix(in srgb, var(--color-text-tertiary) 22%, var(--color-bg-inset));
+
/* Confidence system */
--color-confidence-fresh: #1d8155;
--color-confidence-stale: #9a6614;
@@ -377,6 +397,17 @@
--color-accent-muted: rgba(245, 149, 32, 0.16);
--color-accent-secondary: #a98fc4;
+ /* Accent ramp — see the light block. Steeper here: mixing toward #0a0a0b
+ loses luminance fast, so the same percentages would bottom out invisible. */
+ --color-ramp-1: #f59520;
+ --color-ramp-2: color-mix(in srgb, var(--color-accent-fill) 64%, var(--color-bg-inset));
+ --color-ramp-3: color-mix(in srgb, var(--color-accent-fill) 42%, var(--color-bg-inset));
+ --color-ramp-4: color-mix(in srgb, var(--color-accent-fill) 27%, var(--color-bg-inset));
+ --color-ramp-5: color-mix(in srgb, var(--color-accent-fill) 16%, var(--color-bg-inset));
+ --color-neutral-1: color-mix(in srgb, var(--color-text-tertiary) 70%, var(--color-bg-inset));
+ --color-neutral-2: color-mix(in srgb, var(--color-text-tertiary) 45%, var(--color-bg-inset));
+ --color-neutral-3: color-mix(in srgb, var(--color-text-tertiary) 26%, var(--color-bg-inset));
+
--color-confidence-fresh: #34d399;
--color-confidence-stale: #f2a03d;
--color-confidence-outdated: #e06a5a;
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
index d97a74829..c7994338f 100644
--- a/packages/web/src/app/repos/[id]/commits/page.tsx
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -1,25 +1,128 @@
import type { Metadata } from "next";
+import Link from "next/link";
import { GitCommitHorizontal } from "lucide-react";
import { PageShell } from "@repowise-dev/ui/shared/page-shell";
-import { CommitsExplorer } from "@/components/commits/commits-explorer";
+import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
+import { CommitsLede } from "@repowise-dev/ui/commits/commits-lede";
+import { CodeEvolutionChart } from "@repowise-dev/ui/commits/code-evolution-chart";
+import { AgentTrendStrip } from "@repowise-dev/ui/commits/agent-trend-strip";
+import { CredibilityInfoButton } from "@repowise-dev/ui/commits/credibility-strip";
+import { CommitQueue } from "@/components/commits/commit-queue";
+import { CommitDetailSheet } from "@/components/commits/commit-detail-sheet";
+import { CommitDistribution } from "@/components/commits/commit-distribution";
+import {
+ getAgentTrend,
+ getCommitEvolution,
+ getCommitStats,
+ getCommitsPage,
+} from "@/lib/api/git";
export const metadata: Metadata = { title: "Commits" };
+const PAGE_SIZE = 50;
+// The scatter's own window. Capped at the endpoint's `limit` ceiling; a few
+// hundred dots is also about where the plot stops being readable.
+const SCATTER_SAMPLE = 200;
+
+async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
+ try {
+ return await fn();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * A server component, where this used to be one client component with five SWR
+ * waves behind it. Nothing above the queue needs client state, so every figure
+ * and both charts now arrive in the initial HTML instead of waterfalling in
+ * after paint. What stays interactive is three small islands, each hydrating
+ * only itself and sharing the selected commit through `?commit=` rather than
+ * through a common client parent.
+ *
+ * Order is deliberate. The queue is what people come here for, so it sits
+ * above the analysis charts rather than below them; the evolution chart keeps
+ * the top slot because it is the only one about the repo rather than about the
+ * scoring model.
+ */
export default async function CommitsPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
+ const base = `/repos/${id}`;
+
+ // One wave. The scatter plots its own recency sample rather than reusing the
+ // queue's first page: the feed is risk-sorted, so reusing it would draw only
+ // the top tercile and the "here is the whole spread" reading would be a lie.
+ const [stats, evolution, trend, firstPage, recent] = await Promise.all([
+ safeFetch(() => getCommitStats(id)),
+ safeFetch(() => getCommitEvolution(id)),
+ safeFetch(() => getAgentTrend(id)),
+ safeFetch(() =>
+ getCommitsPage(id, { sort: "risk", authorship: "all", limit: PAGE_SIZE }),
+ ),
+ safeFetch(() => getCommitsPage(id, { sort: "date", limit: SCATTER_SAMPLE })),
+ ]);
+
+ const total = stats?.total_commits ?? firstPage?.total ?? 0;
+
+ if (!firstPage || total === 0) {
+ return (
+ <PageShell
+ icon={<GitCommitHorizontal className="h-5 w-5 text-[var(--color-accent-primary)]" />}
+ title="Commits"
+ description="Every commit scored for change-risk against this repo's own history."
+ >
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ Per-commit change-risk is captured on the next full index. Run a sync and
+ the review queue fills in behind it.
+ </p>
+ </PageShell>
+ );
+ }
return (
<PageShell
- maxWidth="wide"
icon={<GitCommitHorizontal className="h-5 w-5 text-[var(--color-accent-primary)]" />}
title="Commits"
- description="A review-priority queue — every indexed commit scored for change-risk and ranked relative to this repo's own history. Open a commit for its per-feature breakdown."
+ description="Every commit scored for change-risk against this repo's own history, so 'elevated' means elevated here rather than on some global curve."
>
- <CommitsExplorer repoId={id} />
+ {stats && <CommitsLede stats={stats} base={base} LinkComponent={Link} />}
+
+ {evolution && evolution.total_commits > 0 && (
+ <OverviewSection
+ title="How the work changed shape"
+ description="Commit categories over time, read off the subject line. Fixes carry the accent because that is the series this chart exists to show."
+ >
+ <CodeEvolutionChart evolution={evolution} />
+ </OverviewSection>
+ )}
+
+ {trend && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
+
+ <OverviewSection
+ title="Review-priority queue"
+ description="Ranked by change-risk, highest first. Priority is a tercile of this repo's own distribution, so a quiet repo still fills its top band."
+ action={<CredibilityInfoButton />}
+ >
+ <CommitQueue repoId={id} initial={firstPage} total={total} />
+ </OverviewSection>
+
+ <OverviewSection
+ title="How the score behaves here"
+ description="Two views of the same model: where the cuts fall, and what commit shape lands you above them."
+ action={
+ <SectionLink href={`${base}/risk`} LinkComponent={Link}>
+ Change risk
+ </SectionLink>
+ }
+ >
+ <CommitDistribution stats={stats} recent={recent?.items ?? []} />
+ </OverviewSection>
+
+ <CommitDetailSheet repoId={id} />
</PageShell>
);
}
diff --git a/packages/web/src/app/repos/[id]/owners/page.tsx b/packages/web/src/app/repos/[id]/owners/page.tsx
index f9cff1ece..60cf33b2c 100644
--- a/packages/web/src/app/repos/[id]/owners/page.tsx
+++ b/packages/web/src/app/repos/[id]/owners/page.tsx
@@ -1,6 +1,7 @@
"use client";
import { useMemo, useState } from "react";
+import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import useSWR from "swr";
import useSWRInfinite from "swr/infinite";
@@ -73,10 +74,9 @@ export default function OwnersDirectoryPage() {
return (
<PageShell
- maxWidth="wide"
icon={<Users className="h-5 w-5 text-[var(--color-accent-primary)]" />}
title="Contributors"
- description="Who is doing what — ownership, hotspots, dead-code burden, and bus-factor risk per person. Click any card to open the full profile."
+ description="Who knows what, mined from full git history. Ownership follows whoever wrote the surviving lines, not whoever committed last."
>
<OwnerDirectory
owners={items}
@@ -88,6 +88,9 @@ export default function OwnersDirectoryPage() {
filters={filters}
onFiltersChange={setFilters}
onLoadMore={() => setSize(size + 1)}
+ base={`/repos/${id}`}
+ hrefFor={(o) => `/repos/${id}/owners/${encodeURIComponent(o.key)}`}
+ LinkComponent={Link}
onSelect={(o) =>
router.push(`/repos/${id}/owners/${encodeURIComponent(o.key)}`)
}
diff --git a/packages/web/src/components/commits/commit-detail-sheet.tsx b/packages/web/src/components/commits/commit-detail-sheet.tsx
new file mode 100644
index 000000000..c7f3e46bb
--- /dev/null
+++ b/packages/web/src/components/commits/commit-detail-sheet.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { useQueryState } from "nuqs";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@repowise-dev/ui/ui/sheet";
+import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";
+import { AiPromptButton, AiPromptModal, buildCommitAiPrompt } from "@repowise-dev/ui/health";
+import { getCommit } from "@/lib/api/git";
+
+/**
+ * The commit detail drawer, driven entirely by `?commit=`.
+ *
+ * Its own island so the queue and the scatter can both open it without a
+ * shared client parent: they write the query param, this reads it. That is
+ * also what makes the deep link work — entity links from Overview and the file
+ * pages land here with the sheet already open, and it survives a refresh.
+ */
+export function CommitDetailSheet({ repoId }: { repoId: string }) {
+ const [selectedSha, setSelectedSha] = useQueryState("commit");
+ const [promptOpen, setPromptOpen] = useState(false);
+
+ const { data: detail, isLoading } = useSWR(
+ selectedSha ? `commit:${repoId}:${selectedSha}` : null,
+ () => getCommit(repoId, selectedSha as string),
+ { revalidateOnFocus: false },
+ );
+
+ return (
+ <>
+ <Sheet
+ open={selectedSha !== null}
+ onOpenChange={(open) => !open && void setSelectedSha(null)}
+ >
+ <SheetContent side="right" className="w-[440px] max-w-[92vw] sm:w-[560px]">
+ <SheetHeader>
+ <SheetTitle>Commit change-risk</SheetTitle>
+ </SheetHeader>
+ <div className="flex-1 overflow-y-auto px-4 pb-6">
+ {isLoading || !detail ? (
+ <div className="space-y-3 pt-2">
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-40 w-full" />
+ </div>
+ ) : (
+ <>
+ <div className="flex justify-end pt-1 pb-3">
+ <AiPromptButton
+ label="AI review prompt"
+ onClick={() => setPromptOpen(true)}
+ />
+ </div>
+ <CommitDetailCard commit={detail} />
+ </>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={
+ detail
+ ? (flavor) =>
+ buildCommitAiPrompt({
+ commit: {
+ sha: detail.sha,
+ subject: detail.subject,
+ review_priority: detail.review_priority,
+ risk_percentile: detail.risk_percentile,
+ change_risk_score: detail.change_risk_score,
+ is_fix: detail.is_fix,
+ files_changed: detail.files_changed,
+ lines_added: detail.lines_added,
+ lines_deleted: detail.lines_deleted,
+ entropy: detail.entropy,
+ top_drivers: detail.drivers
+ .filter((d) => d.contribution > 0)
+ .map((d) => d.label),
+ author_name: detail.author_name,
+ },
+ flavor,
+ })
+ : null
+ }
+ filePath={detail ? detail.short_sha : null}
+ title="AI commit review"
+ description="A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers."
+ />
+ </>
+ );
+}
diff --git a/packages/web/src/components/commits/commit-distribution.tsx b/packages/web/src/components/commits/commit-distribution.tsx
new file mode 100644
index 000000000..95f662267
--- /dev/null
+++ b/packages/web/src/components/commits/commit-distribution.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { useQueryState } from "nuqs";
+import type { CommitResponse, CommitStats } from "@/lib/api/types";
+import { CommitRiskHistogram } from "@repowise-dev/ui/commits/commit-risk-histogram";
+import { CommitRiskScatter } from "@repowise-dev/ui/commits/commit-risk-scatter";
+
+/**
+ * The two views of how the score behaves here.
+ *
+ * They stay a pair. The histogram says where the tercile cuts fall, the
+ * scatter says what commit shape lands you above them, and neither answers the
+ * question alone — showing one leaves a half-width chart beside dead space,
+ * which is the empty state the old collapsible produced whenever a repo
+ * predated the histogram aggregate.
+ *
+ * A client island only because both charts hover, and because clicking a dot
+ * writes `?commit=` for the detail sheet to pick up.
+ */
+export function CommitDistribution({
+ stats,
+ recent,
+}: {
+ stats: CommitStats | null;
+ recent: CommitResponse[];
+}) {
+ const [, setSelectedSha] = useQueryState("commit");
+
+ const hasHistogram = (stats?.risk_histogram?.length ?? 0) > 0;
+ if (!hasHistogram || !stats || recent.length === 0) return null;
+
+ return (
+ <div className="grid grid-cols-1 gap-7 lg:grid-cols-2 lg:gap-10">
+ <div className="flex flex-col gap-2">
+ <h3 className="text-[13px] font-semibold text-[var(--color-text-primary)]">
+ Score distribution
+ </h3>
+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ Every scored commit, binned on the raw 0 to 10 score rather than the
+ percentile. Percentile ranks are uniform by construction, so that axis
+ has no shape to draw. The dashed lines are the tercile cuts behind each
+ row&apos;s priority pill.
+ </p>
+ <CommitRiskHistogram stats={stats} />
+ </div>
+ <div className="flex flex-col gap-2">
+ <h3 className="text-[13px] font-semibold text-[var(--color-text-primary)]">
+ Size against diffusion
+ </h3>
+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ The {recent.length.toLocaleString()} most recent commits, on their own
+ recency sample rather than the feed above: that defaults to risk-sorted,
+ so reusing it would plot only the top tercile and call it the spread.
+ Big and scattered is what the model penalises. Click a dot to open it.
+ </p>
+ <CommitRiskScatter
+ commits={recent}
+ onSelect={(sha) => void setSelectedSha(sha)}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/commits/commit-queue.tsx b/packages/web/src/components/commits/commit-queue.tsx
new file mode 100644
index 000000000..94a0e799e
--- /dev/null
+++ b/packages/web/src/components/commits/commit-queue.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { useQueryState } from "nuqs";
+import {
+ CommitTable,
+ type CommitAuthorship,
+ type CommitSort,
+} from "@repowise-dev/ui/commits/commit-table";
+import { getCommitsPage } from "@/lib/api/git";
+import type { CommitResponse, Paginated } from "@/lib/api/types";
+
+const PAGE_SIZE = 50;
+const MAX_ROWS = 200;
+
+/**
+ * The review queue: the one part of this page that genuinely needs client
+ * state. Sort, authorship filter and paging all refetch, and selecting a row
+ * writes `?commit=` so the detail sheet can be a separate island that shares
+ * state through the URL rather than through a common parent — which is what
+ * kept the whole page a client component before.
+ *
+ * The first page is server-rendered and handed in as `initial`, so the table
+ * is in the initial HTML and SWR only takes over once the reader changes
+ * something.
+ */
+export function CommitQueue({
+ repoId,
+ initial,
+ total,
+}: {
+ repoId: string;
+ initial: Paginated<CommitResponse>;
+ total: number;
+}) {
+ const [sort, setSort] = useState<CommitSort>("risk");
+ const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
+ const [limit, setLimit] = useState(PAGE_SIZE);
+ const [, setSelectedSha] = useQueryState("commit");
+
+ const pristine = sort === "risk" && authorship === "all" && limit === PAGE_SIZE;
+
+ const { data, isLoading, isValidating } = useSWR<Paginated<CommitResponse>>(
+ `commits:${repoId}:${sort}:${authorship}:${limit}`,
+ () => getCommitsPage(repoId, { sort, authorship, limit }),
+ {
+ revalidateOnFocus: false,
+ keepPreviousData: true,
+ // Nothing to fetch until the reader moves off the server-rendered view.
+ fallbackData: pristine ? initial : undefined,
+ revalidateOnMount: !pristine,
+ },
+ );
+
+ const list = data?.items ?? initial.items;
+
+ return (
+ <CommitTable
+ commits={list}
+ sort={sort}
+ onSortChange={(s) => {
+ setSort(s);
+ setLimit(PAGE_SIZE);
+ }}
+ authorship={authorship}
+ onAuthorshipChange={(a) => {
+ setAuthorship(a);
+ setLimit(PAGE_SIZE);
+ }}
+ onSelect={(c) => void setSelectedSha(c.sha)}
+ total={total}
+ hasMore={data?.has_more ?? initial.has_more}
+ loadingMore={isValidating && !isLoading}
+ onLoadMore={() => setLimit((n) => Math.min(n + PAGE_SIZE, MAX_ROWS))}
+ />
+ );
+}
diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsx
deleted file mode 100644
index cf691c75c..000000000
--- a/packages/web/src/components/commits/commits-explorer.tsx
+++ /dev/null
@@ -1,294 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import useSWR from "swr";
-import { useQueryState } from "nuqs";
-import { AlertTriangle, Bug, GitCommitHorizontal } from "lucide-react";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@repowise-dev/ui/ui/sheet";
-import {
- CommitTable,
- type CommitAuthorship,
- type CommitSort,
-} from "@repowise-dev/ui/commits/commit-table";
-import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";
-import { AiPromptButton, AiPromptModal, buildCommitAiPrompt } from "@repowise-dev/ui/health";
-import { CredibilityInfoButton } from "@repowise-dev/ui/commits/credibility-strip";
-import { CodeEvolutionChart } from "@repowise-dev/ui/commits/code-evolution-chart";
-import { AgentTrendStrip } from "@repowise-dev/ui/commits/agent-trend-strip";
-import { CommitRiskHistogram } from "@repowise-dev/ui/commits/commit-risk-histogram";
-import { CommitRiskScatter } from "@repowise-dev/ui/commits/commit-risk-scatter";
-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
-import {
- getAgentTrend,
- getCommit,
- getCommitEvolution,
- getCommitStats,
- getCommitsPage,
-} from "@/lib/api/git";
-import type { CommitResponse, Paginated } from "@/lib/api/types";
-
-const PAGE_SIZE = 50;
-// The scatter's own window. Capped at the endpoint's `limit` ceiling; a few
-// hundred dots is also about where the plot stops being readable.
-const SCATTER_SAMPLE = 200;
-
-export function CommitsExplorer({ repoId }: { repoId: string }) {
- const [sort, setSort] = useState<CommitSort>("risk");
- const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
- const [limit, setLimit] = useState(PAGE_SIZE);
- // ?commit= deep link — entity links from Overview/file pages land here with
- // the detail sheet already open, and the sheet state survives refresh.
- const [selectedSha, setSelectedSha] = useQueryState("commit");
- const [promptOpen, setPromptOpen] = useState(false);
-
- const { data, isLoading, isValidating, error } = useSWR<Paginated<CommitResponse>>(
- `commits:${repoId}:${sort}:${authorship}:${limit}`,
- () => getCommitsPage(repoId, { sort, authorship, limit }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- const { data: trend } = useSWR(
- `agent-trend:${repoId}`,
- () => getAgentTrend(repoId),
- { revalidateOnFocus: false },
- );
-
- // Headline: the repo's development "story arc" — commit-category mix over time.
- const { data: evolution } = useSWR(
- `commit-evolution:${repoId}`,
- () => getCommitEvolution(repoId),
- { revalidateOnFocus: false },
- );
-
- // Repo-wide stat-card aggregates. Computed server-side over ALL commits — the
- // loaded page is only a window (and, when risk-sorted, entirely top-tercile),
- // so reducing `list` here would under-count fixes and inflate high-priority.
- const { data: stats } = useSWR(
- `commit-stats:${repoId}`,
- () => getCommitStats(repoId),
- { revalidateOnFocus: false },
- );
-
- // The scatter plots its own recency sample rather than `list`: the feed
- // defaults to risk-sorted, so reusing it would draw only the top tercile and
- // the "here's the whole spread" reading would be a lie.
- const { data: recent } = useSWR(
- `commits-recent:${repoId}`,
- () => getCommitsPage(repoId, { sort: "date", limit: SCATTER_SAMPLE }),
- { revalidateOnFocus: false },
- );
-
- const { data: detail, isLoading: detailLoading } = useSWR(
- selectedSha ? `commit:${repoId}:${selectedSha}` : null,
- () => getCommit(repoId, selectedSha as string),
- { revalidateOnFocus: false },
- );
-
- const list = data?.items ?? [];
- const total = stats?.total_commits ?? data?.total ?? list.length;
- const hasMore = data?.has_more ?? false;
- const recentCommits = recent?.items ?? [];
- // Older indexes predate the histogram aggregate, so treat it as optional.
- const hasHistogram = (stats?.risk_histogram?.length ?? 0) > 0;
-
- // Prefer the repo-wide aggregates; fall back to the loaded page only until
- // the stats request resolves so the cards aren't blank on first paint.
- const highCount =
- stats?.high_priority_count ?? list.filter((c) => c.review_priority === "high").length;
- const fixCount = stats?.fix_commit_count ?? list.filter((c) => c.is_fix).length;
- const avgEntropy =
- stats?.avg_entropy ??
- (list.length > 0
- ? list.reduce((s, c) => s + (c.entropy || 0), 0) / list.length
- : 0);
-
- if (isLoading && list.length === 0) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-20 w-full" />
- <Skeleton className="h-96 w-full" />
- </div>
- );
- }
-
- if (error && list.length === 0) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">
- Couldn&apos;t load commits. Per-commit change-risk is captured on the next full index —
- try running a sync first.
- </div>
- );
- }
-
- return (
- <div className="space-y-6">
- {evolution && evolution.total_commits > 0 && (
- <CodeEvolutionChart evolution={evolution} />
- )}
-
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
- <MetricCard
- label="Commits"
- value={total}
- description="with change-risk"
- icon={<GitCommitHorizontal className="h-4 w-4 text-[var(--color-text-tertiary)]" />}
- />
- <MetricCard
- label="High priority"
- value={highCount}
- description="top risk tercile"
- icon={<AlertTriangle className="h-4 w-4 text-[var(--color-error)]" />}
- />
- <MetricCard
- label="Fix commits"
- value={fixCount}
- description="bug-fix subjects"
- icon={<Bug className="h-4 w-4 text-[var(--color-warning)]" />}
- />
- <MetricCard
- label="Avg entropy"
- value={avgEntropy.toFixed(2)}
- description="change diffusion"
- />
- </div>
-
- {/* Secondary signals — smaller than the headline. Both panels are about
- commits (the page's subject); the file-level hotspot view lives on the
- Risk tab, where it isn't a duplicate. Collapsible because this is a
- demoted detail; the agent-trend strip is a thin band beneath it. */}
- {(hasHistogram || recentCommits.length > 0) && (
- <CollapsibleSection
- title="How risky is a typical commit here?"
- hint={`${total.toLocaleString()} scored`}
- defaultOpen
- >
- <div className="grid gap-3 lg:grid-cols-2">
- {hasHistogram && stats && (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <h4 className="text-xs font-medium text-[var(--color-text-secondary)]">
- Score distribution
- </h4>
- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
- Every scored commit in the repo. The dashed lines are the
- tercile cuts behind each row&apos;s priority pill.
- </p>
- <CommitRiskHistogram stats={stats} />
- </div>
- )}
- {recentCommits.length > 0 && (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <h4 className="text-xs font-medium text-[var(--color-text-secondary)]">
- Size vs diffusion
- </h4>
- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
- The {recentCommits.length.toLocaleString()} most recent
- commits. Big and scattered is what the model penalises — click
- a dot to open it.
- </p>
- <CommitRiskScatter
- commits={recentCommits}
- onSelect={(sha) => void setSelectedSha(sha)}
- />
- </div>
- )}
- </div>
- </CollapsibleSection>
- )}
- {trend && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
-
- <div className="space-y-2">
- <div className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- <span>Review-priority queue</span>
- <CredibilityInfoButton />
- </div>
-
- <CommitTable
- commits={list}
- sort={sort}
- onSortChange={(s) => {
- setSort(s);
- setLimit(PAGE_SIZE);
- }}
- authorship={authorship}
- onAuthorshipChange={(a) => {
- setAuthorship(a);
- setLimit(PAGE_SIZE);
- }}
- onSelect={(c) => void setSelectedSha(c.sha)}
- total={total}
- hasMore={hasMore}
- loadingMore={isValidating && !isLoading}
- onLoadMore={() => setLimit((n) => Math.min(n + PAGE_SIZE, 200))}
- />
- </div>
-
- <Sheet
- open={selectedSha !== null}
- onOpenChange={(open) => !open && void setSelectedSha(null)}
- >
- <SheetContent side="right" className="w-[440px] max-w-[92vw] sm:w-[560px]">
- <SheetHeader>
- <SheetTitle>Commit change-risk</SheetTitle>
- </SheetHeader>
- <div className="flex-1 overflow-y-auto px-4 pb-6">
- {detailLoading || !detail ? (
- <div className="space-y-3 pt-2">
- <Skeleton className="h-24 w-full" />
- <Skeleton className="h-40 w-full" />
- </div>
- ) : (
- <>
- <div className="flex justify-end pt-1 pb-3">
- <AiPromptButton
- label="AI review prompt"
- onClick={() => setPromptOpen(true)}
- />
- </div>
- <CommitDetailCard commit={detail} />
- </>
- )}
- </div>
- </SheetContent>
- </Sheet>
-
- <AiPromptModal
- open={promptOpen}
- onOpenChange={setPromptOpen}
- getPrompt={
- detail
- ? (flavor) =>
- buildCommitAiPrompt({
- commit: {
- sha: detail.sha,
- subject: detail.subject,
- review_priority: detail.review_priority,
- risk_percentile: detail.risk_percentile,
- change_risk_score: detail.change_risk_score,
- is_fix: detail.is_fix,
- files_changed: detail.files_changed,
- lines_added: detail.lines_added,
- lines_deleted: detail.lines_deleted,
- entropy: detail.entropy,
- top_drivers: detail.drivers
- .filter((d) => d.contribution > 0)
- .map((d) => d.label),
- author_name: detail.author_name,
- },
- flavor,
- })
- : null
- }
- filePath={detail ? detail.short_sha : null}
- title="AI commit review"
- description="A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers."
- />
- </div>
- );
-}