Skip to content

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

feat(health): surface maintainability as a second health signal (#531)

Raghav Chamadiya764d4f40ba9a
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 33f8c3482..9993997a0 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -69,6 +69,57 @@ The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:
- **Average Health** — NLOC-weighted average over all files.
- **Worst Performer** — single lowest-scoring file.
+## Two health signals: defect risk and maintainability
+
+The score above is the **defect-risk** signal: it is calibrated against a defect
+corpus, the bands are calibrated to it (Alert files carry ~17x the defect rate
+of Healthy files), and it is the overall number surfaced everywhere. But not
+every code smell predicts bugs. A handful of biomarkers fire widely and matter a
+lot for how hard code is to read and change, yet proved weak as defect
+predictors under leakage-free scoring, so the defect calibration floors them to
+0.5 (`low_cohesion`, `brain_method`, `primitive_obsession`, `dry_violation`,
+`error_handling`). Floored inside a defect-framed score they do two unhelpful
+things at once: they still nudge the number a little (noise against the
+calibrated signal) and they get no credit for the real problem they describe
+(maintainability).
+
+Repowise therefore computes a second, parallel signal, **maintainability**, from
+the same biomarker stream:
+
+- The floored smells above deduct at **full weight (1.0)** in maintainability
+ instead of the 0.5 the defect calibration imposes. The defect calibration does
+ not apply to a non-defect signal, so the maintainability weights are expert-set
+ and tuned only against the maintainability pillar's own per-category caps.
+- The structural smells that are genuine defect predictors **and** core
+ maintainability concerns (`god_class`, `large_method`, `nested_complexity`)
+ count toward **both** dimensions.
+- Pure defect/organizational predictors (`change_entropy`, `ownership_risk`,
+ `co_change_scatter`, ...) stay out of maintainability entirely.
+
+The two signals are computed by the single shared scoring kernel
+(`scoring.score_file`) against independent weight/category/cap tables, and they
+**never feed back into each other**. The overall, surfaced score remains exactly
+the defect score (byte-for-byte; a golden test locks this) until a later,
+deliberate decision to blend. Maintainability is surfaced alongside it as a
+co-equal headline:
+
+- **REST/overview**: `summary.maintainability_average` plus a per-file
+ `maintainability_score` on every metric row.
+- **MCP `get_health`**: `kpis.maintainability_average` and per-file
+ `defect_score` / `maintainability_score` / `performance_score`.
+- **CLAUDE.md** and the CLI `status` line print a maintainability headline next
+ to defect-risk health.
+- Every finding carries a `dimension` (`defect` / `maintainability` /
+ `performance`) naming the pillar it homes under, so findings can be filtered
+ per signal.
+
+A third dimension, **performance**, is computed by the same machinery but is not
+yet surfaced as its own pillar in the dashboard, MCP KPIs, or CLAUDE.md (that
+arrives in a later release); its per-file `performance_score` reads `null` on
+indexes built before the performance detectors landed. The dimension names are
+mirrored in `@repowise-dev/types` (`HEALTH_DIMENSIONS`) with a parity test on
+each side.
+
## Bands and distribution
On top of the 1–10 number, every score falls into one of three **bands**. These
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index dc546039b..c9642216a 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -191,11 +191,16 @@ def _query_health_line(repo_path: Path) -> str | None:
band = band_for(float(data["average_health"]))
band_color = {"healthy": "green", "warning": "yellow", "alert": "red"}[band]
+ # Maintainability is a co-surfaced second pillar; show it when the split has
+ # populated it (None on indexes that predate the split).
+ maint = data.get("maintainability_average")
+ maint_part = f" · {maint:.1f} (maintainability)" if maint is not None else ""
return (
f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) "
f"[[{band_color}]{BAND_LABEL[band]}[/{band_color}]] · "
f"{data['hotspot_health']:.1f} (hotspots) · "
f"{worst_repr} (worst: {worst_path})"
+ f"{maint_part}"
)
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 98b5895da..724453c8c 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -484,6 +484,22 @@ def attach_impacts(
return out
+def _wavg_attr(rows: list[HealthFileMetricData], attr: str) -> float | None:
+ """NLOC-weighted average of one metric attribute, skipping ``None`` values.
+
+ Returns ``None`` when no row carries the attribute (e.g. a repo whose
+ ``maintainability_score`` predates the split) so the KPI reads "not measured"
+ rather than a misleading perfect 10.0.
+ """
+ scored = [r for r in rows if getattr(r, attr, None) is not None]
+ if not scored:
+ return None
+ total_w = sum(max(r.nloc, 1) for r in scored)
+ if total_w == 0:
+ return sum(getattr(r, attr) for r in scored) / len(scored)
+ return sum(getattr(r, attr) * max(r.nloc, 1) for r in scored) / total_w
+
+
def compute_kpis(
metrics: list[HealthFileMetricData],
hotspot_paths: set[str],
@@ -493,6 +509,10 @@ def compute_kpis(
- ``hotspot_health``: NLOC-weighted average over files in *hotspot_paths*.
- ``average_health``: NLOC-weighted average over all files.
- ``worst_performer``: lowest-scoring file + score.
+ - ``maintainability_average`` / ``maintainability_hotspot``: the same two
+ NLOC-weighted averages over the per-file ``maintainability_score``, so the
+ maintainability pillar surfaces a repo headline alongside the defect one.
+ ``None`` when no file carries a maintainability score.
"""
if not metrics:
return {
@@ -501,6 +521,8 @@ def compute_kpis(
"worst_performer_path": None,
"worst_performer_score": None,
"file_count": 0,
+ "maintainability_average": None,
+ "maintainability_hotspot": None,
}
def _wavg(rows: list[HealthFileMetricData]) -> float:
@@ -513,10 +535,14 @@ def compute_kpis(
hotspots = [m for m in metrics if m.file_path in hotspot_paths]
worst = min(metrics, key=lambda m: m.score)
+ maint_avg = _wavg_attr(metrics, "maintainability_score")
+ maint_hotspot = _wavg_attr(hotspots, "maintainability_score")
return {
"hotspot_health": round(_wavg(hotspots), 2),
"average_health": round(_wavg(metrics), 2),
"worst_performer_path": worst.file_path,
"worst_performer_score": round(worst.score, 2),
"file_count": len(metrics),
+ "maintainability_average": round(maint_avg, 2) if maint_avg is not None else None,
+ "maintainability_hotspot": round(maint_hotspot, 2) if maint_hotspot is not None else None,
}
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 633946605..6bc958a2d 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -50,6 +50,10 @@ class CodeHealthBlock:
worst_score: float
worst_path: str
hotspot_trend: str = "stable"
+ # Maintainability pillar headline (NLOC-weighted average over the per-file
+ # maintainability scores). ``None`` until the split populates the column, so
+ # the section omits it rather than printing a misleading 10.0.
+ maintainability_average: float | None = None
critical_biomarkers: list[dict] = field(default_factory=list)
untested_hotspots: list[dict] = field(default_factory=list)
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index eb2313080..e714db41b 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -284,6 +284,19 @@ class EditorFileDataFetcher:
else:
hotspot_health = avg
+ # Maintainability pillar headline: NLOC-weighted over the per-file
+ # maintainability scores, skipping rows that predate the split. ``None``
+ # when unmeasured so the section omits the line rather than printing 10.0.
+ maint_rows = [m for m in metric_rows if getattr(m, "maintainability_score", None) is not None]
+ maintainability_average: float | None = None
+ if maint_rows:
+ m_nloc = sum(max(m.nloc, 1) for m in maint_rows)
+ maintainability_average = (
+ sum(m.maintainability_score * max(m.nloc, 1) for m in maint_rows) / m_nloc
+ if m_nloc
+ else sum(m.maintainability_score for m in maint_rows) / len(maint_rows)
+ )
+
# Critical biomarkers: brain methods, or critical-severity findings
# in hotspot files. Cap at 5 to keep CLAUDE.md tight.
f_res = await self._session.execute(
@@ -317,6 +330,9 @@ class EditorFileDataFetcher:
worst_score=round(worst.score, 2),
worst_path=worst.file_path,
hotspot_trend="stable",
+ maintainability_average=(
+ round(maintainability_average, 2) if maintainability_average is not None else None
+ ),
critical_biomarkers=critical,
untested_hotspots=[], # Phase 2 fills this from coverage data
)
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index 3f919b7ee..d57371d71 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -78,9 +78,14 @@ Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.
{% if data.code_health %}
## Code health
-Hotspot health: {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}) ·
+Two signals: **defect risk** (the overall score) and **maintainability** (a separate pillar of the smells that hurt readability/change-cost without predicting bugs). See `docs/CODE_HEALTH.md`.
+
+Defect risk, Hotspot health: {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}) ·
Average: {{ data.code_health.average_health }}/10 ·
Worst: {{ data.code_health.worst_score }}/10 (`{{ data.code_health.worst_path }}`)
+{% if data.code_health.maintainability_average is not none %}
+Maintainability, Average: {{ data.code_health.maintainability_average }}/10
+{% endif %}
{% if data.code_health.critical_biomarkers %}
### Critical biomarkers
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.py
index f91256809..495340274 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py
@@ -471,6 +471,7 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
"worst_performer_path": None,
"worst_performer_score": None,
"open_findings": 0,
+ "maintainability_average": None,
}
total_nloc = sum(max(m.nloc, 1) for m in metrics)
if total_nloc:
@@ -478,6 +479,24 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
else:
avg = sum(m.score for m in metrics) / len(metrics)
worst = min(metrics, key=lambda r: r.score)
+
+ # Maintainability headline: NLOC-weighted average over the per-file
+ # maintainability scores (skipping rows that predate the split / lack one).
+ # ``None`` when no row carries a maintainability score so the surface reads
+ # "not measured" rather than a misleading 10.0.
+ maint_scored = [m for m in metrics if getattr(m, "maintainability_score", None) is not None]
+ maintainability_average: float | None = None
+ if maint_scored:
+ maint_nloc = sum(max(m.nloc, 1) for m in maint_scored)
+ if maint_nloc:
+ maintainability_average = (
+ sum(m.maintainability_score * max(m.nloc, 1) for m in maint_scored) / maint_nloc
+ )
+ else:
+ maintainability_average = sum(m.maintainability_score for m in maint_scored) / len(
+ maint_scored
+ )
+
findings_count = await session.execute(
select(func.count())
.select_from(HealthFinding)
@@ -492,6 +511,9 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
"worst_performer_path": worst.file_path,
"worst_performer_score": round(worst.score, 2),
"open_findings": findings_count.scalar() or 0,
+ "maintainability_average": (
+ round(maintainability_average, 2) if maintainability_average is not None else None
+ ),
}
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 35fc4f2e7..9c3dded59 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -44,9 +44,17 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:
"reason": f.reason,
"details": details,
"status": f.status,
+ # Health pillar this finding homes under (defect / maintainability /
+ # performance) for per-dimension filtering.
+ "dimension": getattr(f, "dimension", None) or "defect",
}
+def _round_opt(v: Any) -> float | None:
+ """Round a nullable per-dimension score, preserving ``None`` (not measured)."""
+ return round(v, 2) if v is not None else None
+
+
def _serialize_metric(m: HealthFileMetric) -> dict[str, Any]:
return {
"file_path": m.file_path,
@@ -58,6 +66,12 @@ def _serialize_metric(m: HealthFileMetric) -> dict[str, Any]:
"line_coverage_pct": m.line_coverage_pct,
"branch_coverage_pct": m.branch_coverage_pct,
"module": m.module,
+ # Per-dimension scores from the three-signal split. ``score`` is the
+ # overall surfaced number (== ``defect_score`` for now);
+ # ``performance_score`` is computed but not yet surfaced as its own pillar.
+ "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)),
}
@@ -111,6 +125,21 @@ def _module_rollups(metrics: list[HealthFileMetric]) -> list[dict[str, Any]]:
return out
+def _maintainability_average(metrics: list[HealthFileMetric]) -> float | None:
+ """NLOC-weighted maintainability headline, or ``None`` when unmeasured.
+
+ Skips rows without a ``maintainability_score`` (those predating the split)
+ so the KPI reads "not measured" rather than a misleading 10.0.
+ """
+ scored = [m for m in metrics if getattr(m, "maintainability_score", None) is not None]
+ if not scored:
+ return None
+ total_nloc = sum(max(m.nloc, 1) for m in scored)
+ if not total_nloc:
+ return round(sum(m.maintainability_score for m in scored) / len(scored), 2)
+ return round(sum(m.maintainability_score * max(m.nloc, 1) for m in scored) / total_nloc, 2)
+
+
def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
if not metrics:
return {
@@ -118,6 +147,7 @@ def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
"average_health": 10.0,
"worst_performer_path": None,
"worst_performer_score": None,
+ "maintainability_average": None,
}
total_nloc = sum(max(m.nloc, 1) for m in metrics)
avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc
@@ -128,6 +158,8 @@ def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
"band": band_for(round(avg, 2)),
"worst_performer_path": worst.file_path,
"worst_performer_score": round(worst.score, 2),
+ # Maintainability pillar headline alongside the defect-backed average.
+ "maintainability_average": _maintainability_average(metrics),
}
@@ -148,6 +180,17 @@ async def get_health(
``complex_method``. Phase 2 adds coverage biomarkers; Phase 3 adds
duplication + organizational biomarkers.
+ Two-signal health: every file metric carries per-dimension scores from the
+ three-signal split. ``score`` is the overall, defect-calibrated number
+ surfaced everywhere (== ``defect_score``); ``maintainability_score`` is a
+ co-equal second signal made of the smells the defect calibration floors
+ (cohesion, brain methods, primitive obsession, duplication, error handling)
+ given full weight in their own pillar; ``performance_score`` is computed but
+ not yet surfaced as its own pillar. ``kpis.maintainability_average`` is the
+ NLOC-weighted repo headline for that pillar. Each finding carries a
+ ``dimension`` (``defect`` / ``maintainability`` / ``performance``) naming the
+ pillar it homes under, so findings can be filtered per dimension.
+
Args:
targets: List of file paths. Empty → dashboard mode.
include: Optional flags. ``"biomarkers"`` always returns findings;
diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.py
index 82f4d264c..33a2ad5e6 100644
--- a/packages/server/src/repowise/server/routers/code_health.py
+++ b/packages/server/src/repowise/server/routers/code_health.py
@@ -65,9 +65,18 @@ def _finding_to_dict(f: Any) -> dict:
"reason": f.reason,
"details": details,
"status": f.status,
+ # Pillar the finding homes under (defect / maintainability / performance)
+ # so the UI can filter findings per dimension. Defaults to defect for
+ # rows that predate the split.
+ "dimension": getattr(f, "dimension", None) or "defect",
}
+def _round_opt(v: Any) -> float | None:
+ """Round a nullable per-dimension score, preserving ``None`` (not measured)."""
+ return round(v, 2) if v is not None else None
+
+
def _metric_to_dict(m: Any) -> dict:
return {
"file_path": m.file_path,
@@ -79,6 +88,12 @@ def _metric_to_dict(m: Any) -> dict:
"line_coverage_pct": m.line_coverage_pct,
"module": m.module,
"duplication_pct": getattr(m, "duplication_pct", None),
+ # Per-dimension scores from the three-signal split. ``score`` above stays
+ # the overall surfaced number (== defect_score for now).
+ # ``performance_score`` is computed but not yet surfaced as its own pillar.
+ "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)),
}
diff --git a/packages/types/__tests__/health.test.ts b/packages/types/__tests__/health.test.ts
index 509c9faa7..9d50ab0ef 100644
--- a/packages/types/__tests__/health.test.ts
+++ b/packages/types/__tests__/health.test.ts
@@ -9,7 +9,7 @@
*/
import { describe, expect, it } from "vitest";
-import { ALERT_MAX, HEALTHY_MIN, bandForScore } from "../src/health.js";
+import { ALERT_MAX, HEALTHY_MIN, HEALTH_DIMENSIONS, bandForScore } from "../src/health.js";
describe("health band cutoffs", () => {
it("are the frozen defect-backed values", () => {
@@ -18,6 +18,15 @@ describe("health band cutoffs", () => {
});
});
+describe("health dimensions", () => {
+ it("match core's DIMENSIONS order (parity guard)", () => {
+ // Mirror of `DIMENSIONS` in
+ // packages/core/src/repowise/core/analysis/health/scoring.py. The Python
+ // half of this guard lives in tests/unit/health/test_scoring_dimensions.py.
+ expect(HEALTH_DIMENSIONS).toEqual(["defect", "maintainability", "performance"]);
+ });
+});
+
describe("bandForScore", () => {
it("maps each band including boundaries", () => {
expect(bandForScore(1.0)).toBe("alert");
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index d20312600..bd1f9d32a 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -18,6 +18,39 @@
/** Finding severity used across the health surface. */
export type HealthSeverity = "low" | "medium" | "high" | "critical";
+/* ------------------------------------------------------------------ *
+ * Health dimensions (the three-signal split)
+ * ------------------------------------------------------------------ */
+
+/**
+ * The orthogonal health signals. `defect` is the historical, calibrated score
+ * surfaced as the overall number; `maintainability` is a co-surfaced second
+ * signal made of the smells the defect calibration floors (they don't predict
+ * bugs, so they get a proper home here instead of diluting the defect score);
+ * `performance` is defined but not yet surfaced (no detectors land until a
+ * later release).
+ *
+ * Mirror of `DIMENSIONS` in
+ * `packages/core/src/repowise/core/analysis/health/scoring.py`, kept in sync by
+ * a parity test (`__tests__/health.test.ts` here,
+ * `tests/unit/health/test_scoring_dimensions.py` in core).
+ */
+export type HealthDimension = "defect" | "maintainability" | "performance";
+
+/** Canonical dimension order (parity-locked against core's `DIMENSIONS`). */
+export const HEALTH_DIMENSIONS: readonly HealthDimension[] = [
+ "defect",
+ "maintainability",
+ "performance",
+] as const;
+
+/** Display labels for the dimensions surfaced today. */
+export const HEALTH_DIMENSION_LABEL: Record<HealthDimension, string> = {
+ defect: "Defect risk",
+ maintainability: "Maintainability",
+ performance: "Performance",
+};
+
/* ------------------------------------------------------------------ *
* Band "currency" layer
* ------------------------------------------------------------------ */
@@ -116,6 +149,17 @@ export interface HealthFileMetric {
line_coverage_pct: number | null;
module: string | null;
duplication_pct?: number | null;
+ /**
+ * Per-dimension scores from the three-signal split. `score` stays the overall
+ * surfaced number (== `defect_score` until a deliberate blend decision).
+ * `maintainability_score` is the co-surfaced second signal;
+ * `performance_score` is computed but not yet surfaced as its own pillar
+ * (`null` on payloads that predate the performance detectors). All optional so
+ * older payloads parse unchanged.
+ */
+ defect_score?: number | null;
+ maintainability_score?: number | null;
+ performance_score?: number | null;
}
export interface HealthFinding {
@@ -132,6 +176,12 @@ export interface HealthFinding {
status: string;
/** Matching symbol id when the finding names a function; links to the symbol page. */
symbol_id?: string | null;
+ /**
+ * The finding's "home" health dimension (`defect` / `maintainability` /
+ * `performance`), used to filter findings by pillar. Optional/`defect` when an
+ * older payload omits it.
+ */
+ dimension?: HealthDimension;
}
export interface HealthModuleRow {
@@ -166,6 +216,14 @@ export interface HealthOverviewSummary {
severity_breakdown?: { critical: number; high: number; medium: number; low: number };
/** Repo-level band derived from `average_health` (added in the band/distribution layer). */
band?: HealthBand;
+ /**
+ * NLOC-weighted repo headline for the maintainability pillar (the second
+ * surfaced signal). `null`/absent when no file carries a maintainability
+ * score. `maintainability_hotspot` is the same average restricted to hotspot
+ * files, when available.
+ */
+ maintainability_average?: number | null;
+ maintainability_hotspot?: number | null;
}
export interface HealthOverviewResponse {
diff --git a/packages/ui/src/health/biomarker-chip.tsx b/packages/ui/src/health/biomarker-chip.tsx
index f902f0820..9f9294d9e 100644
--- a/packages/ui/src/health/biomarker-chip.tsx
+++ b/packages/ui/src/health/biomarker-chip.tsx
@@ -1,7 +1,12 @@
"use client";
import { Info } from "lucide-react";
-import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
+import {
+ biomarkerInfo,
+ biomarkerDimension,
+ CATEGORY_LABEL,
+ DIMENSION_LABEL,
+} from "./biomarker-glossary";
export interface BiomarkerChipProps {
type: string;
@@ -11,7 +16,7 @@ export interface BiomarkerChipProps {
export function BiomarkerChip({ type, showInfo = true, className = "" }: BiomarkerChipProps) {
const info = biomarkerInfo(type);
- const title = `${info.label} · ${CATEGORY_LABEL[info.category]}\n\n${info.description}`;
+ const title = `${info.label} · ${CATEGORY_LABEL[info.category]} · ${DIMENSION_LABEL[biomarkerDimension(type)]}\n\n${info.description}`;
return (
<span
className={`inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-primary)] ${className}`}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index 0fd8b6b23..a907099c0 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -235,3 +235,49 @@ export function biomarkerInfo(name: string): BiomarkerInfo {
export function biomarkerLabel(name: string): string {
return biomarkerInfo(name).label;
}
+
+/* ------------------------------------------------------------------ *
+ * Health dimensions: which pillar a biomarker "homes" under
+ * ------------------------------------------------------------------ */
+
+export type BiomarkerDimension = "defect" | "maintainability";
+
+/**
+ * The biomarkers whose "home" pillar is maintainability: the smells the defect
+ * calibration floors because they don't predict bugs, given a proper home here.
+ * Mirror of ``_MAINTAINABILITY_HOME`` in
+ * ``packages/core/src/repowise/core/analysis/health/scoring.py``. Every other
+ * biomarker (including the structural duals that count toward both dimensions)
+ * homes under defect, its primary calibrated role.
+ *
+ * The server stamps each finding's authoritative ``dimension`` from the same
+ * Python source; this set is only the client-side fallback for payloads that
+ * omit it, so the two can never disagree on a fresh response.
+ */
+export const MAINTAINABILITY_HOME_BIOMARKERS: ReadonlySet<string> = new Set([
+ "low_cohesion",
+ "brain_method",
+ "primitive_obsession",
+ "dry_violation",
+ "error_handling",
+]);
+
+/**
+ * A biomarker's home dimension for display / filtering. Prefer a finding's
+ * server-provided `dimension` field where available; this is the fallback when
+ * only the biomarker type is known (e.g. a glossary entry).
+ */
+export function biomarkerDimension(name: string): BiomarkerDimension {
+ return MAINTAINABILITY_HOME_BIOMARKERS.has(name) ? "maintainability" : "defect";
+}
+
+export const DIMENSION_LABEL: Record<BiomarkerDimension, string> = {
+ defect: "Defect risk",
+ maintainability: "Maintainability",
+};
+
+/** Tailwind chip classes per pillar, matching the surrounding chip palette. */
+export const DIMENSION_CHIP: Record<BiomarkerDimension, string> = {
+ defect: "bg-[var(--color-accent-primary)]/10 text-[var(--color-accent-primary)]",
+ maintainability: "bg-[var(--color-accent-secondary)]/10 text-[var(--color-accent-secondary)]",
+};
diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsx
index 798929501..e428ecf6a 100644
--- a/packages/ui/src/health/biomarker-list.tsx
+++ b/packages/ui/src/health/biomarker-list.tsx
@@ -3,7 +3,15 @@
import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { InfoTip } from "../shared/info-tip";
-import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
+import {
+ biomarkerLabel,
+ biomarkerInfo,
+ biomarkerDimension,
+ CATEGORY_LABEL,
+ DIMENSION_CHIP,
+ DIMENSION_LABEL,
+ type BiomarkerDimension,
+} from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";
@@ -16,6 +24,15 @@ export interface BiomarkerFinding {
health_impact: number;
reason: string;
details?: BiomarkerDetailsRecord | null;
+ /** Server-provided home pillar; falls back to the biomarker's glossary
+ * dimension when an older payload omits it. */
+ dimension?: BiomarkerDimension | string;
+}
+
+/** A finding's home pillar, preferring the server value over the glossary. */
+function findingDimension(f: BiomarkerFinding): BiomarkerDimension {
+ if (f.dimension === "maintainability" || f.dimension === "defect") return f.dimension;
+ return biomarkerDimension(f.biomarker_type);
}
export interface BiomarkerListProps {
@@ -24,6 +41,8 @@ export interface BiomarkerListProps {
grouped?: boolean;
/** Optional minimum severity filter. */
minSeverity?: Severity;
+ /** Optional pillar filter: restrict to one health dimension. */
+ dimension?: BiomarkerDimension | undefined;
onSelect?: ((f: BiomarkerFinding) => void) | undefined;
maxPerGroup?: number;
/** Click-handler for the partner-file chip on hidden_coupling rows. */
@@ -36,14 +55,17 @@ export function BiomarkerList({
findings,
grouped = false,
minSeverity,
+ dimension,
onSelect,
maxPerGroup = 8,
onPartnerSelect,
onPartnerHref,
}: BiomarkerListProps) {
- const filtered = minSeverity
- ? findings.filter((f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[minSeverity])
- : findings;
+ const filtered = findings.filter(
+ (f) =>
+ (!minSeverity || SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[minSeverity]) &&
+ (!dimension || findingDimension(f) === dimension),
+ );
if (filtered.length === 0) {
return (
@@ -137,6 +159,7 @@ function BiomarkerGroup({
<span className="text-xs text-[var(--color-text-tertiary)]">
{CATEGORY_LABEL[info.category]}
</span>
+ <DimensionChip dimension={biomarkerDimension(type)} />
<span className="ml-auto inline-flex items-center gap-1.5 text-xs tabular-nums">
{(Object.keys(sevCounts) as Severity[]).map((s) =>
sevCounts[s] > 0 ? (
@@ -175,6 +198,17 @@ function BiomarkerGroup({
);
}
+function DimensionChip({ dimension }: { dimension: BiomarkerDimension }) {
+ return (
+ <span
+ className={`inline-flex items-center rounded px-1.5 py-px text-[10px] font-medium ${DIMENSION_CHIP[dimension]}`}
+ title={`${DIMENSION_LABEL[dimension]} pillar`}
+ >
+ {DIMENSION_LABEL[dimension]}
+ </span>
+ );
+}
+
function FindingRow({
finding,
onSelect,
@@ -210,6 +244,7 @@ function FindingRow({
label={`About ${biomarkerLabel(f.biomarker_type)}`}
/>
) : null}
+ <DimensionChip dimension={findingDimension(f)} />
</span>
) : null}
<span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 819b4e995..d125954aa 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -4,7 +4,15 @@ import { useState } from "react";
import { ExternalLink } from "lucide-react";
import { AdaptivePanel } from "../shared/adaptive-panel";
import { InfoTip } from "../shared/info-tip";
-import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
+import {
+ biomarkerLabel,
+ biomarkerInfo,
+ biomarkerDimension,
+ CATEGORY_LABEL,
+ DIMENSION_CHIP,
+ DIMENSION_LABEL,
+ type BiomarkerDimension,
+} from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
import { FileSignalsPanel } from "./file-signals-panel";
@@ -30,6 +38,8 @@ export interface HealthDrawerFinding {
reason: string;
status?: string;
details?: BiomarkerDetailsRecord | null;
+ /** Home pillar; falls back to the biomarker's glossary dimension. */
+ dimension?: BiomarkerDimension | string;
}
export interface HealthDrawerMetric {
@@ -42,6 +52,10 @@ export interface HealthDrawerMetric {
duplication_pct?: number | null;
line_coverage_pct?: number | null;
has_test_file: boolean;
+ /** Per-dimension scores from the three-signal split (null until populated). */
+ defect_score?: number | null;
+ maintainability_score?: number | null;
+ performance_score?: number | null;
}
export interface HealthFileDrawerProps {
@@ -138,12 +152,22 @@ export function HealthFileDrawer({
) : (
<>
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
- <Stat label="Score" value={
+ <Stat label="Defect risk" value={
<span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.score)}`}>
{metric.score.toFixed(1)}
<span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
</span>
} />
+ <Stat label="Maintainability" value={
+ metric.maintainability_score == null ? (
+ <span className="text-xs text-[var(--color-text-tertiary)]">—</span>
+ ) : (
+ <span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.maintainability_score)}`}>
+ {metric.maintainability_score.toFixed(1)}
+ <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
+ </span>
+ )
+ } />
<Stat label="Max CCN" value={<span className="text-base font-semibold tabular-nums">{metric.max_ccn}</span>} />
<Stat label="Nest" value={<span className="text-base font-semibold tabular-nums">{metric.max_nesting}</span>} />
<Stat label="NLOC" value={<span className="text-base font-semibold tabular-nums">{metric.nloc}</span>} />
@@ -240,6 +264,20 @@ export function HealthFileDrawer({
<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
+ : 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 =
diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsx
index cf5fe5eb8..e39f1a2b1 100644
--- a/packages/ui/src/health/kpi-cards.tsx
+++ b/packages/ui/src/health/kpi-cards.tsx
@@ -17,6 +17,9 @@ export interface HealthSummary {
severity_breakdown?: SeverityBreakdown;
/** Repo-level band from the API; derived from average_health when absent. */
band?: HealthBand;
+ /** Maintainability pillar headline (the co-surfaced second signal). `null`
+ * when no file carries a maintainability score yet. */
+ maintainability_average?: number | null;
}
export interface HealthKpiCardsProps {
@@ -41,8 +44,9 @@ export function HealthKpiCards({
hotspotDelta,
}: HealthKpiCardsProps) {
const band = summary.band ?? bandForScore(summary.average_health);
+ const maint = summary.maintainability_average;
return (
- <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
<Card label="Files Analyzed">
<p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">
{formatNumber(summary.file_count)}
@@ -66,6 +70,31 @@ export function HealthKpiCards({
</div>
) : null}
</Card>
+ <Card
+ label="Maintainability"
+ hint="A second, parallel health signal: the smells that hurt readability and change-cost (low cohesion, brain methods, primitive obsession, duplication, error handling) scored on their own, separate from the defect-backed score, which they don't predict. NLOC-weighted across the repo."
+ >
+ {maint == null ? (
+ <p className="text-2xl font-bold tabular-nums text-[var(--color-text-tertiary)]">
+ —
+ <span className="ml-1 align-middle text-xs font-normal text-[var(--color-text-tertiary)]">
+ not measured
+ </span>
+ </p>
+ ) : (
+ <p
+ className={`flex items-baseline gap-2 text-2xl font-bold tabular-nums ${scoreTextColor(maint)}`}
+ >
+ <span>
+ {maint.toFixed(1)}
+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>
+ </span>
+ <span className={`text-xs font-semibold uppercase tracking-wide ${healthBandTextColor(bandForScore(maint))}`}>
+ {HEALTH_BAND_LABEL[bandForScore(maint)]}
+ </span>
+ </p>
+ )}
+ </Card>
<Card
label="Hotspot Health"
sparkline={hotspotHistory}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index a5931d1c4..ac4ef0793 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -125,6 +125,7 @@ export function TriageTab({
// ---- One filter set coordinates the queue AND the findings sidebar ----
const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
+ const [pillar, setPillar] = useState<"all" | "defect" | "maintainability">("all");
const [biomarker, setBiomarker] = useState<string>("all");
const [maxEffort, setMaxEffort] = useState<string>("all");
const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
@@ -249,8 +250,8 @@ export function TriageTab({
return (
<div className="space-y-6">
{isLoading ? (
- <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
- {Array.from({ length: 5 }).map((_, i) => (
+ <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
+ {Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-24 w-full rounded-lg" />
))}
</div>
@@ -326,6 +327,18 @@ export function TriageTab({
<h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
Findings
</h2>
+ <select
+ value={pillar}
+ onChange={(e) =>
+ setPillar(e.target.value as "all" | "defect" | "maintainability")
+ }
+ aria-label="Health pillar"
+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ >
+ <option value="all">All pillars</option>
+ <option value="defect">Defect risk</option>
+ <option value="maintainability">Maintainability</option>
+ </select>
<select
value={minSeverity}
onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
@@ -344,6 +357,7 @@ export function TriageTab({
findings={overview.top_findings}
grouped
minSeverity={minSeverity === "all" ? undefined : minSeverity}
+ dimension={pillar === "all" ? undefined : pillar}
onSelect={(f) => setSelectedFile(f.file_path)}
/>
</div>
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 1004c4a7a..e7d44c777 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import pytest
from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
-from repowise.core.generation.editor_files.data import EditorFileData
+from repowise.core.generation.editor_files.data import CodeHealthBlock, EditorFileData
# ---------------------------------------------------------------------------
# Minimal concrete subclass for testing
@@ -51,6 +51,34 @@ def test_render_contains_repo_name(gen):
assert "test-repo" in result
+def _health_block(maintainability_average: float | None) -> CodeHealthBlock:
+ return CodeHealthBlock(
+ hotspot_health=5.0,
+ average_health=7.5,
+ worst_score=2.0,
+ worst_path="src/bad.py",
+ maintainability_average=maintainability_average,
+ )
+
+
+def test_render_surfaces_maintainability_when_present(gen):
+ import dataclasses
+
+ data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ result = gen.render(data)
+ assert "Maintainability, Average: 6.4/10" in result
+
+
+def test_render_omits_maintainability_when_unmeasured(gen):
+ import dataclasses
+
+ data = dataclasses.replace(_minimal_data(), code_health=_health_block(None))
+ result = gen.render(data)
+ # Defect-risk block still renders; the maintainability line is suppressed.
+ assert "Hotspot health" in result
+ assert "Maintainability, Average" not in result
+
+
def test_write_creates_new_file(gen, tmp_path):
data = _minimal_data()
written = gen.write(tmp_path, data)
diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.py
index 082a776a1..466ebaf1e 100644
--- a/tests/unit/health/test_scoring.py
+++ b/tests/unit/health/test_scoring.py
@@ -69,3 +69,43 @@ def test_compute_kpis_empty_returns_defaults():
kpis = compute_kpis([], hotspot_paths=set())
assert kpis["average_health"] == 10.0
assert kpis["file_count"] == 0
+ assert kpis["maintainability_average"] is None
+
+
+def test_compute_kpis_maintainability_average_nloc_weighted():
+ metrics = [
+ HealthFileMetricData(
+ "a.py",
+ score=5.0,
+ max_ccn=1,
+ max_nesting=1,
+ nloc=100,
+ has_test_file=False,
+ maintainability_score=6.0,
+ ),
+ HealthFileMetricData(
+ "b.py",
+ score=10.0,
+ max_ccn=1,
+ max_nesting=1,
+ nloc=10,
+ has_test_file=False,
+ maintainability_score=9.0,
+ ),
+ ]
+ kpis = compute_kpis(metrics, hotspot_paths={"a.py"})
+ # Weighted avg = (6*100 + 9*10) / 110 ≈ 6.27
+ assert abs(kpis["maintainability_average"] - 6.27) < 0.02
+ # Hotspot restricted to a.py -> its own maintainability score.
+ assert kpis["maintainability_hotspot"] == 6.0
+
+
+def test_compute_kpis_maintainability_none_when_unscored():
+ """Files predating the split (no maintainability_score) -> None, not 10.0."""
+ metrics = [
+ HealthFileMetricData(
+ "a.py", score=5.0, max_ccn=1, max_nesting=1, nloc=100, has_test_file=False
+ ),
+ ]
+ kpis = compute_kpis(metrics, hotspot_paths=set())
+ assert kpis["maintainability_average"] is None
diff --git a/tests/unit/health/test_scoring_dimensions.py b/tests/unit/health/test_scoring_dimensions.py
index 860bac83a..d37eafa83 100644
--- a/tests/unit/health/test_scoring_dimensions.py
+++ b/tests/unit/health/test_scoring_dimensions.py
@@ -189,6 +189,16 @@ def test_score_file_returns_all_dimensions():
assert set(scores) == set(DIMENSIONS)
+def test_dimensions_parity_with_typescript():
+ """Order + membership must match HEALTH_DIMENSIONS in packages/types/src/health.ts.
+
+ The TS half of this guard lives in packages/types/__tests__/health.test.ts.
+ The dimension labels cross the wire (the ``dimension`` field on findings), so
+ a silent rename on one side without the other fails one of these two tests.
+ """
+ assert DIMENSIONS == ("defect", "maintainability", "performance")
+
+
def test_performance_measured_with_no_findings_is_ten():
"""The perf detectors are registered (PR3): a file with no perf findings is
measured at 10.0, not null. None of the defect/maintainability fixtures
diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.py
index 45a109f4c..f9b3e27b0 100644
--- a/tests/unit/server/mcp/conftest.py
+++ b/tests/unit/server/mcp/conftest.py
@@ -586,6 +586,8 @@ async def health_data(session: AsyncSession, populated_db: str) -> str:
"nloc": 200,
"has_test_file": False,
"module": "auth",
+ "defect_score": 4.5,
+ "maintainability_score": 6.0,
},
{
"file_path": "src/db/models.py",
@@ -595,6 +597,8 @@ async def health_data(session: AsyncSession, populated_db: str) -> str:
"nloc": 50,
"has_test_file": True,
"module": "db",
+ "defect_score": 8.5,
+ "maintainability_score": 9.0,
},
],
)
@@ -624,6 +628,18 @@ async def health_data(session: AsyncSession, populated_db: str) -> str:
"health_impact": 0.7,
"reason": "authenticate nests 5 levels deep",
},
+ {
+ "file_path": "src/auth/service.py",
+ "biomarker_type": "low_cohesion",
+ "severity": "high",
+ "function_name": None,
+ "line_start": None,
+ "line_end": None,
+ "details": {},
+ "health_impact": 1.0,
+ "reason": "AuthService has low cohesion",
+ "dimension": "maintainability",
+ },
],
)
await session.commit()
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 5d66e47de..1dfde86db 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -19,7 +19,26 @@ async def test_get_health_dashboard(setup_mcp, health_data):
assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"
assert len(result["worst_files"]) == 2
assert result["worst_files"][0]["file_path"] == "src/auth/service.py"
- assert len(result["top_findings"]) == 2
+ assert len(result["top_findings"]) == 3
+
+
+async def test_get_health_dashboard_surfaces_maintainability(setup_mcp, health_data):
+ """The maintainability pillar is surfaced as a co-equal second signal."""
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health()
+ # Repo-level KPI headline for the maintainability pillar.
+ # NLOC-weighted: (6.0*200 + 9.0*50) / 250 = 6.6.
+ assert result["kpis"]["maintainability_average"] == 6.6
+ # Per-file metrics carry both dimension scores; perf is null (no detectors).
+ worst = result["worst_files"][0]
+ assert worst["defect_score"] == 4.5
+ assert worst["maintainability_score"] == 6.0
+ assert worst["performance_score"] is None
+ # Findings are tagged with their home pillar so they can be filtered.
+ dims = {f["dimension"] for f in result["top_findings"]}
+ assert dims == {"defect", "maintainability"}
@pytest.mark.asyncio
@@ -30,4 +49,5 @@ async def test_get_health_targeted(setup_mcp, health_data):
assert result["mode"] == "targets"
assert len(result["metrics"]) == 1
assert result["metrics"][0]["max_ccn"] == 15
+ assert result["metrics"][0]["maintainability_score"] == 6.0
assert all(f["file_path"] == "src/auth/service.py" for f in result["findings"])