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): Extract Method refactoring over the dataflow layer (#615)

Raghav Chamadiya8183e75e9b81
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 199812366..4d6faf0d6 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -10,7 +10,7 @@ Python over tree-sitter + git data, designed to finish in under 30 seconds on a
3 000-file repo.
<div align="center">
-<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle, Split File) your agent executes" width="100%" />
+<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Extract Method, Move Method, Break Cycle, Split File) your agent executes" width="100%" />
</div>
Code health runs as a loop: **measure** every file across three signals,
@@ -568,6 +568,7 @@ ship today:
|------|---------------|------------|
| **Extract Class** | The cohesion groups an incohesive / god class should split into — the exact methods + fields per group. | LCOM4 union-find components; god-class shape confirmed by Lanza-Marinescu (WMC = Σ McCabe, TCC). |
| **Extract Helper** | A clone's exact occurrences and where the shared helper should live. | Rabin–Karp clone pairs (line ranges + token count + co-change); extraction site = community centroid of the files. Transitive clones are clustered into one suggestion, not pairwise nags. |
+| **Extract Method** | A cohesive slice of a long function to lift into a helper, with the inferred parameter (in) and return (out) signature. | Intra-procedural dataflow (CFG + def/use + reaching definitions) over functions a method biomarker already flagged; a single-exit span with a real decision point and no partial branch, `in`/`out` inferred by liveness. Python first. |
| **Move Method** | A feature-envy method and the class it actually belongs to. | Jaccard distance of the method's entity set (fields/methods it touches) to each class over the call graph; fires only when a foreign class is clearly nearer than its own. |
| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | Strongly-connected component → greedy minimum feedback arc set over the real import edges. |
| **Split File** | The cohesive files an oversized module should decompose into — which symbols move where, plus the import edits in every dependent. | Community detection (Leiden/Louvain) over a weighted intra-file symbol graph, gated on partition **modularity**. Language-agnostic (reads `defines`/`calls` edges); the file-level analog of Extract Class. |
@@ -801,7 +802,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts) · 7.0
| Health trend tracking | ✅ | ✅ | ❌ | ❌ |
| Declining health alerts | ✅ | ✅ | ❌ | ❌ |
| Refactoring recommendations | ✅ deterministic | ✅ | ❌ | ❌ |
-| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Move Method / Break Cycle / Split File, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file |
+| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Method / Move Method / Break Cycle / Split File, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file |
| Free for internal use | ✅ AGPL-3.0 | ❌ $15–30/author | ✅ public repos | ❌ |
## See also
diff --git a/docs/REFACTORING.md b/docs/REFACTORING.md
index f50066c75..42886675f 100644
--- a/docs/REFACTORING.md
+++ b/docs/REFACTORING.md
@@ -23,7 +23,7 @@ LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in
<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — biomarkers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" />
</div>
-## The five detectors
+## The six detectors
Each detector is a self-contained module registered into a registry (adding a
refactoring type is a new file + a registry entry, like the biomarker registry).
@@ -34,6 +34,7 @@ one** — and produces stable-sorted, deterministic output.
|------|---------------|---------------------------|
| **Extract Class** | The cohesion groups an incohesive / god class should split into — the exact methods + fields per group. | LCOM4 union-find components (each disconnected component is a candidate class), with the god-class shape confirmed via Lanza-Marinescu (WMC = Σ McCabe, TCC). |
| **Extract Helper** | A clone's exact occurrences and where the shared helper belongs. | Rabin–Karp clone pairs (line ranges, token count, co-change). The extraction site is the community centroid of the involved files; transitive clones (A↔B, B↔C) are clustered into one suggestion, not pairwise nags. |
+| **Extract Method** | A cohesive slice of a long function to lift into a helper, with the inferred parameter (in) and return (out) signature. | An intra-procedural dataflow pass (CFG + def/use + reaching definitions) over functions a method biomarker already flagged. A candidate span cuts at statement boundaries within one block (no partial branch / mid-`try`), carries no control-flow jump (single clean exit) and a real decision point, and infers `in`/`out` by line-based liveness over the def/use facts. Python first. |
| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. |
| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. |
| **Split File** | The cohesive files an oversized module should decompose into — which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |
@@ -147,7 +148,9 @@ a behavior-preservation prompt carrying the structured plan **plus the
graph/co-change context** a bare codegen tool throws away, and returns the
refactored code and a unified diff. Where a self-check is cheap and meaningful it
runs one: Extract Class re-walks the generated classes for an **LCOM4 before/after
-delta**, and Split File re-walks the generated files to assert each is **below the
+delta**, Extract Method re-walks the generated code to confirm the **residual
+method's cyclomatic complexity dropped** below the original's, and Split File
+re-walks the generated files to assert each is **below the
size floor** and the symbols are **partitioned with no duplication**. Results are
cached on disk by a content hash (plan + source + model), so the same plan never
pays twice.
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py
index 7dbe987a2..d729228bd 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py
@@ -671,6 +671,7 @@ def _render_refactoring_targets(
)
_render_extract_class_plans_md(ranked_plans)
_render_extract_helper_plans_md(ranked_plans)
+ _render_extract_method_plans_md(ranked_plans)
_render_move_method_plans_md(ranked_plans)
_render_break_cycle_plans_md(ranked_plans)
_render_split_file_plans_md(ranked_plans)
@@ -695,6 +696,7 @@ def _render_refactoring_targets(
console.print(table)
_render_extract_class_plans_console(ranked_plans)
_render_extract_helper_plans_console(ranked_plans)
+ _render_extract_method_plans_console(ranked_plans)
_render_move_method_plans_console(ranked_plans)
_render_break_cycle_plans_console(ranked_plans)
_render_split_file_plans_console(ranked_plans)
@@ -780,6 +782,46 @@ def _render_extract_helper_plans_md(plans: list[dict]) -> None:
click.echo(f" - {o['file']}:{o['line_start']}-{o['line_end']}")
+def _render_extract_method_plans_console(plans: list[dict]) -> None:
+ """Print the concrete Extract Method (long-function split) plans below the table."""
+ em_plans = [p for p in plans if p["refactoring_type"] == "extract_method"]
+ if not em_plans:
+ return
+ console.print(f"\n[bold]Extract Method plans ({len(em_plans)})[/bold]")
+ for p in em_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ span = pl.get("span", {}) or {}
+ params = ", ".join(pl.get("params", [])) or "—"
+ returns = ", ".join(pl.get("returns", [])) or "none"
+ console.print(
+ f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim] — "
+ f"extract lines {span.get('start')}-{span.get('end')} "
+ f"[dim]({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN, "
+ f"recover ~{p['impact_delta']:.2f}, effort {p['effort_bucket']}, "
+ f"{p['confidence']} confidence)[/dim]"
+ )
+ console.print(f" [dim]params (in):[/dim] {params} [dim]returns (out):[/dim] {returns}")
+
+
+def _render_extract_method_plans_md(plans: list[dict]) -> None:
+ em_plans = [p for p in plans if p["refactoring_type"] == "extract_method"]
+ if not em_plans:
+ return
+ click.echo("\n## Extract Method plans\n")
+ for p in em_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ span = pl.get("span", {}) or {}
+ params = ", ".join(pl.get("params", [])) or "—"
+ returns = ", ".join(pl.get("returns", [])) or "none"
+ click.echo(
+ f"- **{p['target_symbol']}** ({p['file_path']}) — extract lines "
+ f"{span.get('start')}-{span.get('end')} ({ev.get('slice_nloc')} lines, "
+ f"-{ev.get('ccn_removed')} CCN) · in: {params} · out: {returns}"
+ )
+
+
def _render_move_method_plans_console(plans: list[dict]) -> None:
"""Print the concrete Move Method (feature-envy) plans below the table."""
mm_plans = [p for p in plans if p["refactoring_type"] == "move_method"]
@@ -898,9 +940,7 @@ def _render_split_file_plans_md(plans: list[dict]) -> None:
f"modularity {ev.get('modularity')}, split into {len(groups)} files:"
)
for i, g in enumerate(groups, 1):
- click.echo(
- f" {i}. `{g.get('suggested_file')}`: {', '.join(g.get('symbols', []))}"
- )
+ click.echo(f" {i}. `{g.get('suggested_file')}`: {', '.join(g.get('symbols', []))}")
residual = pl.get("residual")
if residual and residual.get("symbols"):
click.echo(f" - core (shared): {', '.join(residual['symbols'])}")
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
index 85a1a4440..fad08bc9f 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
@@ -55,6 +55,7 @@ from .gating import (
is_flagged_function,
)
from .reaching import ReachingDefinitions, compute_reaching
+from .slice import Extraction, find_extractions
__all__ = [
"CFG",
@@ -64,6 +65,7 @@ __all__ = [
"CFGPassStats",
"DefUseDialect",
"Definition",
+ "Extraction",
"FileAnalysisResult",
"FileAnalysisStats",
"FileCFGResult",
@@ -80,6 +82,7 @@ __all__ = [
"build_cfgs_for_file",
"compute_def_use",
"compute_reaching",
+ "find_extractions",
"get_defuse_dialect",
"is_flagged",
"is_flagged_function",
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/analyze.py b/packages/core/src/repowise/core/analysis/health/dataflow/analyze.py
index 874db0408..aab828dcc 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/analyze.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/analyze.py
@@ -16,7 +16,7 @@ function, never a raise.
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import structlog
@@ -48,6 +48,11 @@ class FunctionAnalysis:
cfg: CFG
def_use: FunctionDefUse
reaching: ReachingDefinitions
+ # The function's tree-sitter node, retained so dataflow consumers (the
+ # Extract Method slicer) can re-walk its statement structure. Typed ``Any``
+ # to keep the model free of a tree-sitter import; the node keeps its parse
+ # tree alive while referenced, so it stays valid after analysis returns.
+ fn_node: Any = None
@dataclass
@@ -153,6 +158,7 @@ def analyze_file(
cfg=cfg,
def_use=def_use,
reaching=reaching,
+ fn_node=fn_node,
)
)
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
new file mode 100644
index 000000000..bf1638039
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -0,0 +1,243 @@
+"""Extract Method slicing: find safe, single-exit spans with IN/OUT inference.
+
+The first user-facing consumer of the dataflow layer. Given a function's
+analysis (CFG + def/use from D2), it finds contiguous statement spans that can
+be lifted into a helper method without changing behaviour, and infers the
+helper's signature:
+
+- **IN (parameters)** -- variables the span *reads* whose value is produced
+ before the span (defined-before, used-inside).
+- **OUT (return)** -- variables the span *defines* that are *used after* it,
+ with no intervening redefinition (so the helper returns the live value).
+
+**Extractability predicate (precision-first).** A span is a candidate only when
+it cuts at statement boundaries within a single block (so never a partial
+branch or a mid-``try`` split), contains no control-flow jump that leaves the
+region (``return`` / ``raise`` / ``break`` / ``continue`` -> single clean exit),
+removes real complexity (at least one decision point), is substantial enough to
+matter, and has at most one return and a small parameter list. Everything else
+is suppressed -- ten great extractions, not two hundred maybes.
+
+Line-based liveness over D2's def/use occurrences realises the IN/OUT inference;
+the CFG/jump scan realises the single-exit predicate. Python only for now;
+the jump classification is the sole language-specific piece.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from ..complexity.languages import LanguageNodeMap
+ from .analyze import FunctionAnalysis
+ from .defuse import FunctionDefUse
+
+# Python jump node types (a span containing any of these is not single-exit).
+# The sole language-specific set here; generalised behind a dialect later.
+_JUMP_KINDS: frozenset[str] = frozenset(
+ {"return_statement", "raise_statement", "break_statement", "continue_statement"}
+)
+# Nested scopes whose statements/jumps belong to a different function.
+_SCOPE_BOUNDARIES: frozenset[str] = frozenset(
+ {"lambda", "function_definition", "async_function_definition"}
+)
+
+# Gates (precision-first; tuned to suppress trivial or unwieldy extractions).
+_MIN_STMTS = 2 # at least two statements
+_MIN_SLICE_NLOC = 6 # the extracted helper is substantial
+_MIN_CCN_REMOVED = 1 # extraction must remove a real decision point
+_MAX_PARAMS = 5 # too many ins => the span is not cohesive
+_MAX_RETURNS = 1 # a single clean return (v1); multi-output is future work
+# Backstop against a pathological function producing too many sub-ranges.
+_MAX_CANDIDATES = 4000
+
+
+@dataclass(frozen=True)
+class Extraction:
+ """One safe Extract Method candidate over a function.
+
+ ``start_line`` / ``end_line`` bound the span (1-indexed, inclusive).
+ ``params`` are the inferred IN variables, ``returns`` the inferred OUT
+ variable(s). ``slice_nloc`` is the span's statement line count and
+ ``ccn_removed`` the decision points it carries (the complexity the residual
+ method sheds).
+ """
+
+ start_line: int
+ end_line: int
+ params: tuple[str, ...]
+ returns: tuple[str, ...]
+ slice_nloc: int
+ ccn_removed: int
+
+
+def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[Extraction]:
+ """Return safe Extract Method candidates for *analysis*, best first.
+
+ Best is most complexity removed, then largest span, then fewest parameters,
+ then earliest -- a deterministic order. Empty when the function has no AST
+ node retained or no span clears the extractability gates.
+ """
+ fn_node = analysis.fn_node
+ if fn_node is None:
+ return []
+ body = fn_node.child_by_field_name("body")
+ if body is None:
+ return []
+
+ def_lines, use_lines = _var_lines(analysis.def_use)
+ decision_kinds = (
+ lmap.branch_kinds
+ | lmap.loop_kinds
+ | lmap.case_kinds
+ | lmap.catch_kinds
+ | lmap.boolean_operator_kinds
+ )
+
+ out: list[Extraction] = []
+ evaluated = 0
+ for block in _all_blocks(fn_node):
+ stmts = block.named_children
+ n = len(stmts)
+ is_body = block.id == body.id
+ for i in range(n):
+ for j in range(i, n):
+ evaluated += 1
+ if evaluated > _MAX_CANDIDATES:
+ return _sorted(out)
+ length = j - i + 1
+ if length < _MIN_STMTS:
+ continue
+ # Never extract the whole function body (that is not a split).
+ if is_body and length == n:
+ continue
+ span = stmts[i : j + 1]
+ decisions, has_jump = _span_metrics(span, decision_kinds)
+ if has_jump or decisions < _MIN_CCN_REMOVED:
+ continue
+ slice_nloc = sum(st.end_point[0] - st.start_point[0] + 1 for st in span)
+ if slice_nloc < _MIN_SLICE_NLOC:
+ continue
+ s = span[0].start_point[0] + 1
+ e = span[-1].end_point[0] + 1
+ params, returns = _infer_in_out(def_lines, use_lines, s, e)
+ if len(params) > _MAX_PARAMS or len(returns) > _MAX_RETURNS:
+ continue
+ out.append(
+ Extraction(
+ start_line=s,
+ end_line=e,
+ params=params,
+ returns=returns,
+ slice_nloc=slice_nloc,
+ ccn_removed=decisions,
+ )
+ )
+ return _sorted(out)
+
+
+def _sorted(candidates: list[Extraction]) -> list[Extraction]:
+ return sorted(
+ candidates,
+ key=lambda x: (-x.ccn_removed, -x.slice_nloc, len(x.params), x.start_line),
+ )
+
+
+def _var_lines(def_use: FunctionDefUse) -> tuple[dict[str, list[int]], dict[str, list[int]]]:
+ """Per-variable sorted def lines and use lines from D2's facts.
+
+ Parameter definitions are included (seeded at the signature line), so a
+ parameter naturally counts as "defined before" any body span.
+ """
+ def_lines: dict[str, list[int]] = defaultdict(list)
+ use_lines: dict[str, list[int]] = defaultdict(list)
+ for d in def_use.definitions:
+ def_lines[d.var].append(d.line)
+ for bdu in def_use.blocks.values():
+ for u in bdu.uses:
+ use_lines[u.name].append(u.line)
+ for lines in def_lines.values():
+ lines.sort()
+ for lines in use_lines.values():
+ lines.sort()
+ return def_lines, use_lines
+
+
+def _infer_in_out(
+ def_lines: dict[str, list[int]],
+ use_lines: dict[str, list[int]],
+ s: int,
+ e: int,
+) -> tuple[tuple[str, ...], tuple[str, ...]]:
+ """Infer IN (parameters) and OUT (return) variables for span ``[s, e]``.
+
+ IN: a variable read in the span whose first in-span read is not preceded by
+ an in-span write, and which has a definition before the span (a parameter or
+ an earlier assignment). OUT: a variable written in the span and read after
+ it, with no redefinition between the span and that first later read.
+ """
+ params: list[str] = []
+ returns: list[str] = []
+ for var in sorted(set(def_lines) | set(use_lines)):
+ dl = def_lines.get(var, [])
+ ul = use_lines.get(var, [])
+ in_uses = [ln for ln in ul if s <= ln <= e]
+ in_defs = [ln for ln in dl if s <= ln <= e]
+
+ if in_uses and any(ln < s for ln in dl):
+ first_use = in_uses[0]
+ if not any(ln < first_use for ln in in_defs):
+ params.append(var)
+
+ if in_defs:
+ after_uses = [ln for ln in ul if ln > e]
+ if after_uses:
+ first_after = after_uses[0]
+ redefined = any(e < ln < first_after for ln in dl)
+ if not redefined:
+ returns.append(var)
+ return tuple(params), tuple(returns)
+
+
+def _all_blocks(fn_node: Node) -> list[Node]:
+ """Every statement ``block`` in the function (body + nested), excluding the
+ bodies of nested functions / lambdas."""
+ body = fn_node.child_by_field_name("body")
+ if body is None:
+ return []
+ blocks: list[Node] = []
+ stack: list[Node] = [body]
+ while stack:
+ node = stack.pop()
+ if node.type == "block":
+ blocks.append(node)
+ for child in node.children:
+ if child.type in _SCOPE_BOUNDARIES:
+ continue
+ stack.append(child)
+ return blocks
+
+
+def _span_metrics(span: list[Node], decision_kinds: frozenset[str]) -> tuple[int, bool]:
+ """Decision-point count and jump presence within *span* (nested scopes are
+ not descended into)."""
+ decisions = 0
+ has_jump = False
+ for root in span:
+ stack: list[Node] = [root]
+ while stack:
+ node = stack.pop()
+ t = node.type
+ if t in _JUMP_KINDS:
+ has_jump = True
+ if t in decision_kinds:
+ decisions += 1
+ for child in node.children:
+ if child.type in _SCOPE_BOUNDARIES:
+ continue
+ stack.append(child)
+ return decisions, has_jump
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 14dd17e87..f1ae72eeb 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -35,6 +35,7 @@ from .biomarkers import FileContext, detect_all
from .biomarkers.base import HasEdge
from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
+from .dataflow import analyze_file
from .duplication import DuplicationReport, detect_clones
from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity
from .perf import (
@@ -55,6 +56,10 @@ from .scoring import attach_impacts, compute_kpis, remap_severities, score_file
log = structlog.get_logger(__name__)
+# Method-level smells that make the dataflow / Extract Method pass worthwhile.
+# Only files carrying one of these get a CFG + def/use + reaching pass built.
+_EXTRACT_METHOD_SOURCES = frozenset({"large_method", "brain_method", "complex_method"})
+
def _log_duplication_diagnostics(report: DuplicationReport) -> None:
"""Emit a debug line when a duplication guard fired.
@@ -694,6 +699,26 @@ class HealthAnalyzer:
return FileComplexity(functions=[], classes=[])
return walk_file(path, language, source)
+ def _extract_method_analyses(self, pf: Any, findings: list[HealthFindingData]) -> list[Any]:
+ """Dataflow analyses for the Extract Method detector, gated to files
+ that already carry a method-level smell.
+
+ Building a CFG + def/use + reaching definitions is only useful where a
+ ``large_method`` / ``brain_method`` / ``complex_method`` finding fired,
+ so the dataflow pass (and its re-parse) runs for that small subset of
+ files only -- everything else pays nothing. Degrades to ``[]`` on any
+ read or analysis failure; the detector then yields no suggestion.
+ """
+ if not any(getattr(f, "biomarker_type", "") in _EXTRACT_METHOD_SOURCES for f in findings):
+ return []
+ path = pf.file_info.abs_path
+ language = pf.file_info.language
+ try:
+ source = Path(path).read_bytes()
+ except OSError:
+ return []
+ return analyze_file(path, language, source).functions
+
def _populate_symbol_complexity(self, pf: Any, fc_list: list[FunctionComplexity]) -> None:
if not fc_list:
return
@@ -829,6 +854,7 @@ class HealthAnalyzer:
module_map=self.module_map,
graph=self.graph,
file_scc=(file_scc_index or {}).get(file_path),
+ function_analyses=self._extract_method_analyses(pf, findings),
)
suggestions = detect_refactorings(rctx, disabled=disabled_refactorings or ())
return metric, findings, suggestions
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
index c20022243..7cebdcd7b 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
@@ -17,6 +17,7 @@ from . import (
break_cycle, # noqa: F401 (import-for-side-effect)
extract_class, # noqa: F401 (import-for-side-effect)
extract_helper, # noqa: F401 (import-for-side-effect)
+ extract_method, # noqa: F401 (import-for-side-effect)
move_method, # noqa: F401 (import-for-side-effect)
split_file, # noqa: F401 (import-for-side-effect)
)
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
new file mode 100644
index 000000000..65c3e7266
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -0,0 +1,126 @@
+"""Extract Method detector -- the first dataflow-driven refactoring.
+
+When a function is flagged ``large_method`` / ``brain_method`` /
+``complex_method``, the dataflow layer (CFG + def/use + reaching definitions)
+finds a contiguous statement span that can be lifted into a helper without
+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.
+
+The candidate spans + IN/OUT come from ``dataflow.find_extractions``; this
+module only matches each analysed function to the biomarker finding that flags
+it (for the recovered impact), picks the strongest extraction, and renders the
+plan. Precision-first: a function with no safe, complexity-removing span yields
+no suggestion.
+
+Plan shape (open dict, no migration):
+
+- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],
+ "returns": [str, ...], "suggested_name": str | None}`` -- the lines to lift,
+ the inferred signature, and an optional name (left ``None`` for the codegen /
+ LLM step to choose).
+- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and
+ complexity the residual method sheds.
+- ``blast_radius`` = ``{"callers_count": int}`` -- extraction is local (a new
+ private helper, the public method's signature is unchanged), so callers do
+ not change; carried for the surfaces' consistency.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from ..complexity.languages import get_language_map
+from ..dataflow import find_extractions
+from .models import RefactoringContext, RefactoringSuggestion
+from .registry import RefactoringDetector, effort_bucket, register
+
+if TYPE_CHECKING:
+ from ..dataflow import Extraction, FunctionAnalysis
+
+# The function-level structural biomarkers this detector answers. A function is
+# only offered an extraction when one of these flagged it, so the suggestion
+# list never exceeds (and stays consistent with) what health surfaces.
+_SOURCE_BIOMARKERS = ("brain_method", "large_method", "complex_method")
+
+
+@register
+class ExtractMethodDetector(RefactoringDetector):
+ name = "extract_method"
+
+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
+ analyses: list[FunctionAnalysis] = list(getattr(ctx, "function_analyses", []) or [])
+ if not analyses:
+ return []
+ lmap = get_language_map(ctx.language)
+ if lmap is None:
+ return []
+
+ out: list[RefactoringSuggestion] = []
+ for analysis in analyses:
+ impact, source = self._impact_for(analysis, ctx.findings)
+ if not source:
+ # Only suggest where a method biomarker actually fired.
+ continue
+ candidates = find_extractions(analysis, lmap)
+ if not candidates:
+ continue
+ best = candidates[0] # already best-first
+ out.append(
+ RefactoringSuggestion(
+ refactoring_type=self.name,
+ file_path=ctx.file_path,
+ target_symbol=analysis.name,
+ line_start=analysis.start_line,
+ line_end=analysis.end_line,
+ plan={
+ "span": {"start": best.start_line, "end": best.end_line},
+ "params": list(best.params),
+ "returns": list(best.returns),
+ "suggested_name": None,
+ },
+ evidence={
+ "slice_nloc": best.slice_nloc,
+ "ccn_removed": best.ccn_removed,
+ },
+ impact_delta=round(float(impact), 3),
+ effort_bucket=effort_bucket(best.slice_nloc),
+ blast_radius={"callers_count": 0},
+ confidence=self._confidence(best),
+ source_biomarker=source,
+ )
+ )
+
+ # Stable order: biggest recovery first, then symbol, then span start.
+ out.sort(key=lambda s: (-s.impact_delta, s.target_symbol, s.line_start or 0))
+ 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 = ""
+ for f in findings:
+ if getattr(f, "biomarker_type", "") not in _SOURCE_BIOMARKERS:
+ continue
+ if getattr(f, "function_name", "") != analysis.name:
+ continue
+ 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
+
+ @staticmethod
+ def _confidence(extraction: Extraction) -> str:
+ """High when the extraction is unambiguous -- it removes several decision
+ points with a clean signature; medium otherwise. (Every emitted span is
+ single-exit with at most one return by construction.)"""
+ if extraction.ccn_removed >= 2 and len(extraction.params) <= 4:
+ return "high"
+ return "medium"
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index e38e44157..ee491c97f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -13,10 +13,11 @@ the indexing hot path:
computed, and ask the configured provider for the refactored code and a
unified diff.
3. Self-check the result where it is cheap and meaningful: Extract Class with an
- LCOM4 before/after delta (re-walk the generated classes), and Split File by
+ LCOM4 before/after delta (re-walk the generated classes), Split File by
re-walking the generated files to assert each is below the size floor and the
- symbols are partitioned with no duplication. Other types skip validation
- gracefully.
+ symbols are partitioned with no duplication, and Extract Method by confirming
+ the residual function's cyclomatic complexity dropped below the original's.
+ Other types skip validation gracefully.
Results are cached on disk by a content hash (plan + source + model), so the
same plan never pays for the same generation twice.
@@ -353,6 +354,15 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {
"inversion, a shared interface/protocol module, or a local import as a "
"last resort). Do not merge the files."
),
+ "extract_method": (
+ "Refactoring: EXTRACT METHOD. The target is one long function; the plan's "
+ "'span' gives the line range to lift into a new helper method in the same "
+ "scope. Move exactly those lines into the helper, give it a clear name "
+ "(use 'suggested_name' if set), pass the plan's 'params' as its arguments "
+ "and return the plan's 'returns' value(s), and replace the original lines "
+ "with a call to it. Preserve behaviour exactly; change nothing outside the "
+ "span and the single call site."
+ ),
"split_file": (
"Refactoring: SPLIT FILE. The module is too large and partitions into "
"the cohesive groups in the plan. Create one new file per group at its "
@@ -636,6 +646,70 @@ def _validate_split_file(content: str, file_path: str, plan: dict[str, Any]) ->
}
+# ---------------------------------------------------------------------------
+# Validation — residual-CCN self-check (Extract Method)
+# ---------------------------------------------------------------------------
+
+
+def _validate_extract_method(
+ content: str, file_path: str, spans: list[SourceSpan], target_symbol: str
+) -> dict[str, Any]:
+ """Re-walk the generated code and confirm the extraction did its job.
+
+ A real Extract Method (1) yields >= 2 functions (the residual plus the new
+ helper) and (2) lowers the residual method's cyclomatic complexity below the
+ original function's. The original CCN is recovered by walking the function
+ span that was fed to the model, so the check needs no extra inputs.
+ Best-effort: any parse/walk failure degrades to ``status="skipped"``.
+ """
+ language = _language_for(file_path)
+ if language is None:
+ return {"status": "skipped", "reason": f"no walker for {Path(file_path).suffix}"}
+
+ code = _extract_code_blocks(content, language)
+ if not code.strip():
+ return {"status": "skipped", "reason": "no parseable code blocks in response"}
+
+ try:
+ from repowise.core.analysis.health.complexity import walk_file
+ except Exception as exc:
+ return {"status": "skipped", "reason": f"import failed: {exc}"}
+
+ suffix = Path(file_path).suffix
+ try:
+ generated = walk_file(f"generated{suffix}", language, code.encode())
+ except Exception as exc:
+ return {"status": "skipped", "reason": f"walk failed: {exc}"}
+
+ functions = list(generated.functions)
+ if len(functions) < 2:
+ return {
+ "status": "checked",
+ "function_count": len(functions),
+ "improved": False,
+ "reason": "expected the residual method plus a new helper",
+ }
+
+ original_ccn: int | None = None
+ if spans:
+ try:
+ original = walk_file(f"original{suffix}", language, spans[0].source.encode())
+ original_ccn = max((f.ccn for f in original.functions), default=None)
+ except Exception:
+ original_ccn = None
+
+ residual = next((f for f in functions if f.name == target_symbol), None)
+ residual_ccn = residual.ccn if residual is not None else max(f.ccn for f in functions)
+ improved = original_ccn is not None and residual_ccn < original_ccn and len(functions) >= 2
+ return {
+ "status": "checked",
+ "function_count": len(functions),
+ "original_ccn": original_ccn,
+ "residual_ccn": residual_ccn,
+ "improved": bool(improved),
+ }
+
+
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
@@ -688,6 +762,10 @@ async def enrich_suggestion(
)
elif validate and suggestion.refactoring_type == "split_file":
validation = _validate_split_file(content, suggestion.file_path, suggestion.plan or {})
+ elif validate and suggestion.refactoring_type == "extract_method":
+ validation = _validate_extract_method(
+ content, suggestion.file_path, spans, suggestion.target_symbol
+ )
result = EnrichmentResult(
refactoring_type=suggestion.refactoring_type,
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 b01874d11..87d9bf531 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -122,6 +122,14 @@ class RefactoringContext:
# engine precomputes the repo's SCC index once and threads the per-file
# slice in, so Break Cycle never recomputes SCCs per file.
file_scc: tuple[str, ...] | None = None
+ # Per-flagged-function dataflow analyses (``dataflow.FunctionAnalysis``
+ # records, typed ``Any`` to avoid importing the dataflow layer into the
+ # model). The engine builds these only for files carrying a method-level
+ # smell (``large_method`` / ``brain_method`` / ``complex_method``), so the
+ # Extract Method detector reads CFG + def/use + reaching definitions without
+ # a re-parse of its own. Empty for files with no such finding -- the
+ # detector then yields nothing.
+ function_analyses: list[Any] = field(default_factory=list)
@dataclass
diff --git a/packages/ui/__tests__/refactoring/extract-method-types.test.ts b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
new file mode 100644
index 000000000..26c88c007
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect } from "vitest";
+import {
+ extractMethodPlan,
+ generatedVerdict,
+ planSynopsis,
+ planWins,
+ type GeneratedCode,
+ type RefactoringPlan,
+} from "../../src/refactoring/types";
+import { typeMeta, TYPE_ORDER } from "../../src/refactoring/meta";
+
+function extractMethodPlanFixture(overrides: Partial<RefactoringPlan> = {}): RefactoringPlan {
+ return {
+ id: "p1",
+ refactoring_type: "extract_method",
+ file_path: "pkg/pipeline.py",
+ target_symbol: "run_pipeline",
+ line_start: 10,
+ line_end: 80,
+ plan: {
+ span: { start: 30, end: 48 },
+ params: ["records", "threshold"],
+ returns: ["average"],
+ suggested_name: null,
+ },
+ evidence: { slice_nloc: 19, ccn_removed: 4 },
+ impact_delta: 1.5,
+ effort_bucket: "M",
+ blast_radius: { callers_count: 0 },
+ confidence: "high",
+ source_biomarker: "complex_method",
+ rank_score: 2.1,
+ ...overrides,
+ };
+}
+
+describe("extract_method plan accessors", () => {
+ it("reads the span, params, and returns defensively", () => {
+ const em = extractMethodPlan(extractMethodPlanFixture());
+ expect(em.span).toEqual({ start: 30, end: 48 });
+ expect(em.params).toEqual(["records", "threshold"]);
+ expect(em.returns).toEqual(["average"]);
+ expect(em.suggested_name).toBeNull();
+ });
+
+ it("returns a null span when the plan omits it", () => {
+ const em = extractMethodPlan(extractMethodPlanFixture({ plan: { params: [], returns: [] } }));
+ expect(em.span).toBeNull();
+ expect(em.params).toEqual([]);
+ });
+
+ it("synopsis describes the lifted line count", () => {
+ expect(planSynopsis(extractMethodPlanFixture())).toBe("Extract 19 lines into a helper");
+ });
+
+ it("wins lead with the recovered health and the complexity removed", () => {
+ const wins = planWins(extractMethodPlanFixture());
+ expect(wins[0]).toEqual({ hero: true, label: "+1.5 health recovered" });
+ expect(wins.some((w) => w.label.includes("lifted into a focused helper"))).toBe(true);
+ expect(wins.some((w) => w.label.includes("cyclomatic complexity"))).toBe(true);
+ });
+});
+
+describe("extract_method meta", () => {
+ it("has a label and is in the type order", () => {
+ expect(typeMeta("extract_method").label).toBe("Extract Method");
+ expect(TYPE_ORDER).toContain("extract_method");
+ });
+});
+
+describe("extract_method generated verdict", () => {
+ function generated(validation: Record<string, unknown>): GeneratedCode {
+ return {
+ suggestion_id: "s1",
+ refactoring_type: "extract_method",
+ file_path: "pkg/pipeline.py",
+ target_symbol: "run_pipeline",
+ content: "",
+ diff: "",
+ provider: "mock",
+ model: "mock",
+ cached: false,
+ input_tokens: 0,
+ output_tokens: 0,
+ validation,
+ spans: [],
+ };
+ }
+
+ it("passes when the residual CCN dropped", () => {
+ const v = generatedVerdict(
+ generated({ status: "checked", original_ccn: 12, residual_ccn: 4, function_count: 2, improved: true }),
+ );
+ expect(v?.tone).toBe("pass");
+ expect(v?.label).toBe("Complexity reduced");
+ expect(v?.detail).toContain("CCN 12 → 4");
+ });
+
+ it("fails when complexity did not drop", () => {
+ const v = generatedVerdict(
+ generated({ status: "checked", original_ccn: 12, residual_ccn: 12, function_count: 1, improved: false }),
+ );
+ expect(v?.tone).toBe("fail");
+ });
+
+ it("is neutral when the self-check was skipped", () => {
+ const v = generatedVerdict(generated({ status: "skipped", reason: "no walker" }));
+ expect(v?.tone).toBe("neutral");
+ });
+});
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 3010a16da..0aa51c334 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -20,6 +20,7 @@ import {
cycleMembers,
extractClassGroups,
extractHelperOccurrences,
+ extractMethodPlan,
helperSite,
moveTarget,
type RefactoringPlan,
@@ -1275,6 +1276,21 @@ function refactoringPlanSteps(plan: RefactoringPlan): string {
"Define the helper once, replace every occurrence with a call to it, and confirm the behavior is identical at each site (watch for small per-site differences that need a parameter).",
].join("\n");
}
+ case "extract_method": {
+ const em = extractMethodPlan(plan);
+ if (!em.span) return "Extract the indicated slice into a helper method.";
+ const params = em.params.length ? em.params.join(", ") : "(none)";
+ const returns = em.returns.length ? em.returns.join(", ") : "(nothing)";
+ const name = em.suggested_name ?? "a clearly named helper";
+ return [
+ `Extract lines ${em.span.start}–${em.span.end} of \`${plan.target_symbol}\` into ${name}:`,
+ "",
+ `- **Parameters (in):** ${params}`,
+ `- **Returns (out):** ${returns}`,
+ "",
+ "Move exactly those lines into the new helper in the same scope, pass the parameters above, return the value(s) above, and replace the original lines with a single call to it. Preserve behavior exactly: change nothing outside the span and that one call site.",
+ ].join("\n");
+ }
case "move_method": {
const mv = moveTarget(plan);
if (!mv) return "Move the method to the class it belongs to.";
diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsx
index a8ee7bea9..5487a88dd 100644
--- a/packages/ui/src/refactoring/meta.tsx
+++ b/packages/ui/src/refactoring/meta.tsx
@@ -1,7 +1,7 @@
"use client";
import * as React from "react";
-import { ArrowRightLeft, CopyMinus, FileStack, Split, Unlink } from "lucide-react";
+import { ArrowRightLeft, CopyMinus, FileStack, Scissors, Split, Unlink } from "lucide-react";
import type { Confidence, EffortBucket, RefactoringType } from "./types";
export interface RefactoringTypeMeta {
@@ -26,6 +26,12 @@ export const TYPE_META: Record<string, RefactoringTypeMeta> = {
Icon: CopyMinus,
accentVar: "--color-refactor-extract-helper",
},
+ extract_method: {
+ label: "Extract Method",
+ blurb: "Lift a cohesive slice of a long function into a focused helper.",
+ Icon: Scissors,
+ accentVar: "--color-refactor-extract-method",
+ },
move_method: {
label: "Move Method",
blurb: "Move a method to the class it actually belongs to.",
@@ -84,6 +90,7 @@ export const CONFIDENCE_DOT: Record<Confidence, string> = {
export const TYPE_ORDER: RefactoringType[] = [
"extract_class",
"extract_helper",
+ "extract_method",
"move_method",
"break_cycle",
"split_file",
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index e9a04cd3c..09d6ead59 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -8,6 +8,7 @@ import {
cycleMembers,
extractClassGroups,
extractHelperOccurrences,
+ extractMethodPlan,
helperSite,
moveTarget,
splitBlast,
@@ -254,6 +255,70 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
);
}
+ if (plan.refactoring_type === "extract_method") {
+ const em = extractMethodPlan(plan);
+ const lines = em.span ? em.span.end - em.span.start + 1 : 0;
+ const ccn = Number(plan.evidence?.ccn_removed ?? 0);
+ const helperName = em.suggested_name ?? "helper";
+ const sig = `${helperName}(${em.params.join(", ")})${
+ em.returns.length ? ` -> ${em.returns.join(", ")}` : ""
+ }`;
+ return (
+ <div className="space-y-3">
+ {hideIntro ? null : (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Lift {lines} line{lines === 1 ? "" : "s"} out of{" "}
+ <span className="font-mono">{plan.target_symbol}</span> into a focused helper
+ {ccn ? `, shedding ${ccn} decision point${ccn === 1 ? "" : "s"}` : ""}.
+ </p>
+ )}
+
+ {em.span ? (
+ <div className="flex items-center gap-2 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
+ <Scissors className="h-4 w-4 shrink-0" style={{ color: accent }} aria-hidden />
+ <div className="min-w-0">
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Extract span
+ </div>
+ <FileRef
+ path={plan.file_path}
+ line={em.span.start}
+ fileHref={fileHref}
+ className="block truncate"
+ />
+ </div>
+ <span className="ml-auto shrink-0 font-mono text-xs text-[var(--color-text-secondary)]">
+ lines {em.span.start}–{em.span.end}
+ </span>
+ </div>
+ ) : null}
+
+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
+ <div className="mb-1.5 text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Inferred signature
+ </div>
+ <code className="block break-all font-mono text-xs text-[var(--color-text-primary)]">
+ {sig}
+ </code>
+ <div className="mt-2 flex flex-wrap gap-3 text-[11px] text-[var(--color-text-tertiary)]">
+ <span>
+ In (params):{" "}
+ <span className="text-[var(--color-text-secondary)]">
+ {em.params.length ? em.params.join(", ") : "none"}
+ </span>
+ </span>
+ <span>
+ Out (return):{" "}
+ <span className="text-[var(--color-text-secondary)]">
+ {em.returns.length ? em.returns.join(", ") : "none"}
+ </span>
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
if (plan.refactoring_type === "split_file") {
const groups = splitGroups(plan);
const residual = splitResidual(plan);
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index c7f726ee0..203fd8354 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -10,6 +10,7 @@
export type RefactoringType =
| "extract_class"
| "extract_helper"
+ | "extract_method"
| "move_method"
| "break_cycle"
| "split_file";
@@ -134,6 +135,30 @@ export function cutEdges(plan: RefactoringPlan): CutEdge[] {
});
}
+export interface ExtractMethodPlan {
+ /** The line span (1-indexed, inclusive) to lift into a helper. */
+ span: { start: number; end: number } | null;
+ /** Inferred IN parameters and OUT return(s). */
+ params: string[];
+ returns: string[];
+ suggested_name: string | null;
+}
+
+export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {
+ const p = (plan.plan ?? {}) as Record<string, unknown>;
+ const rawSpan = p.span as Record<string, unknown> | undefined;
+ const span =
+ rawSpan && typeof rawSpan === "object"
+ ? { start: Number(rawSpan.start ?? 0), end: Number(rawSpan.end ?? 0) }
+ : null;
+ return {
+ span: span && span.start && span.end ? span : null,
+ params: Array.isArray(p.params) ? (p.params as string[]) : [],
+ returns: Array.isArray(p.returns) ? (p.returns as string[]) : [],
+ suggested_name: typeof p.suggested_name === "string" ? p.suggested_name : null,
+ };
+}
+
export interface SplitGroup {
name: string | null;
symbols: string[];
@@ -199,6 +224,11 @@ export function planSynopsis(plan: RefactoringPlan): string {
lines ? ` · ${lines} lines` : ""
}`;
}
+ case "extract_method": {
+ const em = extractMethodPlan(plan);
+ const lines = em.span ? em.span.end - em.span.start + 1 : 0;
+ return lines ? `Extract ${lines} line${lines === 1 ? "" : "s"} into a helper` : "Extract a helper method";
+ }
case "move_method": {
const mv = moveTarget(plan);
return mv ? `${mv.from_class} → ${mv.to_class}` : "Move method";
@@ -260,6 +290,8 @@ export const EVIDENCE_LABELS: Record<string, string> = {
modularity: "Modularity",
intra_edges: "Cohesive edges",
cut_edges: "Cut edges",
+ slice_nloc: "Extracted lines",
+ ccn_removed: "Complexity removed",
};
export function evidenceRows(plan: RefactoringPlan): { label: string; value: string }[] {
@@ -341,6 +373,21 @@ export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null
}
if (status !== "checked") return null;
+ if (result.refactoring_type === "extract_method") {
+ const improved = v.improved === true;
+ const parts: string[] = [];
+ const before = fmtMetric(v.original_ccn);
+ const after = fmtMetric(v.residual_ccn);
+ if (before !== null && after !== null) parts.push(`CCN ${before} → ${after}`);
+ const fns = fmtMetric(v.function_count);
+ if (fns !== null) parts.push(`${fns} functions`);
+ return {
+ tone: improved ? "pass" : "fail",
+ label: improved ? "Complexity reduced" : "Complexity not reduced",
+ ...(parts.length ? { detail: parts.join(" · ") } : {}),
+ };
+ }
+
if (result.refactoring_type === "split_file") {
const improved = v.improved === true;
const parts: string[] = [];
@@ -397,6 +444,16 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
if (lines) wins.push({ label: `~${lines} duplicated lines removed` });
break;
}
+ case "extract_method": {
+ const em = extractMethodPlan(plan);
+ const ccn = Number(plan.evidence?.ccn_removed ?? 0);
+ if (em.span) {
+ const lines = em.span.end - em.span.start + 1;
+ wins.push({ label: `${lines} line${lines === 1 ? "" : "s"} lifted into a focused helper` });
+ }
+ if (ccn) wins.push({ label: `-${ccn} cyclomatic complexity on the original method` });
+ break;
+ }
case "move_method": {
const mv = moveTarget(plan);
if (mv) wins.push({ label: `${mv.method} lives with the data it uses` });
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index de5b22564..81ee20cf6 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -113,6 +113,7 @@
exactly what made extract-class / move-method / break-cycle indistinct. */
--color-refactor-extract-class: #b9651b; /* amber */
--color-refactor-extract-helper: #1d8155; /* green */
+ --color-refactor-extract-method: #0e7490; /* teal */
--color-refactor-move-method: #6d4aa6; /* purple */
--color-refactor-break-cycle: #b5396f; /* magenta */
--color-refactor-split-file: #3f6ea5; /* blue */
@@ -347,6 +348,7 @@
/* Refactoring type accents — qualitative palette (dark theme, brighter). */
--color-refactor-extract-class: #f59520; /* amber */
--color-refactor-extract-helper: #34d399; /* green */
+ --color-refactor-extract-method: #22d3ee; /* cyan */
--color-refactor-move-method: #b58cf0; /* purple */
--color-refactor-break-cycle: #ec6fa6; /* magenta */
--color-refactor-split-file: #7da7d9; /* blue */
diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.py
index 6871c1e3f..f5a9362a1 100644
--- a/tests/unit/health/test_refactoring_enrich.py
+++ b/tests/unit/health/test_refactoring_enrich.py
@@ -16,9 +16,11 @@ from repowise.core.analysis.health.refactoring.llm import (
)
from repowise.core.analysis.health.refactoring.llm.enrich import (
_MAX_IMPORT_HEAD_LINES,
+ SourceSpan,
_build_user_prompt,
_extract_diff,
_gather_spans,
+ _validate_extract_method,
)
from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
from repowise.core.providers.llm.base import GeneratedResponse
@@ -389,3 +391,42 @@ def test_llm_enrichment_enabled_gate() -> None:
assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": False}}}) is False
assert llm_enrichment_enabled({"refactoring": {}}) is True
assert llm_enrichment_enabled({}) is True
+
+
+def test_validate_extract_method_detects_ccn_drop():
+ # The original function (high CCN) is the span fed to the model; the
+ # generated response splits it into a low-CCN residual plus a helper.
+ original = (
+ "def process(items, t):\n"
+ " total = 0\n"
+ " for v in items:\n"
+ " if v > t:\n"
+ " total += v\n"
+ " elif v < 0:\n"
+ " total -= v\n"
+ " return total\n"
+ )
+ spans = [SourceSpan(file="m.py", start_line=1, end_line=8, source=original)]
+ content = (
+ "Summary.\n\n"
+ "```python\n"
+ "def _accumulate(items, t):\n"
+ " total = 0\n"
+ " for v in items:\n"
+ " if v > t:\n"
+ " total += v\n"
+ " elif v < 0:\n"
+ " total -= v\n"
+ " return total\n\n"
+ "def process(items, t):\n"
+ " return _accumulate(items, t)\n"
+ "```\n"
+ )
+ result = _validate_extract_method(content, "m.py", spans, "process")
+ if result.get("status") == "skipped":
+ import pytest
+
+ pytest.skip("tree-sitter python pack missing")
+ assert result["function_count"] >= 2
+ assert result["residual_ccn"] < result["original_ccn"]
+ assert result["improved"] is True
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
new file mode 100644
index 000000000..6dda349de
--- /dev/null
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -0,0 +1,202 @@
+"""Unit tests for the Extract Method slicer + detector.
+
+Best-effort: skip when the Python tree-sitter pack is missing.
+"""
+
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass
+
+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.refactoring import detect_refactorings
+from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector
+from repowise.core.analysis.health.refactoring.models import RefactoringContext
+
+# A long function whose tail (compute-average loop) is a clean extraction.
+_PROCESS = """
+def process(records, threshold):
+ results = []
+ errors = 0
+ for r in records:
+ if r is None:
+ errors += 1
+ continue
+ results.append(r)
+ total = 0
+ count = 0
+ for v in results:
+ if v > threshold:
+ total += v
+ count += 1
+ else:
+ total -= v
+ average = total / count if count else 0
+ return average, errors
+"""
+
+
+@dataclass
+class _Finding:
+ biomarker_type: str
+ function_name: str
+ line_start: int
+ health_impact: float
+
+
+def _require_python() -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing for python")
+ if _get_language("python") is None:
+ pytest.skip("tree-sitter language pack missing for python")
+
+
+def _analyses(src: str):
+ _require_python()
+ res = analyze_file("m.py", "python", textwrap.dedent(src).encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for python")
+ return res.functions
+
+
+def _first(src: str):
+ fns = _analyses(src)
+ assert fns
+ return fns[0]
+
+
+# -- slicer ---------------------------------------------------------------------
+
+
+def test_finds_clean_extraction_with_inferred_signature():
+ lmap = get_language_map("python")
+ extractions = find_extractions(_first(_PROCESS), lmap)
+ assert extractions, "expected at least one extraction"
+ best = extractions[0]
+ # The strongest extraction is the compute-average tail.
+ assert "average" in best.returns
+ assert "results" in best.params and "threshold" in best.params
+ # Single clean return, bounded params.
+ assert len(best.returns) <= 1
+ assert best.ccn_removed >= 1
+ assert best.slice_nloc >= 6
+
+
+def test_no_extraction_when_every_span_has_a_jump():
+ # A guard-clause cascade: every span contains a return, so nothing is a
+ # single-exit slice -> no candidate.
+ lmap = get_language_map("python")
+ src = """
+ def classify(x):
+ if x < 0:
+ return "neg"
+ if x == 0:
+ return "zero"
+ if x < 10:
+ return "small"
+ if x < 100:
+ return "medium"
+ return "large"
+ """
+ extractions = find_extractions(_first(src), lmap)
+ assert extractions == []
+
+
+def test_whole_function_body_is_not_extracted():
+ lmap = get_language_map("python")
+ src = """
+ def f(a, b):
+ x = a + b
+ y = x * 2
+ z = y - a
+ return z
+ """
+ # The only span covering the whole body is excluded; the remaining spans
+ # carry no decision point, so nothing qualifies.
+ assert find_extractions(_first(src), lmap) == []
+
+
+def test_extractions_are_deterministic():
+ lmap = get_language_map("python")
+ fn = _first(_PROCESS)
+
+ def serialize():
+ return [
+ (e.start_line, e.end_line, e.params, e.returns, e.ccn_removed)
+ for e in find_extractions(fn, lmap)
+ ]
+
+ first = serialize()
+ for _ in range(3):
+ assert serialize() == first
+
+
+# -- detector -------------------------------------------------------------------
+
+
+def _ctx(src: str, findings):
+ return RefactoringContext(
+ file_path="m.py",
+ language="python",
+ nloc=100,
+ findings=findings,
+ function_analyses=_analyses(src),
+ )
+
+
+def test_detector_emits_suggestion_for_flagged_function():
+ findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]
+ suggestions = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))
+ assert len(suggestions) == 1
+ s = suggestions[0]
+ assert s.refactoring_type == "extract_method"
+ assert s.target_symbol == "process"
+ assert s.source_biomarker == "complex_method"
+ assert s.impact_delta == 1.5
+ # Plan shape is the locked schema.
+ assert set(s.plan) == {"span", "params", "returns", "suggested_name"}
+ assert set(s.plan["span"]) == {"start", "end"}
+ assert set(s.evidence) == {"slice_nloc", "ccn_removed"}
+ assert s.blast_radius == {"callers_count": 0}
+ assert s.confidence in ("medium", "high")
+
+
+def test_detector_silent_without_matching_finding():
+ # The function is analysed but no method biomarker fired -> no suggestion.
+ suggestions = ExtractMethodDetector().detect(_ctx(_PROCESS, findings=[]))
+ assert suggestions == []
+
+
+def test_detector_silent_without_analyses():
+ ctx = RefactoringContext(
+ file_path="m.py",
+ language="python",
+ nloc=100,
+ findings=[_Finding("complex_method", "process", 2, 1.0)],
+ function_analyses=[],
+ )
+ assert ExtractMethodDetector().detect(ctx) == []
+
+
+def test_detector_registered_in_registry():
+ # The detector self-registers, so the generic runner picks it up.
+ findings = [_Finding("large_method", "process", line_start=2, health_impact=2.0)]
+ suggestions = detect_refactorings(_ctx(_PROCESS, findings))
+ assert any(s.refactoring_type == "extract_method" for s in suggestions)
+
+
+def test_detector_is_deterministic():
+ findings = [_Finding("complex_method", "process", 2, 1.5)]
+
+ def run():
+ s = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))[0]
+ return (s.target_symbol, s.plan["span"], tuple(s.plan["params"]), tuple(s.plan["returns"]))
+
+ first = run()
+ for _ in range(3):
+ assert run() == first