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): scale coverage deductions by uncovered fraction (#314)

Raghav Chamadiyab691c9b07160
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 4595ac69f..94aeb4430 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -28,14 +28,15 @@ most:
| Category | Cap | Biomarkers |
|------------------------|-------|------------|
-| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter |
+| 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 |
| 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 (cont.) | −2.0 | coverage_gradient |
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
| Test quality | −0.5 | large_assertion_block, duplicated_assertion_block |
-Twenty-three biomarkers across six categories. `function_hotspot` and
+Twenty-five biomarkers across the categories above. `function_hotspot` and
`code_age_volatility` are blame-based and sit in the organizational bucket —
both are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line
blame index is built.
@@ -113,6 +114,12 @@ dependents. The textbook "write tests before refactoring" case.
**coverage_gap** — Non-test files with meaningful uncovered surface.
Severity grades along coverage depth.
+**coverage_gradient** — A continuous coverage deduction that scales with the
+uncovered fraction (`4.0 × (1 − line_coverage_pct/100)`, capped), so files stay
+penalised in proportion to how much code is untested rather than only when they
+fall below a hard threshold. Fires across the whole 0–100% range for files with
+known coverage; silent (no imputation) where coverage was never ingested.
+
**developer_congestion** — Too many active authors touching the same file.
Usually an ownership problem dressed up as a code problem.
@@ -219,8 +226,9 @@ last lets you feed coverage from any runner once it's mapped to one shape:
"total_coverable_lines": 40 } } }
```
-Coverage data feeds into `untested_hotspot` and `coverage_gap`, and shows up
-on the `/repos/<id>/health/coverage` dashboard.
+Coverage data feeds into `untested_hotspot`, `coverage_gap`, and
+`coverage_gradient` (a continuous deduction proportional to the uncovered
+fraction), and shows up on the `/repos/<id>/health/coverage` dashboard.
## Refactoring targets
@@ -299,7 +307,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
| Feature | Repowise | CodeScene | DeepSource | Sourcery |
|----------------------------------|:--:|:--:|:--:|:--:|
-| Code health score (1–10) | ✅ 24 biomarkers | ✅ 25–30 | ❌ | ❌ |
+| Code health score (1–10) | ✅ 25 biomarkers | ✅ 25–30 | ❌ | ❌ |
| Brain Method detection | ✅ | ✅ | ❌ | ❌ |
| Low cohesion (LCOM4) / god class | ✅ | ✅ | ❌ | ❌ |
| Test coverage intelligence | ✅ LCOV/Cobertura/Clover/JSON | ❌ | ❌ | ❌ |
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index c2e1d4230..14a32b047 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -317,7 +317,7 @@ higher than dormant ones.
---
-## 5. The 24 biomarkers and their categories
+## 5. The 25 biomarkers and their categories
Each biomarker is a stateless class implementing the `Biomarker` Protocol
from `biomarkers/base.py`:
@@ -334,6 +334,7 @@ class Biomarker(Protocol):
| 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 |
| 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 (cont.) | −2.0 | coverage_gradient |
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
| Test quality | −0.5 | large_assertion_block, duplicated_assertion_block |
@@ -372,6 +373,25 @@ value — "this file was bug-fixed N times recently" is immediately actionable,
and it uniquely flags a few files the other signals miss — not for a measured
accuracy lift.
+`coverage_gradient` makes the test-coverage signal **continuous**. The two
+binary coverage gates (`untested_hotspot`, `coverage_gap`) only fire below hard
+thresholds (≈40–60% line coverage), so on a well-tested codebase — where most
+files sit at 85–99% — the score is effectively blind to coverage even though the
+uncovered fraction still carries defect signal. `coverage_gradient` deducts
+health in direct proportion to that fraction: `4.0 × (1 − line_coverage_pct/100)`
+health points, clamped by its category cap (binding at ≥50% uncovered). It uses
+the `deduction` override on `BiomarkerResult` — a continuous magnitude that
+replaces the discrete severity → deduction table for that finding — so it stays
+**linear and per-finding attributable** (the `health_impact` contract holds). It
+is **silent when no coverage report was ingested** (`line_coverage_pct is None`):
+absent coverage is never imputed as uncovered. It lives in its own capped
+category (`test_coverage_gradient`, −2.0) so the additive continuous signal
+neither squeezes nor is squeezed by the binary gates, and it skips test files.
+Calibrated offline against the defect corpus, it recovers **+0.043 corpus AUC
+[95% CI +0.023, +0.061]** on the covered subset (≈65% of the continuous-feature
+ceiling), Popt-neutral, and is exactly zero on repos without ingested coverage —
+a purely additive improvement.
+
`low_cohesion` (LCOM4) and `god_class` are the two **class-level**
structural smells. They read `ctx.class_metrics`, the per-class aggregates
the walker now emits alongside per-function metrics (see §5.2).
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
index 9c0ab322f..6aa20124e 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -36,6 +36,17 @@ Test coverage (cap −2.0):
- `untested_hotspot` — hotspot × low coverage × many dependents.
- `coverage_gap` — non-test files with meaningful uncovered surface.
+Test coverage — continuous (cap −2.0, own category `test_coverage_gradient`):
+- `coverage_gradient` — a per-file deduction that scales **continuously** with
+ the uncovered fraction (`4.0 × (1 − line_coverage_pct/100)`, capped) for files
+ with KNOWN coverage; silent when coverage was never ingested (absent ≠
+ uncovered). Unlike the binary gates above it fires across the whole 0–100%
+ range, so well-tested files at 85–99% still carry proportional signal. Uses
+ the `deduction` override on `BiomarkerResult` (continuous magnitude in place of
+ the discrete severity table), kept in its own capped category so it neither
+ squeezes nor is squeezed by the binary gates. Calibrated offline: +0.043 corpus
+ AUC [95% CI +0.023, +0.061] on the covered subset, Popt-neutral.
+
Organizational (cap −3.5):
- `developer_congestion` — too many active authors competing on a file.
- `knowledge_loss` — primary authors no longer active (de-rated to 0.4).
@@ -104,7 +115,12 @@ table alone would allow.
`BiomarkerResult` carries severity, function name, line span, a `details`
dict (JSON-serialised into `HealthFinding.details_json` for the UI), and a
-`reason` string. `health_impact` is filled in by the scorer.
+`reason` string. `health_impact` is filled in by the scorer. An optional
+`deduction` field carries a continuous deduction magnitude (health points,
+pre-weight/pre-cap); when set the scorer uses it instead of the discrete
+severity → deduction table, letting a biomarker (e.g. `coverage_gradient`)
+express a per-finding signal that varies continuously while staying linear and
+attributable.
## Performance characteristics
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index b5041836e..d2688202c 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -99,6 +99,14 @@ class BiomarkerResult:
line_end: int | None
details: dict[str, Any]
reason: str = ""
+ # Optional continuous deduction override (health points, pre-weight,
+ # pre-category-cap). When set, the scorer uses this magnitude instead of
+ # the discrete ``severity`` → deduction table — letting a biomarker carry a
+ # signal whose strength varies continuously per finding (e.g. a coverage
+ # deduction that scales with the uncovered fraction). ``severity`` is still
+ # carried for display/filtering. Stays fully per-finding attributable, so
+ # the linear ``health_impact`` contract holds.
+ deduction: float | None = None
class Biomarker(Protocol):
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
new file mode 100644
index 000000000..468ccbb8e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
@@ -0,0 +1,106 @@
+"""Coverage Gradient - a continuous, per-file test-coverage deduction.
+
+The two binary coverage biomarkers (``untested_hotspot`` / ``coverage_gap``)
+only fire below hard thresholds (~40-60% line coverage), so on well-tested
+codebases - where most files sit at 85-99% - the score is effectively blind to
+coverage even though the *uncovered fraction* still carries real defect signal.
+
+This biomarker makes the coverage signal **continuous and monotonic**: for any
+file with KNOWN line coverage it deducts health in proportion to the uncovered
+fraction. The deduction is a plain, fully attributable arithmetic function of
+one number (``1 - line_coverage_pct/100``), so it stays linear / explainable and
+adds zero walk cost (it reads already-parsed coverage).
+
+- Deduction (health points) = ``_WEIGHT x uncovered_fraction`` - clamped by the
+ ``test_coverage_gradient`` category cap, which binds once a file is ≥50%
+ uncovered. ``_WEIGHT`` was calibrated offline against the defect corpus.
+- **Absent coverage ≠ zero coverage.** When no coverage report was ingested
+ (``line_coverage_pct is None``) the biomarker is silent - it never imputes
+ uncovered for missing data.
+- Test files are exempt (we don't penalise ``test_foo.py`` for being uncovered),
+ matching ``coverage_gap``.
+
+It is intentionally distinct from the binary gates and lives in its own capped
+category so the additive continuous signal neither squeezes nor is squeezed by
+the has-tests / hotspot gates.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+# Calibrated offline (2026-05-30) on the 13-repo defect corpus: a per-file
+# deduction of 4.0 x uncovered_fraction recovers +0.043 corpus AUC
+# [95% CI +0.023, +0.061] on the covered subset (~65% of the continuous-feature
+# ceiling), Popt-neutral. Reproduced by
+# repowise-bench/health-defect/coverage_scoring_experiment.py (w=4, cap=2.0).
+_WEIGHT = 4.0
+
+# Display-only severity bands (the deduction comes from the continuous
+# ``deduction`` override, not the severity table).
+_COVERAGE_HIGH = 40.0
+_COVERAGE_MEDIUM = 70.0
+
+
+def _looks_like_test_path(path: str) -> bool:
+ p = path.replace("\\", "/").lower()
+ return (
+ "/test/" in p
+ or "/tests/" in p
+ or "/__tests__/" in p
+ or p.startswith(("test/", "tests/", "__tests__/"))
+ or p.endswith(
+ ("_test.py", "_test.go", ".test.ts", ".test.tsx", ".test.js", ".spec.ts", ".spec.js")
+ )
+ or p.rsplit("/", 1)[-1].startswith("test_")
+ )
+
+
+class CoverageGradientDetector:
+ name = "coverage_gradient"
+ category = "test_coverage_gradient"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ cov = ctx.line_coverage_pct
+ if cov is None:
+ # No coverage data -> silent. Absent is not the same as uncovered.
+ return []
+ if _looks_like_test_path(ctx.file_path):
+ return []
+
+ uncovered_fraction = max(0.0, (100.0 - float(cov)) / 100.0)
+ if uncovered_fraction <= 0.0:
+ return []
+
+ if cov < _COVERAGE_HIGH:
+ severity = Severity.HIGH
+ elif cov < _COVERAGE_MEDIUM:
+ severity = Severity.MEDIUM
+ else:
+ severity = Severity.LOW
+
+ deduction = _WEIGHT * uncovered_fraction
+ uncovered_pct = round(uncovered_fraction * 100.0)
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=severity,
+ function_name=None,
+ line_start=None,
+ line_end=None,
+ details={
+ "line_coverage_pct": cov,
+ "branch_coverage_pct": ctx.branch_coverage_pct,
+ "uncovered_fraction": round(uncovered_fraction, 4),
+ },
+ reason=(
+ f"{uncovered_pct}% of lines uncovered ({cov:.0f}% line coverage) - "
+ f"uncovered code carries proportionally more defect risk"
+ ),
+ deduction=deduction,
+ )
+ ]
+
+
+BIOMARKER = CoverageGradientDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 967095e10..a22173a6b 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -21,6 +21,7 @@ from .code_age_volatility import CodeAgeVolatilityDetector
from .complex_conditional import ComplexConditionalDetector
from .complex_method import ComplexMethodDetector
from .coverage_gap import CoverageGapDetector
+from .coverage_gradient import CoverageGradientDetector
from .developer_congestion import DeveloperCongestionDetector
from .dry_violation import DryViolationDetector
from .duplicated_assertion_block import DuplicatedAssertionBlockDetector
@@ -49,6 +50,7 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
DryViolationDetector, # type: ignore[list-item]
UntestedHotspotDetector, # type: ignore[list-item]
CoverageGapDetector, # type: ignore[list-item]
+ CoverageGradientDetector, # type: ignore[list-item]
DeveloperCongestionDetector, # type: ignore[list-item]
KnowledgeLossDetector, # type: ignore[list-item]
HiddenCouplingDetector, # type: ignore[list-item]
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index a41a0d12a..23eaec471 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -29,9 +29,18 @@ CATEGORY_CAPS: dict[str, float] = {
"organizational": 3.5,
"structural_complexity": 2.5,
"test_coverage": 2.0,
+ # Continuous coverage-gradient deduction (scales with the uncovered
+ # fraction). Kept in its OWN capped category, separate from the binary
+ # ``test_coverage`` gates, so the additive, monotonic coverage signal is
+ # bounded on its own terms and never squeezed by - or squeezes - the
+ # has-tests / hotspot gates. Calibrated offline: a per-file deduction of
+ # 4.0 x uncovered_fraction (this cap binding at ≥50% uncovered) recovers
+ # +0.043 corpus AUC [95% CI +0.023, +0.061] on the covered subset,
+ # Popt-neutral, and is exactly zero where coverage was never ingested.
+ "test_coverage_gradient": 2.0,
"size_and_complexity": 1.5,
"duplication": 1.0,
- # Test-quality smells are mild, advisory signals — a small cap keeps a
+ # Test-quality smells are mild, advisory signals - a small cap keeps a
# noisy test file from dominating its own health score.
"test_quality": 0.5,
}
@@ -51,19 +60,19 @@ _SEVERITY_DEDUCTION: dict[Severity, float] = {
#
# CALIBRATED OFFLINE (2026-05-29) against a 13-repo, 5-language defect corpus
# (Python/TS/JS/Rust/Go; 830 files, 216 bug-fix-bearing). Methodology: each
-# file scored at the pre-window commit T0 (no HEAD→window leakage), then an
+# file scored at the pre-window commit T0 (no HEAD->window leakage), then an
# L2-regularized logistic regression of "received a bug-fix in (T0,T1]" on the
-# per-biomarker hits PLUS an explicit NLOC control column — so each weight
+# per-biomarker hits PLUS an explicit NLOC control column - so each weight
# reflects the biomarker's defect lift *beyond file size*. Cross-project
-# (leave-one-repo-out) pooled OOF AUC ≈ 0.70. The fit is reproduced by
+# (leave-one-repo-out) pooled OOF AUC ~ 0.70. The fit is reproduced by
# `local-stash/calibrate_health_weights.py`; the runtime stays pure-
-# deterministic / zero-LLM — only these learned constants ship.
+# deterministic / zero-LLM - only these learned constants ship.
#
# Mapping policy ("balanced"): positive, well-measured predictors are scaled
# into [1.0, 1.8] ∝ coefficient; biomarkers that fired widely but were weak/
# non-predictive at T0 are floored to 0.5 (kept as mild maintainability/parity
# signals, not disabled); biomarkers the benchmark could NOT measure (no
-# coverage ingested → untested_hotspot/coverage_gap; test-only assertion smells;
+# coverage ingested -> untested_hotspot/coverage_gap; test-only assertion smells;
# too-rare churn_risk/hidden_coupling; the gate-bound code_age_volatility) keep
# their prior weight. Top calibrated predictors: co_change_scatter (1.8),
# change_entropy (1.51), ownership_risk (1.38), nested_complexity (1.34).
@@ -84,10 +93,10 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
"god_class": 1.13,
# Prior-defect history (recent bug-fix count). NEUTRAL weight by design, not
# a boost: on the 13-repo corpus its calibrated coefficient is ~+0.02 (no lift
- # beyond size + the existing process signals — it correlates +0.59 with
+ # beyond size + the existing process signals - it correlates +0.59 with
# change_entropy, +0.38 with churn) and the effort-aware Popt gain is +0.01
# with bootstrap CIs straddling zero. So it ships as an interpretable,
- # leakage-free finding ("bug-fixed N times recently" — directly actionable,
+ # leakage-free finding ("bug-fixed N times recently" - directly actionable,
# and it uniquely flags a handful of files the other signals miss), NOT as a
# calibrated predictor. See local-stash/{calibrate_health_weights,
# measure_prior_defect,diagnose_prior_defect}.py + the progress doc Phase 8.5.
@@ -97,7 +106,7 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
"churn_risk": 1.2, # fired in too few repos to calibrate
"code_age_volatility": 1.1, # gate unmet at T0 across the corpus
# --- floored: fired widely but weak / non-predictive at T0 ---
- "developer_congestion": 0.5, # was 1.5 — the HEAD-leakage hero; weak under T0
+ "developer_congestion": 0.5, # was 1.5 - the HEAD-leakage hero; weak under T0
"low_cohesion": 0.5,
"brain_method": 0.5,
"bumpy_road": 0.5,
@@ -105,14 +114,14 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
"dry_violation": 0.5,
"knowledge_loss": 0.4, # confirmed weak-negative since Phase 1
# (coverage_gap, hidden_coupling, large_assertion_block,
- # duplicated_assertion_block default to 1.0 — kept at prior)
- # Governance — additive pass, weights are informational
+ # duplicated_assertion_block default to 1.0 - kept at prior)
+ # Governance - additive pass, weights are informational
"contradictory_decision": 1.0,
"stale_governance": 0.9,
"ungoverned_hotspot": 0.7,
}
-# Map biomarker name → category. Kept here (single source of truth)
+# Map biomarker name -> category. Kept here (single source of truth)
# rather than on each biomarker class because some biomarkers naturally
# span categories and we may want to retune without re-deploying.
_BIOMARKER_CATEGORY: dict[str, str] = {
@@ -128,6 +137,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"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",
@@ -140,7 +150,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"prior_defect": "organizational",
"large_assertion_block": "test_quality",
"duplicated_assertion_block": "test_quality",
- # Governance biomarkers — written by the additive governance pass
+ # Governance biomarkers - written by the additive governance pass
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
"contradictory_decision": "organizational",
@@ -162,7 +172,7 @@ def biomarker_category(name: str) -> str:
def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:
- """Aggregate biomarker hits → final score in [1.0, 10.0].
+ """Aggregate biomarker hits -> final score in [1.0, 10.0].
Returns ``(score, per_result_deductions)`` where the deductions list
is parallel to *results* and represents each finding's contribution
@@ -174,7 +184,12 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:
raw: dict[str, list[tuple[int, float]]] = {}
for idx, r in enumerate(results_list):
cat = biomarker_category(r.biomarker_type)
- weighted = severity_deduction(r.severity) * biomarker_weight(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)
raw.setdefault(cat, []).append((idx, weighted))
per_result = [0.0] * len(results_list)
@@ -200,7 +215,7 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:
def attach_impacts(
results: list[BiomarkerResult], deductions: list[float]
) -> list[HealthFindingData]:
- """Lift ``BiomarkerResult`` → ``HealthFindingData`` with impact attached."""
+ """Lift ``BiomarkerResult`` -> ``HealthFindingData`` with impact attached."""
out: list[HealthFindingData] = []
for r, d in zip(results, deductions, strict=True):
out.append(
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index fc5f496a0..5d0002b16 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -80,6 +80,12 @@ _TEMPLATES: dict[str, str] = {
"uncovered code paths (errors, edge cases, security-sensitive "
"branches) rather than just chasing the percentage."
),
+ "coverage_gradient": (
+ "Raise this file's line coverage. The uncovered fraction tracks "
+ "defect risk directly — add tests for the untested paths, prioritising "
+ "error handling and edge cases, and the deduction shrinks in step with "
+ "the coverage you recover."
+ ),
"developer_congestion": (
"Cool the contention. Too many authors are touching this file "
"at once — clarify ownership, or split the file along its "
diff --git a/tests/unit/health/test_coverage_biomarkers.py b/tests/unit/health/test_coverage_biomarkers.py
index b99200096..09ab47581 100644
--- a/tests/unit/health/test_coverage_biomarkers.py
+++ b/tests/unit/health/test_coverage_biomarkers.py
@@ -4,6 +4,9 @@ from __future__ import annotations
from repowise.core.analysis.health.biomarkers import FileContext
from repowise.core.analysis.health.biomarkers.coverage_gap import CoverageGapDetector
+from repowise.core.analysis.health.biomarkers.coverage_gradient import (
+ CoverageGradientDetector,
+)
from repowise.core.analysis.health.biomarkers.untested_hotspot import (
UntestedHotspotDetector,
)
@@ -124,3 +127,49 @@ def test_coverage_gap_skips_when_no_coverage_data() -> None:
def test_coverage_gap_skips_well_covered() -> None:
ctx = _ctx(line_cov=85.0, total_lines=200, covered_lines=set(range(1, 171)))
assert CoverageGapDetector().detect(ctx) == []
+
+
+# ---------------------------------------------------------------------------
+# coverage_gradient
+# ---------------------------------------------------------------------------
+
+
+def test_coverage_gradient_fires_proportionally_to_uncovered() -> None:
+ # 75% covered → 25% uncovered → deduction 4.0 * 0.25 = 1.0.
+ ctx = _ctx(line_cov=75.0, total_lines=100)
+ results = CoverageGradientDetector().detect(ctx)
+ assert len(results) == 1
+ r = results[0]
+ assert r.deduction == 1.0
+ assert r.details["uncovered_fraction"] == 0.25
+ assert r.severity == "low"
+
+
+def test_coverage_gradient_fires_on_well_covered_file() -> None:
+ # The binary gates stay silent at 92% — the gradient still fires (the point
+ # of this biomarker): 8% uncovered → deduction 0.32.
+ ctx = _ctx(line_cov=92.0, total_lines=300)
+ results = CoverageGradientDetector().detect(ctx)
+ assert len(results) == 1
+ assert round(results[0].deduction, 4) == 0.32
+ assert CoverageGapDetector().detect(ctx) == []
+
+
+def test_coverage_gradient_severity_bands() -> None:
+ assert CoverageGradientDetector().detect(_ctx(line_cov=30.0))[0].severity == "high"
+ assert CoverageGradientDetector().detect(_ctx(line_cov=55.0))[0].severity == "medium"
+ assert CoverageGradientDetector().detect(_ctx(line_cov=90.0))[0].severity == "low"
+
+
+def test_coverage_gradient_silent_when_no_coverage_data() -> None:
+ # Absent coverage is never imputed as uncovered.
+ assert CoverageGradientDetector().detect(_ctx(line_cov=None)) == []
+
+
+def test_coverage_gradient_silent_at_full_coverage() -> None:
+ assert CoverageGradientDetector().detect(_ctx(line_cov=100.0)) == []
+
+
+def test_coverage_gradient_skips_test_files() -> None:
+ ctx = _ctx(path="tests/test_thing.py", line_cov=10.0)
+ assert CoverageGradientDetector().detect(ctx) == []
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index 4bd4cb568..2c53a4fd6 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -1,13 +1,13 @@
"""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.
+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.
+``_EXPECTED_*`` constants below in the same PR - never silently.
"""
from __future__ import annotations
@@ -26,6 +26,9 @@ _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,
@@ -40,7 +43,7 @@ _EXPECTED_SEVERITY_DEDUCTION = {
# 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
+# 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 = {
@@ -54,14 +57,14 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
"complex_method": 1.21,
"function_hotspot": 1.16,
"god_class": 1.13,
- # prior-defect history — neutral weight: interpretable finding, calibrated
+ # 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
+ # floored - fired widely but weak/non-predictive at T0
"developer_congestion": 0.5,
"low_cohesion": 0.5,
"brain_method": 0.5,
@@ -69,7 +72,7 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
"primitive_obsession": 0.5,
"dry_violation": 0.5,
"knowledge_loss": 0.4,
- # Governance biomarkers (informational — surfaced as findings, not fed back
+ # 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,
@@ -89,6 +92,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {
"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",
@@ -147,11 +151,11 @@ def test_known_fixture_score_is_stable():
]
score, _ = 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
+ # 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
+ # total deduction = 2.5 + 0.847 + 1.56 + 0.12 = 5.027 -> 10 - 5.027 = 4.973
assert score == 4.973
@@ -163,11 +167,48 @@ def test_category_cap_clamps_score():
assert score == 7.5
+def test_continuous_deduction_override_is_used_and_capped():
+ """A ``deduction`` override replaces the severity table and is category-capped.
+
+ ``coverage_gradient`` deducts 4.0 x uncovered_fraction in its own
+ ``test_coverage_gradient`` category (cap 2.0). At 25% uncovered the raw
+ deduction is 1.0 (under the cap); at 80% uncovered it is 3.2 -> clamped to
+ the 2.0 cap.
+ """
+ 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,
+ )
+ score, ded = score_file([quarter])
+ assert score == 9.0 # 10 - 1.0
+ assert ded == [1.0]
+
+ 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,
+ )
+ score2, ded2 = score_file([deep])
+ assert score2 == 8.0 # 10 - 2.0 (cap)
+ assert ded2 == [2.0]
+
+
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."""
findings = [_result("developer_congestion", Severity.CRITICAL) for _ in range(3)]
score, _ = score_file(findings)
- # 3 * 2.0 * 0.5 = 3.0 weighted (< 3.5 cap) → score = 7.0
+ # 3 * 2.0 * 0.5 = 3.0 weighted (< 3.5 cap) -> score = 7.0
assert score == 7.0