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 class-level cohesion and god-class detection (#302)

Raghav Chamadiyae33fe3c992e3
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 20b94b33b..5257d194e 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -1,8 +1,9 @@
# Code Health
-Repowise computes a 1–10 health score for every file in your repo from nineteen
+Repowise computes a 1–10 health score for every file in your repo from twenty-one
deterministic biomarkers — McCabe complexity, deep nesting, brain methods,
-clone detection, untested hotspots, function-level churn, code-age volatility,
+class cohesion (LCOM4), god classes, clone detection, untested hotspots,
+function-level churn, code-age volatility,
ownership dispersion, relative churn, change entropy, co-change scatter, and more. **No LLM calls, no cloud requirement.** Pure
Python over tree-sitter + git data, designed to finish in under 30 seconds on a
3 000-file repo.
@@ -27,12 +28,12 @@ most:
| Category | Cap | Biomarkers |
|------------------------|-------|------------|
| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter |
-| Structural complexity | −2.5 | brain_method, nested_complexity, bumpy_road, complex_conditional |
+| Structural complexity | −2.5 | brain_method, low_cohesion, god_class, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
-Nineteen biomarkers across five categories. `function_hotspot` and
+Twenty-one biomarkers across five categories. `function_hotspot` and
`code_age_volatility` are blame-based and sit in the organizational bucket —
both are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line
blame index is built.
@@ -57,7 +58,18 @@ The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:
**brain_method** — A single function that is simultaneously long, deeply
nested, highly complex, and central to the dependency graph. The strongest
-single signal of fragile code.
+single signal of fragile code. Centrality is judged against the repo's own
+dependency density (top-quintile of connected files, with an absolute
+hub bar), so it fires on sparse-graph languages too — not just Python.
+
+**low_cohesion** — A class whose methods split into groups that share no
+fields and don't call each other (LCOM4 ≥ 2). Measured by the walker's
+class-level model; a high value usually means several smaller,
+single-responsibility classes are hiding inside one.
+
+**god_class** — A large class (≥ 200 lines, ≥ 15 methods) that also
+contains a brain method. Size alone isn't flagged — the brain-method
+requirement keeps flat data holders and config tables from firing.
**nested_complexity** — Functions with control-flow nesting ≥ 4 levels.
Hard to read, hard to test, hard to refactor.
@@ -245,8 +257,9 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
| Feature | Repowise | CodeScene | DeepSource | Sourcery |
|----------------------------------|:--:|:--:|:--:|:--:|
-| Code health score (1–10) | ✅ 19 biomarkers | ✅ 25–30 | ❌ | ❌ |
+| Code health score (1–10) | ✅ 21 biomarkers | ✅ 25–30 | ❌ | ❌ |
| Brain Method detection | ✅ | ✅ | ❌ | ❌ |
+| Low cohesion (LCOM4) / god class | ✅ | ✅ | ❌ | ❌ |
| Test coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ | ❌ | ❌ |
| Untested hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ |
| DRY violation detection | ✅ native (no npm) | ✅ | ❌ | ❌ |
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index fdde75132..995488efc 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -304,7 +304,7 @@ they all derive their language sets from the registry automatically.
### Optional language-specific passes
-Three pluggable hooks let a language opt into deeper resolution
+Several pluggable hooks let a language opt into deeper resolution
without touching the shared pipeline files:
- `graph_warmups.py` --- register a one-time pre-import warmup (e.g.
@@ -341,6 +341,18 @@ without touching the shared pipeline files:
declared `"private": true`), and Go (`//go:build integration`-gated
files) — any language that already builds a workspace index can opt
in by stamping the attribute during its warmup.
+- `analysis/health/complexity/languages.py` --- the code-health
+ complexity walker keeps its own per-language node-type map
+ (`LanguageNodeMap`), independent of the ingestion `.scm` queries. Add a
+ map for a language to get McCabe complexity, nesting, cognitive
+ complexity, and the per-function biomarkers; optionally set
+ `class_kinds` / `self_identifiers` / `member_access_kinds` on that map
+ to also get class-level metrics (LCOM4 cohesion, god-class). Both tiers
+ are purely additive and degrade safely — an unmapped language simply
+ produces no health findings rather than wrong ones. Control-flow maps
+ ship for Python, TypeScript, JavaScript, Go, Java, Rust; class-level
+ maps for all of those except Go. See `complexity/README.md` for the
+ extension recipe and the LCOM4 heuristic's limits.
---
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 891433bf4..34f0e44a3 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -273,21 +273,25 @@ Single pass over the parsed file list. For each file:
# engine.py — pseudocode
1. _walk(pf):
source = read_bytes(pf.file_info.abs_path)
- walk_file_complexity(language, source) → list[FunctionComplexity]
+ walk_file(language, source) → FileComplexity(functions, classes)
# Each FunctionComplexity carries: name, line range, nloc, ccn,
# max_nesting, cognitive, bumps, param_count.
+ # Each ClassComplexity carries: name, line range, method_count,
+ # total_nloc, methods, lcom4, max_method_ccn, field_count.
-2. _populate_symbol_complexity(pf, fc_list):
+2. _populate_symbol_complexity(pf, fcx.functions):
# Side effect: write max(ccn) into Symbol.complexity_estimate so
# the ContextAssembler symbol ranker benefits even when callers
# don't query the health tables directly.
-3. _evaluate_file(pf, fc_list, ...):
+3. _evaluate_file(pf, fcx, ...):
# Build a FileContext with:
# - nloc, has_test_file, module
# - function_metrics: dict[symbol_name → FunctionComplexity]
+ # - class_metrics: list[ClassComplexity] (LCOM4 / god-class)
# - git_meta: per-file dict (hotspot, owners, bus factor, ...)
# - dependents_count: in_degree on the graph
+ # - repo_dependents_p80: repo-wide p80 of in-degree (brain_method floor)
# - line_coverage_pct, branch_coverage_pct, covered_lines (when ingested)
# - clones, duplication_pct (from cross-file detect_clones())
results = detect_all(ctx, disabled=file_disabled)
@@ -312,7 +316,7 @@ higher than dormant ones.
---
-## 5. The 19 biomarkers and their categories
+## 5. The 21 biomarkers and their categories
Each biomarker is a stateless class implementing the `Biomarker` Protocol
from `biomarkers/base.py`:
@@ -327,7 +331,7 @@ class Biomarker(Protocol):
| Category | Cap | Biomarkers |
|------------------------|------|------------|
| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter |
-| Structural complexity | −2.5 | brain_method, nested_complexity, bumpy_road, complex_conditional |
+| Structural complexity | −2.5 | brain_method, low_cohesion, god_class, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
@@ -342,6 +346,16 @@ co-change coupling, D'Ambros) are likewise git-only and read the
`co_change_partners_json`. `knowledge_loss` is activity-gated so
abandoned-but-stable files (the survivor effect) no longer fire.
+`low_cohesion` (LCOM4) and `god_class` are the two **class-level**
+structural smells. They read `ctx.class_metrics`, the per-class aggregates
+the walker now emits alongside per-function metrics (see §5.2).
+`brain_method`'s centrality gate is **language-agnostic**: instead of a
+fixed `dependents ≥ 8`, it fires when a file is in the repo's top quintile
+of connected files (`repo_dependents_p80`, computed once per analyze) or
+clears the absolute hub bar of 8 — so it no longer goes silent on
+sparse-graph languages (TS barrels, Rust) whose in-degrees are lower than
+Python's.
+
### 5.1 Change-entropy git-layer fields
`change_entropy` is computed during the **single** FULL-tier co-change walk
@@ -357,6 +371,20 @@ keep pct 0.0 so the biomarker stays silent). Both fields are persisted on
`git_metadata` (migration `0025`) and the additive-reconcile path back-fills
them on legacy DBs.
+### 5.2 Class-level walker metrics (LCOM4)
+
+The complexity walker emits a `ClassComplexity` per class-like node for
+languages that opt in (`LanguageNodeMap.class_kinds` non-empty: Python,
+TS/JS, Java, Rust `impl`; Go has no grouping node). LCOM4 is the number of
+connected components in the graph whose nodes are the class's methods and
+whose edges link methods that share an instance field or call one another.
+Member references are detected per-language via `self`/`this`/`$this`
+member-access nodes. **Safety valve:** a class with no detected member
+references (a static utility, or an unmapped language) reports `lcom4 = 1`
+("no signal") rather than `len(methods)`, so adding a language can only
+turn signal on — never produce a false-positive flood. See
+`complexity/README.md` for the full heuristic and its limits.
+
`biomarkers/registry.py` is an **explicit list**, not auto-discovery —
keeps the registration order deterministic and lets tests inject extras
via `registered_biomarkers(extra=...)`.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
index 16171565f..c9bc0bb8b 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -9,10 +9,16 @@ class Biomarker(Protocol):
def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...
```
-## Registered detectors (19)
+## Registered detectors (21)
Structural complexity (cap −2.5):
-- `brain_method` — symbols simultaneously long, complex, and central.
+- `brain_method` — symbols simultaneously long, complex, and central. The
+ centrality gate is language-agnostic: `dependents ≥ min(8, max(repo p80, 3))`,
+ so it fires on sparse-graph languages (TS/Rust) instead of assuming
+ Python's import density.
+- `low_cohesion` — a class whose methods form unrelated clusters (LCOM4 ≥ 2).
+- `god_class` — a large class (≥ 200 NLOC, ≥ 15 methods) that also hides a
+ brain method.
- `nested_complexity` — functions with deep nesting (≥ 4 levels).
- `bumpy_road` — multiple branches at the same nesting depth.
- `complex_conditional` — compound boolean expressions with ≥ 3 ops.
@@ -63,9 +69,13 @@ table alone would allow.
- `file_path`, `language`, `nloc`, `module`, `has_test_file`.
- `function_metrics` — `dict[symbol_name → FunctionComplexity]`.
+- `class_metrics` — `list[ClassComplexity]` (LCOM4, method count, size).
+ Empty for languages whose walker map doesn't opt into class analysis.
- `git_meta` — per-file git metadata (commits, owners, bus factor,
co-change partners).
- `dependents_count` — file-level in-edge count from the graph.
+- `repo_dependents_p80` — repo-wide p80 of file in-degree; `None` with no
+ graph. The language-agnostic centrality floor for `brain_method`.
- `pagerank_score` — graph centrality (0.0 when symbol-only).
- `line_coverage_pct`, `branch_coverage_pct`, `covered_lines` — coverage
signals; `None` when no coverage was ingested.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index e0570dbdf..b5041836e 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass, field
from typing import Any, Protocol
from ....ingestion.git_indexer.function_blame import BlameIndex
-from ..complexity import FunctionComplexity
+from ..complexity import ClassComplexity, FunctionComplexity
from ..duplication import ClonePair
from ..models import Severity
@@ -38,10 +38,21 @@ class FileContext:
# Map symbol-name → complexity metrics for functions/methods in this
# file. Symbols without a complexity row default to CCN=1, nesting=0.
function_metrics: dict[str, FunctionComplexity] = field(default_factory=dict)
+ # Per-class aggregate metrics (LCOM4, method count, size). Empty for
+ # languages whose walker map doesn't opt into class-level analysis
+ # (see ``complexity.languages``). Consumed by ``low_cohesion`` /
+ # ``god_class``.
+ class_metrics: list[ClassComplexity] = field(default_factory=list)
# Per-file git metadata (may be empty when git indexing skipped).
git_meta: dict[str, Any] = field(default_factory=dict)
# Graph-derived signals.
dependents_count: int = 0
+ # Repo-wide 80th percentile of file-level in-degree (dependents),
+ # computed by the engine across files that have ≥1 dependent. ``None``
+ # when no graph is available. ``brain_method`` uses it as a
+ # language-agnostic centrality floor so its gate adapts to
+ # sparse-graph languages instead of assuming Python's import density.
+ repo_dependents_p80: int | None = None
pagerank_score: float = 0.0
# Coverage signals (populated when --coverage was ingested). When no
# coverage is available these stay ``None`` and coverage-aware
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
index ef897b624..b5bac04ab 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
@@ -5,14 +5,24 @@ when **all three** conditions hold:
- NLOC ≥ 70 (the function is long)
- CCN ≥ 9 (it has many decision paths)
-- enclosing file has ≥ 8 dependents OR pagerank_score in the top decile
- (it sits at a hub, so refactoring carries leverage)
-
-The file-level centrality check matches the plan's intent ("Brain Method
-detection uses graph centrality"). We approximate the per-symbol
-in-degree with the per-file dependents count because symbol-level
-PageRank is not currently exposed via a simple synchronous API; the
-file-level proxy is conservative.
+- the enclosing file is *central* — see the centrality gate below.
+
+**Centrality gate (language-agnostic).** A fixed ``dependents ≥ 8`` gate
+is calibrated for Python's dense import graph and never fires on
+sparse-graph languages (TypeScript barrels, Rust's lower in-degrees),
+silently dropping genuinely complex+central functions. Instead we gate on
+``dependents ≥ floor`` where
+
+ floor = min(8, max(repo_dependents_p80, 3))
+
+i.e. a file qualifies if it has ≥ 8 dependents (the absolute hub bar) OR
+sits in the repo's top quintile of connected files (``repo_dependents_p80``,
+computed by the engine), with a small floor of 3 so a repo where p80 is
+tiny doesn't flag every file with a single importer. When the engine
+can't supply a percentile (no graph), ``floor`` stays at 8 — identical to
+the original behaviour. We use file-level in-degree as a conservative
+proxy for symbol centrality (symbol-level PageRank isn't exposed via a
+simple synchronous API).
"""
from __future__ import annotations
@@ -29,9 +39,19 @@ class BrainMethodDetector:
_NLOC_THRESHOLD = 70
_CCN_THRESHOLD = 9
_DEPENDENTS_THRESHOLD = 8
+ # Lower bound on the percentile branch so a sparse repo (small p80)
+ # doesn't reduce the centrality bar to "any file with one importer".
+ _CENTRALITY_MIN_FLOOR = 3
+
+ def _centrality_floor(self, ctx: FileContext) -> int:
+ p80 = ctx.repo_dependents_p80
+ if p80 is None:
+ return self._DEPENDENTS_THRESHOLD
+ return min(self._DEPENDENTS_THRESHOLD, max(p80, self._CENTRALITY_MIN_FLOOR))
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
- if ctx.dependents_count < self._DEPENDENTS_THRESHOLD:
+ floor = self._centrality_floor(ctx)
+ if ctx.dependents_count < floor:
return []
out: list[BiomarkerResult] = []
@@ -60,6 +80,7 @@ class BrainMethodDetector:
"nloc": fn.nloc,
"max_nesting": fn.max_nesting,
"dependents_count": ctx.dependents_count,
+ "centrality_floor": floor,
},
reason=(
f"Brain Method: {fn.name} is {fn.nloc} lines, CCN {fn.ccn}, "
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py b/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py
new file mode 100644
index 000000000..32db0a4e8
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py
@@ -0,0 +1,75 @@
+"""God Class — a class that is large, has many methods, and hides a brain.
+
+CodeScene's structural module smell: a single class that has accreted too
+many responsibilities. We flag when **all three** hold:
+
+- ``total_nloc ≥ 200`` — the class is large
+- ``method_count ≥ 15`` — it has many methods
+- it contains at least one *brain method* (a method with ``nloc ≥ 70`` and
+ ``ccn ≥ 9``, reusing ``brain_method``'s structural floor) — the size
+ isn't just a flat data holder; real logic concentrates inside it.
+
+Requiring a brain method (not just size) keeps large-but-flat classes
+(config tables, generated DTOs) from firing. Class-level metrics come from
+the walker (``ClassComplexity``); the biomarker simply doesn't fire for
+languages that don't expose class nodes.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+# Reused from brain_method's structural floor.
+_BRAIN_NLOC = 70
+_BRAIN_CCN = 9
+
+
+class GodClassDetector:
+ name = "god_class"
+ category = "structural_complexity"
+
+ _NLOC_THRESHOLD = 200
+ _METHOD_THRESHOLD = 15
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for cls in ctx.class_metrics:
+ if cls.total_nloc < self._NLOC_THRESHOLD:
+ continue
+ if cls.method_count < self._METHOD_THRESHOLD:
+ continue
+ if not any(m.nloc >= _BRAIN_NLOC and m.ccn >= _BRAIN_CCN for m in cls.methods):
+ continue
+
+ if cls.total_nloc >= 400 and cls.method_count >= 25:
+ severity = Severity.CRITICAL
+ elif cls.total_nloc >= 300 or cls.method_count >= 20:
+ severity = Severity.HIGH
+ else:
+ severity = Severity.MEDIUM
+
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=severity,
+ function_name=cls.name,
+ line_start=cls.start_line,
+ line_end=cls.end_line,
+ details={
+ "class_name": cls.name,
+ "total_nloc": cls.total_nloc,
+ "method_count": cls.method_count,
+ "max_method_ccn": cls.max_method_ccn,
+ },
+ reason=(
+ f"{cls.name} is a god class: {cls.total_nloc} lines across "
+ f"{cls.method_count} methods, including a brain method "
+ f"(max method CCN {cls.max_method_ccn})"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = GodClassDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py b/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py
new file mode 100644
index 000000000..7da461350
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py
@@ -0,0 +1,68 @@
+"""Low Cohesion (LCOM4) — a class whose methods form unrelated clusters.
+
+A cohesive class is one whose methods all collaborate around a shared set
+of fields. LCOM4 (Hitz & Montazeri) measures the opposite: it builds a
+graph whose nodes are the class's methods and whose edges link methods
+that share an instance field or call one another, then counts the
+connected components. ``lcom4 = 1`` is fully cohesive; ``lcom4 ≥ 2`` means
+the class splits into method groups that don't talk to each other — a
+candidate for splitting into smaller, single-responsibility classes.
+
+The class-level metrics (including LCOM4) come from the walker
+(``ClassComplexity``); see ``complexity/walker.py`` and ``complexity/README.md``
+for the heuristic and its per-language limits. When a language doesn't
+expose class/member-access nodes the walker reports ``lcom4 = 1`` (no
+signal), so this biomarker simply doesn't fire there — never falsely.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+
+class LowCohesionDetector:
+ name = "low_cohesion"
+ category = "structural_complexity"
+
+ # Ignore tiny classes and data holders — LCOM is only meaningful once
+ # there are enough methods to splinter.
+ _MIN_METHODS = 5
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for cls in ctx.class_metrics:
+ if cls.lcom4 < 2 or cls.method_count < self._MIN_METHODS:
+ continue
+
+ if cls.lcom4 >= 4 and cls.method_count >= 15:
+ severity = Severity.CRITICAL
+ elif cls.lcom4 >= 3 or cls.method_count >= 20:
+ severity = Severity.HIGH
+ else:
+ severity = Severity.MEDIUM
+
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=severity,
+ function_name=cls.name,
+ line_start=cls.start_line,
+ line_end=cls.end_line,
+ details={
+ "class_name": cls.name,
+ "lcom4": cls.lcom4,
+ "method_count": cls.method_count,
+ "field_count": cls.field_count,
+ },
+ reason=(
+ f"{cls.name} has low cohesion (LCOM4={cls.lcom4}): its "
+ f"{cls.method_count} methods split into {cls.lcom4} "
+ f"groups that share no fields or calls"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = LowCohesionDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 062d49311..6f2c86ae8 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -24,9 +24,11 @@ from .coverage_gap import CoverageGapDetector
from .developer_congestion import DeveloperCongestionDetector
from .dry_violation import DryViolationDetector
from .function_hotspot import FunctionHotspotDetector
+from .god_class import GodClassDetector
from .hidden_coupling import HiddenCouplingDetector
from .knowledge_loss import KnowledgeLossDetector
from .large_method import LargeMethodDetector
+from .low_cohesion import LowCohesionDetector
from .nested_complexity import NestedComplexityDetector
from .ownership_risk import OwnershipRiskDetector
from .primitive_obsession import PrimitiveObsessionDetector
@@ -34,6 +36,8 @@ from .untested_hotspot import UntestedHotspotDetector
_DETECTOR_FACTORIES: list[type[Biomarker]] = [
BrainMethodDetector, # type: ignore[list-item]
+ LowCohesionDetector, # type: ignore[list-item]
+ GodClassDetector, # type: ignore[list-item]
NestedComplexityDetector, # type: ignore[list-item]
ComplexMethodDetector, # type: ignore[list-item]
BumpyRoadDetector, # type: ignore[list-item]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index 00be07ca1..4d24cb7e5 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -14,6 +14,9 @@ Tree-sitter AST walker. Single AST pass per file computes:
- **param_count** — formal parameter count. Feeds `primitive_obsession`.
- **nloc** — non-comment lines of code per function.
+It also emits **class-level** aggregates (`ClassComplexity`) for languages
+that opt in — see "Class-level metrics" below.
+
## Performance characteristics
One parser instance per process (lazy-loaded via the ingestion registry).
@@ -25,14 +28,62 @@ ingestion boundary; cost is acceptable (≲ 1 ms for typical files).
```python
from repowise.core.analysis.health.complexity import (
- FunctionComplexity, walk_file_complexity,
+ FileComplexity, FunctionComplexity, walk_file, walk_file_complexity,
)
+# Full result: per-function AND per-class metrics.
+fcx: FileComplexity = walk_file(abs_path, language, source_bytes)
+fcx.functions # list[FunctionComplexity]
+fcx.classes # list[ClassComplexity]
+
+# Back-compat shortcut for callers that only need functions:
results: list[FunctionComplexity] = walk_file_complexity(
abs_path, language, source_bytes
)
```
+## Class-level metrics (LCOM4 / god-class)
+
+`walk_file` also emits a `ClassComplexity` per class-like node for
+languages whose `LanguageNodeMap` opts in (`class_kinds` non-empty):
+
+| Field | Meaning |
+|-------|---------|
+| `method_count`, `total_nloc` | size of the class / impl block |
+| `methods` | the same `FunctionComplexity` rows from the function pass |
+| `max_method_ccn` | peak method complexity |
+| `field_count` | distinct instance members referenced (best-effort) |
+| `lcom4` | **LCOM4 cohesion** — connected components over the methods |
+
+**LCOM4** builds a graph whose nodes are the class's methods and adds an
+edge between two methods when they (a) reference a common instance field
+or (b) one calls the other (a call surfaces as a reference to the callee's
+name). `lcom4` is the number of connected components: `1` is fully
+cohesive; `≥ 2` means the class splinters into unrelated method groups.
+Consumed by `low_cohesion` and `god_class`.
+
+### Heuristic limits (read before trusting a number)
+
+- **Member detection is best-effort and per-language.** A method's field
+ reads and intra-class calls are found by scanning for `self.x` /
+ `this.x` / `$this->x` member-access nodes whose receiver token is in the
+ language's `self_identifiers`. Members accessed without an explicit
+ receiver (Python has none; Ruby's `@ivar`, implicit-`this` in some
+ languages) are not counted.
+- **Safety valve.** If a class yields *zero* detected member references
+ (a pure-static utility class, or a language whose member-access node
+ type isn't mapped yet), `lcom4` falls back to `1` ("no signal") rather
+ than `len(methods)`. This means an unmapped language produces **no**
+ `low_cohesion` finding rather than a false-positive flood — adding a new
+ language can only ever turn signal *on*, never produce noise.
+- **Constructors bridge clusters.** A constructor that initialises every
+ field links all methods that use those fields, lowering LCOM4. This is
+ inherent to LCOM4, not a bug.
+- **Rust groups by `impl` block.** A type with several `impl` blocks
+ yields several `ClassComplexity` rows (one per block). **Go** emits no
+ classes (methods attach to a type via an external receiver, so there is
+ no single grouping node).
+
## Inputs
`abs_path` (filesystem path), `language` (e.g. `"python"`), `source_bytes`
@@ -52,5 +103,25 @@ walker's abstract `BRANCH` / `LOOP` / `TRY` / `BOOLEAN_OP` categories.
Add a new language → one new `LanguageNodeMap` dict (~20 lines). No
`.scm` file edits required — those are owned by the ingestion parser.
-Phase 1 ships mappings for Python, TypeScript, JavaScript, Go, Java, Rust.
-Phase 5 adds C, C++, C#, Kotlin, Ruby, PHP, Swift, Scala.
+To also get **class-level** metrics for that language, set three more
+fields on its `LanguageNodeMap` (all default to empty = opt-out):
+
+- `class_kinds` — node type(s) that group methods (a class body, or
+ Rust's `impl` block).
+- `self_identifiers` — the receiver token(s) for the instance (`self`,
+ `this`, `$this`, `cls`).
+- `member_access_kinds` — node type(s) for `receiver.member` access (both
+ field reads and method calls).
+
+The receiver and member-name children are extracted by a generic
+field-name probe (`walker._self_member_name`), which tries the
+`object`/`value` and `property`/`attribute`/`field`/`name` fields and then
+falls back to positional children — so most tree-sitter grammars need only
+the node-type names above. Get one wrong and the safety valve degrades the
+class to "no signal" rather than emitting a false positive, so it's cheap
+to add a language speculatively and refine later.
+
+Ships control-flow mappings for Python, TypeScript, JavaScript, Go, Java,
+Rust; class-level mappings for Python, TypeScript, JavaScript, Java, Rust
+(Go has no class-grouping node). Adding more languages — either tier — is
+purely additive in `languages.py`.
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
index 6f7f2bb2a..448bc6bdd 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
@@ -2,6 +2,20 @@
from __future__ import annotations
-from .walker import ConditionComplexity, FunctionComplexity, walk_file_complexity
+from .walker import (
+ ClassComplexity,
+ ConditionComplexity,
+ FileComplexity,
+ FunctionComplexity,
+ walk_file,
+ walk_file_complexity,
+)
-__all__ = ["ConditionComplexity", "FunctionComplexity", "walk_file_complexity"]
+__all__ = [
+ "ClassComplexity",
+ "ConditionComplexity",
+ "FileComplexity",
+ "FunctionComplexity",
+ "walk_file",
+ "walk_file_complexity",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 388e93232..5ea380755 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -17,9 +17,14 @@ names to the walker's abstract categories:
- ``LAMBDA`` — anonymous function. Treated as ``FUNCTION`` for
nested-walker recursion but does not emit its own
``FunctionComplexity``.
-
-Phase 1 covers Python, TypeScript, JavaScript, Go, Java, Rust.
-Phase 5 will add C, C++, C#, Kotlin, Ruby, PHP, Swift, Scala.
+- ``CLASS`` — (optional) node type(s) that group methods for
+ class-level metrics (LCOM4 / god-class). Opt-in per
+ language via ``class_kinds`` / ``self_identifiers`` /
+ ``member_access_kinds`` — see the dataclass below.
+
+Control-flow maps cover Python, TypeScript, JavaScript, Go, Java, Rust;
+class-level maps cover all of those except Go (no class-grouping node).
+Adding a language — either tier — is purely additive here.
"""
from __future__ import annotations
@@ -45,6 +50,40 @@ class LanguageNodeMap:
# text content equals ``&&`` or ``||``.
boolean_operator_text_kinds: frozenset[str] = frozenset()
+ # ------------------------------------------------------------------
+ # Class-level analysis (LCOM4 / god-class). All three fields default
+ # to empty, which makes class-level metrics OPT-IN per language:
+ #
+ # * ``class_kinds`` empty → no classes are emitted for this
+ # language at all (e.g. Go, where methods attach to types via an
+ # external receiver rather than nesting in a class body).
+ # * ``self_identifiers`` / ``member_access_kinds`` empty or wrong →
+ # no self/this member references are detected, so the LCOM4
+ # computation falls back to the "no signal" value (``lcom4 = 1``)
+ # rather than guessing. This is the safety valve that keeps the
+ # ``low_cohesion`` biomarker from false-firing on a language whose
+ # member-access node type we have not yet mapped.
+ #
+ # To add class-level support for a new language: set ``class_kinds``
+ # to the node type(s) that group methods (a class body, or Rust's
+ # ``impl`` block), ``self_identifiers`` to the receiver token(s) that
+ # denote the instance (``self`` / ``this`` / ``$this`` / ``cls``), and
+ # ``member_access_kinds`` to the node type(s) for ``receiver.member``
+ # access. The receiver and member-name children are pulled out by the
+ # generic field-name probe in ``walker._self_member_name`` (it tries
+ # the ``object``/``value`` and ``property``/``attribute``/``field``/
+ # ``name`` fields, then falls back to positional children), so most
+ # tree-sitter grammars need only the node-type names below.
+
+ # Node types that group methods into a cohesive unit for LCOM4.
+ class_kinds: frozenset[str] = frozenset()
+ # Receiver tokens denoting "this instance" (text-matched).
+ self_identifiers: frozenset[str] = frozenset()
+ # Node types representing ``receiver.member`` / ``receiver->member``
+ # access (both field reads and method calls — both count as a member
+ # reference for cohesion).
+ member_access_kinds: frozenset[str] = frozenset()
+
_PY = LanguageNodeMap(
function_kinds=frozenset({"function_definition", "async_function_definition"}),
@@ -56,6 +95,9 @@ _PY = LanguageNodeMap(
switch_kinds=frozenset({"match_statement"}),
case_kinds=frozenset({"case_clause"}),
boolean_operator_kinds=frozenset({"boolean_operator"}),
+ class_kinds=frozenset({"class_definition"}),
+ self_identifiers=frozenset({"self", "cls"}),
+ member_access_kinds=frozenset({"attribute"}),
)
_TS = LanguageNodeMap(
@@ -85,6 +127,9 @@ _TS = LanguageNodeMap(
case_kinds=frozenset({"switch_case"}),
boolean_operator_kinds=frozenset(),
boolean_operator_text_kinds=frozenset({"binary_expression"}),
+ class_kinds=frozenset({"class_declaration", "class", "abstract_class_declaration"}),
+ self_identifiers=frozenset({"this"}),
+ member_access_kinds=frozenset({"member_expression"}),
)
_JS = _TS # identical control-flow nodes; tree-sitter-javascript shares shape.
@@ -100,6 +145,10 @@ _GO = LanguageNodeMap(
case_kinds=frozenset({"expression_case", "type_case", "default_case"}),
boolean_operator_kinds=frozenset(),
boolean_operator_text_kinds=frozenset({"binary_expression"}),
+ # No class-level fields: Go methods attach to a type via an external
+ # receiver (``func (r T) m()``) rather than nesting in a class body,
+ # so there is no single node that groups a type's methods. Left for a
+ # future receiver-aware grouping pass; until then Go emits no classes.
)
_JAVA = LanguageNodeMap(
@@ -120,19 +169,34 @@ _JAVA = LanguageNodeMap(
case_kinds=frozenset({"switch_block_statement_group", "switch_rule"}),
boolean_operator_kinds=frozenset(),
boolean_operator_text_kinds=frozenset({"binary_expression"}),
+ class_kinds=frozenset({"class_declaration"}),
+ self_identifiers=frozenset({"this"}),
+ # ``field_access`` covers ``this.field``; ``method_invocation`` covers
+ # ``this.foo()`` (its ``name`` field is the called method).
+ member_access_kinds=frozenset({"field_access", "method_invocation"}),
)
_RUST = LanguageNodeMap(
function_kinds=frozenset({"function_item"}),
lambda_kinds=frozenset({"closure_expression"}),
branch_kinds=frozenset({"if_expression", "if_let_expression"}),
- loop_kinds=frozenset({"for_expression", "while_expression", "while_let_expression", "loop_expression"}),
+ loop_kinds=frozenset(
+ {"for_expression", "while_expression", "while_let_expression", "loop_expression"}
+ ),
try_kinds=frozenset(),
catch_kinds=frozenset(),
switch_kinds=frozenset({"match_expression"}),
case_kinds=frozenset({"match_arm"}),
boolean_operator_kinds=frozenset(),
boolean_operator_text_kinds=frozenset({"binary_expression"}),
+ # Methods live in an ``impl`` block, not the ``struct`` itself; each
+ # impl block is its own cohesion unit (a type with several impl blocks
+ # yields several ``ClassComplexity`` rows). ``field_expression`` covers
+ # both ``self.field`` and ``self.method()`` (the latter nests a
+ # field_expression inside a call_expression).
+ class_kinds=frozenset({"impl_item"}),
+ self_identifiers=frozenset({"self"}),
+ member_access_kinds=frozenset({"field_expression"}),
)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 63551ea24..df2c50269 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -74,6 +74,45 @@ class FunctionComplexity:
self.complex_conditions = []
+@dataclass
+class ClassComplexity:
+ """Per-class aggregate metrics produced by the walker.
+
+ Emitted only for languages whose ``LanguageNodeMap`` opts into
+ class-level analysis (``class_kinds`` non-empty). Consumed by the
+ ``low_cohesion`` (LCOM4) and ``god_class`` biomarkers.
+
+ ``lcom4`` is the LCOM4 cohesion metric — the number of connected
+ components in the graph whose nodes are the class's methods and whose
+ edges link methods that share an instance field or call one another.
+ ``1`` means a fully cohesive class (or "no signal": see the safety
+ valve in ``_compute_lcom4``). Higher values mean the class splinters
+ into unrelated method clusters.
+ """
+
+ name: str
+ start_line: int # 1-indexed
+ end_line: int # 1-indexed
+ method_count: int
+ total_nloc: int
+ methods: list[FunctionComplexity]
+ lcom4: int = 1
+ max_method_ccn: int = 0
+ field_count: int = 0
+
+
+@dataclass
+class FileComplexity:
+ """Walker output for one file: per-function and per-class metrics.
+
+ ``walk_file`` returns this; ``walk_file_complexity`` is the
+ backward-compatible thin wrapper that returns only ``functions``.
+ """
+
+ functions: list[FunctionComplexity]
+ classes: list[ClassComplexity]
+
+
def _find_name(node: Node) -> str:
"""Best-effort: return the text of the first identifier child."""
# Search a couple of common field names first.
@@ -402,21 +441,251 @@ def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
return out
-def walk_file_complexity(
+# ----------------------------------------------------------------------
+# Class-level analysis (LCOM4 / god-class)
+# ----------------------------------------------------------------------
+
+_PROP_FIELD_NAMES = ("property", "attribute", "field", "name")
+_OBJECT_FIELD_NAMES = ("object", "value", "argument", "operand")
+_IDENTIFIER_SUFFIX = "identifier"
+
+
+def _class_name(node: Node) -> str:
+ """Best-effort class/impl name.
+
+ Tries the ``name`` field (most class grammars), then ``type`` (Rust's
+ ``impl T`` exposes the implemented type there), then the generic
+ identifier scan.
+ """
+ for field_name in ("name", "type"):
+ child = node.child_by_field_name(field_name)
+ if child is not None and child.text is not None:
+ return child.text.decode("utf-8", errors="replace")
+ return _find_name(node)
+
+
+def _collect_class_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """All class-like grouping nodes in the file (pre-order).
+
+ Descends through the whole tree so nested classes are found too;
+ each becomes its own ``ClassComplexity``.
+ """
+ out: list[Node] = []
+ stack: list[Node] = [root]
+ while stack:
+ node = stack.pop()
+ # ``is_named`` filters out keyword tokens that share a type name
+ # with an expression node (e.g. the ``class`` keyword vs a
+ # ``class`` expression in tree-sitter-typescript).
+ if node.type in lmap.class_kinds and node.is_named:
+ out.append(node)
+ for child in node.children:
+ stack.append(child)
+ return out
+
+
+def _collect_class_methods(class_node: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """Direct method nodes of *class_node*.
+
+ Stops at nested classes (their methods belong to the inner class) and
+ does not descend into a method body (nested local defs roll up into
+ the method, mirroring ``_collect_function_nodes``).
+ """
+ methods: list[Node] = []
+ stack: list[Node] = list(class_node.children)
+ while stack:
+ node = stack.pop()
+ if node.type in lmap.class_kinds:
+ continue # nested class — its methods are not ours
+ if node.type in lmap.function_kinds:
+ methods.append(node)
+ continue # don't descend into the method body
+ for child in node.children:
+ stack.append(child)
+ return methods
+
+
+def _self_member_name(node: Node, lmap: LanguageNodeMap) -> str | None:
+ """Extract ``member`` from a ``self.member`` / ``this.member`` access.
+
+ Returns the member name when the receiver token is one of the
+ language's ``self_identifiers``; otherwise ``None`` (so ``other.x`` and
+ ``a.b.c``'s outer hops are ignored — only direct instance access
+ counts toward cohesion).
+ """
+ obj: Node | None = None
+ for field_name in _OBJECT_FIELD_NAMES:
+ obj = node.child_by_field_name(field_name)
+ if obj is not None:
+ break
+ if obj is None:
+ obj = next((c for c in node.children if c.is_named), None)
+
+ prop: Node | None = None
+ for field_name in _PROP_FIELD_NAMES:
+ prop = node.child_by_field_name(field_name)
+ if prop is not None:
+ break
+ if prop is None:
+ named = [c for c in node.children if c.is_named]
+ prop = next(
+ (c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)),
+ None,
+ )
+
+ if obj is None or prop is None or obj is prop:
+ return None
+ if obj.text is None or prop.text is None:
+ return None
+ if obj.text.decode("utf-8", errors="replace") not in lmap.self_identifiers:
+ return None
+ return prop.text.decode("utf-8", errors="replace")
+
+
+def _collect_self_members(method_node: Node, lmap: LanguageNodeMap) -> set[str]:
+ """Set of instance-member names referenced by *method_node*.
+
+ Walks the method body (descending through nested functions/lambdas,
+ which close over the same instance) but stops at nested class
+ definitions. Both field reads and method calls reduce to a member
+ name here — both are evidence two methods touch the same thing.
+ """
+ members: set[str] = set()
+ if not lmap.self_identifiers or not lmap.member_access_kinds:
+ return members
+ stack: list[Node] = list(method_node.children)
+ while stack:
+ node = stack.pop()
+ if node.type in lmap.class_kinds:
+ continue # nested class has its own self
+ if node.type in lmap.member_access_kinds:
+ name = _self_member_name(node, lmap)
+ if name:
+ members.add(name)
+ for child in node.children:
+ stack.append(child)
+ return members
+
+
+def _compute_lcom4(
+ method_nodes: list[Node],
+ method_fcs: list[FunctionComplexity],
+ lmap: LanguageNodeMap,
+) -> tuple[int, int]:
+ """Return ``(lcom4, field_count)`` for a class.
+
+ LCOM4 = number of connected components over the methods, where two
+ methods are connected if they share an instance member or one calls
+ the other (a call shows up as a reference to the callee's name).
+
+ **Safety valve:** if no instance-member references are detected at all
+ (a pure-static class, or — importantly — a language whose
+ member-access node type we have not mapped), return ``1`` rather than
+ ``len(methods)``. This prevents ``low_cohesion`` from false-firing on
+ an unverified language: a missing mapping yields "no signal", never a
+ spurious high-LCOM hit.
+ """
+ n = len(method_nodes)
+ if n == 0:
+ return 1, 0
+
+ members_per_method: list[set[str]] = [
+ _collect_self_members(node, lmap) for node in method_nodes
+ ]
+ total_refs = sum(len(m) for m in members_per_method)
+ method_names = {fc.name for fc in method_fcs}
+ all_members: set[str] = set().union(*members_per_method) if members_per_method else set()
+ field_count = len(all_members - method_names)
+
+ if total_refs == 0:
+ return 1, field_count
+
+ # Union-find over method indices.
+ parent = list(range(n))
+
+ def _find(i: int) -> int:
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+
+ def _union(a: int, b: int) -> None:
+ ra, rb = _find(a), _find(b)
+ if ra != rb:
+ parent[ra] = rb
+
+ name_to_idx = {fc.name: i for i, fc in enumerate(method_fcs)}
+ # Bucket method indices by each member they reference; the method that
+ # *defines* that name (a callee) joins the bucket too, so call edges and
+ # shared-field edges are both captured in one pass.
+ buckets: dict[str, list[int]] = {}
+ for i, members in enumerate(members_per_method):
+ for m in members:
+ buckets.setdefault(m, []).append(i)
+ for member, idxs in buckets.items():
+ group = list(idxs)
+ callee = name_to_idx.get(member)
+ if callee is not None:
+ group.append(callee)
+ first = group[0]
+ for other in group[1:]:
+ _union(first, other)
+
+ components = {_find(i) for i in range(n)}
+ return len(components), field_count
+
+
+def _collect_classes(
+ root: Node,
+ lmap: LanguageNodeMap,
+ source: bytes,
+ fc_by_node_id: dict[int, FunctionComplexity],
+) -> list[ClassComplexity]:
+ """Build ``ClassComplexity`` for every class-like node in the file."""
+ if not lmap.class_kinds:
+ return []
+ classes: list[ClassComplexity] = []
+ for class_node in _collect_class_nodes(root, lmap):
+ method_nodes = _collect_class_methods(class_node, lmap)
+ method_fcs = [fc_by_node_id[m.id] for m in method_nodes if m.id in fc_by_node_id]
+ # Keep nodes and FCs aligned (a method missing from the function
+ # pass — unusual — drops out of both).
+ aligned_nodes = [m for m in method_nodes if m.id in fc_by_node_id]
+ lcom4, field_count = _compute_lcom4(aligned_nodes, method_fcs, lmap)
+ classes.append(
+ ClassComplexity(
+ name=_class_name(class_node),
+ start_line=class_node.start_point[0] + 1,
+ end_line=class_node.end_point[0] + 1,
+ method_count=len(method_fcs),
+ total_nloc=_count_nloc(class_node, source),
+ methods=method_fcs,
+ lcom4=lcom4,
+ max_method_ccn=max((fc.ccn for fc in method_fcs), default=0),
+ field_count=field_count,
+ )
+ )
+ return classes
+
+
+def walk_file(
abs_path: str,
language: str,
source: bytes,
-) -> list[FunctionComplexity]:
- """Walk one file's AST. Returns one ``FunctionComplexity`` per fn.
+) -> FileComplexity:
+ """Walk one file's AST once → per-function and per-class metrics.
- Returns an empty list when:
+ Returns an empty ``FileComplexity`` when:
- the language is unsupported (no entry in ``LANGUAGE_MAPS``)
- the tree-sitter language package isn't installed
- parsing fails
+
+ Class-level metrics are populated only when the language's
+ ``LanguageNodeMap`` opts in via ``class_kinds`` (see ``languages.py``).
"""
lmap = get_language_map(language)
if lmap is None:
- return []
+ return FileComplexity(functions=[], classes=[])
try:
from tree_sitter import Parser
@@ -427,38 +696,53 @@ def walk_file_complexity(
from repowise.core.ingestion.parser import _get_language
except Exception as exc:
log.debug("complexity_walker_import_failed", error=str(exc))
- return []
+ return FileComplexity(functions=[], classes=[])
grammar = _get_language(language)
if grammar is None:
- return []
+ return FileComplexity(functions=[], classes=[])
try:
parser = Parser(grammar)
tree = parser.parse(source)
except Exception as exc:
log.debug("complexity_walker_parse_failed", path=abs_path, error=str(exc))
- return []
+ return FileComplexity(functions=[], classes=[])
- results: list[FunctionComplexity] = []
+ functions: list[FunctionComplexity] = []
+ fc_by_node_id: dict[int, FunctionComplexity] = {}
for fn_node in _collect_function_nodes(tree.root_node, lmap):
body = fn_node.child_by_field_name("body") or fn_node
ccn, max_nest, cognitive, bumps, conditions = _walk_function_body(body, lmap)
- results.append(
- FunctionComplexity(
- name=_find_name(fn_node),
- start_line=fn_node.start_point[0] + 1,
- end_line=fn_node.end_point[0] + 1,
- ccn=ccn,
- max_nesting=max_nest,
- cognitive=cognitive,
- nloc=_count_nloc(body, source),
- bumps=bumps,
- param_count=_count_parameters(fn_node),
- complex_conditions=conditions,
- )
+ fc = FunctionComplexity(
+ name=_find_name(fn_node),
+ start_line=fn_node.start_point[0] + 1,
+ end_line=fn_node.end_point[0] + 1,
+ ccn=ccn,
+ max_nesting=max_nest,
+ cognitive=cognitive,
+ nloc=_count_nloc(body, source),
+ bumps=bumps,
+ param_count=_count_parameters(fn_node),
+ complex_conditions=conditions,
)
- return results
+ functions.append(fc)
+ fc_by_node_id[fn_node.id] = fc
+
+ classes = _collect_classes(tree.root_node, lmap, source, fc_by_node_id)
+ return FileComplexity(functions=functions, classes=classes)
+
+
+def walk_file_complexity(
+ abs_path: str,
+ language: str,
+ source: bytes,
+) -> list[FunctionComplexity]:
+ """Backward-compatible wrapper: returns only per-function metrics.
+
+ Prefer ``walk_file`` when class-level metrics are also needed.
+ """
+ return walk_file(abs_path, language, source).functions
def _count_parameters(fn_node: Node) -> int:
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 332aedeb5..7f900bc09 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -31,7 +31,7 @@ from ...ingestion.git_indexer.function_blame import (
)
from .biomarkers import FileContext, detect_all
from .biomarkers.base import HasEdge
-from .complexity import FunctionComplexity, walk_file_complexity
+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
@@ -96,8 +96,20 @@ class _ImportEdgeView:
return data.get("edge_type") == key
+def _percentile_p80(counts: list[int]) -> int | None:
+ """80th percentile of *counts* using the inclusive-lower convention
+ already used by ``churn_percentile`` in ``enrich.compute_percentiles``.
+ Returns ``None`` for an empty list.
+ """
+ if not counts:
+ return None
+ counts = sorted(counts)
+ idx_p80 = min(len(counts) - 1, max(0, int(0.8 * len(counts))))
+ return counts[idx_p80]
+
+
def _compute_repo_function_mod_p80(
- walked: list[tuple[Any, list[FunctionComplexity]]],
+ walked: list[tuple[Any, FileComplexity]],
git_meta_map: dict[str, dict],
) -> int | None:
"""Compute the repo-wide 80th percentile of per-function modification counts.
@@ -108,22 +120,44 @@ def _compute_repo_function_mod_p80(
"no signal" outcome.
"""
counts: list[int] = []
- for pf, fc_list in walked:
+ for pf, fcx in walked:
meta = git_meta_map.get(pf.file_info.path) or {}
idx = meta.get("blame_index")
if not isinstance(idx, BlameIndex) or not idx.lines:
continue
- for fc in fc_list:
+ for fc in fcx.functions:
mod_count = len(distinct_commits_in_range(idx, fc.start_line, fc.end_line))
if mod_count > 0:
counts.append(mod_count)
- if not counts:
+ return _percentile_p80(counts)
+
+
+def _compute_repo_dependents_p80(parsed_files: list[Any], graph: Any) -> int | None:
+ """Repo-wide 80th percentile of file-level in-degree (dependents).
+
+ Restricted to files that actually have ≥1 dependent — this is the
+ "top quintile of *connected* files", mirroring the mod-count p80
+ convention (which only counts functions that were actually modified).
+ Returns ``None`` when no graph is available or no file has dependents,
+ in which case centrality-percentile gates fall back to their fixed
+ floor. Used by ``brain_method`` so its centrality gate adapts to
+ sparse-graph languages (TS/Rust) instead of assuming Python's denser
+ import graph.
+ """
+ if graph is None:
return None
- counts.sort()
- # ``int(0.8 * n)`` matches the (inclusive-lower) percentile convention
- # already used by churn_percentile in enrich.compute_percentiles.
- idx_p80 = min(len(counts) - 1, max(0, int(0.8 * len(counts))))
- return counts[idx_p80]
+ counts: list[int] = []
+ for pf in parsed_files:
+ path = pf.file_info.path
+ if path not in graph:
+ continue
+ try:
+ deg = int(graph.in_degree(path))
+ except Exception:
+ continue
+ if deg > 0:
+ counts.append(deg)
+ return _percentile_p80(counts)
def _build_repo_commit_counts(git_meta_map: dict[str, dict]) -> dict[str, int]:
@@ -235,24 +269,25 @@ class HealthAnalyzer:
# Pre-walk every target so we can compute the repo-wide p80 of
# per-function modification counts ONCE before any biomarker runs.
# The walked list is reused by the per-file biomarker stage below.
- walked: list[tuple[Any, list[FunctionComplexity]]] = []
+ walked: list[tuple[Any, FileComplexity]] = []
for pf in self.parsed_files:
if changed_set is not None and pf.file_info.path not in changed_set:
continue
try:
- fc_list = self._walk(pf)
+ fcx = self._walk(pf)
except Exception as exc:
log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))
- fc_list = []
- walked.append((pf, fc_list))
+ fcx = FileComplexity(functions=[], classes=[])
+ walked.append((pf, fcx))
repo_fn_mod_p80 = _compute_repo_function_mod_p80(walked, self.git_meta_map)
+ repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
- for pf, fc_list in walked:
+ for pf, fcx in walked:
# Side-effect: bump Symbol.complexity_estimate when we can
# match by enclosing line range. Symbols not matched keep
# their default (1).
- self._populate_symbol_complexity(pf, fc_list)
+ self._populate_symbol_complexity(pf, fcx.functions)
file_disabled = list(disabled)
extra = per_file_disabled.get(pf.file_info.path)
@@ -262,13 +297,14 @@ class HealthAnalyzer:
file_disabled.append(name)
file_metric, file_findings = self._evaluate_file(
pf,
- fc_list,
+ fcx,
all_paths,
disabled=file_disabled,
dup_report=dup_report,
graph_view=graph_view,
repo_commit_counts=repo_commit_counts,
repo_function_mod_p80=repo_fn_mod_p80,
+ repo_dependents_p80=repo_dependents_p80,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -353,22 +389,23 @@ class HealthAnalyzer:
workers = max(1, int(max_workers or os.cpu_count() or 4))
semaphore = asyncio.Semaphore(workers)
- async def _one(pf: Any) -> tuple[Any, list[FunctionComplexity]]:
+ async def _one(pf: Any) -> tuple[Any, FileComplexity]:
async with semaphore:
try:
- fc = await asyncio.to_thread(self._walk, pf)
+ fcx = await asyncio.to_thread(self._walk, pf)
except Exception as exc:
log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))
- fc = []
- return pf, fc
+ fcx = FileComplexity(functions=[], classes=[])
+ return pf, fcx
walked = await asyncio.gather(*[_one(pf) for pf in target_files])
repo_fn_mod_p80 = _compute_repo_function_mod_p80(list(walked), self.git_meta_map)
+ repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
- for pf, fc_list in walked:
- self._populate_symbol_complexity(pf, fc_list)
+ for pf, fcx in walked:
+ self._populate_symbol_complexity(pf, fcx.functions)
file_disabled = list(disabled)
extra = per_file_disabled.get(pf.file_info.path)
if extra:
@@ -377,13 +414,14 @@ class HealthAnalyzer:
file_disabled.append(name)
file_metric, file_findings = self._evaluate_file(
pf,
- fc_list,
+ fcx,
all_paths,
disabled=file_disabled,
dup_report=dup_report,
graph_view=graph_view,
repo_commit_counts=repo_commit_counts,
repo_function_mod_p80=repo_fn_mod_p80,
+ repo_dependents_p80=repo_dependents_p80,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -408,14 +446,14 @@ class HealthAnalyzer:
# Helpers
# ------------------------------------------------------------------
- def _walk(self, pf: Any) -> list[FunctionComplexity]:
+ def _walk(self, pf: Any) -> FileComplexity:
path = pf.file_info.abs_path
language = pf.file_info.language
try:
source = Path(path).read_bytes()
except OSError:
- return []
- return walk_file_complexity(path, language, source)
+ return FileComplexity(functions=[], classes=[])
+ return walk_file(path, language, source)
def _populate_symbol_complexity(self, pf: Any, fc_list: list[FunctionComplexity]) -> None:
if not fc_list:
@@ -433,7 +471,7 @@ class HealthAnalyzer:
def _evaluate_file(
self,
pf: Any,
- fc_list: list[FunctionComplexity],
+ fcx: FileComplexity,
all_paths: set[str],
*,
disabled: list[str],
@@ -441,9 +479,11 @@ class HealthAnalyzer:
graph_view: HasEdge | None = None,
repo_commit_counts: dict[str, int] | None = None,
repo_function_mod_p80: int | None = None,
+ repo_dependents_p80: int | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData]]:
file_path = pf.file_info.path
+ fc_list = fcx.functions
fn_metrics: dict[str, FunctionComplexity] = {fc.name: fc for fc in fc_list}
max_ccn = max((fc.ccn for fc in fc_list), default=1)
max_nesting = max((fc.max_nesting for fc in fc_list), default=0)
@@ -482,8 +522,10 @@ class HealthAnalyzer:
or _coverage_is_test_file(file_path),
module=module,
function_metrics=fn_metrics,
+ class_metrics=fcx.classes,
git_meta=file_git_meta,
dependents_count=dependents_count,
+ repo_dependents_p80=repo_dependents_p80,
pagerank_score=0.0,
line_coverage_pct=line_cov,
branch_coverage_pct=branch_cov,
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 561b7c5b3..9af16e689 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -73,6 +73,8 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
# span categories and we may want to retune without re-deploying.
_BIOMARKER_CATEGORY: dict[str, str] = {
"brain_method": "structural_complexity",
+ "low_cohesion": "structural_complexity",
+ "god_class": "structural_complexity",
"nested_complexity": "structural_complexity",
"bumpy_road": "structural_complexity",
"complex_conditional": "structural_complexity",
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index 50c18678a..d28ace531 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -24,6 +24,19 @@ _TEMPLATES: dict[str, str] = {
"many dependents — extract cohesive responsibilities into helpers "
"so each call site sees a smaller surface area."
),
+ "low_cohesion": (
+ "Split this class along its cohesion seams. Its methods form "
+ "groups that share no fields or calls — each group is a smaller, "
+ "single-responsibility class waiting to be extracted. Start by "
+ "moving one disconnected method cluster (and the fields only it "
+ "touches) into its own type."
+ ),
+ "god_class": (
+ "Break up this god class. It is large, has many methods, and "
+ "concentrates real logic in a brain method — extract cohesive "
+ "responsibilities into collaborators so no single class owns the "
+ "whole subsystem. Pair the split with characterization tests."
+ ),
"nested_complexity": (
"Flatten the control flow. Pull early-return guards to the top, "
"extract the deepest branch into a helper, and consider "
diff --git a/tests/fixtures/lang_samples/python/classes.py b/tests/fixtures/lang_samples/python/classes.py
new file mode 100644
index 000000000..dc64041cf
--- /dev/null
+++ b/tests/fixtures/lang_samples/python/classes.py
@@ -0,0 +1,50 @@
+"""Fixtures for class-level (LCOM4 / god-class) walker tests."""
+
+
+class Cohesive:
+ """All methods collaborate around shared state → LCOM4 == 1."""
+
+ def __init__(self):
+ self.total = 0
+ self.count = 0
+
+ def add(self, n):
+ self.total += n
+ self.count += 1
+
+ def average(self):
+ return self.total / self.count if self.count else 0
+
+ def reset(self):
+ self.total = 0
+ self.count = 0
+
+ def describe(self):
+ return f"{self.count} items, avg {self.average()}"
+
+
+class Splintered:
+ """Two disjoint method clusters plus a loner → LCOM4 == 3.
+
+ {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
+ clusters.
+ """
+
+ a = 0
+ b = 0
+
+ def set_a(self, v):
+ self.a = v
+
+ def get_a(self):
+ return self.a
+
+ def set_b(self, v):
+ self.b = v
+
+ def get_b(self):
+ return self.b
+
+ def loner(self):
+ return 42
diff --git a/tests/fixtures/lang_samples/typescript/classes.ts b/tests/fixtures/lang_samples/typescript/classes.ts
new file mode 100644
index 000000000..b0928909e
--- /dev/null
+++ b/tests/fixtures/lang_samples/typescript/classes.ts
@@ -0,0 +1,51 @@
+// Fixtures for class-level (LCOM4) walker tests.
+
+class Cohesive {
+ total = 0;
+ count = 0;
+
+ add(n: number): void {
+ this.total += n;
+ this.count += 1;
+ }
+
+ average(): number {
+ return this.count ? this.total / this.count : 0;
+ }
+
+ reset(): void {
+ this.total = 0;
+ this.count = 0;
+ }
+
+ describe(): string {
+ return `${this.count} items, avg ${this.average()}`;
+ }
+}
+
+// Fields are declared (not assigned in a constructor) so no single
+// method bridges the two clusters → LCOM4 == 3.
+class Splintered {
+ a = 0;
+ b = 0;
+
+ setA(v: number): void {
+ this.a = v;
+ }
+
+ getA(): number {
+ return this.a;
+ }
+
+ setB(v: number): void {
+ this.b = v;
+ }
+
+ getB(): number {
+ return this.b;
+ }
+
+ loner(): number {
+ return 42;
+ }
+}
diff --git a/tests/unit/health/test_biomarkers.py b/tests/unit/health/test_biomarkers.py
index 34095235e..675800121 100644
--- a/tests/unit/health/test_biomarkers.py
+++ b/tests/unit/health/test_biomarkers.py
@@ -11,7 +11,9 @@ from repowise.core.analysis.health.biomarkers.nested_complexity import (
from repowise.core.analysis.health.complexity import FunctionComplexity
-def _ctx(fns: list[FunctionComplexity], *, dependents: int = 0) -> FileContext:
+def _ctx(
+ fns: list[FunctionComplexity], *, dependents: int = 0, repo_dependents_p80: int | None = None
+) -> FileContext:
return FileContext(
file_path="src/example.py",
language="python",
@@ -21,6 +23,7 @@ def _ctx(fns: list[FunctionComplexity], *, dependents: int = 0) -> FileContext:
function_metrics={f.name: f for f in fns},
git_meta={},
dependents_count=dependents,
+ repo_dependents_p80=repo_dependents_p80,
pagerank_score=0.0,
)
@@ -60,6 +63,32 @@ def test_brain_method_requires_centrality():
assert results[0].details["dependents_count"] == 12
+def test_brain_method_percentile_floor_fires_on_sparse_graph():
+ """A complex+central function in a sparse-graph repo (low p80) should
+ fire even below the fixed dependents>=8 bar."""
+ fn = FunctionComplexity("central_brain", 1, 200, ccn=20, max_nesting=4, cognitive=40, nloc=150)
+ # Repo top-quintile is 3 dependents; this file has 4 → top quintile.
+ results = BrainMethodDetector().detect(_ctx([fn], dependents=4, repo_dependents_p80=3))
+ assert len(results) == 1
+ assert results[0].details["centrality_floor"] == 3
+
+
+def test_brain_method_percentile_floor_respects_min_floor():
+ """Even with a tiny p80, the floor never drops below 3, so a file with
+ a single importer is not flagged."""
+ fn = FunctionComplexity("brain", 1, 200, ccn=20, max_nesting=4, cognitive=40, nloc=150)
+ assert BrainMethodDetector().detect(_ctx([fn], dependents=1, repo_dependents_p80=1)) == []
+
+
+def test_brain_method_dense_graph_keeps_fixed_bar():
+ """When p80 is high (dense graph), the floor caps at 8 — a file with 5
+ dependents still doesn't qualify."""
+ fn = FunctionComplexity("brain", 1, 200, ccn=20, max_nesting=4, cognitive=40, nloc=150)
+ assert BrainMethodDetector().detect(_ctx([fn], dependents=5, repo_dependents_p80=40)) == []
+ # 8+ always qualifies regardless of percentile.
+ assert BrainMethodDetector().detect(_ctx([fn], dependents=8, repo_dependents_p80=40))
+
+
def test_detect_all_runs_every_biomarker():
fn = FunctionComplexity("monster", 1, 200, ccn=20, max_nesting=6, cognitive=60, nloc=150)
ctx = _ctx([fn], dependents=15)
diff --git a/tests/unit/health/test_class_biomarkers.py b/tests/unit/health/test_class_biomarkers.py
new file mode 100644
index 000000000..35d53e69e
--- /dev/null
+++ b/tests/unit/health/test_class_biomarkers.py
@@ -0,0 +1,116 @@
+"""Tests for the class-level structural biomarkers: low_cohesion, god_class."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.god_class import GodClassDetector
+from repowise.core.analysis.health.biomarkers.low_cohesion import LowCohesionDetector
+from repowise.core.analysis.health.complexity import ClassComplexity, FunctionComplexity
+
+
+def _fn(name: str, *, nloc: int = 5, ccn: int = 1) -> FunctionComplexity:
+ return FunctionComplexity(
+ name=name, start_line=1, end_line=1 + nloc, ccn=ccn, max_nesting=0, cognitive=0, nloc=nloc
+ )
+
+
+def _cls(
+ name: str,
+ *,
+ method_count: int,
+ lcom4: int = 1,
+ total_nloc: int = 50,
+ methods: list[FunctionComplexity] | None = None,
+ field_count: int = 0,
+) -> ClassComplexity:
+ methods = methods if methods is not None else [_fn(f"m{i}") for i in range(method_count)]
+ return ClassComplexity(
+ name=name,
+ start_line=1,
+ end_line=1 + total_nloc,
+ method_count=method_count,
+ total_nloc=total_nloc,
+ methods=methods,
+ lcom4=lcom4,
+ max_method_ccn=max((m.ccn for m in methods), default=0),
+ field_count=field_count,
+ )
+
+
+def _ctx(classes: list[ClassComplexity]) -> FileContext:
+ return FileContext(
+ file_path="src/example.py",
+ language="python",
+ nloc=200,
+ has_test_file=False,
+ module=None,
+ class_metrics=classes,
+ )
+
+
+# ---- low_cohesion --------------------------------------------------------
+
+
+def test_low_cohesion_flags_splintered_class():
+ cls = _cls("Splintered", method_count=6, lcom4=3, field_count=4)
+ out = LowCohesionDetector().detect(_ctx([cls]))
+ assert len(out) == 1
+ assert out[0].details["lcom4"] == 3
+ assert out[0].severity == "high" # lcom4 >= 3
+
+
+def test_low_cohesion_severity_critical():
+ cls = _cls("Massive", method_count=16, lcom4=5)
+ out = LowCohesionDetector().detect(_ctx([cls]))
+ assert out[0].severity == "critical" # lcom4 >= 4 AND methods >= 15
+
+
+def test_low_cohesion_skips_cohesive_class():
+ cls = _cls("Cohesive", method_count=8, lcom4=1)
+ assert LowCohesionDetector().detect(_ctx([cls])) == []
+
+
+def test_low_cohesion_skips_tiny_class():
+ # Splintered but too few methods to matter.
+ cls = _cls("Tiny", method_count=3, lcom4=3)
+ assert LowCohesionDetector().detect(_ctx([cls])) == []
+
+
+def test_low_cohesion_no_classes_is_silent():
+ assert LowCohesionDetector().detect(_ctx([])) == []
+
+
+# ---- god_class -----------------------------------------------------------
+
+
+def _brainy_methods() -> list[FunctionComplexity]:
+ methods = [_fn(f"m{i}") for i in range(15)]
+ methods.append(_fn("brain", nloc=90, ccn=12)) # the brain method
+ return methods
+
+
+def test_god_class_flags_large_complex_class():
+ cls = _cls("God", method_count=16, total_nloc=320, methods=_brainy_methods())
+ out = GodClassDetector().detect(_ctx([cls]))
+ assert len(out) == 1
+ assert out[0].details["total_nloc"] == 320
+ assert out[0].severity == "high" # total_nloc >= 300
+
+
+def test_god_class_requires_a_brain_method():
+ # Large + many methods but every method is flat → not a god class.
+ flat = [_fn(f"m{i}", nloc=12, ccn=2) for i in range(16)]
+ cls = _cls("BigButFlat", method_count=16, total_nloc=320, methods=flat)
+ assert GodClassDetector().detect(_ctx([cls])) == []
+
+
+def test_god_class_requires_size_and_method_count():
+ # Has a brain method but is small / few methods.
+ cls = _cls("Small", method_count=4, total_nloc=120, methods=[_fn("brain", nloc=90, ccn=12)])
+ assert GodClassDetector().detect(_ctx([cls])) == []
+
+
+def test_god_class_critical_severity():
+ cls = _cls("Behemoth", method_count=26, total_nloc=450, methods=_brainy_methods())
+ out = GodClassDetector().detect(_ctx([cls]))
+ assert out[0].severity == "critical" # total_nloc >= 400 AND methods >= 25
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index f31c328a3..14300ed1c 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -11,7 +11,7 @@ from pathlib import Path
import pytest
-from repowise.core.analysis.health.complexity import walk_file_complexity
+from repowise.core.analysis.health.complexity import walk_file, walk_file_complexity
FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples"
@@ -26,6 +26,16 @@ def _walk(rel_path: str, language: str):
return results
+def _walk_classes(rel_path: str, language: str):
+ p = FIXTURES / rel_path
+ if not p.exists():
+ pytest.skip(f"fixture missing: {p}")
+ fcx = walk_file(str(p), language, p.read_bytes())
+ if not fcx.classes:
+ pytest.skip(f"tree-sitter language pack missing / no classes for {language}")
+ return {c.name: c for c in fcx.classes}
+
+
def _find(results, name):
matches = [r for r in results if r.name == name]
return matches[0] if matches else None
@@ -105,3 +115,44 @@ def test_rust_flat_match_complexity():
def test_unsupported_language_returns_empty():
results = walk_file_complexity("/tmp/x.unknown", "klingon", b"")
assert results == []
+
+
+# ---- class-level metrics (LCOM4) -----------------------------------------
+
+
+def test_python_class_cohesion():
+ classes = _walk_classes("python/classes.py", "python")
+ cohesive = classes.get("Cohesive")
+ splintered = classes.get("Splintered")
+ 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
+ assert splintered.method_count == 5
+ assert splintered.field_count == 2
+
+
+def test_typescript_class_cohesion():
+ classes = _walk_classes("typescript/classes.ts", "typescript")
+ cohesive = classes.get("Cohesive")
+ splintered = classes.get("Splintered")
+ if cohesive is None or splintered is None:
+ pytest.skip("typescript classes not detected")
+ assert cohesive.lcom4 == 1
+ assert splintered.lcom4 == 3
+
+
+def test_class_metrics_carry_methods_and_size():
+ classes = _walk_classes("python/classes.py", "python")
+ cohesive = classes["Cohesive"]
+ # methods are the same FunctionComplexity objects the function pass found
+ assert len(cohesive.methods) == cohesive.method_count
+ assert cohesive.total_nloc > 0
+ assert cohesive.max_method_ccn >= 1
+
+
+def test_unsupported_language_has_no_classes():
+ fcx = walk_file("/tmp/x.unknown", "klingon", b"")
+ assert fcx.classes == []
+ assert fcx.functions == []
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index fb3e59315..211c79b1f 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -57,6 +57,8 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
_EXPECTED_BIOMARKER_CATEGORY = {
"brain_method": "structural_complexity",
+ "low_cohesion": "structural_complexity",
+ "god_class": "structural_complexity",
"nested_complexity": "structural_complexity",
"bumpy_road": "structural_complexity",
"complex_conditional": "structural_complexity",