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): open the Commits page on what the work did to code health (#4154)

Raghav Chamadiya5f6658f236a5
diff --git a/packages/ui/__tests__/commits/commit-detail-card.test.tsx b/packages/ui/__tests__/commits/commit-detail-card.test.tsx
index ee7faf7b6..f67f2fec8 100644
--- a/packages/ui/__tests__/commits/commit-detail-card.test.tsx
+++ b/packages/ui/__tests__/commits/commit-detail-card.test.tsx
@@ -67,10 +67,10 @@ const health: CommitHealth = {
};
describe("commit detail card", () => {
- it("leads with the repo-relative percentile, not a raw score", () => {
+ it("keeps the repo-relative percentile as context, not a raw score", () => {
render(<CommitDetailCard commit={commit} />);
- expect(screen.getByText("36th")).toBeInTheDocument();
+ expect(screen.getAllByText(/36th percentile/).length).toBeGreaterThan(0);
expect(screen.queryByText(/7\.9 out of 10/)).toBeNull();
expect(screen.queryByText(/Supporting diff-size score/)).toBeNull();
});
@@ -105,23 +105,23 @@ describe("commit detail card", () => {
it("renders without the file block on an index that predates it", () => {
render(<CommitDetailCard commit={commit} />);
- expect(screen.getByText("36th")).toBeInTheDocument();
expect(screen.queryByText(/Where this change lands/)).toBeNull();
});
it("keeps the driver table available but collapsed", () => {
- const { container } = render(<CommitDetailCard commit={commit} />);
+ render(<CommitDetailCard commit={commit} />);
- const details = container.querySelector("details");
+ const details = screen.getByText(/How the diff-shape rank was computed/).closest("details");
expect(details).not.toBeNull();
expect(details?.hasAttribute("open")).toBe(false);
- expect(screen.getByText(/How the diff-shape rank was computed/)).toBeInTheDocument();
});
it("counts what the commit broke and what it fixed", () => {
render(<CommitDetailCard commit={{ ...commit, health }} />);
- expect(screen.getByText(/Introduced or worsened 3 findings/)).toBeInTheDocument();
- expect(screen.getByText(/2 new, 1 made worse/)).toBeInTheDocument();
+ // Figure first: what got worse, with what got resolved beside it.
+ expect(screen.getByText("3")).toBeInTheDocument();
+ expect(screen.getByText("findings introduced or worsened · 4 resolved")).toBeInTheDocument();
+ expect(screen.getByText(/2 new, 1 made more severe/)).toBeInTheDocument();
expect(screen.getByText(/Resolved 4 existing findings/)).toBeInTheDocument();
});
@@ -131,7 +131,7 @@ describe("commit detail card", () => {
expect(
screen.getAllByText(/sync_store has cyclomatic complexity 26/).length,
).toBeGreaterThan(0);
- expect(screen.getAllByText(/sync_store — core\/workspace\/update\.py:42/).length).toBeGreaterThan(0);
+ expect(screen.getAllByText("sync_store · L42").length).toBeGreaterThan(0);
expect(screen.getAllByText(/was high/).length).toBeGreaterThan(0);
});
@@ -139,7 +139,7 @@ describe("commit detail card", () => {
render(<CommitDetailCard commit={{ ...commit, health }} />);
expect(
- screen.getAllByText(/in a file this commit touched, not on a line it wrote/).length,
+ screen.getAllByText(/file touched, not a line it wrote/).length,
).toBeGreaterThan(0);
});
@@ -170,14 +170,11 @@ describe("commit detail card", () => {
expect(screen.getByText(/3 of 7 changed files could not be analysed/)).toBeInTheDocument();
});
- it("puts health above the file list, which the host already shows", () => {
+ it("reads got better, then got worse, then risk context, then files", () => {
const { container } = render(<CommitDetailCard commit={{ ...commit, files, health }} />);
const headings = Array.from(container.querySelectorAll("h2")).map((h) => h.textContent);
- expect(headings).toEqual([
- "What this commit did to code health",
- "Where this change lands",
- ]);
+ expect(headings).toEqual(["Got better", "Got worse", "Risk context", "Where this change lands"]);
});
it("keeps a long file list collapsed so it cannot bury what is below it", () => {
@@ -187,33 +184,52 @@ describe("commit detail card", () => {
lines_deleted: 0,
prior_fixes: null,
}));
- const { container } = render(<CommitDetailCard commit={{ ...commit, files: many, health }} />);
+ render(<CommitDetailCard commit={{ ...commit, files: many, health }} />);
- const [healthSection, filesSection] = Array.from(container.querySelectorAll("details"));
- expect(healthSection?.open).toBe(true);
- expect(filesSection?.open).toBe(false);
+ expect(section("Where this change lands")?.open).toBe(false);
// Collapsed, it still says how much is behind it.
expect(screen.getByText("12 files")).toBeInTheDocument();
});
it("leaves a short file list open", () => {
- const { container } = render(<CommitDetailCard commit={{ ...commit, files, health }} />);
+ render(<CommitDetailCard commit={{ ...commit, files, health }} />);
- // Only the two content sections; the driver breakdown below stays shut.
- const [healthSection, filesSection] = Array.from(container.querySelectorAll("details"));
- expect([healthSection?.open, filesSection?.open]).toEqual([true, true]);
+ expect(section("Where this change lands")?.open).toBe(true);
});
- it("names the headline count on the collapsed health toggle", () => {
+ it("folds risk context away when health has something to say", () => {
render(<CommitDetailCard commit={{ ...commit, health }} />);
- expect(screen.getByText("3 introduced or worsened")).toBeInTheDocument();
+ expect(section("Risk context")?.open).toBe(false);
+ // Collapsed, it still names the percentile.
+ expect(screen.getByText("36th percentile")).toBeInTheDocument();
});
- it("renders no health section for a commit that was never scanned", () => {
+ it("says a never-scanned commit is not yet analysed and opens risk context", () => {
render(<CommitDetailCard commit={commit} />);
- expect(screen.queryByText(/What this commit did to code health/)).toBeNull();
+ expect(screen.getByText(/Not analysed for code health yet/)).toBeInTheDocument();
+ expect(section("Risk context")?.open).toBe(true);
expect(screen.queryByText(/Compared clean/)).toBeNull();
});
+
+ it("gives a stale delta its direction only", () => {
+ render(
+ <CommitDetailCard
+ commit={{
+ ...commit,
+ health,
+ health_delta: { status: "available", kind: "worsened", introduced: 3, worsened: 0, resolved: 0, stale: true },
+ }}
+ />,
+ );
+
+ expect(screen.getByText(/An earlier analysis read the direction shown/)).toBeInTheDocument();
+ expect(screen.queryByText(/introduced or worsened/)).toBeNull();
+ expect(screen.queryByText("Got worse")).toBeNull();
+ });
});
+
+function section(title: string): HTMLDetailsElement | null {
+ return screen.getByText(title).closest("details");
+}
diff --git a/packages/ui/__tests__/commits/commit-table.test.tsx b/packages/ui/__tests__/commits/commit-table.test.tsx
index 99aacdd0c..ff2bacad5 100644
--- a/packages/ui/__tests__/commits/commit-table.test.tsx
+++ b/packages/ui/__tests__/commits/commit-table.test.tsx
@@ -24,7 +24,7 @@ describe("commit table empty states", () => {
expect(screen.getByText("No matches")).toBeInTheDocument();
expect(screen.queryByText("No commits indexed")).not.toBeInTheDocument();
- expect(screen.getByRole("button", { name: "All" })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "High priority" })).toBeInTheDocument();
+ expect(screen.getByRole("radio", { name: "All" })).toBeInTheDocument();
+ expect(screen.getByRole("radio", { name: "High priority" })).toBeInTheDocument();
});
});
diff --git a/packages/ui/__tests__/commits/history-filters.test.tsx b/packages/ui/__tests__/commits/history-filters.test.tsx
new file mode 100644
index 000000000..65efa7a4e
--- /dev/null
+++ b/packages/ui/__tests__/commits/history-filters.test.tsx
@@ -0,0 +1,23 @@
+import { render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { HistoryFilters, type HistoryFilterValue } from "../../src/commits/history-filters";
+
+const value: HistoryFilterValue = { impact: "all", hotspots: false, window: "month" };
+
+describe("HistoryFilters", () => {
+ it("disables the impact options with the reason while the window is catching up", () => {
+ render(<HistoryFilters value={value} onChange={vi.fn()} impactPending />);
+
+ const worse = screen.getByRole("radio", { name: /Made things worse/ });
+ expect(worse.getAttribute("aria-disabled")).toBe("true");
+ expect(worse.getAttribute("title")).toBe("Counts appear as commits are analysed by the current analyzer");
+ const health = screen.getByRole("radiogroup", { name: "Health impact" });
+ expect(within(health).getByRole("radio", { name: /^All/ }).getAttribute("aria-disabled")).toBeNull();
+ });
+
+ it("leaves the impact options live otherwise", () => {
+ render(<HistoryFilters value={value} onChange={vi.fn()} />);
+
+ expect(screen.getByRole("radio", { name: /Made things better/ }).getAttribute("aria-disabled")).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/commits/period-health.test.ts b/packages/ui/__tests__/commits/period-health.test.ts
new file mode 100644
index 000000000..ec7e6d65d
--- /dev/null
+++ b/packages/ui/__tests__/commits/period-health.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+import { readPeriodHealth } from "../../src/commits/period-health";
+import { readCommitHealth, worseSentence } from "../../src/commits/commit-health-copy";
+import { readHealthDeltaLede } from "../../src/commits/health-delta-lede";
+import { worseInHotspot } from "../../src/commits/commit-columns";
+import { winsReads } from "../../src/commits/recent-wins";
+import { buildChangeAiPrompt } from "../../src/health/ai-prompt-builder";
+import type { PeriodHealthSummaryResponse, WinsResponse } from "@repowise-dev/types/history";
+import type { CommitHealth } from "@repowise-dev/types/git";
+
+const summary = (o: Partial<PeriodHealthSummaryResponse>): PeriodHealthSummaryResponse => ({
+ total: 0,
+ improved: 0,
+ mixed: 0,
+ worsened: 0,
+ neutral: 0,
+ unscanned: 0,
+ findings_resolved: 0,
+ findings_introduced: 0,
+ findings_worsened: 0,
+ net_findings: 0,
+ ...o,
+});
+
+describe("readPeriodHealth", () => {
+ it("counts mixed on both sides, matching the better/worse filters", () => {
+ const r = readPeriodHealth(summary({ total: 20, improved: 3, mixed: 2, worsened: 4, neutral: 6, unscanned: 5 }));
+ expect(r).toMatchObject({ better: 5, worse: 6, both: 2, neutral: 6, analysed: 15, tone: "mixed" });
+ });
+
+ it("names a window with only improvements as good", () => {
+ expect(readPeriodHealth(summary({ total: 4, improved: 2, neutral: 2 })).tone).toBe("good");
+ });
+
+ it("separates nothing-changed from not-yet-analysed and from an empty window", () => {
+ expect(readPeriodHealth(summary({ total: 3, neutral: 3 })).tone).toBe("quiet");
+ expect(readPeriodHealth(summary({ total: 0 })).tone).toBe("empty");
+ });
+
+ it("leads with progress when most of the window is not analysed yet", () => {
+ expect(readPeriodHealth(summary({ total: 650, worsened: 8, improved: 4, unscanned: 638 })).tone).toBe("catchingUp");
+ expect(readPeriodHealth(summary({ total: 10, worsened: 3, neutral: 2, unscanned: 5 })).tone).toBe("mixed");
+ });
+});
+
+const health = (o: Partial<CommitHealth>): CommitHealth => ({
+ status: "available",
+ introduced_count: 0,
+ worsened_count: 0,
+ resolved_count: 0,
+ files_analyzed: 1,
+ files_skipped: 0,
+ findings: [],
+ ...o,
+});
+
+describe("commit health reading", () => {
+ it("reads a never-analysed commit as no delta, never as clean", () => {
+ expect(readCommitHealth(null, null).kind).toBeNull();
+ expect(readHealthDeltaLede(null)).toMatchObject({ variant: "unknown", value: null });
+ });
+
+ it("gives a stale delta its direction but no figure", () => {
+ const delta = { status: "available", kind: "worsened" as const, introduced: 4, worsened: 0, resolved: 0, stale: true };
+ expect(readCommitHealth(delta, null).stale).toBe(true);
+ expect(readHealthDeltaLede(delta)).toMatchObject({ variant: "stale", value: null });
+ });
+
+ it("leads with what got worse, and with what got better only when nothing did", () => {
+ expect(readHealthDeltaLede({ introduced: 2, worsened: 1, resolved: 4 })).toMatchObject({ variant: "worse", value: 3 });
+ expect(readHealthDeltaLede({ introduced: 0, worsened: 0, resolved: 4 })).toMatchObject({ variant: "improved", value: 4 });
+ expect(readHealthDeltaLede({ introduced: 0, worsened: 0, resolved: 0 })).toMatchObject({ variant: "neutral", value: 0 });
+ });
+
+ it("falls back to the detail's counts", () => {
+ const r = readCommitHealth(null, health({ introduced_count: 2, resolved_count: 3 }));
+ expect(r).toMatchObject({ kind: "mixed", better: 3, worse: 2 });
+ });
+
+ it("says when the worse list is capped", () => {
+ expect(worseSentence(health({ introduced_count: 5, findings: [] }))).toContain("Showing the 0 most severe of 5");
+ });
+});
+
+describe("worseInHotspot", () => {
+ const row = (kind: "improved" | "worsened" | "mixed" | "neutral", touches = 1) =>
+ ({ touches_hotspot: touches, health_delta: { status: "available", kind, introduced: 0, worsened: 0, resolved: 0 } }) as never;
+ it("marks only a commit that made a hotspot worse", () => {
+ expect(worseInHotspot(row("worsened"))).toBe(true);
+ expect(worseInHotspot(row("mixed"))).toBe(true);
+ expect(worseInHotspot(row("improved"))).toBe(false);
+ expect(worseInHotspot(row("worsened", 0))).toBe(false);
+ });
+});
+
+describe("winsReads", () => {
+ const routes = { commit: (s: string) => `/c/${s}`, file: (p: string) => `/f/${p}`, refactorings: "/r" };
+ const wins: WinsResponse = {
+ since: "2026-09-18T00:00:00Z",
+ findings_resolved: {
+ count: 12,
+ commits: 4,
+ top_commits: [{ sha: "abc", subject: "split x", author_name: "a", resolved: 7 }],
+ },
+ files_improved: { count: 0, top: [] },
+ refactorings_landed: { count: 1, top: [{ file_path: "a.py", target_symbol: "run", refactoring_type: "extract_method", before_ccn: 40, after_ccn: 8 }] },
+ };
+
+ it("keeps sections with wins, links their top item, and marks them good", () => {
+ const reads = winsReads(wins, routes);
+ expect(reads.map((r) => r.key)).toEqual(["findings", "refactors"]);
+ expect(reads[0]).toMatchObject({ value: "12", href: "/c/abc", good: true });
+ expect(reads[1]?.why).toBe("run: complexity 40 to 8.");
+ });
+});
+
+describe("buildChangeAiPrompt for one commit", () => {
+ it("names the commit, not a merged change", () => {
+ const text = buildChangeAiPrompt({
+ change: {
+ unit: "commit",
+ label: "abc1234",
+ title: "feat: x",
+ head_sha: "a".repeat(40),
+ commits: ["a".repeat(40)],
+ files: ["src/a.py"],
+ findings: [{ change_kind: "introduced", severity: "high", path: "src/a.py", line_start: 3, reason: "grew" }],
+ resolved: 0,
+ complete: true,
+ attention: [],
+ },
+ });
+ expect(text).toContain("## What this commit made worse");
+ expect(text).toContain("Commit: abc1234");
+ expect(text).not.toContain("merged change");
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index a327cc104..b1dddc011 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -31,6 +31,8 @@
"./git/*": "./src/git/*.tsx",
"./commits": "./src/commits/index.ts",
"./commits/health-delta": "./src/commits/health-delta.ts",
+ "./commits/period-health": "./src/commits/period-health.ts",
+ "./commits/commit-health-copy": "./src/commits/commit-health-copy.ts",
"./commits/*": "./src/commits/*.tsx",
"./dead-code": "./src/dead-code/index.ts",
"./dead-code/*": "./src/dead-code/*.tsx",
diff --git a/packages/ui/src/commits/commit-columns.tsx b/packages/ui/src/commits/commit-columns.tsx
new file mode 100644
index 000000000..9bb0b2959
--- /dev/null
+++ b/packages/ui/src/commits/commit-columns.tsx
@@ -0,0 +1,122 @@
+import { Bug } from "lucide-react";
+import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
+import { priorityLabel } from "./priority-badge";
+import { HealthDeltaMark, type HealthDeltaLabels } from "./health-delta-mark";
+import { healthDeltaKind } from "./health-delta";
+import type { ResponsiveColumn } from "../shared/responsive-table";
+import { formatLOC, formatRelativeTime } from "../lib/format";
+import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
+
+/** The commit list's columns, health first. Split from the table so the list
+ * and its controls stay small. */
+
+/** Marked only when it matters: the commit made health worse (or mixed) and
+ * touched a hotspot file. */
+export function worseInHotspot(c: Commit): boolean {
+ if ((c.touches_hotspot ?? 0) === 0 || !c.health_delta) return false;
+ const kind = healthDeltaKind(c.health_delta);
+ return kind === "worsened" || kind === "mixed";
+}
+
+export type CommitRow = Commit & { _idx: number };
+
+function priorityText(c: Commit): string {
+ return `${Math.round(c.risk_percentile)}th · ${priorityLabel(c.review_priority as ReviewPriority)}`;
+}
+
+export function commitColumns(
+ healthLabels: Partial<HealthDeltaLabels> | undefined,
+ hotspotLabel: string,
+): ResponsiveColumn<CommitRow>[] {
+ return [
+ {
+ // The lead: what the commit did to code health. Green only for a real
+ // improvement, red only for a regression, a word beside every dot.
+ key: "health",
+ header: "Health",
+ headerClassName: "w-32",
+ render: (c) => <HealthDeltaMark delta={c.health_delta} labels={healthLabels ?? {}} />,
+ },
+ {
+ key: "commit",
+ header: "Commit",
+ cellClassName: "min-w-[200px] max-w-[460px]",
+ render: (c) => (
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-xs text-[var(--color-text-tertiary)] shrink-0">
+ {c.short_sha}
+ </span>
+ {c.is_fix && <Bug className="h-3 w-3 shrink-0 text-[var(--color-error)]" />}
+ {/* 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>
+ {/* An exception, not the default: only where a commit made health
+ worse in a hotspot. Plain text, so it never borrows the chip's
+ colours; the "Touched hotspots" filter covers the rest. */}
+ {worseInHotspot(c) && (
+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.08em] text-[var(--color-text-tertiary)]">
+ {hotspotLabel}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ {
+ key: "author",
+ header: "Author",
+ priority: 2,
+ cellClassName: "max-w-[220px]",
+ render: (c) => (
+ <div className="flex items-center gap-1.5 min-w-0 text-xs text-[var(--color-text-secondary)]">
+ <span className="truncate">{c.author_name || "—"}</span>
+ {c.agent_name && <AgentBadge agentName={c.agent_name} tier={c.agent_autonomy_tier} />}
+ {!c.agent_name && isNewContributor(c.author_commit_count) && (
+ <NewContributorBadge commitCount={c.author_commit_count as number} />
+ )}
+ </div>
+ ),
+ mobileRender: (c) => c.author_name || "—",
+ },
+ {
+ key: "when",
+ header: "When",
+ headerClassName: "w-24",
+ priority: 3,
+ render: (c) => (
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {c.committed_at ? formatRelativeTime(c.committed_at) : "—"}
+ </span>
+ ),
+ },
+ {
+ key: "lines",
+ header: "Lines",
+ headerClassName: "w-24",
+ priority: 3,
+ render: (c) => (
+ <span className="text-xs tabular-nums">
+ <span className="text-[var(--color-success)]">+{formatLOC(c.lines_added)}</span>{" "}
+ <span className="text-[var(--color-error)]">-{formatLOC(c.lines_deleted)}</span>
+ </span>
+ ),
+ },
+ {
+ key: "risk",
+ header: "Review priority",
+ headerClassName: "w-36",
+ priority: 3,
+ // Context, not the lead: the diff-shape rank supports the health delta,
+ // so it stays plain text with no colour of its own beside the chip.
+ render: (c) => (
+ <span className="whitespace-nowrap text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {priorityText(c)}
+ </span>
+ ),
+ mobileRender: priorityText,
+ },
+ ];
+}
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
index 9240d2557..c9ddb5645 100644
--- a/packages/ui/src/commits/commit-detail-card.tsx
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -1,14 +1,17 @@
+import type * as React from "react";
import { Bug } from "lucide-react";
import { AskAboutThis } from "../chat/ask-about-this";
import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { RiskDriverBreakdown, describeDriver } from "./risk-driver-breakdown";
import { CommitFilesTable } from "./commit-files-table";
-import { CommitHealthTable } from "./commit-health-table";
-import { PageLede } from "../shared/page-lede";
+import { FindingsByFile } from "./findings-by-file";
+import { betterSentence, commitDelta, readCommitHealth, worseSentence } from "./commit-health-copy";
+import { HealthDeltaLede, type HealthDeltaLedeCopy } from "./health-delta-lede";
+import type { HealthDeltaLabels } from "./health-delta-mark";
import { OverviewSection } from "../overview/section";
import { formatDateTime } from "../lib/format";
-import type { CommitDetail, CommitHealth } from "@repowise-dev/types/git";
+import type { CommitDetail } from "@repowise-dev/types/git";
/** Above this many files, the list starts collapsed. */
const LONG_FILE_LIST = 10;
@@ -18,104 +21,134 @@ export interface CommitDetailCardProps {
/** Rank of this change's fix density against recent commits, when a live
* scorer supplied one. Drives only the reconciliation sentence. */
fixPercentile?: number | null | undefined;
+ /** The primary action beside the verdict, typically the agent prompt. */
+ action?: React.ReactNode;
+ /** Words for the health mark beside the lede figure. */
+ healthLabels?: Partial<HealthDeltaLabels> | undefined;
+ /** The lede's words; the host's translations, English by default. */
+ ledeCopy?: Partial<HealthDeltaLedeCopy> | undefined;
+ /** Where to fix a file's findings (its health view). Without it the
+ * "Got worse" groups carry no link. */
+ fileHref?: ((path: string) => string) | undefined;
+ /** The file link's word; English by default. */
+ openFileLabel?: string | undefined;
+ LinkComponent?: React.ElementType | undefined;
className?: string;
}
/**
- * Drill-down for one commit.
- *
- * The benchmarked repo-relative percentile and its server-owned priority lead.
- * The supporting raw score remains visible with its per-commit unit and
- * diff-shape interpretation, never as a probability.
+ * Drill-down for one commit, in the order a reader acts on it: what it did to
+ * code health (the verdict, then "Got better", then "Got worse" with each
+ * finding's file and line), then the diff-shape review priority as context.
*/
export function CommitDetailCard({
commit,
fixPercentile,
+ action,
+ healthLabels,
+ ledeCopy,
+ fileHref,
+ openFileLabel = "Open file",
+ LinkComponent,
className,
}: CommitDetailCardProps) {
+ const A = LinkComponent ?? "a";
const c = commit;
const files = c.files ?? [];
const health = c.health ?? null;
+ const delta = commitDelta(c.health_delta, health);
+ const read = readCommitHealth(c.health_delta, health);
+ const counted = read.kind !== null && !read.stale;
+ const improvedFiles = (c.health_delta?.files ?? []).filter((f) => (f.change ?? 0) > 0);
+ const reconciled = reconcile(c, fixPercentile ?? null);
return (
<div className={className}>
- <div className="flex flex-col gap-1.5">
- <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
- <span className="font-mono text-xs text-[var(--color-text-secondary)]">
- {c.short_sha}
- </span>
- {c.is_fix && (
- <span className="inline-flex items-center gap-1 text-xs text-[var(--color-error)]">
- <Bug className="h-3 w-3" />
- fix
- </span>
- )}
- {c.agent_name && (
- <AgentBadge
- agentName={c.agent_name}
- tier={c.agent_autonomy_tier}
- confidence={c.agent_confidence}
- />
- )}
- {!c.agent_name && isNewContributor(c.author_commit_count) && (
- <NewContributorBadge commitCount={c.author_commit_count as number} />
- )}
- <AskAboutThis
- context={{
- kind: "commit",
- label: c.short_sha,
- target: c.sha,
- targetKind: "commit",
- }}
- question={`Summarize the intent and impact of commit ${c.short_sha}, and say which files deserve the closest review.`}
- label={`Ask about commit ${c.short_sha}`}
- className="h-6 w-6"
- />
- </div>
- {/* The subject wraps. It is the one thing on this sheet a reader has to
- be able to read in full, so it never gets an ellipsis. */}
- <p className="text-base font-semibold leading-snug text-[var(--color-text-primary)] [overflow-wrap:anywhere] [text-wrap:pretty]">
- {c.subject || "(no subject)"}
- </p>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- {c.author_name || "unknown"}
- {c.committed_at ? ` · ${formatDateTime(c.committed_at)}` : ""}
- </p>
- {c.agent_name && c.agent_channel && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Attributed through {c.agent_channel}
- {c.agent_confidence ? `, ${c.agent_confidence} confidence` : ""}
- </p>
- )}
- </div>
+ <CommitHeader commit={c} />
<div className="mt-7">
- {/* Named for what it measures: diff size, not danger. */}
- <PageLede
- label="Review priority"
- value={`${Math.round(c.risk_percentile)}th`}
- unit="percentile in this repo"
- badge={<PriorityBadge priority={c.review_priority} />}
- >
- <p>{riskSentence(c)}</p>
- {reconcile(c, fixPercentile ?? null) && (
- <p>{reconcile(c, fixPercentile ?? null)}</p>
- )}
- </PageLede>
+ <HealthDeltaLede
+ delta={delta}
+ copy={{ label: "What this commit did to code health", ...ledeCopy }}
+ markLabels={healthLabels}
+ action={action}
+ />
</div>
- {health && (
+ {counted && delta && read.better > 0 && (
<OverviewSection
className="mt-7"
- title="What this commit did to code health"
- description={healthSentence(health)}
- hint={healthHint(health)}
- collapsible
+ title="Got better"
+ description={betterSentence(delta)}
>
- <CommitHealthTable findings={health.findings} />
+ {improvedFiles.length > 0 && (
+ <ul className="space-y-1 font-mono text-[11px] text-[var(--color-text-secondary)]">
+ {improvedFiles.map((f) => (
+ <li key={f.path} className="[overflow-wrap:anywhere]">
+ {f.path}{" "}
+ <span className="tabular-nums text-[var(--color-success)]">
+ {f.before?.toFixed(1)} to {f.after?.toFixed(1)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </OverviewSection>
+ )}
+
+ {counted && health && health.findings.length > 0 && (
+ <OverviewSection className="mt-7" title="Got worse" description={worseSentence(health)}>
+ <FindingsByFile
+ findings={health.findings}
+ fileAction={(g) =>
+ fileHref ? (
+ <A
+ href={fileHref(g.path)}
+ className="text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline focus-visible:text-[var(--color-accent-primary)]"
+ >
+ {openFileLabel}
+ </A>
+ ) : null
+ }
+ />
</OverviewSection>
)}
+ <OverviewSection
+ className="mt-7"
+ title="Risk context"
+ description={riskSentence(c)}
+ hint={`${Math.round(c.risk_percentile)}th percentile`}
+ collapsible
+ // Open only when health has nothing to say: then it is the only signal.
+ defaultOpen={read.kind === null}
+ >
+ <div className="space-y-3 text-xs text-[var(--color-text-secondary)]">
+ <p className="flex flex-wrap items-center gap-2">
+ <span className="tabular-nums">
+ Review priority: {Math.round(c.risk_percentile)}th percentile in this repo
+ </span>
+ <PriorityBadge priority={c.review_priority} />
+ </p>
+ {reconciled && <p>{reconciled}</p>}
+ {/* The drivers explain a diff-size statistic that ranks 0.99 against
+ lines added, so they are transparency about the model rather
+ than the finding a reviewer opened this for. */}
+ <details className="group">
+ <summary className="cursor-pointer text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]">
+ How the diff-shape rank was computed
+ </summary>
+ <p className="mt-2 max-w-[62ch] text-[var(--color-text-tertiary)]">
+ The measurements behind the rank, and the signed points each moved it
+ by against the model&apos;s baseline commit. File, directory and
+ subsystem counts are left out: they enter the score, but their fitted
+ signs are collinearity with diff size rather than a finding.
+ </p>
+ <RiskDriverBreakdown className="mt-3" drivers={c.drivers} />
+ </details>
+ </div>
+ </OverviewSection>
+
{files.length > 0 && (
<OverviewSection
className="mt-7"
@@ -123,75 +156,56 @@ export function CommitDetailCard({
description="The files this commit touched, and how much bug-fix history each one carries. Unlike the percentile above, this does not grow with the size of the diff."
hint={`${files.length} file${files.length === 1 ? "" : "s"}`}
collapsible
- // A long file list is the thing that buries everything below it, and
- // it is the one block a reader can already get from the host.
+ // A long file list is the thing that buries everything below it.
defaultOpen={files.length <= LONG_FILE_LIST}
>
<CommitFilesTable files={files} />
</OverviewSection>
)}
-
- {/* Collapsed, deliberately. The drivers explain a diff-size statistic
- that ranks 0.99 against lines added, so they are transparency about
- the model rather than the finding a reviewer opened this for. */}
- <details className="group mt-7">
- <summary className="cursor-pointer text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]">
- How the diff-shape rank was computed
- </summary>
- <p className="mt-2 max-w-[62ch] text-xs text-[var(--color-text-tertiary)]">
- The measurements behind the rank, and the signed points each moved it
- by against the model&apos;s baseline commit. File, directory and
- subsystem counts are left out: they enter the score, but their fitted
- signs are collinearity with diff size rather than a finding.
- </p>
- <RiskDriverBreakdown className="mt-3" drivers={c.drivers} />
- </details>
</div>
);
}
-function plural(n: number, word: string): string {
- return `${n} ${word}${n === 1 ? "" : "s"}`;
-}
-
-/** The counts, phrased so "2 new, 1 made worse" only appears when it adds
- * something the total does not already say. */
-function madePhrase(h: CommitHealth): string | null {
- const made = h.introduced_count + h.worsened_count;
- if (made === 0) return null;
- const split =
- h.introduced_count > 0 && h.worsened_count > 0
- ? ` (${h.introduced_count} new, ${h.worsened_count} made worse)`
- : "";
- return `Introduced or worsened ${plural(made, "finding")}${split}.`;
-}
-
-/** What a collapsed health section still says: the count that matters most. */
-function healthHint(h: CommitHealth): string {
- const made = h.introduced_count + h.worsened_count;
- if (made > 0) return `${made} introduced or worsened`;
- return h.resolved_count > 0 ? `${h.resolved_count} resolved` : "clean";
-}
-
-/**
- * Summarises the comparison, including what it could not see.
- *
- * Counts before the list: the list is capped and the counts are not.
- */
-function healthSentence(h: CommitHealth): string {
- const made = h.introduced_count + h.worsened_count;
- const parts = [
- madePhrase(h),
- h.resolved_count > 0 ? `Resolved ${plural(h.resolved_count, "existing finding")}.` : null,
- h.findings.length < made ? `Showing the ${h.findings.length} most severe.` : null,
- h.files_skipped > 0
- ? `${h.files_skipped} of ${h.files_analyzed + h.files_skipped} changed files could not be analysed.`
- : null,
- ].filter((p): p is string => p !== null);
-
- // Said out loud: silence would read as "not analysed".
- if (parts.length === 0) return "Compared clean: nothing introduced, worsened or resolved.";
- return parts.join(" ");
+function CommitHeader({ commit: c }: { commit: CommitDetail }) {
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">{c.short_sha}</span>
+ {c.is_fix && (
+ <span className="inline-flex items-center gap-1 text-xs text-[var(--color-error)]">
+ <Bug className="h-3 w-3" />
+ fix
+ </span>
+ )}
+ {c.agent_name && (
+ <AgentBadge agentName={c.agent_name} tier={c.agent_autonomy_tier} confidence={c.agent_confidence} />
+ )}
+ {!c.agent_name && isNewContributor(c.author_commit_count) && (
+ <NewContributorBadge commitCount={c.author_commit_count as number} />
+ )}
+ <AskAboutThis
+ context={{ kind: "commit", label: c.short_sha, target: c.sha, targetKind: "commit" }}
+ question={`Summarize the intent and impact of commit ${c.short_sha}, and say which files deserve the closest review.`}
+ label={`Ask about commit ${c.short_sha}`}
+ className="h-6 w-6"
+ />
+ </div>
+ {/* The subject wraps: the one thing here a reader must read in full. */}
+ <p className="text-base font-semibold leading-snug text-[var(--color-text-primary)] [overflow-wrap:anywhere] [text-wrap:pretty]">
+ {c.subject || "(no subject)"}
+ </p>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {c.author_name || "unknown"}
+ {c.committed_at ? ` · ${formatDateTime(c.committed_at)}` : ""}
+ </p>
+ {c.agent_name && c.agent_channel && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Attributed through {c.agent_channel}
+ {c.agent_confidence ? `, ${c.agent_confidence} confidence` : ""}
+ </p>
+ )}
+ </div>
+ );
}
/**
diff --git a/packages/ui/src/commits/commit-health-copy.ts b/packages/ui/src/commits/commit-health-copy.ts
new file mode 100644
index 000000000..b7275f4f9
--- /dev/null
+++ b/packages/ui/src/commits/commit-health-copy.ts
@@ -0,0 +1,75 @@
+/**
+ * What one commit did to code health, read the same way by the detail sheet
+ * and the fix prompt. Pure, so tests pin the rules (counts only from a current
+ * analysis, never-scanned is not clean).
+ */
+import type { CommitHealth } from "@repowise-dev/types/git";
+import type { HealthDeltaSummaryResponse } from "@repowise-dev/types/history";
+import {
+ betterCount,
+ healthDeltaKind,
+ worseCount,
+ type HealthDeltaCounts,
+ type HealthDeltaKind,
+} from "./health-delta";
+
+/** The commit's delta: the list row's summary, else the detail's counts;
+ * null when the commit was never analysed. */
+export function commitDelta(
+ delta: HealthDeltaSummaryResponse | null | undefined,
+ health: CommitHealth | null | undefined,
+): HealthDeltaCounts | null {
+ if (delta) return { ...delta, stale: delta.stale === true || health?.stale === true };
+ if (!health) return null;
+ return {
+ introduced: health.introduced_count,
+ worsened: health.worsened_count,
+ resolved: health.resolved_count,
+ status: health.status,
+ stale: health.stale === true,
+ };
+}
+
+export interface CommitHealthRead {
+ /** Null when the commit has no analysis at all. */
+ kind: HealthDeltaKind | null;
+ /** From an earlier analyzer version: direction only, no counts. */
+ stale: boolean;
+ better: number;
+ worse: number;
+}
+
+export function readCommitHealth(
+ delta: HealthDeltaSummaryResponse | null | undefined,
+ health: CommitHealth | null | undefined,
+): CommitHealthRead {
+ const d = commitDelta(delta, health);
+ if (!d) return { kind: null, stale: false, better: 0, worse: 0 };
+ return { kind: healthDeltaKind(d), stale: d.stale === true, better: betterCount(d), worse: worseCount(d) };
+}
+
+/** "Got better" description: findings resolved, and (once stored deltas
+ * carry it) findings made less severe. */
+export function betterSentence(d: HealthDeltaCounts): string {
+ const improved = d.improved ?? 0;
+ const parts = [
+ d.resolved > 0 ? `Resolved ${d.resolved} existing finding${d.resolved === 1 ? "" : "s"}.` : null,
+ improved > 0 ? `Made ${improved} finding${improved === 1 ? "" : "s"} less severe.` : null,
+ ].filter((p): p is string => p !== null);
+ return `${parts.join(" ")} A finding that got better has no new location to point at, so it is counted here.`;
+}
+
+/** "Got worse" description: the counts, and what the list cannot show. */
+export function worseSentence(h: CommitHealth): string {
+ const made = h.introduced_count + h.worsened_count;
+ const parts = [
+ h.introduced_count > 0 && h.worsened_count > 0
+ ? `${h.introduced_count} new, ${h.worsened_count} made more severe.`
+ : null,
+ h.findings.length < made ? `Showing the ${h.findings.length} most severe of ${made}.` : null,
+ h.files_skipped > 0
+ ? `${h.files_skipped} of ${h.files_analyzed + h.files_skipped} changed files could not be analysed.`
+ : null,
+ ].filter((p): p is string => p !== null);
+ return parts.length > 0 ? parts.join(" ") : "Each one at the file and line where it sits.";
+}
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 5462adb12..ad3392731 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -1,178 +1,142 @@
"use client";
import { useMemo, useState } from "react";
-import { Bug, Search } from "lucide-react";
-import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
-import { PriorityBadge } from "./priority-badge";
+import { Search } from "lucide-react";
import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
-import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
+import { ResponsiveTable } from "../shared/responsive-table";
import { ResultsFooter } from "../shared/results-footer";
-import { formatLOC, formatRelativeTime } from "../lib/format";
+import { Segmented } from "../shared/segmented";
import { cn } from "../lib/cn";
-import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
+import type { Commit } from "@repowise-dev/types/git";
+import type { HealthDeltaLabels } from "./health-delta-mark";
+import { commitColumns } from "./commit-columns";
export type CommitSort = "risk" | "date";
export type CommitAuthorship = "all" | "human" | "agent" | "unknown";
export type CommitKind = "all" | "high" | "fixes";
-export interface CommitTableProps {
- commits: Commit[];
- /** Server-driven ordering. `risk` = review-priority order, `date` = recency. */
- sort: CommitSort;
- onSortChange?: (sort: CommitSort) => void;
- /** Server-driven authorship filter (agent provenance). Control omitted when
- * no handler is provided. */
- authorship?: CommitAuthorship;
- onAuthorshipChange?: (authorship: CommitAuthorship) => void;
- /** Server-driven review-priority / fixes filter. */
- kind?: CommitKind;
- onKindChange?: (kind: CommitKind) => void;
- /** Repo-wide counts for the filter chips. Page-scoped counts read as
- * "All (50), High priority (50)" on a risk-sorted feed, where every loaded
- * row is already in the top tercile. */
+/** Review priority and fixes, server-driven. `counts` are repo-wide: pass
+ * them only when nothing else narrows the list. */
+export function CommitKindControl({
+ value,
+ onChange,
+ counts,
+}: {
+ value: CommitKind;
+ onChange: (kind: CommitKind) => void;
counts?: { all: number; high: number; fixes: number } | undefined;
+}) {
+ return (
+ <Segmented<CommitKind>
+ label="Review priority and fixes"
+ value={value}
+ options={[
+ { value: "all", label: "All", count: counts?.all.toLocaleString() },
+ { value: "high", label: "High priority", count: counts?.high.toLocaleString() },
+ { value: "fixes", label: "Fixes", count: counts?.fixes.toLocaleString() },
+ ]}
+ onChange={onChange}
+ />
+ );
+}
+
+/** Ordering, server-driven: recency, or the diff-shape review priority. */
+export function CommitSortControl({
+ value,
+ onChange,
+}: {
+ value: CommitSort;
+ onChange: (sort: CommitSort) => void;
+}) {
+ return (
+ <Segmented<CommitSort>
+ label="Sort"
+ value={value}
+ options={[
+ { value: "date", label: "Most recent" },
+ { value: "risk", label: "Review priority" },
+ ]}
+ onChange={onChange}
+ />
+ );
+}
+
+/** Search over the loaded commits; it narrows the page, not the repository. */
+export function CommitSearch({
+ value,
+ onChange,
+ className,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ className?: string | undefined;
+}) {
+ return (
+ <div className={cn("relative", className)}>
+ <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
+ <Input
+ type="search"
+ aria-label="Search commits or authors"
+ placeholder="Search commits or authors…"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="h-8 w-full pl-8 text-xs sm:w-56"
+ />
+ </div>
+ );
+}
+
+/** Loaded commits whose subject, author or sha contains `search`. */
+export function filterCommits(commits: Commit[], search: string): Commit[] {
+ const q = search.trim().toLowerCase();
+ if (!q) return commits;
+ return commits.filter(
+ (c) =>
+ c.subject.toLowerCase().includes(q) ||
+ c.author_name.toLowerCase().includes(q) ||
+ c.sha.toLowerCase().includes(q),
+ );
+}
+
+export interface CommitListProps {
+ commits: Commit[];
+ /** Client-side search over the loaded page. */
+ search?: string | undefined;
+ /** True when a filter narrowed the list, so empty reads "no matches", not
+ * "nothing indexed". */
+ narrowed?: boolean | undefined;
onSelect?: (commit: Commit) => void;
total?: number;
hasMore?: boolean;
loadingMore?: boolean;
onLoadMore?: () => void;
+ /** Words for the health chip; the host's translations. */
+ healthLabels?: Partial<HealthDeltaLabels> | undefined;
+ /** Word marking a commit that made health worse in a hotspot file. */
+ hotspotLabel?: string | undefined;
}
-type CommitRow = Commit & { _idx: number };
-
-const COLUMNS: ResponsiveColumn<CommitRow>[] = [
- {
- key: "rank",
- header: "#",
- headerClassName: "w-8",
- hideInCard: true,
- render: (c) => (
- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{c._idx + 1}</span>
- ),
- },
- {
- key: "commit",
- header: "Commit",
- cellClassName: "min-w-[200px] max-w-[460px]",
- render: (c) => (
- <div className="flex items-center gap-2">
- <span className="font-mono text-xs text-[var(--color-text-tertiary)] shrink-0">
- {c.short_sha}
- </span>
- {c.is_fix && <Bug className="h-3 w-3 shrink-0 text-[var(--color-error)]" />}
- {/* 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>
- ),
- },
- {
- key: "author",
- header: "Author",
- priority: 2,
- cellClassName: "max-w-[220px]",
- render: (c) => (
- <div className="flex items-center gap-1.5 min-w-0 text-xs text-[var(--color-text-secondary)]">
- <span className="truncate">{c.author_name || "—"}</span>
- {c.agent_name && <AgentBadge agentName={c.agent_name} tier={c.agent_autonomy_tier} />}
- {!c.agent_name && isNewContributor(c.author_commit_count) && (
- <NewContributorBadge commitCount={c.author_commit_count as number} />
- )}
- </div>
- ),
- mobileRender: (c) => c.author_name || "—",
- },
- {
- key: "when",
- header: "When",
- headerClassName: "w-24",
- priority: 3,
- render: (c) => (
- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {c.committed_at ? formatRelativeTime(c.committed_at) : "—"}
- </span>
- ),
- },
- {
- key: "lines",
- header: "Lines",
- headerClassName: "w-24",
- priority: 3,
- render: (c) => (
- <span className="text-xs tabular-nums">
- <span className="text-[var(--color-success)]">+{formatLOC(c.lines_added)}</span>{" "}
- <span className="text-[var(--color-error)]">-{formatLOC(c.lines_deleted)}</span>
- </span>
- ),
- },
- {
- key: "risk",
- header: "Review priority",
- 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">
- <span className="w-8 text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {Math.round(c.risk_percentile)}th
- </span>
- <PriorityBadge priority={c.review_priority as ReviewPriority} />
- </div>
- ),
- mobileRender: (c) => (
- <span className="inline-flex items-center gap-2">
- <span className="tabular-nums">{Math.round(c.risk_percentile)}th</span>
- <PriorityBadge priority={c.review_priority as ReviewPriority} />
- </span>
- ),
- },
-];
-
/**
- * The review-priority queue: per-commit change-risk, ranked. Ordering is
- * server-driven (risk vs date); search + priority filters are client-side over
- * the loaded page. Review priority is shown as a **repo-relative** percentile + category,
- * so the column is portable across repos.
+ * The commits themselves, each led by what it did to code health. Controls
+ * are separate pieces, so a host can place them where its page wants them.
*/
-export function CommitTable({
+export function CommitList({
commits,
- sort,
- onSortChange,
- authorship = "all",
- onAuthorshipChange,
- kind = "all",
- onKindChange,
- counts,
+ search = "",
+ narrowed = false,
onSelect,
total,
hasMore,
loadingMore,
onLoadMore,
-}: CommitTableProps) {
- const [search, setSearch] = useState("");
-
- // Search stays client-side over the loaded page; the band and fix filters
- // are server-driven, so they narrow the repository rather than the page.
- const filtered = useMemo(() => {
- if (!search) return commits;
- const q = search.toLowerCase();
- return commits.filter(
- (c) =>
- c.subject.toLowerCase().includes(q) ||
- c.author_name.toLowerCase().includes(q) ||
- c.sha.toLowerCase().includes(q),
- );
- }, [commits, search]);
+ healthLabels,
+ hotspotLabel = "Hotspot",
+}: CommitListProps) {
+ const cols = useMemo(() => commitColumns(healthLabels, hotspotLabel), [healthLabels, hotspotLabel]);
+ const shown = useMemo(() => filterCommits(commits, search), [commits, search]);
- if (commits.length === 0 && authorship === "all" && kind === "all") {
+ if (commits.length === 0 && !narrowed && !search.trim()) {
return (
<EmptyState
title="No commits indexed"
@@ -180,122 +144,89 @@ export function CommitTable({
/>
);
}
+ if (shown.length === 0) {
+ return <EmptyState title="No matches" description="Try adjusting your search or filters." />;
+ }
+ return (
+ <div className="overflow-hidden rounded-lg border border-[var(--color-border-default)]">
+ <ResponsiveTable
+ columns={cols}
+ rows={shown.map((c, i) => ({ ...c, _idx: i }))}
+ rowKey={(c) => c.sha}
+ caption="Commits, each led by what it did to code health"
+ {...(onSelect ? { onRowClick: onSelect } : {})}
+ stacked="sm"
+ bare
+ />
+ {total != null && (
+ <ResultsFooter
+ shown={shown.length}
+ total={total}
+ hasMore={!!hasMore}
+ loading={loadingMore}
+ onLoadMore={onLoadMore}
+ noun="commits"
+ />
+ )}
+ </div>
+ );
+}
- const filters: { key: CommitKind; label: string; count: number | undefined }[] = [
- { key: "all", label: "All", count: counts?.all },
- { key: "high", label: "High priority", count: counts?.high },
- { key: "fixes", label: "Fixes", count: counts?.fixes },
- ];
+const AUTHORSHIP: { key: CommitAuthorship; label: string }[] = [
+ { key: "all", label: "Everyone" },
+ { key: "agent", label: "Agents" },
+ { key: "human", label: "Human-attested" },
+ { key: "unknown", label: "Unknown" },
+];
- const sorts: { key: CommitSort; label: string }[] = [
- { key: "risk", label: "Review priority" },
- { key: "date", label: "Most recent" },
- ];
+export interface CommitTableProps extends Omit<CommitListProps, "search" | "narrowed"> {
+ /** Server-driven ordering. `risk` = review-priority order, `date` = recency. */
+ sort: CommitSort;
+ onSortChange?: (sort: CommitSort) => void;
+ /** Server-driven authorship filter. Control omitted without a handler. */
+ authorship?: CommitAuthorship;
+ onAuthorshipChange?: (authorship: CommitAuthorship) => void;
+ /** Server-driven review-priority / fixes filter. */
+ kind?: CommitKind;
+ onKindChange?: (kind: CommitKind) => void;
+ counts?: { all: number; high: number; fixes: number } | undefined;
+ narrowed?: boolean | undefined;
+}
+/**
+ * The list with its controls in one row above it, for hosts that want the
+ * whole thing in one piece. The OSS Commits page composes the pieces itself.
+ */
+export function CommitTable({
+ sort,
+ onSortChange,
+ authorship = "all",
+ onAuthorshipChange,
+ kind = "all",
+ onKindChange,
+ counts,
+ narrowed = false,
+ ...list
+}: CommitTableProps) {
+ const [search, setSearch] = useState("");
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
- <div className="relative">
- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <Input
- placeholder="Search commits or authors…"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- className="pl-8 h-8 w-full sm:w-56 text-xs"
- />
- </div>
- <div className="flex flex-wrap rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
- {filters.map((f) => (
- <button
- key={f.key}
- onClick={() => onKindChange?.(f.key)}
- aria-pressed={kind === f.key}
- className={cn(
- "px-2.5 py-1.5 font-medium transition-colors",
- kind === f.key
- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
- : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- {f.label}
- {f.count != null && (
- <span className="ml-1 text-[10px] opacity-70">
- ({f.count.toLocaleString()})
- </span>
- )}
- </button>
- ))}
- </div>
+ <CommitSearch value={search} onChange={setSearch} />
+ <CommitKindControl value={kind} onChange={(k) => onKindChange?.(k)} counts={counts} />
{onAuthorshipChange && (
- <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
- {(
- [
- { key: "all", label: "Everyone" },
- { key: "agent", label: "Agents" },
- { key: "human", label: "Human-attested" },
- { key: "unknown", label: "Unknown" },
- ] as { key: CommitAuthorship; label: string }[]
- ).map((a) => (
- <button
- key={a.key}
- onClick={() => onAuthorshipChange(a.key)}
- aria-pressed={authorship === a.key}
- className={cn(
- "px-2.5 py-1.5 font-medium transition-colors",
- authorship === a.key
- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
- : "bg-transparent text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- {a.label}
- </button>
- ))}
- </div>
+ <Segmented<CommitAuthorship>
+ label="Authorship"
+ value={authorship}
+ options={AUTHORSHIP.map((a) => ({ value: a.key, label: a.label }))}
+ onChange={onAuthorshipChange}
+ />
)}
- <div className="ml-auto flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
- {sorts.map((s) => (
- <button
- key={s.key}
- onClick={() => onSortChange?.(s.key)}
- aria-pressed={sort === s.key}
- className={cn(
- "px-2.5 py-1.5 font-medium transition-colors",
- sort === s.key
- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
- : "bg-transparent text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- {s.label}
- </button>
- ))}
+ <div className="ml-auto">
+ <CommitSortControl value={sort} onChange={(s) => onSortChange?.(s)} />
</div>
</div>
-
- {filtered.length === 0 ? (
- <EmptyState title="No matches" description="Try adjusting your search or filters." />
- ) : (
- <div className="rounded-lg border border-[var(--color-border-default)] overflow-hidden">
- <ResponsiveTable
- columns={COLUMNS}
- rows={filtered.map((c, i) => ({ ...c, _idx: i }))}
- rowKey={(c) => c.sha}
- caption="Commit review-priority queue"
- {...(onSelect ? { onRowClick: onSelect } : {})}
- stacked="sm"
- bare
- />
- {total != null && (
- <ResultsFooter
- shown={filtered.length}
- total={total}
- hasMore={!!hasMore}
- loading={loadingMore}
- onLoadMore={onLoadMore}
- noun="commits"
- />
- )}
- </div>
- )}
+ <CommitList {...list} search={search} narrowed={narrowed || kind !== "all" || authorship !== "all"} />
</div>
);
}
diff --git a/packages/ui/src/commits/health-delta-lede.tsx b/packages/ui/src/commits/health-delta-lede.tsx
new file mode 100644
index 000000000..1ae41f453
--- /dev/null
+++ b/packages/ui/src/commits/health-delta-lede.tsx
@@ -0,0 +1,103 @@
+import type * as React from "react";
+import { PageLede } from "../shared/page-lede";
+import { HealthDeltaMark, type HealthDeltaLabels } from "./health-delta-mark";
+import { betterCount, healthDeltaKind, worseCount, type HealthDeltaCounts } from "./health-delta";
+
+export type HealthDeltaLedeVariant = "unknown" | "stale" | "improved" | "neutral" | "worse";
+
+export interface HealthDeltaLedeRead {
+ variant: HealthDeltaLedeVariant;
+ /** The figure: findings made worse, or resolved when nothing got worse;
+ * null when no current count can be shown. */
+ value: number | null;
+ better: number;
+ worse: number;
+}
+
+/** Which reading a delta gets. A stale delta keeps its direction (the mark)
+ * but shows no figure: its counts do not compare with current ones. */
+export function readHealthDeltaLede(delta: HealthDeltaCounts | null | undefined): HealthDeltaLedeRead {
+ if (!delta) return { variant: "unknown", value: null, better: 0, worse: 0 };
+ const better = betterCount(delta);
+ const worse = worseCount(delta);
+ if (delta.stale) return { variant: "stale", value: null, better, worse };
+ const kind = healthDeltaKind(delta);
+ if (kind === "improved") return { variant: "improved", value: better, better, worse };
+ if (kind === "neutral") return { variant: "neutral", value: 0, better, worse };
+ return { variant: "worse", value: worse, better, worse };
+}
+
+/** Every word the lede says; hosts pass translations, English by default. */
+export interface HealthDeltaLedeCopy {
+ label: string;
+ unitWorse: (worse: number, better: number) => string;
+ unitBetter: (better: number) => string;
+ unitNeutral: string;
+ worse: string;
+ improved: (better: number) => string;
+ neutral: string;
+ stale: string;
+ unknown: string;
+}
+
+const s = (n: number) => (n === 1 ? "" : "s");
+
+const DEFAULT_COPY: HealthDeltaLedeCopy = {
+ label: "What this did to code health",
+ unitWorse: (worse, better) => `finding${s(worse)} introduced or worsened · ${better} resolved`,
+ unitBetter: (better) => `finding${s(better)} resolved · nothing made worse`,
+ unitNeutral: "findings changed",
+ worse: "Each one is listed below by file, worst first, with the symbol and line.",
+ improved: (better) => `Resolved ${better} finding${s(better)} and made nothing worse. Nice work.`,
+ neutral: "Compared clean: nothing introduced, worsened or resolved.",
+ stale: "An earlier analysis read the direction shown; its counts do not compare with the current analysis.",
+ unknown: "Not analysed for code health yet.",
+};
+
+export interface HealthDeltaLedeProps {
+ delta: HealthDeltaCounts | null | undefined;
+ copy?: Partial<HealthDeltaLedeCopy> | undefined;
+ /** Words for the mark beside the figure. */
+ markLabels?: Partial<HealthDeltaLabels> | undefined;
+ action?: React.ReactNode;
+ /** Extra reading under the sentence, e.g. what was not compared. */
+ children?: React.ReactNode;
+}
+
+/**
+ * What a commit or a change did to code health, figure first: how many
+ * findings it made worse (or, when it only helped, how many it resolved), the
+ * dot-and-word mark at body size beside it, one reading and the primary
+ * action. One implementation for the change page and the commit sheet.
+ */
+export function HealthDeltaLede({ delta, copy, markLabels, action, children }: HealthDeltaLedeProps) {
+ const c = { ...DEFAULT_COPY, ...copy };
+ const r = readHealthDeltaLede(delta);
+ const unit =
+ r.variant === "worse"
+ ? c.unitWorse(r.worse, r.better)
+ : r.variant === "improved"
+ ? c.unitBetter(r.better)
+ : r.variant === "neutral"
+ ? c.unitNeutral
+ : undefined;
+ const reading = {
+ worse: c.worse,
+ improved: c.improved(r.better),
+ neutral: c.neutral,
+ stale: c.stale,
+ unknown: c.unknown,
+ }[r.variant];
+ return (
+ <PageLede
+ label={c.label}
+ value={r.value === null ? "—" : String(r.value)}
+ unit={unit}
+ badge={<HealthDeltaMark delta={delta ?? null} labels={markLabels ?? {}} figures={false} />}
+ action={action}
+ >
+ <p>{reading}</p>
+ {children}
+ </PageLede>
+ );
+}
diff --git a/packages/ui/src/commits/history-filters.tsx b/packages/ui/src/commits/history-filters.tsx
new file mode 100644
index 000000000..c287aaff9
--- /dev/null
+++ b/packages/ui/src/commits/history-filters.tsx
@@ -0,0 +1,221 @@
+"use client";
+
+import { useEffect, useState, type ReactNode } from "react";
+import { Flame } from "lucide-react";
+import { Input } from "../ui/input";
+import { Segmented } from "../shared/segmented";
+import { ActiveFilterChips, MoreFilters, type ActiveFilterChip } from "../shared/more-filters";
+import { cn } from "../lib/cn";
+
+/** What a commit or change did to health, as the quick filter names it. */
+export type HealthImpact = "all" | "better" | "worse" | "none";
+export type HistoryWindow = "week" | "month" | "quarter" | "all" | "custom";
+
+export interface HistoryFilterValue {
+ impact: HealthImpact;
+ hotspots: boolean;
+ window: HistoryWindow;
+ /** `YYYY-MM-DD`, read only for the custom window; `until` is inclusive. */
+ since?: string | undefined;
+ until?: string | undefined;
+ author?: string | undefined;
+ area?: string | undefined;
+}
+
+export interface HistoryFilterLabels {
+ impactLabel: string;
+ all: string;
+ better: string;
+ worse: string;
+ none: string;
+ hotspots: string;
+ windowLabel: string;
+ week: string;
+ month: string;
+ quarter: string;
+ allTime: string;
+ custom: string;
+ from: string;
+ to: string;
+ author: string;
+ area: string;
+ moreFilters: string;
+ clearAll: string;
+ /** Why the impact options cannot act while the window is catching up. */
+ impactPending: string;
+}
+
+const DEFAULT_LABELS: HistoryFilterLabels = {
+ impactLabel: "Health impact",
+ all: "All",
+ better: "Made things better",
+ worse: "Made things worse",
+ none: "No health impact",
+ hotspots: "Touched hotspots",
+ windowLabel: "Time window",
+ week: "Past week",
+ month: "Past month",
+ quarter: "Past quarter",
+ allTime: "All time",
+ custom: "Custom",
+ from: "From",
+ to: "To",
+ author: "Author email or name",
+ area: "Area, e.g. packages/core",
+ moreFilters: "More filters",
+ clearAll: "Clear all",
+ impactPending: "Counts appear as commits are analysed by the current analyzer",
+};
+
+export interface HistoryFiltersProps {
+ value: HistoryFilterValue;
+ onChange: (patch: Partial<HistoryFilterValue>) => void;
+ /** Per-impact counts under the other filters, so a selected impact never
+ * hides its alternatives' sizes. */
+ counts?: Record<HealthImpact, number> | undefined;
+ labels?: Partial<HistoryFilterLabels> | undefined;
+ /** The host's own secondary controls, placed under "More filters" after
+ * author and area (search, sort and the like). */
+ more?: ReactNode;
+ /** Every active secondary filter, author and area included, as removable
+ * chips; their count shows on the closed disclosure. */
+ chips?: ActiveFilterChip[] | undefined;
+ onClearAll?: (() => void) | undefined;
+ /** True while most of the window is not analysed yet: the impact options
+ * are disabled with the reason, since their counts cannot act. */
+ impactPending?: boolean | undefined;
+ className?: string | undefined;
+}
+
+/**
+ * The quick filters over a history list: health impact, hotspots and the
+ * time window in one row; author, area and the host's secondary controls
+ * behind "More filters", each active one a removable chip. Controlled and
+ * server-driven: the host writes each change to the URL and refetches, so the
+ * counts and the list always describe the same set.
+ */
+export function HistoryFilters({
+ value,
+ onChange,
+ counts,
+ labels,
+ more,
+ chips = [],
+ onClearAll,
+ impactPending = false,
+ className,
+}: HistoryFiltersProps) {
+ const l = { ...DEFAULT_LABELS, ...labels };
+ const count = (k: HealthImpact) => counts?.[k]?.toLocaleString();
+ const pending = impactPending ? l.impactPending : undefined;
+ return (
+ <div className={cn("flex flex-col gap-2.5", className)}>
+ <div className="flex flex-wrap items-center gap-2">
+ <Segmented<HealthImpact>
+ label={l.impactLabel}
+ value={value.impact}
+ options={[
+ { value: "all", label: l.all, count: count("all") },
+ { value: "better", label: l.better, count: count("better"), disabledReason: pending },
+ { value: "worse", label: l.worse, count: count("worse"), disabledReason: pending },
+ { value: "none", label: l.none, count: count("none"), disabledReason: pending },
+ ]}
+ onChange={(impact) => onChange({ impact })}
+ />
+ <button
+ type="button"
+ aria-pressed={value.hotspots}
+ onClick={() => onChange({ hotspots: !value.hotspots })}
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",
+ value.hotspots
+ ? "border-[var(--color-border-hover)] bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ <Flame aria-hidden className="h-3.5 w-3.5" />
+ {l.hotspots}
+ </button>
+ <Segmented<HistoryWindow>
+ label={l.windowLabel}
+ value={value.window}
+ options={[
+ { value: "week", label: l.week },
+ { value: "month", label: l.month },
+ { value: "quarter", label: l.quarter },
+ { value: "all", label: l.allTime },
+ { value: "custom", label: l.custom },
+ ]}
+ onChange={(window) => onChange({ window })}
+ />
+ {value.window === "custom" && (
+ <>
+ <DateField label={l.from} value={value.since} onCommit={(since) => onChange({ since })} />
+ <DateField label={l.to} value={value.until} onCommit={(until) => onChange({ until })} />
+ </>
+ )}
+ </div>
+ <MoreFilters active={chips.length} label={l.moreFilters}>
+ <TextField label={l.author} value={value.author} onCommit={(author) => onChange({ author })} />
+ <TextField label={l.area} value={value.area} onCommit={(area) => onChange({ area })} mono />
+ {more}
+ </MoreFilters>
+ {onClearAll && <ActiveFilterChips chips={chips} onClearAll={onClearAll} clearAllLabel={l.clearAll} />}
+ </div>
+ );
+}
+
+/** A text filter that applies on Enter or blur, not per keystroke: each
+ * apply is a server round trip. */
+function TextField({
+ label,
+ value,
+ onCommit,
+ mono,
+}: {
+ label: string;
+ value: string | undefined;
+ onCommit: (next: string | undefined) => void;
+ mono?: boolean;
+}) {
+ const [draft, setDraft] = useState(value ?? "");
+ useEffect(() => setDraft(value ?? ""), [value]);
+ const commit = () => {
+ const next = draft.trim() || undefined;
+ if (next !== value) onCommit(next);
+ };
+ return (
+ <Input
+ type="search"
+ aria-label={label}
+ placeholder={label}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => e.key === "Enter" && commit()}
+ className={cn("h-8 w-full text-xs sm:w-52", mono && "font-mono")}
+ />
+ );
+}
+
+function DateField({
+ label,
+ value,
+ onCommit,
+}: {
+ label: string;
+ value: string | undefined;
+ onCommit: (next: string | undefined) => void;
+}) {
+ return (
+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">
+ {label}
+ <Input
+ type="date"
+ value={value ?? ""}
+ onChange={(e) => onCommit(e.target.value || undefined)}
+ className="h-8 w-36 text-xs"
+ />
+ </label>
+ );
+}
diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.ts
index 65811269a..55d73edef 100644
--- a/packages/ui/src/commits/index.ts
+++ b/packages/ui/src/commits/index.ts
@@ -15,3 +15,10 @@ export * from "./commit-files-table";
export * from "./health-delta";
export * from "./health-delta-mark";
export * from "./findings-by-file";
+export * from "./period-health";
+export * from "./period-health-headline";
+export * from "./recent-wins";
+export * from "./history-filters";
+export * from "./commit-health-copy";
+export * from "./commit-columns";
+export * from "./health-delta-lede";
diff --git a/packages/ui/src/commits/period-health-headline.tsx b/packages/ui/src/commits/period-health-headline.tsx
new file mode 100644
index 000000000..234731baf
--- /dev/null
+++ b/packages/ui/src/commits/period-health-headline.tsx
@@ -0,0 +1,84 @@
+import * as React from "react";
+import type { PeriodHealthSummaryResponse } from "@repowise-dev/types/history";
+import { PageLede } from "../shared/page-lede";
+import { readPeriodHealth, type PeriodHealthRead } from "./period-health";
+
+/** Every sentence the headline can say. packages/ui has no i18n, so hosts
+ * pass their own; the defaults name commits in English. */
+export interface PeriodHealthCopy {
+ /** Quiet unit beside the figure: "commits made health better". */
+ unit: (r: PeriodHealthRead) => string;
+ /** Something improved and nothing got worse. */
+ good: (r: PeriodHealthRead) => string;
+ /** Both directions happened. The figure already names the improvements,
+ * so the sentence carries what got worse and what did nothing. */
+ mixed: (r: PeriodHealthRead) => string;
+ /** Analysed work that changed no finding. */
+ quiet: (r: PeriodHealthRead) => string;
+ /** Most of the window is not analysed yet: a calm progress line leads. */
+ catchingUpUnit: (r: PeriodHealthRead) => string;
+ catchingUp: (r: PeriodHealthRead) => string;
+ /** The window holds no commits. */
+ empty: (r: PeriodHealthRead) => string;
+ /** How many items have no current analysis; shown only when some do not. */
+ unscanned: (r: PeriodHealthRead) => string;
+}
+
+const s = (n: number) => (n === 1 ? "" : "s");
+
+const DEFAULT_COPY: PeriodHealthCopy = {
+ unit: (r) => `commit${s(r.better)} made health better`,
+ good: (r) =>
+ `Nothing made health worse. ${r.better.toLocaleString()} commit${s(r.better)} made it better, resolving ${r.findingsBetter.toLocaleString()} finding${s(r.findingsBetter)}.`,
+ mixed: (r) =>
+ `${r.worse.toLocaleString()} made it worse, ${r.both.toLocaleString()} of them while also making something better. ${r.neutral.toLocaleString()} had no health impact.`,
+ quiet: (r) =>
+ `None of the ${r.analysed.toLocaleString()} analysed commit${s(r.analysed)} changed a health finding.`,
+ catchingUpUnit: (r) => `of ${r.total.toLocaleString()} commit${s(r.total)} analysed so far`,
+ catchingUp: () =>
+ "Most commits in this window have not been analysed by the current analyzer yet. Recent commits come first, as updates run; the rows below show each older commit's direction from the earlier analysis.",
+ empty: () => "No commits in this window.",
+ unscanned: (r) => `${r.unscanned.toLocaleString()} not yet analysed.`,
+};
+
+export interface PeriodHealthHeadlineProps {
+ summary: PeriodHealthSummaryResponse;
+ /** The window, as the micro-label names it: "Past month". */
+ period: string;
+ copy?: Partial<PeriodHealthCopy> | undefined;
+ action?: React.ReactNode;
+}
+
+/**
+ * The period headline: how many commits (or changes) made health better,
+ * then how many made it worse. Improvements lead because they are the part a
+ * team rarely sees; a window where nothing got worse says so in plain words.
+ * Green only on a real improvement, never red: the regressions are a sentence,
+ * and the list below is where they get worked.
+ */
+export function PeriodHealthHeadline({ summary, period, copy, action }: PeriodHealthHeadlineProps) {
+ const c = { ...DEFAULT_COPY, ...copy };
+ const r = readPeriodHealth(summary);
+ if (r.tone === "catchingUp" || r.tone === "empty") {
+ // No alarm and no green: progress, stated plainly.
+ return (
+ <PageLede label={period} value={r.analysed.toLocaleString()} unit={c.catchingUpUnit(r)} action={action}>
+ <p>{c[r.tone](r)}</p>
+ </PageLede>
+ );
+ }
+ return (
+ <PageLede
+ label={period}
+ value={r.better.toLocaleString()}
+ valueColor={r.better > 0 ? "var(--color-success)" : undefined}
+ unit={c.unit(r)}
+ action={action}
+ >
+ <p>{c[r.tone](r)}</p>
+ {r.unscanned > 0 && (
+ <p className="text-[var(--color-text-tertiary)]">{c.unscanned(r)}</p>
+ )}
+ </PageLede>
+ );
+}
diff --git a/packages/ui/src/commits/period-health.ts b/packages/ui/src/commits/period-health.ts
new file mode 100644
index 000000000..f170cb431
--- /dev/null
+++ b/packages/ui/src/commits/period-health.ts
@@ -0,0 +1,63 @@
+/**
+ * A period's health story, read from the summary endpoints
+ * (`/commits/health-summary`, `/changes/summary`). Pure, so the headline and
+ * the quick-filter counts beside it say the same numbers.
+ */
+import type { PeriodHealthSummaryResponse } from "@repowise-dev/types/history";
+
+export type PeriodHealthTone = "good" | "mixed" | "quiet" | "catchingUp" | "empty";
+
+export interface PeriodHealthRead {
+ /** Items that made anything better, including those that also made
+ * something worse: what the "Made things better" filter returns. */
+ better: number;
+ /** Items that made anything worse, including those that also improved. */
+ worse: number;
+ /** Items counted in both of the above. */
+ both: number;
+ /** Analysed items that changed no finding. */
+ neutral: number;
+ /** Items with no current analysis ("not yet analysed"). */
+ unscanned: number;
+ /** Items with a current analysis. */
+ analysed: number;
+ total: number;
+ /** Findings made better: resolved, plus improved once stored deltas carry it. */
+ findingsBetter: number;
+ /** Findings made worse: introduced plus worsened. */
+ findingsWorse: number;
+ /** `good` when something improved and nothing got worse; `quiet` when the
+ * analysed work changed nothing; `catchingUp` when most of the window is
+ * not analysed by the current analyzer yet (after an upgrade, or older
+ * history the bounded scan has not reached), so counts would mislead;
+ * `empty` when the window holds nothing. */
+ tone: PeriodHealthTone;
+}
+
+export function readPeriodHealth(s: PeriodHealthSummaryResponse): PeriodHealthRead {
+ const better = s.improved + s.mixed;
+ const worse = s.worsened + s.mixed;
+ const analysed = s.improved + s.mixed + s.worsened + s.neutral;
+ const tone: PeriodHealthTone =
+ s.total === 0
+ ? "empty"
+ : s.unscanned * 2 > s.total
+ ? "catchingUp"
+ : worse === 0
+ ? better > 0
+ ? "good"
+ : "quiet"
+ : "mixed";
+ return {
+ better,
+ worse,
+ both: s.mixed,
+ neutral: s.neutral,
+ unscanned: s.unscanned,
+ analysed,
+ total: s.total,
+ findingsBetter: s.findings_resolved + (s.findings_improved ?? 0),
+ findingsWorse: s.findings_introduced + s.findings_worsened,
+ tone,
+ };
+}
diff --git a/packages/ui/src/commits/priority-badge.tsx b/packages/ui/src/commits/priority-badge.tsx
index 7cf3e2a9b..6fb57939f 100644
--- a/packages/ui/src/commits/priority-badge.tsx
+++ b/packages/ui/src/commits/priority-badge.tsx
@@ -33,6 +33,11 @@ const LABELS: Record<ReviewPriority, string> = {
low: "Below typical",
};
+/** The tercile's word, for a caller that shows priority as quiet context. */
+export function priorityLabel(priority: ReviewPriority): string {
+ return LABELS[priority] ?? LABELS.moderate;
+}
+
/**
* Review-priority pill. The priority is **repo-relative** (where the commit
* sits in its own repo's risk distribution), not the absolute calibration band
diff --git a/packages/ui/src/commits/recent-wins.tsx b/packages/ui/src/commits/recent-wins.tsx
new file mode 100644
index 000000000..7b5ab78e8
--- /dev/null
+++ b/packages/ui/src/commits/recent-wins.tsx
@@ -0,0 +1,130 @@
+import * as React from "react";
+import type { WinsResponse } from "@repowise-dev/types/history";
+import { ReadsColumn, type ReadItem } from "../overview/reads-column";
+
+/** Where each win links. The host owns routes. */
+export interface RecentWinsRoutes {
+ commit: (sha: string) => string;
+ file: (path: string) => string;
+ refactorings: string;
+}
+
+/** Every word the column says; English defaults, hosts pass translations. */
+export interface RecentWinsCopy {
+ title: string;
+ findingsLabel: string;
+ findingsUnit: (commits: number) => string;
+ /** The commit that resolved most, as one line. */
+ findingsWhy: (subject: string, resolved: number) => string;
+ filesLabel: string;
+ filesUnit: string;
+ filesWhy: (path: string, before: number, after: number) => string;
+ refactorsLabel: string;
+ refactorsUnit: string;
+ refactorsWhy: (symbol: string, before: number | null, after: number | null) => string;
+ /** Said when the window holds no wins at all. */
+ none: string;
+}
+
+const s = (n: number) => (n === 1 ? "" : "s");
+
+const DEFAULT_COPY: RecentWinsCopy = {
+ title: "Recent wins",
+ findingsLabel: "Findings resolved",
+ findingsUnit: (commits) => `across ${commits.toLocaleString()} commit${s(commits)}`,
+ findingsWhy: (subject, resolved) => `Most in one commit: ${subject} (${resolved}).`,
+ filesLabel: "Files got healthier",
+ filesUnit: "score rose",
+ filesWhy: (path, before, after) => `Biggest gain: ${path}, ${before.toFixed(1)} to ${after.toFixed(1)}.`,
+ refactorsLabel: "Refactorings landed",
+ refactorsUnit: "planned and done",
+ refactorsWhy: (symbol, before, after) =>
+ before != null && after != null
+ ? `${symbol}: complexity ${before} to ${after}.`
+ : `${symbol} was refactored as planned.`,
+ none: "No wins recorded in this window yet. Resolved findings, healthier files and landed refactorings show up here as they happen.",
+};
+
+/**
+ * The wins as rows of the shared reads column. Pure, so the Commits page and
+ * Overview read one window the same way. Sections with nothing in them are
+ * left out rather than shown as zero.
+ */
+export function winsReads(
+ wins: WinsResponse,
+ routes: RecentWinsRoutes,
+ copy: RecentWinsCopy = DEFAULT_COPY,
+): ReadItem[] {
+ const commit = wins.findings_resolved.top_commits?.[0];
+ const file = wins.files_improved.top?.[0];
+ const refactor = wins.refactorings_landed.top?.[0];
+ const sections: (Omit<ReadItem, "value"> & { count: number })[] = [
+ {
+ key: "findings",
+ count: wins.findings_resolved.count,
+ label: copy.findingsLabel,
+ unit: copy.findingsUnit(wins.findings_resolved.commits),
+ why: commit ? copy.findingsWhy(commit.subject, commit.resolved) : "",
+ href: commit ? routes.commit(commit.sha) : routes.refactorings,
+ },
+ {
+ key: "files",
+ count: wins.files_improved.count,
+ label: copy.filesLabel,
+ unit: copy.filesUnit,
+ why: file ? copy.filesWhy(file.path, file.before, file.after) : "",
+ href: file ? routes.file(file.path) : routes.refactorings,
+ },
+ {
+ key: "refactors",
+ count: wins.refactorings_landed.count,
+ label: copy.refactorsLabel,
+ unit: copy.refactorsUnit,
+ why: refactor
+ ? copy.refactorsWhy(refactor.target_symbol, refactor.before_ccn ?? null, refactor.after_ccn ?? null)
+ : "",
+ href: routes.refactorings,
+ },
+ ];
+ return sections
+ .filter((s) => s.count > 0)
+ .map(({ count, ...s }) => ({ ...s, value: count.toLocaleString(), good: true }));
+}
+
+export interface RecentWinsProps {
+ wins: WinsResponse;
+ routes: RecentWinsRoutes;
+ /** The window and who, in words: "Past month, whole repository". */
+ scope: string;
+ copy?: Partial<RecentWinsCopy> | undefined;
+ LinkComponent?: React.ElementType | undefined;
+ className?: string | undefined;
+}
+
+/**
+ * What got better in a window: findings resolved, files whose score rose and
+ * refactorings that landed. Calm on purpose: a success dot and plain words,
+ * no celebration. Reusable wherever a window of wins belongs (Commits,
+ * Overview, a person page with `?author=`); the host fetches `/wins`.
+ */
+export function RecentWins({ wins, routes, scope, copy, LinkComponent, className }: RecentWinsProps) {
+ const c = { ...DEFAULT_COPY, ...copy };
+ const reads = winsReads(wins, routes, c);
+ return (
+ <section className={className} aria-label={c.title}>
+ <div className="mb-3.5 flex items-baseline justify-between gap-3">
+ <h2 className="shrink-0 text-[15px] font-semibold text-[var(--color-text-primary)]">{c.title}</h2>
+ <span className="min-w-0 text-right text-[11px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {scope}
+ </span>
+ </div>
+ {reads.length > 0 ? (
+ <ReadsColumn items={reads} LinkComponent={LinkComponent} />
+ ) : (
+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">
+ {c.none}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/packages/ui/src/health/ai-prompts/change-prompt.ts b/packages/ui/src/health/ai-prompts/change-prompt.ts
index 00226fb41..61cbba010 100644
--- a/packages/ui/src/health/ai-prompts/change-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/change-prompt.ts
@@ -43,8 +43,16 @@ export interface ChangePromptInput {
complete: boolean;
/** Evidence rows that need a look, already worded ("Decisions crossed: 4 accepted"). */
attention: string[];
+ /** `commit` when the unit is one commit rather than a merged change. */
+ unit?: "change" | "commit" | undefined;
}
+/** How the prompt names its unit. */
+const UNIT_WORDS = {
+ change: { noun: "change", subject: "merged change", heading: "Merged change", fact: "Change", madeFor: "merged for" },
+ commit: { noun: "commit", subject: "commit", heading: "Commit", fact: "Commit", madeFor: "made for" },
+} as const;
+
export interface BuildChangePromptOptions {
change: ChangePromptInput;
flavor?: AiPromptFlavor;
@@ -82,16 +90,17 @@ function diffCommand(c: ChangePromptInput): string {
}
function changeFacts(c: ChangePromptInput): string {
+ const w = UNIT_WORDS[c.unit ?? "change"];
const shown = c.files.slice(0, FILE_CAP).map((f) => `\`${f}\``);
const more = c.files.length > FILE_CAP ? ` and ${c.files.length - FILE_CAP} more` : "";
return bulletList([
- `Change: ${c.label} — ${c.title}`,
+ `${w.fact}: ${c.label} — ${c.title}`,
`Commits: ${c.commits.length} (head \`${c.head_sha.slice(0, 12)}\`)`,
`Files (${c.files.length}): ${shown.join(", ")}${more}`,
c.resolved > 0 ? `It also resolved ${c.resolved} existing finding${pluralS(c.resolved)}; keep those fixes.` : null,
- c.complete ? null : "Part of this change could not be compared, so the list below may be incomplete.",
+ c.complete ? null : `Part of this ${w.noun} could not be compared, so the list below may be incomplete.`,
c.omitted
- ? `${c.omitted} more finding${pluralS(c.omitted)} this change made worse ${c.omitted === 1 ? "is" : "are"} not listed below (the list keeps the worst first); after these, check the files above for the rest.`
+ ? `${c.omitted} more finding${pluralS(c.omitted)} this ${w.noun} made worse ${c.omitted === 1 ? "is" : "are"} not listed below (the list keeps the worst first); after these, check the files above for the rest.`
: null,
]);
}
@@ -107,10 +116,11 @@ export function buildChangeAiPrompt({
repoName,
}: BuildChangePromptOptions): string {
const fixing = changePromptFixes(c);
+ const w = UNIT_WORDS[c.unit ?? "change"];
const lead = preamble(flavor, {
source: fixing
- ? "Repowise compared code health before and after this merged change and charged the findings below to it."
- : "Repowise built an evidence checklist for this merged change; the rows below are what it flagged.",
+ ? `Repowise compared code health before and after this ${w.subject} and charged the findings below to it.`
+ : `Repowise built an evidence checklist for this ${w.subject}; the rows below are what it flagged.`,
open: "the files and lines named below",
mcpTail:
"Call `get_context([...])` on the files named below and `get_risk(changed_files=[...])` for blast radius and test gaps before reading by hand.",
@@ -118,13 +128,13 @@ export function buildChangeAiPrompt({
const work =
c.findings.length > 0
- ? ["## What this change made worse", "", bulletList(c.findings.map(findingLine)), ""]
+ ? [`## What this ${w.noun} made worse`, "", bulletList(c.findings.map(findingLine)), ""]
: [];
const flagged = c.attention.length > 0 ? ["## Flagged for a look", "", bulletList(c.attention), ""] : [];
const constraints = fixing
? [
- "Fix the findings above in place. Do not revert the change or undo the behaviour it was merged for.",
+ `Fix the findings above in place. Do not revert the ${w.noun} or undo the behaviour it was ${w.madeFor}.`,
"Keep each fix small and local to the named symbol; no unrelated refactors.",
"If a finding is a false positive or the cost is justified, say so and leave it.",
"Run the tests that cover the touched files before and after.",
@@ -139,20 +149,20 @@ export function buildChangeAiPrompt({
"2. The tests you ran and their result.",
]
: [
- "1. For each flagged row: whether it matters for this change and why.",
+ `1. For each flagged row: whether it matters for this ${w.noun} and why.`,
"2. Anything a reviewer should still check, tied to files.",
];
return joinSections([
lead,
"",
- `## Merged change${repoSuffix(repoName)}`,
+ `## ${w.heading}${repoSuffix(repoName)}`,
"",
changeFacts(c),
"",
...work,
...flagged,
...closingSections(constraints, expected),
- `Read the change with \`${diffCommand(c)}\` first.`,
+ `Read the ${w.noun} with \`${diffCommand(c)}\` first.`,
]);
}
diff --git a/packages/ui/src/overview/reads-column.tsx b/packages/ui/src/overview/reads-column.tsx
index da8e344cc..4b3193977 100644
--- a/packages/ui/src/overview/reads-column.tsx
+++ b/packages/ui/src/overview/reads-column.tsx
@@ -16,6 +16,9 @@ export interface ReadItem {
href: string;
/** Optional proportion bar — use only when the number genuinely splits. */
bar?: ReadBarSegment[];
+ /** A success dot before the label, for a figure that is good news (a win).
+ * The word in `label` still names it; the dot only adds tone. */
+ good?: boolean;
}
/**
@@ -60,7 +63,10 @@ export function ReadsColumn({
value right on one baseline, which looks tidy in a mockup and is
ragged with real data: a trailing unit shifts every number to a
different x, so four figures in a column line up on nothing. */}
- <span className="block font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {item.good && (
+ <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-success)]" />
+ )}
{item.label}
</span>
<span className="mt-1 flex items-baseline gap-1.5">
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index 4292bfa52..a1fcfb71c 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -97,4 +97,5 @@ export {
type ProportionSegment,
} from "./proportion-bar";
export { SERIES, SERIES_TAIL, seriesColor, commitCategoryColor } from "./series";
+export { MoreFilters, ActiveFilterChips, type ActiveFilterChip } from "./more-filters";
export { FilePath, SlashBreaks, type FilePathMode, type FilePathProps } from "./file-path";
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 221da4693..ca7a16eb6 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -275,11 +275,8 @@
"emptyTitle": "No scored commits yet",
"emptyAction": "Go to overview",
"title": "Commits",
- "description": "Every commit scored for change-risk against this repo's own history, so 'elevated' means elevated here rather than on some global curve.",
- "emptyDescription": "Every commit scored for change-risk against this repo's own history.",
+ "description": "Every commit, led by what it did to code health. Review priority from the diff's shape stays alongside as context.",
"emptyHint": "Per-commit change risk is captured on the next full index. Run a sync from the overview and the review queue fills in behind it.",
- "reviewQueueTitle": "Review queue",
- "reviewQueueDescription": "Newest first by default. Priority is a tercile of this repo's own distribution, so sorting by it shows only the top third — the filters narrow the whole repository, not the page.",
"scoreBehaviourTitle": "How the score behaves here",
"scoreBehaviourDescription": "Two views of the same model: where the cuts fall, and what commit shape lands you above them.",
"changeRisk": "Change risk",
@@ -290,7 +287,82 @@
"viewByCommit": "By commit",
"viewEvents": "Events",
"viewReview": "Review a change",
- "reviewDescription": "Pick the files a change touches to see what depends on them, what tends to change with them, and who should review."
+ "reviewDescription": "Pick the files a change touches to see what depends on them, what tends to change with them, and who should review.",
+ "listTitle": "Commit history",
+ "listDescription": "Newest first, each led by what it did to code health. The filters narrow the whole repository, not the page.",
+ "hotspotMark": "Hotspot",
+ "period": {
+ "week": "Past week",
+ "month": "Past month",
+ "quarter": "Past quarter",
+ "all": "All time",
+ "custom": "Custom range"
+ },
+ "headline": {
+ "unit": "{n, plural, one {commit made health better} other {commits made health better}}",
+ "good": "Nothing made health worse. {better, plural, one {# commit made it better} other {# commits made it better}}, resolving {resolved, plural, one {# finding} other {# findings}}.",
+ "mixed": "{worse, plural, one {# commit made it worse} other {# made it worse}}, {both} of them while also making something better. {neutral} had no health impact.",
+ "quiet": "None of the {analysed, plural, one {# analysed commit} other {# analysed commits}} changed a health finding.",
+ "empty": "No commits in this window.",
+ "unscanned": "{n} not yet analysed.",
+ "catchingUpUnit": "of {total, plural, one {# commit} other {# commits}} analysed so far",
+ "catchingUp": "Most commits in this window have not been analysed by the current analyzer yet. Recent commits come first, as updates run; the rows below show each older commit's direction from the earlier analysis."
+ },
+ "wins": {
+ "title": "Recent wins",
+ "wholeRepo": "whole repository",
+ "findingsLabel": "Findings resolved",
+ "findingsUnit": "across {commits, plural, one {# commit} other {# commits}}",
+ "findingsWhy": "Most in one commit: {subject} ({resolved}).",
+ "filesLabel": "Files got healthier",
+ "filesUnit": "score rose",
+ "filesWhy": "Biggest gain: {path}, {before} to {after}.",
+ "refactorsLabel": "Refactorings landed",
+ "refactorsUnit": "planned and done",
+ "refactorsWhy": "{symbol}: complexity {before} to {after}.",
+ "refactorsWhyPlain": "{symbol} was refactored as planned.",
+ "none": "No wins recorded in this window yet. Resolved findings, healthier files and landed refactorings show up here as they happen."
+ },
+ "filters": {
+ "impactLabel": "Health impact",
+ "all": "All",
+ "better": "Made things better",
+ "worse": "Made things worse",
+ "none": "No health impact",
+ "hotspots": "Touched hotspots",
+ "windowLabel": "Time window",
+ "week": "Past week",
+ "month": "Past month",
+ "quarter": "Past quarter",
+ "allTime": "All time",
+ "custom": "Custom",
+ "from": "From",
+ "to": "To",
+ "author": "Author email or name",
+ "area": "Area, e.g. packages/core",
+ "moreFilters": "More filters",
+ "clearAll": "Clear all",
+ "impactPending": "Counts appear as commits are analysed by the current analyzer"
+ },
+ "lede": {
+ "label": "What this commit did to code health",
+ "unitWorse": "{worse, plural, one {finding introduced or worsened} other {findings introduced or worsened}} · {better} resolved",
+ "unitBetter": "{better, plural, one {finding resolved} other {findings resolved}} · nothing made worse",
+ "unitNeutral": "findings changed",
+ "worse": "Each one is listed below by file, worst first, with the symbol and line. The prompt hands them to your agent.",
+ "improved": "Resolved {better, plural, one {# finding} other {# findings}} and made nothing worse. Nice work.",
+ "neutral": "Compared clean: nothing introduced, worsened or resolved.",
+ "stale": "An earlier analysis read the direction shown; its counts do not compare with the current analysis, so none are shown.",
+ "unknown": "This commit has not been analysed for code health yet, so the review priority below is the only signal."
+ },
+ "chips": {
+ "author": "Author: {value}",
+ "area": "Area: {value}",
+ "search": "Search: {value}",
+ "high": "High priority",
+ "fixes": "Fixes",
+ "sortRisk": "Sorted by review priority"
+ }
},
"changes": {
"description": "Every merged change on the main line, read back from git: pull and merge requests, Gerrit changes and lone commits, with the files each one landed.",
@@ -1272,9 +1344,13 @@
"commits": {
"detail": {
"title": "Review this commit",
- "promptLabel": "AI review prompt",
- "promptTitle": "AI commit review",
- "promptDescription": "A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers."
+ "fixPromptLabel": "Copy prompt to fix what this commit made worse",
+ "fixPromptTitle": "Fix what this commit made worse",
+ "fixPromptDescription": "A ready-to-paste prompt that has your AI agent fix the findings this commit introduced or made more severe, at their files and lines, without undoing the commit.",
+ "reviewPromptLabel": "Copy review prompt for your agent",
+ "reviewPromptTitle": "AI commit review",
+ "reviewPromptDescription": "A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers.",
+ "openFile": "Open file"
}
},
"coupling": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index fd021ac38..73b67f3d1 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -275,11 +275,8 @@
"emptyTitle": "尚无已评分的提交",
"emptyAction": "前往概览",
"title": "提交",
- "description": "每个提交都针对该仓库自身的历史评定了变更风险,因此「偏高」是相对本仓库偏高,而不是套用某条全局曲线。",
- "emptyDescription": "每个提交都针对该仓库自身的历史评定了变更风险。",
+ "description": "每个提交都以它对代码健康的影响为先。根据 diff 形态得出的审查优先级作为背景信息一并保留。",
"emptyHint": "每次提交的变更风险会在下一次完整索引时记录。在概览页运行一次同步,审查队列就会随之填充。",
- "reviewQueueTitle": "评审队列",
- "reviewQueueDescription": "默认按最新排序。优先级取自本仓库自身分布的三分位,因此按它排序只会显示前三分之一——筛选条件收窄的是整个仓库,而不是当前这一页。",
"scoreBehaviourTitle": "分数在这个仓库里的表现",
"scoreBehaviourDescription": "同一个模型的两种视角:分档线落在哪里,以及什么样的提交形态能让你高于这些线。",
"changeRisk": "变更风险",
@@ -290,7 +287,82 @@
"viewByCommit": "按提交",
"viewEvents": "事件",
"viewReview": "审查变更",
- "reviewDescription": "选择一次变更涉及的文件,查看依赖它们的代码、常与它们一起变更的文件,以及合适的审查者。"
+ "reviewDescription": "选择一次变更涉及的文件,查看依赖它们的代码、常与它们一起变更的文件,以及合适的审查者。",
+ "listTitle": "提交历史",
+ "listDescription": "最新的在前,每行先显示它对代码健康的影响。筛选作用于整个仓库,而不仅是当前页。",
+ "hotspotMark": "热点",
+ "period": {
+ "week": "过去一周",
+ "month": "过去一个月",
+ "quarter": "过去一个季度",
+ "all": "全部时间",
+ "custom": "自定义范围"
+ },
+ "headline": {
+ "unit": "个提交改善了代码健康",
+ "good": "没有任何提交让健康变差。{better} 个提交改善了健康,解决了 {resolved} 个问题。",
+ "mixed": "{worse} 个让健康变差,其中 {both} 个同时也改善了某些地方。{neutral} 个对健康没有影响。",
+ "quiet": "已分析的 {analysed} 个提交都没有改变任何健康问题。",
+ "empty": "此时间范围内没有提交。",
+ "unscanned": "{n} 个尚未分析。",
+ "catchingUpUnit": "/ {total} 个提交已分析",
+ "catchingUp": "此时间范围内的大多数提交尚未被当前分析器分析。最近的提交会随着更新优先分析;下面各行显示较早提交在之前分析中的方向。"
+ },
+ "wins": {
+ "title": "近期成果",
+ "wholeRepo": "整个仓库",
+ "findingsLabel": "已解决的问题",
+ "findingsUnit": "分布在 {commits} 个提交中",
+ "findingsWhy": "单个提交解决最多:{subject}({resolved})。",
+ "filesLabel": "变得更健康的文件",
+ "filesUnit": "分数上升",
+ "filesWhy": "提升最大:{path},从 {before} 到 {after}。",
+ "refactorsLabel": "已完成的重构",
+ "refactorsUnit": "按计划完成",
+ "refactorsWhy": "{symbol}:复杂度从 {before} 降到 {after}。",
+ "refactorsWhyPlain": "{symbol} 已按计划完成重构。",
+ "none": "此时间范围内还没有记录到成果。已解决的问题、变得更健康的文件和完成的重构会在发生时显示在这里。"
+ },
+ "filters": {
+ "impactLabel": "健康影响",
+ "all": "全部",
+ "better": "让情况变好",
+ "worse": "让情况变差",
+ "none": "对健康无影响",
+ "hotspots": "涉及热点",
+ "windowLabel": "时间范围",
+ "week": "过去一周",
+ "month": "过去一个月",
+ "quarter": "过去一个季度",
+ "allTime": "全部时间",
+ "custom": "自定义",
+ "from": "从",
+ "to": "到",
+ "author": "作者邮箱或姓名",
+ "area": "区域,例如 packages/core",
+ "moreFilters": "更多筛选",
+ "clearAll": "全部清除",
+ "impactPending": "随着当前分析器分析提交,计数会陆续出现"
+ },
+ "lede": {
+ "label": "此提交对代码健康的影响",
+ "unitWorse": "个问题新增或恶化 · 已解决 {better} 个",
+ "unitBetter": "个问题已解决 · 没有让任何地方变差",
+ "unitNeutral": "个问题发生变化",
+ "worse": "下面按文件列出每个问题,最严重的在前,并附有符号和行号。提示词会把它们交给你的智能体。",
+ "improved": "解决了 {better} 个问题,且没有让任何地方变差。干得好。",
+ "neutral": "比较结果干净:没有新增、恶化或解决任何问题。",
+ "stale": "较早的分析给出了所示的方向;其数量无法与当前分析比较,因此不予显示。",
+ "unknown": "此提交还没有进行代码健康分析,因此下面的审查优先级是唯一的信号。"
+ },
+ "chips": {
+ "author": "作者:{value}",
+ "area": "区域:{value}",
+ "search": "搜索:{value}",
+ "high": "高优先级",
+ "fixes": "修复",
+ "sortRisk": "按审查优先级排序"
+ }
},
"changes": {
"description": "主线上每个已合并的变更,均从 git 历史读取:拉取请求、合并请求、Gerrit 变更和单独提交,以及每个变更带入的文件。",
@@ -1272,9 +1344,13 @@
"commits": {
"detail": {
"title": "审阅这次提交",
- "promptLabel": "AI 审阅提示词",
- "promptTitle": "AI 提交审阅",
- "promptDescription": "一段可直接粘贴的提示词,让 AI 智能体审阅这次提交的变更风险、标出需要重点核查之处,并推荐审阅人。"
+ "fixPromptLabel": "复制提示词,修复此提交带来的问题",
+ "fixPromptTitle": "修复此提交带来的问题",
+ "fixPromptDescription": "一段可直接粘贴的提示词,让你的 AI 智能体在对应的文件和行修复此提交引入或加重的问题,而不撤销该提交。",
+ "reviewPromptLabel": "复制审查提示词给你的智能体",
+ "reviewPromptTitle": "AI 提交审查",
+ "reviewPromptDescription": "一段可直接粘贴的提示词,让你的 AI 智能体审查此提交的变更风险,指出需要仔细检查的地方,并推荐审查者。",
+ "openFile": "打开文件"
}
},
"coupling": {
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
index 8c474653f..842801e90 100644
--- a/packages/web/src/app/repos/[id]/commits/page.tsx
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -1,205 +1,61 @@
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 { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-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 { CommitsViewToggle } from "@/components/commits/commits-view-toggle";
import { ByChangeView, type ByChangeParams } from "@/components/commits/by-change-view";
+import { CommitsView } from "@/components/commits/commits-view";
import { EventsView } from "@/components/commits/events-view";
import { ImpactTab } from "@/components/risk/impact-tab";
import { parseCommitsView } from "@/lib/changes";
-import {
- getAgentTrend,
- getCommitEvolution,
- getCommitStats,
- getCommitsPage,
-} from "@/lib/api/git";
import { getTranslations } from "next-intl/server";
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.
- *
- * `?view=changes` swaps all of that for the history grouped by merged change
- * (`ByChangeView`), `?view=events` for what moved between index runs
- * (`EventsView`), `?view=review` for a change's blast radius before it lands
- * (`ImpactTab`, once Code Health's blast-radius tab); the commit view stays
- * the default.
+ * The Commits page: one shell, one view at a time. The commit view
+ * (`CommitsView`) is the default and leads with what the work did to code
+ * health; `?view=changes` groups the history by merged change
+ * (`ByChangeView`), `?view=events` lists what moved between index runs
+ * (`EventsView`), `?view=review` shows a change's blast radius before it
+ * lands (`ImpactTab`). Each view is a server component; what stays interactive is
+ * small islands sharing state through the URL.
*/
export default async function CommitsPage({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
- searchParams: Promise<ByChangeParams & { view?: string }>;
+ searchParams: Promise<ByChangeParams & Record<string, string | string[] | undefined>>;
}) {
const { id } = await params;
const sp = await searchParams;
const view = parseCommitsView(sp.view);
- const base = `/repos/${id}`;
const t = await getTranslations("views.commits");
- const toggle = <CommitsViewToggle repoId={id} view={view} />;
-
- if (view === "changes") {
- const tc = await getTranslations("views.changes");
- return (
- <PageShell
- icon={<GitCommitHorizontal />}
- title={t("title")}
- description={tc("description")}
- actions={toggle}
- >
- <ByChangeView repoId={id} params={sp} />
- </PageShell>
- );
- }
-
- if (view === "events") {
- const te = await getTranslations("views.events");
- return (
- <PageShell
- icon={<GitCommitHorizontal />}
- title={t("title")}
- description={te("description")}
- actions={toggle}
- >
- <EventsView repoId={id} />
- </PageShell>
- );
- }
-
- if (view === "review") {
- return (
- <PageShell
- icon={<GitCommitHorizontal />}
- title={t("title")}
- description={t("reviewDescription")}
- actions={toggle}
- >
- <ImpactTab repoId={id} />
- </PageShell>
- );
- }
-
- // 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: "date", 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 />}
- title={t("title")}
- description={t("emptyDescription")}
- actions={toggle}
- >
- <EmptyState
- title={t("emptyTitle")}
- description={t("emptyHint")}
- action={{ label: t("emptyAction"), href: `${base}/overview` }}
- />
- </PageShell>
- );
- }
+ const description =
+ view === "changes"
+ ? (await getTranslations("views.changes"))("description")
+ : view === "events"
+ ? (await getTranslations("views.events"))("description")
+ : view === "review"
+ ? t("reviewDescription")
+ : t("description");
return (
<PageShell
icon={<GitCommitHorizontal />}
title={t("title")}
- description={t("description")}
- actions={toggle}
+ description={description}
+ actions={<CommitsViewToggle repoId={id} view={view} />}
>
- {stats && <CommitsLede stats={stats} base={base} LinkComponent={Link} />}
-
- {evolution && evolution.total_commits > 0 && (
- <OverviewSection
- title={t("evolutionTitle")}
- description={t("evolutionDescription")}
- >
- <CodeEvolutionChart evolution={evolution} />
- </OverviewSection>
+ {view === "changes" ? (
+ <ByChangeView repoId={id} params={sp} />
+ ) : view === "events" ? (
+ <EventsView repoId={id} />
+ ) : view === "review" ? (
+ <ImpactTab repoId={id} />
+ ) : (
+ <CommitsView repoId={id} searchParams={sp} />
)}
-
- {trend && trend.enabled && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
-
- <OverviewSection
- title={t("reviewQueueTitle")}
- description={t("reviewQueueDescription")}
- action={<CredibilityInfoButton />}
- >
- <CommitQueue
- repoId={id}
- initial={firstPage}
- total={total}
- attributionEnabled={trend?.enabled !== false}
- counts={
- stats
- ? {
- all: stats.total_commits,
- high: stats.high_priority_count,
- fixes: stats.fix_commit_count,
- }
- : undefined
- }
- />
- </OverviewSection>
-
- <OverviewSection
- title={t("scoreBehaviourTitle")}
- description={t("scoreBehaviourDescription")}
- action={
- <SectionLink href={`${base}/code-health`} LinkComponent={Link}>
- {t("changeRisk")}
- </SectionLink>
- }
- >
- <CommitDistribution stats={stats} recent={recent?.items ?? []} />
- </OverviewSection>
-
- <CommitDetailSheet repoId={id} />
</PageShell>
);
}
diff --git a/packages/web/src/components/changes/change-health.tsx b/packages/web/src/components/changes/change-health.tsx
index ea8a453eb..798908b47 100644
--- a/packages/web/src/components/changes/change-health.tsx
+++ b/packages/web/src/components/changes/change-health.tsx
@@ -1,10 +1,9 @@
import type { ReactNode } from "react";
import { getTranslations } from "next-intl/server";
-import { PageLede } from "@repowise-dev/ui/shared/page-lede";
import { OverviewSection } from "@repowise-dev/ui/overview";
import { FindingsByFile } from "@repowise-dev/ui/commits/findings-by-file";
-import { HealthDeltaMark } from "@repowise-dev/ui/commits/health-delta-mark";
-import { betterCount, healthDeltaKind, worseCount } from "@repowise-dev/ui/commits/health-delta";
+import { HealthDeltaLede } from "@repowise-dev/ui/commits/health-delta-lede";
+import { worseCount } from "@repowise-dev/ui/commits/health-delta";
import type { ChangePromptInput } from "@repowise-dev/ui/health/ai-prompt-builder";
import type { ChangeHealthResponse } from "@repowise-dev/types/history";
import { filePromptInput, healthDeltaLabels } from "@/lib/changes";
@@ -16,45 +15,31 @@ type Health = ChangeHealthResponse | null | undefined;
* The change page's lede, figure first: how many findings the change made
* worse (or, when it only helped, how many it resolved), the dot-and-word
* mark beside it, one reading, and the primary action when there is work to
- * hand over. A change none of whose commits was analysed says so.
+ * hand over. A change none of whose commits was analysed says so. The shared
+ * `HealthDeltaLede` draws it; the commit sheet uses the same one.
*/
export async function ChangeHealthLede({ health, action }: { health: Health; action?: ReactNode }) {
const t = await getTranslations("views.changes");
- const labels = healthDeltaLabels(t);
- if (!health) {
- return (
- <PageLede
- label={t("verdictLabel")}
- value="—"
- badge={<HealthDeltaMark delta={null} labels={labels} />}
- action={action}
- >
- <p>{t("verdictUnknown")}</p>
- </PageLede>
- );
- }
- const kind = healthDeltaKind(health);
- const better = betterCount(health);
- const worse = worseCount(health);
- const lead =
- kind === "improved"
- ? { value: better, unit: t("ledeUnitBetter", { better }), reading: t("verdictImproved", { better }) }
- : kind === "neutral"
- ? { value: 0, unit: t("ledeUnitNeutral"), reading: t("verdictNeutral") }
- : { value: worse, unit: t("ledeUnitWorse", { worse, better }), reading: t("verdictWorseReading") };
return (
- <PageLede
- label={t("verdictLabel")}
- value={String(lead.value)}
- unit={lead.unit}
- badge={<HealthDeltaMark delta={health} labels={labels} figures={false} />}
+ <HealthDeltaLede
+ delta={health ?? null}
+ markLabels={healthDeltaLabels(t)}
action={action}
+ copy={{
+ label: t("verdictLabel"),
+ unitWorse: (worse, better) => t("ledeUnitWorse", { worse, better }),
+ unitBetter: (better) => t("ledeUnitBetter", { better }),
+ unitNeutral: t("ledeUnitNeutral"),
+ worse: t("verdictWorseReading"),
+ improved: (better) => t("verdictImproved", { better }),
+ neutral: t("verdictNeutral"),
+ unknown: t("verdictUnknown"),
+ }}
>
- <p>{lead.reading}</p>
- {health.status === "partial" && (
+ {health?.status === "partial" && (
<p>{t("verdictPartial", { unscanned: health.unscanned_commits })}</p>
)}
- </PageLede>
+ </HealthDeltaLede>
);
}
diff --git a/packages/web/src/components/commits/commit-detail-sheet.tsx b/packages/web/src/components/commits/commit-detail-sheet.tsx
index fb4a25d39..eb90c7e9d 100644
--- a/packages/web/src/components/commits/commit-detail-sheet.tsx
+++ b/packages/web/src/components/commits/commit-detail-sheet.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import Link from "next/link";
import useSWR from "swr";
import { useQueryState } from "nuqs";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
@@ -11,21 +12,34 @@ import {
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 { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import {
+ AiPromptButton,
+ AiPromptModal,
+ buildChangeAiPrompt,
+ buildCommitAiPrompt,
+} from "@repowise-dev/ui/health";
import { getCommit } from "@/lib/api/git";
import { getRiskRange } from "@/lib/api/risk";
+import { commitFixPromptInput, commitReviewPromptInput } from "@/lib/commit-prompt";
import { useTranslations } from "next-intl";
+import { useCommitLedeCopy, useHealthDeltaLabels } from "./history-labels";
/**
* The commit detail drawer, driven entirely by `?commit=`.
*
- * Its own island so the queue and the scatter can both open it without a
+ * Its own island so the list 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
+ * 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.
+ *
+ * Its one filled action is the agent prompt: fix what the commit made worse
+ * when it made something worse, otherwise review it.
*/
export function CommitDetailSheet({ repoId }: { repoId: string }) {
const t = useTranslations("commits");
+ const healthLabels = useHealthDeltaLabels();
+ const ledeCopy = useCommitLedeCopy();
const [selectedSha, setSelectedSha] = useQueryState("commit");
const [promptOpen, setPromptOpen] = useState(false);
@@ -47,6 +61,9 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
+ const fix = detail ? commitFixPromptInput(detail) : null;
+ const copy = fix ? "fix" : "review";
+
return (
<>
<Sheet
@@ -64,22 +81,24 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {
<Skeleton className="h-40 w-full" />
</div>
) : (
- <>
- <div className="flex justify-end pt-1 pb-3">
+ <CommitDetailCard
+ className="pt-1"
+ commit={detail}
+ healthLabels={healthLabels}
+ ledeCopy={ledeCopy}
+ fileHref={(path) => `${fileEntityPath(`/repos/${repoId}`, path)}?tab=health`}
+ openFileLabel={t("detail.openFile")}
+ LinkComponent={Link}
+ action={
<AiPromptButton
- label={t("detail.promptLabel")}
+ label={t(`detail.${copy}PromptLabel`)}
onClick={() => setPromptOpen(true)}
/>
- </div>
- <CommitDetailCard
- commit={detail}
- fixPercentile={
- range?.fix_history?.available
- ? range.fix_history.percentile
- : null
- }
- />
- </>
+ }
+ fixPercentile={
+ range?.fix_history?.available ? range.fix_history.percentile : null
+ }
+ />
)}
</div>
</SheetContent>
@@ -91,25 +110,9 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {
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,
- })
+ fix
+ ? buildChangeAiPrompt({ change: fix, flavor })
+ : buildCommitAiPrompt({ commit: commitReviewPromptInput(detail), flavor })
: null
}
filePath={detail ? detail.short_sha : null}
@@ -118,8 +121,8 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {
? { kind: "commit", label: detail.short_sha, target: detail.sha, targetKind: "commit" }
: undefined
}
- title={t("detail.promptTitle")}
- description={t("detail.promptDescription")}
+ title={t(`detail.${copy}PromptTitle`)}
+ description={t(`detail.${copy}PromptDescription`)}
/>
</>
);
diff --git a/packages/web/src/components/commits/commit-filter-chips.ts b/packages/web/src/components/commits/commit-filter-chips.ts
new file mode 100644
index 000000000..e97c6c6cd
--- /dev/null
+++ b/packages/web/src/components/commits/commit-filter-chips.ts
@@ -0,0 +1,52 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import type { ActiveFilterChip } from "@repowise-dev/ui/shared/more-filters";
+import type { HistoryFilterValue } from "@repowise-dev/ui/commits/history-filters";
+import type { CommitListQuery } from "./use-commit-pages";
+
+/**
+ * Every secondary filter on the commit list (author, area, search, review
+ * priority, sort) as a removable chip, plus the one action that clears them
+ * all. The primary row (impact, hotspots, window) is never a chip: it is
+ * always visible.
+ */
+export function useCommitFilterChips({
+ filters,
+ search,
+ query,
+ applyFilters,
+ setSearch,
+ refine,
+}: {
+ filters: HistoryFilterValue;
+ search: string;
+ query: CommitListQuery;
+ applyFilters: (patch: Partial<HistoryFilterValue>) => void;
+ setSearch: (value: string) => void;
+ refine: (patch: Partial<CommitListQuery>) => void;
+}): { chips: ActiveFilterChip[]; clearAll: () => void } {
+ const t = useTranslations("views.commits.chips");
+ const chips: ActiveFilterChip[] = [];
+ if (filters.author) {
+ chips.push({ key: "author", label: t("author", { value: filters.author }), onRemove: () => applyFilters({ author: undefined }) });
+ }
+ if (filters.area) {
+ chips.push({ key: "area", label: t("area", { value: filters.area }), onRemove: () => applyFilters({ area: undefined }) });
+ }
+ if (search.trim()) {
+ chips.push({ key: "search", label: t("search", { value: search.trim() }), onRemove: () => setSearch("") });
+ }
+ if (query.kind !== "all") {
+ chips.push({ key: "kind", label: t(query.kind), onRemove: () => refine({ kind: "all" }) });
+ }
+ if (query.sort !== "date") {
+ chips.push({ key: "sort", label: t("sortRisk"), onRemove: () => refine({ sort: "date" }) });
+ }
+ const clearAll = () => {
+ setSearch("");
+ refine({ kind: "all", sort: "date" });
+ if (filters.author || filters.area) applyFilters({ author: undefined, area: undefined });
+ };
+ return { chips, clearAll };
+}
diff --git a/packages/web/src/components/commits/commit-queue.tsx b/packages/web/src/components/commits/commit-queue.tsx
index 845e7e02d..5c01633cf 100644
--- a/packages/web/src/components/commits/commit-queue.tsx
+++ b/packages/web/src/components/commits/commit-queue.tsx
@@ -1,117 +1,116 @@
"use client";
-import { useMemo, useState } from "react";
-import useSWRInfinite from "swr/infinite";
+import { useState, useTransition } from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useQueryState } from "nuqs";
+import { useTranslations } from "next-intl";
import {
- CommitTable,
- type CommitAuthorship,
- type CommitKind,
- type CommitSort,
+ CommitKindControl,
+ CommitList,
+ CommitSearch,
+ CommitSortControl,
} from "@repowise-dev/ui/commits/commit-table";
-import { getCommitsPage } from "@/lib/api/git";
+import {
+ HistoryFilters,
+ type HealthImpact,
+ type HistoryFilterValue,
+} from "@repowise-dev/ui/commits/history-filters";
+import type { HistoryFilters as ApiHistoryFilters } from "@repowise-dev/types/history";
import type { CommitResponse, Paginated } from "@/lib/api/types";
-
-const PAGE_SIZE = 50;
+import { commitFiltersQuery } from "@/lib/commit-filters";
+import { useHealthDeltaLabels, useHistoryFilterLabels } from "./history-labels";
+import { useCommitFilterChips } from "./commit-filter-chips";
+import { useCommitPages, type CommitListQuery } from "./use-commit-pages";
/**
- * The review queue: the one part of this page that genuinely needs client
- * state. Sort, the filters 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.
+ * The commit list: impact, hotspots and window in one row; author, area,
+ * search, review priority and sort behind "More filters", each active one a
+ * removable chip; then every commit led by what it did to code health.
*
- * Pages accumulate through `offset` rather than by growing `limit`, so the
- * whole history is reachable: the endpoint caps a single page at 200, which
- * used to be the ceiling on everything the queue could ever show.
+ * The history filters are URL state and server-driven: a change writes the
+ * query string and the page re-renders on the server, so the headline, the
+ * wins and this list's first page arrive together. `apiFilters` is that
+ * server's reading of the URL, passed down so later pages ask for the same
+ * range. Search, review priority and sort stay local refinements. Selecting a
+ * row writes `?commit=` for the detail sheet, a separate island.
*/
export function CommitQueue({
repoId,
initial,
- total,
counts,
- attributionEnabled = true,
+ filters,
+ apiFilters,
+ impactCounts,
+ narrowed,
+ impactPending,
}: {
repoId: string;
initial: Paginated<CommitResponse>;
- total: number;
- /** Repo-wide chip counts, from the stats endpoint the page already fetches. */
+ /** Repo-wide review-priority counts; only meaningful when nothing narrows the list. */
counts?: { all: number; high: number; fixes: number } | undefined;
- /** False when AI attribution is off for the repo: no authorship filter. */
- attributionEnabled?: boolean;
+ filters: HistoryFilterValue;
+ apiFilters: ApiHistoryFilters;
+ /** Per-impact counts under the other filters, from the period summary. */
+ impactCounts?: Record<HealthImpact, number> | undefined;
+ narrowed: boolean;
+ /** Most of the window is not analysed yet; the impact options wait. */
+ impactPending?: boolean | undefined;
}) {
- const [sort, setSort] = useState<CommitSort>("date");
- const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
- const [kind, setKind] = useState<CommitKind>("all");
+ const [query, setQuery] = useState<CommitListQuery>({ sort: "date", kind: "all" });
+ const [search, setSearch] = useState("");
const [, setSelectedSha] = useQueryState("commit");
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+ const [pending, startTransition] = useTransition();
+ const t = useTranslations("views.commits");
+ const healthLabels = useHealthDeltaLabels();
+ const filterLabels = useHistoryFilterLabels();
+ const pages = useCommitPages(repoId, apiFilters, query, initial);
- const pristine = sort === "date" && authorship === "all" && kind === "all";
-
- const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<
- Paginated<CommitResponse>
- >(
- (pageIndex, previous) => {
- if (previous && !previous.has_more) return null;
- return `commits:${repoId}:${sort}:${authorship}:${kind}:${pageIndex}`;
- },
- (key) => {
- const pageIndex = parseInt(key.split(":").pop() as string, 10);
- return getCommitsPage(repoId, {
- sort,
- authorship,
- kind,
- limit: PAGE_SIZE,
- offset: pageIndex * PAGE_SIZE,
- });
- },
- {
- revalidateOnFocus: false,
- revalidateFirstPage: false,
- keepPreviousData: true,
- // The first page is server-rendered, so an untouched queue fetches nothing.
- fallbackData: pristine ? [initial] : undefined,
- revalidateOnMount: !pristine,
- },
- );
-
- const list = useMemo(
- () => (data ? data.flatMap((p) => p.items) : initial.items),
- [data, initial.items],
- );
- const loadedTotal = data && data.length > 0 ? data[0].total : total;
- const hasMore = data ? !!data[data.length - 1]?.has_more : initial.has_more;
-
- // Every filter change resets to one page; SWRInfinite keeps `size` across
- // key changes otherwise, which would refetch every page of the new filter.
- const reset = () => void setSize(1);
+ const refine = (patch: Partial<CommitListQuery>) => {
+ setQuery((q) => ({ ...q, ...patch }));
+ pages.reset();
+ };
+ const applyFilters = (patch: Partial<HistoryFilterValue>) => {
+ const next = commitFiltersQuery(new URLSearchParams(searchParams.toString()), patch);
+ pages.reset();
+ startTransition(() => router.replace(next ? `${pathname}?${next}` : pathname, { scroll: false }));
+ };
+ const { chips, clearAll } = useCommitFilterChips({ filters, search, query, applyFilters, setSearch, refine });
return (
- <CommitTable
- commits={list}
- sort={sort}
- onSortChange={(s) => {
- setSort(s);
- reset();
- }}
- authorship={authorship}
- onAuthorshipChange={
- attributionEnabled
- ? (a) => {
- setAuthorship(a);
- reset();
- }
- : undefined
- }
- kind={kind}
- onKindChange={(k) => {
- setKind(k);
- reset();
- }}
- counts={counts}
- onSelect={(c) => void setSelectedSha(c.sha)}
- total={loadedTotal}
- hasMore={hasMore}
- loadingMore={isValidating && !isLoading}
- onLoadMore={() => void setSize((n) => n + 1)}
- />
+ <div className="space-y-4">
+ <HistoryFilters
+ value={filters}
+ onChange={applyFilters}
+ counts={impactCounts}
+ labels={filterLabels}
+ chips={chips}
+ onClearAll={clearAll}
+ impactPending={impactPending}
+ more={
+ <>
+ <CommitSearch value={search} onChange={setSearch} />
+ <CommitKindControl value={query.kind} onChange={(kind) => refine({ kind })} counts={counts} />
+ <CommitSortControl value={query.sort} onChange={(sort) => refine({ sort })} />
+ </>
+ }
+ />
+ <div aria-busy={pending} className={pending ? "opacity-60 transition-opacity" : undefined}>
+ <CommitList
+ commits={pages.commits}
+ search={search}
+ narrowed={narrowed || query.kind !== "all"}
+ onSelect={(c) => void setSelectedSha(c.sha)}
+ total={pages.total}
+ hasMore={pages.hasMore}
+ loadingMore={pages.loadingMore}
+ onLoadMore={pages.loadMore}
+ healthLabels={healthLabels}
+ hotspotLabel={t("hotspotMark")}
+ />
+ </div>
+ </div>
);
}
diff --git a/packages/web/src/components/commits/commits-period.tsx b/packages/web/src/components/commits/commits-period.tsx
new file mode 100644
index 000000000..8238a5181
--- /dev/null
+++ b/packages/web/src/components/commits/commits-period.tsx
@@ -0,0 +1,91 @@
+import Link from "next/link";
+import { getTranslations } from "next-intl/server";
+import {
+ PeriodHealthHeadline,
+ type PeriodHealthCopy,
+} from "@repowise-dev/ui/commits/period-health-headline";
+import { RecentWins, type RecentWinsCopy } from "@repowise-dev/ui/commits/recent-wins";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import type { HistoryFilterValue } from "@repowise-dev/ui/commits/history-filters";
+import type { PeriodHealthSummaryResponse, WinsResponse } from "@repowise-dev/types/history";
+import { effectiveWindow } from "@/lib/commit-filters";
+
+async function headlineCopy(): Promise<PeriodHealthCopy> {
+ const t = await getTranslations("views.commits.headline");
+ return {
+ unit: (r) => t("unit", { n: r.better }),
+ good: (r) => t("good", { better: r.better, resolved: r.findingsBetter }),
+ mixed: (r) => t("mixed", { better: r.better, worse: r.worse, both: r.both, neutral: r.neutral }),
+ quiet: (r) => t("quiet", { analysed: r.analysed }),
+ catchingUpUnit: (r) => t("catchingUpUnit", { total: r.total }),
+ catchingUp: () => t("catchingUp"),
+ empty: () => t("empty"),
+ unscanned: (r) => t("unscanned", { n: r.unscanned }),
+ };
+}
+
+async function winsCopy(): Promise<RecentWinsCopy> {
+ const t = await getTranslations("views.commits.wins");
+ return {
+ title: t("title"),
+ findingsLabel: t("findingsLabel"),
+ findingsUnit: (commits) => t("findingsUnit", { commits }),
+ findingsWhy: (subject, resolved) => t("findingsWhy", { subject, resolved }),
+ filesLabel: t("filesLabel"),
+ filesUnit: t("filesUnit"),
+ filesWhy: (path, before, after) =>
+ t("filesWhy", { path, before: before.toFixed(1), after: after.toFixed(1) }),
+ refactorsLabel: t("refactorsLabel"),
+ refactorsUnit: t("refactorsUnit"),
+ refactorsWhy: (symbol, before, after) =>
+ before != null && after != null
+ ? t("refactorsWhy", { symbol, before, after })
+ : t("refactorsWhyPlain", { symbol }),
+ none: t("none"),
+ };
+}
+
+/**
+ * The commit view's lede: the period headline (improvements first) beside the
+ * window's wins. Both describe the selected window; the headline also follows
+ * author, area and hotspots, the wins follow the author only, and their scope
+ * line says so.
+ */
+export async function CommitsPeriod({
+ repoId,
+ filters,
+ summary,
+ wins,
+}: {
+ repoId: string;
+ filters: HistoryFilterValue;
+ summary: PeriodHealthSummaryResponse | null;
+ wins: WinsResponse | null;
+}) {
+ if (!summary && !wins) return null;
+ const t = await getTranslations("views.commits");
+ const base = `/repos/${repoId}`;
+ const period = t(`period.${effectiveWindow(filters)}`);
+ const scope = [period, filters.author, filters.area || filters.hotspots ? t("wins.wholeRepo") : null]
+ .filter(Boolean)
+ .join(" · ");
+
+ return (
+ <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">
+ {summary ? <PeriodHealthHeadline summary={summary} period={period} copy={await headlineCopy()} /> : <div />}
+ {wins && (
+ <RecentWins
+ wins={wins}
+ scope={scope}
+ LinkComponent={Link}
+ routes={{
+ commit: (sha) => `${base}/commits?commit=${sha}`,
+ file: (path) => `${fileEntityPath(base, path)}?tab=health`,
+ refactorings: `${base}/refactoring`,
+ }}
+ copy={await winsCopy()}
+ />
+ )}
+ </section>
+ );
+}
diff --git a/packages/web/src/components/commits/commits-view.tsx b/packages/web/src/components/commits/commits-view.tsx
new file mode 100644
index 000000000..7d3474ed9
--- /dev/null
+++ b/packages/web/src/components/commits/commits-view.tsx
@@ -0,0 +1,153 @@
+import Link from "next/link";
+import { getTranslations } from "next-intl/server";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
+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 { readPeriodHealth } from "@repowise-dev/ui/commits/period-health";
+import type { PeriodHealthSummaryResponse } from "@repowise-dev/types/history";
+import { CommitQueue } from "./commit-queue";
+import { CommitDetailSheet } from "./commit-detail-sheet";
+import { CommitDistribution } from "./commit-distribution";
+import { CommitsPeriod } from "./commits-period";
+import { historyFilters, isNarrowed, parseCommitFilters } from "@/lib/commit-filters";
+import {
+ getAgentTrend,
+ getCommitEvolution,
+ getCommitHealthSummary,
+ getCommitStats,
+ getCommitsPage,
+} from "@/lib/api/git";
+import { getWins } from "@/lib/api/history";
+
+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;
+const WINS_TOP = 3;
+
+async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
+ try {
+ return await fn();
+ } catch {
+ return null;
+ }
+}
+
+/** Quick-filter sizes from the period summary, under every other filter. */
+function impactCounts(summary: PeriodHealthSummaryResponse | null) {
+ if (!summary) return undefined;
+ const r = readPeriodHealth(summary);
+ return { all: summary.total, better: r.better, worse: r.worse, none: r.neutral };
+}
+
+/**
+ * The commit view: what the work did to code health first.
+ *
+ * The period headline (improvements first) beside the window's wins, then
+ * every commit led by its better/worse chip under the history filters, then
+ * the diff-shape charts as context. The history filters live in the URL and
+ * are read here, so the headline, the wins and the list's first page come
+ * from one fetch wave for the same filters.
+ */
+export async function CommitsView({
+ repoId,
+ searchParams,
+}: {
+ repoId: string;
+ searchParams: Record<string, string | string[] | undefined>;
+}) {
+ const t = await getTranslations("views.commits");
+ const base = `/repos/${repoId}`;
+ const filters = parseCommitFilters(searchParams);
+ const now = new Date();
+ const apiFilters = historyFilters(filters, now);
+ const narrowed = isNarrowed(filters);
+ // Wins follow the window and the author only; the scope line says so.
+ const winsRange = historyFilters({ ...filters, impact: "all", hotspots: false, area: undefined }, now);
+
+ // One wave. The scatter plots its own repo-wide recency sample: it explains
+ // the scoring model, not the filtered list. The summary leaves the impact
+ // filter out so the quick filters keep every option's size.
+ const [stats, evolution, trend, firstPage, recent, summary, wins] = await Promise.all([
+ safeFetch(() => getCommitStats(repoId)),
+ safeFetch(() => getCommitEvolution(repoId)),
+ safeFetch(() => getAgentTrend(repoId)),
+ safeFetch(() =>
+ getCommitsPage(repoId, { ...apiFilters, sort: "date", authorship: "all", limit: PAGE_SIZE }),
+ ),
+ safeFetch(() => getCommitsPage(repoId, { sort: "date", limit: SCATTER_SAMPLE })),
+ safeFetch(() => getCommitHealthSummary(repoId, historyFilters(filters, now, { withImpact: false }))),
+ // `/wins` defaults to the past 30 days; all time asks from the epoch.
+ safeFetch(() =>
+ getWins(repoId, {
+ since: winsRange.since ?? new Date(0).toISOString(),
+ ...(winsRange.until ? { until: winsRange.until } : {}),
+ ...(winsRange.author ? { author: winsRange.author } : {}),
+ top: WINS_TOP,
+ }),
+ ),
+ ]);
+
+ if (!firstPage || (stats?.total_commits ?? firstPage.total) === 0) {
+ return (
+ <EmptyState
+ title={t("emptyTitle")}
+ description={t("emptyHint")}
+ action={{ label: t("emptyAction"), href: `${base}/overview` }}
+ />
+ );
+ }
+
+ return (
+ <>
+ <CommitsPeriod repoId={repoId} filters={filters} summary={summary} wins={wins} />
+
+ <OverviewSection
+ title={t("listTitle")}
+ description={t("listDescription")}
+ action={<CredibilityInfoButton />}
+ >
+ <CommitQueue
+ repoId={repoId}
+ initial={firstPage}
+ filters={filters}
+ apiFilters={apiFilters}
+ narrowed={narrowed}
+ impactCounts={impactCounts(summary)}
+ impactPending={summary ? readPeriodHealth(summary).tone === "catchingUp" : false}
+ // Repo-wide figures: shown only when nothing narrows the list, so a
+ // chip never counts a different set than the one beneath it.
+ counts={
+ stats && !narrowed
+ ? { all: stats.total_commits, high: stats.high_priority_count, fixes: stats.fix_commit_count }
+ : undefined
+ }
+ />
+ </OverviewSection>
+
+ {evolution && evolution.total_commits > 0 && (
+ <OverviewSection title={t("evolutionTitle")} description={t("evolutionDescription")}>
+ <CodeEvolutionChart evolution={evolution} />
+ </OverviewSection>
+ )}
+
+ {trend && trend.enabled && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
+
+ <OverviewSection
+ title={t("scoreBehaviourTitle")}
+ description={t("scoreBehaviourDescription")}
+ action={
+ <SectionLink href={`${base}/code-health?tab=triage`} LinkComponent={Link}>
+ {t("changeRisk")}
+ </SectionLink>
+ }
+ >
+ <CommitDistribution stats={stats} recent={recent?.items ?? []} />
+ </OverviewSection>
+
+ <CommitDetailSheet repoId={repoId} />
+ </>
+ );
+}
diff --git a/packages/web/src/components/commits/history-labels.ts b/packages/web/src/components/commits/history-labels.ts
new file mode 100644
index 000000000..8567786de
--- /dev/null
+++ b/packages/web/src/components/commits/history-labels.ts
@@ -0,0 +1,62 @@
+"use client";
+
+import { useMemo } from "react";
+import { useTranslations } from "next-intl";
+import type { HealthDeltaLabels } from "@repowise-dev/ui/commits/health-delta-mark";
+import type { HealthDeltaLedeCopy } from "@repowise-dev/ui/commits/health-delta-lede";
+import type { HistoryFilterLabels } from "@repowise-dev/ui/commits/history-filters";
+import { healthDeltaLabels } from "@/lib/changes";
+
+/** The health mark's words: the same ones the change records use. */
+export function useHealthDeltaLabels(): HealthDeltaLabels {
+ const t = useTranslations("views.changes");
+ return useMemo(() => healthDeltaLabels(t), [t]);
+}
+
+/** The commit sheet's lede, worded for one commit. */
+export function useCommitLedeCopy(): HealthDeltaLedeCopy {
+ const t = useTranslations("views.commits.lede");
+ return useMemo(
+ () => ({
+ label: t("label"),
+ unitWorse: (worse, better) => t("unitWorse", { worse, better }),
+ unitBetter: (better) => t("unitBetter", { better }),
+ unitNeutral: t("unitNeutral"),
+ worse: t("worse"),
+ improved: (better) => t("improved", { better }),
+ neutral: t("neutral"),
+ stale: t("stale"),
+ unknown: t("unknown"),
+ }),
+ [t],
+ );
+}
+
+/** The quick filters' words, translated. */
+export function useHistoryFilterLabels(): HistoryFilterLabels {
+ const t = useTranslations("views.commits.filters");
+ return useMemo(
+ () => ({
+ impactLabel: t("impactLabel"),
+ all: t("all"),
+ better: t("better"),
+ worse: t("worse"),
+ none: t("none"),
+ hotspots: t("hotspots"),
+ windowLabel: t("windowLabel"),
+ week: t("week"),
+ month: t("month"),
+ quarter: t("quarter"),
+ allTime: t("allTime"),
+ custom: t("custom"),
+ from: t("from"),
+ to: t("to"),
+ author: t("author"),
+ area: t("area"),
+ moreFilters: t("moreFilters"),
+ clearAll: t("clearAll"),
+ impactPending: t("impactPending"),
+ }),
+ [t],
+ );
+}
diff --git a/packages/web/src/components/commits/use-commit-pages.ts b/packages/web/src/components/commits/use-commit-pages.ts
new file mode 100644
index 000000000..fc7504a54
--- /dev/null
+++ b/packages/web/src/components/commits/use-commit-pages.ts
@@ -0,0 +1,73 @@
+"use client";
+
+import { useMemo } from "react";
+import useSWRInfinite from "swr/infinite";
+import type { CommitKind, CommitSort } from "@repowise-dev/ui/commits/commit-table";
+import type { HistoryFilters } from "@repowise-dev/types/history";
+import { getCommitsPage } from "@/lib/api/git";
+import type { CommitResponse, Paginated } from "@/lib/api/types";
+
+const PAGE_SIZE = 50;
+
+/** The list's own refinements. No authorship: agent-vs-human is never a
+ * filter on this page. */
+export interface CommitListQuery {
+ sort: CommitSort;
+ kind: CommitKind;
+}
+
+/**
+ * The commit list's pages for one query. Pages accumulate through `offset`, so
+ * the whole history is reachable past the endpoint's 200-row cap. `initial`
+ * is the server's first page for these `filters` at the default query, so an
+ * untouched list fetches nothing, including after a filter change re-renders
+ * the server with the new first page.
+ */
+export function useCommitPages(
+ repoId: string,
+ filters: HistoryFilters,
+ query: CommitListQuery,
+ initial: Paginated<CommitResponse>,
+) {
+ const pristine = query.sort === "date" && query.kind === "all";
+ const filterKey = JSON.stringify(filters);
+
+ const { data, setSize, isLoading, isValidating } = useSWRInfinite<Paginated<CommitResponse>>(
+ (pageIndex, previous) => {
+ if (previous && !previous.has_more) return null;
+ return `commits:${repoId}:${query.sort}:${query.kind}:${filterKey}:${pageIndex}`;
+ },
+ (key) => {
+ const pageIndex = parseInt(key.split(":").pop() as string, 10);
+ return getCommitsPage(repoId, {
+ ...filters,
+ ...query,
+ limit: PAGE_SIZE,
+ offset: pageIndex * PAGE_SIZE,
+ });
+ },
+ {
+ revalidateOnFocus: false,
+ revalidateFirstPage: false,
+ keepPreviousData: true,
+ fallbackData: pristine ? [initial] : undefined,
+ revalidateOnMount: !pristine,
+ revalidateIfStale: !pristine,
+ },
+ );
+
+ const commits = useMemo(
+ () => (data ? data.flatMap((p) => p.items) : initial.items),
+ [data, initial.items],
+ );
+ return {
+ commits,
+ total: data && data.length > 0 ? data[0].total : initial.total,
+ hasMore: data ? !!data[data.length - 1]?.has_more : initial.has_more,
+ loadingMore: isValidating && !isLoading,
+ loadMore: () => void setSize((n) => n + 1),
+ // SWRInfinite keeps `size` across key changes, which would refetch every
+ // page of a new query; each change starts again from one page.
+ reset: () => void setSize(1),
+ };
+}
diff --git a/packages/web/src/lib/api/history.ts b/packages/web/src/lib/api/history.ts
new file mode 100644
index 000000000..40762f264
--- /dev/null
+++ b/packages/web/src/lib/api/history.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/history";
diff --git a/packages/web/src/lib/commit-filters.test.ts b/packages/web/src/lib/commit-filters.test.ts
new file mode 100644
index 000000000..52176be52
--- /dev/null
+++ b/packages/web/src/lib/commit-filters.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+import {
+ commitFiltersQuery,
+ effectiveWindow,
+ historyFilters,
+ isNarrowed,
+ parseCommitFilters,
+ windowRange,
+} from "./commit-filters";
+
+const NOW = new Date("2026-10-18T15:30:00Z");
+
+describe("commit filters", () => {
+ it("defaults to the past month and ignores junk", () => {
+ const f = parseCommitFilters({ health: "nope", window: "decade", since: "yesterday" });
+ expect(f).toMatchObject({ impact: "all", window: "month", hotspots: false, since: undefined });
+ });
+
+ it("drops days that do not exist rather than throwing", () => {
+ const f = parseCommitFilters({ window: "custom", since: "2026-02-31", until: "2026-13-01" });
+ expect([f.since, f.until]).toEqual([undefined, undefined]);
+ expect(effectiveWindow(f)).toBe("all");
+ expect(isNarrowed(f)).toBe(false);
+ });
+
+ it("keys rolling windows on the UTC day so a day's fetches agree", () => {
+ expect(windowRange({ window: "week" }, NOW)).toEqual({ since: "2026-10-11T00:00:00.000Z" });
+ expect(windowRange({ window: "all" }, NOW)).toEqual({});
+ });
+
+ it("makes the custom end day inclusive", () => {
+ expect(windowRange({ window: "custom", since: "2026-10-01", until: "2026-10-05" }, NOW)).toEqual({
+ since: "2026-10-01T00:00:00Z",
+ until: "2026-10-06T00:00:00.000Z",
+ });
+ });
+
+ it("maps impact to the server's delta, and leaves it out for the summary", () => {
+ const f = parseCommitFilters({ health: "better", hotspots: "1", author: "a@b", area: "packages/ui" });
+ expect(historyFilters(f, NOW)).toMatchObject({
+ delta: "improved",
+ touches_hotspot: true,
+ author: "a@b",
+ area: "packages/ui",
+ });
+ expect(historyFilters(f, NOW, { withImpact: false }).delta).toBeUndefined();
+ });
+
+ it("writes only non-default filters and keeps other params", () => {
+ const q = commitFiltersQuery(new URLSearchParams("commit=abc&health=worse"), {
+ impact: "all",
+ window: "quarter",
+ area: "src",
+ });
+ expect(Object.fromEntries(new URLSearchParams(q))).toEqual({
+ commit: "abc",
+ window: "quarter",
+ area: "src",
+ });
+ expect(commitFiltersQuery(new URLSearchParams("window=custom&since=2026-10-01"), { window: "month" })).toBe("");
+ });
+
+ it("reads the whole history as not narrowed", () => {
+ expect(isNarrowed(parseCommitFilters({ window: "all" }))).toBe(false);
+ expect(isNarrowed(parseCommitFilters({}))).toBe(true);
+ });
+});
diff --git a/packages/web/src/lib/commit-filters.ts b/packages/web/src/lib/commit-filters.ts
new file mode 100644
index 000000000..c8de3f01c
--- /dev/null
+++ b/packages/web/src/lib/commit-filters.ts
@@ -0,0 +1,132 @@
+/**
+ * The commit view's history filters as URL state: health impact, hotspots,
+ * time window, author and area. Pure, so the server page and the client
+ * filter bar read and write the same query string.
+ *
+ * URL: `?health=better|worse|none&hotspots=1&window=week|quarter|all|custom`
+ * `&since=YYYY-MM-DD&until=YYYY-MM-DD&author=&area=`. The past month is the
+ * default window and stays out of the URL, so `/commits` and
+ * `/commits?commit=<sha>` keep working as before.
+ */
+import type { DeltaFilter, HistoryFilters } from "@repowise-dev/types/history";
+import type {
+ HealthImpact,
+ HistoryFilterValue,
+ HistoryWindow,
+} from "@repowise-dev/ui/commits/history-filters";
+
+type Params = Record<string, string | string[] | undefined>;
+
+const IMPACTS: readonly HealthImpact[] = ["all", "better", "worse", "none"];
+const WINDOWS: readonly HistoryWindow[] = ["week", "month", "quarter", "all", "custom"];
+const WINDOW_DAYS: Partial<Record<HistoryWindow, number>> = { week: 7, month: 30, quarter: 90 };
+const DEFAULT_WINDOW: HistoryWindow = "month";
+const DAY_MS = 86_400_000;
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+/** A real calendar day: "2026-02-31" has the shape but not the day, and would
+ * throw when turned into an ISO range. */
+function isDay(v: string | undefined): v is string {
+ if (!v || !DATE.test(v)) return false;
+ const t = Date.parse(`${v}T00:00:00Z`);
+ return Number.isFinite(t) && new Date(t).toISOString().startsWith(v);
+}
+
+/** `improved` and `worsened` include mixed on the server, matching the
+ * headline's "made things better / worse" counts. */
+const IMPACT_DELTA: Record<Exclude<HealthImpact, "all">, DeltaFilter> = {
+ better: "improved",
+ worse: "worsened",
+ none: "neutral",
+};
+
+function one(v: string | string[] | undefined): string | undefined {
+ const s = Array.isArray(v) ? v[0] : v;
+ return s && s.trim() ? s.trim() : undefined;
+}
+
+function pick<T extends string>(v: string | undefined, allowed: readonly T[], fallback: T): T {
+ return v && (allowed as readonly string[]).includes(v) ? (v as T) : fallback;
+}
+
+export function parseCommitFilters(sp: Params): HistoryFilterValue {
+ const since = one(sp.since);
+ const until = one(sp.until);
+ return {
+ impact: pick(one(sp.health), IMPACTS, "all"),
+ hotspots: one(sp.hotspots) === "1",
+ window: pick(one(sp.window), WINDOWS, DEFAULT_WINDOW),
+ since: isDay(since) ? since : undefined,
+ until: isDay(until) ? until : undefined,
+ author: one(sp.author),
+ area: one(sp.area),
+ };
+}
+
+/** Today's UTC midnight: a rolling window keyed on the day, so the server's
+ * render and every refetch that day ask for the same range. */
+function utcDay(now: Date): number {
+ return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
+}
+
+/** The ISO range a window covers; `until` is exclusive. */
+export function windowRange(
+ f: Pick<HistoryFilterValue, "window" | "since" | "until">,
+ now: Date,
+): { since?: string; until?: string } {
+ if (f.window === "custom") {
+ return {
+ ...(f.since ? { since: `${f.since}T00:00:00Z` } : {}),
+ // The picker's "to" day is inclusive, the API's `until` is not.
+ ...(f.until ? { until: new Date(Date.parse(`${f.until}T00:00:00Z`) + DAY_MS).toISOString() } : {}),
+ };
+ }
+ const days = WINDOW_DAYS[f.window];
+ return days ? { since: new Date(utcDay(now) - days * DAY_MS).toISOString() } : {};
+}
+
+/** The API filters. `impact` is left out with `withImpact: false`, for the
+ * summary that counts every impact so the quick filters keep their sizes. */
+export function historyFilters(
+ f: HistoryFilterValue,
+ now: Date,
+ { withImpact = true }: { withImpact?: boolean } = {},
+): HistoryFilters {
+ return {
+ ...windowRange(f, now),
+ ...(f.author ? { author: f.author } : {}),
+ ...(f.area ? { area: f.area } : {}),
+ ...(f.hotspots ? { touches_hotspot: true } : {}),
+ ...(withImpact && f.impact !== "all" ? { delta: IMPACT_DELTA[f.impact] } : {}),
+ };
+}
+
+/** The window the range really covers: a custom window with no dates yet is
+ * the whole history, and is named so. */
+export function effectiveWindow(f: Pick<HistoryFilterValue, "window" | "since" | "until">): HistoryWindow {
+ return f.window === "custom" && !f.since && !f.until ? "all" : f.window;
+}
+
+/** True when anything but the whole history is shown. */
+export function isNarrowed(f: HistoryFilterValue): boolean {
+ return effectiveWindow(f) !== "all" || f.impact !== "all" || f.hotspots || !!f.author || !!f.area;
+}
+
+/**
+ * `current` with `patch` applied, as a query string (no leading `?`). Other
+ * parameters (`commit`, `view`) are kept; defaults are dropped so a reset
+ * filter leaves no trace in the URL.
+ */
+export function commitFiltersQuery(current: URLSearchParams, patch: Partial<HistoryFilterValue>): string {
+ const next = { ...parseCommitFilters(Object.fromEntries(current)), ...patch };
+ const out = new URLSearchParams(current);
+ const set = (k: string, v: string | undefined) => (v ? out.set(k, v) : out.delete(k));
+ set("health", next.impact === "all" ? undefined : next.impact);
+ set("hotspots", next.hotspots ? "1" : undefined);
+ set("window", next.window === DEFAULT_WINDOW ? undefined : next.window);
+ set("since", next.window === "custom" ? next.since : undefined);
+ set("until", next.window === "custom" ? next.until : undefined);
+ set("author", next.author);
+ set("area", next.area);
+ return out.toString();
+}
diff --git a/packages/web/src/lib/commit-prompt.test.ts b/packages/web/src/lib/commit-prompt.test.ts
new file mode 100644
index 000000000..68a02fdf4
--- /dev/null
+++ b/packages/web/src/lib/commit-prompt.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import type { CommitDetail } from "@repowise-dev/types/git";
+import { commitFixPromptInput } from "./commit-prompt";
+
+const finding = {
+ change_kind: "introduced",
+ dimension: "maintainability",
+ biomarker_type: "large_method",
+ severity: "high",
+ path: "src/a.py",
+ line_start: 4,
+ attribution_basis: "added_lines",
+ reason: "run grew",
+};
+
+function commit(o: Partial<CommitDetail>): CommitDetail {
+ return {
+ sha: "a".repeat(40),
+ short_sha: "aaaaaaaa",
+ subject: "feat: x",
+ drivers: [],
+ files: [{ path: "src/a.py" }],
+ health: {
+ status: "available",
+ introduced_count: 1,
+ worsened_count: 0,
+ resolved_count: 2,
+ files_analyzed: 1,
+ files_skipped: 0,
+ findings: [finding],
+ },
+ ...o,
+ } as CommitDetail;
+}
+
+describe("commitFixPromptInput", () => {
+ it("builds the commit-unit fix prompt from the stored findings", () => {
+ expect(commitFixPromptInput(commit({}))).toMatchObject({
+ unit: "commit",
+ label: "aaaaaaaa",
+ files: ["src/a.py"],
+ resolved: 2,
+ complete: true,
+ });
+ });
+
+ it("offers no fix prompt without current findings", () => {
+ expect(commitFixPromptInput(commit({ health: null }))).toBeNull();
+ expect(
+ commitFixPromptInput(
+ commit({
+ health_delta: { status: "available", kind: "worsened", introduced: 1, worsened: 0, resolved: 0, stale: true },
+ }),
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/packages/web/src/lib/commit-prompt.ts b/packages/web/src/lib/commit-prompt.ts
new file mode 100644
index 000000000..214e4c7f1
--- /dev/null
+++ b/packages/web/src/lib/commit-prompt.ts
@@ -0,0 +1,46 @@
+/**
+ * The commit sheet's agent prompts. A commit that made health worse gets the
+ * shared fix prompt (the change prompt, worded for one commit); any other gets
+ * the review prompt. Pure, so the choice is tested once.
+ */
+import type { CommitDetail } from "@repowise-dev/types/git";
+import type { ChangePromptInput, CommitPromptInput } from "@repowise-dev/ui/health/ai-prompt-builder";
+import { readCommitHealth } from "@repowise-dev/ui/commits/commit-health-copy";
+
+/** The fix prompt's input, or null when there is nothing current to fix:
+ * no findings stored, or only an earlier analysis's (direction only). */
+export function commitFixPromptInput(c: CommitDetail): ChangePromptInput | null {
+ const read = readCommitHealth(c.health_delta, c.health);
+ const findings = c.health?.findings ?? [];
+ if (read.stale || findings.length === 0) return null;
+ return {
+ unit: "commit",
+ label: c.short_sha,
+ title: c.subject,
+ head_sha: c.sha,
+ commits: [c.sha],
+ files: (c.files ?? []).map((f) => f.path),
+ findings,
+ resolved: c.health?.resolved_count ?? 0,
+ complete: c.health?.status !== "partial",
+ attention: [],
+ };
+}
+
+/** The review prompt's input: the diff-shape context. */
+export function commitReviewPromptInput(c: CommitDetail): CommitPromptInput {
+ return {
+ sha: c.sha,
+ subject: c.subject,
+ review_priority: c.review_priority,
+ risk_percentile: c.risk_percentile,
+ change_risk_score: c.change_risk_score,
+ is_fix: c.is_fix,
+ files_changed: c.files_changed,
+ lines_added: c.lines_added,
+ lines_deleted: c.lines_deleted,
+ entropy: c.entropy,
+ top_drivers: c.drivers.filter((d) => d.contribution > 0).map((d) => d.label),
+ author_name: c.author_name,
+ };
+}