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): a file with no code finding loses at most one point to git history (#2566)

Raghav Chamadiyab0b2b6c099a6
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 1027e0e90..845c44174 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -317,7 +317,7 @@ golden guarantee (§6).
| Category | Cap | Markers |
|------------------------|------|------------|
-| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter, prior_defect, ungoverned_hotspot†, stale_governance†, contradictory_decision† |
+| Organizational | −3.5‡ | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter, prior_defect, ungoverned_hotspot†, stale_governance†, contradictory_decision† |
| Structural complexity | −2.5 | brain_method, low_cohesion, god_class, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
| Test coverage gradient | −2.0 | coverage_gradient |
@@ -332,6 +332,10 @@ writes them runs *after* scoring completes and never touches
in the table above because `scoring.py` maps them, not because they move a
number.
+‡ A ceiling. The live cap is `history_cap(structure)`, `min(3.5, 1.0 + structure)`,
+where `structure` is the file's capped deduction from every other defect
+category, so git history alone costs a file at most 1.0.
+
The maintainability dimension has its own independent tables
(`_MAINTAINABILITY_CATEGORY`, caps: structural_complexity 4.0,
size_and_complexity 2.0, duplication 2.0, error_handling 2.0, sql 2.0), and the
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index c2531a315..71dbf0882 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -134,7 +134,7 @@ capped per category, so no single category can dominate:
| Category | Cap |
|---|---|
-| Organizational | −3.5 |
+| Organizational | −3.5, less on cleaner code (below) |
| Structural complexity | −2.5 |
| Test coverage | −2.0 |
| Test coverage gradient | −2.0 |
@@ -157,6 +157,11 @@ stores its deduction as two numbers, `structure_deduction` and
`history_deduction`, which sum to the total. Nothing is hidden: the split is on
every metric row, and the Counts control below reads it back.
+Git history on its own measures activity, so its cap follows the code: history
+can cost a file at most 1.0, plus one point for each point the other categories
+deduct, up to 3.5. A file with no code-shape finding never reads below 9.0 from
+history alone.
+
Three repo-level KPIs: **Hotspot Health** (NLOC-weighted average over files the
git layer classifies as hotspots), **Average Health** (NLOC-weighted over all
files), and **Worst Performer**.
diff --git a/packages/core/src/repowise/core/analysis/health/aggregation.py b/packages/core/src/repowise/core/analysis/health/aggregation.py
index 134d1e17c..1def03d33 100644
--- a/packages/core/src/repowise/core/analysis/health/aggregation.py
+++ b/packages/core/src/repowise/core/analysis/health/aggregation.py
@@ -18,10 +18,13 @@ from .ranking import worst_metric
from .rows import detail_map, field
from .scoring import (
CATEGORY_CAPS,
+ HISTORY_CATEGORY,
SCORE_FLOOR,
SCORE_MAX,
biomarker_category,
biomarker_weight,
+ deduction_split,
+ history_cap,
is_advisory,
severity_deduction,
)
@@ -255,10 +258,13 @@ def score_breakdown(findings: Sequence[Any]) -> dict[str, Any]:
categories: list[dict[str, Any]] = []
total_deduction = 0.0
- for category, cap in CATEGORY_CAPS.items():
+ # The history cap follows the structure half, so report the one it scored under.
+ structure, _ = deduction_split(findings)
+ for category, static_cap in CATEGORY_CAPS.items():
entries = per_category.get(category, [])
if not entries:
continue
+ cap = history_cap(structure) if category == HISTORY_CATEGORY else static_cap
raw_each = [finding_raw_deduction(f) for f in entries]
applied_each = [float(field(f, "health_impact", 0.0) or 0.0) for f in entries]
raw_sum = sum(raw_each)
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index e55698e15..74c2e71f1 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -112,6 +112,10 @@ log = structlog.get_logger(__name__)
# and a declining call's arguments are not scanned, so an assertion passed as an
# argument still does not stand in for the header's oracle.
#
+# v32: the history (organizational) cap follows the file's structure half,
+# ``history_cap(structure)`` in scoring.py, so every stored score that carries
+# a history deduction, and the refactoring impact figures, move.
+#
# v31: Pascal opts into assertion detection (``assert_call_kinds``): DUnit's
# ``Check``/``CheckEquals``/``Fail`` family (a new ``asserts/lexicon.py`` row,
# broad tier) and DUnitX's ``Assert.*`` plus the RTL's own ``Assert(cond, msg)``
@@ -303,7 +307,7 @@ log = structlog.get_logger(__name__)
# forms. Files that were counted untested and are not become tested, which
# moves untested-hotspot findings and the scores that carry them, on every
# language with a prefix or spec convention rather than Ruby alone.
-HEALTH_ANALYZER_VERSION = 31
+HEALTH_ANALYZER_VERSION = 32
def walked_functions(
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 548d61030..f0b2bf5e7 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -215,8 +215,8 @@ class RefactoringSuggestion:
plan: dict[str, Any]
# The signals that justify the suggestion (LCOM4, WMC, clone ranges, ...).
evidence: dict[str, Any]
- # Health score the refactoring would recover if applied (the deduction of
- # the source biomarker finding). >= 0.
+ # Health score the refactoring would recover if applied: the deduction of
+ # the source biomarker finding, plus any history deduction it releases. >= 0.
impact_delta: float
# Effort estimate — "S" | "M" | "L" | "XL" (from the target's size).
effort_bucket: str
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
index c3ee066fe..92beb7710 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
@@ -12,9 +12,11 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence
+from dataclasses import replace
import structlog
+from ..scoring import HISTORY_CATEGORY, biomarker_category, deduction_split, history_cap
from .models import CONFIDENCE_LEVELS, RefactoringContext, RefactoringSuggestion
log = structlog.get_logger(__name__)
@@ -81,13 +83,14 @@ def detect_refactorings(
every suggestion.
"""
floor_idx = _confidence_floor_index(min_confidence)
+ structure, history = deduction_split(ctx.findings)
out: list[RefactoringSuggestion] = []
for detector in registered_detectors(disabled=disabled):
try:
for suggestion in detector.detect(ctx):
if floor_idx and _confidence_rank(suggestion.confidence) < floor_idx:
continue
- out.append(suggestion)
+ out.append(_with_released_history(suggestion, structure, history))
except Exception as exc:
# One bad detector must not break the health pass; degrade to
# "no suggestion" for this file.
@@ -95,6 +98,19 @@ def detect_refactorings(
return out
+def _with_released_history(
+ suggestion: RefactoringSuggestion, structure: float, history: float
+) -> RefactoringSuggestion:
+ """Add the history deduction a code-shape fix releases by lowering the history cap."""
+ impact = suggestion.impact_delta
+ if impact <= 0 or history <= 0:
+ return suggestion
+ if biomarker_category(suggestion.source_biomarker) == HISTORY_CATEGORY:
+ return suggestion
+ released = max(0.0, history - history_cap(structure - impact))
+ return replace(suggestion, impact_delta=round(impact + released, 3))
+
+
def _confidence_rank(level: str) -> int:
"""Ordinal of a confidence label; unknown labels rank at the floor (0)."""
try:
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index ec86a1504..f04b40c97 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -6,7 +6,7 @@ cap. Final score is clamped to [1.0, 10.0].
The recalibrated category caps (plan §3.1):
- organizational -> -3.5 # was -1.0 (process-aware signals)
+ organizational -> -3.5 # ceiling; the live cap is history_cap()
structural_complexity -> -2.5 # was -3.5
test_coverage -> -2.0
size_and_complexity -> -1.5 # was -2.0
@@ -68,6 +68,33 @@ CATEGORY_CAPS: dict[str, float] = {
"error_handling": 0.5,
}
+# The one defect category derived from git rather than from the code itself.
+# Splitting on it is what lets a surface say which half of the score moved: a
+# refactor changes the structure half, and nothing a reader types today changes
+# the history half.
+HISTORY_CATEGORY = "organizational"
+
+# History markers read how a file has been changed, not what it is, so on their
+# own they measure activity: a simple file that changes often is busy, not
+# broken. History therefore amplifies code risk rather than standing alone: its
+# cap is 1.0 plus one point per point of structure deduction (every other defect
+# category, already capped), up to the category's 3.5. A file with no code-shape
+# finding keeps at least 9.0. Checked against the defect benchmark: no
+# measurable predictive cost. The weights are unchanged; fit the base and slope
+# with them in the next calibration pass.
+HISTORY_CAP_BASE: float = 1.0
+HISTORY_CAP_PER_STRUCTURE: float = 1.0
+
+
+def history_cap(structure: float) -> float:
+ """The most git history may deduct from a file whose other defect
+ categories deduct *structure* points."""
+ return min(
+ CATEGORY_CAPS[HISTORY_CATEGORY],
+ HISTORY_CAP_BASE + HISTORY_CAP_PER_STRUCTURE * max(structure, 0.0),
+ )
+
+
# Per-biomarker deduction by severity. The scorer caps the per-category
# total at the value in ``CATEGORY_CAPS``.
_SEVERITY_DEDUCTION: dict[Severity, float] = {
@@ -572,12 +599,17 @@ def _score_dimension(
weight_fn: Callable[[str], float],
category_fn: Callable[[str], str],
caps: dict[str, float],
+ conditioned_cap: tuple[str, Callable[[float], float]] | None = None,
) -> 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.
+
+ *conditioned_cap* ``(category, cap_fn)`` replaces that one category's cap
+ with ``cap_fn(sum of every other category's capped total)``; only the
+ defect dimension uses it, for the history category.
"""
raw: dict[str, list[tuple[int, float]]] = {}
for idx, r in enumerate(results_list):
@@ -592,8 +624,17 @@ def _score_dimension(
per_result = [0.0] * len(results_list)
total = 0.0
+ cap_for: dict[str, float] = {}
+ if conditioned_cap is not None:
+ cond_cat, cap_fn = conditioned_cap
+ others = sum(
+ min(sum(d for _, d in entries), caps.get(cat, 1.0))
+ for cat, entries in raw.items()
+ if cat != cond_cat
+ )
+ cap_for[cond_cat] = cap_fn(others)
for cat, entries in raw.items():
- cap = caps.get(cat, 1.0)
+ cap = cap_for.get(cat, caps.get(cat, 1.0))
cat_sum = sum(d for _, d in entries)
if cat_sum <= cap:
for idx, d in entries:
@@ -666,7 +707,11 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | No
]
defect_results = [results_list[i] for i in defect_idx]
defect_score, defect_sub = _score_dimension(
- defect_results, biomarker_weight, biomarker_category, CATEGORY_CAPS
+ defect_results,
+ biomarker_weight,
+ biomarker_category,
+ CATEGORY_CAPS,
+ conditioned_cap=(HISTORY_CATEGORY, history_cap),
)
defect_deductions = [0.0] * len(results_list)
for sub_i, orig_i in enumerate(defect_idx):
@@ -700,13 +745,6 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | No
return scores, defect_deductions
-# The one defect category derived from git rather than from the code itself.
-# Splitting on it is what lets a surface say which half of the score moved: a
-# refactor changes the structure half, and nothing a reader types today changes
-# the history half.
-HISTORY_CATEGORY = "organizational"
-
-
def deduction_split(findings: Iterable[Any]) -> tuple[float, float]:
"""``(structure, history)`` defect deduction over already-scored findings.
diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.py
index 2ef9e45a5..52204e680 100644
--- a/tests/unit/change_health/test_regressions.py
+++ b/tests/unit/change_health/test_regressions.py
@@ -196,8 +196,11 @@ def test_deleting_one_finding_does_not_report_its_neighbours_as_worsened():
head = _scored(specs[1:])
# The premise: the cap binds on both sides and the survivors' impacts rise.
- assert sum(f.health_impact for f in base) == pytest.approx(3.5)
- assert sum(f.health_impact for f in head) == pytest.approx(3.5)
+ # History-only findings, so the cap is the structure-conditioned one at 0.
+ from repowise.core.analysis.health.scoring import history_cap
+
+ assert sum(f.health_impact for f in base) == pytest.approx(history_cap(0.0))
+ assert sum(f.health_impact for f in head) == pytest.approx(history_cap(0.0))
assert head[0].health_impact > base[1].health_impact
result = FindingMatcher().match(base, head)
diff --git a/tests/unit/health/test_aggregation_contract.py b/tests/unit/health/test_aggregation_contract.py
index 1c9ab6fe6..a7de8d712 100644
--- a/tests/unit/health/test_aggregation_contract.py
+++ b/tests/unit/health/test_aggregation_contract.py
@@ -256,6 +256,18 @@ def test_a_capped_category_is_flagged_and_holds_its_applied_total() -> None:
assert category["capped"] is True
+def test_the_history_category_reports_the_cap_it_was_scored_under() -> None:
+ """The history cap follows the structure half, so the breakdown must show
+ the live cap (1.0 + structure), not the 3.5 ceiling it never reached."""
+ from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, history_cap
+
+ shape = _Finding(_category_biomarker("structural_complexity"), health_impact=0.5)
+ hist = _Finding("prior_defect", severity="critical", health_impact=1.5)
+ by_cat = {c["category"]: c for c in score_breakdown([shape, hist])["categories"]}
+ assert by_cat[HISTORY_CATEGORY]["cap"] == round(history_cap(0.5), 2) == 1.5
+ assert by_cat[HISTORY_CATEGORY]["capped"] is True
+
+
def test_a_category_with_no_findings_is_absent_rather_than_zero_filled() -> None:
biomarker = _category_biomarker("structural_complexity")
out = score_breakdown([_Finding(biomarker, health_impact=1.0)])
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index 99798173d..aec791c70 100644
--- a/tests/unit/health/test_model_version_coupling.py
+++ b/tests/unit/health/test_model_version_coupling.py
@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (
# The three stamps as they stand together. Moving either identity model means
# moving the analyzer with it, and updating this tuple in the same commit.
-_STAMPS = (31, 2, 2)
+_STAMPS = (32, 2, 2)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:
diff --git a/tests/unit/health/test_refactoring_registry.py b/tests/unit/health/test_refactoring_registry.py
index e334fb798..8303c4ef3 100644
--- a/tests/unit/health/test_refactoring_registry.py
+++ b/tests/unit/health/test_refactoring_registry.py
@@ -70,3 +70,29 @@ def test_unknown_floor_is_no_floor(_one_detector):
def test_disabled_detector_emits_nothing(_one_detector):
out = detect_refactorings(_ctx(), disabled=["fake_all_confidences"])
assert out == []
+
+
+class _ImpactDetector(RefactoringDetector):
+ name = "fake_impact"
+
+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
+ s = _suggestion("high", name=self.name)
+ s.impact_delta = 0.8
+ s.source_biomarker = "complex_method"
+ return [s]
+
+
[email protected](("history", "expected"), [(1.8, 1.6), (0.5, 0.8)])
+def test_recovered_impact_counts_the_history_the_fix_releases(monkeypatch, history, expected):
+ """History held at its cap (1.0 + 0.8) falls to the 1.0 cap once the 0.8
+ code finding goes, so the fix recovers 1.6; history under the new cap
+ releases nothing."""
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(registry, "_REGISTRY", [_ImpactDetector()])
+ ctx = _ctx()
+ ctx.findings = [
+ SimpleNamespace(biomarker_type="complex_method", health_impact=0.8),
+ SimpleNamespace(biomarker_type="prior_defect", health_impact=history),
+ ]
+ assert detect_refactorings(ctx)[0].impact_delta == pytest.approx(expected)
diff --git a/tests/unit/health/test_scoring_dimensions.py b/tests/unit/health/test_scoring_dimensions.py
index cfd3a9bd7..b1a099ba4 100644
--- a/tests/unit/health/test_scoring_dimensions.py
+++ b/tests/unit/health/test_scoring_dimensions.py
@@ -7,6 +7,12 @@ 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.
+
+One deliberate revision since the split: the history (organizational) category
+is capped at ``min(3.5, 1.0 + structure)`` rather than a flat 3.5, where
+``structure`` is the file's capped deduction from every other category. The
+frozen reference carries that rule with its own frozen constants, so the gate
+still pins the whole algorithm.
"""
from __future__ import annotations
@@ -37,6 +43,10 @@ _LEGACY_CATEGORY_CAPS = {
"error_handling": 0.5,
}
+# The structure-conditioned history cap, frozen here.
+_HISTORY_CAP_BASE = 1.0
+_HISTORY_CAP_PER_STRUCTURE = 1.0
+
_LEGACY_SEVERITY_DEDUCTION = {
Severity.LOW: 0.3,
Severity.MEDIUM: 0.7,
@@ -117,9 +127,16 @@ def _legacy_score_file(results: list[BiomarkerResult]) -> float:
weighted = base * _LEGACY_WEIGHT_MULTIPLIER.get(r.biomarker_type, 1.0)
raw[cat] = raw.get(cat, 0.0) + weighted
+ structure = sum(
+ min(cat_sum, _LEGACY_CATEGORY_CAPS.get(cat, 1.0))
+ for cat, cat_sum in raw.items()
+ if cat != "organizational"
+ )
total = 0.0
for cat, cat_sum in raw.items():
cap = _LEGACY_CATEGORY_CAPS.get(cat, 1.0)
+ if cat == "organizational":
+ cap = min(cap, _HISTORY_CAP_BASE + _HISTORY_CAP_PER_STRUCTURE * structure)
total += min(cat_sum, cap)
return max(1.0, min(10.0, 10.0 - total))
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index a061a532a..f330a42ef 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -229,10 +229,41 @@ def test_error_handling_cap_bounds_stream():
def test_organizational_cap_bounds_stream():
- """The organizational cap (-3.5) bounds a high-volume finding stream. With
- developer_congestion defect-calibrated down to 0.5 (it was a HEAD-leakage
- artifact), three CRITICALs deduct under the cap rather than saturating it."""
+ """History alone is bounded by the structure-conditioned cap, not the 3.5
+ ceiling. Three CRITICAL developer_congestion findings weigh 3.0 (2.0 x 0.5
+ each); on a file with no code-shape finding the history cap is 1.0 + 1.0 x 0,
+ so the file keeps 9.0 (7.0 under the old flat 3.5 cap)."""
findings = [_result("developer_congestion", Severity.CRITICAL) for _ in range(3)]
scores, _ = score_file(findings)
- # 3 * 2.0 * 0.5 = 3.0 weighted (< 3.5 cap) -> score = 7.0
- assert scores["defect"] == 7.0
+ assert scores["defect"] == 9.0
+
+
+def test_history_cap_follows_structure():
+ """Each point of code-shape deduction lets history deduct one more, to 3.5."""
+ history = [_result("prior_defect", Severity.CRITICAL) for _ in range(3)] # 6.0 raw
+ # structure 2.5 (brain_method x 3 -> structural cap) -> history cap 3.5
+ shaped = [*history, *(_result("brain_method", Severity.CRITICAL) for _ in range(3))]
+ scores, _ = score_file(shaped)
+ assert round(scores["defect"], 6) == round(10.0 - 2.5 - 3.5, 6)
+ # structure 0.847 (one MEDIUM complex_method) -> history cap 1.847
+ mid = [*history, _result("complex_method", Severity.MEDIUM)]
+ scores, ded = score_file(mid)
+ assert round(scores["defect"], 6) == round(10.0 - 0.847 - 1.847, 6)
+ # impacts still sum to the deduction the score was computed from
+ assert round(sum(ded), 6) == round(0.847 + 1.847, 6)
+
+
+def test_improving_code_never_lowers_score():
+ """Monotone in structure at fixed history: removing a code-shape finding
+ can only raise the score."""
+ history = [_result("change_entropy", Severity.HIGH) for _ in range(3)]
+ worse = [*history, _result("large_method", Severity.HIGH)]
+ better = list(history)
+ assert score_file(better)[0]["defect"] >= score_file(worse)[0]["defect"]
+
+
+def test_history_cap_constants_locked():
+ """The structure-conditioned history cap is a calibrated-scale constant pair."""
+ from repowise.core.analysis.health.scoring import HISTORY_CAP_BASE, HISTORY_CAP_PER_STRUCTURE
+
+ assert (HISTORY_CAP_BASE, HISTORY_CAP_PER_STRUCTURE) == (1.0, 1.0)