Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): airy Code Health overview with a Findings workbench (#593)
Raghav Chamadiya61af457b72e8
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.pyindex 400a3bc38..4334404e0 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py@@ -433,7 +433,12 @@ async def get_health_findings(HealthFinding.status == status,)if biomarker_type is not None:- q = q.where(HealthFinding.biomarker_type == biomarker_type)+ # Accept a comma-separated list so a caller can pull several biomarker+ # types in one request (e.g. the function-level + coupling panels).+ # A single value with no comma still matches exactly (``IN`` of one).+ types = [t.strip() for t in biomarker_type.split(",") if t.strip()]+ if types:+ q = q.where(HealthFinding.biomarker_type.in_(types))if file_path is not None:q = q.where(HealthFinding.file_path == file_path)if dimension is not None:diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsxindex 081d18f11..e98b4893b 100644--- a/packages/ui/src/health/biomarker-list.tsx+++ b/packages/ui/src/health/biomarker-list.tsx@@ -15,6 +15,14 @@ import {import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";+/** Severity → dot color, same ramp as every score pill on the surface. */+const SEVERITY_DOT: Record<Severity, string> = {+ critical: "var(--color-error)",+ high: "var(--color-warning)",+ medium: "var(--color-caution)",+ low: "var(--color-text-tertiary)",+};+export interface BiomarkerFinding {id: string;file_path: string;@@ -45,6 +53,12 @@ export interface BiomarkerListProps {findings: BiomarkerFinding[];/** When true, group by biomarker type with collapsible sections. */grouped?: boolean;+ /**+ * One-line-per-finding mode for narrow rails: a severity dot, the file, a+ * muted biomarker tag, and the impact, with the prose moved to the tooltip.+ * Overrides `grouped`.+ */+ compact?: boolean;/** Optional minimum severity filter. */minSeverity?: Severity;/** Optional pillar filter: restrict to one health dimension. */@@ -70,6 +84,7 @@ function findingKey(f: BiomarkerFinding, index: number): string {export function BiomarkerList({findings,grouped = false,+ compact = false,minSeverity,dimension,onSelect,@@ -91,6 +106,16 @@ export function BiomarkerList({);}+ if (compact) {+ return (+ <ul className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">+ {filtered.map((f, i) => (+ <CompactFindingRow key={findingKey(f, i)} finding={f} onSelect={onSelect} />+ ))}+ </ul>+ );+ }+if (!grouped) {return (<ul className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">@@ -225,6 +250,46 @@ function BiomarkerGroup({);}+/** A single-line finding row for the inspector rail: severity dot · file ·+ * muted biomarker tag · impact. The reason + location ride in the tooltip. */+function CompactFindingRow({+ finding,+ onSelect,+}: {+ finding: BiomarkerFinding;+ onSelect?: ((f: BiomarkerFinding) => void) | undefined;+}) {+ const f = finding;+ const interactive = !!onSelect;+ const fileName = f.file_path.split("/").pop() ?? f.file_path;+ const tooltip = `${f.file_path}${f.function_name ? ` :: ${f.function_name}` : ""}\n${SEVERITY_LABEL[f.severity]} · −${f.health_impact.toFixed(2)}\n${f.reason}`;+ return (+ <li+ className={`flex items-center gap-2 px-2.5 py-1.5 text-xs ${interactive ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}+ onClick={interactive ? () => onSelect!(f) : undefined}+ title={tooltip}+ >+ <span+ className="h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: SEVERITY_DOT[f.severity] }}+ aria-label={SEVERITY_LABEL[f.severity]}+ />+ <span className="min-w-0 flex-1 truncate font-mono text-[var(--color-text-primary)]">+ {fileName}+ {f.function_name ? (+ <span className="text-[var(--color-text-tertiary)]">{` :: ${f.function_name}`}</span>+ ) : null}+ </span>+ <span className="shrink-0 text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {biomarkerLabel(f.biomarker_type)}+ </span>+ <span className="shrink-0 tabular-nums text-[var(--color-error)]">+ −{f.health_impact.toFixed(2)}+ </span>+ </li>+ );+}+function DimensionChip({ dimension }: { dimension: BiomarkerDimension }) {return (<spandiff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsxindex d68396611..ff05510e5 100644--- a/packages/ui/src/health/code-health-map.tsx+++ b/packages/ui/src/health/code-health-map.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import * as d3 from "d3-hierarchy";import { scoreBand, type ScoreBand } from "./tokens";import { useCommunityFamilies } from "../shared/use-theme-tokens";@@ -12,6 +12,10 @@ export interface CodeHealthMapFile {module: string | null;line_coverage_pct: number | null;has_test_file: boolean;+ /** Maintainability pillar score (1–10) — drives the maintainability overlay. */+ maintainability_score?: number | null;+ /** Performance-risk pillar score (1–10) — drives the performance overlay. */+ performance_score?: number | null;/** 0–100 churn percentile — drives the churn overlay. */churn_percentile?: number | null;/** Reclaimable lines on this file — drives the dead-code overlay. */@@ -26,6 +30,8 @@ export interface CodeHealthMapFile {*/export type CodeHealthOverlay =| "health"+ | "maintainability"+ | "performance"| "coverage"| "churn"| "dead-code"@@ -88,6 +94,12 @@ interface OverlaySpec {legend: LegendRow[];}+/** Score band: same ramp as the health lens, grey when the pillar is unscored. */+function scoreFill(score: number | null | undefined): string {+ if (score == null) return NEUTRAL_FILL;+ return BAND_FILL[scoreBand(score)];+}+/** Coverage band: green = well covered, red = uncovered, grey = no data. */function coverageFill(pct: number | null | undefined): string {if (pct == null) return NEUTRAL_FILL;@@ -113,6 +125,24 @@ const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {fill: (f) => BAND_FILL[scoreBand(f.score)],legend: BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),},+ maintainability: {+ label: "Maintainability",+ caption: "color = maintainability score · grey = not measured",+ fill: (f) => scoreFill(f.maintainability_score),+ legend: [+ ...BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),+ { fill: NEUTRAL_FILL, label: "not measured" },+ ],+ },+ performance: {+ label: "Performance",+ caption: "color = performance-risk score · grey = not measured",+ fill: (f) => scoreFill(f.performance_score),+ legend: [+ ...BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),+ { fill: NEUTRAL_FILL, label: "not measured" },+ ],+ },coverage: {label: "Coverage",caption: "color = line coverage · grey = no coverage data",@@ -158,12 +188,12 @@ const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {};/**- * Lenses offered in the on-canvas switcher. Only the three backed by per-file- * map data are exposed; dead-code and security have no per-file signal in the- * map payload and live on their own tabs, so their `OVERLAY_SPECS` entries stay- * defined (the type is extensible) but are not presented here.+ * 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.*/-const OVERLAY_ORDER: CodeHealthOverlay[] = ["health", "coverage", "churn"];+const OVERLAY_ORDER: CodeHealthOverlay[] = ["health", "maintainability", "performance"];const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad@@ -258,6 +288,23 @@ export function CodeHealthMap({const [hovered, setHovered] = useState<CodeHealthMapFile | null>(null);const famFor = useCommunityFamilies();+ // Latest callbacks held in refs so the node-layer handlers stay referentially+ // stable across renders (the parent re-renders on every hover to drive the+ // rail). Stable handlers let the memoized <FileNodes> skip re-rendering its+ // ~2,000 circles when only the hover/selection highlight changes.+ const onSelectRef = useRef(onSelectFile);+ onSelectRef.current = onSelectFile;+ const onHoverRef = useRef(onHoverFile);+ onHoverRef.current = onHoverFile;+ const handleSelect = useCallback((path: string) => onSelectRef.current?.(path), []);+ const handleHoverEnter = useCallback((f: CodeHealthMapFile) => {+ setHovered(f);+ onHoverRef.current?.(f);+ }, []);+ const handleHoverLeave = useCallback((f: CodeHealthMapFile) => {+ setHovered((h) => (h === f ? null : h));+ }, []);+useEffect(() => {if (!containerRef.current) return;const observer = new ResizeObserver((es) => {@@ -321,6 +368,14 @@ export function CodeHealthMap({return { galaxies, byModule };}, [files, S]);+ // path → laid-out node, for the highlight overlay to position itself without+ // re-rendering the whole node layer on hover/selection.+ const nodeIndex = useMemo(() => {+ const m = new Map<string, FileNode>();+ for (const g of galaxies) for (const nd of g.nodes) m.set(nd.file.file_path, nd);+ return m;+ }, [galaxies]);+// Starfield — static layer, regenerated only on resize.const stars = useMemo(() => {const { width, height } = dims;@@ -448,45 +503,33 @@ export function CodeHealthMap({);})}- {/* File nodes */}- {galaxies.map((g) => {- const faded = focusGalaxy != null && focusGalaxy !== g;- return (- <g key={`nodes-${g.module}`}>- {g.nodes.map((nd) => {- const f = nd.file;- const dim = q.length > 0 && !f.file_path.toLowerCase().includes(q);- const isSel = selectedPath === f.file_path;- const isHover = hovered?.file_path === f.file_path;- return (- <circle- key={f.file_path}- cx={nd.x + offX}- cy={nd.y + offY}- r={isHover ? nd.r + 1.5 : nd.r}- fill={overlaySpec.fill(f)}- fillOpacity={faded ? 0.18 : dim ? 0.12 : isHover || isSel ? 1 : 0.9}- stroke={isSel ? "var(--color-text-primary)" : "var(--color-bg-canvas)"}- strokeWidth={isSel ? 2 : 0.5}- vectorEffect="non-scaling-stroke"- className={onSelectFile ? "cursor-pointer" : undefined}- onMouseEnter={() => {- setHovered(f);- onHoverFile?.(f);- }}- onMouseLeave={() => setHovered((h) => (h === f ? null : h))}- onClick={(e) => {- e.stopPropagation();- onSelectFile?.(f.file_path);- }}- >- <title>{`${f.file_path}\nscore ${f.score.toFixed(1)} · ${f.nloc.toLocaleString()} NLOC`}</title>- </circle>- );- })}- </g>- );- })}+ {/* File nodes — memoized base layer (~2,000 circles). Hover and+ selection are drawn by the cheap highlight layer below, so moving+ the mouse never re-renders this layer. */}+ <FileNodes+ galaxies={galaxies}+ focusModuleKey={focusGalaxy?.module ?? null}+ fill={overlaySpec.fill}+ q={q}+ offX={offX}+ offY={offY}+ interactive={!!onSelectFile}+ onSelect={handleSelect}+ onHoverEnter={handleHoverEnter}+ onHoverLeave={handleHoverLeave}+ />++ {/* Highlight overlay — the hovered (enlarged, opaque) and selected+ (ring) nodes only, drawn on top. Re-renders on hover/select; the+ base node layer above stays untouched. */}+ <NodeHighlight+ hovered={hovered}+ selectedPath={selectedPath ?? null}+ nodeIndex={nodeIndex}+ offX={offX}+ offY={offY}+ fill={overlaySpec.fill}+ />{/* Hub markers */}{galaxies.map((g) => {@@ -611,6 +654,123 @@ export function CodeHealthMap({);}+/**+ * The base file-node layer: every file as a circle, sized + colored by the+ * active lens. Memoized and fed only stable props (laid-out galaxies, a stable+ * fill fn, stable handlers), so a hover — which re-renders the parent — never+ * reconciles these ~2,000 elements. Hover/selection live in {@link NodeHighlight}.+ */+const FileNodes = memo(function FileNodes({+ galaxies,+ focusModuleKey,+ fill,+ q,+ offX,+ offY,+ interactive,+ onSelect,+ onHoverEnter,+ onHoverLeave,+}: {+ galaxies: Galaxy[];+ focusModuleKey: string | null;+ fill: (f: CodeHealthMapFile) => string;+ q: string;+ offX: number;+ offY: number;+ interactive: boolean;+ onSelect: (path: string) => void;+ onHoverEnter: (f: CodeHealthMapFile) => void;+ onHoverLeave: (f: CodeHealthMapFile) => void;+}) {+ return (+ <>+ {galaxies.map((g) => {+ const faded = focusModuleKey != null && g.module !== focusModuleKey;+ return (+ <g key={`nodes-${g.module}`}>+ {g.nodes.map((nd) => {+ const f = nd.file;+ const dim = q.length > 0 && !f.file_path.toLowerCase().includes(q);+ return (+ <circle+ key={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"+ className={interactive ? "cursor-pointer" : undefined}+ onMouseEnter={() => onHoverEnter(f)}+ onMouseLeave={() => onHoverLeave(f)}+ onClick={(e) => {+ e.stopPropagation();+ onSelect(f.file_path);+ }}+ >+ <title>{`${f.file_path}\nscore ${f.score.toFixed(1)} · ${f.nloc.toLocaleString()} NLOC`}</title>+ </circle>+ );+ })}+ </g>+ );+ })}+ </>+ );+});++/** The hovered + selected nodes only, drawn on top of the static node layer so+ * pointer movement repaints two circles instead of the whole field. */+function NodeHighlight({+ hovered,+ selectedPath,+ nodeIndex,+ offX,+ offY,+ fill,+}: {+ hovered: CodeHealthMapFile | null;+ selectedPath: string | null;+ nodeIndex: Map<string, FileNode>;+ offX: number;+ offY: number;+ fill: (f: CodeHealthMapFile) => string;+}) {+ const sel = selectedPath ? nodeIndex.get(selectedPath) : null;+ const hov = hovered ? nodeIndex.get(hovered.file_path) : null;+ return (+ <g className="pointer-events-none">+ {sel ? (+ <circle+ cx={sel.x + offX}+ cy={sel.y + offY}+ r={sel.r}+ fill={fill(sel.file)}+ fillOpacity={1}+ stroke="var(--color-text-primary)"+ strokeWidth={2}+ vectorEffect="non-scaling-stroke"+ />+ ) : null}+ {hov && hov !== sel ? (+ <circle+ cx={hov.x + offX}+ cy={hov.y + offY}+ r={hov.r + 1.5}+ fill={fill(hov.file)}+ fillOpacity={1}+ stroke="var(--color-bg-canvas)"+ strokeWidth={0.5}+ vectorEffect="non-scaling-stroke"+ />+ ) : null}+ </g>+ );+}+function HoverCard({ file }: { file: CodeHealthMapFile }) {const cov = file.line_coverage_pct;return (diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsxnew file mode 100644index 000000000..4ab32fd16--- /dev/null+++ b/packages/ui/src/health/findings-view.tsx@@ -0,0 +1,509 @@+"use client";++/**+ * Findings view — the engineer's workbench. The ranked fix-next queue+ * (refactoring targets + file inventory), the cross-function performance-risk+ * panel, and the function-level / hidden-coupling panels.+ *+ * Split out of {@link TriageView} so the landing surface stays an airy+ * proof + map overview and the dense drill-down lives behind its own tab.+ * Presentation + orchestration only: the host injects data, links, and the+ * file-detail drawer through a {@link CodeHealthAdapter}.+ */++import { useMemo, useState } from "react";+import useSWR from "swr";+import { Gauge, Search } from "lucide-react";+import type {+ HealthFinding,+ HealthFilesResponse,+ HealthOverviewResponse,+ RefactoringQuery,+ RefactoringTargetsResponse,+} from "@repowise-dev/types/health";++import { Skeleton } from "../ui/skeleton";+import { Button } from "../ui/button";+import { EmptyState } from "../shared/empty-state";+import { CollapsibleSection } from "../shared/collapsible-section";++import { AiPromptModal } from "./ai-prompt-modal";+import { HealthFileTable, type FileSortField } from "./file-table";+import { BiomarkerList } from "./biomarker-list";+import { HotFunctionsPanel } from "./hot-functions-panel";+import { HiddenCouplingList } from "./hidden-coupling-list";+import {+ RefactoringTargetList,+ type FindingStatus,+ type RefactoringTarget,+} from "./refactoring-target-list";+import { FilterSelect, FilterChip, ViewToggle } from "./code-health-controls";+import { ImpactEffortQuadrant } from "./impact-effort-quadrant";+import { biomarkerLabel } from "./biomarker-glossary";+import { buildAiPrompt } from "./ai-prompt-builder";+import { type Severity } from "./tokens";+import type { CodeHealthAdapter } from "./code-health-adapter";++const PAGE_SIZE = 50;+const QUEUE_PAGE = 200;+const QUEUE_MAX = 500;++type GroupBy = "none" | "biomarker" | "module" | "effort";+type QueueView = "queue" | "files";++/** Function-level biomarker types fed to the Hot functions panel. */+const HOT_FN_TYPES = ["function_hotspot", "code_age_volatility", "complex_conditional"];++const EFFORT_LABEL: Record<string, string> = {+ S: "Small (≤40 NLOC)",+ M: "Medium (≤150 NLOC)",+ L: "Large (≤400 NLOC)",+ XL: "Extra large (>400 NLOC)",+};++export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {+ const { cacheKey } = adapter;++ // Shares the page-level overview key, so this dedupes onto the one request+ // the landing view already fired — no extra round-trip. Used to gate the+ // queue fetch and seed the biomarker filter options.+ const { data: overview } = useSWR<HealthOverviewResponse>(+ `code-health-overview:${cacheKey}`,+ () => adapter.getOverview(25),+ { revalidateOnFocus: false },+ );++ // The function-level panels and the hidden-coupling list pull four biomarker+ // types — fetched in ONE request (comma-separated `biomarker_type`) and+ // partitioned client-side, instead of four round-trips.+ const { data: panelFindings } = useSWR<HealthFinding[]>(+ `code-health-panel-findings:${cacheKey}`,+ () =>+ adapter+ .listFindings({+ biomarker_type: [...HOT_FN_TYPES, "hidden_coupling"].join(","),+ limit: 400,+ })+ .catch(() => [] as HealthFinding[]),+ { revalidateOnFocus: false },+ );++ const hotFunctionFindings = useMemo(+ () => panelFindings?.filter((f) => HOT_FN_TYPES.includes(f.biomarker_type)),+ [panelFindings],+ );+ const couplingFindings = useMemo(+ () => panelFindings?.filter((f) => f.biomarker_type === "hidden_coupling"),+ [panelFindings],+ );++ // Every open performance-pillar finding (the cross-function N+1 / I/O-in-loop+ // moat), for the dedicated Performance risks panel.+ const { data: perfFindings } = useSWR<HealthFinding[]>(+ `code-health-perf-findings:${cacheKey}`,+ () =>+ adapter+ .listFindings({ dimension: "performance", limit: 200 })+ .catch(() => [] as HealthFinding[]),+ { revalidateOnFocus: false },+ );++ // ---- Queue filters ----+ const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");+ const [biomarker, setBiomarker] = useState<string>("all");+ const [maxEffort, setMaxEffort] = useState<string>("all");+ const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");+ const [groupBy, setGroupBy] = useState<GroupBy>("none");+ const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);+ const [view, setView] = useState<QueueView>("queue");+ const [selectedFile, setSelectedFile] = useState<string | null>(null);+ const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);++ const queueKey = useMemo(+ () =>+ JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),+ [cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],+ );+ const {+ data: queue,+ isLoading: queueLoading,+ mutate: mutateQueue,+ } = useSWR<RefactoringTargetsResponse>(+ overview ? `code-health-queue:${queueKey}` : null,+ () =>+ adapter.getRefactoringTargets({+ limit: queueLimit,+ ...(biomarker !== "all" && { biomarker }),+ ...(minSeverity !== "all" && { min_severity: minSeverity }),+ ...(maxEffort !== "all" && { max_effort: maxEffort }),+ ...(sort && { sort }),+ }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ // ---- All-files inventory view ----+ const [sortField, setSortField] = useState<FileSortField>("score");+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");+ const [search, setSearch] = useState("");+ const [onlyHotspots, setOnlyHotspots] = useState(false);+ const [onlyUntested, setOnlyUntested] = useState(false);+ const [onlyFailing, setOnlyFailing] = useState(false);+ const [offset, setOffset] = useState(0);++ const filesKey = useMemo(+ () =>+ JSON.stringify({+ cacheKey,+ sortField,+ sortOrder,+ search,+ onlyHotspots,+ onlyUntested,+ onlyFailing,+ offset,+ }),+ [cacheKey, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],+ );++ const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(+ overview && view === "files" ? `code-health-files:${filesKey}` : null,+ () =>+ adapter.listFiles({+ sort: sortField,+ order: sortOrder,+ ...(search && { search }),+ ...(onlyHotspots && { only_hotspots: true }),+ ...(onlyUntested && { only_untested: true }),+ ...(onlyFailing && { only_failing: true }),+ offset,+ limit: PAGE_SIZE,+ }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ const handleSort = (field: FileSortField) => {+ if (field === sortField) {+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));+ } else {+ setSortField(field);+ // Score: asc (worst first). Counts: desc. Path: asc.+ setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");+ }+ setOffset(0);+ };++ const handleStatus = async (findingId: string, status: FindingStatus) => {+ await adapter.updateFindingStatus(findingId, status);+ mutateQueue();+ };++ const biomarkerOptions = useMemo(() => {+ const set = new Set<string>();+ (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));+ (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));+ return [...set].sort();+ }, [overview, queue]);++ // Grouped queue — group order follows the user's sort (first occurrence),+ // not group size, so "Leverage" sorted stays leverage-led inside and out.+ const grouped = useMemo(() => {+ const targets = queue?.targets ?? [];+ if (groupBy === "none") return [{ key: "All", targets }];+ const groups = new Map<string, typeof targets>();+ for (const t of targets) {+ let key = "—";+ if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);+ else if (groupBy === "module") key = t.module ?? "(no module)";+ else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key)!.push(t);+ }+ return [...groups.entries()].map(([key, targets]) => ({ key, targets }));+ }, [queue, groupBy]);++ return (+ <div className="space-y-6">+ {/* Performance risks — the cross-function N+1 / I/O-in-loop moat, given a+ dedicated home. Only rendered when risks actually exist (high+ precision, low recall), so a clean repo stays uncluttered. */}+ {perfFindings && perfFindings.length > 0 ? (+ <CollapsibleSection+ title={+ <span className="inline-flex items-center gap-2">+ <Gauge className="h-4 w-4 text-[var(--color-info)]" />+ Performance risks+ </span>+ }+ hint={`${perfFindings.length} ${perfFindings.length === 1 ? "risk" : "risks"}`}+ defaultOpen+ >+ <div className="space-y-3">+ <p className="text-xs text-[var(--color-text-secondary)]">+ Static performance risk: a DB, network, filesystem, or subprocess call+ per loop iteration, detected across function boundaries via the call+ graph. High precision, low recall, never blended into the defect score.+ </p>+ <BiomarkerList+ findings={perfFindings}+ grouped+ onSelect={(f) => setSelectedFile(f.file_path)}+ />+ </div>+ </CollapsibleSection>+ ) : null}++ {/* The full ranked queue + file inventory. */}+ <div className="space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">+ Fix next+ {queue?.total != null ? (+ <span className="ml-2 normal-case tracking-normal text-[var(--color-text-secondary)]">+ {queue.total} candidates+ </span>+ ) : null}+ </h3>+ <ViewToggle+ value={view}+ onChange={setView}+ options={[+ { value: "queue", label: "Queue" },+ { value: "files", label: "All files" },+ ]}+ />+ </div>++ {view === "queue" ? (+ <>+ <div className="flex flex-wrap items-center gap-2">+ <FilterSelect+ label="Biomarker"+ value={biomarker}+ onChange={setBiomarker}+ options={[+ { value: "all", label: "All biomarkers" },+ ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),+ ]}+ />+ <FilterSelect+ label="Severity"+ value={minSeverity}+ onChange={(v) => setMinSeverity(v as Severity | "all")}+ options={[+ { value: "all", label: "All severities" },+ { value: "low", label: "Low+" },+ { value: "medium", label: "Medium+" },+ { value: "high", label: "High+" },+ { value: "critical", label: "Critical" },+ ]}+ />+ <FilterSelect+ label="Max effort"+ value={maxEffort}+ onChange={setMaxEffort}+ options={[+ { value: "all", label: "Any effort" },+ { value: "S", label: "Small only" },+ { value: "M", label: "Medium+" },+ { value: "L", label: "Large+" },+ ]}+ />+ <FilterSelect+ label="Sort"+ value={sort ?? "impact_per_effort"}+ onChange={(v) => setSort(v as RefactoringQuery["sort"])}+ options={[+ { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },+ { value: "total_impact", label: "Total impact" },+ { value: "score", label: "Worst score" },+ { value: "finding_count", label: "Finding count" },+ ]}+ />+ <FilterSelect+ label="Group"+ value={groupBy}+ onChange={(v) => setGroupBy(v as GroupBy)}+ options={[+ { value: "none", label: "Flat list" },+ { value: "biomarker", label: "By biomarker" },+ { value: "module", label: "By module" },+ { value: "effort", label: "By effort" },+ ]}+ />+ </div>++ {queueLoading && !queue ? (+ <div className="grid gap-3">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-28 w-full" />+ ))}+ </div>+ ) : !queue || queue.targets.length === 0 ? (+ <EmptyState+ title="No findings match the current filters"+ description="Try widening the severity or effort filters, or run repowise health to populate findings."+ />+ ) : (+ <>+ {/* Leverage at a glance — impact vs effort, click a dot to open+ the file. Replaces the text-dense ranking as the first read. */}+ <ImpactEffortQuadrant+ points={(queue?.targets ?? []).map((t) => ({+ file_path: t.file_path,+ total_impact: t.total_impact,+ effort_bucket: t.effort_bucket,+ nloc: t.nloc,+ score: t.score,+ }))}+ onSelect={(p) => setSelectedFile(p.file_path)}+ />+ <div className="space-y-6">+ {grouped.map((g) => (+ <section key={g.key} className="space-y-2">+ {groupBy !== "none" ? (+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {g.key}{" "}+ <span className="text-[var(--color-text-secondary)]">+ ({g.targets.length})+ </span>+ </h3>+ ) : null}+ <RefactoringTargetList+ targets={g.targets}+ onSelect={(t) => setSelectedFile(t.file_path)}+ onStatusChange={handleStatus}+ onGeneratePrompt={(t) => setPromptTarget(t)}+ />+ </section>+ ))}+ </div>++ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">+ <span>+ Showing {queue.targets.length} of {queue.total} candidates+ </span>+ {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (+ <Button+ size="sm"+ variant="outline"+ onClick={() => setQueueLimit(QUEUE_MAX)}+ >+ Load more+ </Button>+ ) : null}+ </div>+ </>+ )}+ </>+ ) : (+ <>+ <div className="flex flex-wrap items-center gap-2">+ <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={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setOffset(0);+ }}+ placeholder="Filter path…"+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"+ />+ </div>+ <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>+ Hotspots+ </FilterChip>+ <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>+ Untested+ </FilterChip>+ <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>+ Failing+ </FilterChip>+ <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">+ {files?.total != null ? `${files.total.toLocaleString()} files` : ""}+ </span>+ </div>++ {filesLoading && !files ? (+ <Skeleton className="h-64 w-full rounded-lg" />+ ) : (+ <HealthFileTable+ files={files?.files ?? []}+ sortField={sortField}+ sortOrder={sortOrder}+ onSort={handleSort}+ onSelect={(f) => setSelectedFile(f.file_path)}+ selectedPath={selectedFile}+ />+ )}++ {files && files.total > PAGE_SIZE ? (+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">+ <span>+ Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}+ </span>+ <div className="flex gap-1">+ <Button+ size="sm"+ variant="outline"+ disabled={offset === 0}+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}+ >+ Prev+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={offset + PAGE_SIZE >= files.total}+ onClick={() => setOffset(offset + PAGE_SIZE)}+ >+ Next+ </Button>+ </div>+ </div>+ ) : null}+ </>+ )}+ </div>++ {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (+ <HotFunctionsPanel+ findings={hotFunctionFindings}+ collapsible+ onSelect={(f) => setSelectedFile(f.file_path)}+ symbolHrefFor={(f) =>+ f.symbol_id ? adapter.symbolHref?.(f.symbol_id) : undefined+ }+ />+ ) : null}++ {couplingFindings && couplingFindings.length >= 3 ? (+ <HiddenCouplingList+ findings={couplingFindings}+ collapsible+ onSelect={(path) => setSelectedFile(path)}+ />+ ) : null}++ {adapter.renderFileDrawer({+ filePath: selectedFile,+ onClose: () => setSelectedFile(null),+ })}++ <AiPromptModal+ open={promptTarget !== null}+ onOpenChange={(open) => {+ if (!open) setPromptTarget(null);+ }}+ filePath={promptTarget?.file_path ?? null}+ title="AI fix prompt"+ description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."+ getPrompt={+ promptTarget+ ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })+ : null+ }+ />+ </div>+ );+}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex b4bdbe001..d01b8b6b8 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -38,5 +38,6 @@ export * from "./recalibration-banner";export * from "./defect-accuracy-card";export * from "./code-health-adapter";export * from "./triage-view";+export * from "./findings-view";export * from "./coverage-view";export * from "./trend-view";diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsxindex 504e0f9e5..7b6b9b0de 100644--- a/packages/ui/src/health/kpi-cards.tsx+++ b/packages/ui/src/health/kpi-cards.tsx@@ -11,7 +11,7 @@ import {deltaColor,} from "./tokens";import { Sparkline } from "./sparkline";-import { SeverityDistribution, type SeverityBreakdown } from "./severity-distribution";+import { type SeverityBreakdown } from "./severity-distribution";import { HealthDistributionBar } from "./health-distribution-bar";export interface HealthSummary {@@ -62,7 +62,6 @@ export function HealthKpiCards({distribution,averageHistory,hotspotHistory,- worstHistory,averageDelta,hotspotDelta,onSelectPillar,@@ -116,50 +115,93 @@ export function HealthKpiCards({/></div>- {/* ── Operational stats: the supporting strip, visually quieter ── */}- <div className="grid grid-cols-2 gap-3 md:grid-cols-4">- <StatCard label="Files Analyzed">- <p className="text-xl font-semibold text-[var(--color-text-primary)] tabular-nums">- {formatNumber(summary.file_count)}- </p>- </StatCard>- <StatCard- label="Hotspot Health"- sparkline={hotspotHistory}+ {/* ── Operational stats: one quiet inline strip, not a second card grid ── */}+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-2.5">+ <InlineStat label="Files" value={formatNumber(summary.file_count)} />+ <InlineStat+ label="Hotspot health"+ value={summary.hotspot_health == null ? "—" : summary.hotspot_health.toFixed(1)}+ suffix={summary.hotspot_health == null ? undefined : "/10"}+ valueClass={scoreTextColor(summary.hotspot_health ?? null)}delta={hotspotDelta}+ sparkline={hotspotHistory}hint="The health score averaged over the repo's churn hotspots only (NLOC-weighted) — how healthy is the code you touch most?"- >- <p className={`text-xl font-semibold tabular-nums ${scoreTextColor(summary.hotspot_health ?? null)}`}>- {summary.hotspot_health == null ? "—" : summary.hotspot_health.toFixed(1)}- {summary.hotspot_health == null ? null : (- <span className="text-sm font-normal text-[var(--color-text-secondary)]">/10</span>- )}- </p>- </StatCard>- <StatCard label="Worst Performer" sparkline={worstHistory}>- <p className={`text-xl font-semibold tabular-nums ${scoreTextColor(summary.worst_performer_score)}`}>- {summary.worst_performer_score?.toFixed(1) ?? "—"}- <span className="text-sm font-normal text-[var(--color-text-secondary)]">/10</span>- </p>- <p className="text-xs text-[var(--color-text-tertiary)] mt-1 truncate font-mono">- {summary.worst_performer_path ?? "no data"}- </p>- </StatCard>- <StatCard label="Open Findings">- <p className="text-xl font-semibold text-[var(--color-text-primary)] tabular-nums">- {formatNumber(summary.open_findings)}- </p>- {summary.severity_breakdown ? (- <div className="mt-2">- <SeverityDistribution breakdown={summary.severity_breakdown} showCounts={false} />- </div>- ) : null}- </StatCard>+ />+ <InlineStat+ label="Worst performer"+ value={summary.worst_performer_score?.toFixed(1) ?? "—"}+ suffix={summary.worst_performer_score == null ? undefined : "/10"}+ valueClass={scoreTextColor(summary.worst_performer_score)}+ sub={+ summary.worst_performer_path+ ? summary.worst_performer_path.split("/").pop() ?? summary.worst_performer_path+ : undefined+ }+ subTitle={summary.worst_performer_path ?? undefined}+ />+ <InlineStat label="Open findings" value={formatNumber(summary.open_findings)} /></div></div>);}+/** A compact horizontal stat — tiny label, value, optional /10 suffix, sub-line,+ * delta, and sparkline. Several sit in one slim strip below the signal tiles. */+function InlineStat({+ label,+ value,+ suffix,+ valueClass,+ sub,+ subTitle,+ delta,+ sparkline,+ hint,+}: {+ label: string;+ value: string;+ suffix?: string | undefined;+ valueClass?: string | undefined;+ sub?: string | undefined;+ subTitle?: string | undefined;+ delta?: number | null | undefined;+ sparkline?: number[] | undefined;+ hint?: string | undefined;+}) {+ return (+ <div className="flex flex-col">+ <span className="inline-flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {label}+ {hint ? <InfoTip content={hint} label={`About ${label}`} /> : null}+ </span>+ <span className="flex items-baseline gap-1.5">+ <span className={`text-base font-semibold tabular-nums ${valueClass ?? "text-[var(--color-text-primary)]"}`}>+ {value}+ {suffix ? (+ <span className="text-xs font-normal text-[var(--color-text-secondary)]">{suffix}</span>+ ) : null}+ </span>+ {delta != null && Math.abs(delta) >= 0.005 ? (+ <span className={`text-[11px] tabular-nums ${deltaColor(delta)}`}>{formatDelta(delta)}</span>+ ) : null}+ {sparkline && sparkline.length > 1 ? (+ <span className="text-[var(--color-text-tertiary)]">+ <Sparkline values={sparkline} width={44} height={12} />+ </span>+ ) : null}+ {sub ? (+ <span+ className="max-w-[16rem] truncate font-mono text-xs text-[var(--color-text-tertiary)]"+ title={subTitle}+ >+ {sub}+ </span>+ ) : null}+ </span>+ </div>+ );+}+/** A hero signal tile: icon + label, a large score/10 with band badge, and an* optional supporting line. Becomes a button when `onClick` is provided. */function SignalTile({@@ -245,7 +287,7 @@ function TileShell({children: React.ReactNode;}) {const cls =- "flex w-full flex-col rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-5 text-left transition-colors";+ "flex w-full flex-col rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 text-left transition-colors";if (onClick) {return (<button@@ -328,39 +370,3 @@ function PerformanceTile({);return <TileShell onClick={interactive ? onClick : undefined}>{inner}</TileShell>;}--function StatCard({- label,- children,- sparkline,- delta,- hint,-}: {- label: string;- children: React.ReactNode;- sparkline?: number[] | undefined;- delta?: number | null | undefined;- hint?: string | undefined;-}) {- return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <div className="flex items-start justify-between gap-2 mb-1">- <p className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">- {label}- {hint ? <InfoTip content={hint} label={`About ${label}`} /> : null}- </p>- {sparkline && sparkline.length > 0 ? (- <div className="text-[var(--color-text-tertiary)]">- <Sparkline values={sparkline} width={56} height={16} />- </div>- ) : null}- </div>- {children}- {delta != null ? (- <p className={`mt-1 text-xs tabular-nums ${deltaColor(delta)}`}>- {formatDelta(delta)} vs. prior- </p>- ) : null}- </div>- );-}diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsxindex b257407ee..7f634a634 100644--- a/packages/ui/src/health/triage-view.tsx+++ b/packages/ui/src/health/triage-view.tsx@@ -1,79 +1,44 @@"use client";/**- * Triage view — the "what do I fix next" surface. KPI strip, the master–detail- * Code Health map + inspector rail, the ranked fix-next queue (refactoring- * targets + file inventory), a severity-coordinated findings sidebar, and the- * function-level panels.+ * 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.** Presentation + orchestration only: the host injects data, links, and the* file-detail drawer through a {@link CodeHealthAdapter}, so web and hosted* render the same view from different backends.*/-import { useCallback, useMemo, useRef, useState } from "react";+import { useCallback, useRef, useState } from "react";import useSWR from "swr";-import { Gauge, Search } from "lucide-react";+import { Search } from "lucide-react";import type {- HealthFinding,HealthFilesResponse,HealthOverviewResponse,HealthTrendResponse,- RefactoringQuery,- RefactoringTargetsResponse,} from "@repowise-dev/types/health";import { Skeleton } from "../ui/skeleton";import { Button } from "../ui/button";-import { EmptyState } from "../shared/empty-state";-import { CollapsibleSection } from "../shared/collapsible-section";-import { AiPromptModal } from "./ai-prompt-modal";import { HealthKpiCards } from "./kpi-cards";-import { HealthFileTable, type FileSortField } from "./file-table";import { BiomarkerList } from "./biomarker-list";-import { HotFunctionsPanel } from "./hot-functions-panel";-import { HiddenCouplingList } from "./hidden-coupling-list";import {CodeHealthMap,type CodeHealthMapFile,type CodeHealthOverlay,} from "./code-health-map";import { RecalibrationBanner } from "./recalibration-banner";-import {- RefactoringTargetList,- type FindingStatus,- type RefactoringTarget,-} from "./refactoring-target-list";import { DefectAccuracyCard } from "./defect-accuracy-card";-import {- FileSpotlight,- FilterSelect,- FilterChip,- ViewToggle,-} from "./code-health-controls";-import { ImpactEffortQuadrant } from "./impact-effort-quadrant";-import { biomarkerLabel } from "./biomarker-glossary";-import { buildAiPrompt } from "./ai-prompt-builder";+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";-const PAGE_SIZE = 50;-const QUEUE_PAGE = 200;-const QUEUE_MAX = 500;--type GroupBy = "none" | "biomarker" | "module" | "effort";-type QueueView = "queue" | "files";--const EFFORT_LABEL: Record<string, string> = {- S: "Small (≤40 NLOC)",- M: "Medium (≤150 NLOC)",- L: "Large (≤400 NLOC)",- XL: "Extra large (>400 NLOC)",-};-export function TriageView({adapter,trend,@@ -108,58 +73,12 @@ export function TriageView({() => adapter.getOverview(25),{ revalidateOnFocus: false },);- const { data: hotFunctionFindings } = useSWR<HealthFinding[]>(- `code-health-hot-functions:${cacheKey}`,- async () => {- const types = [- "function_hotspot",- "code_age_volatility",- "complex_conditional",- ] as const;- const batches = await Promise.all(- types.map((t) =>- adapter.listFindings({ biomarker_type: t, limit: 100 }).catch(- () => [] as HealthFinding[],- ),- ),- );- return batches.flat();- },- { revalidateOnFocus: false },- );- const { data: couplingFindings } = useSWR<HealthFinding[]>(- `code-health-hidden-coupling:${cacheKey}`,- () =>- adapter- .listFindings({ biomarker_type: "hidden_coupling", limit: 100 })- .catch(() => []),- { revalidateOnFocus: false },- );-- // Every open performance-pillar finding (the cross-function N+1 / I/O-in-loop- // moat), for the dedicated Performance risks panel.- const { data: perfFindings } = useSWR<HealthFinding[]>(- `code-health-perf-findings:${cacheKey}`,- () =>- adapter- .listFindings({ dimension: "performance", limit: 200 })- .catch(() => [] as HealthFinding[]),- { revalidateOnFocus: false },- );-- // ---- One filter set coordinates the queue AND the findings sidebar ----+ // Severity gates the inspector-rail findings list.const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");- const [biomarker, setBiomarker] = useState<string>("all");- const [maxEffort, setMaxEffort] = useState<string>("all");- const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");- const [groupBy, setGroupBy] = useState<GroupBy>("none");- const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);- const [view, setView] = useState<QueueView>("queue");const [selectedFile, setSelectedFile] = useState<string | null>(null);- const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);- // ---- Map-driven UI: rail spotlight + filename dim + collapsible list ----+ // ---- Map-driven UI: rail spotlight + filename dim + search ----const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);const [mapQuery, setMapQuery] = useState("");@@ -183,108 +102,6 @@ export function TriageView({[setPillar],);- const queueKey = useMemo(- () =>- JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),- [cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],- );- const {- data: queue,- isLoading: queueLoading,- mutate: mutateQueue,- } = useSWR<RefactoringTargetsResponse>(- overview ? `code-health-queue:${queueKey}` : null,- () =>- adapter.getRefactoringTargets({- limit: queueLimit,- ...(biomarker !== "all" && { biomarker }),- ...(minSeverity !== "all" && { min_severity: minSeverity }),- ...(maxEffort !== "all" && { max_effort: maxEffort }),- ...(sort && { sort }),- }),- { revalidateOnFocus: false, keepPreviousData: true },- );-- // ---- All-files inventory view ----- const [sortField, setSortField] = useState<FileSortField>("score");- const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");- const [search, setSearch] = useState("");- const [onlyHotspots, setOnlyHotspots] = useState(false);- const [onlyUntested, setOnlyUntested] = useState(false);- const [onlyFailing, setOnlyFailing] = useState(false);- const [offset, setOffset] = useState(0);-- const filesKey = useMemo(- () =>- JSON.stringify({- cacheKey,- sortField,- sortOrder,- search,- onlyHotspots,- onlyUntested,- onlyFailing,- offset,- }),- [cacheKey, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],- );-- const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(- overview && view === "files" ? `code-health-files:${filesKey}` : null,- () =>- adapter.listFiles({- sort: sortField,- order: sortOrder,- ...(search && { search }),- ...(onlyHotspots && { only_hotspots: true }),- ...(onlyUntested && { only_untested: true }),- ...(onlyFailing && { only_failing: true }),- offset,- limit: PAGE_SIZE,- }),- { revalidateOnFocus: false, keepPreviousData: true },- );-- const handleSort = (field: FileSortField) => {- if (field === sortField) {- setSortOrder((o) => (o === "asc" ? "desc" : "asc"));- } else {- setSortField(field);- // Score: asc (worst first). Counts: desc. Path: asc.- setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");- }- setOffset(0);- };-- const handleStatus = async (findingId: string, status: FindingStatus) => {- await adapter.updateFindingStatus(findingId, status);- mutateQueue();- };-- const biomarkerOptions = useMemo(() => {- const set = new Set<string>();- (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));- (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));- return [...set].sort();- }, [overview, queue]);-- // Grouped queue — group order follows the user's sort (first occurrence),- // not group size, so "Leverage" sorted stays leverage-led inside and out.- const grouped = useMemo(() => {- const targets = queue?.targets ?? [];- if (groupBy === "none") return [{ key: "All", targets }];- const groups = new Map<string, typeof targets>();- for (const t of targets) {- let key = "—";- if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);- else if (groupBy === "module") key = t.module ?? "(no module)";- else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;- if (!groups.has(key)) groups.set(key, []);- groups.get(key)!.push(t);- }- return [...groups.entries()].map(([key, targets]) => ({ key, targets }));- }, [queue, groupBy]);-// Severity + pillar drive the sidebar findings list; omit unset filters// rather than passing `undefined` (strict optional props in the shared lib).const sidebarFilter: {@@ -350,6 +167,13 @@ export function TriageView({) : overview ? (<><RecalibrationBanner repoId={cacheKey} />++ {/* 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}+<HealthKpiCardssummary={overview.summary}distribution={overview.distribution ?? null}@@ -357,10 +181,6 @@ export function TriageView({onSelectPillar={focusPillar}/>- {overview.defect_accuracy ? (- <DefectAccuracyCard data={overview.defect_accuracy} collapsible />- ) : null}-{/* Hero: the Code Health Map — modules as nested bubbles, filessized 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">@@ -375,7 +195,7 @@ export function TriageView({</span></div>{!mapFiles ? (- <Skeleton className="w-full rounded-xl" style={{ height: 664 }} />+ <Skeleton className="w-full rounded-xl" style={{ height: 720 }} />) : (<CodeHealthMapfiles={mapFiles.files}@@ -383,7 +203,7 @@ export function TriageView({selectedPath={selectedFile}onSelectFile={(p) => setSelectedFile(p)}onHoverFile={setHoverFile}- minHeight={664}+ minHeight={720}overlay={overlay}{...mapExtra}/>@@ -393,7 +213,7 @@ export function TriageView({{/* Inspector rail — height-matched to the map (master–detail).Search + the file you're inspecting sit on top; the findingslist scrolls in place so the rail never outgrows the map. */}- <aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[700px]">+ <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@@ -424,7 +244,7 @@ export function TriageView({<selectvalue={minSeverity}onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}- aria-label="Minimum severity (filters the queue too)"+ 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>@@ -437,266 +257,13 @@ export function TriageView({<div className="min-h-0 flex-1 overflow-y-auto pr-1 lg:pb-0 pb-1"><BiomarkerListfindings={overview.top_findings}- grouped+ compact{...sidebarFilter}onSelect={(f) => setSelectedFile(f.file_path)}/></div></aside></div>-- {/* Performance risks — the cross-function N+1 / I/O-in-loop moat,- given a dedicated home. Only rendered when risks actually exist- (high precision, low recall), so a clean repo stays uncluttered. */}- {perfFindings && perfFindings.length > 0 ? (- <CollapsibleSection- title={- <span className="inline-flex items-center gap-2">- <Gauge className="h-4 w-4 text-[var(--color-info)]" />- Performance risks- </span>- }- hint={`${perfFindings.length} ${perfFindings.length === 1 ? "risk" : "risks"}`}- defaultOpen- >- <div className="space-y-3">- <p className="text-xs text-[var(--color-text-secondary)]">- Static performance risk: a DB, network, filesystem, or subprocess call- per loop iteration, detected across function boundaries via the call- graph. High precision, low recall, never blended into the defect score.- </p>- <BiomarkerList- findings={perfFindings}- grouped- onSelect={(f) => setSelectedFile(f.file_path)}- />- </div>- </CollapsibleSection>- ) : null}-- {/* Collapsible: the full ranked queue + file inventory. The severity- filter is shared with the rail above (one control, no duplicate). */}- <CollapsibleSection- title="Targets & findings list"- hint={queue?.total != null ? `${queue.total} candidates` : ""}- defaultOpen={false}- >- <div className="space-y-3">- <div className="flex flex-wrap items-center gap-2">- <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">- Fix next- </h3>- <ViewToggle- value={view}- onChange={setView}- options={[- { value: "queue", label: "Queue" },- { value: "files", label: "All files" },- ]}- />- </div>-- {view === "queue" ? (- <>- <div className="flex flex-wrap items-center gap-2">- <FilterSelect- label="Biomarker"- value={biomarker}- onChange={setBiomarker}- options={[- { value: "all", label: "All biomarkers" },- ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),- ]}- />- <FilterSelect- label="Max effort"- value={maxEffort}- onChange={setMaxEffort}- options={[- { value: "all", label: "Any effort" },- { value: "S", label: "Small only" },- { value: "M", label: "Medium+" },- { value: "L", label: "Large+" },- ]}- />- <FilterSelect- label="Sort"- value={sort ?? "impact_per_effort"}- onChange={(v) => setSort(v as RefactoringQuery["sort"])}- options={[- { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },- { value: "total_impact", label: "Total impact" },- { value: "score", label: "Worst score" },- { value: "finding_count", label: "Finding count" },- ]}- />- <FilterSelect- label="Group"- value={groupBy}- onChange={(v) => setGroupBy(v as GroupBy)}- options={[- { value: "none", label: "Flat list" },- { value: "biomarker", label: "By biomarker" },- { value: "module", label: "By module" },- { value: "effort", label: "By effort" },- ]}- />- </div>-- {queueLoading && !queue ? (- <div className="grid gap-3">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-28 w-full" />- ))}- </div>- ) : !queue || queue.targets.length === 0 ? (- <EmptyState- title="No findings match the current filters"- description="Try widening the severity or effort filters, or run repowise health to populate findings."- />- ) : (- <>- {/* Leverage at a glance — impact vs effort, click a dot- to open the file. Replaces the text-dense ranking as- the first read of the queue. */}- <ImpactEffortQuadrant- points={(queue?.targets ?? []).map((t) => ({- file_path: t.file_path,- total_impact: t.total_impact,- effort_bucket: t.effort_bucket,- nloc: t.nloc,- score: t.score,- }))}- onSelect={(p) => setSelectedFile(p.file_path)}- />- <div className="space-y-6">- {grouped.map((g) => (- <section key={g.key} className="space-y-2">- {groupBy !== "none" ? (- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- {g.key}{" "}- <span className="text-[var(--color-text-secondary)]">- ({g.targets.length})- </span>- </h3>- ) : null}- <RefactoringTargetList- targets={g.targets}- onSelect={(t) => setSelectedFile(t.file_path)}- onStatusChange={handleStatus}- onGeneratePrompt={(t) => setPromptTarget(t)}- />- </section>- ))}- </div>-- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">- <span>- Showing {queue.targets.length} of {queue.total} candidates- </span>- {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (- <Button- size="sm"- variant="outline"- onClick={() => setQueueLimit(QUEUE_MAX)}- >- Load more- </Button>- ) : null}- </div>- </>- )}- </>- ) : (- <>- <div className="flex flex-wrap items-center gap-2">- <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={search}- onChange={(e) => {- setSearch(e.target.value);- setOffset(0);- }}- placeholder="Filter path…"- className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"- />- </div>- <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>- Hotspots- </FilterChip>- <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>- Untested- </FilterChip>- <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>- Failing- </FilterChip>- <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">- {files?.total != null ? `${files.total.toLocaleString()} files` : ""}- </span>- </div>-- {filesLoading && !files ? (- <Skeleton className="h-64 w-full rounded-lg" />- ) : (- <HealthFileTable- files={files?.files ?? []}- sortField={sortField}- sortOrder={sortOrder}- onSort={handleSort}- onSelect={(f) => setSelectedFile(f.file_path)}- selectedPath={selectedFile}- />- )}-- {files && files.total > PAGE_SIZE ? (- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">- <span>- Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}- </span>- <div className="flex gap-1">- <Button- size="sm"- variant="outline"- disabled={offset === 0}- onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}- >- Prev- </Button>- <Button- size="sm"- variant="outline"- disabled={offset + PAGE_SIZE >= files.total}- onClick={() => setOffset(offset + PAGE_SIZE)}- >- Next- </Button>- </div>- </div>- ) : null}- </>- )}- </div>- </CollapsibleSection>-- {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (- <HotFunctionsPanel- findings={hotFunctionFindings}- collapsible- onSelect={(f) => setSelectedFile(f.file_path)}- symbolHrefFor={(f) =>- f.symbol_id ? adapter.symbolHref?.(f.symbol_id) : undefined- }- />- ) : null}-- {couplingFindings && couplingFindings.length >= 3 ? (- <HiddenCouplingList- findings={couplingFindings}- collapsible- onSelect={(path) => setSelectedFile(path)}- />- ) : null}</>) : null}@@ -704,21 +271,6 @@ export function TriageView({filePath: selectedFile,onClose: () => setSelectedFile(null),})}-- <AiPromptModal- open={promptTarget !== null}- onOpenChange={(open) => {- if (!open) setPromptTarget(null);- }}- filePath={promptTarget?.file_path ?? null}- title="AI fix prompt"- description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."- getPrompt={- promptTarget- ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })- : null- }- /></div>);}diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex f3f83cbab..dacdf0795 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -14,7 +14,7 @@*/import { useParams, useRouter, useSearchParams } from "next/navigation";-import { useCallback, useMemo } from "react";+import { useCallback } from "react";import useSWR from "swr";import { HeartPulse, RotateCw } from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";@@ -23,6 +23,7 @@ import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section"import { Button } from "@repowise-dev/ui/ui/button";import type { CodeHealthOverlay } from "@repowise-dev/ui/health";import { TriageTab } from "@/components/code-health/triage-tab";+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";@@ -30,21 +31,20 @@ import { DeadCodeTab } from "@/components/risk/dead-code-tab";import { ImpactTab } from "@/components/risk/impact-tab";import { SecurityTab } from "@/components/risk/security-tab";import {- getChurnComplexity,getHealthOverview,getHealthTrend,listHealthFiles,- type ChurnComplexityResponse,type HealthOverviewResponse,type HealthTrendResponse,type HealthFilesResponse,} from "@/lib/api/code-health";-const TABS = ["triage", "hotspots", "coverage", "dead-code", "impact", "security"] as const;+const TABS = ["triage", "findings", "hotspots", "coverage", "dead-code", "impact", "security"] as const;type TabId = (typeof TABS)[number];const TAB_LABELS: Record<TabId, string> = {- triage: "Triage",+ triage: "Overview",+ findings: "Findings",hotspots: "Hotspots",coverage: "Coverage","dead-code": "Dead code",@@ -64,12 +64,13 @@ const TAB_ALIASES: Record<string, TabId> = {};/**- * Lenses selectable on the map. Only the three backed by per-file map data are- * offered; an unrecognized `?lens=` (including the retired `dead-code`/- * `security` values, which now live solely on their own tabs) falls back to+ * 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.*/-const OVERLAYS: CodeHealthOverlay[] = ["health", "coverage", "churn"];+const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance"];export default function CodeHealthPage() {const params = useParams<{ id: string }>();@@ -113,35 +114,10 @@ export default function CodeHealthPage() {{ revalidateOnFocus: false },);- // Churn percentiles for the churn lens. Shares the SWR key the Hotspots tab- // already uses (`health-churn-complexity:`), so the two surfaces dedupe onto- // one request rather than double-fetching.- const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(- `health-churn-complexity:${repoId}`,- () => getChurnComplexity(repoId),- { revalidateOnFocus: false },- );-- // The churn lens recolors by `churn_percentile`, which arrives from a separate- // request. Until it resolves every node falls back to NEUTRAL_FILL — visually- // identical to "no data". Flag the in-flight state so the map shows a loading- // legend instead of a misleading empty one.- const overlayLoading = overlay === "churn" && churnLoading && !churn;-- // Merge churn_percentile onto each map file (join by path) so the churn lens- // colors real data. Re-runs only when either source changes.- const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {- if (!mapFiles) return undefined;- if (!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]);+ // 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.const setTab = useCallback((next: string) => {@@ -199,14 +175,14 @@ export default function CodeHealthPage() {trend={trend}overlay={overlay}onOverlayChange={setOverlay}- mapFiles={mapFilesWithChurn}- overlayLoading={overlayLoading}+ mapFiles={mapFiles}/><CollapsibleSection title="Health trend" defaultOpen={false}><TrendSection data={trend} isLoading={trendLoading} error={trendError} /></CollapsibleSection></div>)}+ {activeTab === "findings" && <FindingsTab repoId={repoId} />}{activeTab === "hotspots" && <HotspotsTab repoId={repoId} />}{activeTab === "coverage" && <CoverageTab repoId={repoId} />}{activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsxnew file mode 100644index 000000000..a1113fb78--- /dev/null+++ b/packages/web/src/components/code-health/findings-tab.tsx@@ -0,0 +1,49 @@+"use client";++/**+ * Findings host — binds the shared {@link FindingsView} (the fix-next queue,+ * performance risks, and function-level panels) to web's `/api` client,+ * `/repos/:id` routing, and the file-detail drawer. The composition itself+ * lives in `@repowise-dev/ui/health`; this file only injects the app-specific+ * pieces so web and hosted render the same view.+ */++import { useRouter } from "next/navigation";+import {+ FindingsView,+ type CodeHealthAdapter,+} from "@repowise-dev/ui/health";+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";+import {+ getHealthOverview,+ getRefactoringTargets,+ listHealthFiles,+ listHealthFindings,+ getHealthCoverage,+ updateFindingStatus,+} from "@/lib/api/code-health";+import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";++export function FindingsTab({ repoId: id }: { repoId: string }) {+ const router = useRouter();++ const prefix = `/repos/${id}`;+ const adapter: CodeHealthAdapter = {+ cacheKey: id,+ getOverview: (limit) => getHealthOverview(id, limit),+ listFindings: (opts) => listHealthFindings(id, opts),+ listFiles: (opts) => listHealthFiles(id, opts),+ getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),+ updateFindingStatus: (findingId, status) =>+ updateFindingStatus(id, findingId, status),+ getCoverage: (opts) => getHealthCoverage(id, opts),+ fileHref: (path) => fileEntityPath(prefix, path),+ symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),+ navigate: (href) => router.push(href),+ renderFileDrawer: ({ filePath, onClose }) => (+ <HealthFileDrawerHost repoId={id} filePath={filePath} onClose={onClose} />+ ),+ };++ return <FindingsView adapter={adapter} />;+}diff --git a/tests/unit/persistence/test_health_dimensions_crud.py b/tests/unit/persistence/test_health_dimensions_crud.pyindex 77f52158e..5f0839a7e 100644--- a/tests/unit/persistence/test_health_dimensions_crud.py+++ b/tests/unit/persistence/test_health_dimensions_crud.py@@ -119,3 +119,43 @@ async def test_save_health_findings_persists_dimension(async_session):by_type = {r.biomarker_type: r for r in rows}assert by_type["low_cohesion"].dimension == "maintainability"assert by_type["change_entropy"].dimension == "defect"+++async def test_get_health_findings_accepts_comma_separated_biomarker_types(async_session):+ """One request can pull several biomarker types (the panels batch this way);+ a single value with no comma still matches exactly."""+ repo = await insert_repo(async_session)+ findings = [+ HealthFindingData(+ biomarker_type=bt,+ severity=Severity.HIGH,+ file_path="a.py",+ function_name=None,+ line_start=1,+ line_end=10,+ details={},+ health_impact=1.0,+ dimension="defect",+ )+ for bt in ("function_hotspot", "code_age_volatility", "hidden_coupling", "change_entropy")+ ]+ await save_health_findings(async_session, repo.id, findings)+ await async_session.commit()++ multi = await get_health_findings(+ async_session,+ repo.id,+ biomarker_type="function_hotspot,code_age_volatility,hidden_coupling",+ )+ assert {r.biomarker_type for r in multi} == {+ "function_hotspot",+ "code_age_volatility",+ "hidden_coupling",+ }++ # Single value still behaves as an exact match.+ single = await get_health_findings(+ async_session, repo.id, biomarker_type="change_entropy"+ )+ assert {r.biomarker_type for r in single} == {"change_entropy"}