Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(health): price refactoring and fix gains by rescoring the file, not summing health_impact (#4763)

Raghav Chamadiya5424ee526547
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/_files.py b/packages/core/src/repowise/core/analysis/health/fix_first/_files.py
index ec130457b..8074d202b 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/_files.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/_files.py
@@ -8,6 +8,7 @@ from typing import Any
from repowise.core.analysis.health.biomarkers.function_hotspot import FunctionHotspotDetector
from repowise.core.analysis.health.biomarkers.prior_defect import PriorDefectDetector
+from repowise.core.analysis.health.gain import removal_gain
from repowise.core.analysis.health.queue.eligibility import DeadSpan, dead_target
from repowise.core.analysis.health.queue.order import LEVEL_RANK
from repowise.core.analysis.health.queue.value import (
@@ -68,8 +69,10 @@ class _Files:
dead: Mapping[str, list[DeadSpan]] | None = None,
function_changes: Mapping[str, int] | None = None,
blame_skipped: Iterable[str] = (),
+ findings: Mapping[str, list[Any]] | None = None,
) -> None:
self.by_path = {field(m, "file_path"): m for m in metrics}
+ self.findings = findings or {}
self.function_changes = function_changes
self.blame_skipped = frozenset(blame_skipped)
self.functions = functions
@@ -96,6 +99,15 @@ class _Files:
for p, rows in history.items()
}
+ def gain(self, finding: Any) -> float:
+ """What fixing *finding* recovers: its file rescored without it.
+
+ Over the file's shown findings, so a hidden or triaged marker sharing
+ its category is not counted; the error is that marker's slice.
+ """
+ path = field(finding, "file_path")
+ return removal_gain(self.findings.get(path, [finding]), [(finding, 1.0)])
+
def is_test(self, path: str) -> bool | None:
"""The stored flag; ``None`` when the file has no metric row or flag."""
return field(self.by_path.get(path), "is_test")
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
index 4db78be46..672b49c92 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
@@ -170,6 +170,7 @@ def _prepare(
dead_spans(dead_code),
function_changes,
blame_skipped,
+ {p: shape + hist for p, (shape, hist) in split.items()},
)
return split, files
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/finding_units.py b/packages/core/src/repowise/core/analysis/health/fix_first/finding_units.py
index dc34e5ad2..639e7eb2e 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/finding_units.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/finding_units.py
@@ -24,7 +24,6 @@ from ._parts import (
MAX_FACTS,
SIZE_BREAK_UP,
Validate,
- _num,
_one_of,
_risk,
_tail,
@@ -60,7 +59,7 @@ def _finding_rank(finding: Any, files: _Files) -> _ShapeRank:
),
cloned=sized and files.cloned(path, shape),
low=low_priority(marker, shape, error_kind=detail_map(finding).get("kind")),
- gain=_num(field(finding, "health_impact")),
+ gain=files.gain(finding),
# Breaking up the whole function takes out its whole CCN.
ccn_removed=shape.get("ccn", 0) if sized else 0,
dependents=deps,
diff --git a/packages/core/src/repowise/core/analysis/health/gain.py b/packages/core/src/repowise/core/analysis/health/gain.py
new file mode 100644
index 000000000..d06077975
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/gain.py
@@ -0,0 +1,94 @@
+"""What fixing findings is worth: the file rescored without them.
+
+A finding's ``health_impact`` is its share of the file's deduction, not what
+removing it recovers. The saturating category curve, the history cap and its
+de-stacking, and the 1.0 floor all sit between the two: on a saturated
+category one marker frees little, on a floored file nothing moves, and code
+shape removed also lowers what history may take. So every expected gain is
+the file scored again through :func:`.scoring.score_file`, never a sum of
+impacts.
+
+A removal is ``(finding, share)``: share 1.0 fixes the finding, a smaller one
+shrinks its deduction before the curve (an extraction that takes out part of
+a method's complexity).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import replace
+from typing import Any
+
+from .biomarkers.base import BiomarkerResult
+from .governance import GOVERNANCE_BIOMARKERS
+from .history_refresh import as_biomarker_result
+from .models import Severity
+from .rows import field
+from .scoring import HISTORY_CATEGORY, biomarker_category, score_file, severity_deduction
+from .shape_curve import continuous_base
+
+Removal = Iterable[tuple[Any, float]]
+
+
+def removal_gain(findings: Iterable[Any], removed: Removal) -> float:
+ """Defect score the file gains when each removed finding loses its share.
+
+ Scores the file twice per call, so pricing every candidate is quadratic in
+ the file's findings; cheap at real counts (tens). Cache the "before" side
+ per file if a caller ever prices hundreds.
+ """
+ before, after = _lifted(findings, removed)
+ gain = score_file(after)[0]["defect"] - score_file(before)[0]["defect"]
+ return round(max(0.0, gain), 3)
+
+
+def structure_freed(findings: Iterable[Any], removed: Removal) -> float:
+ """Code-shape deduction the removal frees, for a caller that models the
+ history half itself."""
+ before, after = _lifted(findings, removed)
+ return round(max(0.0, _structure(before) - _structure(after)), 3)
+
+
+def _structure(results: list[BiomarkerResult]) -> float:
+ _, deductions = score_file(results)
+ return sum(
+ d
+ for r, d in zip(results, deductions, strict=True)
+ if biomarker_category(r.biomarker_type) != HISTORY_CATEGORY
+ )
+
+
+def _lifted(
+ findings: Iterable[Any], removed: Removal
+) -> tuple[list[BiomarkerResult], list[BiomarkerResult]]:
+ """The file's scored findings as the scorer takes them, before and after."""
+ shares = {id(f): min(max(share, 0.0), 1.0) for f, share in removed}
+ before: list[BiomarkerResult] = []
+ after: list[BiomarkerResult] = []
+ for f in findings:
+ # Governance is written by a later pass that deducts nothing
+ # (``history_refresh``); a stored ``resolved`` row is no longer detected.
+ if (
+ field(f, "biomarker_type", "") in GOVERNANCE_BIOMARKERS
+ or field(f, "status", None) == "resolved"
+ ):
+ continue
+ result = as_biomarker_result(f)
+ before.append(result)
+ share = shares.get(id(f), 0.0)
+ if share < 1.0:
+ after.append(_shrunk(result, 1.0 - share) if share > 0 else result)
+ return before, after
+
+
+def _shrunk(result: BiomarkerResult, keep: float) -> BiomarkerResult:
+ """*result* with *keep* of its base deduction, critical scaling applied first."""
+ base = result.deduction
+ if base is None:
+ base = continuous_base(
+ result.biomarker_type,
+ severity_deduction(result.severity),
+ result.severity == Severity.CRITICAL,
+ result.details,
+ )
+ return replace(result, deduction=base * keep)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
index b359cac67..0c8883e82 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
@@ -8,8 +8,8 @@ the suggestion is deterministic and matches the ``low_cohesion`` /
``god_class`` biomarkers exactly.
The detector confirms the god-class shape with two Lanza-Marinescu signals
-carried as evidence (WMC = Σ method McCabe; method/field counts), reads the
-recovered health impact off the matching biomarker finding, and emits one
+carried as evidence (WMC = Σ method McCabe; method/field counts), prices the
+fix by rescoring the file without the matching biomarker finding, and emits one
``RefactoringSuggestion`` per splittable class with the concrete group
breakdown.
@@ -34,10 +34,13 @@ class.
from __future__ import annotations
+from typing import Any
+
from ..complexity.class_analysis import cohesion_applies, holds_state
from ..complexity.models import CohesionGroup
from ..effort import effort_bucket
-from .models import RefactoringContext, RefactoringSuggestion
+from ..gain import removal_gain
+from .models import RECOVERED_SHARE, RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, register
# The cohesion biomarkers this detector answers. A class is only suggested
@@ -72,7 +75,7 @@ class ExtractClassDetector(RefactoringDetector):
out: list[RefactoringSuggestion] = []
if not cohesion_applies(ctx.file_path, ctx.language):
return out
- impact_by_class = self._impact_by_class(ctx)
+ findings_by_class = self._findings_by_class(ctx)
for cls in ctx.classes:
components = getattr(cls, "components", None) or []
@@ -90,12 +93,8 @@ class ExtractClassDetector(RefactoringDetector):
wmc = sum(getattr(m, "ccn", 0) for m in getattr(cls, "methods", []))
share = _moved_share(cls, substantive)
- impact_delta, source = max(
- (
- (impact * (share if marker == "god_class" else 1.0), marker)
- for impact, marker in impact_by_class.get(cls.name, ())
- ),
- default=(0.0, ""),
+ impact_delta, recovered, source = _best_recovery(
+ ctx.findings, findings_by_class.get(cls.name, ()), share
)
groups = [
@@ -116,8 +115,9 @@ class ExtractClassDetector(RefactoringDetector):
"field_count": cls.field_count,
"wmc": wmc,
"tcc": round(float(getattr(cls, "tcc", 1.0)), 3),
+ RECOVERED_SHARE: round(recovered, 3),
},
- impact_delta=round(float(impact_delta), 3),
+ impact_delta=impact_delta,
effort_bucket=effort_bucket(cls.total_nloc),
blast_radius={"dependents_count": ctx.dependents_count},
confidence=self._confidence(cls),
@@ -131,12 +131,12 @@ class ExtractClassDetector(RefactoringDetector):
return out
@staticmethod
- def _impact_by_class(ctx: RefactoringContext) -> dict[str, list[tuple[float, str]]]:
- """Map class name -> [(finding impact, source biomarker)] from the
- file's cohesion findings. The biomarkers report ``function_name`` =
- the class name.
+ def _findings_by_class(ctx: RefactoringContext) -> dict[str, list[tuple[Any, str]]]:
+ """Map class name -> [(finding, source biomarker)] from the file's
+ cohesion findings. The biomarkers report ``function_name`` = the class
+ name.
"""
- by_class: dict[str, list[tuple[float, str]]] = {}
+ by_class: dict[str, list[tuple[Any, str]]] = {}
for f in ctx.findings:
if getattr(f, "biomarker_type", "") not in _SOURCE_BIOMARKERS:
continue
@@ -146,8 +146,7 @@ class ExtractClassDetector(RefactoringDetector):
name = (getattr(f, "details", {}) or {}).get("class_name")
if not name:
continue
- impact = float(getattr(f, "health_impact", 0.0) or 0.0)
- by_class.setdefault(name, []).append((impact, getattr(f, "biomarker_type", "")))
+ by_class.setdefault(name, []).append((f, getattr(f, "biomarker_type", "")))
return by_class
@staticmethod
@@ -161,6 +160,18 @@ class ExtractClassDetector(RefactoringDetector):
return "medium"
+def _best_recovery(
+ findings: list[Any], matched: list[tuple[Any, str]], share: float
+) -> tuple[float, float, str]:
+ """``(gain, share recovered, marker)`` for the finding the split recovers
+ most of: ``low_cohesion`` whole, ``god_class`` by the moved *share*."""
+ options = []
+ for f, marker in matched:
+ part = share if marker == "god_class" else 1.0
+ options.append((removal_gain(findings, [(f, part)]), part, marker))
+ return max(options, default=(0.0, 1.0, ""))
+
+
def _moved_share(cls: object, groups: list) -> float:
"""Share of the class the split moves out, for a ``god_class`` finding.
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
index 3e8739ffa..bd5952219 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
@@ -28,8 +28,9 @@ Precision-first, the gate demands a block genuinely worth a helper:
vendored bundles) the block still duplicates across ``>= 2`` sites — test
fixtures and migration boilerplate duplicate constantly but a shared
helper is the wrong fix for them;
-- the recovered impact is the block's share of the file's ``dry_violation``
- finding when it overlaps the block, else ``0``: the finding grades the
+- the recovered impact is the file rescored without the block's share of the
+ file's ``dry_violation`` finding when it overlaps the block, else ``0``
+ (``health.gain``): the finding grades the
file's cross-file duplication, so one block is credited the lines of it it
removes here, not the whole finding (:func:`clone_share`). A block inside
one file recovers ``0``: that finding does not grade it, so it stays
@@ -52,9 +53,10 @@ from ....code_origin import is_migration_path, is_vendored_or_generated_path
from ....test_paths import is_test_related_path
from ..duplication.detector import clone_ranges, union_line_count
from ..effort import effort_bucket
+from ..gain import removal_gain
from .graph_signals import defined_symbols
from .language_family import same_language_family
-from .models import RefactoringContext, RefactoringSuggestion
+from .models import RECOVERED_SHARE, RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, register
from .reuse import find_reuse
@@ -435,12 +437,12 @@ class ExtractHelperDetector(RefactoringDetector):
if not blocks:
return []
- impact_lookup = self._impact_for_dry_violation(ctx)
+ dry = self._dry_violations(ctx)
spans_cache: dict[str, list[tuple[int, int]]] = {}
read = _cached_reader(ctx)
out: list[RefactoringSuggestion] = []
for block in blocks:
- suggestion = self._build_suggestion(ctx, block, impact_lookup, spans_cache)
+ suggestion = self._build_suggestion(ctx, block, dry, spans_cache)
if suggestion is not None:
suggestion.plan.update(_reuse_fields(ctx, suggestion.plan["occurrences"], read))
out.append(suggestion)
@@ -492,7 +494,7 @@ class ExtractHelperDetector(RefactoringDetector):
self,
ctx: RefactoringContext,
block: _Block,
- impact_lookup: list[tuple[int, int, float]],
+ dry: list[tuple[int, int, Any]],
spans_cache: dict[str, list[tuple[int, int]]],
) -> RefactoringSuggestion | None:
# Drop test-file occurrences — duplication among fixtures is noise —
@@ -545,12 +547,8 @@ class ExtractHelperDetector(RefactoringDetector):
return None
is_intra = len(occ_files) == 1
- impact = (
- 0.0
- if is_intra
- else self._impact_for_block(anchor_region, impact_lookup)
- * clone_share(occurrences, ctx.file_path, _cross_file_lines(ctx))
- )
+ share = 0.0 if is_intra else clone_share(occurrences, ctx.file_path, _cross_file_lines(ctx))
+ impact = self._gain_for_block(ctx, anchor_region, dry, share) if share else 0.0
suggested_site = self._suggested_site(occ_files)
snippet, snippet_start, snippet_truncated = self._snippet_for(ctx, anchor_region)
@@ -569,6 +567,7 @@ class ExtractHelperDetector(RefactoringDetector):
"token_count": block.token_count,
"co_change_count": block.co_change,
"is_intra_file": is_intra,
+ RECOVERED_SHARE: round(share, 3),
}
other_files = [f for f in occ_files if f != ctx.file_path]
blast_radius = {
@@ -585,7 +584,7 @@ class ExtractHelperDetector(RefactoringDetector):
line_end=anchor_region[1],
plan=plan,
evidence=evidence,
- impact_delta=round(float(impact), 3),
+ impact_delta=impact,
effort_bucket=effort_bucket(duplicated_lines),
blast_radius=blast_radius,
confidence="high" if block.co_change >= ACTIVE_CO_CHANGE else "medium",
@@ -666,35 +665,40 @@ class ExtractHelperDetector(RefactoringDetector):
return "\n".join(block), lo, truncated
@staticmethod
- def _impact_for_dry_violation(ctx: RefactoringContext) -> list[tuple[int, int, float]]:
+ def _dry_violations(ctx: RefactoringContext) -> list[tuple[int, int, Any]]:
"""The file's ``dry_violation`` findings as (line_start, line_end,
- impact) so a block can claim the impact of the clone it overlaps."""
- out: list[tuple[int, int, float]] = []
+ finding) so a block can claim the clone finding it overlaps."""
+ out: list[tuple[int, int, Any]] = []
for f in ctx.findings:
if getattr(f, "biomarker_type", "") != _SOURCE_BIOMARKER:
continue
start = getattr(f, "line_start", None)
end = getattr(f, "line_end", None)
- impact = float(getattr(f, "health_impact", 0.0) or 0.0)
if start is None or end is None:
# No region — attribute to the whole file (matches any block).
- out.append((0, 1_000_000_000, impact))
+ out.append((0, 1_000_000_000, f))
else:
- out.append((int(start), int(end), impact))
+ out.append((int(start), int(end), f))
return out
@staticmethod
- def _impact_for_block(
- region: tuple[int, int], impact_lookup: list[tuple[int, int, float]]
+ def _gain_for_block(
+ ctx: RefactoringContext,
+ region: tuple[int, int],
+ dry: list[tuple[int, int, Any]],
+ share: float,
) -> float:
- """Recovered impact for the block whose anchor region overlaps a
- ``dry_violation`` finding; 0 when none does (precision-first)."""
+ """Gain from removing *share* of the ``dry_violation`` finding the
+ block's anchor region overlaps; 0 when none does (precision-first)."""
start, end = region
- best = 0.0
- for f_start, f_end, impact in impact_lookup:
- if start <= f_end and end >= f_start and impact > best:
- best = impact
- return best
+ return max(
+ (
+ removal_gain(ctx.findings, [(f, share)])
+ for f_start, f_end, f in dry
+ if start <= f_end and end >= f_start
+ ),
+ default=0.0,
+ )
def _cached_reader(ctx: RefactoringContext) -> Callable[[str], list[str] | None] | None:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index fc59f5779..2842ecb6b 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -7,9 +7,9 @@ changing behaviour, and infers that helper's signature (IN parameters,
OUT return). This detector turns the best such span into one structured
``RefactoringSuggestion`` per flagged function.
-``impact_delta`` is the share of the finding the extraction itself removes,
-not the whole finding: the share of what the finding measures that moves into
-the helper, applied to the finding's ``health_impact``. That is
+``impact_delta`` prices the share of the finding the extraction itself
+removes, not the whole finding: the file rescored with that share of the
+finding's deduction taken out (``health.gain``). The share is
``ccn_removed / ccn`` for ``complex_method`` and ``brain_method``, and the
smaller of ``slice_nloc / nloc`` and that for ``large_method``
(:func:`recovered_share`). Both line counts follow the walker's NLOC rule, so
@@ -81,8 +81,9 @@ Plan shape (open dict, no migration):
carries its own. A staged split that cannot be anchored falls back to the
function's best single span; when that cannot be either, the function is
refused (``span_unanchored``).
-- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and
- complexity (code lines, decision points) the residual method sheds.
+- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int, "recovered_share":
+ float}`` -- the size and complexity (code lines, decision points) the
+ residual method sheds, and the share of the finding that removes.
- ``plan.stages`` -- only on a staged plan (``dataflow.stages``): a function
no single helper brings under the bar (CCN over twice a stage's cap, Python
and TS / JS) is split into helpers called in order. Each stage carries the
@@ -117,13 +118,14 @@ from ..complexity.nloc import is_string_stmt
from ..dataflow import Extraction, find_extractions, get_defuse_dialect
from ..dataflow.stages import STAGE_MAX_CCN, StagePlan, find_stages
from ..effort import effort_bucket
+from ..gain import removal_gain
from ..perf.dialects import PERF_DIALECTS
from ..scoring import severity_deduction
from . import render
from .anchors import Scope, anchor_plan, file_source, function_scope
from .declarative import declarative_flat
from .helper_naming import ScopeNames, placeholder_names
-from .models import RefactoringContext, RefactoringSuggestion
+from .models import RECOVERED_SHARE, RefactoringContext, RefactoringSuggestion
from .narrowing import narrowed, narrowings, property_narrowings, span_guards
from .registry import RefactoringDetector, register
@@ -277,7 +279,7 @@ class ExtractMethodDetector(RefactoringDetector):
fields: dict[str, Any],
) -> RefactoringSuggestion:
"""The plan lifting *best*, its rendered *fields* after the span."""
- impact, share, source = self._impact_for(analysis, best, matched)
+ impact, share, source = self._impact_for(ctx, analysis, best, matched)
return RefactoringSuggestion(
refactoring_type=self.name,
file_path=ctx.file_path,
@@ -293,8 +295,9 @@ class ExtractMethodDetector(RefactoringDetector):
evidence={
"slice_nloc": best.slice_nloc,
"ccn_removed": best.ccn_removed,
+ RECOVERED_SHARE: round(share, 3),
},
- impact_delta=round(float(impact), 3),
+ impact_delta=impact,
effort_bucket=effort_bucket(best.slice_nloc),
blast_radius={"scope": "local"},
confidence=self._confidence(best, share),
@@ -319,7 +322,7 @@ class ExtractMethodDetector(RefactoringDetector):
slice_nloc=staged.slice_nloc,
ccn_removed=staged.ccn_removed,
)
- impact, _share, source = self._impact_for(analysis, total, matched)
+ impact, share, source = self._impact_for(ctx, analysis, total, matched)
return RefactoringSuggestion(
refactoring_type=self.name,
file_path=ctx.file_path,
@@ -327,8 +330,12 @@ class ExtractMethodDetector(RefactoringDetector):
line_start=analysis.start_line,
line_end=analysis.end_line,
plan=_staged_fields(analysis, staged, ctx.language, names, receiver),
- evidence={"slice_nloc": total.slice_nloc, "ccn_removed": total.ccn_removed},
- impact_delta=round(float(impact), 3),
+ evidence={
+ "slice_nloc": total.slice_nloc,
+ "ccn_removed": total.ccn_removed,
+ RECOVERED_SHARE: round(share, 3),
+ },
+ impact_delta=impact,
effort_bucket=effort_bucket(total.slice_nloc),
blast_radius={"scope": "local"},
# Several edits to one function: a reviewer reads the plan first.
@@ -355,18 +362,20 @@ class ExtractMethodDetector(RefactoringDetector):
@staticmethod
def _impact_for(
- analysis: FunctionAnalysis, extraction: Extraction, findings: list[Any]
+ ctx: RefactoringContext,
+ analysis: FunctionAnalysis,
+ extraction: Extraction,
+ findings: list[Any],
) -> tuple[float, float, str]:
- """Impact *extraction* recovers, its share of the finding, and the source
+ """Gain *extraction* recovers, its share of the finding, and the source
biomarker. One finding is credited, the one recovering the most: the
composer counts a finding once across steps."""
- best: tuple[float, float, float, str] = (-1.0, 0.0, -1.0, "")
+ best: tuple[float, float, str] = (-1.0, 0.0, "")
for f in findings:
biomarker = getattr(f, "biomarker_type", "")
- full = float(getattr(f, "health_impact", 0.0) or 0.0)
share = recovered_share(biomarker, analysis, extraction)
- best = max(best, (full * share, share, full, biomarker))
- return best[0], best[1], best[3]
+ best = max(best, (removal_gain(ctx.findings, [(f, share)]), share, biomarker))
+ return best
@staticmethod
def _confidence(extraction: Extraction, share: float) -> str:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index f6a699ce6..f403330bc 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -124,6 +124,10 @@ from typing import Any
# plan". Read a detector's confidence as medium-or-high.
CONFIDENCE_LEVELS = ("low", "medium", "high")
+#: The evidence key for the share of its source finding a plan removes (1.0:
+#: the whole finding), so a set of plans is priced by one rescore.
+RECOVERED_SHARE = "recovered_share"
+
@dataclass
class RefactoringContext:
@@ -225,9 +229,10 @@ class RefactoringSuggestion:
plan: dict[str, Any]
# The signals that justify the suggestion (LCOM4, WMC, clone ranges, ...).
evidence: dict[str, Any]
- # Health score the refactoring would recover if applied: the part of the
- # source finding's deduction that applying it removes, plus any history
- # deduction that releases. >= 0.
+ # Health score the refactoring would recover if applied: the file rescored
+ # with the part of the source finding it removes taken out
+ # (``health.gain.removal_gain``), so caps, history release and the floor
+ # all count. >= 0.
impact_delta: float
# Effort estimate — "S" | "M" | "L" | "XL" (from the target's size).
effort_bucket: str
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
index cbda90f1b..7bf6a8b4e 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
@@ -58,11 +58,12 @@ from typing import Any
from ...finding_registry import excluded_types
from ..effort import EFFORT_ORDER
+from ..gain import removal_gain
from ..refactoring_summary import ADVISORY_TYPES, needs_design
from ..rows import field
from .extract_helper import ACTIVE_CO_CHANGE
from .identity import REFACTORING_MODEL_VERSION, assign_public_ids, stable_id
-from .models import RefactoringSuggestion
+from .models import RECOVERED_SHARE, RefactoringSuggestion
from .opportunity_rank import (
opportunity_benefit,
opportunity_risk,
@@ -379,6 +380,29 @@ def _credited(
return credited
+def _recoverable(
+ step_rows: Sequence[tuple[RefactoringSuggestion, str]],
+ credited: set[str],
+ findings: Sequence[Any] | None,
+) -> float:
+ """The credited steps priced together: one rescore of the file without
+ the share of each finding they answer, since gains do not add (caps,
+ history release, the floor). With no findings, or a plan stored before
+ plans carried their share, each step's own gain is summed."""
+ steps = [suggestion for suggestion, plan_id in step_rows if plan_id in credited]
+ shares = [(s, (s.evidence or {}).get(RECOVERED_SHARE)) for s in steps]
+ if findings is None or any(share is None and (s.impact_delta or 0) > 0 for s, share in shares):
+ return sum(float(s.impact_delta or 0.0) for s in steps)
+ removed = [
+ (f, float(share))
+ for s, share in shares
+ if share is not None
+ for f in findings
+ if step_answers(s, f)
+ ]
+ return removal_gain(findings, removed)
+
+
def _step_of(
suggestion: RefactoringSuggestion,
plan_id: str,
@@ -493,7 +517,7 @@ def _compose_one(
addresses_primary_problem=addresses,
steps=steps,
evidence=evidence,
- recoverable_health=sum(step.impact_delta for step in steps if step.plan_id in credited),
+ recoverable_health=_recoverable(step_rows, credited, findings),
mechanical_steps=mechanical,
judgment_steps=len(steps) - mechanical,
affected_files=tuple(touched),
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
index d78e245b2..ccbb508e9 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
@@ -12,11 +12,9 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence
-from dataclasses import replace
import structlog
-from ..scoring import HISTORY_CATEGORY, biomarker_category, deduction_split, history_cap
from .models import CONFIDENCE_LEVELS, RefactoringContext, RefactoringSuggestion
log = structlog.get_logger(__name__)
@@ -68,14 +66,13 @@ def detect_refactorings(
every suggestion.
"""
floor_idx = _confidence_floor_index(min_confidence)
- structure, history = deduction_split(ctx.findings)
out: list[RefactoringSuggestion] = []
for detector in registered_detectors(disabled=disabled):
try:
for suggestion in detector.detect(ctx):
if floor_idx and _confidence_rank(suggestion.confidence) < floor_idx:
continue
- out.append(_with_released_history(suggestion, structure, history))
+ out.append(suggestion)
except Exception as exc:
# One bad detector must not break the health pass; degrade to
# "no suggestion" for this file.
@@ -83,19 +80,6 @@ def detect_refactorings(
return out
-def _with_released_history(
- suggestion: RefactoringSuggestion, structure: float, history: float
-) -> RefactoringSuggestion:
- """Add the history deduction a code-shape fix releases by lowering the history cap."""
- impact = suggestion.impact_delta
- if impact <= 0 or history <= 0:
- return suggestion
- if biomarker_category(suggestion.source_biomarker) == HISTORY_CATEGORY:
- return suggestion
- released = max(0.0, history - history_cap(structure - impact))
- return replace(suggestion, impact_delta=round(impact + released, 3))
-
-
def _confidence_rank(level: str) -> int:
"""Ordinal of a confidence label; unknown labels rank at the floor (0)."""
try:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py b/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py
index 5e9729bcd..a211a166d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py
@@ -5,9 +5,10 @@ A file's score is ``clamp(10 - structure - history)``, where history is capped b
deduct. The stored history is already capped, so ``min(history, history_cap(s))``
is exactly the history left at a lower structure ``s``. With no structure left
that gives the file's ceiling, the most an edit can reach. A finding's ``points``
-are its ``health_impact``, an upper bound when its category sits at its cap
-(the others scale back up). Headline and hotspot gains weight the file gain by
-the file's nloc share of each average.
+are the structure deduction its removal frees, the file's code-shape findings
+rescored without it (``health.gain``), so a saturated category frees little.
+Headline and hotspot gains weight the file gain by the file's nloc share of
+each average.
"""
from __future__ import annotations
@@ -16,6 +17,7 @@ from collections import defaultdict
from dataclasses import dataclass
from typing import Any
+from repowise.core.analysis.health.gain import structure_freed
from repowise.core.analysis.health.grading import TARGET_SCORE
from repowise.core.analysis.health.models import split_by_origin
from repowise.core.analysis.health.scoring import (
@@ -116,7 +118,7 @@ def _file_row(m: Any, findings: list[Any], weights: _Weights) -> dict[str, Any]:
history=getattr(m, "history_deduction", None) or 0.0,
)
ceiling = halves.at(0.0)
- fixes = [_fix(m, f, halves, weights) for f in findings]
+ fixes = [_fix(m, f, findings, halves, weights) for f in findings]
row: dict[str, Any] = {
"file_path": m.file_path,
"score": round(m.score, 2),
@@ -134,8 +136,10 @@ def _file_row(m: Any, findings: list[Any], weights: _Weights) -> dict[str, Any]:
return row
-def _fix(m: Any, f: Any, halves: _FileScore, weights: _Weights) -> dict[str, Any]:
- points = min(f.health_impact, halves.structure)
+def _fix(
+ m: Any, f: Any, findings: list[Any], halves: _FileScore, weights: _Weights
+) -> dict[str, Any]:
+ points = min(structure_freed(findings, [(f, 1.0)]), halves.structure)
file_gain = halves.at(halves.structure - points) - halves.now
fix: dict[str, Any] = {
"file_path": m.file_path,
diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.json
index 08478f997..8814fe665 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.22,
+ "benefit": 0.193,
"cost": 1.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.22,
- "recoverable_health": 0.22,
+ "rank_score": 0.193,
+ "recoverable_health": 0.193,
"refactoring_model_version": 4,
"step_count": 1,
"steps": [
@@ -48,7 +48,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "account.ts",
- "impact_delta": 0.22,
+ "impact_delta": 0.193,
"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.22,
+ "benefit": 0.193,
"cost": 1.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.22,
- "recoverable_health": 0.22,
+ "rank_score": 0.193,
+ "recoverable_health": 0.193,
"refactoring_model_version": 4,
"step_count": 1,
"steps": [
@@ -117,7 +117,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "workspace.ts",
- "impact_delta": 0.22,
+ "impact_delta": 0.193,
"plan_id": "refac4_b21dea1501a82eec255a",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -159,6 +159,7 @@
"duplicated_lines": 23,
"is_intra_file": true,
"occurrence_count": 3,
+ "recovered_share": 0.0,
"token_count": 16200
},
"target_symbol": "handlers.py:25-47"
@@ -172,6 +173,7 @@
"duplicated_lines": 23,
"is_intra_file": true,
"occurrence_count": 2,
+ "recovered_share": 0.0,
"token_count": 8150
},
"target_symbol": "handlers.py:89-111"
@@ -184,14 +186,14 @@
"mechanical_steps": 3,
"opportunity_id": "refop4_147d3fb92ab4fa10d95a",
"rank_factors": {
- "benefit": 0.513,
+ "benefit": 0.291,
"cost": 3.0,
"mechanical_share": 0.5,
"primary_problem": 0.5,
"risk": 0.0
},
- "rank_score": 0.2565,
- "recoverable_health": 0.513,
+ "rank_score": 0.1455,
+ "recoverable_health": 0.291,
"refactoring_model_version": 4,
"step_count": 3,
"steps": [
@@ -215,7 +217,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"plan_id": "refac4_3bb7e47b918d8f2f87b0",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -242,7 +244,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"plan_id": "refac4_431988e94554e6ba35d2",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -269,7 +271,7 @@
"confidence": "high",
"effort_bucket": "S",
"file_path": "handlers.py",
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"plan_id": "refac4_9ff9f92beaaa4041f2fa",
"refactoring_type": "extract_method",
"relocated_by": null,
@@ -283,11 +285,11 @@
"value": 3.0
},
{
- "factor": "benefit",
- "value": 0.513
+ "factor": "mechanical_share",
+ "value": 0.5
},
{
- "factor": "mechanical_share",
+ "factor": "primary_problem",
"value": 0.5
}
]
diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.json
index 168eee65b..3c67af2e9 100644
--- a/tests/unit/health/golden/health_engine.json
+++ b/tests/unit/health/golden/health_engine.json
@@ -421,7 +421,7 @@
"target_symbol": "parseAccount",
"line_start": 15,
"line_end": 56,
- "impact_delta": 0.22,
+ "impact_delta": 0.193,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -432,7 +432,7 @@
"target_symbol": "parseWorkspace",
"line_start": 15,
"line_end": 56,
- "impact_delta": 0.22,
+ "impact_delta": 0.193,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -810,7 +810,7 @@
"target_symbol": "read_account",
"line_start": 22,
"line_end": 48,
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -821,7 +821,7 @@
"target_symbol": "read_project",
"line_start": 150,
"line_end": 176,
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
@@ -832,7 +832,7 @@
"target_symbol": "read_workspace",
"line_start": 86,
"line_end": 112,
- "impact_delta": 0.171,
+ "impact_delta": 0.097,
"effort_bucket": "S",
"confidence": "high",
"source_biomarker": "complex_method"
diff --git a/tests/unit/health/test_extract_method_stages.py b/tests/unit/health/test_extract_method_stages.py
index 498c88f7d..4f4e294b1 100644
--- a/tests/unit/health/test_extract_method_stages.py
+++ b/tests/unit/health/test_extract_method_stages.py
@@ -128,7 +128,8 @@ def test_persistence_shape_yields_a_staged_plan():
residual = plan.plan["orchestrator"]
assert residual["ccn_after"] == residual["ccn_before"] - removed
# Credited the summed drop, not one span's share.
- assert plan.impact_delta == pytest.approx(2.0 * removed / residual["ccn_before"], abs=1e-3)
+ assert plan.evidence["recovered_share"] == round(removed / residual["ccn_before"], 3)
+ assert plan.impact_delta > 0
# Stages carry the raise their sections hold (it propagates unchanged).
lines = textwrap.dedent(_persist()).splitlines()
assert any(
diff --git a/tests/unit/health/test_gain.py b/tests/unit/health/test_gain.py
new file mode 100644
index 000000000..a07ff05cb
--- /dev/null
+++ b/tests/unit/health/test_gain.py
@@ -0,0 +1,157 @@
+"""A fix's gain is the file rescored without it, never a sum of health_impact."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import BiomarkerResult
+from repowise.core.analysis.health.gain import removal_gain, structure_freed
+from repowise.core.analysis.health.models import Severity
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.opportunity import _recoverable
+from repowise.core.analysis.health.scoring import attach_impacts, score_file
+
+
+def _result(marker: str, severity: Severity, function: str | None = None, **details):
+ return BiomarkerResult(
+ biomarker_type=marker,
+ severity=severity,
+ function_name=function,
+ line_start=1,
+ line_end=2,
+ details=details,
+ reason="",
+ )
+
+
+def _scored(*results: BiomarkerResult):
+ """Findings as the index stores them, and the file's score."""
+ scores, deductions = score_file(list(results))
+ return attach_impacts(list(results), deductions), scores["defect"]
+
+
+def test_saturated_category_gains_almost_nothing_per_marker():
+ findings, _ = _scored(
+ *(_result("complex_method", Severity.CRITICAL, f"f{i}", ccn=60) for i in range(8))
+ )
+ one = findings[0]
+ assert one.health_impact > 0.5
+ assert removal_gain(findings, [(one, 1.0)]) < 0.01
+
+
+def test_floored_file_gains_nothing_from_one_fix():
+ findings, score = _scored(
+ _result("co_change_scatter", Severity.CRITICAL),
+ _result("change_entropy", Severity.CRITICAL),
+ *(
+ _result(marker, Severity.CRITICAL, f"g{i}", ccn=80, nloc=600, max_nesting=12)
+ for i, marker in enumerate(
+ ["complex_method", "large_method", "nested_complexity", "complex_conditional"] * 3
+ )
+ ),
+ )
+ assert score == 1.0
+ assert sum(f.health_impact for f in findings) > 9.0
+ assert all(removal_gain(findings, [(f, 1.0)]) == 0.0 for f in findings)
+
+
+def test_unsaturated_markers_gain_their_impact():
+ findings, _ = _scored(
+ _result("complex_method", Severity.MEDIUM, "a"),
+ _result("dry_violation", Severity.LOW),
+ )
+ for f in findings:
+ assert removal_gain(findings, [(f, 1.0)]) == pytest.approx(f.health_impact, abs=2e-3)
+ both = removal_gain(findings, [(f, 1.0) for f in findings])
+ assert both == pytest.approx(sum(f.health_impact for f in findings), abs=2e-3)
+
+
+def test_code_fix_releases_history_held_at_its_cap():
+ findings, _ = _scored(
+ _result("complex_method", Severity.MEDIUM, "a"),
+ _result("co_change_scatter", Severity.CRITICAL),
+ )
+ code = findings[0]
+ # History sits at 1.0 + structure; removing the structure lowers that cap too.
+ assert removal_gain(findings, [(code, 1.0)]) == pytest.approx(2 * code.health_impact, abs=2e-3)
+
+
+def test_partial_share_gains_part_of_the_whole():
+ findings, _ = _scored(_result("complex_method", Severity.HIGH, "a"))
+ whole = removal_gain(findings, [(findings[0], 1.0)])
+ half = removal_gain(findings, [(findings[0], 0.5)])
+ assert 0 < half < whole
+ assert removal_gain(findings, []) == 0.0
+
+
+def test_governance_and_resolved_rows_never_count():
+ findings, _ = _scored(_result("complex_method", Severity.HIGH, "a"))
+ resolved, _ = _scored(_result("complex_method", Severity.CRITICAL, "b", ccn=90))
+ resolved[0].status = "resolved"
+ governance, _ = _scored(_result("ungoverned_hotspot", Severity.HIGH))
+ rows = findings + resolved + governance
+ assert removal_gain(rows, [(findings[0], 1.0)]) == removal_gain(findings, [(findings[0], 1.0)])
+
+
+def test_structure_freed_ignores_history():
+ findings, _ = _scored(_result("complex_method", Severity.MEDIUM, "a"))
+ assert structure_freed(findings, [(findings[0], 1.0)]) == pytest.approx(
+ findings[0].health_impact, abs=1e-3
+ )
+
+
+def _plan(target: str, share: float | None, impact: float) -> RefactoringSuggestion:
+ evidence = {} if share is None else {"recovered_share": share}
+ return RefactoringSuggestion(
+ refactoring_type="extract_method",
+ file_path="m.py",
+ target_symbol=target,
+ line_start=1,
+ line_end=2,
+ plan={},
+ evidence=evidence,
+ impact_delta=impact,
+ effort_bucket="S",
+ blast_radius={},
+ confidence="high",
+ source_biomarker="complex_method",
+ )
+
+
+def test_opportunity_prices_its_steps_together():
+ findings, _ = _scored(
+ *(_result("complex_method", Severity.CRITICAL, f"f{i}", ccn=60) for i in range(8))
+ )
+ rows = [(_plan(f"f{i}", 1.0, removal_gain(findings, [(findings[i], 1.0)])), f"p{i}") for i in range(8)]
+ credited = {plan_id for _, plan_id in rows}
+ each = sum(s.impact_delta for s, _ in rows)
+ together = _recoverable(rows, credited, findings)
+ assert together == removal_gain(findings, [(f, 1.0) for f in findings])
+ assert together > 10 * each
+
+
+def test_opportunity_without_shares_sums_its_steps():
+ findings, _ = _scored(_result("complex_method", Severity.HIGH, "a"))
+ rows = [(_plan("a", None, 0.4), "p0")]
+ assert _recoverable(rows, {"p0"}, findings) == 0.4
+ assert _recoverable(rows, {"p0"}, None) == 0.4
+
+
+def test_opportunity_prices_only_credited_steps_with_a_share():
+ findings, _ = _scored(
+ *(_result("complex_method", Severity.CRITICAL, f"f{i}", ccn=60) for i in range(3))
+ )
+ rows = [(_plan("f0", 1.0, 0.3), "p0"), (_plan("f1", 0.0, 0.3), "p1"), (_plan("f2", 1.0, 0.3), "p2")]
+ only_f0 = removal_gain(findings, [(findings[0], 1.0)])
+ # p2 is not credited and p1 frees nothing.
+ assert _recoverable(rows, {"p0", "p1"}, findings) == only_f0 > 0
+ # No findings to rescore: the credited steps' own gains are summed.
+ assert _recoverable(rows, {"p0", "p1"}, None) == pytest.approx(0.6)
+
+
+def test_one_step_without_a_share_sums_the_whole_opportunity():
+ findings, _ = _scored(
+ *(_result("complex_method", Severity.CRITICAL, f"f{i}", ccn=60) for i in range(2))
+ )
+ rows = [(_plan("f0", 1.0, 0.3), "p0"), (_plan("f1", None, 0.5), "p1")]
+ assert _recoverable(rows, {"p0", "p1"}, findings) == pytest.approx(0.8)
diff --git a/tests/unit/health/test_queue_value_order.py b/tests/unit/health/test_queue_value_order.py
index fa1c6204e..b63dc0643 100644
--- a/tests/unit/health/test_queue_value_order.py
+++ b/tests/unit/health/test_queue_value_order.py
@@ -113,8 +113,8 @@ def test_the_giant_outranks_the_wizard_on_complexity_removed_times_reach() -> No
assert ranked["complexity removed"] == "963"
assert ranked["files that import it"] == "32 (top fifth)"
assert giant.rank < wizard.rank
- # The wizard still earns more health credit: worth, not credit, orders the band.
- assert giant.gain.value < wizard.gain.value
+ # The giant earns no more health credit: worth, not credit, orders the band.
+ assert giant.gain.value <= wizard.gain.value
def test_history_orders_within_a_band_and_never_lifts_one() -> None:
diff --git a/tests/unit/health/test_refactoring_extract_class.py b/tests/unit/health/test_refactoring_extract_class.py
index b529e8c34..8876eb0ac 100644
--- a/tests/unit/health/test_refactoring_extract_class.py
+++ b/tests/unit/health/test_refactoring_extract_class.py
@@ -14,6 +14,7 @@ from __future__ import annotations
from repowise.core.analysis.health.complexity import ClassComplexity, FunctionComplexity
from repowise.core.analysis.health.complexity.walker import walk_file
+from repowise.core.analysis.health.gain import removal_gain
from repowise.core.analysis.health.refactoring import (
RefactoringContext,
detect_refactorings,
@@ -132,7 +133,9 @@ def test_detector_emits_split_for_god_class():
s = sugs[0]
assert s.refactoring_type == "extract_class"
assert s.target_symbol == "TwoJobs"
- assert s.impact_delta == 2.4
+ # The split answers the whole low_cohesion finding: the file rescored without it.
+ assert s.impact_delta == removal_gain(findings, [(findings[0], 1.0)]) > 0
+ assert s.evidence["recovered_share"] == 1.0
assert s.source_biomarker == "low_cohesion"
assert s.blast_radius == {"dependents_count": 5}
assert s.evidence["lcom4"] == 2
diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.py
index 07a93f08c..a2264fc23 100644
--- a/tests/unit/health/test_refactoring_extract_helper.py
+++ b/tests/unit/health/test_refactoring_extract_helper.py
@@ -12,6 +12,7 @@ occurrences are unambiguous and deterministic.
from __future__ import annotations
from repowise.core.analysis.health.duplication import ClonePair
+from repowise.core.analysis.health.gain import removal_gain
from repowise.core.analysis.health.refactoring import (
RefactoringContext,
detect_refactorings,
@@ -336,7 +337,7 @@ def test_impact_from_overlapping_dry_violation():
findings = [_DryFinding(12, 22, 1.8)]
sugs = detect_refactorings(_ctx("pkg/a.py", [pair], findings=findings))
s = next(s for s in sugs if s.refactoring_type == "extract_helper")
- assert s.impact_delta == 1.8
+ assert s.impact_delta == removal_gain(findings, [(findings[0], 1.0)]) > 0
def test_impact_share_counts_cross_file_lines_only():
@@ -348,7 +349,8 @@ def test_impact_share_counts_cross_file_lines_only():
findings = [_DryFinding(10, 25, 2.0)]
sugs = detect_refactorings(_ctx("pkg/a.py", [block, other, intra], findings=findings))
s = next(s for s in sugs if s.target_symbol == "a.py:10-25")
- assert s.impact_delta == 1.0
+ assert s.evidence["recovered_share"] == 0.5
+ assert s.impact_delta == removal_gain(findings, [(findings[0], 0.5)]) > 0
def test_no_impact_when_finding_disjoint():
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 1a9b4427e..3f94314db 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -12,6 +12,7 @@ import pytest
from repowise.core.analysis.health.complexity.languages import get_language_map
from repowise.core.analysis.health.dataflow import analyze_file, find_extractions
+from repowise.core.analysis.health.gain import removal_gain
from repowise.core.analysis.health.refactoring import detect_refactorings
from repowise.core.analysis.health.refactoring.extract_method import (
ExtractMethodDetector,
@@ -760,7 +761,8 @@ def test_detector_emits_suggestion_for_flagged_function():
fn = _first(_PROCESS)
share = s.evidence["ccn_removed"] / fn.ccn
assert 0 < share < 1
- assert s.impact_delta == round(1.5 * share, 3)
+ assert s.evidence["recovered_share"] == round(share, 3)
+ assert s.impact_delta == removal_gain(findings, [(findings[0], share)]) > 0
# Plan shape is the locked schema.
assert set(s.plan) == {
"span",
@@ -787,7 +789,7 @@ def test_detector_emits_suggestion_for_flagged_function():
}
assert s.plan["call_site"]["replace_span"] == s.plan["span"]
assert set(s.plan["span"]) == {"start", "end"}
- assert set(s.evidence) == {"slice_nloc", "ccn_removed"}
+ assert set(s.evidence) == {"slice_nloc", "ccn_removed", "recovered_share"}
# A categorical claim, not a count: extraction is local, so there is nothing
# to measure. The old ``{"callers_count": 0}`` was a hardcoded literal that
# no consumer could tell apart from a measured zero.
@@ -1063,16 +1065,17 @@ def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):
"fn_node": None}
)()
assert not _worth_extracting(fn, trivial, {"complex_method"})
+ findings = [_Finding("complex_method", "f", 1, 1.2)]
ctx = RefactoringContext(
file_path="m.py",
language="python",
nloc=100,
- findings=[_Finding("complex_method", "f", 1, 1.2)],
+ findings=findings,
function_analyses=[analysis],
)
(s,) = ExtractMethodDetector().detect(ctx)
assert s.plan["span"] == {"start": 20, "end": 27}
- assert s.impact_delta == round(1.2 * 3 / 12, 3)
+ assert s.impact_delta == removal_gain(findings, [(findings[0], 3 / 12)])
# A plan that names the extracted loop's own counter as a parameter cannot
diff --git a/tests/unit/health/test_refactoring_registry.py b/tests/unit/health/test_refactoring_registry.py
index 8303c4ef3..e334fb798 100644
--- a/tests/unit/health/test_refactoring_registry.py
+++ b/tests/unit/health/test_refactoring_registry.py
@@ -70,29 +70,3 @@ def test_unknown_floor_is_no_floor(_one_detector):
def test_disabled_detector_emits_nothing(_one_detector):
out = detect_refactorings(_ctx(), disabled=["fake_all_confidences"])
assert out == []
-
-
-class _ImpactDetector(RefactoringDetector):
- name = "fake_impact"
-
- def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
- s = _suggestion("high", name=self.name)
- s.impact_delta = 0.8
- s.source_biomarker = "complex_method"
- return [s]
-
-
[email protected](("history", "expected"), [(1.8, 1.6), (0.5, 0.8)])
-def test_recovered_impact_counts_the_history_the_fix_releases(monkeypatch, history, expected):
- """History held at its cap (1.0 + 0.8) falls to the 1.0 cap once the 0.8
- code finding goes, so the fix recovers 1.6; history under the new cap
- releases nothing."""
- from types import SimpleNamespace
-
- monkeypatch.setattr(registry, "_REGISTRY", [_ImpactDetector()])
- ctx = _ctx()
- ctx.findings = [
- SimpleNamespace(biomarker_type="complex_method", health_impact=0.8),
- SimpleNamespace(biomarker_type="prior_defect", health_impact=history),
- ]
- assert detect_refactorings(ctx)[0].impact_delta == pytest.approx(expected)
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index eb25d17c7..7fcee3f4f 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -2995,10 +2995,12 @@ async def test_what_if_names_the_points_a_fix_recovers(setup_mcp, session, popul
assert row["ceiling"] == 9.0
assert "target_out_of_reach" not in row
top = block["top_fixes"][0]
- assert (top["biomarker_type"], top["points"]) == ("complex_method", 2.0)
- # 2.0 structure points also lower history's cap from 2.5 to 2.0: 4.5 -> 7.0,
- # on 200 of the headline's 500 nloc; the only hotspot carries all of it.
- assert top["gain"] == {"file": 2.5, "average": 1.0, "hotspot": 2.5}
+ # Points are the file rescored without the finding, not its stored impact:
+ # a high nested_complexity frees 1.45 (its 1.0 impact reads less).
+ assert (top["biomarker_type"], top["points"]) == ("nested_complexity", 1.45)
+ # History's cap stays above 2.5 at 1.55 structure: 4.5 -> 5.95, on 200 of
+ # the headline's 500 nloc; the only hotspot carries all of it.
+ assert top["gain"] == {"file": 1.45, "average": 0.581, "hotspot": 1.452}
assert row["fix_all_structure"]["file"] == 4.5