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(health): stop counting field-less cohesion groups in explicit-receiver classes (#3552)
Raghav Chamadiya694478b13c23
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.mdindex 24186e89c..931885369 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md@@ -98,6 +98,9 @@ edge between two methods when they (a) reference a common instance fieldor (b) one calls the other (a call surfaces as a reference to the callee'sname). `lcom4` is the number of connected components: `1` is fullycohesive; `≥ 2` means the class splinters into unrelated method groups.+Only components that touch instance state count: a component that reads no+field (a static helper, a stateless hook override) is listed but not+counted, since it is a method to move, not a class to extract.Consumed by `low_cohesion` and `god_class`.### Heuristic limits (read before trusting a number)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 2ebd99c85..991b2da39 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@@ -607,7 +607,11 @@ def _compute_lcom4(names field declarations (implicit receivers), overloads are one node andonly ``_stateful_groups`` count toward LCOM4; a map that sets``cohesion_counts_state_only`` gets the same count without the implicit- references.+ references. Otherwise every access is a visible ``self.x``, so a+ component touching one field is a real cluster, but one touching none is+ a static helper or a hook override (a Move Method or a function, never a+ class to extract): it stays in ``components``, where ``move_method``+ reads the inherited members it calls, and does not count."""if not method_nodes:return 1, 0, [], 1.0@@ -633,7 +637,8 @@ def _compute_lcom4(if implicit or lmap.cohesion_counts_state_only:groups = _stateful_groups(indexed, refs.contracts)return max(len(groups), 1), field_count, groups, tcc- return len(indexed), field_count, [g for _, g in indexed], tcc+ components = [g for _, g in indexed]+ return max(sum(1 for g in components if g.fields), 1), field_count, components, tccdef _collect_classes(diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex 8f68cdf52..443dfea14 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -196,8 +196,11 @@ class ClassComplexity:``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.+ valve). Implicit-receiver languages keep only the components that count,+ so ``len(components) == lcom4``; explicit-receiver languages keep every+ component and ``lcom4`` counts those that touch a field (see+ ``_compute_lcom4``). The Extract Class refactoring detector reads it+ directly: it *is* the split."""name: strdiff --git a/tests/fixtures/lang_samples/python/classes.py b/tests/fixtures/lang_samples/python/classes.pyindex dc64041cf..6f44328a9 100644--- a/tests/fixtures/lang_samples/python/classes.py+++ b/tests/fixtures/lang_samples/python/classes.py@@ -24,10 +24,10 @@ class Cohesive:class Splintered:- """Two disjoint method clusters plus a loner → LCOM4 == 3.+ """Two disjoint method clusters plus a loner → LCOM4 == 2.{set_a, get_a} share self.a; {set_b, get_b} share self.b; loner- touches neither. Fields are class-level so no constructor bridges the+ touches neither, so it is a component that does not count. Fields are class-level so no constructor bridges theclusters."""diff --git a/tests/fixtures/lang_samples/typescript/classes.ts b/tests/fixtures/lang_samples/typescript/classes.tsindex b0928909e..7dd1fdeb9 100644--- a/tests/fixtures/lang_samples/typescript/classes.ts+++ b/tests/fixtures/lang_samples/typescript/classes.ts@@ -24,7 +24,7 @@ class Cohesive {}// Fields are declared (not assigned in a constructor) so no single-// method bridges the two clusters → LCOM4 == 3.+// method bridges the two clusters → LCOM4 == 2 (the field-less loner does not count).class Splintered {a = 0;b = 0;diff --git a/tests/unit/health/test_class_biomarkers.py b/tests/unit/health/test_class_biomarkers.pyindex f56c20550..bf8cdf591 100644--- a/tests/unit/health/test_class_biomarkers.py+++ b/tests/unit/health/test_class_biomarkers.py@@ -114,6 +114,91 @@ def test_low_cohesion_skips_overloaded_formatter_class():assert LowCohesionDetector().detect(_ctx([fmt])) == []+def _walk_one(path: str, language: str, source: str, name: str) -> ClassComplexity:+ from repowise.core.ingestion.parser import _get_language++ if _get_language(language) is None:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ fc = walk_file(path, language, source.encode())+ return next(c for c in fc.classes if c.name == name)+++_STATELESS_DIALECT = """+class Dialect(BaseDialect):+ literal_kinds = frozenset({"string"})++ def is_literal(self, node):+ return node.type in self.literal_kinds++ def sink_kind(self, name):+ return "query" if name == "execute" else None++ def loop_header(self, node):+ return node.child_by_field_name("condition")++ def param_names(self, fn):+ return self.enclosing_params(fn)++ def is_async_fn(self, fn):+ return fn.type == "async_function"++ def bindings_of(self, node):+ return [c for c in node.children if c.is_named]+"""+++def test_low_cohesion_skips_stateless_hook_overrides():+ # Each hook touches no instance state: a static helper, not a class to extract.+ cls = _walk_one("dialect.py", "python", _STATELESS_DIALECT, "Dialect")+ assert cls.method_count == 6 and cls.lcom4 == 1+ assert LowCohesionDetector().detect(_ctx([cls])) == []+ # Every component stays listed, so move_method still sees the inherited call.+ assert len(cls.components) == 6+ assert any(g.calls == ("enclosing_params",) for g in cls.components)+++def test_low_cohesion_still_counts_field_clusters_beside_stateless_helpers():+ source = """+class Report:+ def add_page(self, page):+ self.pages.append(page)++ def page_count(self):+ return len(self.pages)++ def add_tokens(self, n):+ self.tokens += n++ def cost(self):+ return self.tokens * 0.01++ def label(self, kind):+ return kind.title()++ def describe(self):+ return "report"+"""+ cls = _walk_one("report.py", "python", source, "Report")+ assert cls.lcom4 == 2 # the pages pair and the tokens pair, one field each+ [finding] = LowCohesionDetector().detect(_ctx([cls]))+ assert finding.details["lcom4"] == 2+++def test_low_cohesion_skips_stateless_typescript_strategy():+ source = """+class Strategy extends Base {+ kinds = new Set(["string"]);+ isLiteral(n) { return this.kinds.has(n.type); }+ sinkKind(name) { return name === "execute" ? "query" : null; }+ loopHeader(n) { return n.childForFieldName("condition"); }+ isAsync(fn) { return fn.type === "async_function"; }+ bindings(n) { return n.namedChildren; }+}+"""+ cls = _walk_one("strategy.ts", "typescript", source, "Strategy")+ assert cls.method_count == 5 and cls.lcom4 == 1++# ---- god_class -----------------------------------------------------------diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex 65797d2a3..1291b6209 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -374,8 +374,10 @@ def test_python_class_cohesion():assert cohesive is not None and splintered is not None# All methods collaborate around shared state → single component.assert cohesive.lcom4 == 1- # Two disjoint field clusters + a loner → three components.- assert splintered.lcom4 == 3+ # Two disjoint field clusters; the loner touches no field, so it is a+ # component but not a group to extract.+ assert splintered.lcom4 == 2+ assert len(splintered.components) == 3assert splintered.method_count == 5assert splintered.field_count == 2@@ -446,7 +448,7 @@ def test_typescript_class_cohesion():if cohesive is None or splintered is None:pytest.skip("typescript classes not detected")assert cohesive.lcom4 == 1- assert splintered.lcom4 == 3+ assert splintered.lcom4 == 2def test_class_metrics_carry_methods_and_size():@@ -792,7 +794,7 @@ def test_scala_class_cohesion():splintered = classes.get("Splintered")assert cohesive is not None and splintered is not Noneassert cohesive.lcom4 == 1- assert splintered.lcom4 == 3+ assert splintered.lcom4 == 2assert splintered.method_count == 5assert splintered.field_count == 2# ``object`` and ``trait`` bodies group methods like a class body.diff --git a/tests/unit/health/test_implicit_member_cohesion.py b/tests/unit/health/test_implicit_member_cohesion.pyindex 40166a2b7..4fba6046d 100644--- a/tests/unit/health/test_implicit_member_cohesion.py+++ b/tests/unit/health/test_implicit_member_cohesion.py@@ -193,7 +193,7 @@ class C:return self.a"""c = _classes("python", source, "c.py")["C"]- assert c.lcom4 == 2+ assert c.lcom4 == 1 # ``bare`` touches no field: not a group to extractassert [set(g.methods) for g in c.components] == [{"__init__", "own"}, {"bare"}]