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
"""Snapshot tests guarding scoring stability across refactors.
Locks the published per-category caps, per-severity deductions, the
per-biomarker weight multipliers, and the biomarker -> category mapping.
A change to any of these tables shifts every file's score on every repo
using repowise, so this test exists to force the reviewer to acknowledge
the impact before landing.
If a deliberate retune lands, regenerate the snapshot by updating the
``_EXPECTED_*`` constants below in the same PR - never silently.
"""
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 (
_BIOMARKER_CATEGORY,
_BIOMARKER_WEIGHT_MULTIPLIER,
_SEVERITY_DEDUCTION,
CATEGORY_CAPS,
score_file,
)
_EXPECTED_CATEGORY_CAPS = {
"organizational": 3.5,
"structural_complexity": 2.5,
"test_coverage": 2.0,
# Continuous coverage-gradient deduction - own capped category so it stays
# additive to (and bounded independently of) the binary coverage gates.
"test_coverage_gradient": 2.0,
"size_and_complexity": 1.5,
"duplication": 1.0,
"test_quality": 0.5,
# Error-handling anti-patterns - advisory maintainability signal in its
# own bounded category (AUC-neutral on the T0 benchmark by design).
"error_handling": 0.5,
}
_EXPECTED_SEVERITY_DEDUCTION = {
Severity.LOW: 0.3,
Severity.MEDIUM: 0.7,
Severity.HIGH: 1.2,
Severity.CRITICAL: 2.0,
}
# Defect-calibrated offline (2026-05-29) against a 15-repo / 5-language corpus,
# scoring each file at T0 with an L2-logistic + explicit NLOC control. These are
# learned constants, not hand priors - regenerate via
# local-stash/calibrate_health_weights.py if the corpus changes. See the comment
# block on scoring._BIOMARKER_WEIGHT_MULTIPLIER for the "balanced" mapping policy.
_EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
# calibrated predictors
"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 history - neutral weight: interpretable finding, calibrated
# coef ~0 (redundant with change_entropy/churn), Popt gain within noise.
"prior_defect": 1.0,
# kept at prior (benchmark could not fairly measure)
"untested_hotspot": 1.3,
"churn_risk": 1.2,
"code_age_volatility": 1.1,
# floored - fired widely but weak/non-predictive at T0
"developer_congestion": 0.5,
"low_cohesion": 0.5,
"primitive_obsession": 0.5,
"dry_violation": 0.5,
"knowledge_loss": 0.4,
# Error-handling anti-patterns - maintainability flag excluded from the
# calibration roster; floored weight keeps LOW findings at 0.15 each.
"error_handling": 0.5,
# Governance biomarkers (informational - surfaced as findings, not fed back
# into the score pass, which has already run upstream).
"contradictory_decision": 1.0,
"stale_governance": 0.9,
"ungoverned_hotspot": 0.7,
}
_EXPECTED_BIOMARKER_CATEGORY = {
"brain_method": "structural_complexity",
"low_cohesion": "structural_complexity",
"god_class": "structural_complexity",
"nested_complexity": "structural_complexity",
"repeated_nesting": "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",
"untested_complexity": "test_coverage",
"coverage_gradient": "test_coverage_gradient",
"developer_congestion": "organizational",
"knowledge_loss": "organizational",
"hidden_coupling": "organizational", # advisory: moves no score
"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",
# Moves no score: its only dimension is ``advisory``, so ``score_file``
# filters it out before any category is summed.
"assertion_free_test": "test_quality",
"mock_saturated_test": "test_quality",
"error_handling": "error_handling",
# Phase 4B governance biomarkers.
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
"contradictory_decision": "organizational",
"apex_soql_injection": "apex",
"apex_missing_sharing": "apex",
"apex_hardcoded_id": "apex",
"apex_see_all_data": "apex",
"cobol_unstructured_flow": "cobol",
}
def test_category_caps_locked():
assert CATEGORY_CAPS == _EXPECTED_CATEGORY_CAPS
def test_severity_deductions_locked():
assert _SEVERITY_DEDUCTION == _EXPECTED_SEVERITY_DEDUCTION
def test_biomarker_weight_multipliers_locked():
assert _BIOMARKER_WEIGHT_MULTIPLIER == _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER
def test_biomarker_to_category_locked():
assert _BIOMARKER_CATEGORY == _EXPECTED_BIOMARKER_CATEGORY
def _result(biomarker: str, severity: Severity) -> BiomarkerResult:
return BiomarkerResult(
biomarker_type=biomarker,
severity=severity,
function_name=None,
line_start=None,
line_end=None,
details={},
reason="",
)
def test_known_fixture_score_is_stable():
"""A handcrafted finding set should produce a known, fixed score."""
findings = [
_result("low_cohesion", Severity.CRITICAL),
_result("nested_complexity", Severity.HIGH),
_result("complex_method", Severity.MEDIUM),
_result("untested_hotspot", Severity.HIGH),
_result("knowledge_loss", Severity.LOW),
]
scores, _ = score_file(findings)
# Each category saturates as A * (1 - exp(-raw / A)), A = 3.09 x its cap:
# structural = cohesion(2.0*0.5) + nested(1.2*1.34) = 2.608 -> 2.213
# size_and_cx = complex_method 0.7 * 1.21 = 0.847 -> 0.774
# coverage = untested_hotspot 1.2 * 1.3 = 1.56 -> 1.379
# organizational = knowledge_loss 0.3 * 0.4 = 0.12 (hard cap, not reached)
assert round(scores["defect"], 3) == 5.514
def test_category_curve_bounds_score():
"""Many critical structural findings saturate below 3.09 x the 2.5 cap."""
findings = [_result("low_cohesion", Severity.CRITICAL) for _ in range(10)]
scores, _ = score_file(findings)
# raw 10.0, A = 7.725 -> 5.608
assert round(scores["defect"], 3) == 4.392
def test_continuous_deduction_override_is_used_and_capped():
"""A ``deduction`` override replaces the severity table and saturates.
``coverage_gradient`` deducts 4.0 x uncovered_fraction in its own
``test_coverage_gradient`` category (cap 2.0, so A = 6.18). At 25% uncovered
the raw deduction is 1.0 -> 0.923; at 80% it is 3.2 -> 2.498.
"""
quarter = BiomarkerResult(
biomarker_type="coverage_gradient",
severity=Severity.LOW,
function_name=None,
line_start=None,
line_end=None,
details={},
reason="",
deduction=4.0 * 0.25,
)
scores, ded = score_file([quarter])
assert round(scores["defect"], 3) == 9.077
assert [round(d, 3) for d in ded] == [0.923]
deep = BiomarkerResult(
biomarker_type="coverage_gradient",
severity=Severity.HIGH,
function_name=None,
line_start=None,
line_end=None,
details={},
reason="",
deduction=4.0 * 0.80,
)
scores2, ded2 = score_file([deep])
assert round(scores2["defect"], 3) == 7.502
assert [round(d, 3) for d in ded2] == [2.498]
def test_error_handling_cap_bounds_stream():
"""error_handling findings weigh 0.15 each (LOW 0.3 x 0.5 weight) in their
own category, which saturates toward 3.09 x its 0.5 cap whatever the count."""
two = [_result("error_handling", Severity.LOW) for _ in range(2)]
scores, deductions = score_file(two)
assert round(scores["defect"], 3) == 9.727 # raw 0.3 -> 0.273
assert [round(d, 3) for d in deductions] == [0.136, 0.136]
many = [_result("error_handling", Severity.LOW) for _ in range(10)]
scores2, _ = score_file(many)
assert round(scores2["defect"], 3) == 9.04 # raw 1.5 -> 0.96
def test_organizational_cap_bounds_stream():
"""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)
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."""
# 2.0 + 0.25 x 10.0 = 4.5 de-stacked
history = [_result("prior_defect", Severity.CRITICAL) for _ in range(6)]
# structure 2.486 (low_cohesion x 3, raw 3.0 saturated) -> history cap 3.486
shaped = [*history, *(_result("low_cohesion", Severity.CRITICAL) for _ in range(3))]
scores, _ = score_file(shaped)
assert round(scores["defect"], 3) == 4.028
# structure 0.774 (one MEDIUM complex_method) -> history cap 1.774
mid = [*history, _result("complex_method", Severity.MEDIUM)]
scores, ded = score_file(mid)
assert round(scores["defect"], 3) == 7.452
# impacts still sum to the deduction the score was computed from
assert round(sum(ded), 6) == round(10.0 - scores["defect"], 6)
def test_history_markers_destack():
"""The largest history finding counts whole, every other one at a quarter."""
shaped = [_result("low_cohesion", Severity.CRITICAL) for _ in range(3)] # structure 2.486
history = [
_result("prior_defect", Severity.CRITICAL), # 2.0
_result("change_entropy", Severity.HIGH), # 1.2 x 1.51 = 1.812
]
scores, ded = score_file([*shaped, *history])
# 2.0 + 0.25 x 1.812 = 2.453, under the 3.486 cap
assert round(scores["defect"], 3) == 5.061
assert [round(d, 6) for d in ded[3:]] == [2.0, 0.453]
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)