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.

fix(health): resolve code-health false-flag presentation (grouping, dominant cause, floor magnitude) (#700)

Swati Ahuja33fc3113ed6d
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 42fe2be02..22b4de9e4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -97,7 +97,28 @@ def _round_opt(v: Any) -> float | None:
return round(v, 2) if v is not None else None
-def _serialize_metric(m: HealthFileMetric) -> dict[str, Any]:
+def _leads_by_file(findings: list[Any]) -> dict[str, dict[str, Any]]:
+ """Reduce each file's findings to its dominant cause + pre-clamp magnitude.
+
+ ``primary_biomarker`` / ``primary_reason`` give a low file "the one reason"
+ to lead with; ``total_deduction`` (summed ``health_impact``) distinguishes
+ two files that both floor at 1.0. Additive — the score itself is untouched.
+ """
+ by_file: dict[str, list[Any]] = {}
+ for f in findings:
+ by_file.setdefault(f.file_path, []).append(f)
+ leads: dict[str, dict[str, Any]] = {}
+ for path, fs in by_file.items():
+ primary = max(fs, key=lambda x: x.health_impact)
+ leads[path] = {
+ "primary_biomarker": primary.biomarker_type,
+ "primary_reason": primary.reason,
+ "total_deduction": round(sum(float(x.health_impact or 0.0) for x in fs), 3),
+ }
+ return leads
+
+
+def _serialize_metric(m: HealthFileMetric, lead: dict[str, Any] | None = None) -> dict[str, Any]:
return {
"file_path": m.file_path,
"score": round(m.score, 2),
@@ -114,6 +135,12 @@ def _serialize_metric(m: HealthFileMetric) -> dict[str, Any]:
"defect_score": _round_opt(getattr(m, "defect_score", None)),
"maintainability_score": _round_opt(getattr(m, "maintainability_score", None)),
"performance_score": _round_opt(getattr(m, "performance_score", None)),
+ # Dominant-cause lead + pre-clamp magnitude (null when no findings for
+ # this row). Lets a caller lead with the one reason and rank two floored
+ # files by depth without re-reading every finding.
+ "primary_biomarker": lead.get("primary_biomarker") if lead else None,
+ "primary_reason": lead.get("primary_reason") if lead else None,
+ "total_deduction": lead.get("total_deduction") if lead else None,
}
@@ -386,11 +413,14 @@ async def get_health(
snapshots = await list_health_snapshots(session, repository.id, limit=20)
kpis = _compute_kpis(metric_rows if effective_targets else all_metrics)
+ # Dominant-cause lead per file, from the findings already loaded (targeted
+ # findings are scoped to the targets; dashboard findings cover every file).
+ leads = _leads_by_file(finding_rows)
if effective_targets:
metric_payload: list[dict[str, Any]] = []
for m in metric_rows:
- row = _serialize_metric(m)
+ row = _serialize_metric(m, leads.get(m.file_path))
if m.file_path in signals_by_path:
row["signals"] = signals_by_path[m.file_path]
metric_payload.append(row)
@@ -429,7 +459,7 @@ async def get_health(
"mode": "dashboard",
"kpis": kpis,
"distribution": health_distribution(all_metrics),
- "worst_files": [_serialize_metric(m) for m in metric_rows[:limit]],
+ "worst_files": [_serialize_metric(m, leads.get(m.file_path)) for m in metric_rows[:limit]],
"top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],
"modules": _module_rollups(all_metrics),
}
diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.py
index 560953e10..2216c81f1 100644
--- a/packages/server/src/repowise/server/routers/code_health.py
+++ b/packages/server/src/repowise/server/routers/code_health.py
@@ -79,7 +79,40 @@ def _round_opt(v: Any) -> float | None:
return round(v, 2) if v is not None else None
-def _metric_to_dict(m: Any) -> dict:
+def _primary_and_magnitude(findings: list[Any]) -> dict:
+ """Dominant cause + pre-clamp deduction magnitude for one file's findings.
+
+ Two presentation signals the score alone can't carry:
+
+ - ``primary_biomarker`` / ``primary_reason`` — the single worst finding, so a
+ low file can lead with "the one reason" instead of a wall of markers.
+ - ``total_deduction`` — the summed (pre-floor) ``health_impact``. Equal to
+ the breakdown endpoint's ``total_deduction`` (each finding's stored impact
+ is already the applied, capped value), so it distinguishes two files that
+ both floor at 1.0 (a -25 file from a -9 one) without touching ``score``.
+
+ All-null on an empty list: a clean file has no lead and no magnitude.
+ """
+ if not findings:
+ return {"primary_biomarker": None, "primary_reason": None, "total_deduction": None}
+ primary = max(findings, key=lambda x: x.health_impact)
+ total = sum(float(x.health_impact or 0.0) for x in findings)
+ return {
+ "primary_biomarker": primary.biomarker_type,
+ "primary_reason": primary.reason,
+ "total_deduction": round(total, 3),
+ }
+
+
+def _leads_by_file(findings: list[Any]) -> dict[str, dict]:
+ """Group findings by file and reduce each group to its dominant-cause lead."""
+ by_file: dict[str, list[Any]] = {}
+ for f in findings:
+ by_file.setdefault(f.file_path, []).append(f)
+ return {path: _primary_and_magnitude(fs) for path, fs in by_file.items()}
+
+
+def _metric_to_dict(m: Any, lead: dict | None = None) -> dict:
return {
"file_path": m.file_path,
"score": round(m.score, 2),
@@ -96,6 +129,11 @@ def _metric_to_dict(m: Any) -> dict:
"defect_score": _round_opt(getattr(m, "defect_score", None)),
"maintainability_score": _round_opt(getattr(m, "maintainability_score", None)),
"performance_score": _round_opt(getattr(m, "performance_score", None)),
+ # Dominant-cause lead + pre-clamp magnitude (null when findings weren't
+ # loaded for this row, or the file is clean). Additive; readers degrade.
+ "primary_biomarker": lead.get("primary_biomarker") if lead else None,
+ "primary_reason": lead.get("primary_reason") if lead else None,
+ "total_deduction": lead.get("total_deduction") if lead else None,
}
@@ -317,7 +355,8 @@ async def health_overview(
last_indexed_at = _resolve_last_indexed_at(snapshot_taken_at, repo.updated_at)
- metric_dicts = [_metric_to_dict(m) for m in metrics]
+ leads = _leads_by_file(findings)
+ metric_dicts = [_metric_to_dict(m, leads.get(m.file_path)) for m in metrics]
# Repo-level band (from the NLOC-weighted average) + the per-band file
# distribution. Both derive purely from the existing score — no new data.
@@ -564,11 +603,16 @@ async def list_health_files(
total = len(filtered)
page = filtered[offset : offset + limit]
+ # Leads only for the page's files — enough to carry the top-reason chip and
+ # the magnitude tiebreak without loading every finding for every row.
+ page_paths = {m.file_path for m in page}
+ findings = await crud.get_health_findings(session, repo_id)
+ leads = _leads_by_file([f for f in findings if f.file_path in page_paths])
return {
"total": total,
"offset": offset,
"limit": limit,
- "files": [_metric_to_dict(m) for m in page],
+ "files": [_metric_to_dict(m, leads.get(m.file_path)) for m in page],
}
@@ -685,7 +729,7 @@ async def file_score_breakdown(
snapshots = await crud.list_health_snapshots(session, repo_id)
return {
"file_path": file_path,
- "metric": _metric_to_dict(metric) if metric else None,
+ "metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,
"breakdown": breakdown,
"findings": finding_dicts,
"suggestions": {b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}},
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index b7966d8b2..eee24e5bb 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -30,6 +30,7 @@ from repowise.server.routers.code_health import (
_file_trend_to_dict,
_finding_to_dict,
_metric_to_dict,
+ _primary_and_magnitude,
_score_breakdown_from_findings,
)
from repowise.server.routers.git import _hotspot_from_row
@@ -225,7 +226,7 @@ async def file_detail(
findings = await crud.get_health_findings(session, repo_id, file_path=file_path)
snapshots = await crud.list_health_snapshots(session, repo_id)
health = {
- "metric": _metric_to_dict(metric) if metric else None,
+ "metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,
"breakdown": _score_breakdown_from_findings(findings) if findings else None,
"findings": [_finding_to_dict(f) for f in findings],
"trend": _file_trend_to_dict(file_trend(snapshots, file_path)),
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index f5548008e..4ba9a37ad 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -57,6 +57,15 @@ export interface FileHealthMetric {
defect_score?: number | null;
maintainability_score?: number | null;
performance_score?: number | null;
+ /**
+ * Dominant-cause lead (worst finding's biomarker + reason) and the summed
+ * pre-floor `health_impact`. Additive display signals: the lead headlines the
+ * "one reason", `total_deduction` ranks two files that both floor at `1.0`.
+ * Null on clean files or payloads that predate these fields.
+ */
+ primary_biomarker?: string | null;
+ primary_reason?: string | null;
+ total_deduction?: number | null;
}
export interface FileScoreBreakdownFinding {
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index f29a9c2b8..ebcb1d929 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -178,6 +178,20 @@ export interface HealthFileMetric {
defect_score?: number | null;
maintainability_score?: number | null;
performance_score?: number | null;
+ /**
+ * Dominant-cause lead: the biomarker + reason of this file's worst finding, so
+ * a low file can headline "the one reason" instead of a wall of markers. Null
+ * when the row carries no findings or the payload predates this field.
+ */
+ primary_biomarker?: string | null;
+ primary_reason?: string | null;
+ /**
+ * Summed (pre-floor) `health_impact` across the file's findings — the score's
+ * deduction magnitude. Distinguishes two files that both clamp to `1.0` (a −25
+ * from a −9) so they can be ranked by depth. The calibrated `score` is
+ * unchanged; this is a display-only secondary distinguisher.
+ */
+ total_deduction?: number | null;
}
export interface HealthFinding {
diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsx
new file mode 100644
index 000000000..8bd754f88
--- /dev/null
+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx
@@ -0,0 +1,72 @@
+import { describe, it, expect } from "vitest";
+import { render, screen, within } from "@testing-library/react";
+import {
+ HealthFileDrawer,
+ type HealthDrawerFinding,
+ type HealthDrawerMetric,
+} from "../../src/health/health-file-drawer.js";
+
+function metric(partial: Partial<HealthDrawerMetric> = {}): HealthDrawerMetric {
+ return {
+ file_path: "packages/cli/doctor_cmd.py",
+ score: 1.0,
+ max_ccn: 40,
+ max_nesting: 6,
+ nloc: 800,
+ module: "cli",
+ has_test_file: false,
+ ...partial,
+ };
+}
+
+let seq = 0;
+function finding(partial: Partial<HealthDrawerFinding> = {}): HealthDrawerFinding {
+ seq += 1;
+ return {
+ id: `f${seq}`,
+ biomarker_type: "brain_method",
+ severity: "high",
+ function_name: "_run_repo_checks",
+ line_start: 120,
+ line_end: 487,
+ health_impact: 1.5,
+ reason: "Oversized, deeply-nested function.",
+ ...partial,
+ };
+}
+
+describe("HealthFileDrawer finding grouping", () => {
+ it("collapses many markers on one function into a single group header", () => {
+ const findings: HealthDrawerFinding[] = [
+ finding({ biomarker_type: "brain_method", health_impact: 3.0 }),
+ finding({ biomarker_type: "long_method", health_impact: 2.0 }),
+ finding({ biomarker_type: "deep_nesting", health_impact: 1.0 }),
+ ];
+ render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ );
+
+ // One group header names the function + its worst marker, and sums impact.
+ const header = screen.getByRole("button", { name: /_run_repo_checks/ });
+ expect(within(header).getByText(/3 markers/)).toBeInTheDocument();
+ expect(within(header).getByText(/−6\.00/)).toBeInTheDocument();
+ });
+
+ it("keeps file-level markers (no function) in their own group", () => {
+ const findings: HealthDrawerFinding[] = [
+ finding({ function_name: "_run_repo_checks", health_impact: 5.0 }),
+ finding({
+ biomarker_type: "change_entropy",
+ function_name: null,
+ line_start: null,
+ health_impact: 2.0,
+ reason: "File changes touch many unrelated concerns.",
+ }),
+ ];
+ render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ );
+ expect(screen.getByText("File-level signals")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /_run_repo_checks/ })).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/file-table.tsx b/packages/ui/src/health/file-table.tsx
index adce687ae..ba2734f9d 100644
--- a/packages/ui/src/health/file-table.tsx
+++ b/packages/ui/src/health/file-table.tsx
@@ -1,11 +1,13 @@
"use client";
+import { useMemo } from "react";
import { FileText } from "lucide-react";
import { EmptyState } from "../shared/empty-state";
import {
ResponsiveTable,
type ResponsiveColumn,
} from "../shared/responsive-table";
+import { biomarkerLabel } from "./biomarker-glossary";
import { scoreBadgeClass } from "./tokens";
export interface HealthFileRow {
@@ -18,6 +20,11 @@ export interface HealthFileRow {
line_coverage_pct?: number | null;
module?: string | null;
duplication_pct?: number | null;
+ /** Dominant-cause lead: the worst finding's biomarker + reason (P3). */
+ primary_biomarker?: string | null;
+ primary_reason?: string | null;
+ /** Summed pre-floor `health_impact` — the depth behind a floored score (P1). */
+ total_deduction?: number | null;
}
export type FileSortField =
@@ -56,19 +63,44 @@ export function HealthFileTable({
selectedPath,
emptyMessage,
}: HealthFileTableProps) {
+ // When sorting by score, two floored files both read 1.0; break that tie by
+ // deduction magnitude so the deeper problem sorts first (server sorts by
+ // score only, so this is a within-page refinement — P1).
+ const rows = useMemo(() => {
+ if (sortField !== "score") return files;
+ const dir = sortOrder === "desc" ? -1 : 1;
+ return [...files].sort((a, b) => {
+ if (a.score !== b.score) return (a.score - b.score) * dir;
+ return (b.total_deduction ?? 0) - (a.total_deduction ?? 0);
+ });
+ }, [files, sortField, sortOrder]);
+
const columns: ResponsiveColumn<HealthFileRow>[] = [
{
key: "file_path",
header: "File",
priority: 1,
sortable: true,
- cellClassName: "text-[var(--color-text-primary)] font-mono text-xs max-w-[440px]",
+ cellClassName: "text-[var(--color-text-primary)] max-w-[440px]",
render: (f) => (
- <span className="flex items-center gap-1.5 min-w-0">
- <FileText className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
- <span className="truncate" title={f.file_path}>
- {f.file_path}
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="flex items-center gap-1.5 min-w-0 font-mono text-xs">
+ <FileText className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span className="truncate" title={f.file_path}>
+ {f.file_path}
+ </span>
</span>
+ {f.primary_biomarker ? (
+ <span
+ className="truncate pl-[18px] text-[11px] text-[var(--color-text-tertiary)]"
+ title={f.primary_reason ?? undefined}
+ >
+ <span className="font-medium text-[var(--color-text-secondary)]">
+ {biomarkerLabel(f.primary_biomarker)}
+ </span>
+ {f.primary_reason ? ` — ${f.primary_reason}` : ""}
+ </span>
+ ) : null}
</span>
),
},
@@ -79,10 +111,22 @@ export function HealthFileTable({
priority: 1,
sortable: true,
render: (f) => (
- <span
- className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}
- >
- {f.score.toFixed(1)}
+ <span className="inline-flex flex-col items-end gap-0.5">
+ <span
+ className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}
+ >
+ {f.score.toFixed(1)}
+ </span>
+ {/* Depth behind a floored score: two files that both print 1.0 are
+ distinguishable by their summed deductions (P1 false-flag fix). */}
+ {f.score <= 1 && f.total_deduction != null ? (
+ <span
+ className="text-[10px] tabular-nums text-[var(--color-error)]"
+ title="Total deductions behind this floored score"
+ >
+ −{f.total_deduction.toFixed(1)}
+ </span>
+ ) : null}
</span>
),
},
@@ -150,7 +194,7 @@ export function HealthFileTable({
return (
<ResponsiveTable
columns={columns}
- rows={files}
+ rows={rows}
rowKey={(f) => f.file_path}
onRowClick={onSelect}
selectedKey={selectedPath ?? null}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 17fdc1092..d693a5a44 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { ExternalLink } from "lucide-react";
+import { ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
import { AdaptivePanel } from "../shared/adaptive-panel";
import { InfoTip } from "../shared/info-tip";
import {
@@ -56,6 +56,10 @@ export interface HealthDrawerMetric {
defect_score?: number | null;
maintainability_score?: number | null;
performance_score?: number | null;
+ /** Dominant-cause lead + pre-clamp deduction magnitude (null when absent). */
+ primary_biomarker?: string | null;
+ primary_reason?: string | null;
+ total_deduction?: number | null;
}
export interface HealthFileDrawerProps {
@@ -122,6 +126,144 @@ export function HealthFileDrawer({
setSavingId(null);
}
};
+
+ // A single finding row. Rendered inside a function group; kept as a closure
+ // (not a component) so it reads the drawer's triage state without threading
+ // it through props on every collapsible group.
+ const renderFinding = (f: HealthDrawerFinding) => {
+ const info = biomarkerInfo(f.biomarker_type);
+ return (
+ <li
+ key={f.id}
+ 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]}`}>
+ {SEVERITY_LABEL[f.severity]}
+ </span>
+ <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
+ {biomarkerLabel(f.biomarker_type)}
+ {info.description ? (
+ <InfoTip
+ content={info.description}
+ label={`About ${biomarkerLabel(f.biomarker_type)}`}
+ />
+ ) : null}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {CATEGORY_LABEL[info.category]}
+ </span>
+ {(() => {
+ const dim =
+ f.dimension === "maintainability" ||
+ f.dimension === "defect" ||
+ f.dimension === "performance"
+ ? f.dimension
+ : biomarkerDimension(f.biomarker_type);
+ return (
+ <span
+ className={`inline-flex items-center rounded px-1.5 py-px text-[10px] font-medium ${DIMENSION_CHIP[dim]}`}
+ title={`${DIMENSION_LABEL[dim]} pillar`}
+ >
+ {DIMENSION_LABEL[dim]}
+ </span>
+ );
+ })()}
+ {f.function_name ? (() => {
+ const label = `${f.function_name}${f.line_start ? `:${f.line_start}` : ""}`;
+ const lineHref =
+ f.line_start != null && fileViewHrefFor
+ ? fileViewHrefFor(f.line_start)
+ : f.line_start != null
+ ? fileViewHref
+ : undefined;
+ return lineHref ? (
+ <a
+ href={lineHref}
+ className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline"
+ >
+ {label}
+ </a>
+ ) : (
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
+ {label}
+ </span>
+ );
+ })() : null}
+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">−{f.health_impact.toFixed(2)}</span>
+ </div>
+ <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
+ <BiomarkerDetails
+ biomarkerType={f.biomarker_type}
+ details={f.details}
+ onPartnerSelect={onPartnerSelect}
+ onPartnerHref={onPartnerHref}
+ />
+ {suggestions[f.biomarker_type] ? (
+ <p className="text-xs text-[var(--color-text-tertiary)] italic">
+ {suggestions[f.biomarker_type]}
+ </p>
+ ) : null}
+ {onFindingStatusChange ? (
+ <div className="flex flex-wrap items-center gap-1.5 pt-1">
+ {TRIAGE_STATUSES.map((opt) => {
+ const current = statusOverride[f.id] ?? f.status ?? "open";
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ disabled={savingId === f.id || current === opt.value}
+ onClick={() => setStatus(f.id, opt.value)}
+ className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
+ current === opt.value
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ }`}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+ </li>
+ );
+ };
+
+ // Group findings by the function they fire on so one oversized function reads
+ // as a single collapsible group instead of N sibling rows. File-level markers
+ // (no function_name — co_change_scatter, change_entropy, …) collect into one
+ // "File-level signals" group. Sections sort by summed impact so the dominant
+ // cause leads; the worst section starts expanded.
+ const findingSections = (() => {
+ const groups = new Map<string, HealthDrawerFinding[]>();
+ for (const f of findings) {
+ 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 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 };
+ })
+ .sort((a, b) => b.total - a.total);
+ })();
+
+ // The one reason this file scores low: prefer the server lead, else the
+ // worst finding. Rendered as a headline so the "why" leads (P3).
+ const primaryLead = (() => {
+ if (metric?.primary_biomarker) {
+ return { biomarker: metric.primary_biomarker, reason: metric.primary_reason ?? null };
+ }
+ if (findings.length === 0) return null;
+ const worst = findings.reduce((a, b) => (b.health_impact > a.health_impact ? b : a));
+ return { biomarker: worst.biomarker_type, reason: worst.reason };
+ })();
+
return (
<AdaptivePanel
open={open}
@@ -151,6 +293,20 @@ export function HealthFileDrawer({
</div>
) : (
<>
+ {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}
+ </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)}`}>
@@ -250,107 +406,24 @@ export function HealthFileDrawer({
<h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
All findings ({findings.length})
</h3>
- <ul className="space-y-2">
- {findings.map((f) => {
- const info = biomarkerInfo(f.biomarker_type);
- return (
- <li
- key={f.id}
- 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]}`}>
- {SEVERITY_LABEL[f.severity]}
- </span>
- <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
- {biomarkerLabel(f.biomarker_type)}
- {info.description ? (
- <InfoTip
- content={info.description}
- label={`About ${biomarkerLabel(f.biomarker_type)}`}
- />
- ) : null}
- </span>
- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {CATEGORY_LABEL[info.category]}
- </span>
- {(() => {
- const dim =
- f.dimension === "maintainability" ||
- f.dimension === "defect" ||
- f.dimension === "performance"
- ? f.dimension
- : biomarkerDimension(f.biomarker_type);
- return (
- <span
- className={`inline-flex items-center rounded px-1.5 py-px text-[10px] font-medium ${DIMENSION_CHIP[dim]}`}
- title={`${DIMENSION_LABEL[dim]} pillar`}
- >
- {DIMENSION_LABEL[dim]}
- </span>
- );
- })()}
- {f.function_name ? (() => {
- const label = `${f.function_name}${f.line_start ? `:${f.line_start}` : ""}`;
- const lineHref =
- f.line_start != null && fileViewHrefFor
- ? fileViewHrefFor(f.line_start)
- : f.line_start != null
- ? fileViewHref
- : undefined;
- return lineHref ? (
- <a
- href={lineHref}
- className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline"
- >
- {label}
- </a>
- ) : (
- <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
- {label}
- </span>
- );
- })() : null}
- <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">−{f.health_impact.toFixed(2)}</span>
- </div>
- <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
- <BiomarkerDetails
- biomarkerType={f.biomarker_type}
- details={f.details}
- onPartnerSelect={onPartnerSelect}
- onPartnerHref={onPartnerHref}
- />
- {suggestions[f.biomarker_type] ? (
- <p className="text-xs text-[var(--color-text-tertiary)] italic">
- {suggestions[f.biomarker_type]}
- </p>
- ) : null}
- {onFindingStatusChange ? (
- <div className="flex flex-wrap items-center gap-1.5 pt-1">
- {TRIAGE_STATUSES.map((opt) => {
- const current = statusOverride[f.id] ?? f.status ?? "open";
- return (
- <button
- key={opt.value}
- type="button"
- disabled={savingId === f.id || current === opt.value}
- onClick={() => setStatus(f.id, opt.value)}
- className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
- current === opt.value
- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
- }`}
- >
- {opt.label}
- </button>
- );
- })}
- </div>
- ) : null}
- </li>
- );
- })}
- </ul>
+ <div className="space-y-2">
+ {findingSections.map((s) => (
+ <FunctionFindingsGroup
+ key={s.key}
+ isFile={s.isFile}
+ functionName={s.isFile ? null : s.key}
+ findings={s.group}
+ total={s.total}
+ 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.
+ defaultExpanded={s.group.length === 1}
+ renderFinding={renderFinding}
+ />
+ ))}
+ </div>
</section>
) : null}
</>
@@ -360,6 +433,79 @@ export function HealthFileDrawer({
);
}
+/**
+ * One collapsible group of findings that fire on the same function (or the
+ * "File-level signals" bucket when they have no function). The header names the
+ * function plus its worst marker so a 7-marker oversized function reads as one
+ * row, not seven — the P2 "looks padded" fix. Single-finding groups render
+ * expanded; the caller expands the highest-impact group by default.
+ */
+function FunctionFindingsGroup({
+ isFile,
+ functionName,
+ findings,
+ total,
+ worst,
+ defaultExpanded,
+ renderFinding,
+}: {
+ isFile: boolean;
+ functionName: string | null;
+ findings: HealthDrawerFinding[];
+ total: number;
+ worst: HealthDrawerFinding;
+ defaultExpanded: boolean;
+ renderFinding: (f: HealthDrawerFinding) => React.ReactNode;
+}) {
+ const [expanded, setExpanded] = useState(defaultExpanded);
+ 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
+ role="button"
+ tabIndex={0}
+ onClick={toggle}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ toggle();
+ }
+ }}
+ 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)]"
+ >
+ {expanded ? (
+ <ChevronDown className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />
+ )}
+ {isFile ? (
+ <span className="text-sm font-medium text-[var(--color-text-primary)]">
+ File-level signals
+ </span>
+ ) : (
+ <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>
+ )}
+ <span className="ml-auto inline-flex shrink-0 items-center gap-2 text-xs tabular-nums">
+ <span className="text-[var(--color-text-tertiary)]">
+ {findings.length} {findings.length === 1 ? "marker" : "markers"}
+ </span>
+ <span className="text-[var(--color-error)]">−{total.toFixed(2)}</span>
+ </span>
+ </div>
+ {expanded ? (
+ <ul className="space-y-2 border-t border-[var(--color-border-default)] p-2">
+ {findings.map((f) => renderFinding(f))}
+ </ul>
+ ) : null}
+ </div>
+ );
+}
+
function Stat({ label, value }: { label: string; value: React.ReactNode }) {
return (
<div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index d51e84d09..ed270cc54 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -73,3 +73,22 @@ async def test_get_health_targeted(setup_mcp, health_data):
assert result["metrics"][0]["maintainability_score"] == 6.0
assert result["metrics"][0]["performance_score"] == 9.0
assert all(f["file_path"] == "src/auth/service.py" for f in result["findings"])
+
+
+async def test_get_health_metric_carries_dominant_cause_and_magnitude(setup_mcp, health_data):
+ """Metric rows lead with the worst finding + the pre-floor deduction sum."""
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(targets=["src/auth/service.py"])
+ metric = result["metrics"][0]
+ # Worst of {complex_method 1.2, nested 0.7, low_cohesion 1.0, io_in_loop 1.0}.
+ assert metric["primary_biomarker"] == "complex_method"
+ assert metric["primary_reason"] == "authenticate has cyclomatic complexity 15"
+ # Σ health_impact = 1.2 + 0.7 + 1.0 + 1.0 — the depth behind a floored score.
+ assert metric["total_deduction"] == pytest.approx(3.9)
+ # Same lead reaches dashboard worst_files.
+ dash = await get_health()
+ worst = next(m for m in dash["worst_files"] if m["file_path"] == "src/auth/service.py")
+ assert worst["primary_biomarker"] == "complex_method"
+ assert worst["total_deduction"] == pytest.approx(3.9)
diff --git a/tests/unit/server/test_health_breakdown.py b/tests/unit/server/test_health_breakdown.py
index cda6907c3..f9fbfdb3e 100644
--- a/tests/unit/server/test_health_breakdown.py
+++ b/tests/unit/server/test_health_breakdown.py
@@ -14,22 +14,61 @@ from repowise.core.analysis.health.models import Severity
from repowise.core.analysis.health.scoring import biomarker_weight, severity_deduction
from repowise.server.routers.code_health import (
_finding_base_deduction,
+ _leads_by_file,
+ _primary_and_magnitude,
_score_breakdown_from_findings,
)
-def _finding(biomarker_type, severity, health_impact, *, details=None, fid="x"):
+def _finding(
+ biomarker_type, severity, health_impact, *, details=None, fid="x", reason="", file_path="f.py"
+):
return SimpleNamespace(
id=fid,
+ file_path=file_path,
biomarker_type=biomarker_type,
severity=severity,
health_impact=health_impact,
function_name=None,
- reason="",
+ reason=reason,
details=details or {},
)
+def test_primary_and_magnitude_picks_worst_and_sums_impact() -> None:
+ findings = [
+ _finding("complex_method", Severity.HIGH, 0.8, reason="ccn 15", fid="a"),
+ _finding("god_object", Severity.CRITICAL, 3.5, reason="1200-line class", fid="b"),
+ _finding("deep_nesting", Severity.MEDIUM, 0.7, reason="nests 6 deep", fid="c"),
+ ]
+ lead = _primary_and_magnitude(findings)
+ # Dominant cause = the single worst finding, not the first one.
+ assert lead["primary_biomarker"] == "god_object"
+ assert lead["primary_reason"] == "1200-line class"
+ # Magnitude = summed (pre-floor) impact = 0.8 + 3.5 + 0.7.
+ assert abs(lead["total_deduction"] - 5.0) < 1e-6
+
+
+def test_primary_and_magnitude_empty_is_all_null() -> None:
+ assert _primary_and_magnitude([]) == {
+ "primary_biomarker": None,
+ "primary_reason": None,
+ "total_deduction": None,
+ }
+
+
+def test_leads_by_file_groups_per_path() -> None:
+ findings = [
+ _finding("complex_method", Severity.HIGH, 1.0, fid="a", file_path="a.py"),
+ _finding("god_object", Severity.CRITICAL, 4.0, fid="b", file_path="b.py"),
+ _finding("deep_nesting", Severity.LOW, 0.5, fid="c", file_path="b.py"),
+ ]
+ leads = _leads_by_file(findings)
+ assert leads["a.py"]["primary_biomarker"] == "complex_method"
+ assert leads["b.py"]["primary_biomarker"] == "god_object"
+ assert abs(leads["b.py"]["total_deduction"] - 4.5) < 1e-6
+
+
def test_base_deduction_prefers_continuous_override() -> None:
# coverage_gradient records its continuous base in details["deduction"].
f = _finding("coverage_gradient", Severity.MEDIUM, 1.2, details={"deduction": 1.6})