Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ui): rebuild Code Health on the section design language (#1129)

Raghav Chamadiya914e121591a2
diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsx
index 30ce1b42a..0d5a68e6e 100644
--- a/packages/ui/__tests__/health/code-health-map.test.tsx
+++ b/packages/ui/__tests__/health/code-health-map.test.tsx
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeAll } from "vitest";
import { render, fireEvent } from "@testing-library/react";
import {
CodeHealthMap,
+ MapLegend,
+ MapLensSwitcher,
groupByModule,
type CodeHealthMapFile,
} from "../../src/health/code-health-map.js";
@@ -71,19 +73,45 @@ describe("CodeHealthMap", () => {
f("ui/c.py", 40, "ui", 6),
];
const { container } = render(<CodeHealthMap files={files} onSelectFile={onSelectFile} />);
- // Nodes carry a <title> with the path; pick one and click its circle.
- const titles = Array.from(container.querySelectorAll("title"));
- const target = titles.find((t) => t.textContent?.startsWith("core/a.py"));
+ // Nodes carry their path on data-path (there is no <title>: it was ~2,000
+ // extra nodes driving a native tooltip that duplicated the hover card).
+ const target = container.querySelector('circle[data-path="core/a.py"]');
expect(target).toBeTruthy();
- fireEvent.click(target!.parentElement!);
+ fireEvent.click(target!);
expect(onSelectFile).toHaveBeenCalledWith("core/a.py");
});
+ it("draws file nodes without a per-node <title> or non-scaling-stroke", () => {
+ const files = [f("core/a.py", 120, "core"), f("core/b.py", 60, "core")];
+ const { container } = render(<CodeHealthMap files={files} />);
+ // Both were per-frame costs on a ~2,000 element layer that re-rasters
+ // through a 460ms zoom transition. Asserted so neither creeps back.
+ expect(container.querySelectorAll("title")).toHaveLength(0);
+ expect(
+ container.querySelectorAll("circle[data-path][vector-effect]"),
+ ).toHaveLength(0);
+ });
+
+ it("keeps the node stroke at 0.5 device px by pre-dividing by the zoom scale", () => {
+ const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
+ const { container } = render(<CodeHealthMap files={files} />);
+ const node = () => container.querySelector('circle[data-path="core/a.py"]');
+ // Unzoomed, k === 1, so the raw stroke is the target width.
+ expect(Number(node()!.getAttribute("stroke-width"))).toBeCloseTo(0.5, 5);
+
+ // Zoom into a galaxy: k > 1, so the user-unit stroke has to shrink by the
+ // same factor to land back on 0.5px once the transform scales it up.
+ fireEvent.click(container.querySelector("circle[data-galaxy]")!);
+ const zoomed = Number(node()!.getAttribute("stroke-width"));
+ expect(zoomed).toBeLessThan(0.5);
+ expect(zoomed).toBeGreaterThan(0);
+ });
+
it("zooms into a galaxy and Escape returns to the overview", () => {
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
const { getByText, queryByText, container } = render(<CodeHealthMap files={files} />);
- // Click a galaxy nebula (a blurred blob) to focus it.
- const blob = container.querySelector('circle[filter="url(#ch-nebula)"]');
+ // Click a galaxy nebula to focus it.
+ const blob = container.querySelector("circle[data-galaxy]");
expect(blob).toBeTruthy();
fireEvent.click(blob!);
expect(getByText("← Overview")).toBeInTheDocument();
@@ -122,12 +150,8 @@ describe("CodeHealthMap", () => {
expect(getByText("Not analyzed")).toBeInTheDocument();
expect(getByText("Analyzed, none found")).toBeInTheDocument();
- const fillFor = (path: string) => {
- const title = Array.from(container.querySelectorAll("title")).find((t) =>
- t.textContent?.startsWith(path),
- );
- return (title?.parentElement as SVGCircleElement | undefined)?.getAttribute("fill");
- };
+ const fillFor = (path: string) =>
+ container.querySelector(`circle[data-path="${path}"]`)?.getAttribute("fill");
// A file with findings burns red; a covered-clean file is green; an
// un-analyzed file is grey (tertiary) — never green.
expect(fillFor("core/hot.py")).toBe("var(--color-error)");
@@ -147,4 +171,66 @@ describe("CodeHealthMap", () => {
fireEvent.click(getByRole("button", { name: "Maintainability" }));
expect(onOverlayChange).toHaveBeenCalledWith("maintainability");
});
+
+ it('offers only the lenses it was given', () => {
+ const { getByRole, queryByRole } = render(
+ <CodeHealthMap
+ files={[f("a.py", 30, "core")]}
+ onOverlayChange={vi.fn()}
+ lenses={["health", "churn"]}
+ />,
+ );
+ expect(getByRole("button", { name: "Churn" })).toBeInTheDocument();
+ // Churn is not a default lens: it colors from a field the host has to join
+ // in, so a host that did not join it must not be able to select it.
+ expect(queryByRole("button", { name: "Maintainability" })).not.toBeInTheDocument();
+ });
+
+ it('chrome="none" renders neither the switcher nor the legend', () => {
+ const { queryByText, queryByRole } = render(
+ <CodeHealthMap
+ files={[f("a.py", 30, "core")]}
+ onOverlayChange={vi.fn()}
+ chrome="none"
+ />,
+ );
+ expect(queryByRole("button", { name: "Maintainability" })).not.toBeInTheDocument();
+ expect(queryByText(/galaxy = module/i)).not.toBeInTheDocument();
+ });
+
+ it('defaults to chrome="canvas" so hosts with no other lens picker keep one', () => {
+ // The VS Code webview passes onOverlayChange and renders no lens UI of its
+ // own; the on-canvas switcher is its only picker.
+ const { getByRole } = render(
+ <CodeHealthMap files={[f("a.py", 30, "core")]} onOverlayChange={vi.fn()} />,
+ );
+ expect(getByRole("button", { name: "Maintainability" })).toBeInTheDocument();
+ });
+});
+
+describe("map chrome, off canvas", () => {
+ it("MapLensSwitcher is a radiogroup and reports the picked lens", () => {
+ const onOverlayChange = vi.fn();
+ const { getByRole } = render(
+ <MapLensSwitcher overlay="health" onOverlayChange={onOverlayChange} />,
+ );
+ expect(getByRole("radiogroup", { name: "Map lens" })).toBeInTheDocument();
+ expect(getByRole("radio", { name: "Health" })).toBeChecked();
+ fireEvent.click(getByRole("radio", { name: "Performance" }));
+ expect(onOverlayChange).toHaveBeenCalledWith("performance");
+ });
+
+ it("MapLegend renders the active lens's bands and caption", () => {
+ const { getByText } = render(<MapLegend overlay="performance" />);
+ expect(getByText("5+ findings")).toBeInTheDocument();
+ expect(getByText("Not analyzed")).toBeInTheDocument();
+ expect(getByText(/color = findings, not a score/i)).toBeInTheDocument();
+ });
+
+ it("MapLegend says it is loading rather than showing bands for absent data", () => {
+ const { getByText, queryByText } = render(<MapLegend overlay="churn" loading />);
+ expect(getByText(/loading churn/i)).toBeInTheDocument();
+ // An all-neutral field must not be captioned as though it were measured.
+ expect(queryByText("Top 10%")).not.toBeInTheDocument();
+ });
});
diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsx
index 8cb0c92ab..2567011b6 100644
--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx
+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx
@@ -71,7 +71,14 @@ describe("HealthFileDrawer finding grouping", () => {
});
});
-describe("HealthFileDrawer metric cards", () => {
+describe("HealthFileDrawer metrics", () => {
+ /** Read one cell of the metric list by its label, so these assertions do not
+ * move every time another field joins the grid. */
+ function cellValue(label: string): string {
+ const dt = screen.getByText(label);
+ return dt.parentElement?.querySelector("dd")?.textContent?.trim() ?? "";
+ }
+
it("says 'not measured' instead of 0 when structural counters are absent", () => {
render(
<HealthFileDrawer
@@ -80,7 +87,9 @@ describe("HealthFileDrawer metric cards", () => {
metric={metric({ max_ccn: null, max_nesting: null, nloc: null })}
/>,
);
- expect(screen.getAllByText("not measured")).toHaveLength(3);
+ expect(cellValue("Max CCN")).toBe("not measured");
+ expect(cellValue("Nesting")).toBe("not measured");
+ expect(cellValue("NLOC")).toBe("not measured");
});
it("still renders real zero values as numbers", () => {
@@ -91,8 +100,54 @@ describe("HealthFileDrawer metric cards", () => {
metric={metric({ max_ccn: 0, max_nesting: 0, nloc: 12 })}
/>,
);
- expect(screen.queryByText("not measured")).not.toBeInTheDocument();
- expect(screen.getByText("12")).toBeInTheDocument();
+ expect(cellValue("Max CCN")).toBe("0");
+ expect(cellValue("Nesting")).toBe("0");
+ expect(cellValue("NLOC")).toBe("12");
+ });
+
+ it("applies the same rule to the pillar scores and the percentages", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric()} />);
+ // An unscored pillar is not a zero-risk pillar, and no coverage data is not
+ // 0% coverage.
+ expect(cellValue("Maintainability")).toBe("not measured");
+ expect(cellValue("Performance")).toBe("not measured");
+ expect(cellValue("Coverage")).toBe("not measured");
+ expect(cellValue("Duplication")).toBe("not measured");
+ });
+
+ it("leads with the file's own score and band", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: 1.0 })} />);
+ expect(screen.getByText("1.0")).toBeInTheDocument();
+ expect(screen.getByText("Critical")).toBeInTheDocument();
+ });
+
+ it("offers one link to the full page", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ permalinkHref="/repos/r1/files/a.py?tab=health"
+ />,
+ );
+ const links = screen.getAllByRole("link", { name: /open full page/i });
+ expect(links).toHaveLength(1);
+ expect(links[0]).toHaveAttribute("href", "/repos/r1/files/a.py?tab=health");
+ });
+
+ it("falls back to the file view when there is no permalink", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ fileViewHref="/repos/r1/files/a.py"
+ />,
+ );
+ expect(screen.getByRole("link", { name: /open full page/i })).toHaveAttribute(
+ "href",
+ "/repos/r1/files/a.py",
+ );
});
});
diff --git a/packages/ui/src/blast-radius/impact-view.tsx b/packages/ui/src/blast-radius/impact-view.tsx
index 6a013f82b..3021d0ab4 100644
--- a/packages/ui/src/blast-radius/impact-view.tsx
+++ b/packages/ui/src/blast-radius/impact-view.tsx
@@ -11,7 +11,7 @@
* and hosted render the same view from one source.
*/
-import { useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import useSWR from "swr";
import { Plus, Flame } from "lucide-react";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
@@ -24,8 +24,23 @@ import { BlastRadiusResults } from "./blast-radius-results";
import type { ImpactAdapter } from "./impact-adapter";
import { toFriendlyMessage } from "../lib/errors";
-export function ImpactView({ adapter }: { adapter: ImpactAdapter }) {
- const [selected, setSelected] = useState<string[]>([]);
+export function ImpactView({
+ adapter,
+ initialFiles,
+}: {
+ adapter: ImpactAdapter;
+ /**
+ * Files to seed the selection with, and analyze on arrival.
+ *
+ * Nobody browses to this view: every route into it is a per-file CTA — the
+ * "Blast Radius" button on a file card, "View blast radius for X" in the
+ * symbol drawer. Both already know the path, and without this they landed on
+ * an empty picker and asked the reader to retype the path they had just
+ * clicked. Undefined keeps the blank analyzer, for a direct visit.
+ */
+ initialFiles?: string[];
+}) {
+ const [selected, setSelected] = useState<string[]>(initialFiles ?? []);
const [maxDepth, setMaxDepth] = useState(3);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -57,24 +72,46 @@ export function ImpactView({ adapter }: { adapter: ImpactAdapter }) {
addPaths(hotspotSuggestions.map((h) => h.file_path));
};
- const handleAnalyze = async () => {
- if (selected.length === 0) {
- setError("Add at least one file path.");
- return;
- }
- setLoading(true);
- setError(null);
- setResult(null);
- try {
- const data = await adapter.analyze({ changedFiles: selected, maxDepth });
- setResult(data);
- setAnalyzedFiles(selected);
- } catch (err) {
- setError(toFriendlyMessage(err, "Analysis failed."));
- } finally {
- setLoading(false);
- }
- };
+ const runAnalysis = useCallback(
+ async (files: string[]) => {
+ if (files.length === 0) {
+ setError("Add at least one file path.");
+ return;
+ }
+ setLoading(true);
+ setError(null);
+ setResult(null);
+ try {
+ const data = await adapter.analyze({ changedFiles: files, maxDepth });
+ setResult(data);
+ setAnalyzedFiles(files);
+ } catch (err) {
+ setError(toFriendlyMessage(err, "Analysis failed."));
+ } finally {
+ setLoading(false);
+ }
+ },
+ [adapter, maxDepth],
+ );
+
+ const handleAnalyze = () => void runAnalysis(selected);
+
+ // Analyze a seeded selection on arrival, so following a file card's "Blast
+ // Radius" button lands on the answer rather than on a filled-in form still
+ // waiting for a click. Keyed by the seed so navigating from one file to
+ // another re-runs it, and guarded by a ref so re-renders (and the depth
+ // control, which `runAnalysis` depends on) do not re-fire it.
+ const seedKey = (initialFiles ?? []).join("\n");
+ const analyzedSeed = useRef<string | null>(null);
+ useEffect(() => {
+ if (!seedKey || analyzedSeed.current === seedKey) return;
+ analyzedSeed.current = seedKey;
+ const files = seedKey.split("\n");
+ setSelected(files);
+ void runAnalysis(files);
+ // runAnalysis is deliberately not a dependency; see the ref guard above.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [seedKey]);
return (
<div className="space-y-6">
@@ -82,7 +119,7 @@ export function ImpactView({ adapter }: { adapter: ImpactAdapter }) {
<CardHeader className="pb-3">
<CardTitle className="text-sm">Impact Analyzer</CardTitle>
<p className="text-xs text-[var(--color-text-tertiary)]">
- Estimate the blast radius of a proposed change — direct and transitive risks,
+ Estimate the blast radius of a proposed change: direct and transitive risks,
reviewer suggestions, and test gaps.
</p>
</CardHeader>
diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsx
index 3a93cd762..7779d48bd 100644
--- a/packages/ui/src/files/file-health-tab.tsx
+++ b/packages/ui/src/files/file-health-tab.tsx
@@ -15,10 +15,11 @@ import {
DIMENSION_LABEL,
type BiomarkerDimension,
} from "../health/biomarker-glossary";
-import { SEVERITY_CHIP, SEVERITY_LABEL, scoreBadgeClass, type Severity } from "../health/tokens";
+import { scoreBadgeClass, type Severity } from "../health/tokens";
import { FileTrendChart } from "../health/file-trend-chart";
import { FileSignalsPanel } from "../health/file-signals-panel";
import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";
+import { SeverityMark } from "../health/severity-mark";
export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";
@@ -192,11 +193,7 @@ export function FileHealthTab({
className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-1"
>
<div className="flex items-center gap-2 flex-wrap">
- <span
- className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity as Severity]}`}
- >
- {SEVERITY_LABEL[f.severity as Severity]}
- </span>
+ <SeverityMark severity={f.severity as Severity} />
<span className="text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
</span>
diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsx
index 52733757f..08fbe4bf2 100644
--- a/packages/ui/src/health/biomarker-list.tsx
+++ b/packages/ui/src/health/biomarker-list.tsx
@@ -14,6 +14,7 @@ import {
} from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";
+import { SeverityMark } from "./severity-mark";
/** Severity → dot color, same ramp as every score pill on the surface. */
const SEVERITY_DOT: Record<Severity, string> = {
@@ -215,11 +216,15 @@ function BiomarkerGroup({
<span className="ml-auto inline-flex items-center gap-1.5 text-xs tabular-nums">
{(Object.keys(sevCounts) as Severity[]).map((s) =>
sevCounts[s] > 0 ? (
+ // A count keyed by colour, so it gets the dot and the figure and
+ // no ground. Filled chips here tiled into stripes that outweighed
+ // the marker name they belonged to.
<span
key={s}
- className={`inline-flex items-center rounded px-1.5 py-0.5 font-semibold ${SEVERITY_CHIP[s]}`}
+ className="inline-flex items-center gap-1 font-semibold"
title={SEVERITY_LABEL[s]}
>
+ <SeverityMark severity={s} compact />
{sevCounts[s]}
</span>
) : null,
@@ -322,11 +327,7 @@ function FindingRow({
onClick={interactive ? () => onSelect!(f) : undefined}
>
<div className="flex items-center gap-2">
- <span
- className={`inline-block rounded px-2 py-0.5 text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}
- >
- {SEVERITY_LABEL[f.severity]}
- </span>
+ <SeverityMark severity={f.severity} />
{!hideBiomarker ? (
<span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsx
new file mode 100644
index 000000000..1d3aea913
--- /dev/null
+++ b/packages/ui/src/health/code-health-lede.tsx
@@ -0,0 +1,186 @@
+/**
+ * The Code Health page's opening read: one figure large enough to lead, and the
+ * sentences that make it mean something.
+ *
+ * It replaces four separate containers that used to stack above the map — a
+ * collapsible "can you trust this score?" banner, three bordered signal tiles,
+ * and a bordered strip of operational stats. Between them they carried six
+ * numbers at near-identical weight behind five uppercase labels, which is the
+ * box-soup failure: everything claims the same importance, so nothing leads,
+ * and the page needed borders to produce the structure a type scale should have
+ * given it for free.
+ *
+ * The prose is not decoration here. "329 risks" reads as alarming on its own;
+ * "329 static performance risks, scored separately and never blended into the
+ * defect number" reads as informative. Same figure. The accuracy claim in
+ * particular only means anything next to its base rate — a 72% hit rate is
+ * excellent against a 20% baseline and unremarkable against a 70% one — so it
+ * is a sentence rather than a badge.
+ */
+
+import type {
+ DefectAccuracy,
+ HealthDistribution,
+ HealthOverviewSummary,
+} from "@repowise-dev/types/health";
+import { PageLede } from "../shared/page-lede";
+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
+// Bands come from the one shared function on purpose. Two surfaces disagreeing
+// about where "Good" starts is worse than the duplication that would avoid it.
+import { healthBand } from "../overview/health-lede";
+import { formatNumber } from "../lib/format";
+import { scoreTextColor } from "./tokens";
+import { HealthDistributionBar } from "./health-distribution-bar";
+
+export interface CodeHealthLedeProps {
+ summary: HealthOverviewSummary;
+ /** Null when the repo lacks the defect history to make an honest claim. */
+ accuracy?: DefectAccuracy | null;
+ /** NLOC-weighted split across the bands, shown under the score. */
+ distribution?: HealthDistribution | null;
+ /** Rendered under the prose — the host's pillar deep-links. */
+ action?: React.ReactNode;
+}
+
+/** "3 months" / "1 month", from a day count. */
+function windowLabel(days: number): string {
+ const months = Math.max(1, Math.round(days / 30));
+ return months === 1 ? "month" : `${months} months`;
+}
+
+export function CodeHealthLede({
+ summary,
+ accuracy,
+ distribution,
+ action,
+}: CodeHealthLedeProps) {
+ const band = healthBand(summary.average_health);
+ const maint = summary.maintainability_average;
+ const perf = summary.performance_average;
+ const perfFindings = summary.performance_findings ?? 0;
+ const hotspot = summary.hotspot_health;
+
+ // Assembled rather than interpolated inline: a repo can have measured one
+ // pillar and not the other, and the naive version produces "The three are
+ // scored separately" when there are two of them.
+ const pillars: string[] = [];
+ if (maint != null) pillars.push(`maintainability ${maint.toFixed(1)}`);
+ if (perf != null) pillars.push(`static performance risk ${perf.toFixed(1)}`);
+
+ const stats: RibbonStat[] = [
+ { label: "Files", value: formatNumber(summary.file_count) },
+ {
+ label: "Maintainability",
+ value: maint == null ? "" : `${maint.toFixed(1)}`,
+ valueColor: maint == null ? undefined : scoreTextColor(maint),
+ hint: "Smells that raise change-cost without predicting bugs. Scored on its own, never blended into the defect number.",
+ },
+ {
+ label: "Performance risk",
+ value: perf == null ? "" : formatNumber(perfFindings),
+ hint: "Open static performance risks: a DB, network, filesystem or subprocess call per loop iteration, found across function boundaries. High precision, low recall.",
+ },
+ {
+ label: "Hotspot health",
+ value: hotspot == null ? "" : hotspot.toFixed(1),
+ valueColor: hotspot == null ? undefined : scoreTextColor(hotspot),
+ hint: "The score averaged over the repo's churn hotspots only. How healthy is the code you touch most?",
+ },
+ { label: "Open findings", value: formatNumber(summary.open_findings) },
+ ];
+
+ return (
+ <div className="flex flex-col gap-6">
+ <PageLede
+ label="Defect risk"
+ value={summary.average_health.toFixed(1)}
+ valueColor={band.color}
+ unit="out of 10"
+ band={band}
+ action={action}
+ layout="beside"
+ // The one second read that belongs to the score itself: how the repo's
+ // code volume splits across the bands. A 7.5 average hides whether that
+ // is everything-mediocre or mostly-healthy-with-a-bad-corner, and those
+ // are different problems.
+ figureFooter={
+ distribution ? (
+ <HealthDistributionBar distribution={distribution} height="sm" />
+ ) : undefined
+ }
+ >
+ <p>
+ Across{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {formatNumber(summary.file_count)} files
+ </strong>
+ , this codebase scores{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {summary.average_health.toFixed(1)} out of 10
+ </strong>{" "}
+ on defect risk, weighted by lines of code and built from complexity,
+ duplication, coverage, churn and ownership. We rate that{" "}
+ {band.label.toLowerCase()}.
+ {pillars.length > 0 && (
+ <>
+ {" "}
+ It also scores {pillars.join(" and ")} out of 10;{" "}
+ {pillars.length === 1 ? "the two are" : "the three are"} measured
+ separately and never blended into one number.
+ </>
+ )}
+ </p>
+
+ {accuracy && (
+ <p className="mt-2.5">
+ Ranked against real bug-fix history:{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {accuracy.hits} of the {accuracy.k} files
+ </strong>{" "}
+ it scores worst were touched by a fix in the last{" "}
+ {windowLabel(accuracy.window_days)}. That is{" "}
+ {Math.round(accuracy.precision * 100)}% against a{" "}
+ {Math.round(accuracy.base_rate * 100)}% base rate across the repo
+ {accuracy.lift != null && (
+ <>
+ , so{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {accuracy.lift}× better
+ </strong>{" "}
+ than picking files at random
+ </>
+ )}
+ .
+ </p>
+ )}
+
+ {hotspot != null && (
+ <p className="mt-2.5">
+ The files you change most average{" "}
+ <strong className="font-semibold" style={{ color: healthBand(hotspot).color }}>
+ {hotspot.toFixed(1)}
+ </strong>
+ , {describeGap(hotspot, summary.average_health)}
+ </p>
+ )}
+ </PageLede>
+
+ <StatRibbon stats={stats} />
+ </div>
+ );
+}
+
+/**
+ * How the hotspot average sits against the repo average, in words.
+ *
+ * Worth a sentence rather than a delta chip: hotspot health below the repo
+ * average is the finding that actually changes what someone does next, and
+ * "6.2 (−1.1)" does not say which direction is bad.
+ */
+function describeGap(hotspot: number, average: number): string {
+ const gap = hotspot - average;
+ if (Math.abs(gap) < 0.25) return "in line with the codebase overall.";
+ return gap < 0
+ ? `${Math.abs(gap).toFixed(1)} below the codebase overall. The weak spot is the code in motion.`
+ : `${gap.toFixed(1)} above the codebase overall, so the busiest files are holding up.`;
+}
diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsx
index a9f15593b..c823fc824 100644
--- a/packages/ui/src/health/code-health-map.tsx
+++ b/packages/ui/src/health/code-health-map.tsx
@@ -1,6 +1,9 @@
"use client";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+// Aliased: the bare name would shadow the DOM `KeyboardEvent` the Esc handler
+// below is typed against.
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import * as d3 from "d3-hierarchy";
import { scoreBand, type ScoreBand } from "./tokens";
import { useCommunityFamilies } from "../shared/use-theme-tokens";
@@ -59,14 +62,29 @@ export interface CodeHealthMapProps {
minHeight?: number;
/** Which lens recolors the field. Defaults to `health`. */
overlay?: CodeHealthOverlay;
- /** When provided, an on-canvas lens switcher is rendered. */
+ /** When provided, the lens is switchable. */
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ /** Lenses offered in the switcher. Defaults to {@link OVERLAY_ORDER}. */
+ lenses?: CodeHealthOverlay[];
/**
* The active overlay's per-file signal is still loading. When true the legend
* shows a "loading…" note instead of its bands, so an all-neutral field reads
* as "fetching data" rather than "no data".
*/
overlayLoading?: boolean;
+ /**
+ * Where the lens switcher and legend live.
+ *
+ * `"canvas"` (default) floats them over the map. `"none"` renders neither, for
+ * hosts that lay them out themselves with {@link MapLensSwitcher} /
+ * {@link MapLegend} — the section-style Code Health page does this, because
+ * three glass panels stacked on the left of the canvas put chrome on top of
+ * the one thing the reader came for.
+ *
+ * Defaults to `"canvas"` so the VS Code webview, which has no other lens
+ * picker, keeps working untouched.
+ */
+ chrome?: "canvas" | "none";
}
/* Band → SVG fill var(). Same ramp as every score pill on the surface:
@@ -88,13 +106,13 @@ const BAND_LABEL: { band: ScoreBand; label: string }[] = [
/** Neutral fill for nodes a non-health overlay has no signal for. */
const NEUTRAL_FILL = "var(--color-text-tertiary)";
-interface LegendRow {
+export interface LegendRow {
fill: string;
label: string;
}
-/** Lens metadata: how to fill a node and what the on-canvas key reads. */
-interface OverlaySpec {
+/** Lens metadata: how to fill a node and what the key reads. */
+export interface OverlaySpec {
label: string;
/** Caption shown under the legend key. */
caption: string;
@@ -147,7 +165,7 @@ function churnFill(pctile: number | null | undefined): string {
return "var(--color-success)";
}
-const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
+export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
health: {
label: "Health",
caption: "galaxy = module · size = lines of code",
@@ -220,12 +238,19 @@ const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
};
/**
- * Lenses offered in the on-canvas switcher: the three co-equal health signals,
- * all backed by a per-file score in the map payload. Coverage / churn / dead-code
- * / security keep their `OVERLAY_SPECS` entries (other tabs still use them) but
- * are not presented in this switcher.
+ * Default lenses offered in the switcher: the three co-equal health signals,
+ * all backed by a per-file score that rides on the map payload itself.
+ *
+ * Churn is deliberately not in the default. It colors by `churn_percentile`,
+ * which arrives on a separate request the host has to join in, so offering it
+ * where nobody joined it paints an all-neutral field that reads as "no churn"
+ * rather than "no data". Hosts that do the join pass their own `lenses`.
*/
-const OVERLAY_ORDER: CodeHealthOverlay[] = ["health", "maintainability", "performance"];
+export const OVERLAY_ORDER: CodeHealthOverlay[] = [
+ "health",
+ "maintainability",
+ "performance",
+];
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad
@@ -311,7 +336,9 @@ export function CodeHealthMap({
minHeight = 640,
overlay = "health",
onOverlayChange,
+ lenses = OVERLAY_ORDER,
overlayLoading = false,
+ chrome = "canvas",
}: CodeHealthMapProps) {
const overlaySpec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
const containerRef = useRef<HTMLDivElement>(null);
@@ -434,14 +461,14 @@ export function CodeHealthMap({
const q = (search ?? "").trim().toLowerCase();
if (S === 0) {
- return <div ref={containerRef} className="w-full rounded-xl bg-[var(--color-bg-canvas)]" style={{ minHeight }} />;
+ return <div ref={containerRef} className="w-full rounded-xl bg-[var(--color-bg-root)]" style={{ minHeight }} />;
}
if (files.length === 0) {
return (
<div
ref={containerRef}
- className="flex w-full items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] text-sm text-[var(--color-text-tertiary)]"
+ className="flex w-full items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-root)] text-sm text-[var(--color-text-tertiary)]"
style={{ minHeight }}
>
No files to map yet. Index this repo to populate health.
@@ -468,11 +495,22 @@ export function CodeHealthMap({
<defs>
<radialGradient id="ch-mist" cx="50%" cy="42%" r="75%">
<stop offset="0%" stopColor="var(--color-bg-surface)" />
- <stop offset="100%" stopColor="var(--color-bg-canvas)" />
+ <stop offset="100%" stopColor="var(--color-bg-root)" />
+ </radialGradient>
+ {/* Nebula falloff. This was an feGaussianBlur, which is an offscreen
+ raster pass per blob — and the blobs live inside the group whose
+ transform animates on every galaxy zoom, so all of them re-rastered
+ every frame of a 460ms transition. A gradient is painted directly,
+ costs nothing to animate, and the stops below are tuned to match
+ the old stdDeviation=7 edge: flat through the middle, soft over the
+ last ~15%. `currentColor` resolves per blob, so one def serves
+ every galaxy family instead of one gradient each. */}
+ <radialGradient id="ch-nebula">
+ <stop offset="0%" stopColor="currentColor" stopOpacity="1" />
+ <stop offset="70%" stopColor="currentColor" stopOpacity="1" />
+ <stop offset="88%" stopColor="currentColor" stopOpacity="0.55" />
+ <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
</radialGradient>
- <filter id="ch-nebula" x="-30%" y="-30%" width="160%" height="160%">
- <feGaussianBlur stdDeviation="7" />
- </filter>
</defs>
{/* Misty backdrop + starfield (static, clicking it exits a galaxy). */}
@@ -500,10 +538,14 @@ export function CodeHealthMap({
key={`blob-${g.module}`}
cx={g.cx + offX}
cy={g.cy + offY}
- r={g.R * 0.96}
- fill={fam.hub}
+ // Was 0.96 with a blur that spread past the edge; the gradient
+ // stops inside its own radius, so the blob grows to compensate.
+ r={g.R * 1.02}
+ // `color` feeds the gradient's currentColor stops.
+ style={{ color: fam.hub }}
+ fill="url(#ch-nebula)"
fillOpacity={faded ? 0.05 : 0.16}
- filter="url(#ch-nebula)"
+ data-galaxy={g.module}
className="cursor-zoom-in"
onClick={(e) => {
e.stopPropagation();
@@ -545,6 +587,7 @@ export function CodeHealthMap({
q={q}
offX={offX}
offY={offY}
+ strokeWidth={0.5 / k}
interactive={!!onSelectFile}
onSelect={handleSelect}
onHoverEnter={handleHoverEnter}
@@ -575,7 +618,7 @@ export function CodeHealthMap({
r={Math.max(2.5, g.R * 0.035)}
fill={fam.hub}
fillOpacity={faded ? 0.3 : 0.95}
- stroke="var(--color-bg-canvas)"
+ stroke="var(--color-bg-root)"
strokeWidth={1}
vectorEffect="non-scaling-stroke"
className="pointer-events-none"
@@ -597,8 +640,11 @@ export function CodeHealthMap({
return (
<span
key={`lbl-${g.module}`}
- className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-serif uppercase tracking-wide text-[var(--color-text-primary)] shadow-sm ring-1 ring-[var(--color-border-default)] backdrop-blur-sm ${
- big ? "text-sm font-semibold" : "text-[12px] font-medium"
+ // Mono, not serif. These are data-viz labels on a canvas overlay
+ // — machine-produced names, which the type rules put in mono;
+ // serif is reserved for long-form reading surfaces.
+ className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-mono uppercase tracking-[0.12em] text-[var(--color-text-primary)] shadow-sm ring-1 ring-[var(--color-border-default)] backdrop-blur-sm ${
+ big ? "text-[11px] font-medium" : "text-[10px]"
}`}
style={{ left: p.x, top: p.y }}
>
@@ -611,60 +657,49 @@ export function CodeHealthMap({
})}
</div>
- {/* Lens switcher (on-canvas) — recolors the same field. */}
- {onOverlayChange ? (
- <div className="absolute left-3 top-3 flex flex-wrap gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 text-xs shadow-sm backdrop-blur-sm">
- {OVERLAY_ORDER.map((mode) => (
- <button
- key={mode}
- type="button"
- onClick={() => onOverlayChange(mode)}
- aria-pressed={overlay === mode}
- className={
- overlay === mode
- ? "rounded px-2 py-1 font-medium bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
- : "rounded px-2 py-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }
- >
- {OVERLAY_SPECS[mode].label}
- </button>
- ))}
- </div>
- ) : null}
-
- {/* Legend (on-canvas) — follows the active lens. */}
- <div
- className={`absolute left-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${
- onOverlayChange ? "top-14" : "top-3"
- }`}
- >
- <div className="mb-1.5 font-medium text-[var(--color-text-secondary)]">
- {overlaySpec.label}
- </div>
- {overlayLoading ? (
- <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
- <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
- loading {overlaySpec.label.toLowerCase()}…
- </div>
- ) : (
- <div className="flex flex-col gap-1">
- {overlaySpec.legend.map((row) => (
- <span
- key={row.label}
- className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]"
- >
- <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: row.fill }} />
- {row.label}
- </span>
- ))}
+ {/* Lens switcher + legend, floated over the canvas. Only for hosts that
+ have nowhere else to put them (the VS Code webview). The web page
+ passes chrome="none" and lays both out around the map instead, so the
+ reader is not looking at the field through three glass panels. */}
+ {chrome === "canvas" ? (
+ <>
+ {onOverlayChange ? (
+ <div className="absolute left-3 top-3 flex flex-wrap gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 text-xs shadow-sm backdrop-blur-sm">
+ {lenses.map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => onOverlayChange(mode)}
+ aria-pressed={overlay === mode}
+ className={
+ overlay === mode
+ ? "rounded px-2 py-1 font-medium bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
+ : "rounded px-2 py-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }
+ >
+ {OVERLAY_SPECS[mode].label}
+ </button>
+ ))}
+ </div>
+ ) : null}
+
+ <div
+ className={`absolute left-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${
+ onOverlayChange ? "top-14" : "top-3"
+ }`}
+ >
+ <div className="mb-1.5 font-medium text-[var(--color-text-secondary)]">
+ {overlaySpec.label}
+ </div>
+ <MapLegendRows spec={overlaySpec} loading={overlayLoading} />
+ <div className="mt-2 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)]">
+ {overlaySpec.caption}
+ <br />
+ click a galaxy to zoom
+ </div>
</div>
- )}
- <div className="mt-2 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)]">
- {overlaySpec.caption}
- <br />
- click a galaxy to zoom
- </div>
- </div>
+ </>
+ ) : null}
{/* Zoom-out breadcrumb — only shown while a galaxy is focused */}
{focusGalaxy ? (
@@ -699,6 +734,7 @@ const FileNodes = memo(function FileNodes({
q,
offX,
offY,
+ strokeWidth,
interactive,
onSelect,
onHoverEnter,
@@ -710,6 +746,20 @@ const FileNodes = memo(function FileNodes({
q: string;
offX: number;
offY: number;
+ /**
+ * Stroke in user units, pre-divided by the zoom scale so it lands on 0.5
+ * device px at rest.
+ *
+ * The obvious spelling is `vectorEffect="non-scaling-stroke"`, which is what
+ * this used. But Chrome recomputes stroke geometry per element per frame for
+ * that attribute, and these are ~2,000 elements inside the group whose
+ * transform animates on every galaxy zoom. Dividing by `k` instead is free.
+ * The trade is that during the 460ms transition the browser interpolates the
+ * transform while this value is already at its destination, so strokes are
+ * fractionally off mid-flight — invisible on a 0.5px line under a moving
+ * field, and the field is correct the instant it settles.
+ */
+ strokeWidth: number;
interactive: boolean;
onSelect: (path: string) => void;
onHoverEnter: (f: CodeHealthMapFile) => void;
@@ -725,16 +775,21 @@ const FileNodes = memo(function FileNodes({
const f = nd.file;
const dim = q.length > 0 && !f.file_path.toLowerCase().includes(q);
return (
+ /* No <title> child. It was ~2,000 extra DOM nodes driving a
+ native tooltip that appears on its own delay, in the corner
+ the pointer is in, restating what HoverCard already shows
+ the moment you touch a node — two tooltips racing. `data-path`
+ costs no node and gives tests a stable handle. */
<circle
key={f.file_path}
+ data-path={f.file_path}
cx={nd.x + offX}
cy={nd.y + offY}
r={nd.r}
fill={fill(f)}
fillOpacity={faded ? 0.18 : dim ? 0.12 : 0.9}
- stroke="var(--color-bg-canvas)"
- strokeWidth={0.5}
- vectorEffect="non-scaling-stroke"
+ stroke="var(--color-bg-root)"
+ strokeWidth={strokeWidth}
className={interactive ? "cursor-pointer" : undefined}
onMouseEnter={() => onHoverEnter(f)}
onMouseLeave={() => onHoverLeave(f)}
@@ -742,9 +797,7 @@ const FileNodes = memo(function FileNodes({
e.stopPropagation();
onSelect(f.file_path);
}}
- >
- <title>{`${f.file_path}\nscore ${f.score.toFixed(1)} · ${f.nloc.toLocaleString()} NLOC`}</title>
- </circle>
+ />
);
})}
</g>
@@ -794,7 +847,7 @@ function NodeHighlight({
r={hov.r + 1.5}
fill={fill(hov.file)}
fillOpacity={1}
- stroke="var(--color-bg-canvas)"
+ stroke="var(--color-bg-root)"
strokeWidth={0.5}
vectorEffect="non-scaling-stroke"
/>
@@ -816,3 +869,135 @@ function HoverCard({ file }: { file: CodeHealthMapFile }) {
</div>
);
}
+
+/* ------------------------------------------------------------------ *
+ * Map chrome
+ *
+ * The switcher and the key, as components a host can place around the map
+ * rather than on top of it. Both read the same {@link OVERLAY_SPECS} the
+ * canvas does, so an off-canvas legend can never drift from the fills it is
+ * describing.
+ * ------------------------------------------------------------------ */
+
+/** The legend's colour rows, shared by both placements. */
+function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: boolean }) {
+ if (loading) {
+ return (
+ <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
+ <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
+ loading {spec.label.toLowerCase()}…
+ </div>
+ );
+ }
+ return (
+ <div className="flex flex-col gap-1">
+ {spec.legend.map((row) => (
+ <span key={row.label} className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: row.fill }} />
+ {row.label}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * The lens switcher as a real segmented control, for `chrome="none"` hosts.
+ *
+ * A radiogroup rather than a row of `aria-pressed` buttons: picking a lens is
+ * one choice out of a set, and the roving-tabindex arrow-key behaviour comes
+ * free with the role.
+ */
+export function MapLensSwitcher({
+ overlay,
+ onOverlayChange,
+ lenses = OVERLAY_ORDER,
+ className,
+}: {
+ overlay: CodeHealthOverlay;
+ onOverlayChange: (overlay: CodeHealthOverlay) => void;
+ lenses?: CodeHealthOverlay[];
+ className?: string;
+}) {
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ const i = lenses.indexOf(overlay);
+ if (i < 0) return;
+ let next = i;
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % lenses.length;
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
+ next = (i - 1 + lenses.length) % lenses.length;
+ else return;
+ e.preventDefault();
+ const target = lenses[next];
+ if (target) onOverlayChange(target);
+ };
+
+ return (
+ <div
+ role="radiogroup"
+ aria-label="Map lens"
+ onKeyDown={onKeyDown}
+ className={`inline-flex rounded-md border border-[var(--color-border-default)] p-0.5 ${className ?? ""}`}
+ >
+ {lenses.map((mode) => {
+ const active = overlay === mode;
+ return (
+ <button
+ key={mode}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ tabIndex={active ? 0 : -1}
+ onClick={() => onOverlayChange(mode)}
+ className={`rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
+ : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {OVERLAY_SPECS[mode].label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/**
+ * The active lens's key, laid out as a horizontal strip to sit under the map.
+ *
+ * Same content as the on-canvas panel, arranged to read as a caption rather
+ * than as a floating card: the swatches run inline and the lens caption closes
+ * the line.
+ */
+export function MapLegend({
+ overlay,
+ loading = false,
+ className,
+}: {
+ overlay: CodeHealthOverlay;
+ loading?: boolean;
+ className?: string;
+}) {
+ const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ return (
+ <div
+ className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-[var(--color-text-tertiary)] ${className ?? ""}`}
+ >
+ {loading ? (
+ <span className="flex items-center gap-1.5">
+ <span className="h-2 w-2 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
+ loading {spec.label.toLowerCase()}…
+ </span>
+ ) : (
+ spec.legend.map((row) => (
+ <span key={row.label} className="flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full" style={{ backgroundColor: row.fill }} />
+ {row.label}
+ </span>
+ ))
+ )}
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em]">{spec.caption}</span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/file-signals-panel.tsx b/packages/ui/src/health/file-signals-panel.tsx
index 113138422..d703b3ccf 100644
--- a/packages/ui/src/health/file-signals-panel.tsx
+++ b/packages/ui/src/health/file-signals-panel.tsx
@@ -29,7 +29,7 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
return (
<section className="space-y-2">
{!hideHeading && (
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Signals
</h3>
)}
@@ -47,7 +47,7 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
? null
: `${Math.round(signals.change_entropy_pct)}th pct`
}
- caption="change scatter — how spread out its edits are"
+ caption="change scatter: how spread out its edits are"
present={signals.change_entropy_pct != null}
/>
<Row
@@ -75,7 +75,7 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
: ownerValue(signals.recent_owner_name, signals.recent_owner_commit_pct)
}
caption={
- ownerHandoff ? "recent owner (90d) — differs from primary" : "recent owner (90d)"
+ ownerHandoff ? "recent owner (90d), differs from primary" : "recent owner (90d)"
}
present={signals.recent_owner_name != null}
emphasize={ownerHandoff}
@@ -171,10 +171,15 @@ function plural(n: number, word: string): string {
return n === 1 ? word : `${word}s`;
}
+/**
+ * One signal column. A hairline above it rather than a box around it: three
+ * bordered cards side by side make the group labels compete with the values
+ * they label, and on the 640px drawer they were most of the panel's ink.
+ */
function Group({ label, children }: { label: string; children: React.ReactNode }) {
return (
- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 space-y-2">
- <p className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <div className="flex flex-col gap-2 border-t border-[var(--color-border-default)] pt-2.5">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{label}
</p>
<div className="space-y-2">{children}</div>
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index f75eb81c2..c60980c9b 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -24,10 +24,13 @@ import {
SEVERITY_LABEL,
deltaColor,
formatDelta,
- scoreBadgeClass,
type Severity,
} from "./tokens";
+// Shared band function, never a local threshold: two surfaces disagreeing
+// about where "Good" starts is worse than the import.
+import { healthBand } from "../overview/health-lede";
import type { FileHealthTrend, FileSignals } from "@repowise-dev/types/health";
+import { SeverityMark } from "./severity-mark";
export interface HealthDrawerFinding {
id: string;
@@ -137,14 +140,15 @@ export function HealthFileDrawer({
const renderFinding = (f: HealthDrawerFinding) => {
const info = biomarkerInfo(f.biomarker_type);
return (
+ // A hairline row, not a card inside a card. These sat as bordered boxes
+ // inside a bordered group inside the drawer: three frames deep for one
+ // marker.
<li
key={f.id}
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-1"
+ className="space-y-1 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
>
<div className="flex items-center gap-2 flex-wrap">
- <span className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}>
- {SEVERITY_LABEL[f.severity]}
- </span>
+ <SeverityMark severity={f.severity} />
<span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
{info.description ? (
@@ -242,14 +246,14 @@ export function HealthFileDrawer({
const findingSections = (() => {
const groups = new Map<string, HealthDrawerFinding[]>();
for (const f of findings) {
- const key = f.function_name ?? "file";
+ const key = f.function_name ?? " file";
const bucket = groups.get(key);
if (bucket) bucket.push(f);
else groups.set(key, [f]);
}
return [...groups.entries()]
.map(([key, group]) => {
- const isFile = key === "file";
+ const isFile = key === " file";
const total = group.reduce((s, f) => s + f.health_impact, 0);
const worst = group.reduce((a, b) => (b.health_impact > a.health_impact ? b : a));
return { key, group, isFile, total, worst };
@@ -278,126 +282,112 @@ export function HealthFileDrawer({
title={metric?.file_path ?? "Loading…"}
widthClassName="md:max-w-[640px]"
>
- <div className="px-4 py-4 space-y-5">
- {permalinkHref ? (
- <a
- href={permalinkHref}
- className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- title="Open as a shareable page"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- Open full page
- </a>
- ) : null}
+ <div className="flex flex-col gap-6 px-4 py-4">
{loading ? (
<div className="text-sm text-[var(--color-text-tertiary)]">Loading…</div>
) : !metric ? (
- <div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">
+ <p className="text-sm text-[var(--color-text-secondary)]">
No metric for this file yet. It appears after the next index or sync.
- </div>
+ </p>
) : (
<>
- {primaryLead ? (
- <div className="rounded-md border-l-2 border-[var(--color-error)] bg-[var(--color-bg-elevated)] px-3 py-2">
- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Leading cause
- </p>
- <p className="text-sm text-[var(--color-text-primary)]">
- <span className="font-semibold">{biomarkerLabel(primaryLead.biomarker)}</span>
- {primaryLead.reason ? (
- <span className="text-[var(--color-text-secondary)]"> — {primaryLead.reason}</span>
- ) : null}
+ {/* Lede: the score leads, and the leading cause is the sentence
+ that makes it mean something. This used to be a small chip
+ among ten identical bordered tiles, with the "why" in a
+ separate box above them. */}
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:gap-6">
+ <div className="flex shrink-0 flex-col gap-2 sm:w-[150px]">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Defect risk
</p>
- </div>
- ) : null}
-
- <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
- <Stat label="Defect risk" value={
- <span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.score)}`}>
- {metric.score.toFixed(1)}
- <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
- </span>
- } />
- <Stat label="Maintainability" value={
- metric.maintainability_score == null ? (
- <span className="text-xs text-[var(--color-text-tertiary)]">—</span>
- ) : (
- <span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.maintainability_score)}`}>
- {metric.maintainability_score.toFixed(1)}
- <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
+ <span
+ className="text-[40px] font-semibold leading-none tracking-tight tabular-nums"
+ style={{ color: healthBand(metric.score).color }}
+ >
+ {metric.score.toFixed(1)}
</span>
- )
- } />
- <Stat label="Performance" value={
- metric.performance_score == null ? (
- <span className="text-xs text-[var(--color-text-tertiary)]">—</span>
- ) : (
- <span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.performance_score)}`}>
- {metric.performance_score.toFixed(1)}
- <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
- </span>
- )
- } />
- <Stat label="Max CCN" value={<MeasuredNum v={metric.max_ccn} />} />
- <Stat label="Nest" value={<MeasuredNum v={metric.max_nesting} />} />
- <Stat label="NLOC" value={<MeasuredNum v={metric.nloc} />} />
- <Stat label="Module" value={<span className="text-xs">{metric.module ?? "—"}</span>} />
- <Stat label="Tests" value={<span className="text-xs">{metric.has_test_file ? "Paired" : "None"}</span>} />
- <Stat label="Coverage" value={
- <span className="text-xs tabular-nums">
- {metric.line_coverage_pct == null ? "—" : `${metric.line_coverage_pct.toFixed(0)}%`}
- </span>
- } />
- <Stat label="Duplication" value={
- <span className="text-xs tabular-nums">
- {metric.duplication_pct == null ? "—" : `${metric.duplication_pct.toFixed(0)}%`}
+ <span className="text-xs text-[var(--color-text-tertiary)]">out of 10</span>
+ </div>
+ <span
+ className="w-fit rounded-full border px-2.5 py-0.5 text-[11px] font-medium"
+ style={{
+ color: healthBand(metric.score).color,
+ borderColor: `color-mix(in srgb, ${healthBand(metric.score).color} 40%, transparent)`,
+ background: `color-mix(in srgb, ${healthBand(metric.score).color} 9%, transparent)`,
+ }}
+ >
+ {healthBand(metric.score).label}
</span>
- } />
- </div>
- {trend && trend.points.length >= 2 ? (
- <div className="flex items-center gap-3 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">
- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Trend
- </span>
- <Sparkline
- values={trend.points.map((p) => p.score)}
- domain={[0, 10]}
- width={120}
- height={28}
- stroke="var(--color-accent-primary)"
- />
- {trend.delta != null && trend.delta !== 0 ? (
- <span className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}>
- {formatDelta(trend.delta)}
- </span>
+ {trend && trend.points.length >= 2 ? (
+ <div className="mt-1 flex items-center gap-2">
+ <Sparkline
+ values={trend.points.map((p) => p.score)}
+ domain={[0, 10]}
+ width={92}
+ height={24}
+ stroke="var(--color-accent-primary)"
+ />
+ {trend.delta != null && trend.delta !== 0 ? (
+ <span
+ className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}
+ >
+ {formatDelta(trend.delta)}
+ </span>
+ ) : null}
+ {trend.declining ? (
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-error)]">
+ Declining
+ </span>
+ ) : null}
+ </div>
) : null}
- {trend.declining ? (
- <span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-error)]">
- Declining
- </span>
+ </div>
+
+ <div className="flex min-w-0 flex-col gap-3">
+ {primaryLead ? (
+ <div className="flex flex-col gap-1">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Leading cause
+ </p>
+ <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {biomarkerLabel(primaryLead.biomarker)}.
+ </strong>
+ {primaryLead.reason ? ` ${primaryLead.reason}` : ""}
+ </p>
+ </div>
+ ) : null}
+
+ {/* The one action. It was two links to the same page, one a
+ tertiary line at the top and one accent-coloured in the
+ middle of the body. */}
+ {(permalinkHref ?? fileViewHref) ? (
+ <a
+ href={permalinkHref ?? fileViewHref}
+ className="inline-flex w-fit items-center gap-1.5 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ Open full page
+ </a>
) : null}
</div>
- ) : null}
+ </div>
+
+ {/* The other two pillars and the structural counters, as a
+ hairline list. Ten bordered tiles made a 3.1 and a 14 read as
+ the same kind of news. */}
+ <MetricGrid metric={metric} />
<FileSignalsPanel signals={signals} />
<BugHistorySection signals={signals} />
- {fileViewHref ? (
- <a
- href={fileViewHref}
- className="inline-flex items-center gap-1.5 text-xs text-[var(--color-accent-primary)] hover:underline"
- >
- <ExternalLink className="h-3 w-3" />
- Open in file explorer
- </a>
- ) : null}
-
{breakdown ? (
- <section className="space-y-2">
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Why this score?
+ <section className="flex flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Why this score
</h3>
<ScoreBreakdown
score={breakdown.score}
@@ -408,11 +398,11 @@ export function HealthFileDrawer({
) : null}
{findings.length > 0 ? (
- <section className="space-y-2">
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <section className="flex flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
All findings ({findings.length})
</h3>
- <div className="space-y-2">
+ <div className="flex flex-col">
{findingSections.map((s) => (
<FunctionFindingsGroup
key={s.key}
@@ -423,8 +413,8 @@ export function HealthFileDrawer({
worst={s.worst}
// Single-marker groups have nothing to collapse; multi-
// marker groups start collapsed so the drawer opens as
- // compact headers (the "padded" fix) — the leading-cause
- // headline already surfaces the top reason.
+ // compact headers, since the leading-cause line above
+ // already surfaces the top reason.
defaultExpanded={s.group.length === 1}
renderFinding={renderFinding}
/>
@@ -517,7 +507,7 @@ function FunctionFindingsGroup({
const toggle = () => setExpanded((e) => !e);
const worstLabel = biomarkerLabel(worst.biomarker_type);
return (
- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
+ <div className="border-t border-[var(--color-border-default)]">
<div
role="button"
tabIndex={0}
@@ -529,7 +519,7 @@ function FunctionFindingsGroup({
}
}}
aria-expanded={expanded}
- className="flex w-full items-center gap-2 px-3 py-2 text-left cursor-pointer rounded-t-md hover:bg-[var(--color-bg-surface)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className="flex w-full cursor-pointer items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-[var(--color-bg-surface)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
{expanded ? (
<ChevronDown className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />
@@ -543,7 +533,7 @@ function FunctionFindingsGroup({
) : (
<span className="min-w-0 truncate text-sm font-medium text-[var(--color-text-primary)]">
<span className="font-mono">{functionName}</span>
- <span className="text-[var(--color-text-tertiary)]"> — {worstLabel}</span>
+ <span className="text-[var(--color-text-tertiary)]"> · {worstLabel}</span>
</span>
)}
<span className="ml-auto inline-flex shrink-0 items-center gap-2 text-xs tabular-nums">
@@ -554,7 +544,7 @@ function FunctionFindingsGroup({
</span>
</div>
{expanded ? (
- <ul className="space-y-2 border-t border-[var(--color-border-default)] p-2">
+ <ul className="border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
{findings.map((f) => renderFinding(f))}
</ul>
) : null}
@@ -578,13 +568,108 @@ function MeasuredNum({ v }: { v: number | null }) {
return <span className="text-base font-semibold tabular-nums">{v}</span>;
}
-function Stat({ label, value }: { label: string; value: React.ReactNode }) {
+/**
+ * The two co-pillars and the structural counters, as one hairline `<dl>`.
+ *
+ * Was ten bordered tiles in a 4-column grid that wrapped to 4/4/2 and gave a
+ * pillar score, a cyclomatic count and a module name identical weight. Scores
+ * carry their band colour; counters are plain, because a nesting depth of 3 is
+ * not good or bad news on its own.
+ */
+function MetricGrid({ metric }: { metric: HealthDrawerMetric }) {
+ const cells: { label: string; value: React.ReactNode }[] = [
+ {
+ label: "Maintainability",
+ value: <PillarScore v={metric.maintainability_score ?? null} />,
+ },
+ { label: "Performance", value: <PillarScore v={metric.performance_score ?? null} /> },
+ {
+ label: "Coverage",
+ value: (
+ <PlainValue>
+ {metric.line_coverage_pct == null
+ ? "not measured"
+ : `${metric.line_coverage_pct.toFixed(0)}%`}
+ </PlainValue>
+ ),
+ },
+ { label: "Max CCN", value: <MeasuredNum v={metric.max_ccn} /> },
+ { label: "Nesting", value: <MeasuredNum v={metric.max_nesting} /> },
+ { label: "NLOC", value: <MeasuredNum v={metric.nloc} /> },
+ {
+ label: "Duplication",
+ value: (
+ <PlainValue>
+ {metric.duplication_pct == null
+ ? "not measured"
+ : `${metric.duplication_pct.toFixed(0)}%`}
+ </PlainValue>
+ ),
+ },
+ {
+ label: "Tests",
+ value: <PlainValue>{metric.has_test_file ? "Paired" : "None"}</PlainValue>,
+ },
+ {
+ label: "Module",
+ value: (
+ <span
+ className="block truncate font-mono text-sm text-[var(--color-text-primary)]"
+ title={metric.module ?? undefined}
+ >
+ {metric.module ?? "none"}
+ </span>
+ ),
+ },
+ ];
+
return (
- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">
- {label}
- </p>
- <div className="text-[var(--color-text-primary)]">{value}</div>
- </div>
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3">
+ {cells.map((c, i) => (
+ <div
+ key={c.label}
+ className={[
+ "min-w-0 px-3 py-2.5",
+ "border-[var(--color-border-default)]",
+ // Hairlines between cells only; the outer edges come from border-y
+ // on the wrapper, so cells never double up on a boundary.
+ i % 2 === 1 ? "border-l" : "",
+ i >= 2 ? "border-t" : "",
+ "sm:border-l sm:border-t-0",
+ i % 3 === 0 ? "sm:border-l-0" : "",
+ i >= 3 ? "sm:border-t" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {c.label}
+ </dt>
+ <dd className="mt-1">{c.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+/** A 0–10 pillar score, band-coloured, or an honest "not measured". */
+function PillarScore({ v }: { v: number | null }) {
+ if (v == null) {
+ return <span className="text-sm text-[var(--color-text-tertiary)]">not measured</span>;
+ }
+ return (
+ <span
+ className="text-lg font-semibold tabular-nums"
+ style={{ color: healthBand(v).color }}
+ >
+ {v.toFixed(1)}
+ <span className="text-xs font-normal text-[var(--color-text-tertiary)]">/10</span>
+ </span>
+ );
+}
+
+function PlainValue({ children }: { children: React.ReactNode }) {
+ return (
+ <span className="text-sm tabular-nums text-[var(--color-text-primary)]">{children}</span>
);
}
diff --git a/packages/ui/src/health/hidden-coupling-list.tsx b/packages/ui/src/health/hidden-coupling-list.tsx
index c7b2df546..4057b4028 100644
--- a/packages/ui/src/health/hidden-coupling-list.tsx
+++ b/packages/ui/src/health/hidden-coupling-list.tsx
@@ -3,7 +3,8 @@
import { useState } from "react";
import { ArrowLeftRight, ChevronDown, ChevronRight } from "lucide-react";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
-import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";
+import { type Severity } from "./tokens";
+import { SeverityMark } from "./severity-mark";
export interface HiddenCouplingFinding {
id: string;
@@ -141,11 +142,7 @@ export function HiddenCouplingList({
{rows.map((row) => (
<li key={row.key} className="p-3 space-y-1.5">
<div className="flex items-center gap-2 flex-wrap">
- <span
- className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[row.worst_severity]}`}
- >
- {SEVERITY_LABEL[row.worst_severity]}
- </span>
+ <SeverityMark severity={row.worst_severity} />
<span className="ml-auto inline-flex items-center gap-3 text-xs tabular-nums text-[var(--color-text-tertiary)]">
<span title="Correlation = co-change count / min(commits A, commits B)">
{Math.round(row.correlation * 100)}%
diff --git a/packages/ui/src/health/hot-functions-panel.tsx b/packages/ui/src/health/hot-functions-panel.tsx
index c951bb7df..f0673bad3 100644
--- a/packages/ui/src/health/hot-functions-panel.tsx
+++ b/packages/ui/src/health/hot-functions-panel.tsx
@@ -4,7 +4,8 @@ import { useState } from "react";
import { ArrowUpRight, ChevronDown, ChevronRight, Flame } from "lucide-react";
import { biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
-import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";
+import { type Severity } from "./tokens";
+import { SeverityMark } from "./severity-mark";
export interface HotFunctionFinding {
id: string;
@@ -146,11 +147,7 @@ export function HotFunctionsPanel({
onClick={interactive ? () => onSelect!(row.representative) : undefined}
>
<div className="flex items-center gap-2 flex-wrap">
- <span
- className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[row.worst_severity]}`}
- >
- {SEVERITY_LABEL[row.worst_severity]}
- </span>
+ <SeverityMark severity={row.worst_severity} />
{(() => {
const href = symbolHrefFor
? symbolHrefFor(row.representative)
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 2411e3f09..3bef8414c 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -35,6 +35,8 @@ export * from "./ai-prompt-button";
export * from "./hot-functions-panel";
export * from "./hidden-coupling-list";
export * from "./defect-accuracy-card";
+export * from "./code-health-lede";
+export * from "./severity-mark";
export * from "./code-health-adapter";
export * from "./triage-view";
export * from "./findings-view";
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index e5fa064fb..a60fabd5c 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -5,7 +5,8 @@ import { ArrowUpRight, ChevronDown, ChevronRight, Sparkles } from "lucide-react"
import { InfoTip } from "../shared/info-tip";
import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
-import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";
+import { type Severity } from "./tokens";
+import { SeverityMark } from "./severity-mark";
export type EffortBucket = "S" | "M" | "L" | "XL";
@@ -89,11 +90,7 @@ export function RefactoringCard({
>
<div className="p-4 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
- <span
- className={`inline-block rounded px-2 py-0.5 text-[10px] uppercase font-semibold ${SEVERITY_CHIP[target.primary_severity]}`}
- >
- {SEVERITY_LABEL[target.primary_severity]}
- </span>
+ <SeverityMark severity={target.primary_severity} />
<span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(target.primary_biomarker)}
{biomarkerInfo(target.primary_biomarker).description ? (
@@ -183,11 +180,7 @@ export function RefactoringCard({
{target.all_findings.map((f) => (
<li key={f.id} className="px-4 py-2 space-y-1">
<div className="flex items-center gap-2 flex-wrap">
- <span
- className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}
- >
- {SEVERITY_LABEL[f.severity]}
- </span>
+ <SeverityMark severity={f.severity} />
<span className="text-xs font-medium text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
</span>
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index b2d3e1771..ebc906bfb 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -4,7 +4,8 @@ import {
biomarkerLabel,
type BiomarkerCategory,
} from "./biomarker-glossary";
-import { SEVERITY_CHIP, SEVERITY_LABEL, scoreBadgeClass, type Severity } from "./tokens";
+import { scoreBadgeClass, type Severity } from "./tokens";
+import { SeverityMark } from "./severity-mark";
export interface ScoreBreakdownCategoryFinding {
id: string;
@@ -81,9 +82,12 @@ export function ScoreBreakdown({
100,
);
return (
+ // Hairline-separated, not a card each. Every category already has a
+ // label, a figure and a proportion bar; a border around that is a
+ // fourth way of saying "this is a group".
<div
key={c.category}
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"
+ className="border-t border-[var(--color-border-default)] px-1 pt-3 first:border-t-0 first:pt-0"
>
<div className="flex items-center justify-between gap-2 text-xs">
<span className="font-medium text-[var(--color-text-primary)]">
@@ -120,11 +124,7 @@ export function ScoreBreakdown({
key={f.id}
className="flex flex-wrap items-baseline gap-x-2 text-xs"
>
- <span
- className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}
- >
- {SEVERITY_LABEL[f.severity]}
- </span>
+ <SeverityMark severity={f.severity} />
<span className="font-medium text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
</span>
diff --git a/packages/ui/src/health/severity-mark.tsx b/packages/ui/src/health/severity-mark.tsx
new file mode 100644
index 000000000..5e67c1288
--- /dev/null
+++ b/packages/ui/src/health/severity-mark.tsx
@@ -0,0 +1,54 @@
+import { SEVERITY_LABEL, type Severity } from "./tokens";
+
+/** Dot colour per severity. Literal class strings so Tailwind's scanner keeps them. */
+const SEVERITY_DOT: Record<Severity, string> = {
+ critical: "bg-[var(--color-error)]",
+ high: "bg-[var(--color-warning)]",
+ medium: "bg-[var(--color-caution)]",
+ low: "bg-[var(--color-text-tertiary)]",
+};
+
+const SEVERITY_TEXT: Record<Severity, string> = {
+ critical: "text-[var(--color-error)]",
+ high: "text-[var(--color-warning)]",
+ medium: "text-[var(--color-caution)]",
+ low: "text-[var(--color-text-tertiary)]",
+};
+
+/**
+ * A finding's severity, as a dot and a word rather than a filled pill.
+ *
+ * `SEVERITY_CHIP` renders a tinted ground plus a border plus coloured text:
+ * three ways of saying one thing, on a token that appears several times per row
+ * in lists that are already dense. In a findings list that is most of the ink on
+ * screen, and the grounds tile into stripes that read as more important than the
+ * marker names beside them.
+ *
+ * The word stays. Colour alone is not the name of a state, and "critical" and
+ * "high" are red and amber, which is exactly the pair that colour-blind readers
+ * cannot separate. `compact` drops the word to the dot plus a screen-reader
+ * label, for rows too tight to carry it.
+ */
+export function SeverityMark({
+ severity,
+ compact = false,
+ className,
+}: {
+ severity: Severity;
+ compact?: boolean;
+ className?: string;
+}) {
+ return (
+ <span
+ className={`inline-flex shrink-0 items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] ${
+ SEVERITY_TEXT[severity]
+ } ${className ?? ""}`}
+ >
+ <span
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${SEVERITY_DOT[severity]}`}
+ aria-hidden
+ />
+ <span className={compact ? "sr-only" : undefined}>{SEVERITY_LABEL[severity]}</span>
+ </span>
+ );
+}
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 31654faea..4a0e98569 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -25,6 +25,13 @@ export const SEVERITY_LABEL: Record<Severity, string> = {
low: "Low",
};
+/**
+ * @deprecated Use `SeverityMark`. This paints a tinted ground, a border and
+ * coloured text for one token that repeats several times per row, and in a
+ * findings list the grounds tile into stripes that outweigh the marker names
+ * beside them. Kept exported because `@repowise-dev/ui` is consumed outside
+ * this repo; nothing in here should reach for it.
+ */
export const SEVERITY_CHIP: Record<Severity, string> = {
critical:
"bg-[var(--color-error)]/15 text-[var(--color-error)] border border-[var(--color-error)]/30",
diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsx
index 031e62e8a..e952b1356 100644
--- a/packages/ui/src/health/trend-chart.tsx
+++ b/packages/ui/src/health/trend-chart.tsx
@@ -16,10 +16,10 @@ export interface TrendChartProps {
export function TrendChart({ history, height = 220 }: TrendChartProps) {
if (!history || history.length === 0) {
return (
- <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-center text-sm text-[var(--color-text-tertiary)]">
- No snapshots yet. Each index or sync records one; the trend appears
- from the second snapshot on.
- </div>
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ No snapshots yet. Each index or sync records one; the trend appears from the
+ second snapshot on.
+ </p>
);
}
@@ -47,9 +47,11 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {
};
return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">
- <div className="flex items-center justify-between gap-4 mb-2">
- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ // No card. The chart sits inside a section that already names it, so a
+ // border here is a second frame around content that has one.
+ <div className="flex flex-col">
+ <div className="mb-2 flex items-center justify-between gap-4">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
KPI trend
</h3>
<div className="flex items-center gap-3 text-xs text-[var(--color-text-tertiary)]">
diff --git a/packages/ui/src/health/trend-slope-chart.tsx b/packages/ui/src/health/trend-slope-chart.tsx
index b683e3b26..a032d847a 100644
--- a/packages/ui/src/health/trend-slope-chart.tsx
+++ b/packages/ui/src/health/trend-slope-chart.tsx
@@ -43,9 +43,9 @@ export function TrendSlopeChart({ points, height = 320, max = 18 }: TrendSlopeCh
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)]">
+ <p className="text-sm text-[var(--color-text-secondary)]">
No per-file score changes to plot yet.
- </div>
+ </p>
);
}
@@ -61,7 +61,8 @@ export function TrendSlopeChart({ points, height = 320, max = 18 }: TrendSlopeCh
const yScale = (score: number) => padT + ((10 - Math.max(0, Math.min(10, score))) / 10) * plotH;
return (
- <div className="relative rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">
+ // No card: the section heading above already frames this.
+ <div className="relative">
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Score change slope chart">
{/* Axis columns */}
<line x1={xBefore} y1={padT} x2={xBefore} y2={H - padB} stroke="currentColor" strokeOpacity={0.15} />
diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsx
index c6ab93c2d..a555e8ed8 100644
--- a/packages/ui/src/health/trend-view.tsx
+++ b/packages/ui/src/health/trend-view.tsx
@@ -1,22 +1,32 @@
"use client";
/**
- * Trend view — KPI history over recent indexes. Handles the single-snapshot
- * case explicitly (no misleading flat chart) and renders per-file score
- * movement as a slope chart. Trend data is fetched once by the host and passed
- * in, so it isn't double-fetched alongside the KPI sparklines.
+ * Trend view — the KPI history over recent indexes, on the section design
+ * language.
+ *
+ * It used to open with three `MetricCard`s in a grid, then stack tinted alert
+ * boxes and two dashed empty-state boxes under them: six bordered containers at
+ * near-identical weight for what is really two numbers, a warning and a chart.
+ * The figures are a hairline `StatRibbon` now, the alerts are rows that spend
+ * their colour on the icon and the label rather than on a ground, and the empty
+ * states are sentences saying what will fill them.
+ *
+ * The single-snapshot case stays explicit. A trend line drawn through one point
+ * is a flat line, which reads as "stable" when the truth is "not measured yet".
+ *
+ * Trend data is fetched once by the host and passed in, so it is not
+ * double-fetched alongside anything else on the page.
*/
-import { AlertTriangle, TrendingUp } from "lucide-react";
+import { AlertTriangle } from "lucide-react";
import type { HealthTrendResponse } from "@repowise-dev/types/health";
import { Skeleton } from "../ui/skeleton";
-import { MetricCard } from "../shared/metric-card";
-import { EmptyState } from "../shared/empty-state";
+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { TrendChart } from "./trend-chart";
import { TrendSlopeChart } from "./trend-slope-chart";
-import { deltaColor, formatDelta } from "./tokens";
+import { deltaColor, formatDelta, scoreTextColor } from "./tokens";
export function TrendView({
data,
@@ -30,89 +40,96 @@ export function TrendView({
if (isLoading) return <Skeleton className="h-64 w-full rounded-lg" />;
if (error || !data) {
return (
- <EmptyState
- title="Couldn't load trend data"
- description="The trend endpoint returned an error. Try refreshing."
- />
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Couldn&apos;t load trend data. Try refreshing.
+ </p>
);
}
const singleSnapshot = data.snapshot_count <= 1;
+ const { summary } = data;
+
+ // "0.00 vs. 7.5" is the shape a delta takes when nothing happened, and it
+ // reads as a measurement rather than as "no news". Say it plainly instead.
+ const deltaSub = (delta: number | null, previous: number | null) => {
+ if (delta == null) return "no prior snapshot";
+ if (Math.abs(delta) < 0.05) return "unchanged since last index";
+ return `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`;
+ };
+
+ const stats: RibbonStat[] = [
+ {
+ label: "Average health",
+ value: summary.current_average_health.toFixed(1),
+ valueColor: scoreTextColor(summary.current_average_health),
+ sub: deltaSub(summary.average_delta, summary.previous_average_health),
+ ...(Math.abs(summary.average_delta ?? 0) >= 0.05
+ ? { subColor: deltaColor(summary.average_delta) }
+ : {}),
+ },
+ {
+ label: "Hotspot health",
+ value: summary.current_hotspot_health.toFixed(1),
+ valueColor: scoreTextColor(summary.current_hotspot_health),
+ sub: deltaSub(summary.hotspot_delta, summary.previous_hotspot_health),
+ ...(Math.abs(summary.hotspot_delta ?? 0) >= 0.05
+ ? { subColor: deltaColor(summary.hotspot_delta) }
+ : {}),
+ },
+ {
+ label: "Snapshots",
+ value: String(data.snapshot_count),
+ sub: "rolling window, 50 max",
+ },
+ ];
return (
- <div className="space-y-6">
- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
- <DeltaMetric
- label="Average health"
- current={data.summary.current_average_health}
- previous={data.summary.previous_average_health}
- delta={data.summary.average_delta}
- />
- <DeltaMetric
- label="Hotspot health"
- current={data.summary.current_hotspot_health}
- previous={data.summary.previous_hotspot_health}
- delta={data.summary.hotspot_delta}
- />
- <MetricCard
- label="Snapshots"
- value={data.snapshot_count}
- distBar={
- <span className="text-xs text-[var(--color-text-tertiary)]">
- rolling window: 50 max
- </span>
- }
- />
- </div>
+ <div className="flex flex-col gap-6">
+ <StatRibbon stats={stats} />
- {data.alerts.length > 0 ? (
- <div className="space-y-2">
- {data.alerts.map((a, i) => (
- <div
- key={i}
- className={`rounded-lg border p-3 flex items-start gap-2 ${
- a.kind === "declining"
- ? "border-[var(--color-error)]/40 bg-[var(--color-error)]/5"
- : "border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5"
- }`}
- >
- <AlertTriangle
- className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-[var(--color-error)]" : "text-[var(--color-warning)]"}`}
- />
- <div className="text-sm">
- <p className="font-medium text-[var(--color-text-primary)]">
- {a.kind === "declining" ? "Declining health" : "Predicted decline"}
- </p>
- <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>
- </div>
- </div>
- ))}
+ {data.alerts.length > 0 && (
+ <div className="flex flex-col gap-2">
+ {data.alerts.map((a, i) => {
+ const color =
+ a.kind === "declining" ? "var(--color-error)" : "var(--color-warning)";
+ return (
+ <p key={i} className="flex items-start gap-2 text-sm">
+ <AlertTriangle
+ className="mt-0.5 h-4 w-4 shrink-0"
+ style={{ color }}
+ aria-hidden
+ />
+ <span>
+ <strong className="font-semibold" style={{ color }}>
+ {a.kind === "declining" ? "Declining health." : "Predicted decline."}
+ </strong>{" "}
+ <span className="text-[var(--color-text-secondary)]">{a.message}</span>
+ </span>
+ </p>
+ );
+ })}
</div>
- ) : null}
+ )}
{singleSnapshot ? (
- <EmptyState
- icon={<TrendingUp className="h-6 w-6" />}
- title="One snapshot so far"
- description="The trend lines appear once a second snapshot lands. Sync the repo (or wait for the next automatic one) and this page fills in."
- />
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ One snapshot so far. The trend lines appear once a second one lands. Sync the
+ repo, or wait for the next automatic index, and this fills in.
+ </p>
) : (
<TrendChart history={[...data.history].reverse()} />
)}
- <section className="space-y-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <section className="flex flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Largest score changes since last index
- </h2>
+ </h3>
{data.file_deltas.length === 0 ? (
- <EmptyState
- {...(singleSnapshot
- ? {
- title: "No comparison available yet",
- description: "Per-file deltas compare the last two snapshots.",
- }
- : { title: "No per-file changes between the last two snapshots" })}
- />
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ {singleSnapshot
+ ? "Per-file movement compares the last two snapshots, so it appears with the second one."
+ : "No file changed score between the last two snapshots."}
+ </p>
) : (
<TrendSlopeChart points={data.file_deltas} />
)}
@@ -120,36 +137,3 @@ export function TrendView({
</div>
);
}
-
-function DeltaMetric({
- label,
- current,
- previous,
- delta,
-}: {
- label: string;
- current: number;
- previous: number | null;
- delta: number | null;
-}) {
- return (
- <MetricCard
- label={label}
- value={
- <>
- {current.toFixed(1)}
- <span className="text-base font-normal text-[var(--color-text-secondary)]">
- /10
- </span>
- </>
- }
- distBar={
- <span className={`text-xs tabular-nums ${deltaColor(delta)}`}>
- {delta == null
- ? "no prior snapshot"
- : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}
- </span>
- }
- />
- );
-}
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
index f9aa99364..822ea9244 100644
--- a/packages/ui/src/health/triage-view.tsx
+++ b/packages/ui/src/health/triage-view.tsx
@@ -1,11 +1,21 @@
"use client";
/**
- * Triage view — the landing surface for Code Health. An airy proof + overview:
- * the "can you trust this score?" headline, the repo KPI strip, and the master–
- * detail Code Health map with its inspector rail. The dense drill-down (the
- * fix-next queue, performance risks, function-level panels) lives in
- * {@link FindingsView} behind its own tab.
+ * Code Health's landing surface, on the section design language.
+ *
+ * The shape is: one lede that leads with the defect score and says in prose
+ * what it means, then the galaxy map as the page's spine with its inspector
+ * beside it, then the host's hotspot and trend sections. Grouping is hairlines
+ * and vertical rhythm, not boxes — the previous version stacked a collapsible
+ * accuracy banner, three bordered signal tiles, a bordered stat strip and a
+ * bordered map, then floated three more glass panels on top of the map itself,
+ * which is chrome sitting on the one thing the reader came to look at.
+ *
+ * The map's lens switcher and legend now live around the canvas rather than on
+ * it (`chrome="none"`), which is also what let the floating panels go: one of
+ * them painted `--color-bg-glass`, a token still pinned to the graphite the
+ * dark ramp moved off in July, so those panels were rendering a surface colour
+ * that exists nowhere else in the app.
*
* Presentation + orchestration only: the host injects data, links, and the
* file-detail drawer through a {@link CodeHealthAdapter}, so web and hosted
@@ -13,6 +23,7 @@
*/
import { useCallback, useRef, useState } from "react";
+import type { ReactNode } from "react";
import useSWR from "swr";
import { Search } from "lucide-react";
import type {
@@ -24,48 +35,67 @@ import type {
import { Skeleton } from "../ui/skeleton";
import { ApiError } from "../shared/api-error";
import { toFriendlyMessage } from "../lib/errors";
+import { OverviewSection } from "../overview/section";
-import { HealthKpiCards } from "./kpi-cards";
+import { CodeHealthLede } from "./code-health-lede";
import { BiomarkerList } from "./biomarker-list";
import {
CodeHealthMap,
+ MapLegend,
+ MapLensSwitcher,
type CodeHealthMapFile,
type CodeHealthOverlay,
} from "./code-health-map";
-import { DefectAccuracyCard } from "./defect-accuracy-card";
import { FileSpotlight } from "./code-health-controls";
import { type Severity } from "./tokens";
import type { CodeHealthAdapter } from "./code-health-adapter";
export type HealthPillar = "all" | "defect" | "maintainability" | "performance";
+/** Map height. The inspector is height-matched to it so the rail never outgrows
+ * the field it is inspecting. */
+const MAP_HEIGHT = 720;
+
export function TriageView({
adapter,
- trend,
+ trend: _trend,
overlay = "health",
onOverlayChange,
+ lenses,
mapFiles,
overlayLoading,
pillar: controlledPillar,
onPillarChange,
+ hotspotsSlot,
+ trendSlot,
}: {
adapter: CodeHealthAdapter;
- /** Trend fetched once by the host — feeds the KPI sparklines. */
+ /** Trend fetched once by the host. Consumed by `trendSlot`; accepted here so
+ * the host's existing call site keeps type-checking. */
trend?: HealthTrendResponse;
/** Active map lens, owned by the host so the spine is shared across tabs. */
overlay?: CodeHealthOverlay;
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ /** Lenses offered in the switcher. Hosts that join churn in pass it here. */
+ lenses?: CodeHealthOverlay[];
/** Map files fetched once by the host (shared across overlays). */
mapFiles?: HealthFilesResponse;
/** The active lens's per-file signal is still loading (e.g. churn). */
overlayLoading?: boolean;
/**
* Findings pillar filter. Controlled by the host when it wants to URL-sync
- * the value (so the Overview + KPI tiles can deep-link into a dimension);
- * falls back to local state otherwise.
+ * the value; falls back to local state otherwise.
*/
pillar?: HealthPillar;
onPillarChange?: (pillar: HealthPillar) => void;
+ /**
+ * Sections the host composes and hands in, rather than props this view
+ * fetches for itself. Hotspots needs git history and trend needs a second
+ * endpoint; a host without either passes nothing and the section does not
+ * render, instead of an empty state pitching data that will never arrive.
+ */
+ hotspotsSlot?: ReactNode;
+ trendSlot?: ReactNode;
}) {
const { cacheKey } = adapter;
const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
@@ -74,16 +104,14 @@ export function TriageView({
{ revalidateOnFocus: false },
);
- // Severity gates the inspector-rail findings list.
+ // Severity gates the inspector findings list.
const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
const [selectedFile, setSelectedFile] = useState<string | null>(null);
- // ---- Map-driven UI: rail spotlight + filename dim + search ----
+ // ---- Map-driven UI: inspector spotlight + filename dim + search ----
const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);
const [mapQuery, setMapQuery] = useState("");
- // ---- Pillar filter — controlled by the host (URL-synced) when supplied,
- // otherwise local. Lets the Overview + KPI tiles deep-link a dimension. ----
const [pillarState, setPillarState] = useState<HealthPillar>("all");
const pillar = controlledPillar ?? pillarState;
const findingsRef = useRef<HTMLDivElement | null>(null);
@@ -94,16 +122,9 @@ export function TriageView({
},
[onPillarChange],
);
- const focusPillar = useCallback(
- (next: "defect" | "maintainability" | "performance") => {
- setPillar(next);
- findingsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
- },
- [setPillar],
- );
- // Severity + pillar drive the sidebar findings list; omit unset filters
- // rather than passing `undefined` (strict optional props in the shared lib).
+ // Severity + pillar drive the findings list; omit unset filters rather than
+ // passing `undefined` (strict optional props in the shared lib).
const sidebarFilter: {
minSeverity?: Severity;
dimension?: "defect" | "maintainability" | "performance";
@@ -111,160 +132,150 @@ export function TriageView({
if (minSeverity !== "all") sidebarFilter.minSeverity = minSeverity;
if (pillar !== "all") sidebarFilter.dimension = pillar;
- const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);
- const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);
- const worstSeries = trend?.history
- ?.slice()
- .reverse()
- .map((p) => p.worst_performer_score ?? 0);
-
- // KPI trend inputs are all optional in the shared card; include only the
- // ones the host actually fetched (no `undefined` under strict optionals).
- const kpiTrend: {
- averageHistory?: number[];
- hotspotHistory?: number[];
- worstHistory?: number[];
- averageDelta?: number;
- hotspotDelta?: number;
- } = {};
- if (avgSeries) kpiTrend.averageHistory = avgSeries;
- if (hotspotSeries) kpiTrend.hotspotHistory = hotspotSeries;
- if (worstSeries) kpiTrend.worstHistory = worstSeries;
- if (trend?.summary?.average_delta != null)
- kpiTrend.averageDelta = trend.summary.average_delta;
- if (trend?.summary?.hotspot_delta != null)
- kpiTrend.hotspotDelta = trend.summary.hotspot_delta;
-
- // CodeHealthMap's lens controls are optional; omit when the host doesn't
- // own the lens (hosted before it wires the shared spine).
+ // CodeHealthMap's optional props, omitted rather than passed as `undefined`.
const mapExtra: {
- onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ lenses?: CodeHealthOverlay[];
overlayLoading?: boolean;
} = {};
- if (onOverlayChange) mapExtra.onOverlayChange = onOverlayChange;
+ if (lenses) mapExtra.lenses = lenses;
if (overlayLoading !== undefined) mapExtra.overlayLoading = overlayLoading;
- return (
- <div className="space-y-6">
- {isLoading ? (
- <div className="space-y-3">
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-28 w-full rounded-xl" />
- ))}
- </div>
- <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-20 w-full rounded-lg" />
- ))}
- </div>
- </div>
- ) : error ? (
- <ApiError
- title="Couldn't load health data"
- message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}
- onRetry={() => void mutate()}
- />
- ) : overview ? (
- <>
- {/* Proof, up front: the defect-validated headline that sets this score
- apart — a slim one-line banner that expands to the full breakdown. */}
- {overview.defect_accuracy ? (
- <DefectAccuracyCard data={overview.defect_accuracy} collapsible />
- ) : null}
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-6">
+ {/* Shapes and widths match the real layout. A skeleton that does not
+ causes a reflow when content lands, which reads as slower than
+ showing nothing. */}
+ <Skeleton className="h-12 w-40 rounded-lg" />
+ <Skeleton className="h-20 w-full max-w-[54ch] rounded-lg" />
+ <Skeleton className="h-[74px] w-full" />
+ <Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ApiError
+ title="Couldn't load health data"
+ message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}
+ onRetry={() => void mutate()}
+ />
+ );
+ }
- <HealthKpiCards
- summary={overview.summary}
- distribution={overview.distribution ?? null}
- {...kpiTrend}
- onSelectPillar={focusPillar}
- />
+ if (!overview) return null;
- {/* Hero: the Code Health Map — modules as nested bubbles, files
- sized by lines of code and colored by health. The centerpiece. */}
- <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_320px] gap-6">
- <div className="space-y-2">
- <div className="flex flex-wrap items-baseline gap-2">
- <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
- Code health map
- </h2>
- <span className="text-xs text-[var(--color-text-tertiary)]">
- {mapFiles ? `${mapFiles.total.toLocaleString()} files` : "loading…"} · click a module to
- zoom, a file to open
+ return (
+ <div className="flex flex-col gap-6 sm:gap-8">
+ <CodeHealthLede
+ summary={overview.summary}
+ accuracy={overview.defect_accuracy ?? null}
+ distribution={overview.distribution ?? null}
+ />
+
+ <OverviewSection
+ title="Code health map"
+ description="Every file as a node, clustered into module galaxies and sized by lines of code. The lens recolors the same field rather than redrawing it. Click a galaxy to zoom, a file to inspect it."
+ action={
+ onOverlayChange ? (
+ <MapLensSwitcher
+ overlay={overlay}
+ onOverlayChange={onOverlayChange}
+ {...(lenses ? { lenses } : {})}
+ />
+ ) : undefined
+ }
+ >
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="flex flex-col gap-2.5">
+ {!mapFiles ? (
+ <Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
+ ) : (
+ <CodeHealthMap
+ files={mapFiles.files}
+ search={mapQuery}
+ selectedPath={selectedFile}
+ onSelectFile={(p) => setSelectedFile(p)}
+ onHoverFile={setHoverFile}
+ minHeight={MAP_HEIGHT}
+ overlay={overlay}
+ chrome="none"
+ {...mapExtra}
+ />
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">
+ <MapLegend overlay={overlay} loading={overlayLoading ?? false} />
+ {mapFiles && (
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] tabular-nums text-[var(--color-text-tertiary)]">
+ {mapFiles.total.toLocaleString()} files
</span>
- </div>
- {!mapFiles ? (
- <Skeleton className="w-full rounded-xl" style={{ height: 720 }} />
- ) : (
- <CodeHealthMap
- files={mapFiles.files}
- search={mapQuery}
- selectedPath={selectedFile}
- onSelectFile={(p) => setSelectedFile(p)}
- onHoverFile={setHoverFile}
- minHeight={720}
- overlay={overlay}
- {...mapExtra}
- />
)}
</div>
+ </div>
+
+ {/* Inspector — height-matched to the map. Separated by space, not by
+ a rule: a vertical hairline down the side of the canvas would turn
+ the map into a trench. */}
+ <aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[772px]">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
+ <input
+ value={mapQuery}
+ onChange={(e) => setMapQuery(e.target.value)}
+ placeholder="Find a file in the map…"
+ aria-label="Find a file in the map"
+ className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-strong)] focus:outline-none"
+ />
+ </div>
- {/* Inspector rail — height-matched to the map (master–detail).
- Search + the file you're inspecting sit on top; the findings
- list scrolls in place so the rail never outgrows the map. */}
- <aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[756px]">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <input
- value={mapQuery}
- onChange={(e) => setMapQuery(e.target.value)}
- placeholder="Find a file in the map…"
- className="w-full text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
+ <FileSpotlight file={hoverFile} onOpen={(p) => setSelectedFile(p)} />
- <FileSpotlight file={hoverFile} onOpen={(p) => setSelectedFile(p)} />
+ <div
+ ref={findingsRef}
+ className="flex flex-wrap items-center gap-2 border-t border-[var(--color-border-default)] pt-3"
+ >
+ <h3 className="mr-auto font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Findings
+ </h3>
+ <select
+ value={pillar}
+ onChange={(e) => setPillar(e.target.value as HealthPillar)}
+ aria-label="Health pillar"
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs"
+ >
+ <option value="all">All pillars</option>
+ <option value="defect">Defect risk</option>
+ <option value="maintainability">Maintainability</option>
+ <option value="performance">Performance</option>
+ </select>
+ <select
+ value={minSeverity}
+ onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
+ aria-label="Minimum severity"
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs"
+ >
+ <option value="all">All severities</option>
+ <option value="low">Low+</option>
+ <option value="medium">Medium+</option>
+ <option value="high">High+</option>
+ <option value="critical">Critical</option>
+ </select>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto pb-1 pr-1 lg:pb-0">
+ <BiomarkerList
+ findings={overview.top_findings}
+ compact
+ {...sidebarFilter}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ />
+ </div>
+ </aside>
+ </div>
+ </OverviewSection>
- <div ref={findingsRef} className="flex items-center gap-2 scroll-mt-4">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
- Findings
- </h2>
- <select
- value={pillar}
- onChange={(e) => setPillar(e.target.value as HealthPillar)}
- aria-label="Health pillar"
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
- >
- <option value="all">All pillars</option>
- <option value="defect">Defect risk</option>
- <option value="maintainability">Maintainability</option>
- <option value="performance">Performance</option>
- </select>
- <select
- value={minSeverity}
- onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
- aria-label="Minimum severity"
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
- >
- <option value="all">All severities</option>
- <option value="low">Low+</option>
- <option value="medium">Medium+</option>
- <option value="high">High+</option>
- <option value="critical">Critical</option>
- </select>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto pr-1 lg:pb-0 pb-1">
- <BiomarkerList
- findings={overview.top_findings}
- compact
- {...sidebarFilter}
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- </div>
- </aside>
- </div>
- </>
- ) : null}
+ {hotspotsSlot}
+ {trendSlot}
{adapter.renderFileDrawer({
filePath: selectedFile,
diff --git a/packages/ui/src/shared/page-lede.tsx b/packages/ui/src/shared/page-lede.tsx
index 9c934dce3..4e3b0a5fd 100644
--- a/packages/ui/src/shared/page-lede.tsx
+++ b/packages/ui/src/shared/page-lede.tsx
@@ -28,6 +28,22 @@ export interface PageLedeProps {
children: React.ReactNode;
/** Optional jump into the page that owns the subject. */
action?: React.ReactNode;
+ /**
+ * Where the prose sits.
+ *
+ * `"stacked"` (default) puts it under the figure — right for a lede that
+ * shares its row with something else, which is how Overview uses it.
+ * `"beside"` puts it in a column to the right, for a page whose lede owns the
+ * full width: at three paragraphs the stacked version pushes everything below
+ * it off the fold while leaving most of the row empty.
+ */
+ layout?: "stacked" | "beside";
+ /**
+ * Rendered directly under the figure, inside its column. For a second read
+ * that belongs to the number itself — a distribution bar, a sparkline — not
+ * for another statistic.
+ */
+ figureFooter?: React.ReactNode;
}
/**
@@ -52,9 +68,13 @@ export function PageLede({
badge,
children,
action,
+ layout = "stacked",
+ figureFooter,
}: PageLedeProps) {
- return (
- <div className="flex flex-col">
+ const beside = layout === "beside";
+
+ const figure = (
+ <div className={beside ? "flex shrink-0 flex-col" : "flex flex-col"}>
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{label}
</p>
@@ -89,13 +109,47 @@ export function PageLede({
{badge}
</div>
- <div className="mt-3.5 max-w-[54ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
- {children}
- </div>
+ {figureFooter && <div className="mt-4">{figureFooter}</div>}
+ </div>
+ );
+ const prose = (
+ <div
+ className={
+ beside
+ ? // Two columns from xl. Three paragraphs in one 62ch column runs tall
+ // enough to push the page's actual subject below the fold while
+ // leaving half the row empty; flowed into two ~48ch columns it is
+ // about half the height and fills the space it was already taking
+ // up. Paragraphs are kept whole so a sentence never splits across
+ // the gap.
+ "max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty] xl:max-w-[102ch] xl:columns-2 xl:gap-10 xl:[&>p]:break-inside-avoid"
+ : "max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]"
+ }
+ >
+ {children}
{action && <div className="mt-4">{action}</div>}
</div>
);
+
+ if (beside) {
+ return (
+ // The figure column is fixed so the prose starts at the same x whatever
+ // the number is; without it a 7.5 and a 10.0 indent the paragraph
+ // differently and the block looks unaligned between repos.
+ <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:gap-12">
+ <div className="lg:w-[220px]">{figure}</div>
+ {prose}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ {figure}
+ <div className="mt-3.5">{prose}</div>
+ </div>
+ );
}
/** The standard action under a lede. */
diff --git a/packages/ui/src/shared/view-tabs.tsx b/packages/ui/src/shared/view-tabs.tsx
index c840ab97b..1544375d5 100644
--- a/packages/ui/src/shared/view-tabs.tsx
+++ b/packages/ui/src/shared/view-tabs.tsx
@@ -6,7 +6,9 @@ import { cn } from "../lib/cn";
export interface ViewTab {
id: string;
label: string;
- badge?: number;
+ /** How much is behind this tab, so a clean one says so before it is clicked.
+ * A string carries a unit where the figure needs one ("61%"). */
+ badge?: number | string;
/** Optional leading icon. Lets a host carry a canonical icon for a tab (e.g.
* the Architecture/Knowledge-Graph surface) so both apps render the same
* glyph from one tab definition instead of hand-rolling their own toggle.
@@ -101,8 +103,11 @@ export function ViewTabs({
</span>
)}
{tab.label}
- {typeof tab.badge === "number" && (
- <span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-medium tabular-nums text-[var(--color-text-secondary)]">
+ {/* Mono text, no ground. A filled pill on every tab is a ground
+ that does not respond to anything — the count is a figure, and
+ figures the machine produced are set in mono. */}
+ {tab.badge !== undefined && (
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
{tab.badge}
</span>
)}
diff --git a/packages/ui/src/stats/stat-ribbon.tsx b/packages/ui/src/stats/stat-ribbon.tsx
index a82182d3c..36556fb77 100644
--- a/packages/ui/src/stats/stat-ribbon.tsx
+++ b/packages/ui/src/stats/stat-ribbon.tsx
@@ -4,6 +4,17 @@ export interface RibbonStat {
label: string;
value: string;
hint?: string;
+ /**
+ * Tailwind text-colour class for the value. Only for figures that carry a
+ * band — a health grade, a risk tercile — never to brighten a plain count.
+ * Added for Code Health, where a 3.1 and a 9.4 in the same row read as the
+ * same news without it.
+ */
+ valueColor?: string | undefined;
+ /** A quiet second line under the value — a delta, a comparison, a filename. */
+ sub?: string | undefined;
+ /** Tailwind text-colour class for `sub`. Same rule as `valueColor`. */
+ subColor?: string | undefined;
/** Optional jump to the page that owns this figure. Added because the
* Overview replaced a strip of *linked* KPI tiles with this component, and
* without it Files and Symbols lost their only entry point from that page. */
@@ -67,7 +78,11 @@ export function StatRibbon({
<dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{s.label}
</dt>
- <dd className="mt-1 text-xl font-semibold tabular-nums text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
+ <dd
+ className={`mt-1 text-xl font-semibold tabular-nums group-hover:text-[var(--color-accent-primary)] ${
+ s.valueColor ?? "text-[var(--color-text-primary)]"
+ }`}
+ >
{s.value}
</dd>
</A>
@@ -76,9 +91,22 @@ export function StatRibbon({
<dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{s.label}
</dt>
- <dd className="mt-1 text-xl font-semibold tabular-nums text-[var(--color-text-primary)]">
+ <dd
+ className={`mt-1 text-xl font-semibold tabular-nums ${
+ s.valueColor ?? "text-[var(--color-text-primary)]"
+ }`}
+ >
{s.value}
</dd>
+ {s.sub && (
+ <dd
+ className={`mt-0.5 text-xs tabular-nums ${
+ s.subColor ?? "text-[var(--color-text-tertiary)]"
+ }`}
+ >
+ {s.sub}
+ </dd>
+ )}
</>
)}
</div>
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index 9511bc2d4..a6ed14655 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -469,7 +469,12 @@
/* C4 / graph canvas surfaces — dark variants (the var()-derived aliases
flip on their own; only the explicit rgbas need a dark override). */
--color-canvas-dot: rgba(255, 255, 255, 0.05);
- --color-bg-glass: rgba(35, 35, 37, 0.72);
+ /* Tracks --color-bg-surface. It was rgba(35,35,37,.72) — the #232325 that
+ bg-surface used to be, left behind when the dark ramp moved in July 2026 —
+ so every glass chip on every canvas was painting a graphite that exists
+ nowhere else in the app, and read as a lighter plane floating over the new
+ near-black. Same alpha, current colour. */
+ --color-bg-glass: rgba(20, 20, 22, 0.72);
--color-bg-wash: rgba(255, 255, 255, 0.04);
--color-bg-wash-hover: rgba(255, 255, 255, 0.08);
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index d7e4f2c15..6bb3f8bff 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -3,74 +3,87 @@
/**
* Code Health — `/repos/[id]/code-health`.
*
- * One living map + a thin drill-down. The galaxy map is the page spine; a lens
- * switcher recolors the same field (health / coverage / churn — the three lenses
- * backed by per-file map data) so the cross-tab redundancy collapses. Dead-code
- * and security have no per-file map signal and stay on their own tabs. Surviving
- * tabs — Triage
- * (the map spine), Hotspots, Coverage, Dead code, Impact, Security — are
- * URL-synced via `?tab=`; the active lens via `?lens=`. Modules folded into the
- * map's hub layer and Trend into a compact section.
+ * One living map, a lede that says what the score means, and a thin drill-down.
+ * The galaxy map is the page spine; a lens switcher recolors the same field
+ * (health / maintainability / performance / churn) so the cross-tab redundancy
+ * collapses.
+ *
+ * Six tabs, down from seven. Hotspots is gone: it rendered a *second* galaxy map
+ * on the churn lens directly under this page's, so churn became a lens here and
+ * what the lens cannot say — bus factor, the ranked table — became a section
+ * under the map. Blast radius keeps its `impact` tab id (existing file-card and
+ * symbol-drawer deep links point at it) but is labelled for what it is.
+ *
+ * Tabs carry their count where one is cheap to get, so a clean repo says so
+ * before you spend a click. Findings rides on the overview request the page
+ * already makes and dead code dedupes onto the key its own tab uses. Security
+ * has no count endpoint (only a findings list), and blast radius is a tool you
+ * operate rather than a pile you read, so neither is numbered.
*/
import { useParams, useRouter, useSearchParams } from "next/navigation";
-import { useCallback, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { HeartPulse, RotateCw } from "lucide-react";
import { PageShell } from "@repowise-dev/ui/shared/page-shell";
import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
+import { OverviewSection } from "@repowise-dev/ui/overview";
import { Button } from "@repowise-dev/ui/ui/button";
import type { CodeHealthOverlay } from "@repowise-dev/ui/health";
+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
import { TriageTab } from "@/components/code-health/triage-tab";
+import { HotspotsSection } from "@/components/code-health/hotspots-section";
import { FindingsTab } from "@/components/code-health/findings-tab";
import { CoverageTab } from "@/components/code-health/coverage-tab";
import { TrendSection } from "@/components/code-health/trend-tab";
-import { HotspotsTab } from "@/components/risk/hotspots-tab";
import { DeadCodeTab } from "@/components/risk/dead-code-tab";
import { ImpactTab } from "@/components/risk/impact-tab";
import { SecurityTab } from "@/components/risk/security-tab";
+import { getDeadCodeSummary } from "@/lib/api/dead-code";
import {
+ getChurnComplexity,
+ getHealthCoverage,
getHealthOverview,
getHealthTrend,
listHealthFiles,
+ type ChurnComplexityResponse,
+ type HealthCoverageResponse,
type HealthOverviewResponse,
type HealthTrendResponse,
type HealthFilesResponse,
} from "@/lib/api/code-health";
-const TABS = ["triage", "findings", "hotspots", "coverage", "dead-code", "impact", "security"] as const;
+const TABS = ["triage", "findings", "coverage", "dead-code", "security", "impact"] as const;
type TabId = (typeof TABS)[number];
const TAB_LABELS: Record<TabId, string> = {
triage: "Overview",
findings: "Findings",
- hotspots: "Hotspots",
coverage: "Coverage",
"dead-code": "Dead code",
- impact: "Impact",
security: "Security",
+ impact: "Blast radius",
};
/**
- * Legacy tab ids → their new home. `heatmap` was the old churn tab; `modules`
- * folded into the map's hub layer; `trend` folded into the compact section that
- * lives under Triage.
+ * Legacy tab ids → their new home. `heatmap` was the old churn tab and
+ * `hotspots` its successor; both now land on the map, whose churn lens replaced
+ * them. `modules` folded into the map's hub layer, `trend` into the section
+ * under it.
*/
const TAB_ALIASES: Record<string, TabId> = {
- heatmap: "hotspots",
+ heatmap: "triage",
+ hotspots: "triage",
modules: "triage",
trend: "triage",
};
/**
- * Lenses selectable on the map: the three co-equal health signals (defect /
- * maintainability / performance), all backed by a per-file score in the map
- * payload. An unrecognized `?lens=` (including the retired `coverage`/`churn`/
- * `dead-code`/`security` values, which live on their own tabs) falls back to
- * `health` so a stale URL never renders an all-grey map.
+ * Lenses on the map. The three co-equal health signals ride on the map payload
+ * itself; churn arrives on its own request and is joined in below, which is why
+ * it is listed here rather than in the map component's default.
*/
-const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance"];
+const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];
export default function CodeHealthPage() {
const params = useParams<{ id: string }>();
@@ -89,7 +102,8 @@ export default function CodeHealthPage() {
? (rawLens as CodeHealthOverlay)
: "health";
- // Shares the SWR key with TriageTab — the meta line costs no extra request.
+ // Shares the SWR key with TriageView — the meta line and the findings count
+ // cost no extra request.
const { data: overview } = useSWR<HealthOverviewResponse>(
`code-health-overview:${repoId}`,
() => getHealthOverview(repoId, 25),
@@ -98,8 +112,7 @@ export default function CodeHealthPage() {
const meta = overview?.meta;
// Refresh revalidates every SWR key for this repo (overview + each tab's own
- // keys — coverage, findings, hotspots…), so the button works on whichever
- // tab is active, not just the shared overview.
+ // keys), so the button works on whichever tab is active.
const { mutate: mutateAll } = useSWRConfig();
const [refreshing, setRefreshing] = useState(false);
const refresh = useCallback(async () => {
@@ -115,8 +128,7 @@ export default function CodeHealthPage() {
}
}, [mutateAll, repoId]);
- // Trend fetched ONCE here, fed to both the KPI sparklines (Triage) and the
- // folded Trend section — no second fetch, no second SWR key.
+ // Trend fetched ONCE here, fed to the folded Trend section — no second fetch.
const { data: trend, isLoading: trendLoading, error: trendError } =
useSWR<HealthTrendResponse>(
`code-health-trend:${repoId}`,
@@ -124,18 +136,60 @@ export default function CodeHealthPage() {
{ revalidateOnFocus: false },
);
- // Every file (NLOC-first) for the circle-packing map — one big pull, shared
- // across overlays so switching the lens never refetches.
+ // Every file (NLOC-first) for the map — one big pull, shared across overlays
+ // so switching the lens never refetches.
const { data: mapFiles } = useSWR<HealthFilesResponse>(
`code-health-map-files:${repoId}`,
() => listHealthFiles(repoId, { limit: 2000, sort: "nloc", order: "desc" }),
{ revalidateOnFocus: false },
);
- // The maintainability + performance lenses recolor by per-file scores that
- // already ride along on the map payload (the `/files` rows carry
- // `maintainability_score` / `performance_score`), so no second fetch or merge
- // is needed — the lens switch is a pure recolor.
+ // Churn percentiles for the churn lens. Fetched only once that lens is
+ // selected: it is a second request, and the other three lenses color from
+ // fields already on the map payload.
+ const churnWanted = overlay === "churn";
+ const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(
+ churnWanted ? `health-churn-complexity:${repoId}` : null,
+ () => getChurnComplexity(repoId),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ // Join churn onto the map rows by path. Until it lands every node would be
+ // neutral, so the legend is told it is loading rather than letting an
+ // all-grey field read as "no churn anywhere".
+ const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {
+ if (!mapFiles || !churn) return mapFiles;
+ const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));
+ return {
+ ...mapFiles,
+ files: mapFiles.files.map((file) => ({
+ ...file,
+ churn_percentile: byPath.get(file.file_path) ?? null,
+ })),
+ };
+ }, [mapFiles, churn]);
+
+ // ---- Tab counts ----
+ // Dead code uses the same key + fetcher as its own tab, so this is a prefetch
+ // rather than a duplicate request.
+ const { data: deadCode } = useSWR<DeadCodeSummary>(
+ `dead-code-summary:${repoId}`,
+ () => getDeadCodeSummary(repoId),
+ { revalidateOnFocus: false },
+ );
+ // Coverage's own tab pulls 5,000 file rows; this asks for the summary alone,
+ // on its own key, so a badge never drags the heavy payload onto page load.
+ const { data: coverage } = useSWR<HealthCoverageResponse>(
+ `code-health-coverage-summary:${repoId}`,
+ () => getHealthCoverage(repoId, { limit: 1 }),
+ { revalidateOnFocus: false },
+ );
+ const coveragePct = coverage?.summary.line_coverage_pct;
+
+ const badges: Partial<Record<TabId, number | string>> = {};
+ if (overview) badges.findings = overview.summary.open_findings;
+ if (deadCode) badges["dead-code"] = deadCode.total_findings;
+ if (coveragePct != null) badges.coverage = `${Math.round(coveragePct)}%`;
const setTab = useCallback(
(next: string) => {
@@ -161,21 +215,24 @@ export default function CodeHealthPage() {
return (
<PageShell
- title="Code Health"
+ title="Code health"
icon={<HeartPulse className="h-5 w-5 text-[var(--color-success)]" />}
- description="Per-file health scores from complexity, duplication, coverage, churn, and ownership markers — ranked into a fix-next queue."
+ // No description: the lede below opens with what the score is built from,
+ // and a header that says it first only says it twice.
+ //
+ // "wide" rather than the style's usual 1280 — a deliberate divergence. At
+ // 1280 the map keeps ~900px beside its 320px inspector; the extra width
+ // goes entirely to the field, which is this page's whole subject.
maxWidth="wide"
actions={
<Button size="sm" variant="outline" onClick={refresh} disabled={refreshing}>
- <RotateCw
- className={`h-3.5 w-3.5 mr-1.5 ${refreshing ? "animate-spin" : ""}`}
- />{" "}
+ <RotateCw className={`mr-1.5 h-3.5 w-3.5 ${refreshing ? "animate-spin" : ""}`} />{" "}
{refreshing ? "Refreshing…" : "Refresh"}
</Button>
}
>
{meta ? (
- <p className="-mt-3 text-xs text-[var(--color-text-tertiary)]">
+ <p className="-mt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{meta.last_indexed_at
? `Indexed ${new Date(meta.last_indexed_at).toLocaleString()}`
: "Not indexed yet"}
@@ -185,30 +242,39 @@ export default function CodeHealthPage() {
) : null}
<ViewTabs
- tabs={TABS.map((id) => ({ id, label: TAB_LABELS[id] }))}
+ tabs={TABS.map((id) => ({
+ id,
+ label: TAB_LABELS[id],
+ ...(badges[id] !== undefined ? { badge: badges[id] } : {}),
+ }))}
value={activeTab}
onValueChange={setTab}
>
{activeTab === "triage" && (
- <div className="space-y-6">
- <TriageTab
- repoId={repoId}
- trend={trend}
- overlay={overlay}
- onOverlayChange={setOverlay}
- mapFiles={mapFiles}
- />
- <CollapsibleSection title="Health trend" defaultOpen={false}>
- <TrendSection data={trend} isLoading={trendLoading} error={trendError} />
- </CollapsibleSection>
- </div>
+ <TriageTab
+ repoId={repoId}
+ trend={trend}
+ overlay={overlay}
+ onOverlayChange={setOverlay}
+ lenses={OVERLAYS}
+ mapFiles={mapFilesWithChurn}
+ overlayLoading={churnWanted && churnLoading && !churn}
+ hotspotsSlot={<HotspotsSection repoId={repoId} />}
+ trendSlot={
+ <OverviewSection
+ title="Health trend"
+ description="How the scores have moved across indexed snapshots."
+ >
+ <TrendSection data={trend} isLoading={trendLoading} error={trendError} />
+ </OverviewSection>
+ }
+ />
)}
{activeTab === "findings" && <FindingsTab repoId={repoId} />}
- {activeTab === "hotspots" && <HotspotsTab repoId={repoId} />}
{activeTab === "coverage" && <CoverageTab repoId={repoId} />}
{activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}
- {activeTab === "impact" && <ImpactTab repoId={repoId} />}
{activeTab === "security" && <SecurityTab repoId={repoId} />}
+ {activeTab === "impact" && <ImpactTab repoId={repoId} />}
</ViewTabs>
</PageShell>
);
diff --git a/packages/web/src/components/code-health/hotspots-section.tsx b/packages/web/src/components/code-health/hotspots-section.tsx
new file mode 100644
index 000000000..fae55f42c
--- /dev/null
+++ b/packages/web/src/components/code-health/hotspots-section.tsx
@@ -0,0 +1,141 @@
+"use client";
+
+/**
+ * Hotspots, as a section under the Code Health map rather than a tab of its own.
+ *
+ * The tab it replaces rendered a *second* galaxy map — same component, churn
+ * lens, 420px — directly beneath the page's 720px one, plus five bordered chart
+ * cards at identical weight. Churn is now a lens on the single map, which is
+ * where it always belonged, so what survives here is only what the lens cannot
+ * say: which hot files have a single owner, and the ranked table itself.
+ *
+ * Four charts did not survive. The commit-category donut spent four unrelated
+ * hues on four categories, which is the exact pattern the colour rule exists to
+ * stop. The churn histogram, the risk-distribution chart and the churn-vs-bus-
+ * factor scatter all restate columns the table below them already shows, in a
+ * form you cannot sort.
+ *
+ * The scatter was the close call, and it lost on its own data. Its whole point
+ * is a top-right danger zone — changes constantly, only one person understands
+ * it — but on a real repo almost every hotspot sits at bus factor 1 and the
+ * 100th churn percentile, so the danger zone is the entire plot and the shape
+ * carries nothing. The table says it better: a `BUS FACTOR` column you can sort
+ * and a "Bus factor risk" filter chip that names the set outright.
+ */
+
+import { useState } from "react";
+import useSWR from "swr";
+import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
+import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
+import { AiPromptModal, buildHotspotAiPrompt } from "@repowise-dev/ui/health";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { hotspotToFileCard } from "@repowise-dev/ui/shared/file-card";
+import type { Hotspot } from "@repowise-dev/types/git";
+import Link from "next/link";
+import { useFileCardHost } from "@/components/shared/file-card-host";
+import { HotspotTopSymbolsHost } from "@/components/symbols/hotspot-top-symbols-host";
+import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper";
+import { getHotspotsPage } from "@/lib/api/git";
+import type { Paginated, SymbolResponse, HotspotResponse } from "@/lib/api/types";
+
+const PAGE_SIZE = 100;
+const PAGE_MAX = 500;
+
+export function HotspotsSection({ repoId }: { repoId: string }) {
+ const { showFile, dialog } = useFileCardHost(repoId);
+ const [pageLimit, setPageLimit] = useState(PAGE_SIZE);
+ const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);
+ const [promptHotspot, setPromptHotspot] = useState<Hotspot | null>(null);
+
+ const {
+ data: page,
+ isLoading,
+ isValidating,
+ error,
+ } = useSWR<Paginated<HotspotResponse>>(
+ `risk-hotspots:${repoId}:${pageLimit}`,
+ () => getHotspotsPage(repoId, { limit: pageLimit }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const list = page?.items ?? [];
+ const total = page?.total ?? list.length;
+
+ // The section renders nothing at all when a repo has no git history to mine,
+ // rather than an empty state explaining an absence the reader cannot act on.
+ if (!isLoading && !error && list.length === 0) return null;
+
+ return (
+ <OverviewSection
+ title="Hotspots"
+ description="Ranked by change frequency and prior bug fixes, mined from full git history. The danger is not churn on its own. It is a file that changes constantly and only one person understands."
+ action={
+ <SectionLink href={`/repos/${repoId}/commits`} LinkComponent={Link}>
+ Commit history
+ </SectionLink>
+ }
+ >
+ {error && list.length === 0 ? (
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Couldn&apos;t load hotspots. Run a sync to mine git history for this repo.
+ </p>
+ ) : isLoading && list.length === 0 ? (
+ <Skeleton className="h-72 w-full rounded-xl" />
+ ) : (
+ <HotspotTable
+ hotspots={list}
+ repoId={repoId}
+ onSelect={(h) => showFile(hotspotToFileCard(h))}
+ onGeneratePrompt={setPromptHotspot}
+ total={total}
+ hasMore={page?.has_more ?? false}
+ loadingMore={isValidating && !isLoading}
+ onLoadMore={() => setPageLimit((n) => Math.min(n + PAGE_SIZE, PAGE_MAX))}
+ renderExpandedRow={(h) => (
+ <HotspotTopSymbolsHost
+ repoId={repoId}
+ filePath={h.file_path}
+ onSelectSymbol={setDrawerSymbol}
+ />
+ )}
+ />
+ )}
+
+ {dialog}
+ <SymbolDrawerWrapper
+ symbol={drawerSymbol}
+ repoId={repoId}
+ onClose={() => setDrawerSymbol(null)}
+ />
+ <AiPromptModal
+ open={promptHotspot !== null}
+ onOpenChange={(o) => !o && setPromptHotspot(null)}
+ getPrompt={
+ promptHotspot
+ ? (flavor) =>
+ buildHotspotAiPrompt({
+ hotspot: {
+ file_path: promptHotspot.file_path,
+ churn_percentile: promptHotspot.churn_percentile,
+ commit_count_90d: promptHotspot.commit_count_90d,
+ commit_count_30d: promptHotspot.commit_count_30d,
+ bus_factor: promptHotspot.bus_factor,
+ contributor_count: promptHotspot.contributor_count,
+ primary_owner: promptHotspot.primary_owner,
+ lines_added_90d: promptHotspot.lines_added_90d,
+ lines_deleted_90d: promptHotspot.lines_deleted_90d,
+ temporal_hotspot_score: promptHotspot.temporal_hotspot_score,
+ change_entropy_pct: promptHotspot.change_entropy_pct,
+ prior_defect_count: promptHotspot.prior_defect_count,
+ },
+ flavor,
+ })
+ : null
+ }
+ filePath={promptHotspot?.file_path}
+ title="AI stabilization prompt"
+ description="A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain."
+ />
+ </OverviewSection>
+ );
+}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index a0240bb53..6e127f65b 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -8,6 +8,7 @@
*/
import { useCallback } from "react";
+import type { ReactNode } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
TriageView,
@@ -33,19 +34,27 @@ export function TriageTab({
trend,
overlay = "health",
onOverlayChange,
+ lenses,
mapFiles,
overlayLoading,
+ hotspotsSlot,
+ trendSlot,
}: {
repoId: string;
- /** Trend fetched once at the page level — feeds the KPI sparklines. */
+ /** Trend fetched once at the page level. */
trend?: HealthTrendResponse;
/** Active map lens, owned by the page so the spine is shared across tabs. */
overlay?: CodeHealthOverlay;
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ /** Lenses offered in the switcher, including any the page joined in. */
+ lenses?: CodeHealthOverlay[];
/** Map files fetched once at the page level (shared across overlays). */
mapFiles?: HealthFilesResponse;
/** The active lens's per-file signal is still loading (e.g. churn). */
overlayLoading?: boolean;
+ /** Sections composed by the page and rendered under the map. */
+ hotspotsSlot?: ReactNode;
+ trendSlot?: ReactNode;
}) {
const router = useRouter();
const searchParams = useSearchParams();
@@ -94,10 +103,13 @@ export function TriageTab({
trend={trend}
overlay={overlay}
onOverlayChange={onOverlayChange}
+ lenses={lenses}
mapFiles={mapFiles}
overlayLoading={overlayLoading}
pillar={pillar}
onPillarChange={onPillarChange}
+ hotspotsSlot={hotspotsSlot}
+ trendSlot={trendSlot}
/>
);
}
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
deleted file mode 100644
index 7f4ab1b2b..000000000
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ /dev/null
@@ -1,273 +0,0 @@
-"use client";
-
-import { useMemo, useState } from "react";
-import useSWR from "swr";
-import { useFileCardHost } from "@/components/shared/file-card-host";
-import { HotspotTopSymbolsHost } from "@/components/symbols/hotspot-top-symbols-host";
-import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper";
-import type { Paginated, SymbolResponse } from "@/lib/api/types";
-import { hotspotToFileCard } from "@repowise-dev/ui/shared/file-card";
-import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
-import { HotspotTrendStrip } from "@repowise-dev/ui/git/hotspot-trend-strip";
-import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
-import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";
-import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
-import { ChurnVsBusFactorScatter } from "@repowise-dev/ui/git/churn-vs-bus-factor-scatter";
-import {
- CodeHealthMap,
- type CodeHealthOverlay,
-} from "@repowise-dev/ui/health/code-health-map";
-import { AiPromptModal, buildHotspotAiPrompt } from "@repowise-dev/ui/health";
-import type { Hotspot } from "@repowise-dev/types/git";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { getHotspotsPage } from "@/lib/api/git";
-import { getChurnComplexity, listHealthFiles } from "@/lib/api/code-health";
-import type { ChurnComplexityResponse, HealthFilesResponse } from "@/lib/api/code-health";
-import type { HotspotResponse } from "@/lib/api/types";
-
-const PAGE_SIZE = 100;
-
-export function HotspotsTab({ repoId }: { repoId: string }) {
- const { showFile, dialog } = useFileCardHost(repoId);
- const [pageLimit, setPageLimit] = useState(PAGE_SIZE);
- const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);
- const [promptHotspot, setPromptHotspot] = useState<Hotspot | null>(null);
- // The galaxy map opens on the churn lens here — this is the hotspots surface,
- // so "what changes most" is the first read; the switcher still offers
- // health/coverage for cross-reference.
- const [overlay, setOverlay] = useState<CodeHealthOverlay>("churn");
- const { data: churnComplexity, isLoading: loadingChurn } =
- useSWR<ChurnComplexityResponse>(
- `health-churn-complexity:${repoId}`,
- () => getChurnComplexity(repoId),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- // Same payload + SWR key the triage page uses for its galaxy map, so the two
- // surfaces dedupe onto one request instead of double-fetching.
- const { data: mapFiles } = useSWR<HealthFilesResponse>(
- `code-health-map-files:${repoId}`,
- () => listHealthFiles(repoId, { limit: 2000, sort: "nloc", order: "desc" }),
- { revalidateOnFocus: false },
- );
-
- // The churn lens recolors by `churn_percentile`, which rides on the separate
- // churn request. Until it lands every node is neutral — flag that so the map
- // reads as "loading" rather than "no data".
- const overlayLoading = overlay === "churn" && loadingChurn && !churnComplexity;
-
- // Join churn percentiles onto the map files (by path) so the churn lens colors
- // real data; recomputes only when either source changes.
- const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {
- if (!mapFiles) return undefined;
- if (!churnComplexity) return mapFiles;
- const byPath = new Map(
- churnComplexity.points.map((p) => [p.file_path, p.churn_percentile]),
- );
- return {
- ...mapFiles,
- files: mapFiles.files.map((file) => ({
- ...file,
- churn_percentile: byPath.get(file.file_path) ?? null,
- })),
- };
- }, [mapFiles, churnComplexity]);
- const {
- data: hotspotsPage,
- isLoading: loadingHotspots,
- isValidating: validatingHotspots,
- error: hotspotsError,
- } = useSWR<Paginated<HotspotResponse>>(
- `risk-hotspots:${repoId}:${pageLimit}`,
- () => getHotspotsPage(repoId, { limit: pageLimit }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
- const list = hotspotsPage?.items ?? [];
- const total = hotspotsPage?.total ?? list.length;
- const hasMore = hotspotsPage?.has_more ?? false;
- const aggregatedCategories: Record<string, number> = {};
- for (const h of list) {
- for (const [cat, count] of Object.entries(h.commit_categories || {})) {
- aggregatedCategories[cat] = (aggregatedCategories[cat] || 0) + (count as number);
- }
- }
-
- if (loadingHotspots && list.length === 0) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-72 w-full" />
- </div>
- );
- }
-
- if (hotspotsError && list.length === 0) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">
- Couldn&apos;t load hotspots. The data may not be ready yet — try running a sync first.
- </div>
- );
- }
-
- return (
- <div className="space-y-6">
- {list.length > 0 && (
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <Card className="lg:col-span-2">
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Churn Distribution</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ChurnHistogram hotspots={list} />
- </CardContent>
- </Card>
-
- {Object.keys(aggregatedCategories).length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Commit Types</CardTitle>
- </CardHeader>
- <CardContent className="pt-0 flex items-center justify-center">
- <CommitCategoryDonut categories={aggregatedCategories} />
- </CardContent>
- </Card>
- )}
- </div>
- )}
-
- {list.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Code health map</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Files clustered into module galaxies — dot size is NLOC, color is the
- chosen lens. On churn, the brightest nodes are your hottest files;
- switch lenses to cross-reference health or coverage. Click a file to
- inspect it.
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- {!mapFilesWithChurn ? (
- <Skeleton className="h-[420px] w-full" />
- ) : (
- <CodeHealthMap
- files={mapFilesWithChurn.files}
- overlay={overlay}
- onOverlayChange={setOverlay}
- overlayLoading={overlayLoading}
- minHeight={420}
- onSelectFile={(path) => {
- const hit = list.find((h) => h.file_path === path);
- showFile(hit ? hotspotToFileCard(hit) : { file_path: path });
- }}
- />
- )}
- </CardContent>
- </Card>
- )}
-
- {list.length > 0 && (
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Risk Distribution</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Composite risk score: churn (40%) + bus factor (35%) + trend (25%)
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <RiskDistributionChart hotspots={list} />
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Churn × bus factor</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Top-right is the danger zone: high churn and a single owner. Bubble
- size reflects 90-day commit count.
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <ChurnVsBusFactorScatter
- hotspots={list}
- onSelect={(path) => {
- const hit = list.find((h) => h.file_path === path);
- if (hit) showFile(hotspotToFileCard(hit));
- }}
- />
- </CardContent>
- </Card>
- </div>
- )}
-
- {list.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Hotspot trend</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Top files by churn. Heating arrows mark files where the last 30 days are
- outpacing the 90-day baseline.
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <HotspotTrendStrip hotspots={list} />
- </CardContent>
- </Card>
- )}
-
- <HotspotTable
- hotspots={list}
- repoId={repoId}
- onSelect={(h) => showFile(hotspotToFileCard(h))}
- onGeneratePrompt={setPromptHotspot}
- total={total}
- hasMore={hasMore}
- loadingMore={validatingHotspots && !loadingHotspots}
- onLoadMore={() => setPageLimit((n) => Math.min(n + PAGE_SIZE, 500))}
- renderExpandedRow={(h) => (
- <HotspotTopSymbolsHost
- repoId={repoId}
- filePath={h.file_path}
- onSelectSymbol={setDrawerSymbol}
- />
- )}
- />
- {dialog}
- <SymbolDrawerWrapper
- symbol={drawerSymbol}
- repoId={repoId}
- onClose={() => setDrawerSymbol(null)}
- />
- <AiPromptModal
- open={promptHotspot !== null}
- onOpenChange={(o) => !o && setPromptHotspot(null)}
- getPrompt={
- promptHotspot
- ? (flavor) =>
- buildHotspotAiPrompt({
- hotspot: {
- file_path: promptHotspot.file_path,
- churn_percentile: promptHotspot.churn_percentile,
- commit_count_90d: promptHotspot.commit_count_90d,
- commit_count_30d: promptHotspot.commit_count_30d,
- bus_factor: promptHotspot.bus_factor,
- contributor_count: promptHotspot.contributor_count,
- primary_owner: promptHotspot.primary_owner,
- lines_added_90d: promptHotspot.lines_added_90d,
- lines_deleted_90d: promptHotspot.lines_deleted_90d,
- temporal_hotspot_score: promptHotspot.temporal_hotspot_score,
- change_entropy_pct: promptHotspot.change_entropy_pct,
- prior_defect_count: promptHotspot.prior_defect_count,
- },
- flavor,
- })
- : null
- }
- filePath={promptHotspot?.file_path}
- title="AI stabilization prompt"
- description="A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain."
- />
- </div>
- );
-}
diff --git a/packages/web/src/components/risk/impact-tab.tsx b/packages/web/src/components/risk/impact-tab.tsx
index e63790662..684859293 100644
--- a/packages/web/src/components/risk/impact-tab.tsx
+++ b/packages/web/src/components/risk/impact-tab.tsx
@@ -9,6 +9,7 @@
*/
import useSWR from "swr";
+import { useSearchParams } from "next/navigation";
import { ImpactView, type ImpactAdapter } from "@repowise-dev/ui/blast-radius";
import { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";
import { analyzeBlastRadius } from "@/lib/api/blast-radius";
@@ -38,6 +39,13 @@ function ReviewersPanel({ repoId, files }: { repoId: string; files: string[] })
}
export function ImpactTab({ repoId }: { repoId: string }) {
+ // `?file=` is how every route into this view arrives: the file card's "Blast
+ // Radius" button and the symbol drawer's CTA both link here with the path
+ // already chosen. Nothing read the param before, so those links landed on an
+ // empty picker and asked for the path back.
+ const searchParams = useSearchParams();
+ const seeded = searchParams.getAll("file").filter(Boolean);
+
const adapter: ImpactAdapter = {
cacheKey: repoId,
listHotspots: (limit) => getHotspots(repoId, limit),
@@ -50,5 +58,5 @@ export function ImpactTab({ repoId }: { repoId: string }) {
renderReviewers: (files) => <ReviewersPanel repoId={repoId} files={files} />,
};
- return <ImpactView adapter={adapter} />;
+ return <ImpactView adapter={adapter} {...(seeded.length > 0 ? { initialFiles: seeded } : {})} />;
}