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): ignore Python overload stubs in cohesion (#2764)
Ranjanaa684707480cc
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 ae8394698..0a51aa77c 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@@ -19,6 +19,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, NamedTuple+from ....ingestion.python_overload import is_python_overloadfrom ....test_paths import is_test_related_pathfrom .ast_utils import _IDENTIFIER_SUFFIX, _find_namefrom .languages import LanguageNodeMap, get_language_map@@ -91,12 +92,15 @@ def _text(node: Node) -> str:return node.text.decode("utf-8", errors="replace") if node.text is not None else ""-def _collect_class_body(class_node: Node, lmap: LanguageNodeMap) -> _ClassBody:+def _collect_class_body(+ class_node: Node, lmap: LanguageNodeMap, language: str, source: str+) -> _ClassBody:"""Direct method, field-declaration and nested-class nodes of *class_node*.Stops at nested types (their members are not ours) and does not descendinto a method body (nested local defs roll up into the method, mirroring- ``_collect_function_nodes``).+ ``_collect_function_nodes``). Python ``@overload`` stubs are dropped here+ so they never reach the method counts or LCOM4."""body = _ClassBody([], [], [])stack: list[Node] = list(class_node.children)@@ -105,6 +109,8 @@ def _collect_class_body(class_node: Node, lmap: LanguageNodeMap) -> _ClassBody:if node.type in lmap.class_kinds:body.nested.append(node)elif node.type in lmap.function_kinds:+ if language == "python" and is_python_overload(node, source):+ continuebody.methods.append(node)elif node.type in lmap.field_decl_kinds:body.field_decls.append(node)@@ -605,6 +611,7 @@ def _collect_classes(source: bytes,fc_by_node_id: dict[int, FunctionComplexity],code_lines: CodeLineIndex,+ language: str,) -> list[ClassComplexity]:"""Build ``ClassComplexity`` for every class-like node in the file.@@ -613,9 +620,10 @@ def _collect_classes("""if not lmap.class_kinds:return []+ source_str = source.decode("utf-8", errors="replace")classes: list[ClassComplexity] = []for class_node in class_nodes:- body = _collect_class_body(class_node, lmap)+ body = _collect_class_body(class_node, lmap, language, source_str)method_fcs = [fc_by_node_id[m.id] for m in body.methods 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).diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 0be2a45dc..34107f647 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -207,7 +207,9 @@ def walk_file(functions.append(fc)fc_by_node_id[fn_node.id] = fc- classes = _collect_classes(scan.class_nodes, lmap, source, fc_by_node_id, scan.lines)+ classes = _collect_classes(+ scan.class_nodes, lmap, source, fc_by_node_id, scan.lines, language+ )perf_hits, io_boundary_names, perf_fn_facts = _collect_perf_hits(tree.root_node, language, lmap, scan.io_names)diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex fc7a7b592..6b79b97bb 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -118,6 +118,7 @@ from .parser_helpers import (_ts_nested_object_method_owner,)from .python_local_refs import extract_python_local_refs+from .python_overload import is_python_overload as _is_python_overloadfrom .sfc_source import component_call_sites, prepare_sourcefrom .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_specialfrom .symbol_identity import disambiguate_colliding_ids, symbol_discriminator@@ -520,23 +521,6 @@ def _match_identity(return def_node, name_nodes, name, export_type, start_line-# ``@overload`` stubs are signatures for the type checker; the undecorated def-# that follows under the same id is the one that runs.-def _is_python_overload(def_node: Node, src: str) -> bool:- parent = def_node.parent- if parent is None or parent.type != "decorated_definition":- return False- for decorator in parent.children:- if decorator.type != "decorator":- continue- # The expression, not the node text: a trailing comment sits inside it.- expr = next((c for c in decorator.named_children if c.type != "comment"), None)- # ``overload``, ``typing.overload``, or through an alias (``t.overload``).- if expr is not None and _node_text(expr, src).rsplit(".", 1)[-1] == "overload":- return True- return False--_TS_OVERLOAD_SIGNATURES = frozenset({"function_signature", "method_signature"})diff --git a/packages/core/src/repowise/core/ingestion/python_overload.py b/packages/core/src/repowise/core/ingestion/python_overload.pynew file mode 100644index 000000000..629036e8b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/python_overload.py@@ -0,0 +1,23 @@+"""Shared helpers for Python ``@overload`` stubs."""++from __future__ import annotations++from tree_sitter import Node++from .extractors.helpers import node_text+++def is_python_overload(def_node: Node, src: str) -> bool:+ """True when *def_node* is a type-checker-only ``@overload`` signature stub."""+ parent = def_node.parent+ if parent is None or parent.type != "decorated_definition":+ return False+ for decorator in parent.children:+ if decorator.type != "decorator":+ continue+ # The expression, not the node text: a trailing comment sits inside it.+ expr = next((c for c in decorator.named_children if c.type != "comment"), None)+ # ``overload``, ``typing.overload``, or through an alias (``t.overload``).+ if expr is not None and node_text(expr, src).rsplit(".", 1)[-1] == "overload":+ return True+ return Falsediff --git a/tests/unit/health/test_class_biomarkers.py b/tests/unit/health/test_class_biomarkers.pyindex 35d53e69e..f56c20550 100644--- a/tests/unit/health/test_class_biomarkers.py+++ b/tests/unit/health/test_class_biomarkers.py@@ -2,10 +2,12 @@from __future__ import annotations+import pytest+from repowise.core.analysis.health.biomarkers import FileContextfrom repowise.core.analysis.health.biomarkers.god_class import GodClassDetectorfrom repowise.core.analysis.health.biomarkers.low_cohesion import LowCohesionDetector-from repowise.core.analysis.health.complexity import ClassComplexity, FunctionComplexity+from repowise.core.analysis.health.complexity import ClassComplexity, FunctionComplexity, walk_filedef _fn(name: str, *, nloc: int = 5, ccn: int = 1) -> FunctionComplexity:@@ -80,6 +82,38 @@ def test_low_cohesion_no_classes_is_silent():assert LowCohesionDetector().detect(_ctx([])) == []+def test_low_cohesion_skips_overloaded_formatter_class():+ try:+ from repowise.core.ingestion.parser import _get_language+ except Exception:+ pytest.skip("tree-sitter language pack missing for python")+ if _get_language("python") is None:+ pytest.skip("tree-sitter language pack missing for python")++ source = (+ b"from typing import overload\n\n"+ b"class Formatter:\n"+ b" def __init__(self):\n"+ b" self.value = 0\n"+ b" self.other = 1\n\n"+ b" @overload\n"+ b" def format(self, x: int) -> str: ...\n"+ b" @overload\n"+ b" def format(self, x: str) -> str: ...\n"+ b" @overload\n"+ b" def format(self, x: float) -> str: ...\n"+ b" def format(self, x):\n"+ b" return str(self.value) + str(x)\n\n"+ b" def reset(self):\n"+ b" self.other = 0\n"+ )+ fc = walk_file("formatter.py", "python", source)+ assert fc.classes+ fmt = next(c for c in fc.classes if c.name == "Formatter")+ assert fmt.method_count == 3 and fmt.lcom4 == 1+ assert LowCohesionDetector().detect(_ctx([fmt])) == []++# ---- god_class -----------------------------------------------------------diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex cdf45623a..aa28b4a4b 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -346,6 +346,65 @@ def test_python_class_cohesion():assert splintered.field_count == 2+def _formatter_overload_class(overload_decorator: str) -> bytes:+ return (+ f"{overload_decorator}\n\n"+ "class Formatter:\n"+ " def __init__(self):\n"+ " self.value = 0\n"+ " self.other = 1\n\n"+ " @overload\n"+ " def format(self, x: int) -> str: ...\n"+ " @overload\n"+ " def format(self, x: str) -> str: ...\n"+ " @overload\n"+ " def format(self, x: float) -> str: ...\n"+ " def format(self, x):\n"+ " return str(self.value) + str(x)\n\n"+ " def reset(self):\n"+ " self.other = 0\n"+ ).encode()+++def _formatter_class_metrics(source: bytes):+ _require_language("python")+ classes = walk_file("formatter.py", "python", source).classes+ if not classes:+ pytest.skip("tree-sitter language pack missing for python")+ fmt = next((c for c in classes if c.name == "Formatter"), None)+ assert fmt is not None+ return fmt+++def test_python_class_cohesion_ignores_overload_stubs():+ fmt = _formatter_class_metrics(_formatter_overload_class("from typing import overload"))+ assert fmt.method_count == 3+ assert fmt.lcom4 == 1+ assert len(fmt.methods) == 3+++def test_python_class_cohesion_ignores_typing_overload_decorator():+ src = (+ _formatter_overload_class("import typing")+ .decode()+ .replace("@overload\n", "@typing.overload\n")+ )+ fmt = _formatter_class_metrics(src.encode())+ assert fmt.method_count == 3+ assert fmt.lcom4 == 1+++def test_python_class_cohesion_ignores_aliased_overload_decorator():+ src = (+ _formatter_overload_class("import typing as t")+ .decode()+ .replace("@overload\n", "@t.overload\n")+ )+ fmt = _formatter_class_metrics(src.encode())+ assert fmt.method_count == 3+ assert fmt.lcom4 == 1++def test_typescript_class_cohesion():classes = _walk_classes("typescript/classes.ts", "typescript")cohesive = classes.get("Cohesive")