Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(refactoring): credit extract_method only with the impact its span recovers (#2570)
Raghav Chamadiyaa066ed741b37
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex e768e67e3..b42a580ec 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -63,7 +63,7 @@ web).| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. || `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. Names are omitted rather than invented: `suggested_name` and a group's `name` / `suggested_file` are `null` whenever no fact anchors a name, and `suggested_site.directory` is `null` unless an occurrence actually lives in that directory. || `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. |-| `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. |+| `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. Extract Method credits only what its one span removes: the residual method and the new helper are re-graded with the source biomarker's own thresholds, so a span that leaves the method in the same severity band recovers `0`, and one that drops a band recovers the difference. || `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. || `blast_radius` | What else must move: the callers, co-change partners, and importing files. Extract Method carries `{"scope": "local"}` instead — extraction adds a private helper and changes no signature, so nothing outside the file moves and there is no count to make. || `confidence` | `low` \| `medium` \| `high` (drives the `min_confidence` surface gate). |diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.pyindex 50dbd846f..9d799c4d1 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py@@ -49,6 +49,20 @@ class BrainMethodDetector:return self._DEPENDENTS_THRESHOLDreturn min(self._DEPENDENTS_THRESHOLD, max(p80, self._CENTRALITY_MIN_FLOOR))+ @classmethod+ def severity_for(cls, ccn: int, nloc: int) -> Severity | None:+ """The severity a function of this shape earns in a file that already+ clears the centrality gate, ``None`` below the size/complexity bar."""+ if nloc < cls._NLOC_THRESHOLD or ccn < cls._CCN_THRESHOLD:+ return None+ return (+ Severity.CRITICAL+ if ccn >= 20 and nloc >= 150+ else Severity.HIGH+ if ccn >= 14 or nloc >= 120+ else Severity.MEDIUM+ )+def detect(self, ctx: FileContext) -> list[BiomarkerResult]:floor = self._centrality_floor(ctx)if ctx.dependents_count < floor:@@ -56,18 +70,9 @@ class BrainMethodDetector:out: list[BiomarkerResult] = []for fn in ctx.all_functions:- if fn.nloc < self._NLOC_THRESHOLD:- continue- if fn.ccn < self._CCN_THRESHOLD:+ severity = self.severity_for(fn.ccn, fn.nloc)+ if severity is None:continue-- severity = (- Severity.CRITICAL- if fn.ccn >= 20 and fn.nloc >= 150- else Severity.HIGH- if fn.ccn >= 14 or fn.nloc >= 120- else Severity.MEDIUM- )out.append(BiomarkerResult(biomarker_type=self.name,diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.pyindex 920103d7b..b0cd64f3c 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py@@ -16,18 +16,19 @@ class ComplexMethodDetector:_CCN_THRESHOLD = 9+ @classmethod+ def severity_for(cls, ccn: int, nloc: int) -> Severity | None:+ """The severity a function of this shape earns, ``None`` below the bar."""+ if ccn < cls._CCN_THRESHOLD:+ return None+ return Severity.CRITICAL if ccn >= 25 else Severity.HIGH if ccn >= 15 else Severity.MEDIUM+def detect(self, ctx: FileContext) -> list[BiomarkerResult]:out: list[BiomarkerResult] = []for fn in ctx.all_functions:- if fn.ccn < self._CCN_THRESHOLD:+ severity = self.severity_for(fn.ccn, fn.nloc)+ if severity is None:continue- severity = (- Severity.CRITICAL- if fn.ccn >= 25- else Severity.HIGH- if fn.ccn >= 15- else Severity.MEDIUM- )out.append(BiomarkerResult(biomarker_type=self.name,diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.pyindex 6a09a6260..6bcc2dda7 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py@@ -33,20 +33,27 @@ class LargeMethodDetector:# a per-function flat-match flag threaded from the walker (a larger change)._CCN_FLOOR = 3+ @classmethod+ def severity_for(cls, ccn: int, nloc: int) -> Severity | None:+ """The severity a function of this shape earns, ``None`` below the bar."""+ if nloc < cls._NLOC_THRESHOLD or ccn < cls._CCN_FLOOR:+ return None+ return (+ Severity.CRITICAL+ if nloc >= 200+ else Severity.HIGH+ if nloc >= 120+ else Severity.MEDIUM+ if nloc >= 90+ else Severity.LOW+ )+def detect(self, ctx: FileContext) -> list[BiomarkerResult]:out: list[BiomarkerResult] = []for fn in ctx.all_functions:- if fn.nloc < self._NLOC_THRESHOLD or fn.ccn < self._CCN_FLOOR:+ severity = self.severity_for(fn.ccn, fn.nloc)+ if severity is None:continue- severity = (- Severity.CRITICAL- if fn.nloc >= 200- else Severity.HIGH- if fn.nloc >= 120- else Severity.MEDIUM- if fn.nloc >= 90- else Severity.LOW- )out.append(BiomarkerResult(biomarker_type=self.name,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.pyindex c21e3dc48..d87f50270 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,6 +7,17 @@ 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 what the extraction itself recovers, not the whole+finding. The residual method keeps ``ccn - ccn_removed`` decision points and+``nloc - slice_nloc + 1`` lines (the call replaces the span), the new helper+carries ``ccn_removed + 1`` and ``slice_nloc``, and each is re-graded with the+source biomarker's own severity rule. The finding's impact is credited in+proportion to the severity deduction that disappears: all of it when both+shapes fall below the biomarker's bar, the band difference when the residual+only drops a band, and nothing when a CCN 209 method sheds 6 and stays+critical. A function that needs several extractions therefore shows several+partial steps rather than one step claiming the full finding.+The candidate spans + IN/OUT come from ``dataflow.find_extractions``; thismodule only matches each analysed function to the biomarker finding that flagsit (for the recovered impact), picks the strongest extraction, and renders the@@ -34,16 +45,22 @@ Plan shape (open dict, no migration):from __future__ import annotations+from collections.abc import Callablefrom typing import TYPE_CHECKING, Any+from ..biomarkers.brain_method import BrainMethodDetector+from ..biomarkers.complex_method import ComplexMethodDetector+from ..biomarkers.large_method import LargeMethodDetectorfrom ..complexity.languages import get_language_mapfrom ..dataflow import find_extractions+from ..scoring import severity_deductionfrom .models import RefactoringContext, RefactoringSuggestionfrom .naming import identifier_slugfrom .registry import RefactoringDetector, effort_bucket, registerif TYPE_CHECKING:from ..dataflow import Extraction, FunctionAnalysis+ from ..models import Severity# OUT values whose name describes the variable's role, not the block's# product: ``compute_result`` names nothing the reader did not know.@@ -56,6 +73,13 @@ _UNINFORMATIVE_OUT = frozenset(# list never exceeds (and stays consistent with) what health surfaces._SOURCE_BIOMARKERS = ("brain_method", "large_method", "complex_method")+# Each source biomarker's own ``(ccn, nloc) -> severity`` rule.+_SEVERITY_RULE: dict[str, Callable[[int, int], Severity | None]] = {+ "brain_method": BrainMethodDetector.severity_for,+ "large_method": LargeMethodDetector.severity_for,+ "complex_method": ComplexMethodDetector.severity_for,+}+@registerclass ExtractMethodDetector(RefactoringDetector):@@ -71,14 +95,15 @@ class ExtractMethodDetector(RefactoringDetector):out: list[RefactoringSuggestion] = []for analysis in analyses:- impact, source = self._impact_for(analysis, ctx.findings)- if not source:+ matched = self._findings_for(analysis, ctx.findings)+ if not matched:# Only suggest where a method biomarker actually fired.continuecandidates = find_extractions(analysis, lmap)if not candidates:continuebest = candidates[0] # already best-first+ impact, source = self._impact_for(analysis, best, matched)out.append(RefactoringSuggestion(refactoring_type=self.name,@@ -109,12 +134,11 @@ class ExtractMethodDetector(RefactoringDetector):return out@staticmethod- def _impact_for(analysis: FunctionAnalysis, findings: list[Any]) -> tuple[float, str]:- """Recovered impact + source biomarker for *analysis*, from the file's- method-smell findings. Matches by function name and line containment so- the right finding is picked when a name repeats."""- best_impact = 0.0- best_source = ""+ def _findings_for(analysis: FunctionAnalysis, findings: list[Any]) -> list[Any]:+ """The file's method-smell findings on *analysis*. Matches by function+ name and line containment so the right finding is picked when a name+ repeats."""+ out = []for f in findings:if getattr(f, "biomarker_type", "") not in _SOURCE_BIOMARKERS:continue@@ -123,11 +147,23 @@ class ExtractMethodDetector(RefactoringDetector):line = getattr(f, "line_start", None)if line is not None and not (analysis.start_line <= line <= analysis.end_line):continue- impact = float(getattr(f, "health_impact", 0.0) or 0.0)- if impact >= best_impact:- best_impact = impact- best_source = getattr(f, "biomarker_type", "")- return best_impact, best_source+ out.append(f)+ return out++ @staticmethod+ def _impact_for(+ analysis: FunctionAnalysis, extraction: Extraction, findings: list[Any]+ ) -> tuple[float, str]:+ """Impact *extraction* recovers + the source biomarker it recovers it+ from. The finding recovering the most wins; when none recovers+ anything, the largest finding still names the cause."""+ best: tuple[float, float, str] = (-1.0, -1.0, "")+ for f in findings:+ biomarker = getattr(f, "biomarker_type", "")+ full = float(getattr(f, "health_impact", 0.0) or 0.0)+ recovered = full * _recovered_fraction(biomarker, analysis, extraction)+ best = max(best, (recovered, full, biomarker))+ return best[0], best[2]@staticmethoddef _suggested_name(analysis: FunctionAnalysis, extraction: Extraction) -> str | None:@@ -167,3 +203,27 @@ class ExtractMethodDetector(RefactoringDetector):if extraction.ccn_removed >= 2 and len(extraction.params) <= 4:return "high"return "medium"+++def _recovered_fraction(+ biomarker: str, analysis: FunctionAnalysis, extraction: Extraction+) -> float:+ """Share of *biomarker*'s deduction that applying *extraction* removes.++ Both post-extraction shapes (the residual method and the new helper) are+ graded with the biomarker's own rule; whatever deduction they still earn+ is subtracted. Brain Method's file-level centrality gate is unchanged by a+ local extraction, so only its size/complexity bar is re-checked.+ """+ rule = _SEVERITY_RULE[biomarker]+ before = rule(analysis.ccn, analysis.nloc)+ if before is None:+ # These metrics do not reproduce the finding, so there is no band to+ # re-grade against; keep the finding's own impact.+ return 1.0+ residual = rule(+ analysis.ccn - extraction.ccn_removed, analysis.nloc - extraction.slice_nloc + 1+ )+ helper = rule(extraction.ccn_removed + 1, extraction.slice_nloc)+ remaining = sum(severity_deduction(s) for s in (residual, helper) if s is not None)+ return max(0.0, 1.0 - remaining / severity_deduction(before))diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex f0b2bf5e7..62ae5d4ea 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -215,8 +215,9 @@ class RefactoringSuggestion:plan: dict[str, Any]# The signals that justify the suggestion (LCOM4, WMC, clone ranges, ...).evidence: dict[str, Any]- # Health score the refactoring would recover if applied: the deduction of- # the source biomarker finding, plus any history deduction it releases. >= 0.+ # 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.impact_delta: float# Effort estimate — "S" | "M" | "L" | "XL" (from the target's size).effort_bucket: strdiff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonindex 1c3c2eb61..bdda29b80 100644--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -86,14 +86,14 @@"mechanical_steps": 1,"opportunity_id": "refop2_d82fe75fc83659cefa14","rank_factors": {- "benefit": 1.452,+ "benefit": 0.605,"cost": 1.0,"mechanical_share": 0.5,"primary_problem": 0.5,"risk": 0.0},- "rank_score": 1.452,- "recoverable_health": 1.452,+ "rank_score": 0.605,+ "recoverable_health": 0.605,"refactoring_model_version": 2,"step_count": 1,"steps": [@@ -115,7 +115,7 @@"confidence": "high","effort_bucket": "S","file_path": "account.ts",- "impact_delta": 1.452,+ "impact_delta": 0.605,"plan_id": "refac2_a5f94bcfa0d5e0e24f37","refactoring_type": "extract_method","relocated_by": null,@@ -124,14 +124,14 @@}],"why_ranked": [- {- "factor": "benefit",- "value": 1.452- },{"factor": "cost","value": 1.0},+ {+ "factor": "benefit",+ "value": 0.605+ },{"factor": "mechanical_share","value": 0.5@@ -153,14 +153,14 @@"mechanical_steps": 1,"opportunity_id": "refop2_443f00cfefc5d4f86685","rank_factors": {- "benefit": 1.452,+ "benefit": 0.605,"cost": 1.0,"mechanical_share": 0.5,"primary_problem": 0.5,"risk": 0.0},- "rank_score": 1.452,- "recoverable_health": 1.452,+ "rank_score": 0.605,+ "recoverable_health": 0.605,"refactoring_model_version": 2,"step_count": 1,"steps": [@@ -182,7 +182,7 @@"confidence": "high","effort_bucket": "S","file_path": "workspace.ts",- "impact_delta": 1.452,+ "impact_delta": 0.605,"plan_id": "refac2_b21dea1501a82eec255a","refactoring_type": "extract_method","relocated_by": null,@@ -191,14 +191,14 @@}],"why_ranked": [- {- "factor": "benefit",- "value": 1.452- },{"factor": "cost","value": 1.0},+ {+ "factor": "benefit",+ "value": 0.605+ },{"factor": "mechanical_share","value": 0.5diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex b17ee46cc..b5a715fd5 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -12,9 +12,14 @@ import pytestfrom repowise.core.analysis.health.complexity.languages import get_language_mapfrom repowise.core.analysis.health.dataflow import analyze_file, find_extractions+from repowise.core.analysis.health.models import Severityfrom repowise.core.analysis.health.refactoring import detect_refactorings-from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector+from repowise.core.analysis.health.refactoring.extract_method import (+ ExtractMethodDetector,+ _recovered_fraction,+)from repowise.core.analysis.health.refactoring.models import RefactoringContext+from repowise.core.analysis.health.scoring import severity_deduction# A long function whose tail (compute-average loop) is a clean extraction._PROCESS = """@@ -442,3 +447,61 @@ def test_detector_is_deterministic():first = run()for _ in range(3):assert run() == first+++# -- honest impact --------------------------------------------------------------+++@dataclass+class _Shape:+ ccn: int+ nloc: int+++@dataclass+class _Span:+ ccn_removed: int+ slice_nloc: int+++def test_extraction_that_clears_the_bar_recovers_the_whole_finding():+ # CCN 12 -> 6 residual, helper CCN 7: both below complex_method's bar of 9.+ assert _recovered_fraction("complex_method", _Shape(12, 40), _Span(6, 15)) == 1.0+++def test_extraction_that_only_drops_a_band_recovers_the_band_difference():+ # CCN 15 (high) -> 12 (medium): still a complex method, one band lower.+ got = _recovered_fraction("complex_method", _Shape(15, 40), _Span(3, 8))+ expected = 1 - severity_deduction(Severity.MEDIUM) / severity_deduction(Severity.HIGH)+ assert got == pytest.approx(expected)+++def test_extraction_that_stays_in_band_recovers_nothing():+ # CCN 209 -> 203 stays critical for both brain_method and complex_method.+ assert _recovered_fraction("brain_method", _Shape(209, 900), _Span(6, 20)) == 0.0+ assert _recovered_fraction("complex_method", _Shape(209, 900), _Span(6, 20)) == 0.0+++def test_helper_that_inherits_the_smell_is_charged_against_the_recovery():+ # 130-line method (high) lifts 100 lines out: the residual clears the bar+ # but the helper is itself a 100-line large_method (medium).+ got = _recovered_fraction("large_method", _Shape(12, 130), _Span(6, 100))+ assert 0.0 < got < 1.0+++def test_detector_credits_only_what_the_best_extraction_recovers():+ # The finding claims a CCN far above what _PROCESS's best span can clear,+ # so the plan still stands but recovers nothing.+ fns = _analyses(_PROCESS)+ fn = fns[0]+ fn.ccn, fn.nloc = 40, 18+ ctx = RefactoringContext(+ file_path="m.py",+ language="python",+ nloc=100,+ findings=[_Finding("complex_method", "process", line_start=2, health_impact=2.0)],+ function_analyses=[fn],+ )+ (s,) = ExtractMethodDetector().detect(ctx)+ assert s.source_biomarker == "complex_method"+ assert s.impact_delta == 0.0