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): saturating per-category curve with per-function grouping (#4144)

Raghav Chamadiyaa922f38f994d
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 5f9de678f..32133f961 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -343,6 +343,17 @@ category, so git history alone costs a file at most 1.0. Before that cap, the
history findings de-stack: the largest counts whole and each other one at 0.25
(`destacked`), since a busy file trips several history markers for one cause.
+Every other defect category follows a saturating curve rather than stopping at
+its cap (`shape_curve.py`). A category's raw total `R` deducts
+`A * (1 - exp(-R / A))` with `A = 3.09 x cap`, so a second critical function
+still costs something and no category ever deducts more than 3.09 times its cap.
+Two rules feed the curve. Findings on one function count the largest in full and
+the rest at 0.25. A critical `complex_method`, `large_method` or
+`nested_complexity` finding deducts `2.0 x value / threshold` (CCN 25, 200 lines,
+nesting 7), so halving a CCN-50 function pays even while it stays critical. The
+3.09 is fitted so the corpus mean score matches the hard-capped one; the curve is
+AUC-neutral on the 66-repo corpus.
+
`hidden_coupling` is advisory: still detected, stored and listed, it deducts
nothing. On its own it ranks defect-prone files near chance (AUC about 0.55), and
a pre-registered test on 12 repositories no earlier health study used found the
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index d43e813eb..5a0e82a5e 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -54,7 +54,10 @@ counted in full in maintainability.
## Reading the score
Each file starts at 10. Every finding deducts its severity times its marker
-weight, deductions are capped per category, and the result is clamped to 1-10.
+weight, deductions are bounded per category, and the result is clamped to 1-10.
+Code categories bend toward their bound rather than stopping at it, so shrinking a
+critical function raises the score even while it stays critical, and several findings on one
+function count mostly once.
| Band | Score | Meaning |
|---|---|---|
diff --git a/packages/core/src/repowise/core/analysis/health/aggregation.py b/packages/core/src/repowise/core/analysis/health/aggregation.py
index 6843317db..53441017f 100644
--- a/packages/core/src/repowise/core/analysis/health/aggregation.py
+++ b/packages/core/src/repowise/core/analysis/health/aggregation.py
@@ -30,6 +30,7 @@ from .scoring import (
is_advisory,
severity_deduction,
)
+from .shape_curve import ceiling, continuous_base, group_by_function
__all__ = [
"MODULE_ROOT_LABEL",
@@ -214,20 +215,24 @@ def finding_base_deduction(finding: Any) -> float:
Mirrors ``scoring.score_file``: a continuous ``deduction`` recorded in the
finding's details (the coverage gradient scales with the uncovered fraction)
- takes the place of the discrete severity table. Reading the override here is
- what lets a breakdown show the continuous signal rather than a band proxy.
+ takes the place of the discrete severity table, and a critical sized finding
+ scales past its threshold (``shape_curve.continuous_base``).
"""
- override = detail_map(finding).get("deduction")
+ details = detail_map(finding)
+ override = details.get("deduction")
if isinstance(override, (int, float)):
return float(override)
- return severity_deduction(_severity_key(field(finding, "severity", None)))
+ severity = _severity_key(field(finding, "severity", None))
+ biomarker = field(finding, "biomarker_type", None) or ""
+ base = severity_deduction(severity)
+ return continuous_base(biomarker, base, severity == "critical", details)
def finding_raw_deduction(finding: Any) -> float:
- """One finding's deduction before any category cap redistributed it.
+ """One finding's deduction before its function group or category reshaped it.
- ``base x weight``, the quantity ``_score_dimension`` computes and then
- scales away. ``health_impact`` is what survives that scaling, so it moves
+ ``base x weight``, the quantity ``_score_dimension`` starts from and then
+ scales. ``health_impact`` is what survives that scaling, so it moves
when a *neighbour* in the same capped category appears or goes away; this
one depends on the finding alone. A breakdown needs it to say how much a
category shed, and a change comparison needs it to ask whether one finding
@@ -263,11 +268,51 @@ def primary_and_magnitude_by_file(findings: Iterable[Any]) -> dict[str, dict[str
return {path: primary_and_magnitude(fs) for path, fs in by_file.items()}
-def _scored_raw(finding: Any) -> float:
- """:func:`finding_raw_deduction`, or 0 for a governance finding the score pass never saw."""
- if field(finding, "biomarker_type", None) in GOVERNANCE_BIOMARKERS:
- return 0.0
- return finding_raw_deduction(finding)
+def _scored_raw(findings: list[Any]) -> list[float]:
+ """Each finding's raw deduction as the scorer grouped it by function.
+
+ A governance finding counts 0: the score pass never saw it.
+ """
+ raw = [
+ 0.0
+ if field(f, "biomarker_type", None) in GOVERNANCE_BIOMARKERS
+ else finding_raw_deduction(f)
+ for f in findings
+ ]
+ names = [(field(f, "biomarker_type", "") or "", field(f, "function_name", None)) for f in findings]
+ group_by_function(names, raw)
+ return raw
+
+
+def _category_row(
+ category: str, entries: list[tuple[Any, float]], cap: float
+) -> tuple[dict[str, Any], float]:
+ """One breakdown row from ``(finding, raw)`` pairs, and its applied total."""
+ applied_each = [float(field(f, "health_impact", 0.0) or 0.0) for f, _ in entries]
+ raw_sum = sum(r for _, r in entries)
+ applied_sum = sum(applied_each)
+ row = {
+ "category": category,
+ "cap": round(cap, 2),
+ "raw_deduction": round(raw_sum, 3),
+ "applied_deduction": round(applied_sum, 3),
+ # Held at the cap; a curved category sheds weight but never sits at its ceiling.
+ "capped": category == HISTORY_CATEGORY and applied_sum < raw_sum - 1e-6,
+ "finding_count": len(entries),
+ "findings": [
+ {
+ "id": field(f, "id", None),
+ "biomarker_type": field(f, "biomarker_type", None),
+ "severity": field(f, "severity", None),
+ "raw_impact": round(raw, 3),
+ "applied_impact": round(applied, 3),
+ "function_name": field(f, "function_name", None),
+ "reason": field(f, "reason", None),
+ }
+ for (f, raw), applied in zip(entries, applied_each, strict=True)
+ ],
+ }
+ return row, applied_sum
def score_breakdown(findings: Sequence[Any]) -> dict[str, Any]:
@@ -276,61 +321,38 @@ def score_breakdown(findings: Sequence[Any]) -> dict[str, Any]:
The applied impact is the **stored** ``health_impact`` — the exact
already-weighted-and-capped value the scorer produced at index time — so the
breakdown reproduces the file's score instead of re-deriving it. Only the
- raw (pre-cap) figure is reconstructed, with the same ``base x weight``
- formula and the same history de-stacking, so a capped category is honest
- about how much it shed.
+ raw figure is reconstructed, with the same ``base x weight`` formula,
+ function grouping and history de-stacking, so a category is honest about how
+ much its curve or cap shed. ``cap`` is history's hard cap, or for every other
+ category the ceiling its curve approaches.
Categories are emitted in :data:`CATEGORY_CAPS` order and a category with no
findings is omitted, not zero-filled.
"""
- per_category: dict[str, list[Any]] = {}
- for finding in findings:
- biomarker = field(finding, "biomarker_type", None)
- # No deduction to explain. Left in, it reports a raw deduction the
- # file never paid and a ``capped`` flag on an uncapped category.
- if is_advisory(biomarker or ""):
- continue
- per_category.setdefault(biomarker_category(biomarker), []).append(finding)
+ # Advisory findings deduct nothing; left in, they report a raw deduction
+ # the file never paid.
+ kept = [f for f in findings if not is_advisory(field(f, "biomarker_type", None) or "")]
+ per_category: dict[str, list[tuple[Any, float]]] = {}
+ for finding, raw in zip(kept, _scored_raw(kept), strict=True):
+ category = biomarker_category(field(finding, "biomarker_type", None))
+ per_category.setdefault(category, []).append((finding, raw))
categories: list[dict[str, Any]] = []
total_deduction = 0.0
# 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
- raw_each = [_scored_raw(f) for f in entries]
- cap = static_cap
- if category == HISTORY_CATEGORY:
- cap, raw_each = history_cap(structure), destacked(raw_each)
- applied_each = [float(field(f, "health_impact", 0.0) or 0.0) for f in entries]
- raw_sum = sum(raw_each)
- applied_sum = sum(applied_each)
- categories.append(
- {
- "category": category,
- "cap": round(cap, 2),
- "raw_deduction": round(raw_sum, 3),
- "applied_deduction": round(applied_sum, 3),
- # Category shed weight iff its applied total is held at the cap.
- "capped": applied_sum < raw_sum - 1e-6,
- "finding_count": len(entries),
- "findings": [
- {
- "id": field(f, "id", None),
- "biomarker_type": field(f, "biomarker_type", None),
- "severity": field(f, "severity", None),
- "raw_impact": round(raw, 3),
- "applied_impact": round(applied, 3),
- "function_name": field(f, "function_name", None),
- "reason": field(f, "reason", None),
- }
- for f, raw, applied in zip(entries, raw_each, applied_each, strict=True)
- ],
- }
- )
- total_deduction += applied_sum
+ if entries := per_category.get(category):
+ # Only history keeps a hard cap; every other category follows the curve.
+ if category == HISTORY_CATEGORY:
+ cap = history_cap(structure)
+ raw = destacked([r for _, r in entries])
+ entries = [(f, r) for (f, _), r in zip(entries, raw, strict=True)]
+ else:
+ cap = ceiling(static_cap)
+ row, applied = _category_row(category, entries, cap)
+ categories.append(row)
+ total_deduction += applied
score = max(SCORE_FLOOR, min(SCORE_MAX, SCORE_MAX - total_deduction))
return {
"score": round(score, 2),
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index e761fd2f1..5b36553bb 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -103,6 +103,9 @@ log = structlog.get_logger(__name__)
# declarators and Kotlin lists; cached walks refresh the total, typed and scalar
# counts, enabling primitive_obsession in those languages.
# History findings de-stack before the history cap (``scoring.destacked``).
+# Defect code categories follow a saturating curve scaled by their cap, findings on
+# one function group, and critical size findings scale past their threshold
+# (``shape_curve``).
#
# v40: an Extract Method plan names its helper with a placeholder
# (``extracted_helper``, numbered when taken in scope) and asks the agent applying
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 4e931b185..b85b62f24 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -1,9 +1,11 @@
"""Per-file score aggregation + repo-level KPIs.
Each file starts at 10.0. Biomarker findings deduct; each finding's severity
-deduction is scaled by its biomarker's weight, then capped per category
-(:data:`CATEGORY_CAPS`; history by :func:`history_cap`). The final score is
-clamped to [1.0, 10.0].
+deduction is scaled by its biomarker's weight, then bounded per category: the
+defect score's code categories follow the saturating curve in ``shape_curve``
+scaled by :data:`CATEGORY_CAPS`, history keeps a hard cap (:func:`history_cap`),
+and the other dimensions cap each category. The final score is clamped to
+[1.0, 10.0].
"""
from __future__ import annotations
@@ -15,6 +17,7 @@ from typing import TYPE_CHECKING, Any
from .grading import analysed_share
from .models import HealthFileMetricData, HealthFindingData, Severity
from .rows import field, scored_rows, split_tests, split_unscored
+from .shape_curve import continuous_base, group_by_function, saturated
if TYPE_CHECKING:
# Annotation-only, and deliberately not imported at runtime: the biomarker
@@ -40,7 +43,8 @@ SCORE_FIELDS: tuple[str, ...] = (
"history_deduction",
)
-# Per-category max deduction.
+# Per-category cap: a hard maximum for history and the non-defect dimensions,
+# the curve's scale (``shape_curve.ceiling``) for every other defect category.
CATEGORY_CAPS: dict[str, float] = {
"organizational": 3.5,
"structural_complexity": 2.5,
@@ -50,7 +54,7 @@ CATEGORY_CAPS: dict[str, float] = {
# ``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
+ # 4.0 x uncovered_fraction (on a hard 2.0 cap) recovered
# +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,
@@ -78,7 +82,7 @@ HISTORY_CATEGORY = "organizational"
# 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
+# category, after its curve), up to the category's 3.5. A file with no code-shape
# finding keeps at least 9.0. Against a flat 3.5 cap this costs about 0.009
# defect AUC; it is kept so a refactor can lift a file that history holds down.
HISTORY_CAP_BASE: float = 1.0
@@ -105,8 +109,7 @@ def destacked(values: Sequence[float]) -> list[float]:
return [v if i == top else v * HISTORY_STACK_SHARE for i, v in enumerate(values)]
-# Per-biomarker deduction by severity. The scorer caps the per-category
-# total at the value in ``CATEGORY_CAPS``.
+# Per-biomarker deduction by severity, before weights and category bounds.
_SEVERITY_DEDUCTION: dict[Severity, float] = {
Severity.LOW: 0.3,
Severity.MEDIUM: 0.7,
@@ -169,8 +172,8 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
# Error-handling anti-patterns: maintainability flag, NOT a fitted
# predictor - deliberately excluded from the calibration roster (same
# treatment as governance biomarkers). Floored weight + LOW severity
- # (0.3 x 0.5 = 0.15/finding) + the 0.5 category cap keep the impact
- # bounded at half a point per file regardless of hit count.
+ # (0.3 x 0.5 = 0.15/finding) + the 0.5 category scale keep the impact
+ # under about 1.5 points per file regardless of hit count.
"error_handling": 0.5,
# (coverage_gap, large_assertion_block, duplicated_assertion_block
# default to 1.0 - kept at prior)
@@ -226,15 +229,10 @@ _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
+# The surfaced health score is the DEFECT score. ``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.
+# same biomarker stream, and they never feed back into ``defect``; the frozen
+# reference in ``tests/unit/health/test_scoring_dimensions`` locks that.
DIMENSIONS: tuple[str, ...] = ("defect", "maintainability", "performance")
@@ -626,30 +624,49 @@ def performance_category(name: str) -> str:
# Per category: ``(index into the scored results, weighted deduction)``.
_Entries = dict[str, list[tuple[int, float]]]
+# A category's total from its raw sum and its cap.
+_Settle = Callable[[float, float], float]
-def _weighted_by_category(
+def _weighted(
results_list: list[BiomarkerResult],
weight_fn: Callable[[BiomarkerResult], float],
- category_fn: Callable[[str], str],
-) -> _Entries:
- """Each finding's ``base x weight``, grouped by category."""
- raw: _Entries = {}
- for idx, r in enumerate(results_list):
+ shaped: bool,
+) -> list[float]:
+ """Each finding's ``base x weight``; *shaped* applies the code-shape rules (``shape_curve``)."""
+ out: list[float] = []
+ for r in results_list:
# A continuous ``deduction`` override (coverage scaled by the uncovered
# fraction) takes the place of the severity table, so its impact stays linear.
base = r.deduction if r.deduction is not None else severity_deduction(r.severity)
- raw.setdefault(category_fn(r.biomarker_type), []).append((idx, base * weight_fn(r)))
+ if shaped and r.deduction is None:
+ critical = r.severity == Severity.CRITICAL
+ base = continuous_base(r.biomarker_type, base, critical, r.details)
+ out.append(base * weight_fn(r))
+ if shaped:
+ group_by_function([(r.biomarker_type, r.function_name) for r in results_list], out)
+ return out
+
+
+def _by_category(
+ results_list: list[BiomarkerResult], weighted: list[float], category_fn: Callable[[str], str]
+) -> _Entries:
+ raw: _Entries = {}
+ for idx, (r, d) in enumerate(zip(results_list, weighted, strict=True)):
+ raw.setdefault(category_fn(r.biomarker_type), []).append((idx, d))
return raw
def _condition(
- raw: _Entries, caps: dict[str, float], conditioned_cap: tuple[str, Callable[[float], float]]
+ raw: _Entries,
+ caps: dict[str, float],
+ conditioned_cap: tuple[str, Callable[[float], float]],
+ settle: _Settle,
) -> dict[str, float]:
"""De-stack the conditioned category in place and return its live cap."""
cond_cat, cap_fn = conditioned_cap
others = sum(
- min(sum(d for _, d in entries), caps.get(cat, 1.0))
+ settle(sum(d for _, d in entries), caps.get(cat, 1.0))
for cat, entries in raw.items()
if cat != cond_cat
)
@@ -659,13 +676,16 @@ def _condition(
return {cond_cat: cap_fn(others)}
-def _capped(entries: list[tuple[int, float]], cap: float, per_result: list[float]) -> float:
- """Write each entry's share of the capped category total; return that total."""
+def _settled(
+ entries: list[tuple[int, float]], cap: float, settle: _Settle, per_result: list[float]
+) -> float:
+ """Write each entry's share of the settled category total; return that total."""
cat_sum = sum(d for _, d in entries)
- scale = 1.0 if cat_sum <= cap else cap / cat_sum
+ total = settle(cat_sum, cap)
+ scale = total / cat_sum if cat_sum > 0 else 0.0
for idx, d in entries:
per_result[idx] = d * scale
- return min(cat_sum, cap)
+ return total
def _score_dimension(
@@ -674,6 +694,8 @@ def _score_dimension(
category_fn: Callable[[str], str],
caps: dict[str, float],
conditioned_cap: tuple[str, Callable[[float], float]] | None = None,
+ *,
+ shaped: bool = False,
) -> tuple[float, list[float]]:
"""Aggregate one dimension's deductions -> ``(score, per_result_deductions)``.
@@ -683,16 +705,21 @@ def _score_dimension(
*conditioned_cap* ``(category, cap_fn)`` de-stacks that one category's
findings (:func:`destacked`) and replaces its cap with ``cap_fn(sum of every
- other category's capped total)``; only the defect dimension uses it, for the
- history category.
+ other category's total)``; only the defect dimension uses it, for the
+ history category. *shaped* (defect only) applies ``shape_curve``: continuous
+ critical severity, per-function grouping, and the saturating curve in place
+ of every other category's hard cap.
"""
- raw = _weighted_by_category(results_list, weight_fn, category_fn)
- cap_for = _condition(raw, caps, conditioned_cap) if conditioned_cap else {}
+ raw = _by_category(results_list, _weighted(results_list, weight_fn, shaped), category_fn)
+ settle: _Settle = saturated if shaped else min
+ cap_for = _condition(raw, caps, conditioned_cap, settle) if conditioned_cap else {}
per_result = [0.0] * len(results_list)
- total = sum(
- _capped(entries, cap_for.get(cat, caps.get(cat, 1.0)), per_result)
- for cat, entries in raw.items()
- )
+ total = 0.0
+ for cat, entries in raw.items():
+ if cat in cap_for:
+ total += _settled(entries, cap_for[cat], min, per_result)
+ else:
+ total += _settled(entries, caps.get(cat, 1.0), settle, per_result)
score = max(SCORE_FLOOR, min(SCORE_MAX, SCORE_MAX - total))
return score, per_result
@@ -729,25 +756,18 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | No
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 now measured (PR3): a file with no perf
- findings scores 10.0; the perf detectors deduct under a single bounded
- ``performance`` cap (2.0, a conservative ceiling). It never blends
- into ``defect``.
+ ``scores["defect"]`` is the surfaced score. ``scores["performance"]``
+ is 10.0 for a file with no perf findings; perf detectors deduct under
+ one ``performance`` cap (2.0) and never blend into ``defect``.
- ``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.
+ after grouping and category bounds, parallel to *results*. It populates
+ ``HealthFindingData.health_impact``, a defect-pillar quantity.
"""
results_list = list(results)
- # DEFECT: only biomarkers whose dimensions include ``defect`` deduct. EVERY
- # historical biomarker does (``dimensions_for`` defaults to ``{"defect"}``),
- # so this reproduces the pre-split single score byte-for-byte; the new
- # performance-only detectors are excluded and never move the surfaced score.
- # ``defect_deductions`` stays parallel to the FULL ``results_list`` (perf
- # findings get 0.0 defect impact) so ``attach_impacts`` can zip 1:1.
+ # Only biomarkers whose dimensions include ``defect`` deduct here.
+ # ``defect_deductions`` stays parallel to the full ``results_list`` (others
+ # get 0.0) so ``attach_impacts`` can zip 1:1.
defect_idx = [
i for i, r in enumerate(results_list) if "defect" in dimensions_for(r.biomarker_type)
]
@@ -758,6 +778,7 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | No
biomarker_category,
CATEGORY_CAPS,
conditioned_cap=(HISTORY_CATEGORY, history_cap),
+ shaped=True,
)
defect_deductions = [0.0] * len(results_list)
for sub_i, orig_i in enumerate(defect_idx):
diff --git a/packages/core/src/repowise/core/analysis/health/shape_curve.py b/packages/core/src/repowise/core/analysis/health/shape_curve.py
new file mode 100644
index 000000000..54198cd5c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/shape_curve.py
@@ -0,0 +1,101 @@
+"""How the defect score aggregates code-shape findings.
+
+Three rules, fitted together on the defect corpus so the headline stays
+AUC-neutral while every improvement to a large function shows:
+
+- A critical complexity, size or nesting finding deducts in proportion to how
+ far past its critical threshold the function sits, so halving a CCN-50
+ function pays even while it stays critical.
+- Findings on one function share a group: the largest counts whole and every
+ other one at :data:`FUNCTION_STACK_SHARE`, so one tangled function is not
+ charged once per marker that sees it.
+- A category's total follows a saturating curve, ``A * (1 - exp(-raw / A))``
+ with ``A = CATEGORY_SATURATION x the category cap``, instead of stopping at
+ the cap, so a second critical function still costs something.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping, Sequence
+
+# The curve's asymptote as a multiple of the category cap, calibrated so the
+# corpus mean score matches the hard-capped one.
+CATEGORY_SATURATION: float = 3.09
+FUNCTION_STACK_SHARE: float = 0.25
+
+# Markers that describe one function's shape and so share its group.
+FUNCTION_SHAPE_MARKERS: frozenset[str] = frozenset(
+ {
+ "complex_method",
+ "large_method",
+ "nested_complexity",
+ "brain_method",
+ "repeated_nesting",
+ "complex_conditional",
+ "primitive_obsession",
+ "god_class",
+ "low_cohesion",
+ }
+)
+
+# The measure each continuous marker reads and the value its critical band starts at.
+_CRITICAL_MEASURE: dict[str, tuple[str, float]] = {
+ "complex_method": ("ccn", 25),
+ "large_method": ("nloc", 200),
+ "nested_complexity": ("max_nesting", 7),
+}
+_CRITICAL_BASE: float = 2.0
+
+
+def continuous_base(biomarker: str, base: float, critical: bool, details: Mapping | None) -> float:
+ """*base*, or for a critical sized finding past its threshold ``2.0 x value / threshold``."""
+ measure = _CRITICAL_MEASURE.get(biomarker)
+ if not critical or measure is None:
+ return base
+ key, threshold = measure
+ value = (details or {}).get(key)
+ if isinstance(value, (int, float)) and value > threshold:
+ return _CRITICAL_BASE * value / threshold
+ return base
+
+
+def group_by_function(names: Sequence[tuple[str, str | None]], weighted: list[float]) -> None:
+ """Scale *weighted* in place so each function's shape findings total max + share x rest.
+
+ *names* is ``(biomarker, function_name)`` per entry, parallel to *weighted*.
+ """
+ groups: dict[str, list[int]] = {}
+ for i, (biomarker, function) in enumerate(names):
+ if function and biomarker in FUNCTION_SHAPE_MARKERS:
+ groups.setdefault(function, []).append(i)
+ for members in groups.values():
+ total = sum(weighted[i] for i in members)
+ if total <= 0:
+ continue
+ top = max(weighted[i] for i in members)
+ scale = (top + FUNCTION_STACK_SHARE * (total - top)) / total
+ for i in members:
+ weighted[i] *= scale
+
+
+def saturated(raw: float, cap: float) -> float:
+ """A category's deduction under the saturating curve."""
+ top = ceiling(cap)
+ return top * (1.0 - math.exp(-raw / top)) if top > 0 else 0.0
+
+
+def ceiling(cap: float) -> float:
+ """The most a saturating category can ever deduct."""
+ return CATEGORY_SATURATION * cap
+
+
+__all__ = [
+ "CATEGORY_SATURATION",
+ "FUNCTION_SHAPE_MARKERS",
+ "FUNCTION_STACK_SHARE",
+ "ceiling",
+ "continuous_base",
+ "group_by_function",
+ "saturated",
+]
diff --git a/packages/ui/src/health/ai-prompts/file-health-prompt.ts b/packages/ui/src/health/ai-prompts/file-health-prompt.ts
index dca8d7716..7cc0fbb36 100644
--- a/packages/ui/src/health/ai-prompts/file-health-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/file-health-prompt.ts
@@ -192,7 +192,7 @@ function leadingCause(file: FileHealthPromptInput): string | null {
function categoryLine(c: FileHealthPromptCategory): string {
const label = CATEGORY_LABEL[c.category as keyof typeof CATEGORY_LABEL] ?? c.category;
- const cap = c.cap != null ? `, capped at −${c.cap.toFixed(1)}` : "";
+ const cap = c.cap != null ? `, bounded at −${c.cap.toFixed(1)}` : "";
// A capped category's figure is a floor, not a measurement.
const note = c.capped ? " — **at its ceiling**, so this understates the category" : "";
return `${label}: −${c.applied_deduction.toFixed(2)} from ${c.finding_count} finding${pluralS(
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index e417f8272..e24de3318 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -120,7 +120,7 @@ export function ScoreBreakdown({
</span>
<span
className="cursor-help tabular-nums text-[var(--color-text-tertiary)]"
- title="The cap is the most this category is allowed to subtract from the 10-point score, no matter how many findings it has."
+ title="The cap is the most this category can subtract from the 10-point score. Code categories approach it gradually as findings add up; history stops at it."
>
−{c.applied_deduction.toFixed(2)}
{cap != null ? <> / cap −{cap.toFixed(1)}</> : null}
diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.json
index 0f66961b9..08478f997 100644
--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json
+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json
@@ -17,14 +17,14 @@
"mechanical_steps": 1,
"opportunity_id": "refop4_b09c227ff6aff8d07dda",
"rank_factors": {
- "benefit": 0.256,
+ "benefit": 0.22,
"cost": 1.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.256,
- "recoverable_health": 0.256,
+ "rank_score": 0.22,
+ "recoverable_health": 0.22,
"refactoring_model_version": 4,
"step_count": 1,
"steps": [
@@ -48,7 +48,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "account.ts",
- "impact_delta": 0.256,
+ "impact_delta": 0.22,
"plan_id": "refac4_a5f94bcfa0d5e0e24f37",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -86,14 +86,14 @@
"mechanical_steps": 1,
"opportunity_id": "refop4_b4793adb29a0d1200787",
"rank_factors": {
- "benefit": 0.256,
+ "benefit": 0.22,
"cost": 1.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.256,
- "recoverable_health": 0.256,
+ "rank_score": 0.22,
+ "recoverable_health": 0.22,
"refactoring_model_version": 4,
"step_count": 1,
"steps": [
@@ -117,7 +117,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "workspace.ts",
- "impact_delta": 0.256,
+ "impact_delta": 0.22,
"plan_id": "refac4_b21dea1501a82eec255a",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -184,14 +184,14 @@
"mechanical_steps": 3,
"opportunity_id": "refop4_147d3fb92ab4fa10d95a",
"rank_factors": {
- "benefit": 0.249,
+ "benefit": 0.513,
"cost": 3.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.1245,
- "recoverable_health": 0.249,
+ "rank_score": 0.2565,
+ "recoverable_health": 0.513,
"refactoring_model_version": 4,
"step_count": 3,
"steps": [
@@ -215,7 +215,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"plan_id": "refac4_3bb7e47b918d8f2f87b0",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -242,7 +242,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"plan_id": "refac4_431988e94554e6ba35d2",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -269,7 +269,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"plan_id": "refac4_9ff9f92beaaa4041f2fa",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -283,11 +283,11 @@
"value": 3.0
},
{
- "factor": "mechanical_share",
- "value": 0.5
+ "factor": "benefit",
+ "value": 0.513
},
{
- "factor": "primary_problem",
+ "factor": "mechanical_share",
"value": 0.5
}
]
diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.py
index 30db05999..0605055db 100644
--- a/tests/unit/change_health/test_regressions.py
+++ b/tests/unit/change_health/test_regressions.py
@@ -211,6 +211,8 @@ def _scored(specs: list[tuple[str, str, int]]) -> list[HealthFindingData]:
self.biomarker_type = marker
self.severity = Severity.MEDIUM
self.deduction = None
+ self.function_name = None
+ self.details: dict = {}
_score, impacts = score_file([_R(m) for m, _sym, _line in specs])
return [
diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.json
index 8989540d0..b17269793 100644
--- a/tests/unit/health/golden/health_engine.json
+++ b/tests/unit/health/golden/health_engine.json
@@ -109,7 +109,7 @@
"metrics": [
{
"file_path": "account.ts",
- "score": 8.2,
+ "score": 8.42,
"max_ccn": 17,
"max_nesting": 3,
"nloc": 66,
@@ -118,10 +118,10 @@
"duplication_pct": 97.14,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.2,
+ "defect_score": 8.42,
"maintainability_score": 8.1,
"performance_score": 10.0,
- "structure_deduction": 1.802,
+ "structure_deduction": 1.578,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -147,7 +147,7 @@
},
{
"file_path": "workspace.ts",
- "score": 8.2,
+ "score": 8.42,
"max_ccn": 17,
"max_nesting": 3,
"nloc": 66,
@@ -156,10 +156,10 @@
"duplication_pct": 97.14,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.2,
+ "defect_score": 8.42,
"maintainability_score": 8.1,
"performance_score": 10.0,
- "structure_deduction": 1.802,
+ "structure_deduction": 1.578,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -184,7 +184,7 @@
"end": 52
}
},
- "health_impact": 1.452,
+ "health_impact": 1.247,
"reason": "parseAccount has cyclomatic complexity 17",
"dimension": "defect",
"id": "finding_f79a5d5e8f306abe7ab7"
@@ -203,7 +203,7 @@
"worst_clone_partner": "workspace.ts",
"worst_clone_co_change": 0
},
- "health_impact": 0.35,
+ "health_impact": 0.331,
"reason": "97% of file duplicated in other files; worst clone shares 68 lines with workspace.ts",
"dimension": "maintainability",
"id": "finding_adecdf1cea8a1aad2796"
@@ -226,7 +226,7 @@
"end": 52
}
},
- "health_impact": 1.452,
+ "health_impact": 1.247,
"reason": "parseWorkspace has cyclomatic complexity 17",
"dimension": "defect",
"id": "finding_d79d97d650bcedab3ec2"
@@ -245,7 +245,7 @@
"worst_clone_partner": "account.ts",
"worst_clone_co_change": 0
},
- "health_impact": 0.35,
+ "health_impact": 0.331,
"reason": "97% of file duplicated in other files; worst clone shares 68 lines with account.ts",
"dimension": "maintainability",
"id": "finding_27bf987f937f7819f307"
@@ -253,9 +253,9 @@
],
"kpis": {
"hotspot_health": null,
- "average_health": 8.28,
+ "average_health": 8.49,
"worst_performer_path": "account.ts",
- "worst_performer_score": 8.2,
+ "worst_performer_score": 8.42,
"worst_test_path": null,
"worst_test_score": null,
"file_count": 3,
@@ -263,11 +263,11 @@
"maintainability_hotspot": null,
"performance_average": 10.0,
"performance_hotspot": null,
- "structure_average": 1.72,
+ "structure_average": 1.51,
"structure_hotspot": null,
"history_average": 0.0,
"history_hotspot": null,
- "production_average": 8.28,
+ "production_average": 8.49,
"production_file_count": 3,
"unanalysed_file_count": 0,
"analysed_share": 1.0
@@ -280,7 +280,7 @@
"target_symbol": "parseAccount",
"line_start": 15,
"line_end": 56,
- "impact_delta": 0.256,
+ "impact_delta": 0.22,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -291,7 +291,7 @@
"target_symbol": "parseWorkspace",
"line_start": 15,
"line_end": 56,
- "impact_delta": 0.256,
+ "impact_delta": 0.22,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -302,7 +302,7 @@
"metrics": [
{
"file_path": "handlers.py",
- "score": 8.5,
+ "score": 6.91,
"max_ccn": 12,
"max_nesting": 3,
"nloc": 182,
@@ -311,10 +311,10 @@
"duplication_pct": 85.42,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.5,
+ "defect_score": 6.91,
"maintainability_score": 8.0,
"performance_score": 10.0,
- "structure_deduction": 1.5,
+ "structure_deduction": 3.084,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -339,7 +339,7 @@
"end": 46
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "read_account has cyclomatic complexity 12",
"dimension": "defect",
"id": "finding_c58a781745af6691c556"
@@ -362,7 +362,7 @@
"end": 67
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "close_account has cyclomatic complexity 10",
"dimension": "defect",
"id": "finding_8b967d56d3c522a17535"
@@ -385,7 +385,7 @@
"end": 110
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "read_workspace has cyclomatic complexity 12",
"dimension": "defect",
"id": "finding_0b6ecfa0a2ac9cd7addc"
@@ -408,7 +408,7 @@
"end": 131
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "close_workspace has cyclomatic complexity 10",
"dimension": "defect",
"id": "finding_4934d3ca94e412af4fb3"
@@ -431,7 +431,7 @@
"end": 174
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "read_project has cyclomatic complexity 12",
"dimension": "defect",
"id": "finding_39991e29869edf38f6d2"
@@ -454,7 +454,7 @@
"end": 195
}
},
- "health_impact": 0.25,
+ "health_impact": 0.514,
"reason": "close_project has cyclomatic complexity 10",
"dimension": "defect",
"id": "finding_ebd7768c22e919caee2c"
@@ -462,9 +462,9 @@
],
"kpis": {
"hotspot_health": null,
- "average_health": 8.5,
+ "average_health": 6.91,
"worst_performer_path": "handlers.py",
- "worst_performer_score": 8.5,
+ "worst_performer_score": 6.91,
"worst_test_path": null,
"worst_test_score": null,
"file_count": 1,
@@ -472,11 +472,11 @@
"maintainability_hotspot": null,
"performance_average": 10.0,
"performance_hotspot": null,
- "structure_average": 1.5,
+ "structure_average": 3.08,
"structure_hotspot": null,
"history_average": 0.0,
"history_hotspot": null,
- "production_average": 8.5,
+ "production_average": 6.91,
"production_file_count": 1,
"unanalysed_file_count": 0,
"analysed_share": 1.0
@@ -489,7 +489,7 @@
"target_symbol": "read_account",
"line_start": 22,
"line_end": 48,
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -500,7 +500,7 @@
"target_symbol": "read_project",
"line_start": 150,
"line_end": 176,
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -511,7 +511,7 @@
"target_symbol": "read_workspace",
"line_start": 86,
"line_end": 112,
- "impact_delta": 0.083,
+ "impact_delta": 0.171,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -582,7 +582,7 @@
},
{
"file_path": "cpp/nested.cpp",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 9,
"max_nesting": 4,
"nloc": 24,
@@ -591,10 +591,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -658,7 +658,7 @@
},
{
"file_path": "csharp/nested.cs",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 9,
"max_nesting": 4,
"nloc": 34,
@@ -667,10 +667,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -715,7 +715,7 @@
},
{
"file_path": "dart/nested.dart",
- "score": 8.21,
+ "score": 8.34,
"max_ccn": 9,
"max_nesting": 4,
"nloc": 24,
@@ -724,10 +724,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.21,
+ "defect_score": 8.34,
"maintainability_score": 8.6,
"performance_score": 10.0,
- "structure_deduction": 1.785,
+ "structure_deduction": 1.657,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -753,7 +753,7 @@
},
{
"file_path": "go/conditionals.go",
- "score": 9.2,
+ "score": 9.24,
"max_ccn": 8,
"max_nesting": 1,
"nloc": 19,
@@ -762,17 +762,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.2,
+ "defect_score": 9.24,
"maintainability_score": 9.4,
"performance_score": 10.0,
- "structure_deduction": 0.798,
+ "structure_deduction": 0.758,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "go/nested.go",
- "score": 8.39,
+ "score": 8.55,
"max_ccn": 6,
"max_nesting": 5,
"nloc": 19,
@@ -781,17 +781,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.39,
+ "defect_score": 8.55,
"maintainability_score": 8.8,
"performance_score": 10.0,
- "structure_deduction": 1.608,
+ "structure_deduction": 1.452,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "go/perf_io_in_loop.go",
- "score": 9.85,
+ "score": 9.86,
"max_ccn": 2,
"max_nesting": 1,
"nloc": 56,
@@ -800,17 +800,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.85,
+ "defect_score": 9.86,
"maintainability_score": 9.7,
"performance_score": 8.0,
- "structure_deduction": 0.15,
+ "structure_deduction": 0.143,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "java/Conditionals.java",
- "score": 9.2,
+ "score": 9.24,
"max_ccn": 8,
"max_nesting": 1,
"nloc": 20,
@@ -819,17 +819,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.2,
+ "defect_score": 9.24,
"maintainability_score": 9.4,
"performance_score": 10.0,
- "structure_deduction": 0.798,
+ "structure_deduction": 0.758,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "java/Nested.java",
- "score": 8.24,
+ "score": 8.41,
"max_ccn": 7,
"max_nesting": 5,
"nloc": 23,
@@ -838,10 +838,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.24,
+ "defect_score": 8.41,
"maintainability_score": 8.5,
"performance_score": 10.0,
- "structure_deduction": 1.758,
+ "structure_deduction": 1.595,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -867,7 +867,7 @@
},
{
"file_path": "javascript/nested.js",
- "score": 8.24,
+ "score": 8.41,
"max_ccn": 7,
"max_nesting": 5,
"nloc": 20,
@@ -876,10 +876,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.24,
+ "defect_score": 8.41,
"maintainability_score": 8.5,
"performance_score": 10.0,
- "structure_deduction": 1.758,
+ "structure_deduction": 1.595,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -943,7 +943,7 @@
},
{
"file_path": "kotlin/nested.kt",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 9,
"max_nesting": 4,
"nloc": 24,
@@ -952,10 +952,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1038,7 +1038,7 @@
},
{
"file_path": "pascal/complex.pas",
- "score": 9.15,
+ "score": 9.23,
"max_ccn": 13,
"max_nesting": 1,
"nloc": 40,
@@ -1047,17 +1047,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.15,
+ "defect_score": 9.23,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.847,
+ "structure_deduction": 0.774,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "pascal/nested.pas",
- "score": 8.39,
+ "score": 8.55,
"max_ccn": 6,
"max_nesting": 5,
"nloc": 32,
@@ -1066,10 +1066,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.39,
+ "defect_score": 8.55,
"maintainability_score": 8.8,
"performance_score": 10.0,
- "structure_deduction": 1.608,
+ "structure_deduction": 1.452,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1133,7 +1133,7 @@
},
{
"file_path": "php/nested.php",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 7,
"max_nesting": 4,
"nloc": 89,
@@ -1142,10 +1142,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1171,7 +1171,7 @@
},
{
"file_path": "python/classes.py",
- "score": 9.65,
+ "score": 9.66,
"max_ccn": 2,
"max_nesting": 1,
"nloc": 34,
@@ -1180,17 +1180,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.65,
+ "defect_score": 9.66,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.35,
+ "structure_deduction": 0.342,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "python/complex.py",
- "score": 8.55,
+ "score": 8.75,
"max_ccn": 15,
"max_nesting": 2,
"nloc": 21,
@@ -1199,17 +1199,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.55,
+ "defect_score": 8.75,
"maintainability_score": 8.8,
"performance_score": 10.0,
- "structure_deduction": 1.452,
+ "structure_deduction": 1.247,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "python/conditionals.py",
- "score": 9.2,
+ "score": 9.24,
"max_ccn": 8,
"max_nesting": 1,
"nloc": 12,
@@ -1218,10 +1218,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.2,
+ "defect_score": 9.24,
"maintainability_score": 9.4,
"performance_score": 10.0,
- "structure_deduction": 0.798,
+ "structure_deduction": 0.758,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1247,7 +1247,7 @@
},
{
"file_path": "python/nested.py",
- "score": 8.09,
+ "score": 8.28,
"max_ccn": 7,
"max_nesting": 5,
"nloc": 14,
@@ -1256,10 +1256,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.09,
+ "defect_score": 8.28,
"maintainability_score": 8.2,
"performance_score": 10.0,
- "structure_deduction": 1.908,
+ "structure_deduction": 1.724,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1342,7 +1342,7 @@
},
{
"file_path": "ruby/nested.rb",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 7,
"max_nesting": 4,
"nloc": 81,
@@ -1351,10 +1351,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1380,7 +1380,7 @@
},
{
"file_path": "rust/conditionals.rs",
- "score": 9.2,
+ "score": 9.24,
"max_ccn": 8,
"max_nesting": 1,
"nloc": 18,
@@ -1389,10 +1389,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.2,
+ "defect_score": 9.24,
"maintainability_score": 9.4,
"performance_score": 10.0,
- "structure_deduction": 0.798,
+ "structure_deduction": 0.758,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1418,7 +1418,7 @@
},
{
"file_path": "rust/nested.rs",
- "score": 8.39,
+ "score": 8.55,
"max_ccn": 6,
"max_nesting": 5,
"nloc": 19,
@@ -1427,10 +1427,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.39,
+ "defect_score": 8.55,
"maintainability_score": 8.8,
"performance_score": 10.0,
- "structure_deduction": 1.608,
+ "structure_deduction": 1.452,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1475,7 +1475,7 @@
},
{
"file_path": "scala/classes.scala",
- "score": 9.65,
+ "score": 9.66,
"max_ccn": 2,
"max_nesting": 1,
"nloc": 50,
@@ -1484,17 +1484,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.65,
+ "defect_score": 9.66,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.35,
+ "structure_deduction": 0.342,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "scala/nested.scala",
- "score": 7.54,
+ "score": 7.77,
"max_ccn": 9,
"max_nesting": 5,
"nloc": 49,
@@ -1503,10 +1503,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 7.54,
+ "defect_score": 7.77,
"maintainability_score": 8.1,
"performance_score": 10.0,
- "structure_deduction": 2.455,
+ "structure_deduction": 2.226,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1532,7 +1532,7 @@
},
{
"file_path": "shell/control_flow.sh",
- "score": 9.15,
+ "score": 9.23,
"max_ccn": 10,
"max_nesting": 1,
"nloc": 30,
@@ -1541,10 +1541,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.15,
+ "defect_score": 9.23,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.847,
+ "structure_deduction": 0.774,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1646,7 +1646,7 @@
},
{
"file_path": "swift/nested.swift",
- "score": 9.06,
+ "score": 9.12,
"max_ccn": 9,
"max_nesting": 4,
"nloc": 24,
@@ -1655,10 +1655,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.06,
+ "defect_score": 9.12,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.938,
+ "structure_deduction": 0.883,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1684,7 +1684,7 @@
},
{
"file_path": "typescript/classes.ts",
- "score": 9.65,
+ "score": 9.66,
"max_ccn": 2,
"max_nesting": 1,
"nloc": 37,
@@ -1693,17 +1693,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.65,
+ "defect_score": 9.66,
"maintainability_score": 9.3,
"performance_score": 10.0,
- "structure_deduction": 0.35,
+ "structure_deduction": 0.342,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "typescript/conditionals.ts",
- "score": 9.2,
+ "score": 9.24,
"max_ccn": 8,
"max_nesting": 1,
"nloc": 26,
@@ -1712,17 +1712,17 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 9.2,
+ "defect_score": 9.24,
"maintainability_score": 9.4,
"performance_score": 10.0,
- "structure_deduction": 0.798,
+ "structure_deduction": 0.758,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
},
{
"file_path": "typescript/nested.ts",
- "score": 8.24,
+ "score": 8.41,
"max_ccn": 7,
"max_nesting": 5,
"nloc": 21,
@@ -1731,10 +1731,10 @@
"duplication_pct": null,
"line_coverage_pct": null,
"branch_coverage_pct": null,
- "defect_score": 8.24,
+ "defect_score": 8.41,
"maintainability_score": 8.5,
"performance_score": 10.0,
- "structure_deduction": 1.758,
+ "structure_deduction": 1.595,
"history_deduction": 0.0,
"is_test": false,
"code_origin": "production"
@@ -1835,7 +1835,7 @@
"end": 10
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeplyNested nests 4 levels deep",
"dimension": "defect",
"id": "finding_7336de57febe95c93630"
@@ -2035,7 +2035,7 @@
"end": 16
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "DeeplyNested nests 4 levels deep",
"dimension": "defect",
"id": "finding_525e8162089608e8a869"
@@ -2058,7 +2058,7 @@
"end": 10
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeplyNested nests 4 levels deep",
"dimension": "defect",
"id": "finding_14da5768ef44be629cdb"
@@ -2081,7 +2081,7 @@
"end": 21
}
},
- "health_impact": 0.847,
+ "health_impact": 0.774,
"reason": "manyBranches has cyclomatic complexity 9",
"dimension": "defect",
"id": "finding_75e1face476206b793af"
@@ -2208,7 +2208,7 @@
"dispatch_share": 0.0,
"symbol_line": 3
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "if condition combines 3 boolean operators",
"dimension": "defect",
"id": "finding_b4706faf8eea57f3c000"
@@ -2227,7 +2227,7 @@
"dispatch_share": 0.0,
"symbol_line": 10
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "for condition combines 6 boolean operators",
"dimension": "defect",
"id": "finding_ed03ae737c057c537559"
@@ -2250,7 +2250,7 @@
"end": 12
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "DeeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_8a94b5551a568cc7522f"
@@ -2267,7 +2267,7 @@
"symbol_line": 36,
"symbol": "deferInLoop"
},
- "health_impact": 0.15,
+ "health_impact": 0.143,
"reason": "error value is checked then ignored, or discarded via the blank identifier",
"dimension": "maintainability",
"id": "finding_ae2ad6b7dd45e467cae7"
@@ -2439,7 +2439,7 @@
"dispatch_share": 0.0,
"symbol_line": 2
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "if condition combines 3 boolean operators",
"dimension": "defect",
"id": "finding_92b0b6c1f3be5fe497d3"
@@ -2458,7 +2458,7 @@
"dispatch_share": 0.0,
"symbol_line": 9
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "while condition combines 6 boolean operators",
"dimension": "defect",
"id": "finding_13a165fcb9f91a97a666"
@@ -2481,7 +2481,7 @@
"end": 12
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_716ef8994749727b5d74"
@@ -2498,7 +2498,7 @@
"symbol_line": 2,
"symbol": "deeplyNested"
},
- "health_impact": 0.15,
+ "health_impact": 0.143,
"reason": "caught exception is swallowed without any handling",
"dimension": "maintainability",
"id": "finding_45419b3eb06537a00ce0"
@@ -2654,7 +2654,7 @@
"end": 10
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_bd08c69b932b606b18c9"
@@ -2671,7 +2671,7 @@
"symbol_line": 1,
"symbol": "deeplyNested"
},
- "health_impact": 0.15,
+ "health_impact": 0.143,
"reason": "caught exception is swallowed without any handling",
"dimension": "maintainability",
"id": "finding_4614b0ce342fb6f1e7f8"
@@ -2694,7 +2694,7 @@
"end": 10
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeplyNested nests 4 levels deep",
"dimension": "defect",
"id": "finding_341db9359cf919b9c51c"
@@ -2717,7 +2717,7 @@
"end": 28
}
},
- "health_impact": 0.847,
+ "health_impact": 0.774,
"reason": "ManyBranches has cyclomatic complexity 13",
"dimension": "defect",
"id": "finding_cdb1bfd5e7f5961c0f48"
@@ -2740,7 +2740,7 @@
"end": 23
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "DeeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_472f3545d0b4e4e51dcb"
@@ -2763,7 +2763,7 @@
"end": 11
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeply_nested nests 4 levels deep",
"dimension": "defect",
"id": "finding_08fb66e3bd4471dcc116"
@@ -2782,7 +2782,7 @@
"field_count": 2,
"symbol_line": 26
},
- "health_impact": 0.35,
+ "health_impact": 0.342,
"reason": "Splintered has low cohesion (LCOM4=2): its 5 methods split into 2 groups that share no fields or calls",
"dimension": "maintainability",
"id": "finding_2c342a6d7294a6f43a48"
@@ -2805,7 +2805,7 @@
"end": 20
}
},
- "health_impact": 1.452,
+ "health_impact": 1.247,
"reason": "many_branches has cyclomatic complexity 15",
"dimension": "defect",
"id": "finding_0218dfee9ddbbc3acb0c"
@@ -2824,7 +2824,7 @@
"dispatch_share": 0.0,
"symbol_line": 1
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "if condition combines 3 boolean operators",
"dimension": "defect",
"id": "finding_c86a6881aaec275e9ff1"
@@ -2843,7 +2843,7 @@
"dispatch_share": 0.0,
"symbol_line": 7
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "while condition combines 6 boolean operators",
"dimension": "defect",
"id": "finding_3ce2bf004e5ad8e70bed"
@@ -2866,7 +2866,7 @@
"end": 10
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeply_nested nests 5 levels deep",
"dimension": "defect",
"id": "finding_d4ee38f48a43bc6c92fd"
@@ -2883,7 +2883,7 @@
"symbol_line": 1,
"symbol": "deeply_nested"
},
- "health_impact": 0.15,
+ "health_impact": 0.136,
"reason": "caught exception is swallowed without any handling",
"dimension": "maintainability",
"id": "finding_a2c98dd353bdd9aa22b3"
@@ -2900,7 +2900,7 @@
"symbol_line": 1,
"symbol": "deeply_nested"
},
- "health_impact": 0.15,
+ "health_impact": 0.136,
"reason": "broad `except Exception` catches unrelated errors and can hide bugs",
"dimension": "maintainability",
"id": "finding_61df1a80f37292b7b485"
@@ -3074,7 +3074,7 @@
"end": 10
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeply_nested nests 4 levels deep",
"dimension": "defect",
"id": "finding_980163708d497ecefb31"
@@ -3400,7 +3400,7 @@
"dispatch_share": 0.0,
"symbol_line": 1
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "if condition combines 3 boolean operators",
"dimension": "defect",
"id": "finding_5e2e7ed7cf94318d223b"
@@ -3419,7 +3419,7 @@
"dispatch_share": 0.0,
"symbol_line": 8
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "while condition combines 6 boolean operators",
"dimension": "defect",
"id": "finding_a4bb8ffa6c328be7035f"
@@ -3442,7 +3442,7 @@
"end": 11
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeply_nested nests 5 levels deep",
"dimension": "defect",
"id": "finding_51c3d3fb3a7baa49f5d1"
@@ -3613,7 +3613,7 @@
"field_count": 2,
"symbol_line": 30
},
- "health_impact": 0.35,
+ "health_impact": 0.342,
"reason": "Splintered has low cohesion (LCOM4=2): its 5 methods split into 2 groups that share no fields or calls",
"dimension": "maintainability",
"id": "finding_37149d90e97e94d08056"
@@ -3636,7 +3636,7 @@
"end": 13
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_8444c612b6ad7c705ffd"
@@ -3659,7 +3659,7 @@
"end": 25
}
},
- "health_impact": 0.847,
+ "health_impact": 0.774,
"reason": "manyBranches has cyclomatic complexity 9",
"dimension": "defect",
"id": "finding_35278d63e4c3bf59be37"
@@ -3846,7 +3846,7 @@
"end": 13
}
},
- "health_impact": 0.847,
+ "health_impact": 0.774,
"reason": "process has cyclomatic complexity 10",
"dimension": "defect",
"id": "finding_d2fe951005c971f897c1"
@@ -3869,7 +3869,7 @@
"end": 10
}
},
- "health_impact": 0.938,
+ "health_impact": 0.883,
"reason": "deeplyNested nests 4 levels deep",
"dimension": "defect",
"id": "finding_d407fd3ab687e2789f32"
@@ -3888,7 +3888,7 @@
"field_count": 2,
"symbol_line": 28
},
- "health_impact": 0.35,
+ "health_impact": 0.342,
"reason": "Splintered has low cohesion (LCOM4=2): its 5 methods split into 2 groups that share no fields or calls",
"dimension": "maintainability",
"id": "finding_71eaf8ee511ffe4dce0d"
@@ -3907,7 +3907,7 @@
"dispatch_share": 0.0,
"symbol_line": 1
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "if condition combines 3 boolean operators",
"dimension": "defect",
"id": "finding_5da1fdb1c287eae427a0"
@@ -3926,7 +3926,7 @@
"dispatch_share": 0.0,
"symbol_line": 8
},
- "health_impact": 0.399,
+ "health_impact": 0.379,
"reason": "while condition combines 6 boolean operators",
"dimension": "defect",
"id": "finding_35d87c20e1ce38c81d46"
@@ -3949,7 +3949,7 @@
"end": 12
}
},
- "health_impact": 1.608,
+ "health_impact": 1.452,
"reason": "deeplyNested nests 5 levels deep",
"dimension": "defect",
"id": "finding_28aa3ceec6692a33ea1e"
@@ -3966,7 +3966,7 @@
"symbol_line": 1,
"symbol": "deeplyNested"
},
- "health_impact": 0.15,
+ "health_impact": 0.143,
"reason": "caught exception is swallowed without any handling",
"dimension": "maintainability",
"id": "finding_a35ce27fd3a48728b788"
@@ -4043,9 +4043,9 @@
],
"kpis": {
"hotspot_health": null,
- "average_health": 9.55,
+ "average_health": 9.59,
"worst_performer_path": "scala/nested.scala",
- "worst_performer_score": 7.54,
+ "worst_performer_score": 7.77,
"worst_test_path": null,
"worst_test_score": null,
"file_count": 63,
@@ -4053,11 +4053,11 @@
"maintainability_hotspot": null,
"performance_average": 9.5,
"performance_hotspot": null,
- "structure_average": 0.45,
+ "structure_average": 0.41,
"structure_hotspot": null,
"history_average": 0.0,
"history_hotspot": null,
- "production_average": 9.55,
+ "production_average": 9.59,
"production_file_count": 63,
"unanalysed_file_count": 4,
"analysed_share": 0.9403
diff --git a/tests/unit/health/test_aggregation_contract.py b/tests/unit/health/test_aggregation_contract.py
index 1cfbffe41..7a44d48b9 100644
--- a/tests/unit/health/test_aggregation_contract.py
+++ b/tests/unit/health/test_aggregation_contract.py
@@ -246,14 +246,18 @@ def test_the_breakdown_reproduces_the_score_from_stored_impact() -> None:
assert out["categories"][0]["applied_deduction"] == 2.25
-def test_a_capped_category_is_flagged_and_holds_its_applied_total() -> None:
+def test_a_curved_category_reports_its_ceiling_and_is_never_held_at_it() -> None:
+ """Code categories saturate toward 3.09 x their cap, so none sits at a ceiling."""
+ from repowise.core.analysis.health.shape_curve import ceiling
+
biomarker = _category_biomarker("structural_complexity")
cap = CATEGORY_CAPS["structural_complexity"]
findings = [_Finding(biomarker, severity="critical", health_impact=cap / 4) for _ in range(4)]
category = score_breakdown(findings)["categories"][0]
assert category["applied_deduction"] == pytest.approx(cap)
assert category["raw_deduction"] > cap
- assert category["capped"] is True
+ assert category["cap"] == round(ceiling(cap), 2)
+ assert category["capped"] is False
def test_the_history_category_reports_the_cap_it_was_scored_under() -> None:
diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.py
index d89408432..0dec207b5 100644
--- a/tests/unit/health/test_scoring.py
+++ b/tests/unit/health/test_scoring.py
@@ -5,7 +5,6 @@ from __future__ import annotations
from repowise.core.analysis.health.biomarkers.base import BiomarkerResult
from repowise.core.analysis.health.models import HealthFileMetricData, Severity
from repowise.core.analysis.health.scoring import (
- CATEGORY_CAPS,
compute_kpis,
remap_severities,
score_file,
@@ -67,24 +66,22 @@ def test_score_clean_file_is_ten():
def test_score_clamps_floor_at_one():
- # Twenty critical findings in the same category — should hit the cap
- # but never go below 1.0.
+ # Twenty critical findings in one category saturate toward 3.09 x its
+ # 1.5 cap and never take the score below 1.0.
results = [_r("complex_method", Severity.CRITICAL) for _ in range(20)]
scores, _ = score_file(results)
assert scores["defect"] >= 1.0
- # Cap on size_and_complexity is 1.5 (post-recalibration) → score 8.5.
- assert scores["defect"] == 8.5
+ assert round(scores["defect"], 3) == 5.365
-def test_category_cap_applied():
- # Two structural-complexity hits that together would deduct 4.0 raw,
- # but the category cap is 3.5.
+def test_category_curve_applied():
+ # Two structural-complexity hits, 3.68 weighted, saturate to 2.928.
results = [
- _r("brain_method", Severity.CRITICAL), # 2.0 raw
- _r("nested_complexity", Severity.CRITICAL), # 2.0 raw
+ _r("low_cohesion", Severity.CRITICAL), # 2.0 x 0.5
+ _r("nested_complexity", Severity.CRITICAL), # 2.0 x 1.34
]
scores, _ = score_file(results)
- assert scores["defect"] == 10.0 - CATEGORY_CAPS["structural_complexity"]
+ assert round(scores["defect"], 3) == 7.072
def test_compute_kpis_uses_nloc_weighting():
diff --git a/tests/unit/health/test_scoring_dimensions.py b/tests/unit/health/test_scoring_dimensions.py
index c6d0c25da..642173d32 100644
--- a/tests/unit/health/test_scoring_dimensions.py
+++ b/tests/unit/health/test_scoring_dimensions.py
@@ -17,6 +17,7 @@ still pins the whole algorithm.
from __future__ import annotations
+import math
from dataclasses import replace
import pytest
@@ -52,6 +53,8 @@ _HISTORY_CAP_BASE = 1.0
_HISTORY_CAP_PER_STRUCTURE = 1.0
# History de-stacking: the largest history finding whole, the rest at this share.
_HISTORY_STACK_SHARE = 0.25
+# Every other category saturates toward this multiple of its cap.
+_SATURATION = 3.09
_LEGACY_SEVERITY_DEDUCTION = {
Severity.LOW: 0.3,
@@ -140,17 +143,18 @@ def _legacy_score_file(results: list[BiomarkerResult]) -> float:
top = max(history)
raw["organizational"] = top + _HISTORY_STACK_SHARE * (sum(history) - top)
+ def saturated(cat: str, cat_sum: float) -> float:
+ ceiling = _SATURATION * _LEGACY_CATEGORY_CAPS.get(cat, 1.0)
+ return ceiling * (1.0 - math.exp(-cat_sum / ceiling))
+
structure = sum(
- min(cat_sum, _LEGACY_CATEGORY_CAPS.get(cat, 1.0))
- for cat, cat_sum in raw.items()
- if cat != "organizational"
+ saturated(cat, cat_sum) 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)
+ history_cap = min(
+ _LEGACY_CATEGORY_CAPS["organizational"],
+ _HISTORY_CAP_BASE + _HISTORY_CAP_PER_STRUCTURE * structure,
+ )
+ total = structure + min(raw.get("organizational", 0.0), history_cap)
return max(1.0, min(10.0, 10.0 - total))
@@ -199,10 +203,10 @@ _FIXTURES: list[list[BiomarkerResult]] = [
def test_defect_dimension_matches_legacy_golden():
- """THE GATE: scores["defect"] == the frozen pre-split score for every fixture."""
+ """THE GATE: scores["defect"] == the frozen reference score for every fixture (to float rounding)."""
for fixture in _FIXTURES:
scores, _ = score_file(fixture)
- assert scores["defect"] == _legacy_score_file(fixture)
+ assert scores["defect"] == pytest.approx(_legacy_score_file(fixture), abs=1e-9)
# The widened maintainability pillar, pinned per fixture. Maintainability is
@@ -356,8 +360,8 @@ 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
+ # defect: 2.0 * 0.5 = 1.0, saturated to 0.938
+ assert round(scores["defect"], 3) == 9.062
# maintainability: 2.0 * 1.0 = 2.0 in structural_complexity (cap 4.0) -> 8.0
assert scores["maintainability"] == 8.0
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index 5bc137294..694aed6a1 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -160,30 +160,28 @@ def test_known_fixture_score_is_stable():
_result("knowledge_loss", Severity.LOW),
]
scores, _ = score_file(findings)
- # Math (defect-calibrated weights):
- # structural = cohesion(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 scores["defect"] == 4.973
+ # 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_cap_clamps_score():
- """Many critical structural findings should not exceed the -2.5 cap."""
+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)
- # Cap at -2.5, so floor on this category alone is 7.5.
- assert scores["defect"] == 7.5
+ # 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 is category-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). 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.
+ ``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",
@@ -196,8 +194,8 @@ def test_continuous_deduction_override_is_used_and_capped():
deduction=4.0 * 0.25,
)
scores, ded = score_file([quarter])
- assert scores["defect"] == 9.0 # 10 - 1.0
- assert ded == [1.0]
+ assert round(scores["defect"], 3) == 9.077
+ assert [round(d, 3) for d in ded] == [0.923]
deep = BiomarkerResult(
biomarker_type="coverage_gradient",
@@ -210,21 +208,21 @@ def test_continuous_deduction_override_is_used_and_capped():
deduction=4.0 * 0.80,
)
scores2, ded2 = score_file([deep])
- assert scores2["defect"] == 8.0 # 10 - 2.0 (cap)
- assert ded2 == [2.0]
+ 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 deduct 0.15 each (LOW 0.3 x 0.5 weight) in
- their own advisory category, capped at 0.5/file regardless of count."""
+ """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 scores["defect"] == 9.7 # 10 - 2 * 0.15
- assert deductions == [0.15, 0.15]
+ 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 scores2["defect"] == 9.5 # 10 * 0.15 = 1.5 raw -> clamped to the 0.5 cap
+ assert round(scores2["defect"], 3) == 9.04 # raw 1.5 -> 0.96
def test_organizational_cap_bounds_stream():
@@ -241,28 +239,28 @@ 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.5 (low_cohesion x 3 -> structural cap) -> history cap 3.5
+ # 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"], 6) == round(10.0 - 2.5 - 3.5, 6)
- # structure 0.847 (one MEDIUM complex_method) -> history cap 1.847
+ 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"], 6) == round(10.0 - 0.847 - 1.847, 6)
+ assert round(scores["defect"], 3) == 7.452
# impacts still sum to the deduction the score was computed from
- assert round(sum(ded), 6) == round(0.847 + 1.847, 6)
+ 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.5
+ 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.5 cap
- assert round(scores["defect"], 6) == round(10.0 - 2.5 - 2.453, 6)
+ # 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]
diff --git a/tests/unit/health/test_shape_curve.py b/tests/unit/health/test_shape_curve.py
new file mode 100644
index 000000000..296757829
--- /dev/null
+++ b/tests/unit/health/test_shape_curve.py
@@ -0,0 +1,107 @@
+"""The defect score's code-shape aggregation: continuous critical severity,
+per-function grouping and the saturating category curve."""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import BiomarkerResult
+from repowise.core.analysis.health.models import Severity
+from repowise.core.analysis.health.scoring import CATEGORY_CAPS, score_file
+from repowise.core.analysis.health.shape_curve import CATEGORY_SATURATION
+
+
+def _r(name: str, severity: Severity, fn: str | None = None, **details) -> BiomarkerResult:
+ return BiomarkerResult(
+ biomarker_type=name,
+ severity=severity,
+ function_name=fn,
+ line_start=1,
+ line_end=2,
+ details=details,
+ )
+
+
+def _defect(results: list[BiomarkerResult]) -> float:
+ return score_file(results)[0]["defect"]
+
+
+def test_halving_a_critical_function_raises_the_score():
+ """CCN 50 -> 26 stays critical and still pays."""
+ big = _defect([_r("complex_method", Severity.CRITICAL, "f", ccn=50)])
+ half = _defect([_r("complex_method", Severity.CRITICAL, "f", ccn=26)])
+ assert half > big
+
+
+def test_a_second_critical_function_still_costs():
+ one = _defect([_r("complex_method", Severity.CRITICAL, "f", ccn=30)])
+ two = _defect(
+ [
+ _r("complex_method", Severity.CRITICAL, "f", ccn=30),
+ _r("complex_method", Severity.CRITICAL, "g", ccn=30),
+ ]
+ )
+ assert two < one
+
+
+def test_one_function_is_charged_once_per_group_not_per_marker():
+ """complex + large on one function deduct max + 0.25 x the other."""
+ same = _defect(
+ [_r("complex_method", Severity.MEDIUM, "f"), _r("large_method", Severity.MEDIUM, "f")]
+ )
+ apart = _defect(
+ [_r("complex_method", Severity.MEDIUM, "f"), _r("large_method", Severity.MEDIUM, "g")]
+ )
+ assert same > apart
+ raw = 0.7 * 1.25 + 0.25 * 0.7 * 1.21
+ ceiling = CATEGORY_SATURATION * CATEGORY_CAPS["size_and_complexity"]
+ assert same == pytest.approx(10.0 - ceiling * (1 - math.exp(-raw / ceiling)))
+
+
+def test_continuous_critical_base_matches_the_curve():
+ """CCN 50 is twice the critical threshold: base 4.0, weight 1.21."""
+ ceiling = CATEGORY_SATURATION * CATEGORY_CAPS["size_and_complexity"]
+ scores, ded = score_file([_r("complex_method", Severity.CRITICAL, "f", ccn=50)])
+ expected = ceiling * (1 - math.exp(-4.0 * 1.21 / ceiling))
+ assert scores["defect"] == pytest.approx(10.0 - expected)
+ assert ded == [pytest.approx(expected)]
+
+
+def test_history_cap_follows_the_saturated_structure():
+ shape = [_r("complex_method", Severity.MEDIUM, "f")]
+ history = [_r("prior_defect", Severity.CRITICAL) for _ in range(6)]
+ scores, ded = score_file([*shape, *history])
+ structure = ded[0]
+ assert sum(ded[1:]) == pytest.approx(1.0 + structure)
+ assert scores["defect"] == pytest.approx(10.0 - structure - (1.0 + structure))
+
+
+def test_maintainability_keeps_its_hard_caps():
+ findings = [_r("low_cohesion", Severity.CRITICAL, f"f{i}") for i in range(10)]
+ assert score_file(findings)[0]["maintainability"] == 6.0
+
+
+def test_breakdown_reports_function_grouped_raw():
+ """The breakdown's raw figures follow the same per-function grouping."""
+ from repowise.core.analysis.health.aggregation import score_breakdown
+ from repowise.core.analysis.health.scoring import attach_impacts
+
+ results = [_r("complex_method", Severity.MEDIUM, "f"), _r("large_method", Severity.MEDIUM, "f")]
+ findings = attach_impacts(results, score_file(results)[1])
+ size = score_breakdown(findings)["categories"][0]
+ assert size["raw_deduction"] == round(0.7 * 1.25 + 0.25 * 0.7 * 1.21, 3)
+ assert size["capped"] is False
+
+
+def test_a_critical_function_growing_is_worsened():
+ """A critical finding's raw deduction tracks its measure past the threshold."""
+ from repowise.core.analysis.health.aggregation import finding_raw_deduction
+ from repowise.core.analysis.health.scoring import attach_impacts
+
+ def raw(ccn: int) -> float:
+ results = [_r("complex_method", Severity.CRITICAL, "f", ccn=ccn)]
+ return finding_raw_deduction(attach_impacts(results, score_file(results)[1])[0])
+
+ assert raw(40) > raw(30) > raw(25)