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(commits): replace the file-risk bars with commit-level distribution views (#950)

Raghav Chamadiya7155b5fabac5
diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.ts
index 65fd05b51..e53c9b19e 100644
--- a/packages/api-client/src/types/git.ts
+++ b/packages/api-client/src/types/git.ts
@@ -179,6 +179,15 @@ export interface CommitEvolution {
last_commit_at: string | null;
}
+/** One bin of the repo's raw change-risk score distribution. */
+export interface RiskHistogramBucket {
+ /** Bin lower bound on the 0-10 raw score axis (inclusive). */
+ start: number;
+ /** Bin upper bound (exclusive, except the final bin). */
+ end: number;
+ count: number;
+}
+
/** Repo-wide commit aggregates (computed over all commits, not the loaded page). */
export interface CommitStats {
total_commits: number;
@@ -186,4 +195,11 @@ export interface CommitStats {
fix_commit_count: number;
agent_commit_count: number;
avg_entropy: number;
+ /** Binned on the raw score, not the percentile — percentile ranks are
+ * uniform by construction, so only the raw axis has a shape to draw. */
+ risk_histogram?: RiskHistogramBucket[];
+ /** Raw score at the low/moderate tercile boundary. */
+ moderate_cut?: number | null;
+ /** Raw score at the moderate/high boundary — the review-priority line. */
+ high_cut?: number | null;
}
diff --git a/packages/core/src/repowise/core/analysis/change_risk/normalize.py b/packages/core/src/repowise/core/analysis/change_risk/normalize.py
index 1d53e89eb..c841c5a1b 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/normalize.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/normalize.py
@@ -68,6 +68,45 @@ class RiskNormalizer:
equal = bisect_right(self.scores, score) - below
return 100.0 * (below + 0.5 * equal) / n
+ def cut(self, pct: float) -> float | None:
+ """Lowest score whose percentile reaches *pct*, or ``None`` if none does.
+
+ The inverse of :meth:`percentile` — lets a display surface draw the
+ tercile boundaries on the *raw score* axis, where the distribution has
+ shape (percentile ranks are uniform by construction, so a histogram of
+ them says nothing).
+
+ Defined by searching the scores rather than indexing at ``n * pct``, so
+ ``priority(cut(p))`` is exactly the band at ``p``. Mid-rank percentiles
+ pull tied runs *below* their positional index, and a chart that colours
+ bins by comparing against the cut would otherwise disagree with the
+ per-commit priority on the boundary bin.
+
+ ``None`` when no score reaches *pct* — a fully tied repo has no
+ elevated band, and the caller should draw no line rather than a
+ misleading one.
+ """
+ lo, hi = 0, len(self.scores) - 1
+ found: float | None = None
+ while lo <= hi: # percentile is monotone in score, so binary search
+ mid = (lo + hi) // 2
+ if self.percentile(self.scores[mid]) >= pct:
+ found = self.scores[mid]
+ hi = mid - 1
+ else:
+ lo = mid + 1
+ return found
+
+ @property
+ def moderate_cut(self) -> float | None:
+ """Score at the low/moderate boundary."""
+ return self.cut(_MODERATE_PCT)
+
+ @property
+ def high_cut(self) -> float | None:
+ """Score at the moderate/high boundary — the review-priority line."""
+ return self.cut(_HIGH_PCT)
+
def priority(self, score: float | None) -> str:
"""Repo-relative review priority: ``high`` | ``moderate`` | ``low``.
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index a98f9fb41..9b930a9c0 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -44,6 +44,7 @@ from repowise.server.schemas import (
Paginated,
ReviewerSuggestionsResponse,
RiskDriverResponse,
+ RiskHistogramBucket,
RiskRangeResponse,
)
from repowise.server.services.reviewer_suggestions import suggest_reviewers
@@ -308,9 +309,35 @@ async def get_commit_stats(
fix_commit_count=int(fix_count or 0),
agent_commit_count=int(agent_count or 0),
avg_entropy=float(avg_entropy or 0.0),
+ risk_histogram=_risk_histogram(normalizer.scores),
+ moderate_cut=normalizer.moderate_cut,
+ high_cut=normalizer.high_cut,
)
+_HISTOGRAM_BINS = 20 # 0.5-wide bins across the 0-10 raw change-risk score
+
+
+def _risk_histogram(sorted_scores: list[float]) -> list[RiskHistogramBucket]:
+ """Bin the repo's raw change-risk scores for the distribution chart.
+
+ Reuses the score list already fetched for the normalizer, so this costs no
+ extra query. The top bin is closed on the right so a perfect 10.0 lands
+ somewhere instead of falling off the end.
+ """
+ if not sorted_scores:
+ return []
+ width = 10.0 / _HISTOGRAM_BINS
+ counts = [0] * _HISTOGRAM_BINS
+ for s in sorted_scores:
+ idx = min(_HISTOGRAM_BINS - 1, max(0, int(s / width)))
+ counts[idx] += 1
+ return [
+ RiskHistogramBucket(start=i * width, end=(i + 1) * width, count=c)
+ for i, c in enumerate(counts)
+ ]
+
+
@router.get("/{repo_id}/commits/evolution", response_model=CommitEvolutionResponse)
async def get_commit_evolution(
repo_id: str,
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index fd95474a6..84918b552 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -82,6 +82,7 @@ from .git import (
HotspotResponse,
OwnershipEntry,
RiskDriverResponse,
+ RiskHistogramBucket,
RiskRangeResponse,
)
from .graph import (
@@ -323,6 +324,7 @@ __all__ = [
"ReviewerSuggestion",
"ReviewerSuggestionsResponse",
"RiskDriverResponse",
+ "RiskHistogramBucket",
"RiskRangeResponse",
"SearchRequest",
"SearchResultResponse",
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 7d55690a0..e1d240a25 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -295,6 +295,14 @@ class RiskRangeResponse(BaseModel):
drivers: list[RiskDriverResponse]
+class RiskHistogramBucket(BaseModel):
+ """One bin of the repo's raw change-risk score distribution."""
+
+ start: float # bin lower bound on the 0-10 raw score axis (inclusive)
+ end: float # bin upper bound (exclusive, except the final bin)
+ count: int # commits whose stored score falls in the bin
+
+
class CommitStatsResponse(BaseModel):
"""Repo-wide commit aggregates for the commits-page headline stat cards.
@@ -309,3 +317,10 @@ class CommitStatsResponse(BaseModel):
fix_commit_count: int # subjects classified as bug-fixes
agent_commit_count: int # agent-attributed commits
avg_entropy: float # mean change-diffusion across all commits
+
+ # The distribution behind the tercile banding. Binned on the *raw* score
+ # rather than the percentile, because percentile ranks are uniform by
+ # construction — only the raw axis has a shape worth drawing.
+ risk_histogram: list[RiskHistogramBucket] = []
+ moderate_cut: float | None = None # raw score at the low/moderate boundary
+ high_cut: float | None = None # raw score at the moderate/high boundary
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 53ce0dfc2..6cceb55d2 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -216,6 +216,15 @@ export interface CommitEvolution {
last_commit_at: string | null;
}
+/** One bin of the repo's raw change-risk score distribution. */
+export interface RiskHistogramBucket {
+ /** Bin lower bound on the 0-10 raw score axis (inclusive). */
+ start: number;
+ /** Bin upper bound (exclusive, except the final bin). */
+ end: number;
+ count: number;
+}
+
/** Repo-wide commit aggregates (over all commits, not the loaded page). */
export interface CommitStats {
total_commits: number;
@@ -223,6 +232,13 @@ export interface CommitStats {
fix_commit_count: number;
agent_commit_count: number;
avg_entropy: number;
+ /** Binned on the raw score, not the percentile — percentile ranks are
+ * uniform by construction, so only the raw axis has a shape to draw. */
+ risk_histogram?: RiskHistogramBucket[];
+ /** Raw score at the low/moderate tercile boundary. */
+ moderate_cut?: number | null;
+ /** Raw score at the moderate/high boundary — the review-priority line. */
+ high_cut?: number | null;
}
export interface OwnershipEntry {
diff --git a/packages/ui/src/commits/commit-risk-histogram.tsx b/packages/ui/src/commits/commit-risk-histogram.tsx
new file mode 100644
index 000000000..786a635af
--- /dev/null
+++ b/packages/ui/src/commits/commit-risk-histogram.tsx
@@ -0,0 +1,242 @@
+"use client";
+
+import * as React from "react";
+import type { CommitStats, ReviewPriority } from "@repowise-dev/types/git";
+import { cn } from "../lib/cn";
+
+/**
+ * The distribution behind the review-priority terciles: how this repo's raw
+ * change-risk scores are actually spread, with the low/typical and
+ * typical/elevated cut lines drawn on top.
+ *
+ * Binned on the **raw 0-10 score**, never the percentile — percentile ranks
+ * are uniform by construction, so a histogram of them is a flat block that
+ * says nothing. The raw axis is where the shape lives.
+ *
+ * Colours match {@link PriorityBadge}: calm below the cuts, warning above, so
+ * a bar and a row pill for the same commit never disagree.
+ */
+
+const BAND_FILL: Record<ReviewPriority, string> = {
+ low: "color-mix(in srgb, var(--color-success) 55%, transparent)",
+ moderate: "color-mix(in srgb, var(--color-text-tertiary) 45%, transparent)",
+ high: "color-mix(in srgb, var(--color-warning) 70%, transparent)",
+};
+
+const BAND_LABEL: Record<ReviewPriority, string> = {
+ low: "Below typical",
+ moderate: "Typical",
+ high: "Elevated",
+};
+
+const BAND_ORDER: ReviewPriority[] = ["low", "moderate", "high"];
+
+function bandFor(
+ binStart: number,
+ moderateCut: number | null,
+ highCut: number | null,
+): ReviewPriority {
+ if (highCut != null && binStart >= highCut) return "high";
+ if (moderateCut != null && binStart >= moderateCut) return "moderate";
+ return "low";
+}
+
+export function CommitRiskHistogram({
+ stats,
+ className,
+}: {
+ stats: CommitStats;
+ className?: string;
+}) {
+ const [hover, setHover] = React.useState<number | null>(null);
+
+ const buckets = stats.risk_histogram ?? [];
+ const moderateCut = stats.moderate_cut ?? null;
+ const highCut = stats.high_cut ?? null;
+
+ const total = React.useMemo(
+ () => buckets.reduce((s, b) => s + b.count, 0),
+ [buckets],
+ );
+
+ // Trim the empty tail so a repo whose scores top out at 6 doesn't spend
+ // 40% of the axis on bins that can never fill.
+ const shown = React.useMemo(() => {
+ let last = buckets.length - 1;
+ while (last > 0 && buckets[last]?.count === 0) last--;
+ return buckets.slice(0, last + 1);
+ }, [buckets]);
+
+ if (shown.length === 0 || total === 0) return null;
+
+ const padding = { top: 10, right: 10, bottom: 26, left: 30 };
+ const width = 480;
+ const height = 200;
+ const innerW = width - padding.left - padding.right;
+ const innerH = height - padding.top - padding.bottom;
+
+ const xMax = shown[shown.length - 1]?.end ?? 10;
+ const yMax = Math.max(...shown.map((b) => b.count));
+ const barW = innerW / shown.length;
+ const xOf = (score: number) => padding.left + (score / xMax) * innerW;
+
+ const hovered = hover != null ? shown[hover] : null;
+
+ return (
+ <div className={cn("w-full space-y-2", className)}>
+ <div className="relative">
+ <svg
+ viewBox={`0 0 ${width} ${height}`}
+ preserveAspectRatio="xMidYMid meet"
+ className="h-auto w-full"
+ role="img"
+ aria-label="Histogram of commit change-risk scores across the repository"
+ >
+ {/* Baseline + y axis, both recessive */}
+ <line
+ x1={padding.left}
+ y1={padding.top + innerH}
+ x2={padding.left + innerW}
+ y2={padding.top + innerH}
+ stroke="var(--color-border-default)"
+ />
+
+ {/* Two y ticks is enough — the shape matters, the exact counts live
+ in the tooltip. */}
+ {[0, yMax].map((tick) => (
+ <text
+ key={`y-${tick}`}
+ x={padding.left - 6}
+ y={padding.top + innerH - (tick / yMax) * innerH + 3}
+ textAnchor="end"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ {tick}
+ </text>
+ ))}
+
+ {/* Bars — 2px surface gap between neighbours per the mark spec */}
+ {shown.map((b, i) => {
+ const h = yMax > 0 ? (b.count / yMax) * innerH : 0;
+ const band = bandFor(b.start, moderateCut, highCut);
+ return (
+ <rect
+ key={b.start}
+ x={padding.left + i * barW + 1}
+ y={padding.top + innerH - h}
+ width={Math.max(1, barW - 2)}
+ height={h}
+ rx={2}
+ fill={BAND_FILL[band]}
+ stroke={hover === i ? "var(--color-text-secondary)" : "none"}
+ strokeWidth={1}
+ onMouseEnter={() => setHover(i)}
+ onMouseLeave={() => setHover(null)}
+ />
+ );
+ })}
+
+ {/* Hit targets wider than the marks, so thin bars stay hoverable */}
+ {shown.map((b, i) => (
+ <rect
+ key={`hit-${b.start}`}
+ x={padding.left + i * barW}
+ y={padding.top}
+ width={barW}
+ height={innerH}
+ fill="transparent"
+ onMouseEnter={() => setHover(i)}
+ onMouseLeave={() => setHover(null)}
+ />
+ ))}
+
+ {/* The tercile cuts — the whole point of drawing this. On a skewed
+ repo both cuts crowd the right edge, so the labels stack on
+ separate lines and flip to the inside when they'd overflow. */}
+ {[
+ { at: moderateCut, label: "typical", row: 0 },
+ { at: highCut, label: "elevated", row: 1 },
+ ].map(({ at, label, row }) => {
+ if (at == null || at <= 0 || at >= xMax) return null;
+ const x = xOf(at);
+ const flip = x > padding.left + innerW * 0.78;
+ return (
+ <g key={label}>
+ <line
+ x1={x}
+ y1={padding.top}
+ x2={x}
+ y2={padding.top + innerH}
+ stroke="var(--color-text-tertiary)"
+ strokeDasharray="4 3"
+ />
+ <text
+ x={flip ? x - 4 : x + 4}
+ y={padding.top + 9 + row * 11}
+ textAnchor={flip ? "end" : "start"}
+ fontSize="9"
+ fill="var(--color-text-tertiary)"
+ >
+ {flip ? `↑ ${label}` : `${label} ↑`}
+ </text>
+ </g>
+ );
+ })}
+
+ {/* X labels */}
+ {[0, xMax / 2, xMax].map((tick) => (
+ <text
+ key={`x-${tick}`}
+ x={xOf(tick)}
+ y={padding.top + innerH + 14}
+ textAnchor="middle"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ {tick.toFixed(1)}
+ </text>
+ ))}
+ <text
+ x={padding.left + innerW / 2}
+ y={height - 2}
+ textAnchor="middle"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ Change-risk score →
+ </text>
+ </svg>
+
+ {hovered && (
+ <div className="pointer-events-none absolute left-1/2 top-0 -translate-x-1/2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-2.5 py-1.5 text-xs shadow-md">
+ <span className="tabular-nums text-[var(--color-text-primary)]">
+ {hovered.start.toFixed(1)}–{hovered.end.toFixed(1)}
+ </span>
+ <span className="ml-2 tabular-nums text-[var(--color-text-secondary)]">
+ {hovered.count} commit{hovered.count === 1 ? "" : "s"} (
+ {Math.round((hovered.count / total) * 100)}%)
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* Identity only, no counts: a bin that straddles a cut is drawn in one
+ band but its commits split across two, so bin-summed totals would
+ contradict the high-priority stat card above. */}
+ <div className="flex flex-wrap gap-x-4 gap-y-1.5">
+ {BAND_ORDER.map((band) => (
+ <div key={band} className="flex items-center gap-1.5 text-xs">
+ <span
+ className="h-2.5 w-2.5 shrink-0 rounded-[3px]"
+ style={{ background: BAND_FILL[band] }}
+ />
+ <span className="text-[var(--color-text-secondary)]">
+ {BAND_LABEL[band]}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/commit-risk-scatter.tsx b/packages/ui/src/commits/commit-risk-scatter.tsx
new file mode 100644
index 000000000..f1486b278
--- /dev/null
+++ b/packages/ui/src/commits/commit-risk-scatter.tsx
@@ -0,0 +1,224 @@
+"use client";
+
+import * as React from "react";
+import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
+import { cn } from "../lib/cn";
+
+/**
+ * What a risky commit actually looks like in this repo: every commit is a dot
+ * at (size, diffusion), coloured by its repo-relative review priority. The
+ * top-right corner is the shape the change-risk model penalises most — a large
+ * change scattered across many files — so the model explains itself without
+ * anyone opening the detail sheet.
+ *
+ * Size is drawn on a log axis because commit sizes span orders of magnitude; a
+ * linear axis pins every ordinary commit to the left edge.
+ */
+
+const PRIORITY_FILL: Record<ReviewPriority, string> = {
+ low: "color-mix(in srgb, var(--color-success) 55%, transparent)",
+ moderate: "color-mix(in srgb, var(--color-text-tertiary) 45%, transparent)",
+ high: "color-mix(in srgb, var(--color-warning) 75%, transparent)",
+};
+
+const PRIORITY_LABEL: Record<ReviewPriority, string> = {
+ low: "Below typical",
+ moderate: "Typical",
+ high: "Elevated",
+};
+
+const PRIORITY_ORDER: ReviewPriority[] = ["low", "moderate", "high"];
+
+export function CommitRiskScatter({
+ commits,
+ onSelect,
+ className,
+}: {
+ commits: Commit[];
+ onSelect?: (sha: string) => void;
+ className?: string;
+}) {
+ const [hover, setHover] = React.useState<string | null>(null);
+
+ const padding = { top: 12, right: 12, bottom: 30, left: 34 };
+ const width = 480;
+ const height = 200;
+ const innerW = width - padding.left - padding.right;
+ const innerH = height - padding.top - padding.bottom;
+
+ const { points, xMaxLog, yMax } = React.useMemo(() => {
+ const sized = commits.map((c) => ({
+ commit: c,
+ churn: (c.lines_added || 0) + (c.lines_deleted || 0),
+ entropy: c.entropy || 0,
+ }));
+ const xMaxLogRaw = Math.max(
+ 1,
+ ...sized.map((s) => Math.log10(1 + s.churn)),
+ );
+ const yMaxRaw = Math.max(1, ...sized.map((s) => s.entropy));
+ return {
+ 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)),
+ _x: Math.log10(1 + s.churn) / xMaxLogRaw,
+ _y: s.entropy / yMaxRaw,
+ })),
+ xMaxLog: xMaxLogRaw,
+ yMax: yMaxRaw,
+ };
+ }, [commits]);
+
+ const counts = React.useMemo(() => {
+ const out: Record<ReviewPriority, number> = { low: 0, moderate: 0, high: 0 };
+ for (const p of points) out[p.commit.review_priority] += 1;
+ return out;
+ }, [points]);
+
+ if (points.length === 0) return null;
+
+ const hovered = hover ? points.find((p) => p.commit.sha === hover) : null;
+
+ // Draw elevated commits last so they sit above the calm ones where dots overlap.
+ const ordered = [...points].sort(
+ (a, b) =>
+ PRIORITY_ORDER.indexOf(a.commit.review_priority) -
+ PRIORITY_ORDER.indexOf(b.commit.review_priority),
+ );
+
+ return (
+ <div className={cn("w-full space-y-2", className)}>
+ <div className="relative">
+ <svg
+ viewBox={`0 0 ${width} ${height}`}
+ preserveAspectRatio="xMidYMid meet"
+ className="h-auto w-full"
+ role="img"
+ aria-label="Commit size versus change diffusion, coloured by review priority"
+ >
+ {/* Axes */}
+ <line
+ x1={padding.left}
+ y1={padding.top + innerH}
+ x2={padding.left + innerW}
+ y2={padding.top + innerH}
+ stroke="var(--color-border-default)"
+ />
+ <line
+ x1={padding.left}
+ y1={padding.top}
+ x2={padding.left}
+ y2={padding.top + innerH}
+ stroke="var(--color-border-default)"
+ />
+
+ {/* X ticks at decade boundaries — the log axis is only honest if it
+ is labelled as one. */}
+ {Array.from({ length: Math.floor(xMaxLog) + 1 }, (_, d) => d).map((d) => (
+ <text
+ key={`x-${d}`}
+ x={padding.left + (d / xMaxLog) * innerW}
+ y={padding.top + innerH + 14}
+ textAnchor="middle"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ {Math.pow(10, d).toLocaleString()}
+ </text>
+ ))}
+ <text
+ x={padding.left + innerW / 2}
+ y={height - 2}
+ textAnchor="middle"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ Lines changed (log) →
+ </text>
+
+ {/* Y ticks */}
+ {[0, yMax].map((t) => (
+ <text
+ key={`y-${t}`}
+ x={padding.left - 6}
+ y={padding.top + innerH - (t / yMax) * innerH + 3}
+ textAnchor="end"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ {t.toFixed(1)}
+ </text>
+ ))}
+ <text
+ x={-padding.top - innerH / 2}
+ y={11}
+ transform="rotate(-90)"
+ textAnchor="middle"
+ fontSize="10"
+ fill="var(--color-text-tertiary)"
+ >
+ Diffusion →
+ </text>
+
+ {ordered.map((p) => {
+ const cx = padding.left + p._x * innerW;
+ const cy = padding.top + innerH - p._y * innerH;
+ const isHover = hover === p.commit.sha;
+ return (
+ <circle
+ key={p.commit.sha}
+ cx={cx}
+ cy={cy}
+ r={isHover ? p.r + 2 : p.r}
+ fill={PRIORITY_FILL[p.commit.review_priority]}
+ // 2px surface ring so overlapping dots stay countable.
+ stroke={isHover ? "var(--color-text-primary)" : "var(--color-bg-surface)"}
+ strokeWidth={isHover ? 1.5 : 2}
+ onMouseEnter={() => setHover(p.commit.sha)}
+ onMouseLeave={() => setHover(null)}
+ onClick={onSelect ? () => onSelect(p.commit.sha) : undefined}
+ style={{ cursor: onSelect ? "pointer" : "default" }}
+ />
+ );
+ })}
+ </svg>
+
+ {hovered && (
+ <div className="pointer-events-none absolute left-1/2 top-0 max-w-[280px] -translate-x-1/2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-2.5 py-1.5 text-xs shadow-md">
+ <p className="truncate font-medium text-[var(--color-text-primary)]">
+ {hovered.commit.subject}
+ </p>
+ <p className="tabular-nums text-[var(--color-text-secondary)]">
+ {hovered.churn.toLocaleString()} lines ·{" "}
+ {hovered.commit.files_changed} file
+ {hovered.commit.files_changed === 1 ? "" : "s"} · diffusion{" "}
+ {hovered.entropy.toFixed(2)}
+ </p>
+ <p className="text-[var(--color-text-tertiary)]">
+ {PRIORITY_LABEL[hovered.commit.review_priority]} ·{" "}
+ {hovered.commit.short_sha}
+ </p>
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-wrap gap-x-4 gap-y-1.5">
+ {PRIORITY_ORDER.map((p) => (
+ <div key={p} className="flex items-center gap-1.5 text-xs">
+ <span
+ className="h-2.5 w-2.5 shrink-0 rounded-full"
+ style={{ background: PRIORITY_FILL[p] }}
+ />
+ <span className="text-[var(--color-text-secondary)]">
+ {PRIORITY_LABEL[p]}
+ </span>
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {counts[p]}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.ts
index 711ee080b..d8b188556 100644
--- a/packages/ui/src/commits/index.ts
+++ b/packages/ui/src/commits/index.ts
@@ -6,3 +6,5 @@ export * from "./priority-badge";
export * from "./credibility-strip";
export * from "./agent-badge";
export * from "./agent-trend-strip";
+export * from "./commit-risk-histogram";
+export * from "./commit-risk-scatter";
diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsx
index 96c98303d..cf691c75c 100644
--- a/packages/web/src/components/commits/commits-explorer.tsx
+++ b/packages/web/src/components/commits/commits-explorer.tsx
@@ -22,7 +22,8 @@ import { AiPromptButton, AiPromptModal, buildCommitAiPrompt } from "@repowise-de
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 { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
+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,
@@ -30,11 +31,13 @@ import {
getCommitEvolution,
getCommitStats,
getCommitsPage,
- getHotspots,
} 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");
@@ -73,11 +76,12 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
{ revalidateOnFocus: false },
);
- // Repo-relative risk distribution — turns the credibility strip's
- // "relative to this repo" claim into a picture.
- const { data: hotspots } = useSWR(
- `commits-risk-dist:${repoId}`,
- () => getHotspots(repoId, 25),
+ // 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 },
);
@@ -90,6 +94,9 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
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.
@@ -152,17 +159,45 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
/>
</div>
- {/* Secondary signals — smaller than the headline. Risk distribution is
- collapsible (it's a demoted detail); the agent-trend strip is a thin
- full-width band beneath it. */}
- {hotspots && hotspots.length > 0 && (
+ {/* 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="Risk distribution across the riskiest files"
- hint={`${Math.min(12, hotspots.length)} of ${hotspots.length}`}
+ title="How risky is a typical commit here?"
+ hint={`${total.toLocaleString()} scored`}
defaultOpen
>
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <RiskDistributionChart hotspots={hotspots} maxBars={12} />
+ <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>
)}
diff --git a/tests/unit/analysis/test_change_risk_normalize.py b/tests/unit/analysis/test_change_risk_normalize.py
index f0961d7b5..313e9e41c 100644
--- a/tests/unit/analysis/test_change_risk_normalize.py
+++ b/tests/unit/analysis/test_change_risk_normalize.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import pytest
+
from repowise.core.analysis.change_risk import RiskNormalizer, review_priority_classification
@@ -55,6 +57,42 @@ def test_priority_is_repo_relative_not_absolute() -> None:
assert n.priority(9.0) == "high"
+def test_cut_is_empty_on_empty_distribution() -> None:
+ n = RiskNormalizer.from_scores([])
+ assert n.cut(50.0) is None
+ assert n.moderate_cut is None
+ assert n.high_cut is None
+
+
+ "scores",
+ [
+ [float(i) for i in range(1, 10)], # small and evenly spaced
+ [i / 7 for i in range(71)], # dense, so mid-rank ties bite
+ [8.0, 8.2, 8.4, 8.6, 8.8, 9.0], # narrow band, all high-absolute
+ [3.0, 3.0, 3.0, 7.0, 7.0, 7.0], # heavy ties either side of the cut
+ ],
+)
+def test_cuts_agree_with_priority_banding(scores: list[float]) -> None:
+ # A chart draws the cuts and colours each bin by comparing against them.
+ # If that comparison disagreed with priority() for even one score, a bar
+ # and the row pill for the same commit would contradict each other.
+ n = RiskNormalizer.from_scores(scores)
+ assert n.moderate_cut is not None and n.high_cut is not None
+ assert n.moderate_cut <= n.high_cut
+ for s in scores:
+ expected = (
+ "high" if s >= n.high_cut else "moderate" if s >= n.moderate_cut else "low"
+ )
+ assert n.priority(s) == expected, s
+
+
+def test_no_cut_when_every_score_ties() -> None:
+ # Nothing reaches the top tercile, so there is no elevated line to draw.
+ n = RiskNormalizer.from_scores([7.0] * 10)
+ assert n.high_cut is None
+
+
def test_review_priority_classification() -> None:
assert review_priority_classification("low") == "Below typical"
assert review_priority_classification("moderate") == "Typical"
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index c54423e69..6e6a01c96 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -316,6 +316,42 @@ async def test_commits_authorship_filter(client: AsyncClient, app) -> None:
assert all(c["agent_name"] is None for c in humans.json()["items"])
+async def test_commit_stats_risk_histogram(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits/stats")
+ assert resp.status_code == 200
+ data = resp.json()
+
+ hist = data["risk_histogram"]
+ assert len(hist) == 20 # 0.5-wide bins across the 0-10 score axis
+ assert sum(b["count"] for b in hist) == 3
+ # Fixture scores 2.0 / 5.0 / 8.5 land in their own bins, nowhere else.
+ filled = {b["start"]: b["count"] for b in hist if b["count"]}
+ assert filled == {2.0: 1, 5.0: 1, 8.5: 1}
+
+ # The cuts must sit inside the distribution and keep their order, so the
+ # chart's dashed lines land where the priority pills change.
+ assert data["moderate_cut"] < data["high_cut"]
+ assert 2.0 <= data["moderate_cut"] <= 8.5
+
+
+async def test_commit_stats_histogram_empty_without_scores(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits/stats")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["risk_histogram"] == []
+ assert data["moderate_cut"] is None
+ assert data["high_cut"] is None
+
+
@pytest.mark.asyncio
async def test_agent_trend(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)