Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(refactoring): stop move_method targeting result types and base classes (#2572)
Raghav Chamadiyad053fa12c8a2
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 7691bfb99..e768e67e3 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -34,7 +34,7 @@ one**, and produces stable-sorted, deterministic output.|------|---------------|---------------------------|| **Extract Class** | The cohesion groups an incohesive / god class should split into: the exact methods + fields per group. | LCOM4 union-find components (each disconnected component is a candidate class), with the god-class shape confirmed via Lanza-Marinescu (WMC = Σ McCabe, TCC). || **Extract Helper** | A clone's exact occurrences and where the shared helper belongs. | Rabin–Karp clone pairs (line ranges, token count, co-change). The extraction site is the community centroid of the involved files; transitive clones (A↔B, B↔C) are clustered into one suggestion, not pairwise nags. |-| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. |+| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own and draws more of the method's calls than its home file does. A class the method instantiates (a result it builds) and an ancestor of its own class are never targets. || **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. || **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. || **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify, and IN/OUT comes from liveness over the def/use facts. A span is offered only when the gate can prove it behavior-preserving: every returned value must be written on every path through the span, and a span nested in a loop must carry no state between iterations and must not mutate what the loop iterates. What the gate cannot prove is suppressed, not demoted, so the layer under-reports rather than suggest a rewrite that changes behavior. |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.pyindex f3d84460e..b35b4061f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py@@ -24,6 +24,22 @@ than of its own class, and almost nothing of its own class. We only everconsider classes ``m`` already calls into, so the target is always a classthe method can legally reach. Dunder / framework hook methods are skipped —moving ``__init__`` or ``__eq__`` is never the intent.++Two kinds of class are never a target, because touching their members is not+envy:++- a class the method **instantiates**. A method that builds a result object+ and fills it in (``result = WriteResult(); result.record(...)``) is that+ object's producer; moving it onto the result type turns a record into the+ place the work happens. Envy is operating on an instance someone else owns.+- an **ancestor** of the method's own class (``extends`` / ``implements``).+ Calling an inherited method is calling your own member; the base class is+ not somewhere else to move to.++And the target must draw more of the method's calls than its home file does.+The Jaccard sets see only class-owned callees, so a method whose work is three+module-level helpers plus ``result.record`` / ``result.note`` on a collector it+was handed looked like it envied the collector."""from __future__ import annotations@@ -75,6 +91,18 @@ def _file_is_test(graph: Any, path: str) -> bool:return is_test_related_path(path)+def _ancestors(graph: Any, class_id: str) -> set[str]:+ """Every class *class_id* inherits from, transitively."""+ seen: set[str] = set()+ stack = [class_id]+ while stack:+ for _u, base, data in graph.out_edges(stack.pop(), data=True):+ if data.get("edge_type") in ("extends", "implements") and base not in seen:+ seen.add(base)+ stack.append(base)+ return seen++def _owning_class_id(graph: Any, callee_id: str) -> str | None:"""The class node a callee belongs to: the method's parent class, or theclass itself for a constructor call. ``None`` for free functions and@@ -179,12 +207,15 @@ class MoveMethodDetector(RefactoringDetector):# Group the method's class-owned callees by the class they belong to.accessed_by_class: dict[str, set[str]] = {}+ home: set[str] = set()for _u, callee, edata in graph.out_edges(method_id, data=True):if (not is_reliable_call_edge(edata.get("edge_type"), edata.get("resolution_origin"))or callee == method_id):continue+ if (_node(graph, callee) or {}).get("file_path") == ctx.file_path:+ home.add(callee)owner = _owning_class_id(graph, callee)if owner is None:continue@@ -202,7 +233,13 @@ class MoveMethodDetector(RefactoringDetector):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]+ # A constructor call lands the class id in its own member set.+ inherited = _ancestors(graph, own_class_id)+ foreign = [+ (c, m)+ for c, m in accessed_by_class.items()+ if c != own_class_id and c not in inherited and c not in m+ ]if not foreign:return Noneown_distance = self._distance(graph, own_class_id, accessed, members_cache)@@ -216,7 +253,8 @@ class MoveMethodDetector(RefactoringDetector):if foreign_distinct < _MIN_FOREIGN_MEMBERS:return None- if foreign_distinct <= own_distinct:+ # The own class lives in the home file, so this covers it too.+ if foreign_distinct <= len(home):return Noneif target_distance > _MAX_TARGET_DISTANCE:return Nonediff --git a/tests/unit/health/test_refactoring_move_method.py b/tests/unit/health/test_refactoring_move_method.pyindex c8143623c..c90cf14f6 100644--- a/tests/unit/health/test_refactoring_move_method.py+++ b/tests/unit/health/test_refactoring_move_method.py@@ -259,3 +259,28 @@ def test_detector_equal_with_and_without_provided_index():assert [(s.target_symbol, s.plan) for s in provided] == [(s.target_symbol, s.plan) for s in derived]+++def test_a_class_the_method_instantiates_is_not_a_move_target():+ # ``result = T(); result.alpha(); ...``: the method produces T, it does not+ # envy it. The constructor call is a ``calls`` edge onto the class node.+ g = _envy_graph()+ _call(g, "c.py::C.envious", "t.py::T")+ assert _detect(g, "c.py") == []+++def test_an_ancestor_of_the_own_class_is_not_a_move_target():+ g = _envy_graph()+ g.add_edge("c.py::C", "t.py::T", edge_type="extends")+ assert _detect(g, "c.py") == []+++def test_a_method_whose_work_is_in_its_home_file_does_not_envy():+ # Three module-level helpers in c.py outweigh three calls on T.+ g = _envy_graph()+ for fn in ("load", "write", "render"):+ g.add_node(f"c.py::{fn}", node_type="symbol", kind="function", name=fn, file_path="c.py")+ _call(g, "c.py::C.envious", f"c.py::{fn}")+ assert _detect(g, "c.py") == []+ g.remove_node("c.py::render")+ assert len(_detect(g, "c.py")) == 1