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): split code-health score into defect, maintainability, and performance dimensions (#528)
Raghav Chamadiya0aea6aaf77c2
diff --git a/packages/core/alembic/versions/0032_health_dimensions.py b/packages/core/alembic/versions/0032_health_dimensions.pynew file mode 100644index 000000000..6356964d2--- /dev/null+++ b/packages/core/alembic/versions/0032_health_dimensions.py@@ -0,0 +1,48 @@+"""Per-dimension health scores on health_file_metrics + dimension on findings.++The single code-health score is split into three orthogonal signals at the+scoring layer: defect, maintainability, and performance. This revision lands the+storage for that split:++- ``health_file_metrics`` gains nullable ``defect_score`` / ``maintainability_score``+ / ``performance_score`` columns. The existing ``score`` column stays the+ overall surfaced number and equals ``defect_score`` for now.+- ``health_findings`` gains a nullable ``dimension`` column (which pillar a+ finding homes under) for later per-pillar filtering.++All columns are additive and nullable with no backfill - the next index recompute+repopulates them. The overall surfaced score is unchanged.++Revision ID: 0032+Revises: 0031+Create Date: 2026-06-20+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0032"+down_revision: str | None = "0031"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("health_file_metrics", sa.Column("defect_score", sa.Float, nullable=True))+ op.add_column(+ "health_file_metrics", sa.Column("maintainability_score", sa.Float, nullable=True)+ )+ op.add_column("health_file_metrics", sa.Column("performance_score", sa.Float, nullable=True))+ op.add_column("health_findings", sa.Column("dimension", sa.String(16), nullable=True))+++def downgrade() -> None:+ op.drop_column("health_findings", "dimension")+ op.drop_column("health_file_metrics", "performance_score")+ op.drop_column("health_file_metrics", "maintainability_score")+ op.drop_column("health_file_metrics", "defect_score")diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 0b4299ae1..e491965bc 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -666,14 +666,19 @@ class HealthAnalyzer:)biomarker_results = detect_all(ctx, disabled=disabled)- score, deductions = score_file(biomarker_results)+ scores, deductions = score_file(biomarker_results)findings = attach_impacts(biomarker_results, deductions)for f in findings:f.file_path = file_path+ # The overall surfaced score stays == the defect dimension (no blend+ # yet); the per-dimension scores ride alongside it, additively.+ defect_score = scores["defect"]+ maint_score = scores["maintainability"]+ perf_score = scores["performance"]metric = HealthFileMetricData(file_path=file_path,- score=round(score, 2),+ score=round(defect_score, 2),max_ccn=max_ccn,max_nesting=max_nesting,nloc=nloc,@@ -682,6 +687,9 @@ class HealthAnalyzer:line_coverage_pct=line_cov,branch_coverage_pct=branch_cov,duplication_pct=dup_pct,+ defect_score=round(defect_score, 2),+ maintainability_score=(round(maint_score, 2) if maint_score is not None else None),+ performance_score=(round(perf_score, 2) if perf_score is not None else None),)return metric, findingsdiff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex cd30e5ba1..104e1ccf9 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -33,6 +33,10 @@ class HealthFindingData:details: dict[str, Any]health_impact: floatreason: str = ""+ # The finding's "home" health dimension (``defect`` / ``maintainability`` /+ # ``performance``) for per-pillar filtering. Defaults to ``defect`` - the+ # historical, surfaced pillar - so callers that don't set it are unchanged.+ dimension: str = "defect"@dataclass@@ -49,6 +53,14 @@ class HealthFileMetricData:duplication_pct: float | None = Noneline_coverage_pct: float | None = Nonebranch_coverage_pct: float | None = None+ # Per-dimension scores from the three-signal split. ``score`` above stays the+ # overall surfaced number and equals ``defect_score`` for now (the overall+ # score is not blended until a later, deliberate decision). ``performance_score``+ # is ``None`` until the performance detectors land. All nullable/defaulted so+ # the split is additive.+ defect_score: float | None = None+ maintainability_score: float | None = None+ performance_score: float | None = None@dataclassdiff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex 749df74b9..be737e856 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -19,7 +19,7 @@ empirical predictors are no longer suppressed by uniform severity values.from __future__ import annotations-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom .biomarkers.base import BiomarkerResultfrom .models import HealthFileMetricData, HealthFindingData, Severity@@ -171,6 +171,92 @@ _BIOMARKER_CATEGORY: dict[str, str] = {}+# ---------------------------------------------------------------------------+# Per-dimension scoring (defect / maintainability / performance)+# ---------------------------------------------------------------------------+#+# The single surfaced health score is, and remains, the DEFECT score: today's+# exact weights / categories / caps (the tables above), unchanged. Splitting the+# score into dimensions is purely additive: ``maintainability`` and+# ``performance`` are independent, independently-capped signals derived from the+# SAME biomarker stream, and they NEVER feed back into ``defect``.+#+# The load-bearing guarantee (locked by ``tests/unit/health/test_scoring_dimensions``)+# is that ``score_file(results)["defect"]`` reproduces the pre-split single+# score byte-for-byte for any input. If that drifts, the split is wrong.++DIMENSIONS: tuple[str, ...] = ("defect", "maintainability", "performance")++# Which dimensions each biomarker's deduction feeds. Biomarkers not listed here+# contribute to ``defect`` only - the historical behaviour, since every+# biomarker has always counted toward the single score. The maintainability+# smells the defect calibration floored to 0.5 (because they don't predict bugs)+# get their full weight back in ``maintainability``; the structural smells are+# genuine defect predictors AND core maintainability signals, so they count+# toward both.+_BIOMARKER_DIMENSIONS: dict[str, set[str]] = {+ # Floored-in-defect maintainability smells -> full weight in maintainability.+ "low_cohesion": {"defect", "maintainability"},+ "brain_method": {"defect", "maintainability"},+ "primitive_obsession": {"defect", "maintainability"},+ "dry_violation": {"defect", "maintainability"},+ "error_handling": {"defect", "maintainability"},+ # Structural smells: calibrated defect predictors that are ALSO core+ # maintainability signals - they contribute to both dimensions.+ "god_class": {"defect", "maintainability"},+ "large_method": {"defect", "maintainability"},+ "nested_complexity": {"defect", "maintainability"},+}++# Maintainability per-biomarker weight multipliers. Expert-set by definition -+# the defect calibration does not apply to a non-defect signal. The smells the+# defect score floors to 0.5 deduct at FULL weight (1.0) here; the structural+# duals stay at 1.0 too. Tuned only against the maintainability cap budget+# below, never against the defect corpus. Unknown biomarkers fall back to 1.0.+_MAINTAINABILITY_WEIGHT_MULTIPLIER: dict[str, float] = {+ "low_cohesion": 1.0,+ "brain_method": 1.0,+ "primitive_obsession": 1.0,+ "dry_violation": 1.0,+ "error_handling": 1.0,+ "god_class": 1.0,+ "large_method": 1.0,+ "nested_complexity": 1.0,+}++# Maintainability category per biomarker - an OWN table, independent of the+# defect category map, so the two dimensions can be retuned separately.+_MAINTAINABILITY_CATEGORY: dict[str, str] = {+ "brain_method": "structural_complexity",+ "low_cohesion": "structural_complexity",+ "god_class": "structural_complexity",+ "nested_complexity": "structural_complexity",+ "large_method": "structural_complexity",+ "primitive_obsession": "size_and_complexity",+ "dry_violation": "duplication",+ "error_handling": "error_handling",+}++# Maintainability per-category caps. Bounded so no single category dominates the+# maintainability score, mirroring the defect cap discipline but on the+# maintainability dimension's own budget.+_MAINTAINABILITY_CATEGORY_CAPS: dict[str, float] = {+ "structural_complexity": 4.0,+ "size_and_complexity": 2.0,+ "duplication": 2.0,+ "error_handling": 2.0,+}++# A finding's single "home" dimension, used for display and per-pillar+# filtering. Biomarkers that exist ONLY as maintainability signals home there;+# the structural duals and every calibrated predictor home to ``defect`` (their+# primary, calibrated role). Multi-dimension membership for scoring lives in+# ``_BIOMARKER_DIMENSIONS`` - this label is just the finding's primary bucket.+_MAINTAINABILITY_HOME: frozenset[str] = frozenset(+ {"low_cohesion", "brain_method", "primitive_obsession", "dry_violation", "error_handling"}+)++def severity_deduction(sev: Severity) -> float:return _SEVERITY_DEDUCTION.get(sev, 0.5)@@ -185,31 +271,55 @@ def biomarker_category(name: str) -> str:return _BIOMARKER_CATEGORY.get(name, "size_and_complexity")-def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:- """Aggregate biomarker hits -> final score in [1.0, 10.0].+def dimensions_for(name: str) -> set[str]:+ """Dimensions a biomarker's deduction contributes to (always >= ``{"defect"}``)."""+ return _BIOMARKER_DIMENSIONS.get(name, {"defect"})- Returns ``(score, per_result_deductions)`` where the deductions list- is parallel to *results* and represents each finding's contribution- AFTER category capping. Use it to populate- ``HealthFindingData.health_impact`` so the UI can show per-finding- impact.++def biomarker_dimension(name: str) -> str:+ """The finding's single 'home' dimension for display / per-pillar filtering."""+ if name in _MAINTAINABILITY_HOME:+ return "maintainability"+ return "defect"+++def maintainability_weight(name: str) -> float:+ """Maintainability multiplier; 1.0 for unknown biomarkers."""+ return _MAINTAINABILITY_WEIGHT_MULTIPLIER.get(name, 1.0)+++def maintainability_category(name: str) -> str:+ """Default to ``size_and_complexity`` for unknown biomarkers."""+ return _MAINTAINABILITY_CATEGORY.get(name, "size_and_complexity")+++def _score_dimension(+ results_list: list[BiomarkerResult],+ weight_fn: Callable[[str], float],+ category_fn: Callable[[str], str],+ caps: dict[str, float],+) -> tuple[float, list[float]]:+ """Aggregate one dimension's deductions -> ``(score, per_result_deductions)``.++ The single, shared scoring kernel: weight each finding, accumulate per+ category, cap each category, clamp to ``[1.0, 10.0]``. Every dimension runs+ the identical algorithm against its own weight / category / cap tables."""- results_list = list(results)raw: dict[str, list[tuple[int, float]]] = {}for idx, r in enumerate(results_list):- cat = biomarker_category(r.biomarker_type)+ cat = category_fn(r.biomarker_type)# A continuous ``deduction`` override (e.g. coverage scaled by the# uncovered fraction) takes the place of the discrete severity table;# both paths are then weighted and category-capped identically, so the# per-finding ``health_impact`` stays linear and attributable.base = r.deduction if r.deduction is not None else severity_deduction(r.severity)- weighted = base * biomarker_weight(r.biomarker_type)+ weighted = base * weight_fn(r.biomarker_type)raw.setdefault(cat, []).append((idx, weighted))per_result = [0.0] * len(results_list)total = 0.0for cat, entries in raw.items():- cap = CATEGORY_CAPS.get(cat, 1.0)+ cap = caps.get(cat, 1.0)cat_sum = sum(d for _, d in entries)if cat_sum <= cap:for idx, d in entries:@@ -226,6 +336,48 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:return score, per_result+def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | None], list[float]]:+ """Aggregate biomarker hits into per-dimension scores in ``[1.0, 10.0]``.++ Returns ``(scores, defect_deductions)`` where:++ - ``scores`` maps each dimension in ``DIMENSIONS`` to its score.+ ``scores["defect"]`` is the historical single score - byte-for-byte+ identical to the pre-split ``score_file`` (the load-bearing guarantee).+ ``scores["performance"]`` is ``None`` until the performance detectors land+ (no biomarker contributes to it yet), signalling "not measured" rather+ than a misleading perfect 10.0.+ - ``defect_deductions`` is each finding's contribution to the DEFECT score+ after category capping, parallel to *results*. It populates+ ``HealthFindingData.health_impact`` - a defect-pillar quantity - so the+ surfaced per-finding impact numbers are unchanged.+ """+ results_list = list(results)++ defect_score, defect_deductions = _score_dimension(+ results_list, biomarker_weight, biomarker_category, CATEGORY_CAPS+ )++ maint_results = [+ r for r in results_list if "maintainability" in dimensions_for(r.biomarker_type)+ ]+ maint_score, _ = _score_dimension(+ maint_results,+ maintainability_weight,+ maintainability_category,+ _MAINTAINABILITY_CATEGORY_CAPS,+ )++ scores: dict[str, float | None] = {+ "defect": defect_score,+ "maintainability": maint_score,+ # No performance detectors exist yet; the dimension is defined but empty+ # until PR3 registers its biomarkers. ``None`` = not measured.+ "performance": None,+ }+ return scores, defect_deductions++def attach_impacts(results: list[BiomarkerResult], deductions: list[float]) -> list[HealthFindingData]:@@ -243,6 +395,7 @@ def attach_impacts(details=r.details,health_impact=round(d, 3),reason=r.reason,+ dimension=biomarker_dimension(r.biomarker_type),))return outdiff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.pyindex 347d56a05..f91256809 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py@@ -260,6 +260,7 @@ async def save_health_findings("details_json": json.dumps(f.details or {}),"health_impact": float(f.health_impact),"reason": f.reason or "",+ "dimension": getattr(f, "dimension", None) or "defect",}else:data = dict(f)@@ -342,6 +343,7 @@ async def replace_governance_findings("details_json": json.dumps(f.details or {}),"health_impact": float(f.health_impact),"reason": f.reason or "",+ "dimension": getattr(f, "dimension", None) or "defect",}else:data = dict(f)@@ -396,6 +398,9 @@ async def save_health_metrics("line_coverage_pct": m.line_coverage_pct,"branch_coverage_pct": m.branch_coverage_pct,"module": m.module,+ "defect_score": getattr(m, "defect_score", None),+ "maintainability_score": getattr(m, "maintainability_score", None),+ "performance_score": getattr(m, "performance_score", None),}else:data = dict(m)@@ -618,6 +623,7 @@ async def upsert_health_findings("details_json": json.dumps(f.details or {}),"health_impact": float(f.health_impact),"reason": f.reason or "",+ "dimension": getattr(f, "dimension", None) or "defect",}else:data = dict(f)@@ -673,6 +679,9 @@ async def upsert_health_metrics("line_coverage_pct": m.line_coverage_pct,"branch_coverage_pct": m.branch_coverage_pct,"module": m.module,+ "defect_score": getattr(m, "defect_score", None),+ "maintainability_score": getattr(m, "maintainability_score", None),+ "performance_score": getattr(m, "performance_score", None),}else:data = dict(m)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex a73305760..b37484318 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -881,6 +881,10 @@ class HealthFinding(Base):details_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")health_impact: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ # Health dimension this finding homes under (defect / maintainability /+ # performance). Nullable + no backfill: old rows stay NULL until the next+ # index recomputes them; new writes always set it (defaults to "defect").+ dimension: Mapped[str | None] = mapped_column(String(16), nullable=True, default="defect")status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc@@ -909,6 +913,13 @@ class HealthFileMetric(Base):line_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)module: Mapped[str | None] = mapped_column(String(255), nullable=True)+ # Three-signal split. ``score`` above stays the overall surfaced number and+ # equals ``defect_score`` until a deliberate blend decision. ``performance_score``+ # is NULL until the performance detectors land. All nullable + no backfill:+ # recompute on the next index repopulates them.+ defect_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ maintainability_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ performance_score: Mapped[float | None] = mapped_column(Float, nullable=True)updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc)diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.pyindex 494ed810e..082a776a1 100644--- a/tests/unit/health/test_scoring.py+++ b/tests/unit/health/test_scoring.py@@ -24,8 +24,8 @@ def _r(name: str, severity: Severity) -> BiomarkerResult:def test_score_clean_file_is_ten():- score, deductions = score_file([])- assert score == 10.0+ scores, deductions = score_file([])+ assert scores["defect"] == 10.0assert deductions == []@@ -33,10 +33,10 @@ def test_score_clamps_floor_at_one():# Twenty critical findings in the same category — should hit the cap# but never go below 1.0.results = [_r("complex_method", Severity.CRITICAL) for _ in range(20)]- score, _ = score_file(results)- assert score >= 1.0+ scores, _ = score_file(results)+ assert scores["defect"] >= 1.0# Cap on size_and_complexity is 1.5 (post-recalibration) → score 8.5.- assert score == 8.5+ assert scores["defect"] == 8.5def test_category_cap_applied():@@ -46,8 +46,8 @@ def test_category_cap_applied():_r("brain_method", Severity.CRITICAL), # 2.0 raw_r("nested_complexity", Severity.CRITICAL), # 2.0 raw]- score, _ = score_file(results)- assert score == 10.0 - CATEGORY_CAPS["structural_complexity"]+ scores, _ = score_file(results)+ assert scores["defect"] == 10.0 - CATEGORY_CAPS["structural_complexity"]def test_compute_kpis_uses_nloc_weighting():diff --git a/tests/unit/health/test_scoring_dimensions.py b/tests/unit/health/test_scoring_dimensions.pynew file mode 100644index 000000000..d5cf26818--- /dev/null+++ b/tests/unit/health/test_scoring_dimensions.py@@ -0,0 +1,294 @@+"""Three-signal split: the golden defect guarantee + maintainability scoring.++The load-bearing guardrail of the dimension split is that the ``defect``+dimension reproduces the pre-split single score EXACTLY. ``_legacy_score_file``+below is a FROZEN copy of the scoring algorithm and its three tables as they+stood before the split. ``test_defect_dimension_matches_legacy_golden`` asserts+``score_file(...)["defect"]`` equals that frozen reference across a broad fixture+set. If it ever drifts, the split has corrupted the calibrated, surfaced score+and the change is wrong - do NOT update the golden to match; fix the regression.+"""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers.base import BiomarkerResult+from repowise.core.analysis.health.models import Severity+from repowise.core.analysis.health.scoring import (+ DIMENSIONS,+ attach_impacts,+ biomarker_dimension,+ dimensions_for,+ score_file,+)++# ---------------------------------------------------------------------------+# Frozen legacy reference (do NOT import the live tables - copy them so a live+# retune can never silently move the golden).+# ---------------------------------------------------------------------------++_LEGACY_CATEGORY_CAPS = {+ "organizational": 3.5,+ "structural_complexity": 2.5,+ "test_coverage": 2.0,+ "test_coverage_gradient": 2.0,+ "size_and_complexity": 1.5,+ "duplication": 1.0,+ "test_quality": 0.5,+ "error_handling": 0.5,+}++_LEGACY_SEVERITY_DEDUCTION = {+ Severity.LOW: 0.3,+ Severity.MEDIUM: 0.7,+ Severity.HIGH: 1.2,+ Severity.CRITICAL: 2.0,+}++_LEGACY_WEIGHT_MULTIPLIER = {+ "co_change_scatter": 1.8,+ "change_entropy": 1.51,+ "ownership_risk": 1.38,+ "nested_complexity": 1.34,+ "complex_conditional": 1.33,+ "large_method": 1.25,+ "complex_method": 1.21,+ "function_hotspot": 1.16,+ "god_class": 1.13,+ "prior_defect": 1.0,+ "untested_hotspot": 1.3,+ "churn_risk": 1.2,+ "code_age_volatility": 1.1,+ "developer_congestion": 0.5,+ "low_cohesion": 0.5,+ "brain_method": 0.5,+ "bumpy_road": 0.5,+ "primitive_obsession": 0.5,+ "dry_violation": 0.5,+ "knowledge_loss": 0.4,+ "error_handling": 0.5,+ "contradictory_decision": 1.0,+ "stale_governance": 0.9,+ "ungoverned_hotspot": 0.7,+}++_LEGACY_CATEGORY = {+ "brain_method": "structural_complexity",+ "low_cohesion": "structural_complexity",+ "god_class": "structural_complexity",+ "nested_complexity": "structural_complexity",+ "bumpy_road": "structural_complexity",+ "complex_conditional": "structural_complexity",+ "complex_method": "size_and_complexity",+ "large_method": "size_and_complexity",+ "primitive_obsession": "size_and_complexity",+ "dry_violation": "duplication",+ "untested_hotspot": "test_coverage",+ "coverage_gap": "test_coverage",+ "coverage_gradient": "test_coverage_gradient",+ "developer_congestion": "organizational",+ "knowledge_loss": "organizational",+ "hidden_coupling": "organizational",+ "function_hotspot": "organizational",+ "code_age_volatility": "organizational",+ "ownership_risk": "organizational",+ "churn_risk": "organizational",+ "change_entropy": "organizational",+ "co_change_scatter": "organizational",+ "prior_defect": "organizational",+ "large_assertion_block": "test_quality",+ "duplicated_assertion_block": "test_quality",+ "error_handling": "error_handling",+ "ungoverned_hotspot": "organizational",+ "stale_governance": "organizational",+ "contradictory_decision": "organizational",+}+++def _legacy_score_file(results: list[BiomarkerResult]) -> float:+ """The pre-split algorithm, verbatim, against the frozen tables above."""+ raw: dict[str, float] = {}+ for r in results:+ cat = _LEGACY_CATEGORY.get(r.biomarker_type, "size_and_complexity")+ base = (+ r.deduction+ if r.deduction is not None+ else _LEGACY_SEVERITY_DEDUCTION.get(r.severity, 0.5)+ )+ weighted = base * _LEGACY_WEIGHT_MULTIPLIER.get(r.biomarker_type, 1.0)+ raw[cat] = raw.get(cat, 0.0) + weighted++ total = 0.0+ for cat, cat_sum in raw.items():+ cap = _LEGACY_CATEGORY_CAPS.get(cat, 1.0)+ total += min(cat_sum, cap)+ return max(1.0, min(10.0, 10.0 - total))+++def _r(name: str, severity: Severity, *, deduction: float | None = None) -> BiomarkerResult:+ return BiomarkerResult(+ biomarker_type=name,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={},+ reason="",+ deduction=deduction,+ )+++# A broad, deterministic spread of fixtures: empty, single-category saturation,+# cross-category mixes, floored smells, structural duals, continuous overrides,+# and an unknown biomarker (default category/weight path).+_FIXTURES: list[list[BiomarkerResult]] = [+ [],+ [_r("complex_method", Severity.CRITICAL) for _ in range(20)],+ [_r("brain_method", Severity.CRITICAL), _r("nested_complexity", Severity.CRITICAL)],+ [+ _r("brain_method", Severity.CRITICAL),+ _r("nested_complexity", Severity.HIGH),+ _r("complex_method", Severity.MEDIUM),+ _r("untested_hotspot", Severity.HIGH),+ _r("knowledge_loss", Severity.LOW),+ ],+ [_r("error_handling", Severity.LOW) for _ in range(10)],+ [_r("developer_congestion", Severity.CRITICAL) for _ in range(3)],+ [+ _r("co_change_scatter", Severity.HIGH),+ _r("change_entropy", Severity.MEDIUM),+ _r("ownership_risk", Severity.HIGH),+ _r("dry_violation", Severity.MEDIUM),+ _r("primitive_obsession", Severity.HIGH),+ _r("god_class", Severity.CRITICAL),+ _r("large_method", Severity.HIGH),+ _r("low_cohesion", Severity.MEDIUM),+ ],+ [_r("coverage_gradient", Severity.LOW, deduction=4.0 * 0.8)],+ [_r("some_unregistered_biomarker", Severity.HIGH)],+]+++def test_defect_dimension_matches_legacy_golden():+ """THE GATE: scores["defect"] == the frozen pre-split score for every fixture."""+ for fixture in _FIXTURES:+ scores, _ = score_file(fixture)+ assert scores["defect"] == _legacy_score_file(fixture)+++def test_defect_deductions_unchanged():+ """The returned per-finding deductions still drive defect-based health_impact."""+ fixture = _FIXTURES[3]+ _, deductions = score_file(fixture)+ # Parallel to the input and non-negative.+ assert len(deductions) == len(fixture)+ assert all(d >= 0 for d in deductions)+++def test_score_file_returns_all_dimensions():+ scores, _ = score_file([_r("brain_method", Severity.HIGH)])+ assert set(scores) == set(DIMENSIONS)+++def test_performance_is_none_until_detectors_land():+ """No performance biomarkers exist yet -> the dimension is null, not 10.0."""+ for fixture in _FIXTURES:+ scores, _ = score_file(fixture)+ assert scores["performance"] is None+++def test_clean_file_is_ten_in_every_active_dimension():+ scores, _ = score_file([])+ assert scores["defect"] == 10.0+ assert scores["maintainability"] == 10.0+++# ---------------------------------------------------------------------------+# Maintainability dimension+# ---------------------------------------------------------------------------+++def test_floored_smell_is_full_weight_in_maintainability():+ """low_cohesion is floored to 0.5 in defect but full (1.0) in maintainability."""+ findings = [_r("low_cohesion", Severity.CRITICAL)]+ scores, _ = score_file(findings)+ # defect: 2.0 * 0.5 = 1.0 -> 9.0+ assert scores["defect"] == 9.0+ # maintainability: 2.0 * 1.0 = 2.0 in structural_complexity (cap 4.0) -> 8.0+ assert scores["maintainability"] == 8.0+++def test_maintainability_ignores_pure_defect_biomarkers():+ """A biomarker that only feeds defect leaves maintainability untouched."""+ findings = [_r("change_entropy", Severity.CRITICAL)]+ assert "maintainability" not in dimensions_for("change_entropy")+ scores, _ = score_file(findings)+ assert scores["maintainability"] == 10.0+ assert scores["defect"] < 10.0+++def test_structural_dual_counts_toward_both_dimensions():+ findings = [_r("god_class", Severity.HIGH)]+ assert dimensions_for("god_class") == {"defect", "maintainability"}+ scores, _ = score_file(findings)+ assert scores["defect"] < 10.0+ assert scores["maintainability"] < 10.0+++def test_maintainability_accumulates_across_findings():+ """Two structural maintainability smells accumulate (under the 4.0 cap)."""+ findings = [+ _r("low_cohesion", Severity.HIGH), # 1.2 * 1.0+ _r("brain_method", Severity.HIGH), # 1.2 * 1.0+ ]+ scores, _ = score_file(findings)+ # structural_complexity maintainability: 1.2 + 1.2 = 2.4 (< 4.0 cap) -> 7.6+ assert scores["maintainability"] == 7.6+++def test_maintainability_structural_cap_bounds_stream():+ """Many critical structural smells saturate the 4.0 maintainability cap."""+ findings = [_r("brain_method", Severity.CRITICAL) for _ in range(10)]+ scores, _ = score_file(findings)+ # 10 * 2.0 = 20 raw -> clamped to the 4.0 structural cap -> 6.0+ assert scores["maintainability"] == 6.0+++def test_maintainability_categories_capped_independently():+ """Each maintainability category is bounded on its own budget."""+ findings = [+ _r("brain_method", Severity.CRITICAL), # structural, capped at 4.0+ _r("brain_method", Severity.CRITICAL),+ _r("brain_method", Severity.CRITICAL),+ _r("dry_violation", Severity.CRITICAL), # duplication, capped at 2.0+ _r("dry_violation", Severity.CRITICAL),+ _r("error_handling", Severity.CRITICAL), # error_handling, capped at 2.0+ _r("error_handling", Severity.CRITICAL),+ ]+ scores, _ = score_file(findings)+ # structural 6.0->4.0 cap, duplication 4.0->2.0 cap, error_handling 4.0->2.0 cap+ # total = 4.0 + 2.0 + 2.0 = 8.0 -> 10 - 8 = 2.0+ assert scores["maintainability"] == 2.0+++# ---------------------------------------------------------------------------+# Finding "home" dimension+# ---------------------------------------------------------------------------+++def test_biomarker_home_dimension():+ assert biomarker_dimension("low_cohesion") == "maintainability"+ assert biomarker_dimension("error_handling") == "maintainability"+ # Structural duals home to defect (their primary, calibrated role).+ assert biomarker_dimension("god_class") == "defect"+ # Calibrated predictors home to defect.+ assert biomarker_dimension("change_entropy") == "defect"+ # Unknown defaults to defect.+ assert biomarker_dimension("mystery") == "defect"+++def test_attach_impacts_tags_finding_dimension():+ results = [_r("low_cohesion", Severity.HIGH), _r("change_entropy", Severity.HIGH)]+ _, deductions = score_file(results)+ findings = attach_impacts(results, deductions)+ assert findings[0].dimension == "maintainability"+ assert findings[1].dimension == "defect"diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pyindex a1720252e..5446c46aa 100644--- a/tests/unit/health/test_scoring_snapshot.py+++ b/tests/unit/health/test_scoring_snapshot.py@@ -156,22 +156,22 @@ def test_known_fixture_score_is_stable():_result("untested_hotspot", Severity.HIGH),_result("knowledge_loss", Severity.LOW),]- score, _ = score_file(findings)+ scores, _ = score_file(findings)# Math (defect-calibrated weights):# structural = brain(2.0*0.5) + nested(1.2*1.34) = 1.0 + 1.608 = 2.608 -> capped at 2.5# size_and_cx = complex_method 0.7 * 1.21 = 0.847 (under 1.5 cap)# coverage = untested_hotspot 1.2 * 1.3 = 1.56 (under 2.0 cap)# organizational = knowledge_loss 0.3 * 0.4 = 0.12 (under 3.5 cap)# total deduction = 2.5 + 0.847 + 1.56 + 0.12 = 5.027 -> 10 - 5.027 = 4.973- assert score == 4.973+ assert scores["defect"] == 4.973def test_category_cap_clamps_score():"""Many critical structural findings should not exceed the -2.5 cap."""findings = [_result("brain_method", Severity.CRITICAL) for _ in range(10)]- score, _ = score_file(findings)+ scores, _ = score_file(findings)# Cap at -2.5, so floor on this category alone is 7.5.- assert score == 7.5+ assert scores["defect"] == 7.5def test_continuous_deduction_override_is_used_and_capped():@@ -192,8 +192,8 @@ def test_continuous_deduction_override_is_used_and_capped():reason="",deduction=4.0 * 0.25,)- score, ded = score_file([quarter])- assert score == 9.0 # 10 - 1.0+ scores, ded = score_file([quarter])+ assert scores["defect"] == 9.0 # 10 - 1.0assert ded == [1.0]deep = BiomarkerResult(@@ -206,8 +206,8 @@ def test_continuous_deduction_override_is_used_and_capped():reason="",deduction=4.0 * 0.80,)- score2, ded2 = score_file([deep])- assert score2 == 8.0 # 10 - 2.0 (cap)+ scores2, ded2 = score_file([deep])+ assert scores2["defect"] == 8.0 # 10 - 2.0 (cap)assert ded2 == [2.0]@@ -215,13 +215,13 @@ def test_error_handling_cap_bounds_stream():"""error_handling findings deduct 0.15 each (LOW 0.3 x 0.5 weight) intheir own advisory category, capped at 0.5/file regardless of count."""two = [_result("error_handling", Severity.LOW) for _ in range(2)]- score, deductions = score_file(two)- assert score == 9.7 # 10 - 2 * 0.15+ scores, deductions = score_file(two)+ assert scores["defect"] == 9.7 # 10 - 2 * 0.15assert deductions == [0.15, 0.15]many = [_result("error_handling", Severity.LOW) for _ in range(10)]- score2, _ = score_file(many)- assert score2 == 9.5 # 10 * 0.15 = 1.5 raw -> clamped to the 0.5 cap+ scores2, _ = score_file(many)+ assert scores2["defect"] == 9.5 # 10 * 0.15 = 1.5 raw -> clamped to the 0.5 capdef test_organizational_cap_bounds_stream():@@ -229,6 +229,6 @@ def test_organizational_cap_bounds_stream():developer_congestion defect-calibrated down to 0.5 (it was a HEAD-leakageartifact), three CRITICALs deduct under the cap rather than saturating it."""findings = [_result("developer_congestion", Severity.CRITICAL) for _ in range(3)]- score, _ = score_file(findings)+ scores, _ = score_file(findings)# 3 * 2.0 * 0.5 = 3.0 weighted (< 3.5 cap) -> score = 7.0- assert score == 7.0+ assert scores["defect"] == 7.0diff --git a/tests/unit/persistence/test_health_dimensions_crud.py b/tests/unit/persistence/test_health_dimensions_crud.pynew file mode 100644index 000000000..77f52158e--- /dev/null+++ b/tests/unit/persistence/test_health_dimensions_crud.py@@ -0,0 +1,121 @@+"""Per-dimension health scores survive the persistence round trip.++Locks BOTH metric writers - the full-reindex ``save_health_metrics`` and the+incremental ``upsert_health_metrics`` - plus the findings ``dimension`` column,+so a future edit to one writer that forgets the new fields is caught.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.models import (+ HealthFileMetricData,+ HealthFindingData,+ Severity,+)+from repowise.core.persistence.crud.analysis import (+ get_health_findings,+ get_health_metrics,+ save_health_findings,+ save_health_metrics,+ upsert_health_metrics,+)+from tests.unit.persistence.helpers import insert_repo+++def _metric(path: str, **overrides) -> HealthFileMetricData:+ base = dict(+ file_path=path,+ score=7.5,+ max_ccn=3,+ max_nesting=2,+ nloc=120,+ has_test_file=False,+ defect_score=7.5,+ maintainability_score=6.0,+ performance_score=None,+ )+ base.update(overrides)+ return HealthFileMetricData(**base)+++async def test_save_health_metrics_persists_dimension_scores(async_session):+ repo = await insert_repo(async_session)+ await save_health_metrics(async_session, repo.id, [_metric("a.py")])+ await async_session.commit()++ rows = await get_health_metrics(async_session, repo.id)+ assert len(rows) == 1+ row = rows[0]+ assert row.score == 7.5+ assert row.defect_score == 7.5+ assert row.maintainability_score == 6.0+ assert row.performance_score is None+++async def test_upsert_health_metrics_persists_dimension_scores(async_session):+ """The incremental update path must carry the new fields too."""+ repo = await insert_repo(async_session)+ # First write via upsert (insert branch).+ await upsert_health_metrics(async_session, repo.id, [_metric("b.py")])+ await async_session.commit()++ row = (await get_health_metrics(async_session, repo.id))[0]+ assert row.defect_score == 7.5+ assert row.maintainability_score == 6.0+ assert row.performance_score is None++ # Re-upsert the same path with new values (update branch).+ await upsert_health_metrics(+ async_session,+ repo.id,+ [_metric("b.py", score=4.0, defect_score=4.0, maintainability_score=2.5)],+ )+ await async_session.commit()++ rows = await get_health_metrics(async_session, repo.id)+ assert len(rows) == 1 # updated in place, not duplicated+ row = rows[0]+ assert row.score == 4.0+ assert row.defect_score == 4.0+ assert row.maintainability_score == 2.5+ assert row.performance_score is None+++async def test_save_health_findings_persists_dimension(async_session):+ repo = await insert_repo(async_session)+ findings = [+ HealthFindingData(+ biomarker_type="low_cohesion",+ severity=Severity.HIGH,+ file_path="a.py",+ function_name=None,+ line_start=1,+ line_end=10,+ details={},+ health_impact=1.2,+ dimension="maintainability",+ ),+ HealthFindingData(+ biomarker_type="change_entropy",+ severity=Severity.HIGH,+ file_path="a.py",+ function_name=None,+ line_start=1,+ line_end=10,+ details={},+ health_impact=1.5,+ dimension="defect",+ ),+ ]+ await save_health_findings(async_session, repo.id, findings)+ await async_session.commit()++ rows = await get_health_findings(async_session, repo.id)+ by_type = {r.biomarker_type: r for r in rows}+ assert by_type["low_cohesion"].dimension == "maintainability"+ assert by_type["change_entropy"].dimension == "defect"