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
feat(health): add deterministic Extract Class refactoring detector (#586)
Raghav Chamadiyaaf39a31a946f
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.pyindex 9f0705af1..0e084d330 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py@@ -286,7 +286,12 @@ def health_command(findings = [f for f in findings if f.file_path.startswith(module_filter)]if refactoring_targets:- _render_refactoring_targets(metrics_sorted, findings, fmt=fmt)+ suggestions = getattr(report, "refactoring_suggestions", None) or []+ if file_filter:+ suggestions = [s for s in suggestions if s.file_path == file_filter]+ if module_filter:+ suggestions = [s for s in suggestions if s.file_path.startswith(module_filter)]+ _render_refactoring_targets(metrics_sorted, findings, suggestions, fmt=fmt)returnif badge_view:@@ -489,10 +494,27 @@ def _effort_bucket(nloc: int) -> tuple[str, int]:return "XL", 5+def _suggestion_to_dict(s: object) -> dict:+ """Serialize a ``RefactoringSuggestion`` dataclass to a plain dict."""+ import dataclasses++ return dataclasses.asdict(s) if dataclasses.is_dataclass(s) else dict(s)++def _render_refactoring_targets(- metrics: list, findings: list, *, fmt: str, limit: int = 20+ metrics: list, findings: list, suggestions: list | None = None, *, fmt: str, limit: int = 20) -> None:- """Aggregate findings per file, rank by impact/effort, render."""+ """Aggregate findings per file, rank by impact/effort, render.++ When the refactoring layer produced structured *suggestions* (e.g. an+ Extract Class split), the concrete plan is attached to each target's row+ (JSON/MD) and printed as a group tree below the table.+ """+ suggestions = suggestions or []+ sugg_by_file: dict[str, list] = {}+ for s in suggestions:+ sugg_by_file.setdefault(s.file_path, []).append(s)+by_file: dict[str, list] = {}for f in findings:by_file.setdefault(f.file_path, []).append(f)@@ -506,6 +528,7 @@ def _render_refactoring_targets(primary = max(fs, key=lambda x: x.health_impact)total_impact = round(sum(x.health_impact for x in fs), 3)bucket, weight = _effort_bucket(nloc)+ file_sugg = sugg_by_file.get(path, [])targets.append({"file_path": path,@@ -518,13 +541,22 @@ def _render_refactoring_targets("effort_bucket": bucket,"impact_per_effort": round(total_impact / weight, 3),"finding_count": len(fs),+ "plans": [_suggestion_to_dict(s) for s in file_sugg],})targets.sort(key=lambda t: (-t["impact_per_effort"], -t["total_impact"]))targets = targets[:limit]+ # Structured plans are ranked + displayed independently of the impact/effort+ # file table (a god class worth splitting may not top that churn-weighted+ # list), highest recovered impact first.+ ranked_plans = sorted(+ (_suggestion_to_dict(s) for s in suggestions),+ key=lambda p: -p.get("impact_delta", 0.0),+ )[:limit]+if fmt == "json":- click.echo(json.dumps({"targets": targets}, indent=2))+ click.echo(json.dumps({"targets": targets, "refactoring_plans": ranked_plans}, indent=2))returnif fmt == "md":click.echo("# Refactoring targets\n")@@ -534,6 +566,7 @@ def _render_refactoring_targets(f"score {t['score']:.1f}/10, -{t['total_impact']:.2f}) "f"— {t['primary_biomarker']}: {t['primary_reason']}")+ _render_extract_class_plans_md(ranked_plans)returntable = Table(title=f"Refactoring targets ({len(targets)})")@@ -553,6 +586,47 @@ def _render_refactoring_targets(t["primary_biomarker"],)console.print(table)+ _render_extract_class_plans_console(ranked_plans)+++def _render_extract_class_plans_console(plans: list[dict]) -> None:+ """Print the concrete Extract Class splits below the table — the wedge."""+ ec_plans = [p for p in plans if p["refactoring_type"] == "extract_class"]+ if not ec_plans:+ return+ console.print(f"\n[bold]Extract Class plans ({len(ec_plans)})[/bold]")+ for p in ec_plans:+ ev = p["evidence"]+ groups = p["plan"].get("groups", [])+ console.print(+ f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim] — "+ f"LCOM4={ev.get('lcom4')}, {ev.get('method_count')} methods, "+ f"WMC={ev.get('wmc')} → split into {len(groups)} classes "+ f"[dim](recover ~{p['impact_delta']:.2f}, effort {p['effort_bucket']}, "+ f"{p['confidence']} confidence)[/dim]"+ )+ for i, g in enumerate(groups, 1):+ fields = ", ".join(g["fields"]) or "—"+ console.print(+ f" [bold]{i}.[/bold] methods: {', '.join(g['methods'])}\n"+ f" [dim]fields:[/dim] {fields}"+ )+++def _render_extract_class_plans_md(plans: list[dict]) -> None:+ ec_plans = [p for p in plans if p["refactoring_type"] == "extract_class"]+ if not ec_plans:+ return+ click.echo("\n## Extract Class plans\n")+ for p in ec_plans:+ groups = p["plan"].get("groups", [])+ click.echo(+ f"- **{p['target_symbol']}** ({p['file_path']}) — "+ f"LCOM4={p['evidence'].get('lcom4')}, split into {len(groups)} classes:"+ )+ for i, g in enumerate(groups, 1):+ fields = ", ".join(g["fields"]) or "—"+ click.echo(f" {i}. methods: {', '.join(g['methods'])} · fields: {fields}")def _render_trend(repo_path: object, *, fmt: str) -> None:@@ -705,9 +779,7 @@ def _persist_health(average_health=float(kpis.get("average_health", 10.0)),worst_performer_path=kpis.get("worst_performer_path"),worst_performer_score=kpis.get("worst_performer_score"),- per_file_scores={- m.file_path: round(float(m.score), 2) for m in metrics- },+ per_file_scores={m.file_path: round(float(m.score), 2) for m in metrics},)except Exception as exc:console.print(f"[yellow]Snapshot write skipped: {exc}[/yellow]")diff --git a/packages/core/alembic/versions/0034_refactoring_suggestions.py b/packages/core/alembic/versions/0034_refactoring_suggestions.pynew file mode 100644index 000000000..200b121a0--- /dev/null+++ b/packages/core/alembic/versions/0034_refactoring_suggestions.py@@ -0,0 +1,67 @@+"""refactoring_suggestions table — structured Extract Class (and later) plans.++The refactoring layer turns the structural signals the health pass already+computes (LCOM4 cohesion components in Phase 1) into structured+``RefactoringSuggestion`` rows: the concrete plan, the evidence behind it,+and the blast radius of applying it. The JSON payload columns+(``plan_json`` / ``evidence_json`` / ``blast_radius_json``) keep the schema+type-agnostic so later refactoring types add rows, not columns.++Mirrors the ``health_findings`` write model: delete-then-insert per repo on+a full index, upsert-by-file on an incremental update.++Revision ID: 0034+Revises: 0033+Create Date: 2026-06-24+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0034"+down_revision: str | None = "0033"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "refactoring_suggestions",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("refactoring_type", sa.String(32), nullable=False),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("target_symbol", sa.String(255), nullable=False, server_default=""),+ sa.Column("line_start", sa.Integer, nullable=True),+ sa.Column("line_end", sa.Integer, nullable=True),+ sa.Column("plan_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("evidence_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("impact_delta", sa.Float, nullable=False, server_default="0"),+ sa.Column("effort_bucket", sa.String(8), nullable=False, server_default=""),+ sa.Column("blast_radius_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("confidence", sa.String(16), nullable=False, server_default="medium"),+ sa.Column("source_biomarker", sa.String(64), nullable=False, server_default=""),+ sa.Column("status", sa.String(32), nullable=False, server_default="open"),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ )+ op.create_index(+ "ix_refactoring_suggestions_repo",+ "refactoring_suggestions",+ ["repository_id"],+ )+++def downgrade() -> None:+ op.drop_index("ix_refactoring_suggestions_repo", "refactoring_suggestions")+ op.drop_table("refactoring_suggestions")diff --git a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py b/packages/core/src/repowise/core/analysis/health/complexity/__init__.pyindex 61fc7b32c..c4274d4ac 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom .walker import (ClassComplexity,+ CohesionGroup,ConditionComplexity,ErrorHandlingHit,FileComplexity,@@ -16,6 +17,7 @@ from .walker import (__all__ = ["ClassComplexity",+ "CohesionGroup","ConditionComplexity","ErrorHandlingHit","FileComplexity",diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.pyindex 37e1690fd..9423e9717 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py@@ -14,7 +14,7 @@ from typing import TYPE_CHECKINGfrom .ast_utils import _IDENTIFIER_SUFFIX, _find_namefrom .languages import LanguageNodeMap-from .models import ClassComplexity, FunctionComplexity+from .models import ClassComplexity, CohesionGroup, FunctionComplexityfrom .nloc import _count_nlocif TYPE_CHECKING:@@ -147,23 +147,27 @@ def _compute_lcom4(method_nodes: list[Node],method_fcs: list[FunctionComplexity],lmap: LanguageNodeMap,-) -> tuple[int, int]:- """Return ``(lcom4, field_count)`` for a class.+) -> tuple[int, int, list[CohesionGroup]]:+ """Return ``(lcom4, field_count, components)`` for a class.LCOM4 = number of connected components over the methods, where twomethods are connected if they share an instance member or one callsthe other (a call shows up as a reference to the callee's name).+ ``components`` is the per-component membership behind that integer:+ one ``CohesionGroup`` (methods + the fields they touch) per connected+ component, stable-ordered. It *is* the Extract Class split.**Safety valve:** if no instance-member references are detected at all(a pure-static class, or — importantly — a language whosemember-access node type we have not mapped), return ``1`` rather than``len(methods)``. This prevents ``low_cohesion`` from false-firing onan unverified language: a missing mapping yields "no signal", never a- spurious high-LCOM hit.+ spurious high-LCOM hit. ``components`` is empty in every no-signal case+ (the integer carries no real split to expose)."""n = len(method_nodes)if n == 0:- return 1, 0+ return 1, 0, []members_per_method: list[set[str]] = [_collect_self_members(node, lmap) for node in method_nodes@@ -174,7 +178,7 @@ def _compute_lcom4(field_count = len(all_members - method_names)if total_refs == 0:- return 1, field_count+ return 1, field_count, []# Union-find over method indices.parent = list(range(n))@@ -207,8 +211,39 @@ def _compute_lcom4(for other in group[1:]:_union(first, other)- components = {_find(i) for i in range(n)}- return len(components), field_count+ roots = [_find(i) for i in range(n)]+ components = set(roots)++ # Build the per-component membership behind the integer. Bucket method+ # indices by their union-find root, then order each group's methods (and+ # the groups themselves) by source position so the split reads+ # top-to-bottom. Ordering is by ``(start_line, name)`` rather than+ # collection index, which makes it both deterministic and stable across+ # runs. Each group's fields are the members its methods reference that+ # aren't method names.+ by_root: dict[int, list[int]] = {}+ for i in range(n):+ by_root.setdefault(roots[i], []).append(i)++ def _pos(i: int) -> tuple[int, str]:+ return (method_fcs[i].start_line, method_fcs[i].name)++ # Pair each group with its earliest member index so the inter-group sort+ # keys off that index directly (robust to duplicate method names, which a+ # name->index lookup would resolve to the wrong method).+ indexed_groups: list[tuple[int, CohesionGroup]] = []+ for member_idxs in by_root.values():+ member_idxs.sort(key=_pos)+ group_methods = [method_fcs[i].name for i in member_idxs]+ group_fields: set[str] = set()+ for i in member_idxs:+ group_fields |= members_per_method[i] - method_names+ indexed_groups.append(+ (member_idxs[0], CohesionGroup(methods=group_methods, fields=sorted(group_fields)))+ )+ indexed_groups.sort(key=lambda pair: _pos(pair[0]))+ groups = [g for _, g in indexed_groups]+ return len(components), field_count, groupsdef _collect_classes(@@ -227,7 +262,7 @@ def _collect_classes(# Keep nodes and FCs aligned (a method missing from the function# pass — unusual — drops out of both).aligned_nodes = [m for m in method_nodes if m.id in fc_by_node_id]- lcom4, field_count = _compute_lcom4(aligned_nodes, method_fcs, lmap)+ lcom4, field_count, components = _compute_lcom4(aligned_nodes, method_fcs, lmap)classes.append(ClassComplexity(name=_class_name(class_node),@@ -239,6 +274,7 @@ def _collect_classes(lcom4=lcom4,max_method_ccn=max((fc.ccn for fc in method_fcs), default=0),field_count=field_count,+ components=components,))return classesdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex 92023276b..e752a4cff 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -57,6 +57,23 @@ class FunctionComplexity:self.assertion_blocks = []+@dataclass+class CohesionGroup:+ """One LCOM4 connected component within a class.++ A cluster of methods that share instance state (a field or a+ method-call edge), plus the instance fields the cluster collectively+ touches. Emitted as a side-channel by ``_compute_lcom4`` and consumed+ by the Extract Class refactoring detector — when a class has+ ``lcom4 >= 2`` each group is a candidate extracted class. ``methods``+ and ``fields`` are stable-sorted (by first appearance / name) so the+ same class yields the same split across runs.+ """++ methods: list[str]+ fields: list[str]++@dataclassclass ClassComplexity:"""Per-class aggregate metrics produced by the walker.@@ -71,6 +88,12 @@ class ClassComplexity:``1`` means a fully cohesive class (or "no signal": see the safetyvalve in ``_compute_lcom4``). Higher values mean the class splintersinto unrelated method clusters.++ ``components`` carries those connected components as ``CohesionGroup``+ records (the method+field membership behind the ``lcom4`` integer).+ Empty when there is no cohesion signal (``lcom4`` was the ``1`` safety+ valve); otherwise ``len(components) == lcom4``. The Extract Class+ refactoring detector reads it directly — it *is* the split."""name: str@@ -82,6 +105,7 @@ class ClassComplexity:lcom4: int = 1max_method_ccn: int = 0field_count: int = 0+ components: list[CohesionGroup] = field(default_factory=list)@dataclass(frozen=True)diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 606564500..208f7cb42 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -50,6 +50,7 @@ from .languages import get_language_map# keep importing the output schema from ``complexity.walker`` unchanged.from .models import (ClassComplexity,+ CohesionGroup,ConditionComplexity,ErrorHandlingHit,FileComplexity,@@ -65,6 +66,7 @@ from .perf_walk import _collect_perf_hits__all__ = ["ClassComplexity",+ "CohesionGroup","ConditionComplexity","ErrorHandlingHit","FileComplexity",diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex d3013063b..5043e3a5d 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -37,6 +37,7 @@ from .complexity import FileComplexity, FunctionComplexity, walk_filefrom .coverage import is_test_file as _coverage_is_test_filefrom .duplication import DuplicationReport, detect_clonesfrom .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity+from .refactoring import RefactoringContext, RefactoringSuggestion, detect_refactoringsfrom .perf import (CallGraphIndex,PerfRanker,@@ -348,8 +349,10 @@ class HealthAnalyzer:log.debug("health_duplication_failed", error=str(exc))dup_report = DuplicationReport()+ disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))findings: list[HealthFindingData] = []metrics: list[HealthFileMetricData] = []+ suggestions: list[RefactoringSuggestion] = []# Pre-walk every target so we can compute the repo-wide p80 of# per-function modification counts ONCE before any biomarker runs.@@ -390,7 +393,7 @@ class HealthAnalyzer:file_disabled.append(name)file_severity_overrides = dict(repo_severity_overrides)file_severity_overrides.update(per_file_severity_overrides.get(pf.file_info.path, {}))- file_metric, file_findings = self._evaluate_file(+ file_metric, file_findings, file_suggestions = self._evaluate_file(pf,fcx,path_basenames,@@ -402,9 +405,11 @@ class HealthAnalyzer:repo_dependents_p80=repo_dependents_p80,repo_active_contributors_90d=repo_active_contributors,severity_overrides=file_severity_overrides or None,+ disabled_refactorings=disabled_refactorings,)metrics.append(file_metric)findings.extend(file_findings)+ suggestions.extend(file_suggestions)if on_step:on_step(pf.file_info.path)@@ -425,6 +430,7 @@ class HealthAnalyzer:metrics=metrics,kpis=kpis,function_blame_rows=self._function_blame_rows(walked),+ refactoring_suggestions=suggestions,)async def analyze_async(@@ -530,8 +536,10 @@ class HealthAnalyzer:walked = list(walked)self._apply_crossfn_perf(walked)+ disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))findings: list[HealthFindingData] = []metrics: list[HealthFileMetricData] = []+ suggestions: list[RefactoringSuggestion] = []for pf, fcx in walked:self._populate_symbol_complexity(pf, fcx.functions)file_disabled = list(disabled)@@ -542,7 +550,7 @@ class HealthAnalyzer:file_disabled.append(name)file_severity_overrides = dict(repo_severity_overrides)file_severity_overrides.update(per_file_severity_overrides.get(pf.file_info.path, {}))- file_metric, file_findings = self._evaluate_file(+ file_metric, file_findings, file_suggestions = self._evaluate_file(pf,fcx,path_basenames,@@ -554,9 +562,11 @@ class HealthAnalyzer:repo_dependents_p80=repo_dependents_p80,repo_active_contributors_90d=repo_active_contributors,severity_overrides=file_severity_overrides or None,+ disabled_refactorings=disabled_refactorings,)metrics.append(file_metric)findings.extend(file_findings)+ suggestions.extend(file_suggestions)if on_step:on_step(pf.file_info.path)@@ -573,6 +583,7 @@ class HealthAnalyzer:metrics=metrics,kpis=kpis,function_blame_rows=self._function_blame_rows(walked),+ refactoring_suggestions=suggestions,)# ------------------------------------------------------------------@@ -674,7 +685,8 @@ class HealthAnalyzer:repo_dependents_p80: int | None = None,repo_active_contributors_90d: int | None = None,severity_overrides: dict[str, Severity] | None = None,- ) -> tuple[HealthFileMetricData, list[HealthFindingData]]:+ disabled_refactorings: list[str] | None = None,+ ) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:file_path = pf.file_info.pathfc_list = fcx.functions@@ -764,7 +776,20 @@ class HealthAnalyzer:maintainability_score=(round(maint_score, 2) if maint_score is not None else None),performance_score=(round(perf_score, 2) if perf_score is not None else None),)- return metric, findings++ # Refactoring layer: reuse the data just computed (class cohesion+ # components + this file's findings) to emit structured suggestions.+ # Fault-isolated per detector; degrades to [] on any missing signal.+ rctx = RefactoringContext(+ file_path=file_path,+ language=pf.file_info.language,+ nloc=nloc,+ classes=fcx.classes,+ findings=findings,+ dependents_count=dependents_count,+ )+ suggestions = detect_refactorings(rctx, disabled=disabled_refactorings or ())+ return metric, findings, suggestionsdef _is_hotspot(self, meta: dict | object) -> bool:if isinstance(meta, dict):diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex 104e1ccf9..b987847f5 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -74,3 +74,9 @@ class HealthReport:# Per-function blame rollup rows (``git_function_blame``), derived from the# FULL-tier blame index. Empty on ESSENTIAL tier / when blame is absent.function_blame_rows: list[dict] = field(default_factory=list)+ # Deterministic refactoring suggestions (``RefactoringSuggestion``), one+ # per detected opportunity. Produced by the refactoring layer in the same+ # per-file pass that produces findings; empty when the layer is disabled+ # or no opportunity is found. Typed ``Any`` to avoid importing the+ # refactoring package here (it imports this module).+ refactoring_suggestions: list[Any] = field(default_factory=list)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.pynew file mode 100644index 000000000..248dbee4c--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py@@ -0,0 +1,39 @@+"""Deterministic refactoring-intelligence layer (code-health sub-capability).++Turns the structural signals the health pass already computes (LCOM4+cohesion components, clone pairs, the call graph) into concrete, structured+``RefactoringSuggestion`` plans — "split this class into these groups",+"extract this clone here" — with zero LLM calls and zero new runtime deps.++Importing this package registers every detector (the modules below+self-register via ``@register``), so ``detect_refactorings`` sees them.+"""++from __future__ import annotations++# Importing the detector modules triggers their ``@register`` side effect.+# Listed explicitly (and in a fixed order) so the registry is deterministic.+from . import extract_class # noqa: F401 (import-for-side-effect)+from .models import (+ CONFIDENCE_LEVELS,+ RefactoringContext,+ RefactoringSuggestion,+)+from .registry import (+ RefactoringDetector,+ detect_refactorings,+ effort_bucket,+ register,+ registered_detectors,+)++__all__ = [+ "CONFIDENCE_LEVELS",+ "RefactoringContext",+ "RefactoringDetector",+ "RefactoringSuggestion",+ "detect_refactorings",+ "effort_bucket",+ "register",+ "registered_detectors",+]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.pynew file mode 100644index 000000000..df3747c24--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py@@ -0,0 +1,156 @@+"""Extract Class detector — the flagship refactoring (Phase 1).++When a class's LCOM4 cohesion components splinter into two or more groups+(methods that share no fields or calls), each component is a candidate+extracted class. The split is not heuristic: it *is* the LCOM4 connected+components the walker already computed (``ClassComplexity.components``), so+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+``RefactoringSuggestion`` per splittable class with the concrete group+breakdown.++Precision-first — Extract Class is about partitioning *shared state* into+cohesive classes, so the gate demands genuine state to partition:++- the class is one the cohesion biomarker already flags (``lcom4 >= 2``,+ ``method_count >= _MIN_METHODS``), so the list never exceeds what health+ surfaces;+- at least two *field-bearing* groups — the state splits into ≥2 independent+ stateful clusters, not "one core + loose helpers";+- a minimum field density (fields per method) — this rejects stateless+ strategy / dialect classes (many independent predicate methods, almost no+ shared state) that LCOM4 over-fires on but that should never be "split".++The displayed plan keeps only the substantive groups (field-bearing or+multi-method); lone fieldless helper methods don't constitute their own+extracted class and are dropped from the split so the plan reads honestly.+"""++from __future__ import annotations++from .models import RefactoringContext, RefactoringSuggestion+from .registry import RefactoringDetector, effort_bucket, register++# The cohesion biomarkers this detector answers. A class is only suggested+# for splitting if one of these flagged it, so the suggestion list never+# exceeds (and stays consistent with) what health already surfaces.+_SOURCE_BIOMARKERS = ("low_cohesion", "god_class")++# Mirror ``LowCohesionDetector._MIN_METHODS`` so a class we suggest splitting+# is exactly one the cohesion biomarker would also flag — never noise below+# its threshold.+_MIN_METHODS = 5++# Minimum shared-state density (instance fields per method) for a class to be+# a real Extract Class target. Stateless strategy/dialect classes — lots of+# independent predicate methods, near-zero shared fields — sit well below this+# (dogfooded at <=0.29 on our own ``*PerfDialect`` classes) and are rejected;+# genuinely stateful god classes sit at ~0.5 to 1.0.+_MIN_FIELD_DENSITY = 0.4+++def _is_substantive(group: object) -> bool:+ """A group worth extracting on its own: ≥2 methods, or ≥1 method that+ touches ≥1 field. Filters out lone, fieldless helper methods so a class+ isn't sold as an N-way split when it is really "one class + loners"."""+ methods = getattr(group, "methods", [])+ fields = getattr(group, "fields", [])+ return len(methods) >= 2 or (len(methods) >= 1 and len(fields) >= 1)+++@register+class ExtractClassDetector(RefactoringDetector):+ name = "extract_class"++ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:+ out: list[RefactoringSuggestion] = []+ impact_by_class = self._impact_by_class(ctx)++ for cls in ctx.classes:+ components = getattr(cls, "components", None) or []+ # Need a real multi-component split on a class big enough to matter+ # and stateful enough that splitting its fields makes sense.+ if cls.lcom4 < 2 or cls.method_count < _MIN_METHODS:+ continue+ field_density = cls.field_count / max(cls.method_count, 1)+ if field_density < _MIN_FIELD_DENSITY:+ continue+ # The split must partition real state into ≥2 stateful clusters.+ field_bearing = [g for g in components if getattr(g, "fields", None)]+ if len(field_bearing) < 2:+ continue+ # Present only the substantive groups; lone fieldless helpers don't+ # form their own class. Re-check we still have a ≥2-way split.+ substantive = [g for g in components if _is_substantive(g)]+ if len(substantive) < 2:+ continue++ wmc = sum(getattr(m, "ccn", 0) for m in getattr(cls, "methods", []))+ impact_delta, source = impact_by_class.get(cls.name, (0.0, ""))++ groups = [+ {"name": None, "methods": list(g.methods), "fields": list(g.fields)}+ for g in substantive+ ]+ out.append(+ RefactoringSuggestion(+ refactoring_type=self.name,+ file_path=ctx.file_path,+ target_symbol=cls.name,+ line_start=cls.start_line,+ line_end=cls.end_line,+ plan={"groups": groups},+ evidence={+ "lcom4": cls.lcom4,+ "method_count": cls.method_count,+ "field_count": cls.field_count,+ "wmc": wmc,+ },+ impact_delta=round(float(impact_delta), 3),+ effort_bucket=effort_bucket(cls.total_nloc),+ blast_radius={"dependents_count": ctx.dependents_count},+ confidence=self._confidence(cls),+ source_biomarker=source or _SOURCE_BIOMARKERS[0],+ )+ )++ # Stable order: biggest recovery first, then by class name so ties+ # (and the no-finding case) are still deterministic.+ out.sort(key=lambda s: (-s.impact_delta, s.target_symbol))+ return out++ @staticmethod+ def _impact_by_class(ctx: RefactoringContext) -> dict[str, tuple[float, str]]:+ """Map class name -> (recovered impact, source biomarker) from the+ file's cohesion findings. The biomarkers report ``function_name`` =+ the class name; keep the largest impact when both fire on one class.+ """+ by_class: dict[str, tuple[float, str]] = {}+ for f in ctx.findings:+ if getattr(f, "biomarker_type", "") not in _SOURCE_BIOMARKERS:+ continue+ name = getattr(f, "function_name", None)+ if not name:+ # Fall back to the details payload both biomarkers carry.+ name = (getattr(f, "details", {}) or {}).get("class_name")+ if not name:+ continue+ impact = float(getattr(f, "health_impact", 0.0) or 0.0)+ prev = by_class.get(name)+ if prev is None or impact > prev[0]:+ by_class[name] = (impact, getattr(f, "biomarker_type", ""))+ return by_class++ @staticmethod+ def _confidence(cls: object) -> str:+ """High when the god-class shape is unambiguous (many groups / many+ methods); medium for a clean two-way split."""+ lcom4 = getattr(cls, "lcom4", 0)+ method_count = getattr(cls, "method_count", 0)+ if lcom4 >= 3 or method_count >= 15:+ return "high"+ return "medium"diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pynew file mode 100644index 000000000..8b19679cd--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -0,0 +1,84 @@+"""Structured refactoring suggestions — the spine of the refactoring layer.++A ``RefactoringSuggestion`` is the deterministic, structured output of a+``RefactoringDetector`` (see ``registry.py``). It replaces the old static+suggestion *string* with a record carrying the concrete plan, the evidence+behind it, and the blast radius of applying it. Human-readable text is+rendered from this structure at the edges (CLI / MCP / web); the structure+is the source of truth, never a string.++The schema is shared across refactoring types: ``plan`` / ``evidence`` /+``blast_radius`` are open dicts whose shape is type-specific (documented per+detector), so later phases (Extract Helper, Move Method, Break Cycle) add a+type without touching this module. For Extract Class (Phase 1):++- ``plan`` = ``{"groups": [{"name": None, "methods": [...], "fields": [...]}]}``+ — one group per cohesive cluster the class should split into.+- ``evidence`` = ``{"lcom4": int, "method_count": int, "field_count": int,+ "wmc": int}`` — the cohesion/size signals that justify the split.+- ``blast_radius`` = ``{"dependents_count": int}`` — files importing the+ class's file that may need to follow the split.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++# Confidence buckets a detector may assign. Ordered low -> high; the surface+# layers may filter on a ``min_confidence`` config (Phase 1 default: medium).+CONFIDENCE_LEVELS = ("low", "medium", "high")+++@dataclass+class RefactoringContext:+ """Per-file inputs a ``RefactoringDetector`` reads.++ Assembled by the health engine from data it has already computed (no+ re-parse): the file's class models (carrying LCOM4 ``components``), the+ file's biomarker findings (so a detector can read the ``health_impact``+ its refactoring would recover), the file's NLOC (for the effort bucket),+ and the file-level dependents count (the blast-radius seed). Detectors+ degrade to "no suggestion" on any missing signal — never a wrong one.+ """++ file_path: str+ language: str+ nloc: int+ # ``ClassComplexity`` records for the file (typed ``Any`` to avoid a+ # circular import with the complexity walker package).+ classes: list[Any] = field(default_factory=list)+ # The file's ``HealthFindingData`` findings (typed ``Any`` for the same+ # reason); a detector keys off these for the recovered impact.+ findings: list[Any] = field(default_factory=list)+ # Files importing this file (graph in-degree) — the blast-radius seed.+ dependents_count: int = 0+++@dataclass+class RefactoringSuggestion:+ """One deterministic refactoring opportunity. Persisted as a+ ``RefactoringSuggestion`` ORM row; rendered to text only at the edges.+ """++ refactoring_type: str # "extract_class" (Phase 1); more in later phases+ file_path: str+ target_symbol: str # the class / method / site the refactoring acts on+ line_start: int | None+ line_end: int | None+ # The concrete plan — shape is ``refactoring_type``-specific (see module+ # docstring). Always structured data, never prose.+ 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). >= 0.+ impact_delta: float+ # Effort estimate — "S" | "M" | "L" | "XL" (from the target's size).+ effort_bucket: str+ # What else must change: callers, co-change partners, importing files.+ blast_radius: dict[str, Any]+ # "low" | "medium" | "high" — drives the ``min_confidence`` surface gate.+ confidence: str+ # The biomarker finding this suggestion answers (e.g. "low_cohesion").+ source_biomarker: str = ""diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py b/packages/core/src/repowise/core/analysis/health/refactoring/registry.pynew file mode 100644index 000000000..e6ef79744--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py@@ -0,0 +1,81 @@+"""Refactoring-detector registry — the modular spine of the layer.++Every refactoring type is a self-contained ``RefactoringDetector`` that+registers itself with the ``@register`` decorator. Adding a refactoring is a+new file plus an import in ``__init__.py`` — zero edits to the health engine.+``detect_refactorings`` runs every registered detector with per-detector+fault isolation (a detector that raises yields no suggestion, never breaks+the health pass), mirroring the biomarker registry's ``detect_all``.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from collections.abc import Sequence++import structlog++from .models import RefactoringContext, RefactoringSuggestion++log = structlog.get_logger(__name__)+++def effort_bucket(nloc: int) -> str:+ """Map a target's NLOC to a coarse effort bucket.++ Shared by every detector so the effort label is consistent across+ refactoring types (matches the CLI's refactoring-targets thresholds).+ """+ if nloc <= 40:+ return "S"+ if nloc <= 150:+ return "M"+ if nloc <= 400:+ return "L"+ return "XL"+++class RefactoringDetector(ABC):+ """Detector contract. Each concrete detector sets a unique ``name`` and+ implements ``detect`` over a single file's ``RefactoringContext``.+ """++ name: str = ""++ @abstractmethod+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:+ """Return zero or more suggestions for *ctx*. Deterministic: the same+ context must always yield the same suggestions in the same order."""+ raise NotImplementedError+++# Registration is import-time and order-deterministic: ``__init__`` imports+# the detector modules in a fixed order, so ``_REGISTRY`` is stable per run.+_REGISTRY: list[RefactoringDetector] = []+++def register(cls: type[RefactoringDetector]) -> type[RefactoringDetector]:+ """Class decorator: instantiate *cls* and add it to the registry."""+ _REGISTRY.append(cls())+ return cls+++def registered_detectors(*, disabled: Sequence[str] = ()) -> list[RefactoringDetector]:+ """Active detector instances, minus any whose ``name`` is *disabled*."""+ disabled_set = set(disabled)+ return [d for d in _REGISTRY if d.name not in disabled_set]+++def detect_refactorings(+ ctx: RefactoringContext, *, disabled: Sequence[str] = ()+) -> list[RefactoringSuggestion]:+ """Run every registered detector on *ctx*, fault-isolated per detector."""+ out: list[RefactoringSuggestion] = []+ for detector in registered_detectors(disabled=disabled):+ try:+ out.extend(detector.detect(ctx))+ except Exception as exc:+ # One bad detector must not break the health pass; degrade to+ # "no suggestion" for this file.+ log.debug("refactoring_detector_failed", detector=detector.name, error=str(exc))+ return outdiff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.pyindex d3bc97d1e..5d78396dc 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py@@ -21,6 +21,7 @@ from ..models import (HealthFileMetric,HealthFinding,HealthSnapshot,+ RefactoringSuggestion,_new_uuid,_now_utc,)@@ -55,9 +56,7 @@ def _dead_code_row_kwargs(finding: Any, repository_id: str) -> dict:"commit_count_90d": finding.commit_count_90d,"lines": finding.lines,"package": finding.package,- "evidence_json": json.dumps(- finding.evidence if hasattr(finding, "evidence") else []- ),+ "evidence_json": json.dumps(finding.evidence if hasattr(finding, "evidence") else []),"safe_to_delete": finding.safe_to_delete,"primary_owner": finding.primary_owner,"age_days": finding.age_days,@@ -441,9 +440,7 @@ async def get_health_findings(# Older rows predate the split and carry a NULL dimension that homes# under "defect"; fold those in so a defect filter never drops them.if dimension == "defect":- q = q.where(- or_(HealthFinding.dimension == "defect", HealthFinding.dimension.is_(None))- )+ q = q.where(or_(HealthFinding.dimension == "defect", HealthFinding.dimension.is_(None)))else:q = q.where(HealthFinding.dimension == dimension)if min_severity is not None:@@ -783,6 +780,145 @@ async def upsert_health_metrics(await session.flush()+# ---------------------------------------------------------------------------+# Refactoring suggestion CRUD+# ---------------------------------------------------------------------------+++def _refactoring_row_kwargs(suggestion: Any, repository_id: str) -> dict:+ """Normalize a ``RefactoringSuggestion`` dataclass or a plain dict into+ kwargs for the ORM row (folding the open ``plan`` / ``evidence`` /+ ``blast_radius`` dicts into their ``*_json`` columns)."""+ if hasattr(suggestion, "refactoring_type"):+ data = {+ "refactoring_type": suggestion.refactoring_type,+ "file_path": suggestion.file_path,+ "target_symbol": suggestion.target_symbol,+ "line_start": suggestion.line_start,+ "line_end": suggestion.line_end,+ "plan_json": json.dumps(suggestion.plan or {}),+ "evidence_json": json.dumps(suggestion.evidence or {}),+ "impact_delta": float(suggestion.impact_delta),+ "effort_bucket": suggestion.effort_bucket,+ "blast_radius_json": json.dumps(suggestion.blast_radius or {}),+ "confidence": suggestion.confidence,+ "source_biomarker": suggestion.source_biomarker,+ }+ else:+ data = dict(suggestion)+ for key in ("plan", "evidence", "blast_radius"):+ if key in data:+ data[f"{key}_json"] = json.dumps(data.pop(key) or {})++ return {+ "id": _new_uuid(),+ "repository_id": repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(RefactoringSuggestion, k)+ },+ }+++async def save_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ suggestions: list[Any],+) -> None:+ """Replace open refactoring suggestions for *repository_id*.++ Delete-then-insert, mirroring ``save_health_findings``. Accepts+ ``RefactoringSuggestion`` dataclasses or plain dicts.+ """+ existing = await session.execute(+ select(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.status == "open",+ )+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ for i in range(0, len(suggestions), _BATCH_SIZE):+ batch = suggestions[i : i + _BATCH_SIZE]+ for s in batch:+ session.add(RefactoringSuggestion(**_refactoring_row_kwargs(s, repository_id)))+ await session.flush()+++async def upsert_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ suggestions: list[Any],+ *,+ file_paths: list[str],+) -> None:+ """Replace open suggestions **only for the given file paths**.++ The incremental ``repowise update`` sibling of+ ``save_refactoring_suggestions``: unchanged files keep their suggestions.+ Pass the full set of *changed* paths (not just those that produced a+ suggestion) so a changed-but-now-clean file is cleared.+ """+ if not file_paths:+ return+ allowed = set(file_paths)+ existing = await session.execute(+ select(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.status == "open",+ RefactoringSuggestion.file_path.in_(file_paths),+ )+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ scoped = [s for s in suggestions if _finding_file_path(s) in allowed]+ for i in range(0, len(scoped), _BATCH_SIZE):+ batch = scoped[i : i + _BATCH_SIZE]+ for s in batch:+ session.add(RefactoringSuggestion(**_refactoring_row_kwargs(s, repository_id)))+ await session.flush()+++async def get_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ *,+ refactoring_type: str | None = None,+ file_paths: list[str] | None = None,+ min_confidence: str | None = None,+ status: str = "open",+) -> list[RefactoringSuggestion]:+ """Return refactoring suggestions, highest recovered impact first."""+ q = select(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.status == status,+ )+ if refactoring_type is not None:+ q = q.where(RefactoringSuggestion.refactoring_type == refactoring_type)+ if file_paths is not None:+ q = q.where(RefactoringSuggestion.file_path.in_(file_paths))+ if min_confidence is not None:+ order = {"low": 0, "medium": 1, "high": 2}+ threshold = order.get(min_confidence, 0)+ allowed = [k for k, v in order.items() if v >= threshold]+ q = q.where(RefactoringSuggestion.confidence.in_(allowed))+ # Secondary keys (file_path, target_symbol) make the read order stable for+ # ties — notably the common 0.0 no-finding case — so it matches the+ # detector's own deterministic ordering rather than DB row order.+ q = q.order_by(+ RefactoringSuggestion.impact_delta.desc(),+ RefactoringSuggestion.file_path.asc(),+ RefactoringSuggestion.target_symbol.asc(),+ )+ result = await session.execute(q)+ return list(result.scalars().all())++# ---------------------------------------------------------------------------# Coverage CRUD# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 2d7f4f3e5..7329d78bd 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -898,6 +898,44 @@ class HealthFinding(Base):)+class RefactoringSuggestion(Base):+ """One deterministic refactoring opportunity from the refactoring layer.++ Mirrors the ``RefactoringSuggestion`` dataclass in+ ``analysis/health/refactoring/models.py``. ``plan_json`` /+ ``evidence_json`` / ``blast_radius_json`` carry the structured,+ type-specific payloads (open dicts) so later refactoring types add no+ columns. Written delete-then-insert per repo (or upserted per changed+ file on incremental updates), exactly like ``health_findings``.+ """++ __tablename__ = "refactoring_suggestions"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ refactoring_type: Mapped[str] = mapped_column(String(32), nullable=False)+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ target_symbol: Mapped[str] = mapped_column(String(255), nullable=False, default="")+ line_start: Mapped[int | None] = mapped_column(Integer, nullable=True)+ line_end: Mapped[int | None] = mapped_column(Integer, nullable=True)+ plan_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ impact_delta: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ effort_bucket: Mapped[str] = mapped_column(String(8), nullable=False, default="")+ blast_radius_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ confidence: Mapped[str] = mapped_column(String(16), nullable=False, default="medium")+ source_biomarker: Mapped[str] = mapped_column(String(64), nullable=False, default="")+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++class HealthFileMetric(Base):"""Per-file aggregate metrics + final score."""diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex af385d126..c18382f3b 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -332,6 +332,7 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Nonfrom repowise.core.persistence.crud import (upsert_health_findings,upsert_health_metrics,+ upsert_refactoring_suggestions,)changed_paths = sorted({m.file_path for m in report.metrics or []})@@ -341,6 +342,15 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Nonawait upsert_health_findings(session, repo_id, list(report.findings or []), file_paths=changed_paths)+ # Refactoring suggestions for the changed files only (unchanged files keep+ # theirs). Scoped delete-then-insert across the full changed-file set, so a+ # file that became clean has its stale suggestions removed.+ await upsert_refactoring_suggestions(+ session,+ repo_id,+ list(getattr(report, "refactoring_suggestions", None) or []),+ file_paths=changed_paths,+ )# Per-function blame rollup for the changed files (keeps git_function_blame# current between full indexes; FULL git tier only — empty otherwise).fn_blame_rows = getattr(report, "function_blame_rows", None)diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 3c4b97856..c6b51b913 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -511,6 +511,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:save_health_findings,save_health_metrics,save_health_snapshot,+ save_refactoring_suggestions,upsert_git_function_blame_bulk,)@@ -524,6 +525,11 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:await save_health_metrics(session, repo_id, hr.metrics or [])if hr.findings:await save_health_findings(session, repo_id, hr.findings)+ # Structured refactoring suggestions (Extract Class, ...). Repo-wide+ # delete-then-insert like findings; empty list clears prior rows.+ await save_refactoring_suggestions(+ session, repo_id, getattr(hr, "refactoring_suggestions", None) or []+ )# Per-function blame rollup (FULL tier only; empty otherwise).fn_blame_rows = getattr(hr, "function_blame_rows", None)if fn_blame_rows:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex a948bf304..dc714e519 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -21,6 +21,7 @@ from repowise.core.persistence.crud import (get_git_metadata,get_graph_node,get_node_degree_counts,+ get_refactoring_suggestions,list_health_snapshots,load_coverage_for_repo,)@@ -58,6 +59,36 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:}+def _serialize_refactoring(r: Any) -> dict[str, Any]:+ """Serialize a ``RefactoringSuggestion`` ORM row into a structured plan.++ The ``*_json`` columns are decoded back into their open dicts so an agent+ reads the concrete plan (the split groups, the evidence, the blast radius)+ rather than a prose string.+ """++ def _load(raw: str | None) -> Any:+ try:+ return json.loads(raw) if raw else {}+ except Exception:+ return {}++ return {+ "refactoring_type": r.refactoring_type,+ "file_path": r.file_path,+ "target_symbol": r.target_symbol,+ "line_start": r.line_start,+ "line_end": r.line_end,+ "plan": _load(r.plan_json),+ "evidence": _load(r.evidence_json),+ "impact_delta": round(r.impact_delta, 3),+ "effort_bucket": r.effort_bucket,+ "blast_radius": _load(r.blast_radius_json),+ "confidence": r.confidence,+ "source_biomarker": r.source_biomarker,+ }++def _round_opt(v: Any) -> float | None:"""Round a nullable per-dimension score, preserving ``None`` (not measured)."""return round(v, 2) if v is not None else None@@ -291,6 +322,20 @@ async def get_health(exclude_spec,)+ # Structured refactoring plans (Extract Class, ...) — loaded only when+ # asked for, scoped to the same targets, exclude-filtered like findings.+ refactoring_rows: list[Any] = []+ if "refactoring" in include_set:+ refactoring_rows = filter_rows_by_attr(+ await get_refactoring_suggestions(+ session,+ repository.id,+ file_paths=list(effective_targets) if effective_targets else None,+ ),+ "file_path",+ exclude_spec,+ )+coverage_rows: list[Any] = []coverage_summary: dict[str, Any] = {}if "coverage" in include_set:@@ -327,8 +372,7 @@ async def get_health(if "churn_complexity" in include_set and not effective_targets:git_meta_by_path = await get_all_git_metadata(session, repository.id)churn_points = [- asdict(p)- for p in churn_complexity_points(all_metrics, git_meta_by_path)[:limit]+ asdict(p) for p in churn_complexity_points(all_metrics, git_meta_by_path)[:limit]]# Load the snapshot window for the repo-level trend block and/or the@@ -401,9 +445,13 @@ async def get_health(result["findings"] = [_serialize_finding(f) for f in finding_rows]if "refactoring" in include_set:- # Attach deterministic refactoring suggestions to every finding- # in the response. Surfaces on the dashboard cards as well so- # both consumers stay in sync.+ # Structured refactoring plans (the concrete split groups / evidence /+ # blast radius) for detectors that have one — the upgrade over the old+ # prose-string suggestions.+ result["refactoring_plans"] = [_serialize_refactoring(r) for r in refactoring_rows]+ # Attach the deterministic prose suggestion to every finding as the+ # fallback for biomarkers without a structured detector yet. Surfaces+ # on the dashboard cards too so both consumers stay in sync.for field in ("findings", "top_findings"):rows = result.get(field)if rows:diff --git a/tests/unit/health/test_file_nloc.py b/tests/unit/health/test_file_nloc.pyindex 18f8be829..1155a72dc 100644--- a/tests/unit/health/test_file_nloc.py+++ b/tests/unit/health/test_file_nloc.py@@ -85,7 +85,7 @@ def test_health_metric_nloc_uses_file_nloc():file_info=SimpleNamespace(path="src/route.js", language="javascript", abs_path=str(p)),symbols=[],)- metric, _ = HealthAnalyzer(graph=None)._evaluate_file(+ metric, _, _ = HealthAnalyzer(graph=None)._evaluate_file(pf,fcx,path_basenames={"route.js"},diff --git a/tests/unit/health/test_refactoring_extract_class.py b/tests/unit/health/test_refactoring_extract_class.pynew file mode 100644index 000000000..befc624be--- /dev/null+++ b/tests/unit/health/test_refactoring_extract_class.py@@ -0,0 +1,228 @@+"""Tests for the Extract Class refactoring detector and its LCOM4 data unlock.++Two layers:+- the walker now returns the LCOM4 connected components behind the ``lcom4``+ integer (``ClassComplexity.components``);+- the ``ExtractClassDetector`` turns a multi-component class into a structured+ ``RefactoringSuggestion`` with the concrete split groups.++Fixtures are small real-Python classes with a known split so the expected+groups are unambiguous and the assertions are deterministic.+"""++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.refactoring import (+ RefactoringContext,+ detect_refactorings,+ registered_detectors,+)+from repowise.core.analysis.health.refactoring.extract_class import ExtractClassDetector++# A class with two disjoint, stateful responsibilities: a "parse" cluster over+# fields ``a``/``a2`` and a "render" cluster over fields ``b``/``b2``. No+# constructor links them, so LCOM4 sees two field-bearing components — a real+# Extract Class shape (high field density).+_TWO_JOB_CLASS = b"""+class TwoJobs:+ def parse_a(self):+ return self.a + self.a2+ def parse_a2(self):+ return self.parse_a() + self.a+ def parse_a3(self):+ return self.a2 + self.parse_a2()+ def render_b(self):+ return self.b + self.b2+ def render_b2(self):+ return self.render_b() * self.b+ def render_b3(self):+ return self.b2 + self.render_b2()+"""++# A cohesive class: every method touches the shared field, so LCOM4 == 1.+_COHESIVE_CLASS = b"""+class Cohesive:+ def a(self):+ return self.shared+ def b(self):+ return self.shared + self.a()+ def c(self):+ return self.shared + self.b()+ def d(self):+ return self.shared + self.c()+ def e(self):+ return self.shared + self.d()+"""+++def _walk(src: bytes) -> ClassComplexity:+ fc = walk_file("example.py", "python", src)+ assert fc.classes, "fixture produced no class"+ return fc.classes[0]+++class _Finding:+ """Minimal HealthFindingData-like stand-in for a cohesion finding."""++ def __init__(self, name: str, impact: float, biomarker: str = "low_cohesion"):+ self.biomarker_type = biomarker+ self.function_name = name+ self.health_impact = impact+ self.details = {"class_name": name}+++def _ctx(cls: ClassComplexity, findings: list | None = None, dependents: int = 0):+ return RefactoringContext(+ file_path="example.py",+ language="python",+ nloc=cls.total_nloc,+ classes=[cls],+ findings=findings or [],+ dependents_count=dependents,+ )+++# ---- data unlock: LCOM4 components ---------------------------------------+++def test_lcom4_returns_components_for_split_class():+ cls = _walk(_TWO_JOB_CLASS)+ assert cls.lcom4 == 2+ assert len(cls.components) == 2+ # Each component carries its methods + the field(s) it touches.+ groups = {tuple(g.methods): g.fields for g in cls.components}+ assert ["parse_a", "parse_a2", "parse_a3"] in [list(k) for k in groups]+ assert ["render_b", "render_b2", "render_b3"] in [list(k) for k in groups]+ for g in cls.components:+ assert g.fields # each cluster touches at least one field+++def test_cohesive_class_has_single_or_no_component():+ cls = _walk(_COHESIVE_CLASS)+ assert cls.lcom4 == 1+ # lcom4 == 1 means no real split to expose.+ assert len(cls.components) <= 1+++def test_components_are_deterministic_and_source_ordered():+ a = _walk(_TWO_JOB_CLASS)+ b = _walk(_TWO_JOB_CLASS)+ sig_a = [(tuple(g.methods), tuple(g.fields)) for g in a.components]+ sig_b = [(tuple(g.methods), tuple(g.fields)) for g in b.components]+ assert sig_a == sig_b+ # Groups read top-to-bottom: the parse cluster (earlier lines) first.+ assert a.components[0].methods[0] == "parse_a"+++# ---- detector ------------------------------------------------------------+++def test_detector_registered():+ assert "extract_class" in [d.name for d in registered_detectors()]+++def test_detector_emits_split_for_god_class():+ cls = _walk(_TWO_JOB_CLASS)+ findings = [_Finding("TwoJobs", 2.4)]+ sugs = detect_refactorings(_ctx(cls, findings, dependents=5))+ assert len(sugs) == 1+ s = sugs[0]+ assert s.refactoring_type == "extract_class"+ assert s.target_symbol == "TwoJobs"+ assert s.impact_delta == 2.4+ assert s.source_biomarker == "low_cohesion"+ assert s.blast_radius == {"dependents_count": 5}+ assert s.evidence["lcom4"] == 2+ assert s.evidence["method_count"] == 6+ assert s.evidence["wmc"] == sum(m.ccn for m in cls.methods)+ assert len(s.plan["groups"]) == 2+ assert all(g["name"] is None for g in s.plan["groups"])+++def test_detector_silent_on_cohesive_class():+ cls = _walk(_COHESIVE_CLASS)+ assert detect_refactorings(_ctx(cls)) == []+++def test_detector_silent_below_min_methods():+ # lcom4 >= 2 but only 4 methods — below the cohesion threshold, no suggestion.+ methods = [+ FunctionComplexity(+ name=f"m{i}", start_line=i, end_line=i, ccn=1, max_nesting=0, cognitive=0, nloc=2+ )+ for i in range(4)+ ]+ cls = ClassComplexity(+ name="Small",+ start_line=1,+ end_line=20,+ method_count=4,+ total_nloc=20,+ methods=methods,+ lcom4=2,+ )+ assert detect_refactorings(_ctx(cls)) == []+++def test_detector_without_finding_still_emits_with_zero_impact():+ cls = _walk(_TWO_JOB_CLASS)+ sugs = detect_refactorings(_ctx(cls, findings=[]))+ assert len(sugs) == 1+ assert sugs[0].impact_delta == 0.0+++def test_detector_output_is_stable_ordered():+ # Two splittable classes; output sorts by recovered impact desc, then name.+ src = (+ _TWO_JOB_CLASS+ + b"""+class OtherJobs:+ def load_x(self):+ return self.x + self.x2+ def load_x2(self):+ return self.load_x() + self.x+ def load_x3(self):+ return self.x2 + self.load_x2()+ def save_y(self):+ return self.y + self.y2+ def save_y2(self):+ return self.save_y() * self.y+ def save_y3(self):+ return self.y2 + self.save_y2()+"""+ )+ fc = walk_file("multi.py", "python", src)+ findings = [_Finding("TwoJobs", 1.0), _Finding("OtherJobs", 3.0)]+ ctx = RefactoringContext(+ file_path="multi.py",+ language="python",+ nloc=100,+ classes=fc.classes,+ findings=findings,+ )+ sugs = detect_refactorings(ctx)+ assert [s.target_symbol for s in sugs] == ["OtherJobs", "TwoJobs"]+++def test_disabled_detector_yields_nothing():+ cls = _walk(_TWO_JOB_CLASS)+ sugs = detect_refactorings(_ctx(cls, [_Finding("TwoJobs", 2.0)]), disabled=["extract_class"])+ assert sugs == []+++def test_detector_is_deterministic():+ cls = _walk(_TWO_JOB_CLASS)+ findings = [_Finding("TwoJobs", 2.4)]+ a = detect_refactorings(_ctx(cls, findings))+ b = detect_refactorings(_ctx(cls, findings))+ assert [(s.target_symbol, s.plan) for s in a] == [(s.target_symbol, s.plan) for s in b]+++def test_confidence_high_for_strong_god_class():+ cls = _walk(_TWO_JOB_CLASS)+ # Bump method_count to cross the high-confidence threshold.+ cls.method_count = 16+ det = ExtractClassDetector()+ assert det._confidence(cls) == "high"diff --git a/tests/unit/health/test_severity_overrides_integration.py b/tests/unit/health/test_severity_overrides_integration.pyindex 9f503d6d3..90e16fce7 100644--- a/tests/unit/health/test_severity_overrides_integration.py+++ b/tests/unit/health/test_severity_overrides_integration.py@@ -54,7 +54,7 @@ def _evaluate(severity_overrides):),symbols=[],)- metric, findings = HealthAnalyzer(graph=None)._evaluate_file(+ metric, findings, _ = HealthAnalyzer(graph=None)._evaluate_file(pf,fcx,path_basenames=set(),diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex e13db2c55..3d97140b8 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -316,6 +316,7 @@ def test_base_includes_all_models():"health_findings","health_file_metrics","health_snapshots",+ "refactoring_suggestions","coverage_files","pipeline_jobs","graph_metrics",diff --git a/tests/unit/persistence/test_refactoring_suggestions_crud.py b/tests/unit/persistence/test_refactoring_suggestions_crud.pynew file mode 100644index 000000000..2ec5143af--- /dev/null+++ b/tests/unit/persistence/test_refactoring_suggestions_crud.py@@ -0,0 +1,133 @@+"""Refactoring suggestions survive the persistence round trip.++Locks both writers — the full-reindex ``save_refactoring_suggestions`` and+the incremental ``upsert_refactoring_suggestions`` — plus the JSON payload+columns, so a future edit that forgets a field is caught.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.refactoring import RefactoringSuggestion+from repowise.core.persistence.crud.analysis import (+ get_refactoring_suggestions,+ save_refactoring_suggestions,+ upsert_refactoring_suggestions,+)+from tests.unit.persistence.helpers import insert_repo+++def _suggestion(path: str, target: str, **overrides) -> RefactoringSuggestion:+ base = dict(+ refactoring_type="extract_class",+ file_path=path,+ target_symbol=target,+ line_start=1,+ line_end=80,+ plan={"groups": [{"name": None, "methods": ["m1", "m2"], "fields": ["a"]}]},+ evidence={"lcom4": 2, "method_count": 6, "field_count": 2, "wmc": 9},+ impact_delta=2.4,+ effort_bucket="M",+ blast_radius={"dependents_count": 3},+ confidence="high",+ source_biomarker="low_cohesion",+ )+ base.update(overrides)+ return RefactoringSuggestion(**base)+++async def test_save_refactoring_suggestions_round_trip(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()++ rows = await get_refactoring_suggestions(async_session, repo.id)+ assert len(rows) == 1+ r = rows[0]+ assert r.refactoring_type == "extract_class"+ assert r.target_symbol == "Foo"+ assert r.impact_delta == 2.4+ assert r.effort_bucket == "M"+ assert r.confidence == "high"+ assert r.source_biomarker == "low_cohesion"+ import json++ assert json.loads(r.plan_json)["groups"][0]["fields"] == ["a"]+ assert json.loads(r.evidence_json)["wmc"] == 9+ assert json.loads(r.blast_radius_json)["dependents_count"] == 3+++async def test_save_is_idempotent(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ rows = await get_refactoring_suggestions(async_session, repo.id)+ assert len(rows) == 1+++async def test_get_filters_by_type_and_confidence(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(+ async_session,+ repo.id,+ [+ _suggestion("a.py", "Foo", confidence="high", impact_delta=3.0),+ _suggestion("b.py", "Bar", confidence="medium", impact_delta=1.0),+ ],+ )+ await async_session.commit()++ # Highest impact first.+ rows = await get_refactoring_suggestions(async_session, repo.id)+ assert [r.target_symbol for r in rows] == ["Foo", "Bar"]++ high_only = await get_refactoring_suggestions(async_session, repo.id, min_confidence="high")+ assert [r.target_symbol for r in high_only] == ["Foo"]++ typed = await get_refactoring_suggestions(+ async_session, repo.id, refactoring_type="extract_class"+ )+ assert len(typed) == 2+++async def test_get_breaks_impact_ties_deterministically(async_session):+ repo = await insert_repo(async_session)+ # Same impact (the common 0.0 no-finding case) across several files — the+ # read order must be stable, keyed (file_path, target_symbol), not DB order.+ await save_refactoring_suggestions(+ async_session,+ repo.id,+ [+ _suggestion("z.py", "Zeta", impact_delta=0.0),+ _suggestion("a.py", "Alpha", impact_delta=0.0),+ _suggestion("m.py", "Mu", impact_delta=0.0),+ ],+ )+ await async_session.commit()+ rows = await get_refactoring_suggestions(async_session, repo.id)+ assert [r.file_path for r in rows] == ["a.py", "m.py", "z.py"]+++async def test_upsert_only_touches_given_files(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(+ async_session,+ repo.id,+ [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")],+ )+ await async_session.commit()++ # Re-run for a.py only: a.py's rows are replaced, b.py's are untouched, and+ # a now-clean a.py (empty list scoped to its path) is cleared.+ await upsert_refactoring_suggestions(async_session, repo.id, [], file_paths=["a.py"])+ await async_session.commit()+ rows = await get_refactoring_suggestions(async_session, repo.id)+ assert [r.target_symbol for r in rows] == ["Bar"]