Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ui): rebuild Coverage and Dead code on the section design language (#1132)
Raghav Chamadiya793c33be3cd0
diff --git a/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsxnew file mode 100644index 000000000..3e557ca34--- /dev/null+++ b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx@@ -0,0 +1,60 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { DeadCodeLede } from "../../src/dead-code/dead-code-lede.js";+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";++const SUMMARY: DeadCodeSummary = {+ total_findings: 142,+ confidence_summary: { high: 89, medium: 41, low: 12 },+ deletable_lines: 4321,+ total_lines: 91234,+ by_kind: { unreachable_file: 12, unused_export: 88, zombie_package: 42 },+};++describe("DeadCodeLede", () => {+ it("leads with the reclaimable line count", () => {+ render(<DeadCodeLede summary={SUMMARY} />);+ expect(screen.getByText("4,321")).toBeInTheDocument();+ expect(screen.getByText("lines")).toBeInTheDocument();+ });++ it("names every kind in prose rather than as separate tiles", () => {+ render(<DeadCodeLede summary={SUMMARY} />);+ const prose = screen.getByText(/have no reachable caller/);+ expect(prose.textContent).toContain("88 unused exports");+ expect(prose.textContent).toContain("42 zombie packages");+ expect(prose.textContent).toContain("12 unreachable files");+ });++ it("splits confidence across the ribbon and the bar", () => {+ render(<DeadCodeLede summary={SUMMARY} />);+ // High stands alone; medium and low are the one "verify this" bucket.+ expect(screen.getByText("89")).toBeInTheDocument();+ expect(screen.getByText("53")).toBeInTheDocument();+ expect(screen.getByLabelText("89 high confidence")).toBeInTheDocument();+ });++ it("reports the deletable share of the flagged lines, not of the repo", () => {+ render(<DeadCodeLede summary={SUMMARY} />);+ // 4,321 of the 91,234 lines sitting inside a finding.+ expect(screen.getByText("5%")).toBeInTheDocument();+ expect(screen.getByText("91,234")).toBeInTheDocument();+ });++ it("says a clean repository is a result, not an absence", () => {+ render(+ <DeadCodeLede+ summary={{+ total_findings: 0,+ confidence_summary: { high: 0, medium: 0, low: 0 },+ deletable_lines: 0,+ total_lines: 0,+ by_kind: {},+ }}+ />,+ );+ expect(+ screen.getByText(/Nothing in this repository is currently flagged/),+ ).toBeInTheDocument();+ });+});diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsxindex b8aaa78ab..9a2f25df3 100644--- a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx@@ -33,15 +33,19 @@ vi.mock("sonner", () => ({* The findings table stacks into a mobile card list beside the real table and* lets CSS pick one; jsdom applies no CSS, so a row control matches in both.* These scope row queries to the table.+ *+ * By caption, not by role alone: the cluster rollups above it are no longer+ * behind a disclosure, so the page now carries more than one <table>.*/+const FINDINGS_TABLE = { name: "Dead code findings" };const rowButton = (name: string) =>- within(screen.getByRole("table")).getByRole("button", { name });+ within(screen.getByRole("table", FINDINGS_TABLE)).getByRole("button", { name });const queryRowButton = (name: string) => {- const table = screen.queryByRole("table");+ const table = screen.queryByRole("table", FINDINGS_TABLE);return table ? within(table).queryByRole("button", { name }) : null;};const findRowButton = async (name: string) => {- await screen.findByRole("table");+ await screen.findByRole("table", FINDINGS_TABLE);return rowButton(name);};@@ -151,18 +155,18 @@ describe("DeadCodeView", () => {it("renders the summary and the safe-to-delete pile from adapter data", async () => {renderView(<DeadCodeView adapter={makeAdapter()} />);- // Summary headline (total findings) + the safe pile punchline.+ // The lede's figure, then the safe pile's own sentence.expect(await screen.findByText("Propose cleanup")).toBeInTheDocument();- expect(screen.getByText("lines in cleanup candidates")).toBeInTheDocument();+ expect(screen.getByText(/come back high confidence/)).toBeInTheDocument();// The safe slice (not the unsafe bootstrap file) drives the pile preview.- expect(screen.getByText(/legacy\.ts/)).toBeInTheDocument();+ expect(screen.getAllByText(/legacy\.ts/).length).toBeGreaterThan(0);});it("Re-analyze calls the adapter and shows a success toast", async () => {const adapter = makeAdapter();renderView(<DeadCodeView adapter={adapter} />);- fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));+ fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));await waitFor(() => expect(adapter.analyze).toHaveBeenCalledTimes(1));expect(toastSuccess).toHaveBeenCalled();@@ -203,7 +207,7 @@ describe("DeadCodeView", () => {expect(screen.queryByText(/No open dead-code findings/),).not.toBeInTheDocument();- expect(screen.queryByRole("button", { name: /All findings/ })).not.toBeInTheDocument();+ expect(screen.queryByRole("table", FINDINGS_TABLE)).not.toBeInTheDocument();});it("reviews and reopens an acknowledged finding, which the toast alone could not", async () => {@@ -243,8 +247,6 @@ describe("DeadCodeView", () => {fireEvent.change(screen.getByLabelText("Status"), { target: { value: "open" } });expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();- // It is cleanup-ready, so a pile now exists and the section mounts closed.- fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));expect(await findRowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();});@@ -262,10 +264,9 @@ describe("DeadCodeView", () => {});renderView(<DeadCodeView adapter={adapter} />);- fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));expect(await findRowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));+ fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));// A transient failure on the refresh must not take the working table away// and lose the user's place; it reports itself above the rows.@@ -312,10 +313,10 @@ describe("DeadCodeView", () => {),});renderView(<DeadCodeView adapter={adapter} />);- await screen.findByText("lines in cleanup candidates");+ await screen.findByText(/come back high confidence/);const listCallsBefore = (adapter.listFindings as ReturnType<typeof vi.fn>).mock.calls.length;- fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));+ fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));await waitFor(() => expect(adapter.waitForAnalysis).toHaveBeenCalledWith("job-1"));resolveJob?.();@@ -343,7 +344,7 @@ describe("DeadCodeView", () => {});renderView(<DeadCodeView adapter={adapter} />);- fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));+ fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));// The job is running; "Couldn't start analysis" would be a false statement.await waitFor(() => expect(toastError).toHaveBeenCalled());@@ -360,7 +361,7 @@ describe("DeadCodeView", () => {});renderView(<DeadCodeView adapter={adapter} />);- fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));+ fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));await waitFor(() => expect(toastError).toHaveBeenCalled());expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Another job is already running/);@@ -370,8 +371,6 @@ describe("DeadCodeView", () => {const adapter = makeAdapter();renderView(<DeadCodeView adapter={adapter} />);- // Open the drill-down table (collapsed by default).- fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));fireEvent.click(await findRowButton("Resolve src/old/legacy.ts"));fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));diff --git a/packages/ui/__tests__/dead-code/findings-table.test.tsx b/packages/ui/__tests__/dead-code/findings-table.test.tsxindex fee51a6b2..39805c08f 100644--- a/packages/ui/__tests__/dead-code/findings-table.test.tsx+++ b/packages/ui/__tests__/dead-code/findings-table.test.tsx@@ -284,7 +284,9 @@ describe("FindingsTable row affordances", () => {const onGeneratePrompt = vi.fn();renderTable([finding({ id: "a" }), finding({ id: "b" })], { onGeneratePrompt });- fireEvent.click(inTable().getByRole("button", { name: "AI cleanup prompt for src/a.ts" }));+ // Per-row: behind the overflow, with Resolve as the row's one visible verb.+ fireEvent.click(inTable().getByRole("button", { name: "More actions for src/a.ts" }));+ fireEvent.click(screen.getByRole("button", { name: "Draft AI cleanup prompt" }));expect(onGeneratePrompt).toHaveBeenCalledWith(["a"]);fireEvent.click(screen.getByLabelText("Select all findings"));@@ -293,10 +295,15 @@ describe("FindingsTable row affordances", () => {});it("renders the graph action from the host's route, and hides it without one", () => {+ const openMenu = () =>+ fireEvent.click(inTable().getByRole("button", { name: "More actions for src/a.ts" }));+ const LINK = { name: "Open in dependency graph" };+const { unmount } = renderTable([finding({ id: "a" })], {graphHref: (p: string) => `/repos/repo-1/architecture?node=${encodeURIComponent(p)}`,});- expect(inTable().getByRole("link", { name: "Graph" })).toHaveAttribute(+ openMenu();+ expect(screen.getByRole("link", LINK)).toHaveAttribute("href","/repos/repo-1/architecture?node=src%2Fa.ts",);@@ -305,7 +312,8 @@ describe("FindingsTable row affordances", () => {// No graph route on the host (the hosted frontend today) means no action,// rather than a link into a page that does not exist there.renderTable([finding({ id: "a" })]);- expect(screen.queryByRole("link", { name: "Graph" })).not.toBeInTheDocument();+ openMenu();+ expect(screen.queryByRole("link", LINK)).not.toBeInTheDocument();});it("reports a rejecting bulk resolve instead of wedging the dialog open", async () => {diff --git a/packages/ui/__tests__/dead-code/summary-bar.test.tsx b/packages/ui/__tests__/dead-code/summary-bar.test.tsxdeleted file mode 100644index 6d355ab85..000000000--- a/packages/ui/__tests__/dead-code/summary-bar.test.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { describe, it, expect } from "vitest";-import { render, screen } from "@testing-library/react";-import { SummaryBar } from "../../src/dead-code/summary-bar.js";-import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";--const SUMMARY: DeadCodeSummary = {- total_findings: 142,- confidence_summary: { high: 89, medium: 41, low: 12 },- deletable_lines: 4321,- total_lines: 91234,- by_kind: { unreachable_file: 12, unused_export: 88, zombie_package: 42 },-};--describe("SummaryBar", () => {- it("renders the headline counts", () => {- render(<SummaryBar summary={SUMMARY} />);- expect(screen.getByText("142")).toBeInTheDocument();- expect(screen.getByText("4,321")).toBeInTheDocument();- });-- it("breaks out by_kind and confidence_summary entries", () => {- render(<SummaryBar summary={SUMMARY} />);- expect(screen.getByText("unreachable file")).toBeInTheDocument();- expect(screen.getByText("unused export")).toBeInTheDocument();- expect(screen.getByText("zombie package")).toBeInTheDocument();- expect(screen.getByText("high")).toBeInTheDocument();- expect(screen.getByText("89")).toBeInTheDocument();- });-});diff --git a/packages/ui/src/dead-code/dead-code-lede.tsx b/packages/ui/src/dead-code/dead-code-lede.tsxnew file mode 100644index 000000000..aac37eedb--- /dev/null+++ b/packages/ui/src/dead-code/dead-code-lede.tsx@@ -0,0 +1,226 @@+/**+ * The Dead Code tab's opening read.+ *+ * It replaces four `MetricCard`s in a grid, two of which held a stacked+ * label-and-count list inside the value slot. That is a table wearing a card:+ * seven figures at near-identical weight behind four uppercase labels, with+ * nothing leading and nothing saying what any of it means. A count of findings+ * is also the wrong figure to lead with, because the question this tab answers+ * is "what can I delete", and the answer is measured in lines.+ *+ * The kind breakdown moved into prose. Four kinds as four tiles read as four+ * equal problems; as a sentence they read as what they are, one pile sorted by+ * how it was found.+ */++import type { ReactNode } from "react";+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";++import { PageLede } from "../shared/page-lede";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";+import { formatNumber } from "../lib/format";++export interface DeadCodeLedeProps {+ summary: DeadCodeSummary;+ /**+ * Findings in the slice on screen. Passed so the lede can say when the+ * server-wide totals and the list below describe different populations,+ * rather than letting a capped page read as the whole repository.+ */+ shownCount?: number;+ truncated?: boolean;+ /** Rendered under the prose. The tab's one action. */+ action?: ReactNode;+}++/** How a finding was reached, in the words a person would use. */+const KIND_LABELS: Record<string, string> = {+ unreachable_file: "unreachable file",+ unused_export: "unused export",+ unused_internal: "unused internal symbol",+ zombie_package: "zombie package",+};++function kindPhrase(kind: string, count: number): string {+ const label = KIND_LABELS[kind] ?? kind.replace(/_/g, " ");+ return `${formatNumber(count)} ${label}${count === 1 ? "" : "s"}`;+}++/** "a, b and c" — an Oxford-comma-free list, built rather than interpolated so+ * a repo with one kind does not read "1 unused export and". */+function joinPhrases(parts: string[]): string {+ if (parts.length <= 1) return parts[0] ?? "";+ return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;+}++export function DeadCodeLede({+ summary,+ shownCount,+ truncated = false,+ action,+}: DeadCodeLedeProps) {+ const kinds = Object.entries(summary.by_kind)+ .filter(([, count]) => count > 0)+ .sort((a, b) => b[1] - a[1]);+ const confidence = summary.confidence_summary;+ const high = confidence.high ?? 0;+ const medium = confidence.medium ?? 0;+ const low = confidence.low ?? 0;+ const graded = high + medium + low;+ const flagged = summary.total_lines;+ const share =+ flagged > 0 ? Math.round((summary.deletable_lines / flagged) * 100) : null;++ const stats: RibbonStat[] = [+ {+ label: "Findings",+ value: formatNumber(summary.total_findings),+ ...(truncated && shownCount != null+ ? { sub: `${formatNumber(shownCount)} on this page` }+ : {}),+ },+ {+ label: "Lines flagged",+ value: formatNumber(flagged),+ sub: "across every finding",+ hint: "Every line inside a dead-code finding, whether or not we would delete it unreviewed.",+ },+ {+ label: "High confidence",+ value: formatNumber(high),+ valueColor: high > 0 ? "text-[var(--color-success)]" : undefined,+ sub: "confidence 0.7 or better",+ hint: "No dynamic reference, no re-export, no entry point that we can see.",+ },+ {+ label: "Needs a look",+ value: formatNumber(medium + low),+ sub: "verify before deleting",+ hint: "Reachable only through something static analysis cannot follow: a dynamic import, a plugin registry, a framework hook.",+ },+ {+ label: "Deletion-ready",+ value: share == null ? "" : `${share}%`,+ sub: "of the flagged lines",+ hint: "High confidence and outside the config, bootstrap and environment paths we never auto-delete from.",+ },+ ];++ return (+ <div className="flex flex-col gap-6">+ <PageLede+ label="Reclaimable"+ value={formatNumber(summary.deletable_lines)}+ unit="lines"+ layout="beside"+ {...(action ? { action } : {})}+ figureFooter={+ graded > 0 ? (+ <ConfidenceSplit high={high} medium={medium} low={low} />+ ) : undefined+ }+ >+ {summary.total_findings === 0 ? (+ <p>+ Nothing in this repository is currently flagged as unreachable, unused or+ zombie. That is a real result rather than an absence: the analysis walked+ the import graph, the export surface and the package manifests and found+ no symbol it could reach from no entry point. Re-run it after a large+ refactor, when whole call paths tend to go quiet at once.+ </p>+ ) : (+ <>+ <p>+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(summary.total_findings)} findings+ </strong>{" "}+ covering{" "}+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(flagged)} lines+ </strong>{" "}+ have no reachable caller. They are{" "}+ {joinPhrases(kinds.map(([kind, count]) => kindPhrase(kind, count)))},+ found by walking the import graph and the export surface rather than by+ matching names.+ </p>++ <p className="mt-2.5">+ Of those,{" "}+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(summary.deletable_lines)} lines+ </strong>{" "}+ are deletion-ready: high confidence, and outside the config, bootstrap+ and environment paths we never delete from unreviewed+ {share != null ? `, which is ${share}% of what is flagged` : ""}. That+ is the number the cleanup brief is seeded from.+ </p>++ <p className="mt-2.5">+ Confidence is not a hedge on the finding, it is a statement about the+ language. A Python entry point registered by string name and a+ TypeScript symbol re-exported through a barrel file are both invisible+ to a call-graph walk, and calling either one dead would be wrong.+ </p>+ </>+ )}+ </PageLede>++ <StatRibbon stats={stats} />+ </div>+ );+}++/**+ * The one second read belonging to the number itself: how much of the pile you+ * can act on now. Stepped down from the accent rather than reaching for three+ * new hues, because confidence is an ordered scale, not three categories.+ */+function ConfidenceSplit({+ high,+ medium,+ low,+}: {+ high: number;+ medium: number;+ low: number;+}) {+ const total = high + medium + low;+ const segments = [+ { key: "high", label: "high", count: high, bar: "bg-[var(--color-accent-primary)]" },+ {+ key: "medium",+ label: "medium",+ count: medium,+ bar: "bg-[color-mix(in_srgb,var(--color-accent-primary)_45%,var(--color-bg-inset))]",+ },+ {+ key: "low",+ label: "low",+ count: low,+ bar: "bg-[color-mix(in_srgb,var(--color-accent-primary)_18%,var(--color-bg-inset))]",+ },+ ].filter((s) => s.count > 0);++ return (+ <div className="space-y-1.5">+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">+ {segments.map((s) => (+ <div+ key={s.key}+ className={s.bar}+ style={{ width: `${(s.count / total) * 100}%` }}+ aria-label={`${s.count} ${s.label} confidence`}+ />+ ))}+ </div>+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">+ {segments.map((s) => (+ <span key={s.key} className="inline-flex items-center gap-1 tabular-nums">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${s.bar}`} />+ {formatNumber(s.count)} {s.label}+ </span>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsxindex ce1fe7db1..f3021749e 100644--- a/packages/ui/src/dead-code/dead-code-view.tsx+++ b/packages/ui/src/dead-code/dead-code-view.tsx@@ -1,12 +1,21 @@"use client";/**- * Dead Code view — the safe-to-delete pile (the "what do I delete" punchline),- * optional cluster rollups behind progressive disclosure, and the full- * drill-down table with its single confidence control. Carries the optimistic- * row patch + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and+ * Dead Code view, on the section design language.+ *+ * The shape is: a lede that leads with the reclaimable line count and says in+ * prose what confidence means, then the safe-to-delete pile, the optional+ * cluster rollups, and the full drill-down table. Carries the optimistic row+ * patch + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and* Re-analyze.*+ * What it replaces: four `MetricCard`s in a grid (two of them holding a stacked+ * count list inside the value slot), a red gradient hero card that repeated the+ * headline figure, and a floating chrome row carrying a status dropdown and a+ * button above all of it. The controls now sit in the header of the section+ * they operate on, which is also why the status filter can live there safely:+ * a section header renders whether or not the table underneath it does.+ ** Presentation + orchestration only: the host injects data fetching,* mutations, links, and navigation through a {@link DeadCodeAdapter}, so web* and hosted render the same view from one source.@@ -26,12 +35,12 @@ import { Trash2 } from "lucide-react";import { Button } from "../ui/button";import { Skeleton } from "../ui/skeleton";import { ApiError } from "../shared/api-error";-import { CollapsibleSection } from "../shared/collapsible-section";import { EmptyState } from "../shared/empty-state";+import { OverviewSection } from "../overview/section";import { AiPromptModal } from "../health/ai-prompt-modal";import { buildDeadCodeAiPrompt } from "../health/ai-prompt-builder";-import { SummaryBar } from "./summary-bar";+import { DeadCodeLede } from "./dead-code-lede";import { SafeToDeletePile } from "./safe-to-delete-pile";import { OwnerLeaderboard } from "./owner-leaderboard";import { FindingsBreakdownGrid } from "./findings-breakdown-grid";@@ -278,50 +287,42 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {return succeededIds;};- return (- <div className="space-y-6">- <div className="flex flex-wrap items-center justify-end gap-3">- {/* The way back to an acknowledged or false-positive finding, which was- otherwise reachable only from a toast that expires in six seconds.- It sits here rather than among the table's own filters because a- clean repository swaps the table out for an empty state, and a- control living inside it would go with it. */}- <div className="flex items-center gap-2">- <label htmlFor="finding-status" className="text-xs text-[var(--color-text-secondary)]">- Status- </label>- <select- id="finding-status"- value={statusFilter}- onChange={(e) => setStatusFilter(e.target.value as DeadCodeStatus)}- className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]"- >- {STATUS_ORDER.map((s) => (- <option key={s} value={s}>- {DEAD_CODE_STATUS_LABELS[s]}- </option>- ))}- </select>- </div>- <Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>- {analyzing ? "Analyzing…" : "Re-analyze"}- </Button>- </div>+ // The tab's one action, placed under the lede prose. It is the same element+ // wherever the lede cannot render, so a failed summary still leaves a way to+ // re-run the pass.+ const reanalyze = (+ <Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>+ {analyzing ? "Analyzing…" : "Re-analyze"}+ </Button>+ );+ return (+ <div className="flex flex-col gap-6 sm:gap-8">{loadingSummary ? (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-24 w-full rounded-lg" />- ))}+ // Shapes and widths match the lede, so nothing reflows when it lands.+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-5 lg:flex-row lg:gap-12">+ <Skeleton className="h-[92px] w-full rounded-lg lg:w-[220px]" />+ <Skeleton className="h-[92px] w-full max-w-[62ch] rounded-lg" />+ </div>+ <Skeleton className="h-[74px] w-full" /></div>) : summary ? (- <SummaryBar summary={summary} />- ) : summaryError ? (- <RetryCard- title="Couldn't load summary"- error={summaryError}- onRetry={() => void mutateSummary()}+ <DeadCodeLede+ summary={summary}+ shownCount={findingsList.length}+ truncated={truncated}+ action={reanalyze}/>+ ) : summaryError ? (+ <div className="flex flex-col gap-3">+ <RetryCard+ title="Couldn't load summary"+ error={summaryError}+ onRetry={() => void mutateSummary()}+ />+ <div>{reanalyze}</div>+ </div>) : null}{/* Act now: the single "what do I delete" surface. */}@@ -337,108 +338,122 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {/>)}- {/* Where it clusters — optional rollups, collapsed by default so the spine- stays pile → drill-down. */}+ {/* Where it clusters. No longer behind a disclosure: the accordion existed+ because this sat among six boxes of equal weight and something had to+ give, and a hairline plus vertical rhythm now does that job without+ hiding a rollup the reader has to guess at. */}{findingsList.length > 0 && (- <CollapsibleSection+ <OverviewSectiontitle="Where it clusters"- hint="By owner and confidence × kind"- defaultOpen={false}+ description="The same findings cut two ways: by the person who last owned the code, and by how sure we are against how it was found.">- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <div>- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">- Reclaimable lines per primary contributor — who has the most cleanup leverage.+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <div className="flex flex-col gap-2">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Reclaimable lines by owner</p><OwnerLeaderboard findings={findingsList} safeOnly /></div>- <div>- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">- Where findings concentrate — start with high-confidence cells.+ <div className="flex flex-col gap-2">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Confidence against kind</p><FindingsBreakdownGrid findings={findingsList} /></div></div>- </CollapsibleSection>+ </OverviewSection>)}- {/* Everything below routes off the slice actually on screen, not the open- fetch: a failed open fetch used to blank the table even when the user- had switched the filter to a slice that loaded fine.+ {/* The drill-down. Its contents route off the slice actually on screen,+ not the open fetch: a failed open fetch used to blank the table even+ when the user had switched the filter to a slice that loaded fine.- A failure with nothing to show has to be the whole story - a table or- an empty state underneath it would restate the failure as "clean". */}- {tableError && tableFindings.length === 0 && !tableLoading ? (- <RetryCard- title="Couldn't load findings"- error={tableError}- onRetry={retryTable}- />- ) : tableLoading && tableFindings.length === 0 ? (- <Skeleton className="h-40 w-full rounded-lg" />- ) : /* A clean repository gets said out loud, with the way to re-check it.- Keyed off the fetched payload, not the locally filtered list: resolving- the last row must not swap the table out for an empty state, because- undoing it would then bring the row back into a section that- remounted collapsed. Only for the open slice — swapping the table out- while reviewing acknowledged findings would take the status filter- with it and strand the user there. */- statusFilter === "open" && fetched.length === 0 && findingsList.length === 0 ? (- <EmptyState- icon={<Trash2 className="h-6 w-6" />}- title="No dead code found"- description="Nothing in this repository is currently flagged as unreachable, unused or zombie. Re-run the analysis after a large refactor."- action={{ label: analyzing ? "Analyzing…" : "Re-analyze", onClick: () => void handleAnalyze() }}- />- ) : (- /* Drill-down: the full interactive table, the single confidence control.- Rendered only once the findings settle so `defaultOpen` sees the real- pile: mounted mid-load it would always read "no pile" and open. */- <CollapsibleSection- // Remount on a status switch: defaultOpen is read once, so without this- // picking "Acknowledged" while the section sits collapsed changes only- // the hint text and the filter reads as broken.- key={statusFilter}+ The status control lives in this header rather than among the table's+ own filters because a clean repository swaps the table out for an+ empty state, and a control living inside it would go with it. The+ header renders either way. */}+ <OverviewSectiontitle="All findings"- hint={+ description={tableLoading? "Loading…": statusFilter !== "open"- ? `${reviewTruncated ? `First ${tableFindings.length}` : tableFindings.length} ${DEAD_CODE_STATUS_LABELS[statusFilter].toLowerCase()}`+ ? `${reviewTruncated ? `The first ${tableFindings.length}` : tableFindings.length} ${DEAD_CODE_STATUS_LABELS[statusFilter].toLowerCase()} finding${tableFindings.length === 1 ? "" : "s"}. Reopen one to put it back in the working list.`: truncated && summary- ? `Showing ${findingsList.length} of ${summary.total_findings} findings`- : `${findingsList.length} findings`+ ? `Showing ${findingsList.length} of ${summary.total_findings} open findings. Resolve, acknowledge or flag a false positive; every action is undoable for six seconds.`+ : `${findingsList.length} open finding${findingsList.length === 1 ? "" : "s"}. Resolve, acknowledge or flag a false positive; every action is undoable for six seconds.`+ }+ action={+ <div className="flex items-center gap-2">+ <label+ htmlFor="finding-status"+ className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"+ >+ Status+ </label>+ <select+ id="finding-status"+ value={statusFilter}+ onChange={(e) => setStatusFilter(e.target.value as DeadCodeStatus)}+ className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]"+ >+ {STATUS_ORDER.map((s) => (+ <option key={s} value={s}>+ {DEAD_CODE_STATUS_LABELS[s]}+ </option>+ ))}+ </select>+ </div>}- // With no safe pile above it this is the only content on the page, so- // a collapsed section reads as an empty screen. A review slice is- // always opened: the user asked for it explicitly.- defaultOpen={statusFilter !== "open" || safeFindings.length === 0}>- {/* A failed refresh over data we already hold: say so, but keep the- rows. Replacing a working table with an error card loses the user's- place over a transient blip. */}- {tableError && (- <div className="mb-3">- <RetryCard- title="Couldn't refresh findings"- error={tableError}- onRetry={retryTable}+ {/* A failure with nothing to show has to be the whole story: a table or+ an empty state underneath it would restate the failure as "clean". */}+ {tableError && tableFindings.length === 0 && !tableLoading ? (+ <RetryCard+ title="Couldn't load findings"+ error={tableError}+ onRetry={retryTable}+ />+ ) : tableLoading && tableFindings.length === 0 ? (+ <Skeleton className="h-40 w-full rounded-lg" />+ ) : /* A clean repository gets said out loud. Keyed off the fetched+ payload, not the locally filtered list: resolving the last row must+ not swap the table out, because undoing it would then bring the row+ back into a section that had remounted. Only for the open slice:+ swapping the table out while reviewing acknowledged findings would+ strand the user there. */+ statusFilter === "open" && fetched.length === 0 && findingsList.length === 0 ? (+ <EmptyState+ icon={<Trash2 className="h-6 w-6" />}+ title="No dead code found"+ description="Nothing in this repository is currently flagged as unreachable, unused or zombie. Re-run the analysis after a large refactor, when whole call paths tend to go quiet at once."+ />+ ) : (+ <>+ {/* A failed refresh over data we already hold: say so, but keep the+ rows. Replacing a working table with an error card loses the+ user's place over a transient blip. */}+ {tableError && (+ <RetryCard+ title="Couldn't refresh findings"+ error={tableError}+ onRetry={retryTable}+ />+ )}+ <FindingsTable+ findings={tableFindings}+ onPatch={handlePatch}+ onBulkResolve={handleBulkResolve}+ onGeneratePrompt={handlePropose}+ fileHref={(p) => adapter.fileHref(p)}+ onNavigate={(href) => adapter.navigate(href)}+ {...(adapter.graphHref ? { graphHref: (p: string) => adapter.graphHref!(p) } : {})}+ status={statusFilter}+ isLoading={tableLoading}/>- </div>+ </>)}- <FindingsTable- findings={tableFindings}- onPatch={handlePatch}- onBulkResolve={handleBulkResolve}- onGeneratePrompt={handlePropose}- fileHref={(p) => adapter.fileHref(p)}- onNavigate={(href) => adapter.navigate(href)}- {...(adapter.graphHref ? { graphHref: (p: string) => adapter.graphHref!(p) } : {})}- status={statusFilter}- isLoading={tableLoading}- />- </CollapsibleSection>- )}+ </OverviewSection><AiPromptModalopen={promptIds !== null}diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsxindex 877bb8b48..9e19d8d4e 100644--- a/packages/ui/src/dead-code/finding-cells.tsx+++ b/packages/ui/src/dead-code/finding-cells.tsx@@ -1,13 +1,13 @@"use client";import { useState, type MouseEvent } from "react";-import { GitBranch } from "lucide-react";+import type * as React from "react";+import { CircleSlash, Eye, GitBranch, MoreHorizontal, Sparkles } from "lucide-react";import { toast } from "sonner";import { Button } from "../ui/button";import { Badge } from "../ui/badge";import { ConfirmDialog } from "../ui/confirm-dialog";-import { RowActions } from "../shared/row-actions";-import { AiPromptButton } from "../health/ai-prompt-button";+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";import { formatConfidence } from "../lib/format";import { toFriendlyMessage } from "../lib/errors";import { cn } from "../lib/cn";@@ -175,9 +175,23 @@ export interface FindingRowActionsProps {}/**- * Per-row status actions: resolve, acknowledge or mark false positive while a- * finding is open, and the way back once it is not. Reopening used to be- * reachable only from a toast that expires after six seconds.+ * Per-row status actions: one verb in the row, the rest behind an overflow.+ *+ * This cell used to carry five controls at once — an AI-prompt icon, a graph+ * link, and `Resolve` / `Ack` / `FP` — inside a 9rem column that then wrapped+ * them onto two lines. Down a 500-row table that is 2,500 controls at identical+ * weight, which is rule 10 pointed at actions: if every row shouts, none of+ * them tells you anything, and the reader has to read a cluster before they can+ * read a row.+ *+ * What stays in the row is `Resolve`, because it is the verb that clears the+ * working list and the one the bulk control at the top uses, so the row and the+ * toolbar agree. Acknowledge and false positive keep their real words inside+ * the menu rather than living in the row as abbreviations only someone who+ * already knows the model can expand. The graph link and the AI prompt go with+ * them: both navigate somewhere or write something, neither decides anything+ * about this record, and mixing the two kinds is what made the cluster read as+ * a pile rather than a choice.*/export function FindingRowActions({finding,@@ -187,6 +201,7 @@ export function FindingRowActions({}: FindingRowActionsProps) {const [pending, setPending] = useState(false);const [confirmStatus, setConfirmStatus] = useState<string | null>(null);+ const [menuOpen, setMenuOpen] = useState(false);const applyPatch = async (status: string) => {setPending(true);@@ -204,54 +219,47 @@ export function FindingRowActions({const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;+ /** One row of the overflow menu. */+ const menuItem = (+ label: string,+ icon: React.ComponentType<{ className?: string }>,+ onClick: () => void,+ tone?: string,+ ) => {+ const Icon = icon;+ return (+ <button+ type="button"+ disabled={pending}+ onClick={() => {+ setMenuOpen(false);+ onClick();+ }}+ className={cn(+ "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] disabled:opacity-50",+ tone ?? "text-[var(--color-text-secondary)]",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ {label}+ </button>+ );+ };+return (<span onClick={(e) => e.stopPropagation()}>- <span className="flex flex-wrap items-center justify-end gap-1">- {onGeneratePrompt && (- <AiPromptButton- variant="icon"- label={`AI cleanup prompt for ${finding.file_path}`}- onClick={() => onGeneratePrompt(finding.id)}- />- )}- {graphHref && (- <RowActions- actions={[{ icon: GitBranch, label: "Graph", href: graphHref(finding.file_path) }]}- />- )}+ <span className="flex items-center justify-end gap-1">{finding.status === "open" ? (- <>- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => setConfirmStatus("resolved")}- className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"- aria-label={`Resolve ${finding.file_path}`}- >- Resolve- </Button>- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => setConfirmStatus("acknowledged")}- className="h-6 px-2 text-xs"- aria-label={`Acknowledge ${finding.file_path}`}- >- Ack- </Button>- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => setConfirmStatus("false_positive")}- className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"- aria-label={`Mark ${finding.file_path} as false positive`}- >- FP- </Button>- </>+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => setConfirmStatus("resolved")}+ className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"+ aria-label={`Resolve ${finding.file_path}`}+ >+ Resolve+ </Button>) : (<Buttonsize="sm"@@ -264,6 +272,43 @@ export function FindingRowActions({Reopen</Button>)}++ <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ <PopoverTrigger asChild>+ <Button+ size="sm"+ variant="ghost"+ className="h-6 w-6 px-0 text-[var(--color-text-tertiary)]"+ aria-label={`More actions for ${finding.file_path}`}+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-56 p-1">+ {finding.status === "open" && (+ <>+ {menuItem("Acknowledge", Eye, () => setConfirmStatus("acknowledged"))}+ {menuItem("Mark false positive", CircleSlash, () =>+ setConfirmStatus("false_positive"),+ )}+ </>+ )}+ {onGeneratePrompt &&+ menuItem("Draft AI cleanup prompt", Sparkles, () =>+ onGeneratePrompt(finding.id),+ )}+ {graphHref && (+ <a+ href={graphHref(finding.file_path)}+ onClick={() => setMenuOpen(false)}+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs text-[var(--color-text-secondary)] no-underline hover:bg-[var(--color-bg-elevated)]"+ >+ <GitBranch className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ Open in dependency graph+ </a>+ )}+ </PopoverContent>+ </Popover></span>{confirmConfig && (<ConfirmDialogdiff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsxindex 9988d2384..75a5e283c 100644--- a/packages/ui/src/dead-code/findings-table.tsx+++ b/packages/ui/src/dead-code/findings-table.tsx@@ -346,7 +346,9 @@ export function FindingsTable({key: "actions",header: <span className="sr-only">Actions</span>,mobileLabel: "Actions",- headerClassName: "w-36",+ // Two controls, not five: the cell no longer has to reserve room for a+ // cluster that wrapped onto a second line at this width.+ headerClassName: "w-24",align: "right",render: (f) => (<FindingRowActionsdiff --git a/packages/ui/src/dead-code/index.ts b/packages/ui/src/dead-code/index.tsindex d6c3ea974..b9bf5370b 100644--- a/packages/ui/src/dead-code/index.ts+++ b/packages/ui/src/dead-code/index.ts@@ -1,4 +1,4 @@-export * from "./summary-bar";+export * from "./dead-code-lede";export * from "./safe-to-delete-pile";export * from "./owner-leaderboard";export * from "./findings-breakdown-grid";diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsxindex b274ac7ac..5b9c854b3 100644--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx@@ -1,8 +1,9 @@"use client";import * as React from "react";-import { Trash2, ArrowRight } from "lucide-react";+import { ArrowRight } from "lucide-react";import { AiPromptButton } from "../health/ai-prompt-button";+import { OverviewSection } from "../overview/section";import { cn } from "../lib/cn";export interface SafeToDeletePileFinding {@@ -28,8 +29,16 @@ interface SafeToDeletePileProps {}/**- * Big visual card highlighting the high-confidence "safe to delete" pile —- * the demo's punchline for dead-code: "X lines, Y files, click to clean."+ * The "what do I delete" list: files carrying high-confidence findings, biggest+ * pile first.+ *+ * It used to be a red gradient card with a trash icon in a tinted tile and the+ * reclaimable line count set at 3xl. The lede above now leads with that same+ * figure, so repeating it here at near-hero size gave the page two headlines+ * that agree, and the red ground made a list of file paths read as a warning+ * about the files rather than an offer to remove them. Rule 9: the loudest+ * thing on screen should be the thing that responds, and what responds here is+ * the row and the prompt button.*/export function SafeToDeletePile({findings,@@ -74,63 +83,45 @@ export function SafeToDeletePile({}return [...byFile.values()].sort((a, b) => b.lines - a.lines);}, [findings]);- const top = groups.slice(0, 5);+ const top = groups.slice(0, 6);const moreFiles = Math.max(0, groups.length - top.length);return (- <div- className={cn(- "rounded-xl border border-[var(--color-error)]/30 bg-gradient-to-br from-[var(--color-error)]/10 via-[var(--color-bg-elevated)] to-[var(--color-bg-elevated)]",- "p-5",- className,- )}- >- <div className="flex items-start gap-4">- <div className="rounded-lg bg-[var(--color-error)]/15 p-2.5 text-[var(--color-error)] shrink-0">- <Trash2 className="h-5 w-5" />- </div>- <div className="flex-1 min-w-0">- <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">- <span className="text-3xl font-semibold tabular-nums text-[var(--color-text-primary)]">- {lines.toLocaleString()}- </span>- <span className="text-sm text-[var(--color-text-secondary)]">lines in cleanup candidates</span>- </div>- <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">- High-confidence candidates across <span className="font-medium">{files}</span> file- {files === 1 ? "" : "s"} ({findings.length} finding{findings.length === 1 ? "" : "s"}) —- {" "}review before deleting.- </p>- </div>- {onPropose && findings.length > 0 && (+ <OverviewSection+ title="Safe to delete"+ description={`${lines.toLocaleString()} lines across ${files.toLocaleString()} file${files === 1 ? "" : "s"} (${findings.length.toLocaleString()} finding${findings.length === 1 ? "" : "s"}) come back high confidence, with no caller we can find. Read the diff before you delete, then hand the rest to an agent.`}+ {...(className ? { className } : {})}+ action={+ onPropose && findings.length > 0 ? (// The canonical AI affordance, not a bespoke red button: every other// "hand this to an agent" action in the dashboard is this pill, and// red read as destructive on a button that only writes a prompt.<AiPromptButtonlabel="Propose cleanup"onClick={() => onPropose(findings.map((f) => f.id))}- className="shrink-0"/>- )}- </div>-+ ) : undefined+ }+ >{top.length > 0 && (- <ul className="mt-4 grid gap-1.5">+ <ul className="border-t border-[var(--color-border-default)]">{top.map((g) => {const Tag = onSelect ? "button" : "div";return (- <li key={g.file_path}>+ <li+ key={g.file_path}+ className="border-b border-[var(--color-border-default)]"+ ><Tagtype={onSelect ? "button" : undefined}onClick={onSelect ? () => onSelect(g.representative) : undefined}className={cn(- "flex w-full items-center justify-between gap-3 rounded-md border border-transparent px-2 py-1.5",- "text-left text-xs transition",- onSelect && "hover:border-[var(--color-border-default)] hover:bg-[var(--color-bg-surface)]",+ "flex w-full items-center justify-between gap-3 py-2.5 text-left text-xs",+ onSelect && "hover:bg-[var(--color-bg-elevated)]",)}><span- className="font-mono text-xs text-[var(--color-text-secondary)] truncate"+ className="min-w-0 truncate font-mono text-xs text-[var(--color-text-primary)]"title={g.file_path}>{g.file_path}@@ -148,14 +139,14 @@ export function SafeToDeletePile({</li>);})}- {moreFiles > 0 && (- <li className="px-2 pt-0.5 text-xs text-[var(--color-text-tertiary)]">- +{moreFiles.toLocaleString()} more file{moreFiles === 1 ? "" : "s"} —- {" "}see findings table below.- </li>- )}</ul>)}- </div>+ {moreFiles > 0 && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {moreFiles.toLocaleString()} more file{moreFiles === 1 ? "" : "s"} in the+ findings table below.+ </p>+ )}+ </OverviewSection>);}diff --git a/packages/ui/src/dead-code/summary-bar.tsx b/packages/ui/src/dead-code/summary-bar.tsxdeleted file mode 100644index 9af0da52e..000000000--- a/packages/ui/src/dead-code/summary-bar.tsx+++ /dev/null@@ -1,53 +0,0 @@-import { formatNumber } from "../lib/format";-import { MetricCard } from "../shared/metric-card";-import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";--export interface SummaryBarProps {- /** Summary rollup; caller fetches. */- summary: DeadCodeSummary;-}--/** Compact list rendered inside a MetricCard value slot (By Kind / Confidence). */-function CountList({ entries }: { entries: [string, number][] }) {- return (- <div className="space-y-1 text-xs font-normal">- {entries.map(([label, count]) => (- <div key={label} className="flex items-center justify-between gap-2">- <span className="truncate text-[var(--color-text-secondary)]">- {label.replace(/_/g, " ")}- </span>- <span className="ml-2 font-medium tabular-nums text-[var(--color-text-primary)]">- {formatNumber(count)}- </span>- </div>- ))}- </div>- );-}--export function SummaryBar({ summary }: SummaryBarProps) {- return (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <MetricCard- label="Total Findings"- value={formatNumber(summary.total_findings)}- />- <MetricCard- label="Candidate Lines"- value={- <span className="text-[var(--color-warning)]">- {formatNumber(summary.deletable_lines)}- </span>- }- />- <MetricCard- label="By Kind"- value={<CountList entries={Object.entries(summary.by_kind)} />}- />- <MetricCard- label="Confidence"- value={<CountList entries={Object.entries(summary.confidence_summary)} />}- />- </div>- );-}diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsxnew file mode 100644index 000000000..157261d14--- /dev/null+++ b/packages/ui/src/health/coverage-lede.tsx@@ -0,0 +1,192 @@+/**+ * The Coverage tab's opening read: one figure, the sentences that make it mean+ * something, and the operational facts as a hairline ribbon.+ *+ * It replaces five `MetricCard`s in a grid. Between them they carried the+ * headline percentage, two line counts, the report format and its ingest time+ * at identical weight behind five uppercase labels, which is the box-soup+ * failure: nothing leads, and the reader has to assemble the meaning from+ * five separate boxes. "88.9%" on its own also does not say whether that is+ * every file at 89 or most files at 100 with an untested corner, which is a+ * different problem with a different fix, so the band split under the figure+ * is part of the figure rather than another statistic.+ */++import { useMemo } from "react";+import type { ReactNode } from "react";+import type { CoverageFileRow, CoverageSummary } from "@repowise-dev/types/health";++import { PageLede } from "../shared/page-lede";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";+import { formatNumber } from "../lib/format";+import { coverageBand } from "./tokens";++export interface CoverageLedeProps {+ summary: CoverageSummary;+ /** Instrumented file rows, for the band split under the figure. */+ files: CoverageFileRow[];+ /** Directories carrying coverable lines. */+ moduleCount: number;+ /** Rendered under the prose. */+ action?: ReactNode;+}++/** Band order for the split bar: worst first, matching how the tables list. */+const BANDS = [+ { key: "thin", label: "Thin", max: 30, bar: "bg-[var(--color-error)]" },+ { key: "partial", label: "Partial", max: 60, bar: "bg-[var(--color-warning)]" },+ { key: "solid", label: "Solid", max: 80, bar: "bg-[var(--color-caution)]" },+ { key: "strong", label: "Strong", max: 101, bar: "bg-[var(--color-success)]" },+] as const;++export function CoverageLede({+ summary,+ files,+ moduleCount,+ action,+}: CoverageLedeProps) {+ const pct = summary.line_coverage_pct;+ const band = pct == null ? null : coverageBand(pct);+ const uncovered = Math.max(0, summary.total_lines - summary.covered_lines);++ // Weighted by coverable lines rather than by file count, for the same reason+ // the health distribution weights by NLOC: one large untested module must not+ // hide behind a hundred fully covered one-line shims.+ const split = useMemo(() => {+ const lines = BANDS.map(() => 0);+ let total = 0;+ for (const f of files) {+ // A file with no coverable lines has no percentage to band. Counting it+ // as 0% would invent a thin slice out of empty `__init__` files.+ if (f.total_coverable_lines <= 0 || f.line_coverage_pct == null) continue;+ const i = BANDS.findIndex((b) => f.line_coverage_pct! < b.max);+ const at = i === -1 ? BANDS.length - 1 : i;+ lines[at] = (lines[at] ?? 0) + f.total_coverable_lines;+ total += f.total_coverable_lines;+ }+ if (total === 0) return null;+ return BANDS.map((b, i) => ({+ ...b,+ pct: Math.round(((lines[i] ?? 0) / total) * 1000) / 10,+ })).filter((b) => b.pct > 0);+ }, [files]);++ const stats: RibbonStat[] = [+ {+ label: "Files instrumented",+ value: formatNumber(summary.file_count),+ ...(moduleCount > 0+ ? { sub: `across ${formatNumber(moduleCount)} directories` }+ : {}),+ },+ {+ label: "Uncovered lines",+ value: formatNumber(uncovered),+ sub: `of ${formatNumber(summary.total_lines)} coverable`,+ },+ {+ label: "Branch coverage",+ value:+ summary.branch_coverage_pct == null+ ? ""+ : `${summary.branch_coverage_pct.toFixed(1)}%`,+ hint: "Share of conditional branches a test takes both ways. Many runners emit no branch data at all, in which case this cell is absent rather than zero.",+ },+ {+ label: "Report format",+ value: (summary.source_format ?? "").toUpperCase(),+ ...(summary.ingested_at+ ? { sub: `ingested ${new Date(summary.ingested_at).toLocaleDateString()}` }+ : {}),+ },+ ];++ return (+ <div className="flex flex-col gap-6">+ <PageLede+ label="Line coverage"+ value={pct == null ? "—" : `${pct.toFixed(1)}%`}+ {...(band ? { valueColor: band.color, band } : {})}+ unit="of coverable lines"+ layout="beside"+ {...(action ? { action } : {})}+ figureFooter={split ? <BandSplit split={split} /> : undefined}+ >+ <p>+ Tests reach{" "}+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(summary.covered_lines)} of {formatNumber(summary.total_lines)}{" "}+ coverable lines+ </strong>{" "}+ across {formatNumber(summary.file_count)} instrumented files+ {moduleCount > 0 ? ` in ${formatNumber(moduleCount)} directories` : ""}.+ {band ? ` We rate that ${band.label.toLowerCase()}.` : ""} Coverage is read+ from your own test run, not inferred: nothing here is a guess about which+ lines a test would have touched.+ </p>++ <p className="mt-2.5">+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(uncovered)} lines+ </strong>{" "}+ have no test executing them. Where that matters is not evenly spread, which+ is what the map below is for: an uncovered line in a file nothing depends on+ and nobody edits costs little, and the same line in a file that changes+ weekly is where defects arrive.+ </p>++ {summary.source_format && (+ <p className="mt-2.5">+ Read from{" "}+ <span className="font-mono text-[var(--color-text-primary)]">+ {summary.source_format}+ </span>{" "}+ output+ {summary.ingested_at+ ? `, ingested ${new Date(summary.ingested_at).toLocaleString()}`+ : ""}+ {summary.ingested_commit_sha+ ? ` at ${summary.ingested_commit_sha.slice(0, 8)}`+ : ""}+ . Re-ingest after a test run to move these figures;{" "}+ {summary.branch_coverage_pct == null+ ? "this report carries no branch data, so branch coverage is absent rather than zero."+ : "branch coverage rides on the same report."}+ </p>+ )}+ </PageLede>++ <StatRibbon stats={stats} />+ </div>+ );+}++/** The one second read that belongs to the percentage itself. */+function BandSplit({+ split,+}: {+ split: { key: string; label: string; bar: string; pct: number }[];+}) {+ return (+ <div className="space-y-1.5">+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">+ {split.map((b) => (+ <div+ key={b.key}+ className={b.bar}+ style={{ width: `${b.pct}%` }}+ aria-label={`${b.label} ${b.pct}%`}+ />+ ))}+ </div>+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">+ {split.map((b) => (+ <span key={b.key} className="inline-flex items-center gap-1 tabular-nums">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${b.bar}`} />+ {b.pct}% {b.label.toLowerCase()}+ </span>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 3fa9584f9..09e5906ee 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -1,10 +1,18 @@"use client";/**- * Coverage view — test-coverage summary, risk × coverage scatter, untested- * hotspots (with the dependents/commit context from the findings), module- * rollup, and the per-file table. Rows link to the file page's coverage tab- * (line-level heatmap).+ * Coverage view, on the section design language.+ *+ * The shape is: a lede that leads with the coverage percentage and says in+ * prose what it is built from, then the health × coverage map, then the files+ * where a gap costs something, the module rollup and the per-file table, each+ * grouped by a hairline rather than boxed. Rows link to the file page's+ * coverage tab (the line-level heatmap).+ *+ * What it replaces: five `MetricCard`s in a grid above a bordered chart, a+ * tinted warning panel, a bordered module list and a collapsed table section.+ * Six containers at near-identical weight behind five uppercase labels, which+ * is the box-soup failure the section style exists to fix.** Presentation + orchestration only: the host injects data fetching, links,* and navigation through a {@link CodeHealthAdapter}.@@ -23,10 +31,10 @@ import { Skeleton } from "../ui/skeleton";import { EmptyState } from "../shared/empty-state";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { ResultsFooter } from "../shared/results-footer";-import { MetricCard } from "../shared/metric-card";-import { CollapsibleSection } from "../shared/collapsible-section";+import { OverviewSection } from "../overview/section";import { AiPromptModal } from "./ai-prompt-modal";+import { CoverageLede } from "./coverage-lede";import { CoverageBar } from "./coverage-bar";import { ModuleCoverageList } from "./module-coverage-list";import {@@ -65,7 +73,7 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {adapter.navigate(`${adapter.fileHref(path)}?tab=coverage`);return (- <div className="space-y-6">+ <div className="flex flex-col gap-6 sm:gap-8">{isLoading ? (<CoverageSkeleton />) : error ? (@@ -177,7 +185,15 @@ function CoverageBody({const scatterPoints = useMemo(() =>files- .filter((f) => f.health_score != null && f.line_coverage_pct != null)+ // Same rule as `covOf`: a file with no coverable lines has no coverage+ // percentage. It used to plot at 0% and pile up empty `__init__` files+ // against the left edge, exactly where "critical untested" is written.+ .filter(+ (f) =>+ f.health_score != null &&+ f.line_coverage_pct != null &&+ f.total_coverable_lines > 0,+ ).map((f) => ({file_path: f.file_path,health_score: f.health_score!,@@ -339,86 +355,42 @@ function CoverageBody({const activeColumns = columns.filter((c): c is ResponsiveColumn<CoverageFileRow> => c !== null,);- const uncoveredLines = summary.total_lines - summary.covered_lines;const fetchTruncated = summary.file_count > files.length;return (- <div className="space-y-6">- <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">- <MetricCard- label="Files instrumented"- value={summary.file_count.toLocaleString()}- />- <MetricCard- label="Line coverage"- value={- summary.line_coverage_pct == null- ? "—"- : `${summary.line_coverage_pct.toFixed(1)}%`- }- distBar={- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">- {summary.covered_lines.toLocaleString()} /{" "}- {summary.total_lines.toLocaleString()} lines- </span>- }- />- {hasBranch ? (- <MetricCard- label="Branch coverage"- value={- summary.branch_coverage_pct == null- ? "—"- : `${summary.branch_coverage_pct.toFixed(1)}%`- }- />- ) : (- <MetricCard- label="Uncovered lines"- value={uncoveredLines.toLocaleString()}- distBar={- <span className="text-xs text-[var(--color-text-tertiary)]">- lines with no test coverage- </span>- }- />- )}- <MetricCard- label="Source"- value={- <span className="text-lg uppercase">{summary.source_format ?? "—"}</span>- }- distBar={- <span className="text-xs text-[var(--color-text-tertiary)]">- {summary.ingested_at- ? new Date(summary.ingested_at).toLocaleString()- : "never"}- </span>- }- />- </div>+ <div className="flex flex-col gap-6 sm:gap-8">+ <CoverageLede summary={summary} files={files} moduleCount={modules.length} />- <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onOpenFile(p.file_path)} />+ <OverviewSection+ title="Health against coverage"+ description="Every instrumented file placed by its defect-risk score and its line coverage, sized by lines of code. The bottom-left quadrant is the one that costs money: code we score as weak, with no test watching it. Click a file to open its line-level heatmap."+ >+ <RiskCoverageScatter+ points={scatterPoints}+ onSelect={(p) => onOpenFile(p.file_path)}+ />+ </OverviewSection>{untested.length > 0 ? (- <UntestedHotspotWarning entries={untested} onSelect={onOpenFile} />+ <OverviewSection+ title="Untested hotspots"+ description="Files that change often or that much of the codebase depends on, with little or no coverage. A gap here is worth more than the same gap in code nobody touches."+ >+ <UntestedHotspotWarning entries={untested} onSelect={onOpenFile} />+ </OverviewSection>) : null}- <section className="space-y-2">- <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">- Module coverage- </h2>+ <OverviewSection+ title="Module coverage"+ description="Directories rolled up under their top-level package, weighted by coverable lines and worst covered first. A directory with no coverable lines reads as no data rather than as a red zero."+ ><ModuleCoverageList modules={modules} />- </section>+ </OverviewSection>- <CollapsibleSection- title={`Files (${summary.file_count.toLocaleString()})`}- defaultOpen={false}- >- <div className="flex items-center gap-2">- <span className="mr-auto text-xs text-[var(--color-text-tertiary)]">- Per-file coverage — click a row for the line-level heatmap.- </span>+ <OverviewSection+ title="Every file"+ description="Sorted worst first. Click a row for the line-level heatmap, or the prompt icon to draft a brief that has your AI agent write the missing tests."+ action={<inputvalue={search}onChange={(e) => {@@ -426,10 +398,12 @@ function CoverageBody({setVisible(PAGE);}}placeholder="Filter path…"- className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"+ aria-label="Filter files by path"+ className="w-48 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs focus:border-[var(--color-border-strong)] focus:outline-none sm:w-56"/>- </div>- <div className="overflow-hidden rounded-lg border border-[var(--color-border-default)]">+ }+ >+ <div className="border-t border-[var(--color-border-default)]"><ResponsiveTablecolumns={activeColumns}rows={visibleFiles}@@ -460,48 +434,53 @@ function CoverageBody({{fetchTruncated ? (<p className="text-xs text-[var(--color-text-tertiary)]">Showing {files.length.toLocaleString()} of{" "}- {summary.file_count.toLocaleString()} instrumented files (capped for- performance).+ {summary.file_count.toLocaleString()} instrumented files, capped so one+ tab does not pull the whole repository.</p>) : null}- </CollapsibleSection>+ </OverviewSection></div>);}+/**+ * Says what will fill the page, not that something is missing. The two commands+ * are the whole setup, so they are the content rather than a footnote under a+ * dashed placeholder box.+ */function NoCoverageState() {return (- <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">- <div className="max-w-xl mx-auto text-center space-y-3">- <h2 className="text-base font-semibold text-[var(--color-text-primary)]">- No coverage data ingested yet- </h2>- <p className="text-sm text-[var(--color-text-secondary)]">- Run your test suite with coverage enabled, then ingest the report.- You'll see a risk × coverage map, untested-hotspot warnings, and a- per-module breakdown.- </p>- <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">- pytest --cov --cov-report=lcov{"\n"}- repowise coverage add coverage.lcov- </pre>- <p className="text-xs text-[var(--color-text-tertiary)]">- Supported formats: LCOV · Cobertura · Clover.- </p>- </div>+ <div className="flex max-w-[62ch] flex-col gap-3">+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">+ No coverage report ingested yet+ </h2>+ <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ Run your test suite with coverage on and hand us the report. This tab then+ plots every file by health against coverage, names the files where a gap+ actually costs something, and rolls the numbers up per directory. Nothing is+ inferred: we read the lines your tests really executed.+ </p>+ <pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-muted)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">+ pytest --cov --cov-report=lcov{"\n"}+ repowise coverage add coverage.lcov+ </pre>+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ LCOV · Cobertura · Clover+ </p></div>);}+/** Shapes and widths match the real layout, so nothing reflows when data lands. */function CoverageSkeleton() {return (- <div className="space-y-6">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-24 w-full rounded-lg" />- ))}+ <div className="flex flex-col gap-6 sm:gap-8">+ <div className="flex flex-col gap-5 lg:flex-row lg:gap-12">+ <Skeleton className="h-[92px] w-full rounded-lg lg:w-[220px]" />+ <Skeleton className="h-[92px] w-full max-w-[62ch] rounded-lg" /></div>- <Skeleton className="h-72 w-full rounded-lg" />+ <Skeleton className="h-[74px] w-full" />+ <Skeleton className="h-[340px] w-full rounded-lg" /><Skeleton className="h-48 w-full rounded-lg" /></div>);diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex 3bef8414c..c085ca62f 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -36,6 +36,7 @@ export * from "./hot-functions-panel";export * from "./hidden-coupling-list";export * from "./defect-accuracy-card";export * from "./code-health-lede";+export * from "./coverage-lede";export * from "./severity-mark";export * from "./code-health-adapter";export * from "./triage-view";diff --git a/packages/ui/src/health/module-coverage-list.tsx b/packages/ui/src/health/module-coverage-list.tsxindex c1772b994..76df4755d 100644--- a/packages/ui/src/health/module-coverage-list.tsx+++ b/packages/ui/src/health/module-coverage-list.tsx@@ -115,7 +115,9 @@ export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageLi/></div>- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">+ {/* Hairlines, not a card. The rows are the content; a border plus a raised+ ground around them makes the list read as one object you act on. */}+ <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">{filtered.map((g) => {const expanded = isOpen(g.key);return (@@ -123,7 +125,7 @@ export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageLi<buttontype="button"onClick={() => toggle(g.key)}- className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-[var(--color-bg-elevated)]"+ className="flex w-full items-center gap-3 px-2 py-3 text-left hover:bg-[var(--color-bg-elevated)]"aria-expanded={expanded}><ChevronRight@@ -148,7 +150,7 @@ export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageLireturn (<divkey={c.module}- className={`flex items-center gap-3 py-2 pl-11 pr-4 ${onSelectModule ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}+ className={`flex items-center gap-3 py-2 pl-9 pr-2 ${onSelectModule ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}onClick={onSelectModule ? () => onSelectModule(c.module) : undefined}><spandiff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxindex 72045e50c..4dbee2200 100644--- a/packages/ui/src/health/risk-coverage-scatter.tsx+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";export interface RiskCoveragePoint {file_path: string;@@ -16,148 +16,237 @@ export interface RiskCoverageScatterProps {}/**- * Health × Coverage quadrant chart. Y axis = health (0–10, higher is better),- * X axis = line coverage % (0–100). Each dot is one file; radius encodes NLOC.+ * Health × coverage quadrant plot. Y axis is the defect-risk score (0 to 10,+ * higher is better), X axis is line coverage (0 to 100), and dot radius encodes+ * lines of code.*- * Quadrant labels:- * - Top-right (high health, high cov): Sweet spot- * - Top-left (high health, low cov): Risky — fix tests first- * - Bot-right (low health, high cov): Tested but messy- * - Bot-left (low health, low cov): Critical untested hotspot+ * - Top right (healthy, covered): Sweet spot+ * - Top left (healthy, uncovered): Risky, needs tests+ * - Bottom right (weak, covered): Tested but messy+ * - Bottom left (weak, uncovered): Critical hotspot+ *+ * Three things here are deliberate rather than incidental:+ *+ * The SVG sizes to its container instead of scaling a fixed 640-unit viewBox.+ * Inside a full-width section that box was being scaled by ~2.4, so every 10px+ * axis label rendered at 24px and the quadrant captions outweighed the field+ * they annotate. One unit is now one CSS pixel at every width, which also makes+ * the tooltip's position a plain read of the point's coordinates.+ *+ * The dot field is memoised away from the hover state. It is one element per+ * file and a real repo brings ~1,400 of them; without the split, moving the+ * pointer reconciled the whole field on every event.+ *+ * No `<title>` child per dot. That is a second DOM node per file for a native+ * tooltip that fires on its own delay and fights the hover card below. The path+ * rides on `data-file` instead, which is also a stable handle for tests.*/export function RiskCoverageScatter({points,onSelect,- height = 320,+ height = 340,}: RiskCoverageScatterProps) {- const [hovered, setHovered] = useState<RiskCoveragePoint | null>(null);+ const containerRef = useRef<HTMLDivElement | null>(null);+ // Seeded rather than zero so the first paint is a plausible chart instead of+ // an empty box that reflows a frame later.+ const [width, setWidth] = useState(900);+ const [hovered, setHovered] = useState<number | null>(null);++ useEffect(() => {+ const el = containerRef.current;+ if (!el || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver((entries) => {+ const w = entries[0]?.contentRect.width;+ if (w && w > 0) setWidth(w);+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);+const data = useMemo(- () => points.filter((p) => p.line_coverage_pct != null && Number.isFinite(p.health_score)),+ () =>+ points.filter(+ (p) => p.line_coverage_pct != null && Number.isFinite(p.health_score),+ ),[points],);+ const geom = useMemo(() => {+ const W = Math.max(320, Math.round(width));+ const H = height;+ const padL = 36;+ const padR = 16;+ const padT = 22;+ const padB = 32;+ const plotW = W - padL - padR;+ const plotH = H - padT - padB;+ const maxNloc = Math.max(...data.map((d) => d.nloc), 1);+ const xScale = (pct: number) => padL + (pct / 100) * plotW;+ const yScale = (score: number) => padT + ((10 - score) / 10) * plotH;+ const radius = (nloc: number) => 2 + Math.min(7, Math.sqrt(nloc / maxNloc) * 7);+ return {+ W,+ H,+ padL,+ padR,+ padT,+ padB,+ xScale,+ yScale,+ radius,+ // 60% coverage and a 7.0 score are the quadrant thresholds.+ midX: xScale(60),+ midY: yScale(7),+ };+ }, [width, height, data]);++ // The expensive part, held apart from `hovered` so pointer movement does not+ // rebuild one element per file. React bails out of reconciling a subtree whose+ // element is referentially identical, so this is what keeps hover cheap.+ const field = useMemo(+ () => (+ <g>+ {data.map((p, i) => (+ <circle+ key={p.file_path}+ data-file={p.file_path}+ data-i={i}+ cx={geom.xScale(p.line_coverage_pct ?? 0)}+ cy={geom.yScale(p.health_score)}+ r={geom.radius(p.nloc)}+ className={`${bandFill(p.health_score)} ${onSelect ? "cursor-pointer" : ""}`}+ fillOpacity={0.7}+ />+ ))}+ </g>+ ),+ [data, geom, onSelect],+ );+if (data.length === 0) {return (- <div- className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)] text-center"- style={{ minHeight: height }}- >- Ingest a coverage report to see the risk × coverage map for every file.- </div>+ <p className="text-sm text-[var(--color-text-tertiary)]">+ No file carries both a health score and a coverage figure yet, so there is+ nothing to plot.+ </p>);}- const W = 640;- const H = height;- const padL = 40;- const padR = 12;- const padT = 24;- const padB = 30;- const plotW = W - padL - padR;- const plotH = H - padT - padB;+ const { W, H, padL, padR, padT, padB, midX, midY, xScale, yScale } = geom;+ const active = hovered != null ? data[hovered] : undefined;- const maxNloc = Math.max(...data.map((d) => d.nloc), 1);-- const xScale = (pct: number) => padL + (pct / 100) * plotW;- const yScale = (score: number) => padT + ((10 - score) / 10) * plotH;- const r = (nloc: number) => 2 + Math.min(7, Math.sqrt(nloc / maxNloc) * 7);-- const midX = xScale(60); // 60% coverage threshold- const midY = yScale(7); // 7.0 health threshold+ // Delegated: one handler on the svg rather than two props on every dot.+ const indexFrom = (target: EventTarget): number | null => {+ const raw = (target as SVGElement)?.getAttribute?.("data-i");+ return raw == null ? null : Number(raw);+ };return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">- <div className="mb-2 flex items-baseline gap-2">- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- Risk × coverage map- </h3>- <span className="text-xs text-[var(--color-text-tertiary)]">- {data.length} files · dot size = NLOC- </span>- </div>- <div className="relative">- <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Risk vs coverage scatter plot">- {/* Quadrant tinting */}+ <div className="flex flex-col gap-2.5">+ <div ref={containerRef} className="relative">+ <svg+ viewBox={`0 0 ${W} ${H}`}+ width="100%"+ height={H}+ role="img"+ aria-label="Health against line coverage, one dot per file"+ onMouseOver={(e) => setHovered(indexFrom(e.target))}+ onMouseOut={() => setHovered(null)}+ onClick={(e) => {+ if (!onSelect) return;+ const i = indexFrom(e.target);+ const point = i == null ? undefined : data[i];+ if (point) onSelect(point);+ }}+ >+ {/* Quadrant tinting. Faint enough to read as ground rather than as+ four coloured panels the dots sit on top of. */}<rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" /><rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/5" /><rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/8" /><rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />- {/* Axes */}+ {/* Axes and the two thresholds */}<line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} /><line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} /><line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" /><line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />- {/* Axis labels */}{[0, 25, 50, 75, 100].map((v) => (- <g key={`x${v}`}>- <text x={xScale(v)} y={H - padB + 14} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>- {v}%- </text>- </g>+ <text key={`x${v}`} x={xScale(v)} y={H - padB + 15} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>+ {v}%+ </text>))}{[0, 2, 4, 6, 8, 10].map((v) => (- <g key={`y${v}`}>- <text x={padL - 6} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>- {v}- </text>- </g>+ <text key={`y${v}`} x={padL - 7} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>+ {v}+ </text>))}- <text x={W / 2} y={H - 4} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>- Line coverage %+ <text x={padL + (W - padL - padR) / 2} y={H - 3} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ Line coverage</text>- <text x={10} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 10 ${H / 2})`}>+ <text x={11} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 11 ${H / 2})`}>Health score</text>- {/* Quadrant captions */}- <text x={padL + 6} y={padT + 14} fontSize={10} fill="currentColor" opacity={0.5}>Risky — needs tests</text>- <text x={W - padR - 6} y={padT + 14} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Sweet spot</text>- <text x={padL + 6} y={H - padB - 6} fontSize={10} fill="currentColor" opacity={0.5}>Critical hotspot</text>- <text x={W - padR - 6} y={H - padB - 6} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Tested but messy</text>-- {/* Points */}- {data.map((p) => {- const cx = xScale(p.line_coverage_pct ?? 0);- const cy = yScale(p.health_score);- const isHovered = hovered?.file_path === p.file_path;- const fillCls =- p.health_score < 4- ? "fill-[var(--color-error)]"- : p.health_score < 6- ? "fill-[var(--color-warning)]"- : p.health_score < 8- ? "fill-[var(--color-caution)]"- : "fill-[var(--color-success)]";- return (- <circle- key={p.file_path}- cx={cx}- cy={cy}- r={r(p.nloc) * (isHovered ? 1.4 : 1)}- className={`${fillCls} ${onSelect ? "cursor-pointer" : ""}`}- fillOpacity={0.7}- stroke={isHovered ? "white" : "none"}- strokeWidth={1.5}- onMouseEnter={() => setHovered(p)}- onMouseLeave={() => setHovered(null)}- onClick={onSelect ? () => onSelect(p) : undefined}- >- <title>{`${p.file_path}\nHealth ${p.health_score.toFixed(1)} · Cov ${p.line_coverage_pct?.toFixed(0)}% · NLOC ${p.nloc}`}</title>- </circle>- );- })}+ {/* Quadrant captions. These stay on the canvas because they name a+ region of it; the chart's key, which does not, sits underneath. */}+ <text x={padL + 8} y={padT + 14} fontSize={10} fill="currentColor" opacity={0.5}>Risky, needs tests</text>+ <text x={W - padR - 8} y={padT + 14} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Sweet spot</text>+ <text x={padL + 8} y={H - padB - 8} fontSize={10} fill="currentColor" opacity={0.5}>Critical hotspot</text>+ <text x={W - padR - 8} y={H - padB - 8} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Tested but messy</text>++ {field}++ {/* The hover ring is drawn over the field rather than by re-rendering+ the hovered dot, which would take the whole field with it. */}+ {active && (+ <circle+ cx={xScale(active.line_coverage_pct ?? 0)}+ cy={yScale(active.health_score)}+ r={geom.radius(active.nloc) * 1.5}+ className={bandFill(active.health_score)}+ fillOpacity={0.9}+ stroke="var(--color-text-primary)"+ strokeWidth={1.5}+ pointerEvents="none"+ />+ )}</svg>- {hovered ? (- <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md">- <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>- <span className="ml-2 text-[var(--color-text-tertiary)]">- {hovered.health_score.toFixed(1)} · {hovered.line_coverage_pct?.toFixed(0)}% · {hovered.nloc} NLOC++ {active && (+ <div+ className="pointer-events-none absolute z-10 max-w-[min(320px,80%)] -translate-x-1/2 -translate-y-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md"+ style={{+ // Clamped so a dot against either edge does not push the card out+ // of the plot; the offset lifts it clear of its own dot.+ left: Math.min(Math.max(xScale(active.line_coverage_pct ?? 0), 110), W - 110),+ top: yScale(active.health_score) - 10,+ }}+ >+ <span className="block truncate font-mono text-[var(--color-text-primary)]">+ {active.file_path}+ </span>+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ {active.health_score.toFixed(1)} health ·{" "}+ {active.line_coverage_pct?.toFixed(0)}% covered · {active.nloc} lines</span></div>- ) : null}+ )}</div>++ <p className="border-t border-[var(--color-border-default)] pt-2 font-mono text-[10px] uppercase tracking-[0.12em] tabular-nums text-[var(--color-text-tertiary)]">+ {data.length.toLocaleString()} files · dot size = lines of code · thresholds+ at 60% coverage and 7.0 health+ </p></div>);}++/** Fill by health band. The bands are the same ones the rest of health uses. */+function bandFill(score: number): string {+ if (score < 4) return "fill-[var(--color-error)]";+ if (score < 6) return "fill-[var(--color-warning)]";+ if (score < 8) return "fill-[var(--color-caution)]";+ return "fill-[var(--color-success)]";+}diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.tsindex 4a0e98569..143d24057 100644--- a/packages/ui/src/health/tokens.ts+++ b/packages/ui/src/health/tokens.ts@@ -172,6 +172,30 @@ export function coverageColor(pct: number): string {return "bg-[var(--color-success)]";}+/**+ * Coverage as a band, at the thresholds {@link coverageColor} already paints.+ *+ * One function for the same reason `healthBand()` is one function: the coverage+ * lede prints the label, the figure takes the colour and the distribution bar+ * segments by it, and three call sites disagreeing about where "Strong" starts+ * is worse than the duplication that avoids it.+ */+export function coverageBand(pct: number): { color: string; label: string } {+ if (pct < 30) return { color: "var(--color-error)", label: "Thin" };+ if (pct < 60) return { color: "var(--color-warning)", label: "Partial" };+ if (pct < 80) return { color: "var(--color-caution)", label: "Solid" };+ return { color: "var(--color-success)", label: "Strong" };+}++/** Tailwind text colour for a coverage figure, on the same bands. */+export function coverageTextColor(pct: number | null | undefined): string {+ if (pct == null) return "text-[var(--color-text-primary)]";+ if (pct < 30) return "text-[var(--color-error)]";+ if (pct < 60) return "text-[var(--color-warning)]";+ if (pct < 80) return "text-[var(--color-caution)]";+ return "text-[var(--color-success)]";+}+export function deltaColor(delta: number | null | undefined): string {if (delta == null || delta === 0) return "text-[var(--color-text-tertiary)]";return delta > 0 ? "text-[var(--color-success)]" : "text-[var(--color-error)]";diff --git a/packages/ui/src/health/untested-hotspot-warning.tsx b/packages/ui/src/health/untested-hotspot-warning.tsxindex 4b6733a16..0d9189713 100644--- a/packages/ui/src/health/untested-hotspot-warning.tsx+++ b/packages/ui/src/health/untested-hotspot-warning.tsx@@ -1,4 +1,6 @@-import { AlertTriangle, ArrowUpRight } from "lucide-react";+import { ArrowUpRight } from "lucide-react";++import { coverageBand } from "./tokens";export interface UntestedHotspotEntry {file_path: string;@@ -15,72 +17,82 @@ export interface UntestedHotspotWarningProps {onSelect?: ((filePath: string) => void) | undefined;}+/**+ * The files where a coverage gap actually costs something, as hairline rows.+ *+ * It used to be a tinted warning panel with its own border, icon, heading and+ * description, which is four pieces of chrome around a list the section header+ * now names. The colour moved onto the one figure that carries a band, the+ * coverage percentage, so a file at 0% reads louder than one at 28% instead of+ * every row reading equally alarming because the panel behind them is amber.+ */export function UntestedHotspotWarning({entries,- limit = 5,+ limit = 6,onSelect,}: UntestedHotspotWarningProps) {if (entries.length === 0) return null;const shown = entries.slice(0, limit);+return (- <div className="rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5 p-4">- <div className="flex items-start gap-2 mb-2">- <AlertTriangle className="h-4 w-4 text-[var(--color-warning)] mt-0.5" />- <div>- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- Untested hotspots- </h3>- <p className="text-xs text-[var(--color-text-secondary)]">- High-churn, centrally depended-on files with little or no test coverage.- </p>- </div>- </div>- <ul className="space-y-0.5">+ <div className="flex flex-col">+ <ul className="border-t border-[var(--color-border-default)]">{shown.map((e) => {- const meta = (- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">- {e.line_coverage_pct == null- ? "no coverage data"- : `${e.line_coverage_pct.toFixed(0)}% covered`}- {e.dependents_count != null && ` · ${e.dependents_count} dependents`}- {e.commit_count_90d != null &&- e.commit_count_90d > 0 &&- ` · ${e.commit_count_90d} commits/90d`}- </span>+ const body = (+ <>+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-[var(--color-text-primary)]">+ {e.file_path}+ </span>+ <span className="shrink-0 tabular-nums text-xs text-[var(--color-text-tertiary)]">+ {e.dependents_count != null && `${e.dependents_count} dependents`}+ {e.dependents_count != null &&+ e.commit_count_90d != null &&+ e.commit_count_90d > 0 &&+ " · "}+ {e.commit_count_90d != null &&+ e.commit_count_90d > 0 &&+ `${e.commit_count_90d} commits in 90d`}+ </span>+ <span+ className="w-[4.5rem] shrink-0 text-right text-xs font-semibold tabular-nums"+ style={{+ color:+ e.line_coverage_pct == null+ ? "var(--color-text-tertiary)"+ : coverageBand(e.line_coverage_pct).color,+ }}+ >+ {e.line_coverage_pct == null+ ? "no data"+ : `${e.line_coverage_pct.toFixed(0)}%`}+ </span>+ </>);- if (onSelect) {- return (- <li key={e.file_path}>++ return (+ <li+ key={e.file_path}+ className="border-b border-[var(--color-border-default)]"+ >+ {onSelect ? (<buttontype="button"onClick={() => onSelect(e.file_path)}- className="group flex w-full flex-wrap items-baseline gap-x-3 rounded-md px-2 py-1 text-left text-sm hover:bg-[var(--color-warning)]/10"+ className="group flex w-full items-baseline gap-x-4 py-2.5 text-left hover:bg-[var(--color-bg-elevated)]">- <span className="inline-flex items-center gap-1 font-mono text-[var(--color-text-primary)] truncate">- <span className="truncate">{e.file_path}</span>- <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-warning)]" />- </span>- {meta}+ {body}+ <ArrowUpRight className="h-3 w-3 shrink-0 self-center text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" /></button>- </li>- );- }- return (- <li- key={e.file_path}- className="flex flex-wrap items-baseline gap-x-3 px-2 py-1 text-sm"- >- <span className="font-mono text-[var(--color-text-primary)] truncate">- {e.file_path}- </span>- {meta}+ ) : (+ <div className="flex w-full items-baseline gap-x-4 py-2.5">{body}</div>+ )}</li>);})}</ul>{entries.length > limit && (- <p className="text-xs text-[var(--color-text-tertiary)] mt-2">- + {entries.length - limit} more+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ {entries.length - limit} more sit in the file table below.</p>)}</div>