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): add Move Method and Break Cycle refactoring detectors (#588)

Raghav Chamadiya42517a290ed8
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py
index 65ace4226..fa5bca7b7 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py
@@ -547,21 +547,12 @@ def _render_refactoring_targets(
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, then — for clone dedup, where the
- # dry_violation deduction is near-uniform — the actively co-changed, larger
- # blocks; target_symbol last for a deterministic tie-break.
- def _plan_rank(p: dict) -> tuple:
- ev = p.get("evidence", {}) or {}
- return (
- -p.get("impact_delta", 0.0),
- -int(ev.get("co_change_count", 0)),
- -int(ev.get("duplicated_lines", 0)),
- p.get("target_symbol", ""),
- )
-
- ranked_plans = sorted((_suggestion_to_dict(s) for s in suggestions), key=_plan_rank)[:limit]
+ # Structured plans are displayed independently of the impact/effort file
+ # table (a god class worth splitting may not top that churn-weighted list).
+ # The order is the engine's unified rank (impact x centrality x blast
+ # radius across all detector types), so we preserve it rather than
+ # re-sorting per type.
+ ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]
if fmt == "json":
click.echo(json.dumps({"targets": targets, "refactoring_plans": ranked_plans}, indent=2))
@@ -576,6 +567,8 @@ def _render_refactoring_targets(
)
_render_extract_class_plans_md(ranked_plans)
_render_extract_helper_plans_md(ranked_plans)
+ _render_move_method_plans_md(ranked_plans)
+ _render_break_cycle_plans_md(ranked_plans)
return
table = Table(title=f"Refactoring targets ({len(targets)})")
@@ -597,6 +590,8 @@ def _render_refactoring_targets(
console.print(table)
_render_extract_class_plans_console(ranked_plans)
_render_extract_helper_plans_console(ranked_plans)
+ _render_move_method_plans_console(ranked_plans)
+ _render_break_cycle_plans_console(ranked_plans)
def _render_extract_class_plans_console(plans: list[dict]) -> None:
@@ -679,6 +674,80 @@ def _render_extract_helper_plans_md(plans: list[dict]) -> None:
click.echo(f" - {o['file']}:{o['line_start']}-{o['line_end']}")
+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"]
+ if not mm_plans:
+ return
+ console.print(f"\n[bold]Move Method plans ({len(mm_plans)})[/bold]")
+ for p in mm_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ to_file = pl.get("to_file")
+ dest = f"{pl.get('to_class')}" + (f" [dim]({to_file})[/dim]" if to_file else "")
+ console.print(
+ f"\n[cyan]{pl.get('from_class')}.{pl.get('method')}[/cyan] "
+ f"[dim]({p['file_path']})[/dim] → move to [bold]{dest}[/bold] "
+ f"[dim](uses {ev.get('foreign_calls')} of its members vs "
+ f"{ev.get('own_calls')} of its own, effort {p['effort_bucket']}, "
+ f"{p['confidence']} confidence)[/dim]"
+ )
+
+
+def _render_move_method_plans_md(plans: list[dict]) -> None:
+ mm_plans = [p for p in plans if p["refactoring_type"] == "move_method"]
+ if not mm_plans:
+ return
+ click.echo("\n## Move Method plans\n")
+ for p in mm_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ dest = pl.get("to_class")
+ if pl.get("to_file"):
+ dest = f"{dest} ({pl['to_file']})"
+ click.echo(
+ f"- **{pl.get('from_class')}.{pl.get('method')}** ({p['file_path']}) "
+ f"— move to `{dest}` "
+ f"(uses {ev.get('foreign_calls')} vs {ev.get('own_calls')} own members)"
+ )
+
+
+def _render_break_cycle_plans_console(plans: list[dict]) -> None:
+ """Print the concrete Break Cycle (import-cycle cut) plans below the table."""
+ bc_plans = [p for p in plans if p["refactoring_type"] == "break_cycle"]
+ if not bc_plans:
+ return
+ console.print(f"\n[bold]Break Cycle plans ({len(bc_plans)})[/bold]")
+ for p in bc_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ cuts = pl.get("cut_edges", [])
+ console.print(
+ f"\n[cyan]Import cycle of {ev.get('cycle_size')} files[/cyan] "
+ f"[dim]({ev.get('edge_count')} edges)[/dim] → cut "
+ f"{len(cuts)} edge(s) "
+ f"[dim](effort {p['effort_bucket']}, {p['confidence']} confidence)[/dim]"
+ )
+ for e in cuts:
+ console.print(f" [dim]-[/dim] invert {e['from']} → {e['to']}")
+ for f in pl.get("cycle", []):
+ console.print(f" [dim]·[/dim] {f}")
+
+
+def _render_break_cycle_plans_md(plans: list[dict]) -> None:
+ bc_plans = [p for p in plans if p["refactoring_type"] == "break_cycle"]
+ if not bc_plans:
+ return
+ click.echo("\n## Break Cycle plans\n")
+ for p in bc_plans:
+ pl = p["plan"]
+ ev = p["evidence"]
+ cuts = pl.get("cut_edges", [])
+ click.echo(f"- **Import cycle of {ev.get('cycle_size')} files** — cut {len(cuts)} edge(s):")
+ for e in cuts:
+ click.echo(f" - invert {e['from']} -> {e['to']}")
+
+
def _render_trend(repo_path: object, *, fmt: str) -> None:
"""Print the last 10 health snapshots straight from SQLite history.
diff --git a/packages/core/alembic/versions/0035_graph_node_membership.py b/packages/core/alembic/versions/0035_graph_node_membership.py
new file mode 100644
index 000000000..36f6d414d
--- /dev/null
+++ b/packages/core/alembic/versions/0035_graph_node_membership.py
@@ -0,0 +1,62 @@
+"""graph_node_membership table — queryable SCC + symbol-community rows.
+
+The break-cycle and move-method refactoring detectors reason over two
+structural facts the graph already carries but never persisted as rows:
+file-level strongly-connected components (import cycles) and symbol-level
+communities. They were only reachable by rebuilding the in-memory graph (or
+buried inside ``graph_nodes.community_meta_json``). This table materializes
+both as queryable rows — ``scc_id`` / ``scc_size`` for file nodes that sit in
+a real (size >= 2) cycle, and ``symbol_community_id`` for symbol nodes — so
+the web layer can read cycles and communities without re-running NetworkX.
+
+Additive to ``graph_nodes`` / ``graph_metrics``; written on full index and
+refreshed on the incremental graph-node path. Non-load-bearing: a failure to
+materialize never fails the index.
+
+Revision ID: 0035
+Revises: 0034
+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 = "0035"
+down_revision: str | None = "0034"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "graph_node_membership",
+ 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("node_id", sa.Text, nullable=False),
+ sa.Column("node_type", sa.String(16), nullable=False, server_default="file"),
+ sa.Column("scc_id", sa.Integer, nullable=True),
+ sa.Column("scc_size", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("symbol_community_id", sa.Integer, nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
+ sa.UniqueConstraint("repository_id", "node_id", name="uq_graph_node_membership"),
+ )
+ op.create_index(
+ "ix_graph_node_membership_repo",
+ "graph_node_membership",
+ ["repository_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_graph_node_membership_repo", "graph_node_membership")
+ op.drop_table("graph_node_membership")
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 0370c407c..792da4417 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -37,7 +37,6 @@ from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
from .duplication import DuplicationReport, detect_clones
from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity
-from .refactoring import RefactoringContext, RefactoringSuggestion, detect_refactorings
from .perf import (
CallGraphIndex,
PerfRanker,
@@ -45,6 +44,13 @@ from .perf import (
collect_centrality_gated,
collect_crossfn_io_in_loop,
)
+from .refactoring import (
+ RefactoringContext,
+ RefactoringSuggestion,
+ detect_refactorings,
+ rank_suggestions,
+)
+from .refactoring.graph_signals import build_file_scc_index
from .scoring import attach_impacts, compute_kpis, remap_severities, score_file
log = structlog.get_logger(__name__)
@@ -350,6 +356,9 @@ class HealthAnalyzer:
dup_report = DuplicationReport()
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
+ # Repo-wide SCC index (import cycles), computed once and threaded into
+ # each file's RefactoringContext so Break Cycle never recomputes it.
+ file_scc_index = build_file_scc_index(self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
suggestions: list[RefactoringSuggestion] = []
@@ -406,6 +415,7 @@ class HealthAnalyzer:
repo_active_contributors_90d=repo_active_contributors,
severity_overrides=file_severity_overrides or None,
disabled_refactorings=disabled_refactorings,
+ file_scc_index=file_scc_index,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -423,6 +433,9 @@ class HealthAnalyzer:
else:
kpis = {}
+ suggestions = rank_suggestions(
+ suggestions, centrality=self._refactoring_centrality(suggestions)
+ )
return HealthReport(
repo_id="",
analyzed_at=datetime.now(UTC),
@@ -537,6 +550,7 @@ class HealthAnalyzer:
self._apply_crossfn_perf(walked)
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
+ file_scc_index = build_file_scc_index(self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
suggestions: list[RefactoringSuggestion] = []
@@ -563,6 +577,7 @@ class HealthAnalyzer:
repo_active_contributors_90d=repo_active_contributors,
severity_overrides=file_severity_overrides or None,
disabled_refactorings=disabled_refactorings,
+ file_scc_index=file_scc_index,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -576,6 +591,9 @@ class HealthAnalyzer:
else:
kpis = {}
+ suggestions = rank_suggestions(
+ suggestions, centrality=self._refactoring_centrality(suggestions)
+ )
return HealthReport(
repo_id="",
analyzed_at=datetime.now(UTC),
@@ -590,6 +608,24 @@ class HealthAnalyzer:
# Helpers
# ------------------------------------------------------------------
+ def _refactoring_centrality(self, suggestions: list[RefactoringSuggestion]) -> dict[str, float]:
+ """File-dependency centrality (importer in-degree) for each file a
+ suggestion targets — the cheap, deterministic proxy ``rank`` blends
+ with impact + blast radius. Empty when the health pass ran without a
+ graph (the ranking then degrades to impact + blast only)."""
+ if self.graph is None:
+ return {}
+ out: dict[str, float] = {}
+ for s in suggestions:
+ path = s.file_path
+ if path in out or path not in self.graph:
+ continue
+ try:
+ out[path] = float(self.graph.in_degree(path))
+ except Exception:
+ out[path] = 0.0
+ return out
+
def _apply_crossfn_perf(self, walked: list[tuple[Any, FileComplexity]]) -> None:
"""Run the graph-dependent perf passes over the walked files, in place.
@@ -686,6 +722,7 @@ class HealthAnalyzer:
repo_active_contributors_90d: int | None = None,
severity_overrides: dict[str, Severity] | None = None,
disabled_refactorings: list[str] | None = None,
+ file_scc_index: dict[str, tuple[str, ...]] | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:
file_path = pf.file_info.path
@@ -789,6 +826,8 @@ class HealthAnalyzer:
dependents_count=dependents_count,
clones=list(clones),
module_map=self.module_map,
+ graph=self.graph,
+ file_scc=(file_scc_index or {}).get(file_path),
)
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 5ffc1e0c8..4b40d254e 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
@@ -14,14 +14,18 @@ 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 (
+ break_cycle, # noqa: F401 (import-for-side-effect)
extract_class, # noqa: F401 (import-for-side-effect)
extract_helper, # noqa: F401 (import-for-side-effect)
+ move_method, # noqa: F401 (import-for-side-effect)
)
+from .graph_signals import build_file_scc_index
from .models import (
CONFIDENCE_LEVELS,
RefactoringContext,
RefactoringSuggestion,
)
+from .rank import rank_suggestions
from .registry import (
RefactoringDetector,
detect_refactorings,
@@ -35,8 +39,10 @@ __all__ = [
"RefactoringContext",
"RefactoringDetector",
"RefactoringSuggestion",
+ "build_file_scc_index",
"detect_refactorings",
"effort_bucket",
+ "rank_suggestions",
"register",
"registered_detectors",
]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py b/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py
new file mode 100644
index 000000000..b7b0199cc
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py
@@ -0,0 +1,168 @@
+"""Break Cycle detector — name the import edge to cut.
+
+A strongly-connected component of the file dependency graph is a circular
+import: a set of files that mutually (transitively) depend on each other, so
+none can be understood, tested, or moved in isolation. The fix is to break
+the cycle by inverting or abstracting a minimal set of edges. This detector
+names that minimal set — it does *not* invent the abstraction (that is left
+to a human or an opt-in code-gen step); it answers the hard part
+deterministically: *which* edge to cut.
+
+The cycle is not a heuristic: it is a strongly-connected component the graph
+already encodes (computed once by the engine and threaded in as
+``ctx.file_scc``). The minimal cut is the feedback arc set — NP-hard exactly,
+so we use the classic greedy feedback-arc-set heuristic: order the nodes to
+minimise backward edges, then the backward edges are the arcs to remove. It
+is deterministic (sorted tie-breaks) and near-optimal on the small, dense
+components real import cycles form.
+
+A cycle spans files, so — like Extract Helper — the suggestion is emitted
+only from the **canonical anchor** (the lexicographically smallest member),
+so one cycle yields one suggestion, not one per file.
+"""
+
+from __future__ import annotations
+
+from .graph_signals import cycle_edges
+from .models import RefactoringContext, RefactoringSuggestion
+from .registry import RefactoringDetector, register
+
+# Break Cycle answers "which edge to cut" — that only stays actionable when
+# the cut is small and the cycle surveyable. A sprawling barrel-import tangle
+# (a package whose __init__ re-exports dozens of submodules that import the
+# package back) yields a huge SCC with a hundred-edge cut: real, but not a
+# "name the edge" suggestion. Those are dropped here (a coarser package-layout
+# finding, out of scope) so the surface only carries surgical, trustworthy cuts.
+_MAX_CYCLE_FILES = 20
+_MAX_CUT_EDGES = 4
+
+
+def _greedy_mfas(members: tuple[str, ...], edges: list[tuple[str, str]]) -> list[tuple[str, str]]:
+ """Approximate the minimum feedback arc set with the greedy ordering heuristic.
+
+ Returns the backward edges of a greedy linear ordering — a small set whose
+ removal makes the component acyclic. Deterministic: every choice breaks
+ ties on sorted node order, so the same cycle always yields the same cut.
+ """
+ nodes = list(members)
+ adj_out: dict[str, set[str]] = {n: set() for n in nodes}
+ adj_in: dict[str, set[str]] = {n: set() for n in nodes}
+ node_set = set(nodes)
+ for u, v in edges:
+ if u in node_set and v in node_set and u != v:
+ adj_out[u].add(v)
+ adj_in[v].add(u)
+
+ remaining = set(nodes)
+ s1: list[str] = [] # sources side (front of the ordering)
+ s2: list[str] = [] # sinks side (back of the ordering)
+
+ def _out_deg(n: str) -> int:
+ return len(adj_out[n] & remaining)
+
+ def _in_deg(n: str) -> int:
+ return len(adj_in[n] & remaining)
+
+ while remaining:
+ progressed = True
+ while progressed:
+ progressed = False
+ for n in sorted(remaining):
+ if _out_deg(n) == 0: # sink → prepend to s2
+ s2.insert(0, n)
+ remaining.discard(n)
+ progressed = True
+ for n in sorted(remaining):
+ if n in remaining and _in_deg(n) == 0: # source → append to s1
+ s1.append(n)
+ remaining.discard(n)
+ progressed = True
+ if remaining:
+ # Pick the node most "source-like" (out-degree minus in-degree);
+ # lexicographic tie-break keeps the ordering deterministic.
+ best = max(sorted(remaining), key=lambda n: _out_deg(n) - _in_deg(n))
+ s1.append(best)
+ remaining.discard(best)
+
+ ordering = s1 + s2
+ pos = {n: i for i, n in enumerate(ordering)}
+ # Backward edges (target earlier than source in the ordering) are the cut.
+ # Both endpoints are always in ``pos`` (the ordering covers every member and
+ # ``edges`` is restricted to member-member edges) — the explicit membership
+ # check keeps a malformed edge from silently yielding an incomplete cut.
+ cut = [(u, v) for (u, v) in edges if u in pos and v in pos and pos[u] > pos[v]]
+ return sorted(set(cut))
+
+
+def _basename(path: str) -> str:
+ return path.replace("\\", "/").rsplit("/", 1)[-1]
+
+
+@register
+class BreakCycleDetector(RefactoringDetector):
+ name = "break_cycle"
+
+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
+ members = ctx.file_scc
+ if not members or len(members) < 2:
+ return []
+ # Surgical cuts only: a giant barrel-import tangle is not a "name the
+ # edge" refactoring (see module note).
+ if len(members) > _MAX_CYCLE_FILES:
+ return []
+ # Canonical anchor: emit each cycle exactly once, from its smallest
+ # member path (members is sorted by the engine's SCC index).
+ if ctx.file_path != members[0]:
+ return []
+ if ctx.graph is None:
+ return []
+
+ edges = cycle_edges(ctx.graph, members)
+ if not edges:
+ return []
+ cut = _greedy_mfas(members, edges)
+ if not cut or len(cut) > _MAX_CUT_EDGES:
+ return []
+
+ size = len(members)
+ plan = {
+ "cycle": list(members),
+ "cut_edges": [{"from": u, "to": v} for u, v in cut],
+ }
+ evidence = {
+ "cycle_size": size,
+ "edge_count": len(edges),
+ "cut_count": len(cut),
+ }
+ blast_radius = {"files": list(members), "file_count": size}
+ # A short cut on a small cycle is the cleanest, highest-confidence
+ # break; a sprawling component with many back-edges is murkier.
+ confidence = "high" if len(cut) == 1 and size <= 4 else "medium"
+ cut_label = ", ".join(f"{_basename(u)}->{_basename(v)}" for u, v in cut)
+ return [
+ RefactoringSuggestion(
+ refactoring_type=self.name,
+ file_path=ctx.file_path,
+ target_symbol=f"cycle[{size}]: {cut_label}",
+ line_start=None,
+ line_end=None,
+ plan=plan,
+ evidence=evidence,
+ impact_delta=0.0,
+ effort_bucket=_cycle_effort(size),
+ blast_radius=blast_radius,
+ confidence=confidence,
+ source_biomarker="",
+ )
+ ]
+
+
+def _cycle_effort(size: int) -> str:
+ """Effort scales with how many files the break touches."""
+ if size <= 2:
+ return "S"
+ if size <= 4:
+ return "M"
+ if size <= 8:
+ return "L"
+ return "XL"
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
new file mode 100644
index 000000000..64e9e83cb
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -0,0 +1,79 @@
+"""Repo-level graph signals shared by the graph-native detectors.
+
+Move Method and Break Cycle reason over the symbol/file graph rather than a
+single file, but the detector contract is per-file. To keep that contract
+intact — and avoid each detector re-deriving global structure on every file —
+the health engine precomputes the few repo-wide signals here ONCE before the
+per-file pass and threads the per-file slice into ``RefactoringContext``.
+
+All functions are pure and deterministic: the same graph yields the same
+output, with stable (sorted) ordering, and degrade to empty on a missing
+graph rather than raising.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+# File->file edge types that constitute a structural dependency cycle.
+# ``imports`` is the actionable, invertible edge; the others are carried so a
+# cycle that closes through a framework/type edge is still reported. Today the
+# only file-level edge type the graph emits is ``imports`` (the rest are
+# symbol-level), so this closely tracks ``GraphBuilder.file_subgraph`` (which
+# drops only git ``co_changes``) and the persisted ``graph_node_membership``
+# rows; the two could drift only if a new file-level edge type is added to one
+# definition but not the other.
+_CYCLE_EDGE_TYPES = ("imports", "framework", "dynamic", "type_use", "extends", "implements")
+
+
+def build_file_scc_index(graph: Any) -> dict[str, tuple[str, ...]]:
+ """Map each file in a non-trivial dependency cycle to its sorted members.
+
+ Returns ``{file_path: (member, ...)}`` covering only files that sit in a
+ strongly-connected component of size >= 2 (a real cycle). Files with no
+ cycle — the overwhelming majority — are absent. The member tuple is
+ sorted, so the canonical anchor (``members[0]``) is deterministic.
+ """
+ if graph is None:
+ return {}
+ try:
+ import networkx as nx
+ except Exception:
+ return {}
+
+ fg: nx.DiGraph = nx.DiGraph()
+ for node, data in graph.nodes(data=True):
+ if data.get("node_type", "file") in ("file", "external"):
+ fg.add_node(node)
+ for u, v, data in graph.edges(data=True):
+ if u == v:
+ continue
+ if data.get("edge_type") in _CYCLE_EDGE_TYPES and u in fg and v in fg:
+ fg.add_edge(u, v)
+
+ out: dict[str, tuple[str, ...]] = {}
+ for scc in nx.strongly_connected_components(fg):
+ if len(scc) < 2:
+ continue
+ members = tuple(sorted(scc))
+ for node in scc:
+ out[node] = members
+ return out
+
+
+def cycle_edges(graph: Any, members: tuple[str, ...]) -> list[tuple[str, str]]:
+ """Return the directed dependency edges *within* a cycle's member set.
+
+ Deterministic (sorted). Self-loops and edges leaving the cycle are
+ excluded — only the edges that keep the cycle strongly connected.
+ """
+ if graph is None:
+ return []
+ member_set = set(members)
+ edges: list[tuple[str, str]] = []
+ for u, v, data in graph.edges(data=True):
+ if u == v or u not in member_set or v not in member_set:
+ continue
+ if data.get("edge_type") in _CYCLE_EDGE_TYPES:
+ edges.append((u, v))
+ return sorted(set(edges))
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 aa11b743c..b536796e1 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -10,7 +10,7 @@ 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):
+type without touching this module. For Extract Class:
- ``plan`` = ``{"groups": [{"name": None, "methods": [...], "fields": [...]}]}``
— one group per cohesive cluster the class should split into.
@@ -19,7 +19,7 @@ type without touching this module. For Extract Class (Phase 1):
- ``blast_radius`` = ``{"dependents_count": int}`` — files importing the
class's file that may need to follow the split.
-For Extract Helper (Phase 2):
+For Extract Helper:
- ``plan`` = ``{"occurrences": [{"file": str, "line_start": int,
"line_end": int}, ...], "suggested_site": {"module": str | None,
@@ -30,6 +30,26 @@ For Extract Helper (Phase 2):
size + activity signals that justify extracting a helper.
- ``blast_radius`` = ``{"files": [...], "file_count": int,
"co_change_count": int}`` — the other files that must change in lockstep.
+
+For Move Method:
+
+- ``plan`` = ``{"method": str, "from_class": str, "to_class": str,
+ "to_file": str | None}`` — the feature-envy method and where it belongs.
+- ``evidence`` = ``{"foreign_calls": int, "own_calls": int,
+ "own_distance": float, "target_distance": float}`` — the Jaccard distances
+ and call counts that prove the method is closer to ``to_class`` than its own.
+- ``blast_radius`` = ``{"callers": int, "files": [...]}`` — who calls the
+ method (they keep working, but the move touches both classes' files).
+
+For Break Cycle:
+
+- ``plan`` = ``{"cycle": [str, ...], "cut_edges": [{"from": str, "to": str},
+ ...]}`` — the files in the import cycle and the minimal set of import edges
+ to invert/abstract to break it (greedy MFAS).
+- ``evidence`` = ``{"cycle_size": int, "edge_count": int,
+ "cut_count": int}`` — the SCC size, total intra-cycle edges, and cut size.
+- ``blast_radius`` = ``{"files": [...], "file_count": int}`` — every file in
+ the cycle (breaking it is a multi-file change).
"""
from __future__ import annotations
@@ -38,7 +58,7 @@ 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).
+# layers may filter on a ``min_confidence`` config (default: medium).
CONFIDENCE_LEVELS = ("low", "medium", "high")
@@ -76,6 +96,17 @@ class RefactoringContext:
# Empty on small repos that produced no community labels — the detector
# then falls back to a shared-directory site.
module_map: dict[str, str] = field(default_factory=dict)
+ # The repo's symbol/file graph (a ``networkx.DiGraph``, typed ``Any`` to
+ # avoid importing networkx into the model layer). A shared read-only
+ # reference — the graph-native detectors (Move Method, Break Cycle) read
+ # call / has_method / imports edges off it. ``None`` when the health pass
+ # ran without a graph; those detectors then degrade to "no suggestion".
+ graph: Any = None
+ # This file's strongly-connected component (sorted member file paths) when
+ # it sits in a real import cycle (``size >= 2``); ``None`` otherwise. The
+ # 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
@dataclass
@@ -84,7 +115,7 @@ class RefactoringSuggestion:
``RefactoringSuggestion`` ORM row; rendered to text only at the edges.
"""
- refactoring_type: str # "extract_class" (Phase 1); more in later phases
+ refactoring_type: str # "extract_class", "extract_helper", "move_method", ...
file_path: str
target_symbol: str # the class / method / site the refactoring acts on
line_start: int | None
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
new file mode 100644
index 000000000..8c487dc3d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
@@ -0,0 +1,301 @@
+"""Move Method detector — Feature Envy as a graph query.
+
+A method suffers *feature envy* when it is more interested in another class
+than the one it lives in: it calls into a foreign class's members far more
+than its own. The fix is to move it next to the data it actually uses — a
+cross-file architectural refactoring that falls straight out of the call
+graph the health pass already built.
+
+Detection (Jaccard-distance feature envy over the call graph):
+
+- A method ``m`` in class ``C`` accesses a set of class-owned members (its
+ callees that belong to some class, resolved via the ``calls`` graph).
+- For ``C`` and every foreign class ``T`` that ``m`` touches, the Jaccard
+ distance ``1 - |accessed AND members(T)| / |accessed OR members(T)|``
+ measures how close ``m`` is to that class.
+- If a foreign class ``T`` is *strictly nearer* than ``m``'s own class — and
+ ``m`` barely uses its own class while leaning on ``T`` — ``m`` belongs in
+ ``T``.
+
+Feature envy is notoriously noisy, so the gate is deliberately strict
+(high-precision, low-recall): the method must access at least
+``_MIN_FOREIGN_MEMBERS`` distinct members of the target, more of the target
+than of its own class, and almost nothing of its own class. We only ever
+consider classes ``m`` already calls into, so the target is always a class
+the method can legally reach. Dunder / framework hook methods are skipped —
+moving ``__init__`` or ``__eq__`` is never the intent.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from .models import RefactoringContext, RefactoringSuggestion
+from .registry import RefactoringDetector, effort_bucket, register
+
+# Distinct foreign members the method must access for the envy to be real
+# (a single shared call is incidental, not envy).
+_MIN_FOREIGN_MEMBERS = 2
+
+# The method may touch at most this many distinct members of its OWN class —
+# above this it still has a real reason to live where it is.
+_MAX_OWN_MEMBERS = 1
+
+# The method must be genuinely close to the target class, not merely closer
+# than its (empty) own class: calling 2 methods of a 100-member god class
+# (Jaccard distance ~0.98) is not envy, it is normal collaboration. A real
+# move target shares a meaningful fraction of its members with the method.
+_MAX_TARGET_DISTANCE = 0.7
+
+# The target must be clearly nearer than the own class by this margin, so a
+# near-tie (the method is about as related to both) never fires.
+_MIN_DISTANCE_MARGIN = 0.25
+
+
+def _is_test_path(path: str) -> bool:
+ """Conservative test-file check (segment-aware).
+
+ A test method that exercises the class under test calls into it heavily —
+ that reads as feature envy but is never a move target, so test files are
+ excluded on both ends (the method's file and the proposed destination).
+ Catches both a ``test/`` / ``tests/`` directory anywhere in the path
+ (including the first segment, e.g. Django's ``tests/app/tests.py``) and
+ the usual per-file naming conventions."""
+ p = path.lower().replace("\\", "/")
+ segments = p.split("/")
+ if any(seg in ("test", "tests", "__tests__") for seg in segments[:-1]):
+ return True
+ base = segments[-1]
+ return (
+ base in ("tests.py", "test.py", "conftest.py")
+ or base.startswith("test_")
+ or base.endswith(
+ (
+ "_test.py",
+ "_test.go",
+ ".test.ts",
+ ".test.tsx",
+ ".test.js",
+ ".spec.ts",
+ ".spec.js",
+ )
+ )
+ )
+
+
+def _node(graph: Any, node_id: str) -> dict | None:
+ if node_id not in graph:
+ return None
+ return graph.nodes[node_id]
+
+
+def _owning_class_id(graph: Any, callee_id: str) -> str | None:
+ """The class node a callee belongs to: the method's parent class, or the
+ class itself for a constructor call. ``None`` for free functions and
+ unresolved callees (they carry no class membership)."""
+ data = _node(graph, callee_id)
+ if data is None:
+ return None
+ kind = data.get("kind")
+ if kind == "method":
+ parent = data.get("parent_name")
+ file_path = data.get("file_path")
+ if parent and file_path:
+ class_id = f"{file_path}::{parent}"
+ return class_id if class_id in graph else None
+ return None
+ if kind == "class":
+ return callee_id
+ return None
+
+
+@register
+class MoveMethodDetector(RefactoringDetector):
+ name = "move_method"
+
+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
+ graph = ctx.graph
+ if graph is None or _is_test_path(ctx.file_path):
+ return []
+
+ methods = self._methods_in_file(graph, ctx.file_path)
+ if not methods:
+ return []
+
+ members_cache: dict[str, set[str]] = {}
+ out: list[RefactoringSuggestion] = []
+ for method_id in methods:
+ suggestion = self._envy_for(ctx, graph, method_id, members_cache)
+ if suggestion is not None:
+ out.append(suggestion)
+
+ # Deterministic: impact is 0 for this graph-native type, so order by
+ # the strength of the envy (foreign members accessed), then symbol.
+ out.sort(key=lambda s: (-int(s.evidence.get("foreign_calls", 0)), s.target_symbol))
+ return out
+
+ def _methods_in_file(self, graph: Any, file_path: str) -> list[str]:
+ """Symbol ids of methods defined in *file_path*, via ``defines`` edges
+ (falling back to a prefix scan), sorted for determinism."""
+ out: list[str] = []
+ if file_path in graph:
+ for _u, v, data in graph.out_edges(file_path, data=True):
+ if data.get("edge_type") != "defines":
+ continue
+ node = _node(graph, v)
+ if node and node.get("kind") == "method":
+ out.append(v)
+ if not out:
+ prefix = f"{file_path}::"
+ for node_id, data in graph.nodes(data=True):
+ if (
+ data.get("node_type") == "symbol"
+ and data.get("kind") == "method"
+ and node_id.startswith(prefix)
+ ):
+ out.append(node_id)
+ return sorted(set(out))
+
+ def _class_members(self, graph: Any, class_id: str, cache: dict[str, set[str]]) -> set[str]:
+ cached = cache.get(class_id)
+ if cached is not None:
+ return cached
+ members: set[str] = set()
+ if class_id in graph:
+ for _u, v, data in graph.out_edges(class_id, data=True):
+ if data.get("edge_type") == "has_method":
+ members.add(v)
+ cache[class_id] = members
+ return members
+
+ def _envy_for(
+ self,
+ ctx: RefactoringContext,
+ graph: Any,
+ method_id: str,
+ members_cache: dict[str, set[str]],
+ ) -> RefactoringSuggestion | None:
+ data = _node(graph, method_id)
+ if data is None:
+ return None
+ name = data.get("name") or ""
+ if name.startswith("__"): # dunder / hook methods don't move
+ return None
+ parent = data.get("parent_name")
+ if not parent:
+ return None
+ own_class_id = f"{ctx.file_path}::{parent}"
+ if own_class_id not in graph:
+ return None
+
+ # Group the method's class-owned callees by the class they belong to.
+ accessed_by_class: dict[str, set[str]] = {}
+ for _u, callee, edata in graph.out_edges(method_id, data=True):
+ if edata.get("edge_type") != "calls" or callee == method_id:
+ continue
+ owner = _owning_class_id(graph, callee)
+ if owner is None:
+ continue
+ accessed_by_class.setdefault(owner, set()).add(callee)
+
+ accessed: set[str] = set()
+ for members in accessed_by_class.values():
+ accessed |= members
+ if not accessed:
+ return None
+
+ own_accessed = accessed_by_class.get(own_class_id, set())
+ own_distinct = len(own_accessed)
+ if own_distinct > _MAX_OWN_MEMBERS:
+ return None
+
+ # Nearest foreign class by Jaccard distance (tie-break on class id).
+ foreign = [(c, m) for c, m in accessed_by_class.items() if c != own_class_id]
+ if not foreign:
+ return None
+ own_distance = self._distance(graph, own_class_id, accessed, members_cache)
+
+ def _dist(item: tuple[str, set[str]]) -> tuple[float, str]:
+ return (self._distance(graph, item[0], accessed, members_cache), item[0])
+
+ target_id, target_accessed = min(foreign, key=_dist)
+ target_distance = self._distance(graph, target_id, accessed, members_cache)
+ foreign_distinct = len(target_accessed)
+
+ if foreign_distinct < _MIN_FOREIGN_MEMBERS:
+ return None
+ if foreign_distinct <= own_distinct:
+ return None
+ if target_distance > _MAX_TARGET_DISTANCE:
+ return None
+ if own_distance - target_distance < _MIN_DISTANCE_MARGIN:
+ return None
+
+ target_node = _node(graph, target_id) or {}
+ target_class = target_node.get("name") or target_id.rsplit("::", 1)[-1]
+ target_file = target_node.get("file_path")
+ if target_file and _is_test_path(target_file):
+ return None # never propose moving production code into a test class
+
+ callers = self._caller_count(graph, method_id)
+ plan = {
+ "method": name,
+ "from_class": parent,
+ "to_class": target_class,
+ "to_file": target_file,
+ }
+ evidence = {
+ "foreign_calls": foreign_distinct,
+ "own_calls": own_distinct,
+ "own_distance": round(own_distance, 3),
+ "target_distance": round(target_distance, 3),
+ }
+ blast_radius = {
+ "callers": callers,
+ "files": sorted({ctx.file_path, target_file} - {None}),
+ }
+ nloc = self._method_nloc(data)
+ confidence = "high" if own_distinct == 0 and foreign_distinct >= 3 else "medium"
+ return RefactoringSuggestion(
+ refactoring_type=self.name,
+ file_path=ctx.file_path,
+ target_symbol=f"{parent}.{name}",
+ line_start=data.get("start_line"),
+ line_end=data.get("end_line"),
+ plan=plan,
+ evidence=evidence,
+ impact_delta=0.0,
+ effort_bucket=effort_bucket(nloc),
+ blast_radius=blast_radius,
+ confidence=confidence,
+ source_biomarker="",
+ )
+
+ def _distance(
+ self, graph: Any, class_id: str, accessed: set[str], cache: dict[str, set[str]]
+ ) -> float:
+ """Jaccard distance between the method's accessed-entity set and a
+ class's members. 0 = the method only touches this class; 1 = no
+ overlap. Empty union degrades to max distance."""
+ members = self._class_members(graph, class_id, cache)
+ union = accessed | members
+ if not union:
+ return 1.0
+ return 1.0 - len(accessed & members) / len(union)
+
+ @staticmethod
+ def _caller_count(graph: Any, method_id: str) -> int:
+ count = 0
+ if method_id in graph:
+ for _u, _v, data in graph.in_edges(method_id, data=True):
+ if data.get("edge_type") == "calls":
+ count += 1
+ return count
+
+ @staticmethod
+ def _method_nloc(data: dict) -> int:
+ start = data.get("start_line")
+ end = data.get("end_line")
+ if isinstance(start, int) and isinstance(end, int) and end >= start:
+ return end - start + 1
+ return 0
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/rank.py b/packages/core/src/repowise/core/analysis/health/refactoring/rank.py
new file mode 100644
index 000000000..68adfe9a0
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/rank.py
@@ -0,0 +1,96 @@
+"""Unified ranking across every refactoring detector.
+
+Each detector sorts its own output deterministically, but the surfaces (CLI,
+MCP, web) present a single mixed list — so the *global* order is what the user
+actually sees. This module imposes one ranking over all types so the top of
+the list is always the most valuable refactoring regardless of kind, instead
+of a churn-only or impact-only sort that buries cross-file wins.
+
+The key blends three orthogonal signals as a product of ``(1 + signal)``
+factors (so a zero in any one dimension shapes the order without annihilating
+the suggestion):
+
+- **recovered impact** — the health the refactoring buys back (0 for the
+ graph-native types that answer no biomarker);
+- **target centrality** — how depended-upon the file is, so a refactoring on a
+ hub file outranks the same refactoring on a leaf;
+- **blast radius** — how much else moves, as a mild amplifier (a wide, real
+ refactoring is worth surfacing) rather than a penalty;
+- **confidence** — a final weight so a high-confidence plan edges out a
+ borderline one at the same score.
+
+Because impact-free types still rank via centrality and blast, Move Method and
+Break Cycle interleave fairly with Extract Class / Extract Helper rather than
+sinking below every impact-bearing suggestion.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping, Sequence
+
+from .models import RefactoringSuggestion
+
+_CONFIDENCE_WEIGHT = {"high": 1.25, "medium": 1.0, "low": 0.75}
+
+
+def _blast_size(s: RefactoringSuggestion) -> int:
+ """A single 'how much else moves' integer, read from whichever blast-radius
+ shape this refactoring type carries."""
+ br = s.blast_radius or {}
+ for key in ("file_count", "dependents_count", "callers"):
+ value = br.get(key)
+ if isinstance(value, (int, float)) and value:
+ return int(value)
+ files = br.get("files")
+ return len(files) if isinstance(files, list) else 0
+
+
+def _enrich_blast_radius(s: RefactoringSuggestion, centrality: Mapping[str, float]) -> None:
+ """Give every plan a caller/dependents rollup so the 'what else moves'
+ signal is uniform across types. Extract Helper carries only its
+ co-occurrence files; here we add the importing-file count summed over the
+ occurrences (the callers that ride along), which the ranking then reads."""
+ br = dict(s.blast_radius or {})
+ if "callers" not in br and "dependents_count" not in br:
+ files = br.get("files")
+ if isinstance(files, list) and files:
+ br["callers"] = sum(int(centrality.get(f, 0)) for f in files)
+ s.blast_radius = br
+
+
+def score(s: RefactoringSuggestion, centrality: Mapping[str, float]) -> float:
+ """The unified rank score (higher = surface sooner)."""
+ impact_factor = 1.0 + max(0.0, float(s.impact_delta or 0.0))
+ cen = float(centrality.get(s.file_path, 0.0))
+ centrality_factor = 1.0 + math.log1p(max(0.0, cen))
+ blast_factor = 1.0 + math.log1p(_blast_size(s))
+ confidence_weight = _CONFIDENCE_WEIGHT.get(s.confidence, 1.0)
+ return impact_factor * centrality_factor * blast_factor * confidence_weight
+
+
+def rank_suggestions(
+ suggestions: Sequence[RefactoringSuggestion],
+ *,
+ centrality: Mapping[str, float] | None = None,
+) -> list[RefactoringSuggestion]:
+ """Return *suggestions* in unified-rank order (a new list).
+
+ *centrality* maps a file path to its dependency centrality (the importer
+ count / in-degree is a good cheap proxy); missing files score 0. Ties break
+ on type, file, then target so the order is fully deterministic. Also
+ enriches each suggestion's blast radius in place so the persisted/rendered
+ plan carries the same caller rollup the ranking used.
+ """
+ cen = centrality or {}
+ for s in suggestions:
+ _enrich_blast_radius(s, cen)
+ return sorted(
+ suggestions,
+ key=lambda s: (
+ -score(s, cen),
+ s.refactoring_type,
+ s.file_path,
+ s.target_symbol,
+ ),
+ )
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index 747e4a458..b01d805a9 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -40,9 +40,7 @@ class MetricsMixin:
values without recomputing them via NetworkX.
"""
self._pagerank_cache = {n: float(m.get("pagerank", 0.0)) for n, m in metrics.items()}
- self._betweenness_cache = {
- n: float(m.get("betweenness", 0.0)) for n, m in metrics.items()
- }
+ self._betweenness_cache = {n: float(m.get("betweenness", 0.0)) for n, m in metrics.items()}
self._community_cache = {n: int(m.get("community_id", 0)) for n, m in metrics.items()}
self._in_degree_cache = {n: int(m.get("in_degree", 0)) for n, m in metrics.items()}
self._out_degree_cache = {n: int(m.get("out_degree", 0)) for n, m in metrics.items()}
@@ -98,9 +96,7 @@ class MetricsMixin:
]
sub = g.subgraph(file_nodes).copy()
edges_to_remove = [
- (u, v)
- for u, v, d in sub.edges(data=True)
- if d.get("edge_type") in ("co_changes",)
+ (u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)
]
sub.remove_edges_from(edges_to_remove)
self._file_subgraph_cache = sub
@@ -385,3 +381,51 @@ class MetricsMixin:
for node in scc:
result[node] = scc_id
return result
+
+ def node_membership_snapshot(self) -> dict[str, dict[str, Any]]:
+ """Materialize SCC + symbol-community memberships as a ``node_id → {...}`` map.
+
+ Two structural facts the graph carries but never persisted as rows:
+
+ - **File-level SCCs** (import cycles). Only non-trivial components
+ (``size >= 2``) are emitted — a singleton is not a cycle — each with
+ a stable ``scc_id`` and the cycle ``scc_size``.
+ - **Symbol communities** (call/heritage clusters). Only communities of
+ ``size >= 2`` are emitted (a lone symbol is not a community).
+
+ Read back by the web layer (and the break-cycle / move-method
+ detectors' downstream queries) without rebuilding the NetworkX graph.
+ Computed from the cached metric kernels, so calling it is cheap once
+ the graph is built.
+ """
+ out: dict[str, dict[str, Any]] = {}
+
+ for scc_id, scc in enumerate(nx.strongly_connected_components(self.file_subgraph())):
+ if len(scc) < 2:
+ continue
+ for node in scc:
+ out[node] = {
+ "node_type": "file",
+ "scc_id": scc_id,
+ "scc_size": len(scc),
+ "symbol_community_id": None,
+ }
+
+ sym_communities = self.symbol_communities()
+ community_sizes: dict[int, int] = {}
+ for cid in sym_communities.values():
+ community_sizes[cid] = community_sizes.get(cid, 0) + 1
+ for node, cid in sym_communities.items():
+ if community_sizes.get(cid, 0) < 2:
+ continue
+ entry = out.get(node)
+ if entry is None:
+ out[node] = {
+ "node_type": "symbol",
+ "scc_id": None,
+ "scc_size": 0,
+ "symbol_community_id": int(cid),
+ }
+ else:
+ entry["symbol_community_id"] = int(cid)
+ return out
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 8fcd9e5e8..428ce6abf 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -19,6 +19,7 @@ from repowise.core.providers.embedding.base import Embedder, MockEmbedder
from .crud import (
batch_upsert_graph_edges,
batch_upsert_graph_metrics,
+ batch_upsert_graph_node_membership,
batch_upsert_graph_nodes,
batch_upsert_symbols,
bulk_upsert_decisions,
@@ -56,6 +57,7 @@ from .crud import (
get_page_versions,
get_repository,
get_repository_by_path,
+ get_scc_members,
get_stale_decisions,
get_stale_pages,
get_top_entry_points,
@@ -127,6 +129,7 @@ from .models import (
GraphEdge,
GraphMetric,
GraphNode,
+ GraphNodeMembership,
KnowledgeGraphLayer,
KnowledgeGraphNodeMeta,
KnowledgeGraphProjectMeta,
@@ -169,6 +172,7 @@ __all__ = [
"GraphEdge",
"GraphMetric",
"GraphNode",
+ "GraphNodeMembership",
# vector store
"InMemoryVectorStore",
# knowledge graph
@@ -190,6 +194,7 @@ __all__ = [
# crud
"batch_upsert_graph_edges",
"batch_upsert_graph_metrics",
+ "batch_upsert_graph_node_membership",
"batch_upsert_graph_nodes",
"batch_upsert_symbols",
# decision graph (edges + node links + lineage)
@@ -244,6 +249,7 @@ __all__ = [
"get_repo_db_path",
"get_repository",
"get_repository_by_path",
+ "get_scc_members",
"get_session",
"get_stale_decisions",
"get_stale_pages",
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index 3ded527e9..79e4c47cb 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -15,6 +15,7 @@ from ..models import (
GraphEdge,
GraphMetric,
GraphNode,
+ GraphNodeMembership,
_new_uuid,
)
from ._shared import _BATCH_SIZE, _batch_upsert_keyed
@@ -47,6 +48,15 @@ def _update_graph_metric(existing: GraphMetric, m: dict) -> None:
setattr(existing, key, m[key])
+_MEMBERSHIP_FIELDS = ("node_type", "scc_id", "scc_size", "symbol_community_id")
+
+
+def _update_graph_node_membership(existing: GraphNodeMembership, m: dict) -> None:
+ for key in _MEMBERSHIP_FIELDS:
+ if key in m:
+ setattr(existing, key, m[key])
+
+
async def batch_upsert_graph_nodes(
session: AsyncSession,
repository_id: str,
@@ -146,6 +156,65 @@ async def batch_upsert_graph_metrics(
)
+async def batch_upsert_graph_node_membership(
+ session: AsyncSession,
+ repository_id: str,
+ membership: dict[str, dict],
+) -> None:
+ """Materialize the SCC + symbol-community snapshot into ``graph_node_membership``.
+
+ *membership* maps ``node_id`` → a dict with ``node_type`` and any of
+ ``scc_id`` / ``scc_size`` (file nodes in a size>=2 cycle) /
+ ``symbol_community_id`` (symbol nodes). Additive to ``graph_nodes``;
+ SELECT-then-write for dialect portability (SQLite + Postgres).
+ """
+ await _batch_upsert_keyed(
+ session,
+ GraphNodeMembership,
+ list(membership.items()),
+ prefilter=(GraphNodeMembership.repository_id == repository_id,),
+ item_key_fn=lambda kv: kv[0],
+ row_key_fn=lambda row: row.node_id,
+ update_fn=lambda existing, kv: _update_graph_node_membership(existing, kv[1]),
+ insert_fn=lambda kv: GraphNodeMembership(
+ id=_new_uuid(),
+ repository_id=repository_id,
+ node_id=kv[0],
+ node_type=str(kv[1].get("node_type", "file")),
+ scc_id=(None if kv[1].get("scc_id") is None else int(kv[1]["scc_id"])),
+ scc_size=int(kv[1].get("scc_size", 0)),
+ symbol_community_id=(
+ None
+ if kv[1].get("symbol_community_id") is None
+ else int(kv[1]["symbol_community_id"])
+ ),
+ ),
+ )
+
+
+async def get_scc_members(
+ session: AsyncSession,
+ repository_id: str,
+) -> dict[int, list[str]]:
+ """Read the persisted file-level cycles as ``scc_id → [node_id, ...]``.
+
+ Only non-trivial SCCs (``scc_size >= 2``) are materialized, so every
+ returned group is a real import cycle.
+ """
+ result = await session.execute(
+ select(GraphNodeMembership).where(
+ GraphNodeMembership.repository_id == repository_id,
+ GraphNodeMembership.scc_id.isnot(None),
+ )
+ )
+ out: dict[int, list[str]] = {}
+ for row in result.scalars().all():
+ out.setdefault(int(row.scc_id), []).append(row.node_id)
+ for members in out.values():
+ members.sort()
+ return out
+
+
async def get_graph_metrics(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 7329d78bd..91cbcd301 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -279,6 +279,39 @@ class GraphMetric(Base):
__table_args__ = (UniqueConstraint("repository_id", "node_id", name="uq_graph_metric"),)
+class GraphNodeMembership(Base):
+ """Materialized component memberships — SCCs and symbol communities.
+
+ Persists two structural facts the graph carries but never exposed as
+ queryable rows: file-level strongly-connected components (import cycles,
+ ``scc_id`` / ``scc_size`` with ``scc_size >= 2``) and symbol-level
+ communities (``symbol_community_id``). The break-cycle and move-method
+ refactoring detectors compute the same structure from the in-memory graph
+ at health time; this snapshot lets the web layer read cycles and
+ communities without rebuilding the graph. Additive to ``graph_nodes`` /
+ ``graph_metrics``; non-load-bearing.
+ """
+
+ __tablename__ = "graph_node_membership"
+
+ 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, index=True
+ )
+ node_id: Mapped[str] = mapped_column(Text, nullable=False)
+ node_type: Mapped[str] = mapped_column(String(16), nullable=False, default="file")
+ scc_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ scc_size: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ symbol_community_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+
+ __table_args__ = (
+ UniqueConstraint("repository_id", "node_id", name="uq_graph_node_membership"),
+ )
+
+
class WebhookEvent(Base):
__tablename__ = "webhook_events"
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index c6b51b913..6599cbe88 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -119,6 +119,7 @@ async def persist_graph_nodes(
"""
from repowise.core.persistence import (
batch_upsert_graph_metrics,
+ batch_upsert_graph_node_membership,
batch_upsert_graph_nodes,
)
@@ -203,6 +204,16 @@ async def persist_graph_nodes(
except Exception as exc: # materialization is non-load-bearing
logger.warning("graph_metrics_materialize_skipped", error=str(exc))
+ # Materialize file-level SCCs (import cycles) + symbol communities as
+ # queryable rows (graph_node_membership). Feeds the break-cycle /
+ # move-method refactoring surfaces; non-load-bearing like graph_metrics.
+ try:
+ await batch_upsert_graph_node_membership(
+ session, repo_id, graph_builder.node_membership_snapshot()
+ )
+ except Exception as exc: # materialization is non-load-bearing
+ logger.warning("graph_node_membership_materialize_skipped", error=str(exc))
+
# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit.
_PRUNE_CHUNK = 500
diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.py
new file mode 100644
index 000000000..8bac7ebaa
--- /dev/null
+++ b/tests/unit/cli/test_refactoring_targets_render.py
@@ -0,0 +1,68 @@
+"""The `health --refactoring-targets` surface renders every plan type.
+
+Locks the JSON + Markdown rendering of the Move Method and Break Cycle plans
+(the graph-native types) so a future detector edit can't silently drop them
+from the CLI, and confirms the plan order is the engine's unified rank
+(preserved, not re-sorted).
+"""
+
+from __future__ import annotations
+
+import json
+
+from repowise.cli.commands.health_cmd import _render_refactoring_targets
+from repowise.core.analysis.health.refactoring import RefactoringSuggestion
+
+
+def _move_method() -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="move_method",
+ file_path="c.py",
+ target_symbol="C.envious",
+ line_start=10,
+ line_end=30,
+ plan={"method": "envious", "from_class": "C", "to_class": "T", "to_file": "t.py"},
+ evidence={"foreign_calls": 3, "own_calls": 0, "own_distance": 1.0, "target_distance": 0.0},
+ impact_delta=0.0,
+ effort_bucket="M",
+ blast_radius={"callers": 2, "files": ["c.py", "t.py"]},
+ confidence="high",
+ )
+
+
+def _break_cycle() -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="break_cycle",
+ file_path="a.py",
+ target_symbol="cycle[2]: b.py->a.py",
+ line_start=None,
+ line_end=None,
+ plan={"cycle": ["a.py", "b.py"], "cut_edges": [{"from": "b.py", "to": "a.py"}]},
+ evidence={"cycle_size": 2, "edge_count": 2, "cut_count": 1},
+ impact_delta=0.0,
+ effort_bucket="S",
+ blast_radius={"files": ["a.py", "b.py"], "file_count": 2},
+ confidence="high",
+ )
+
+
+def test_json_includes_move_and_break_plans(capsys):
+ suggestions = [_move_method(), _break_cycle()]
+ _render_refactoring_targets([], [], suggestions, fmt="json")
+ out = json.loads(capsys.readouterr().out)
+ types = {p["refactoring_type"] for p in out["refactoring_plans"]}
+ assert {"move_method", "break_cycle"} <= types
+ # Order is preserved from the (already unified-ranked) input.
+ assert [p["refactoring_type"] for p in out["refactoring_plans"]] == [
+ "move_method",
+ "break_cycle",
+ ]
+
+
+def test_markdown_renders_both_sections(capsys):
+ _render_refactoring_targets([], [], [_move_method(), _break_cycle()], fmt="md")
+ text = capsys.readouterr().out
+ assert "## Move Method plans" in text
+ assert "C.envious" in text and "`T (t.py)`" in text
+ assert "## Break Cycle plans" in text
+ assert "invert b.py -> a.py" in text
diff --git a/tests/unit/health/test_refactoring_break_cycle.py b/tests/unit/health/test_refactoring_break_cycle.py
new file mode 100644
index 000000000..d7b2c27a7
--- /dev/null
+++ b/tests/unit/health/test_refactoring_break_cycle.py
@@ -0,0 +1,137 @@
+"""Tests for the Break Cycle refactoring detector + the SCC graph signal.
+
+The detector consumes the per-file SCC slice the engine precomputes
+(``RefactoringContext.file_scc``) plus the in-memory graph, runs a greedy
+feedback-arc-set cut, and names the import edge(s) to invert. Fixtures build
+small import graphs so the cycle and its minimal cut are explicit.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.health.refactoring import (
+ RefactoringContext,
+ build_file_scc_index,
+ detect_refactorings,
+)
+from repowise.core.analysis.health.refactoring.break_cycle import (
+ BreakCycleDetector,
+ _greedy_mfas,
+)
+
+
+def _import_graph(edges: list[tuple[str, str]]) -> nx.DiGraph:
+ g = nx.DiGraph()
+ files = {f for e in edges for f in e}
+ for f in files:
+ g.add_node(f, node_type="file")
+ for u, v in edges:
+ g.add_edge(u, v, edge_type="imports")
+ return g
+
+
+def _detect(g: nx.DiGraph, file_path: str) -> list:
+ idx = build_file_scc_index(g)
+ ctx = RefactoringContext(
+ file_path=file_path,
+ language="python",
+ nloc=50,
+ graph=g,
+ file_scc=idx.get(file_path),
+ )
+ return [s for s in detect_refactorings(ctx) if s.refactoring_type == "break_cycle"]
+
+
+def test_two_file_cycle_cuts_one_edge():
+ g = _import_graph([("a.py", "b.py"), ("b.py", "a.py")])
+ out = _detect(g, "a.py")
+ assert len(out) == 1
+ s = out[0]
+ assert s.evidence == {"cycle_size": 2, "edge_count": 2, "cut_count": 1}
+ assert s.plan["cut_edges"] == [{"from": "b.py", "to": "a.py"}]
+ assert s.plan["cycle"] == ["a.py", "b.py"]
+ assert s.confidence == "high"
+ assert s.blast_radius == {"files": ["a.py", "b.py"], "file_count": 2}
+
+
+def test_emitted_only_from_canonical_anchor():
+ g = _import_graph([("a.py", "b.py"), ("b.py", "a.py")])
+ assert _detect(g, "b.py") == [] # b.py is not the smallest member
+
+
+def test_no_cycle_yields_nothing():
+ g = _import_graph([("a.py", "b.py"), ("b.py", "c.py")])
+ assert build_file_scc_index(g) == {}
+ assert _detect(g, "a.py") == []
+
+
+def test_three_file_cycle_is_one_suggestion():
+ g = _import_graph([("a.py", "b.py"), ("b.py", "c.py"), ("c.py", "a.py")])
+ out = _detect(g, "a.py")
+ assert len(out) == 1
+ s = out[0]
+ assert s.evidence["cycle_size"] == 3
+ assert s.evidence["cut_count"] >= 1
+ # The cut makes the cycle acyclic.
+ members = ("a.py", "b.py", "c.py")
+ cut = {(e["from"], e["to"]) for e in s.plan["cut_edges"]}
+ remaining = nx.DiGraph()
+ remaining.add_nodes_from(members)
+ for u, v in [("a.py", "b.py"), ("b.py", "c.py"), ("c.py", "a.py")]:
+ if (u, v) not in cut:
+ remaining.add_edge(u, v)
+ assert nx.is_directed_acyclic_graph(remaining)
+
+
+def test_greedy_mfas_is_deterministic_and_minimal():
+ members = ("a", "b", "c")
+ edges = [("a", "b"), ("b", "c"), ("c", "a")]
+ cut1 = _greedy_mfas(members, edges)
+ cut2 = _greedy_mfas(members, edges)
+ assert cut1 == cut2
+ assert len(cut1) == 1 # a single back edge breaks a simple 3-cycle
+
+
+def test_no_graph_yields_nothing():
+ ctx = RefactoringContext(
+ file_path="a.py",
+ language="python",
+ nloc=50,
+ graph=None,
+ file_scc=("a.py", "b.py"),
+ )
+ assert BreakCycleDetector().detect(ctx) == []
+
+
+def test_huge_barrel_cycle_is_dropped():
+ # A package __init__ that re-exports many submodules which import it back
+ # forms a giant SCC with a large cut — not a "name the edge" refactoring.
+ edges = [(f"m{i}.py", "pkg/__init__.py") for i in range(25)]
+ edges += [("pkg/__init__.py", f"m{i}.py") for i in range(25)]
+ g = _import_graph(edges)
+ # The cycle exists...
+ assert any(len(m) > 20 for m in build_file_scc_index(g).values())
+ # ...but no surgical suggestion is emitted for an oversized tangle.
+ anchor = sorted(f for e in edges for f in e)[0]
+ assert _detect(g, anchor) == []
+
+
+def test_large_cut_is_dropped():
+ # A small cycle whose minimal cut still exceeds the cut cap is not surfaced.
+ # A 6-node bidirectional clique needs many back-edges to break.
+ files = [f"f{i}.py" for i in range(6)]
+ edges = [(a, b) for a in files for b in files if a != b]
+ g = _import_graph(edges)
+ out = _detect(g, "f0.py")
+ assert out == []
+
+
+def test_co_change_edges_do_not_form_a_cycle():
+ # Only a co_changes edge between the pair → not a structural cycle.
+ g = nx.DiGraph()
+ g.add_node("a.py", node_type="file")
+ g.add_node("b.py", node_type="file")
+ g.add_edge("a.py", "b.py", edge_type="imports")
+ g.add_edge("b.py", "a.py", edge_type="co_changes")
+ assert build_file_scc_index(g) == {}
diff --git a/tests/unit/health/test_refactoring_move_method.py b/tests/unit/health/test_refactoring_move_method.py
new file mode 100644
index 000000000..b502fa0b5
--- /dev/null
+++ b/tests/unit/health/test_refactoring_move_method.py
@@ -0,0 +1,183 @@
+"""Tests for the Move Method refactoring detector (feature envy).
+
+The detector reads the method/class membership and ``calls`` edges off the
+in-memory graph (surfaced on ``RefactoringContext.graph``) and suggests
+moving a method to the class it actually uses. Fixtures build a tiny NetworkX
+graph directly so the entity sets — which class owns which member, who calls
+whom — are explicit and the expected suggestion is unambiguous.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.health.refactoring import (
+ RefactoringContext,
+ detect_refactorings,
+)
+from repowise.core.analysis.health.refactoring.move_method import MoveMethodDetector
+
+
+def _add_class(g: nx.DiGraph, file_path: str, cls: str, methods: list[str]) -> None:
+ if file_path not in g:
+ g.add_node(file_path, node_type="file")
+ class_id = f"{file_path}::{cls}"
+ g.add_node(class_id, node_type="symbol", kind="class", name=cls, file_path=file_path)
+ for m in methods:
+ mid = f"{file_path}::{cls}.{m}"
+ g.add_node(
+ mid,
+ node_type="symbol",
+ kind="method",
+ name=m,
+ parent_name=cls,
+ file_path=file_path,
+ start_line=1,
+ end_line=20,
+ )
+ g.add_edge(class_id, mid, edge_type="has_method")
+ g.add_edge(file_path, mid, edge_type="defines")
+
+
+def _call(g: nx.DiGraph, src: str, dst: str) -> None:
+ g.add_edge(src, dst, edge_type="calls")
+
+
+def _ctx(g: nx.DiGraph, file_path: str) -> RefactoringContext:
+ return RefactoringContext(file_path=file_path, language="python", nloc=40, graph=g)
+
+
+def _detect(g: nx.DiGraph, file_path: str) -> list:
+ return [
+ s for s in detect_refactorings(_ctx(g, file_path)) if s.refactoring_type == "move_method"
+ ]
+
+
+def _envy_graph() -> nx.DiGraph:
+ """C.envious calls 3 of T's members and 0 of its own — textbook envy."""
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["envious", "helper"])
+ _add_class(g, "t.py", "T", ["alpha", "beta", "gamma"])
+ for m in ("alpha", "beta", "gamma"):
+ _call(g, "c.py::C.envious", f"t.py::T.{m}")
+ return g
+
+
+def test_feature_envy_suggests_move_to_target_class():
+ out = _detect(_envy_graph(), "c.py")
+ assert len(out) == 1
+ s = out[0]
+ assert s.refactoring_type == "move_method"
+ assert s.target_symbol == "C.envious"
+ assert s.plan == {
+ "method": "envious",
+ "from_class": "C",
+ "to_class": "T",
+ "to_file": "t.py",
+ }
+ assert s.evidence["foreign_calls"] == 3
+ assert s.evidence["own_calls"] == 0
+ assert s.evidence["target_distance"] < s.evidence["own_distance"]
+ assert s.confidence == "high"
+
+
+def test_method_that_uses_its_own_class_is_not_envious():
+ g = _envy_graph()
+ # envious now also calls 2 of its own class's members → no longer clearly
+ # foreign-leaning (own_calls above the max-own gate).
+ _add_class(g, "c.py", "C", ["envious", "helper", "h2"])
+ _call(g, "c.py::C.envious", "c.py::C.helper")
+ _call(g, "c.py::C.envious", "c.py::C.h2")
+ assert _detect(g, "c.py") == []
+
+
+def test_single_foreign_call_below_threshold_is_ignored():
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["m"])
+ _add_class(g, "t.py", "T", ["alpha", "beta"])
+ _call(g, "c.py::C.m", "t.py::T.alpha") # only one foreign member
+ assert _detect(g, "c.py") == []
+
+
+def test_dunder_methods_never_move():
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["__init__"])
+ _add_class(g, "t.py", "T", ["alpha", "beta", "gamma"])
+ for m in ("alpha", "beta", "gamma"):
+ _call(g, "c.py::C.__init__", f"t.py::T.{m}")
+ assert _detect(g, "c.py") == []
+
+
+def test_nearest_of_two_foreign_classes_wins():
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["m"])
+ _add_class(g, "t.py", "T", ["a", "b", "c"])
+ _add_class(g, "u.py", "U", ["x", "y", "z", "w", "v"])
+ # m touches all 3 of T (small class → distance 0) but only 2 of U's 5.
+ for member in ("a", "b", "c"):
+ _call(g, "c.py::C.m", f"t.py::T.{member}")
+ for member in ("x", "y"):
+ _call(g, "c.py::C.m", f"u.py::U.{member}")
+ out = _detect(g, "c.py")
+ assert len(out) == 1
+ assert out[0].plan["to_class"] == "T"
+
+
+def test_no_graph_yields_no_suggestions():
+ ctx = RefactoringContext(file_path="c.py", language="python", nloc=40, graph=None)
+ assert MoveMethodDetector().detect(ctx) == []
+
+
+def test_calling_two_methods_of_a_huge_class_is_not_envy():
+ # A method that touches 2 members of a 40-member god class is far from it
+ # (Jaccard distance ~0.95) — normal collaboration, not envy.
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["m"])
+ _add_class(g, "big.py", "Big", [f"meth{i}" for i in range(40)])
+ _call(g, "c.py::C.m", "big.py::Big.meth0")
+ _call(g, "c.py::C.m", "big.py::Big.meth1")
+ assert _detect(g, "c.py") == []
+
+
+def test_method_in_test_file_is_skipped():
+ # A test method exercising the class under test is not a move candidate.
+ g = nx.DiGraph()
+ _add_class(g, "tests/test_thing.py", "ThingTest", ["test_it"])
+ _add_class(g, "t.py", "T", ["alpha", "beta", "gamma"])
+ for m in ("alpha", "beta", "gamma"):
+ _call(g, "tests/test_thing.py::ThingTest.test_it", f"t.py::T.{m}")
+ assert _detect(g, "tests/test_thing.py") == []
+
+
+def test_target_in_test_file_is_rejected():
+ # Never propose moving production code into a test class.
+ g = nx.DiGraph()
+ _add_class(g, "c.py", "C", ["m"])
+ _add_class(g, "tests/test_t.py", "T", ["alpha", "beta", "gamma"])
+ for m in ("alpha", "beta", "gamma"):
+ _call(g, "c.py::C.m", f"tests/test_t.py::T.{m}")
+ assert _detect(g, "c.py") == []
+
+
+def test_deterministic_and_stable_order():
+ g = _envy_graph()
+ # A second envious method in the same file → two suggestions, stable order.
+ _add_class(g, "c.py", "C", ["envious", "envious2", "helper"])
+ g.add_node(
+ "c.py::C.envious2",
+ node_type="symbol",
+ kind="method",
+ name="envious2",
+ parent_name="C",
+ file_path="c.py",
+ start_line=1,
+ end_line=20,
+ )
+ g.add_edge("c.py::C", "c.py::C.envious2", edge_type="has_method")
+ g.add_edge("c.py", "c.py::C.envious2", edge_type="defines")
+ for m in ("alpha", "beta", "gamma"):
+ _call(g, "c.py::C.envious2", f"t.py::T.{m}")
+ first = [s.target_symbol for s in _detect(g, "c.py")]
+ second = [s.target_symbol for s in _detect(g, "c.py")]
+ assert first == second
+ assert len(first) == 2
diff --git a/tests/unit/health/test_refactoring_rank.py b/tests/unit/health/test_refactoring_rank.py
new file mode 100644
index 000000000..4dd06d237
--- /dev/null
+++ b/tests/unit/health/test_refactoring_rank.py
@@ -0,0 +1,87 @@
+"""Tests for the unified cross-detector ranking (rank.py).
+
+One ranking is imposed over every refactoring type so the surfaces show the
+most valuable suggestion first regardless of kind. The key blends recovered
+impact, target centrality, and blast radius, weighted by confidence.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.refactoring import rank_suggestions
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.rank import score
+
+
+def _sugg(
+ rtype: str,
+ file_path: str,
+ target: str,
+ *,
+ impact: float = 0.0,
+ confidence: str = "medium",
+ blast: dict | None = None,
+) -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type=rtype,
+ file_path=file_path,
+ target_symbol=target,
+ line_start=None,
+ line_end=None,
+ plan={},
+ evidence={},
+ impact_delta=impact,
+ effort_bucket="M",
+ blast_radius=blast or {},
+ confidence=confidence,
+ )
+
+
+def test_higher_impact_ranks_first():
+ low = _sugg("extract_class", "a.py", "A", impact=1.0)
+ high = _sugg("extract_class", "b.py", "B", impact=5.0)
+ ranked = rank_suggestions([low, high])
+ assert [s.target_symbol for s in ranked] == ["B", "A"]
+
+
+def test_centrality_breaks_an_impact_tie():
+ leaf = _sugg("extract_class", "leaf.py", "Leaf", impact=2.0)
+ hub = _sugg("extract_class", "hub.py", "Hub", impact=2.0)
+ ranked = rank_suggestions([leaf, hub], centrality={"hub.py": 50, "leaf.py": 0})
+ assert [s.target_symbol for s in ranked] == ["Hub", "Leaf"]
+
+
+def test_graph_native_zero_impact_still_ranks_via_centrality():
+ # A move_method on a very central file outranks a tiny-impact extract on a leaf.
+ move = _sugg("move_method", "hub.py", "Hub.m", impact=0.0, blast={"callers": 20})
+ tiny = _sugg("extract_class", "leaf.py", "Leaf", impact=0.05)
+ ranked = rank_suggestions([tiny, move], centrality={"hub.py": 80, "leaf.py": 0})
+ assert ranked[0].target_symbol == "Hub.m"
+
+
+def test_blast_radius_enrichment_adds_callers():
+ s = _sugg("extract_helper", "a.py", "a.py:1-10", blast={"files": ["b.py", "c.py"]})
+ rank_suggestions([s], centrality={"b.py": 3, "c.py": 4})
+ assert s.blast_radius["callers"] == 7 # 3 + 4 importers ride along
+
+
+def test_confidence_weights_a_tie():
+ med = _sugg("extract_class", "a.py", "A", impact=2.0, confidence="medium")
+ high = _sugg("extract_class", "a.py", "B", impact=2.0, confidence="high")
+ ranked = rank_suggestions([med, high], centrality={"a.py": 5})
+ assert [s.target_symbol for s in ranked] == ["B", "A"]
+
+
+def test_ordering_is_deterministic():
+ items = [
+ _sugg("extract_class", "a.py", "A", impact=1.0),
+ _sugg("move_method", "a.py", "A.m", blast={"callers": 2}),
+ _sugg("break_cycle", "a.py", "cycle", blast={"file_count": 3}),
+ ]
+ first = [s.target_symbol for s in rank_suggestions(items)]
+ second = [s.target_symbol for s in rank_suggestions(list(reversed(items)))]
+ assert first == second
+
+
+def test_score_is_positive_even_with_all_zero_signals():
+ s = _sugg("break_cycle", "a.py", "cycle")
+ assert score(s, {}) > 0
diff --git a/tests/unit/ingestion/test_graph_node_membership.py b/tests/unit/ingestion/test_graph_node_membership.py
new file mode 100644
index 000000000..63b0fa1f8
--- /dev/null
+++ b/tests/unit/ingestion/test_graph_node_membership.py
@@ -0,0 +1,79 @@
+"""SCC + symbol-community membership snapshot (graph_node_membership).
+
+Proves ``node_membership_snapshot`` materializes file-level import cycles
+(strongly-connected components of size >= 2) as rows the refactoring / web
+layers can read without rebuilding the graph, and that acyclic files are
+absent.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo, Import, ParsedFile
+
+
+def _fi(path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="python",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _imp(module_path: str) -> Import:
+ return Import(
+ raw_statement=f"import {module_path}",
+ module_path=module_path,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+
+
+def _parsed(path: str, imports: list[Import] | None = None) -> ParsedFile:
+ return ParsedFile(
+ file_info=_fi(path),
+ symbols=[],
+ imports=imports or [],
+ exports=[],
+ docstring=None,
+ parse_errors=[],
+ content_hash="",
+ )
+
+
+def test_cycle_files_are_materialized_as_scc_rows():
+ b = GraphBuilder()
+ # a <-> b mutual import (a 2-file cycle); c is acyclic.
+ b.add_file(_parsed("a.py", [_imp("b")]))
+ b.add_file(_parsed("b.py", [_imp("a")]))
+ b.add_file(_parsed("c.py", [_imp("a")]))
+ b.build()
+
+ snap = b.node_membership_snapshot()
+
+ assert "a.py" in snap and "b.py" in snap
+ assert snap["a.py"]["scc_size"] == 2
+ assert snap["b.py"]["scc_size"] == 2
+ assert snap["a.py"]["scc_id"] == snap["b.py"]["scc_id"]
+ assert snap["a.py"]["node_type"] == "file"
+ # c.py is not in a cycle → no SCC row.
+ assert "c.py" not in snap or snap["c.py"].get("scc_id") is None
+
+
+def test_acyclic_graph_has_no_scc_rows():
+ b = GraphBuilder()
+ b.add_file(_parsed("a.py", [_imp("b")]))
+ b.add_file(_parsed("b.py"))
+ b.build()
+ snap = b.node_membership_snapshot()
+ assert all(v.get("scc_id") is None for v in snap.values())
diff --git a/tests/unit/persistence/test_graph_node_membership_crud.py b/tests/unit/persistence/test_graph_node_membership_crud.py
new file mode 100644
index 000000000..b7630071b
--- /dev/null
+++ b/tests/unit/persistence/test_graph_node_membership_crud.py
@@ -0,0 +1,54 @@
+"""graph_node_membership survives the persistence round trip.
+
+Locks the materializer ``batch_upsert_graph_node_membership`` and the
+``get_scc_members`` reader so the SCC + symbol-community snapshot stays
+queryable.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.crud.graph import (
+ batch_upsert_graph_node_membership,
+ get_scc_members,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def test_membership_round_trip_and_scc_read(async_session):
+ repo = await insert_repo(async_session)
+ membership = {
+ "a.py": {"node_type": "file", "scc_id": 0, "scc_size": 2, "symbol_community_id": None},
+ "b.py": {"node_type": "file", "scc_id": 0, "scc_size": 2, "symbol_community_id": None},
+ "m.py::C.x": {
+ "node_type": "symbol",
+ "scc_id": None,
+ "scc_size": 0,
+ "symbol_community_id": 7,
+ },
+ }
+ await batch_upsert_graph_node_membership(async_session, repo.id, membership)
+ await async_session.commit()
+
+ sccs = await get_scc_members(async_session, repo.id)
+ assert sccs == {0: ["a.py", "b.py"]}
+
+
+async def test_membership_upsert_is_idempotent(async_session):
+ repo = await insert_repo(async_session)
+ membership = {
+ "a.py": {"node_type": "file", "scc_id": 1, "scc_size": 2, "symbol_community_id": None},
+ "b.py": {"node_type": "file", "scc_id": 1, "scc_size": 2, "symbol_community_id": None},
+ }
+ await batch_upsert_graph_node_membership(async_session, repo.id, membership)
+ await async_session.commit()
+ # Re-running updates in place (no duplicate rows).
+ membership["a.py"]["scc_size"] = 3
+ await batch_upsert_graph_node_membership(async_session, repo.id, membership)
+ await async_session.commit()
+
+ sccs = await get_scc_members(async_session, repo.id)
+ assert sccs == {1: ["a.py", "b.py"]}
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 3d97140b8..f80d368c1 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -320,6 +320,7 @@ def test_base_includes_all_models():
"coverage_files",
"pipeline_jobs",
"graph_metrics",
+ "graph_node_membership",
"knowledge_graph_layers",
"knowledge_graph_tour_steps",
"kg_project_meta",