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 primitive_obsession on CLI commands, keyword-only and framework-bound parameters, and same-file overrides (#4758)
Raghav Chamadiya850b5386e72c
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.pyindex 29f8bc1ff..8dfb337da 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py@@ -24,6 +24,11 @@ These narrowings keep the finding to signatures someone can actually fix:is judged on the count alone.- A parameter a framework binds by annotation (``@PathVariable``) is theroute's or the data format's, so only the remaining ones are counted.+- A keyword-only parameter is left out too: every call site names it, so it+ carries none of the argument-order hazard a long positional list does.+- A Click or Typer command's parameters mirror its CLI options, and a Python+ method overriding a base class in the same file keeps the base's+ parameters; both count as a signature set elsewhere.A wide signature only counts as obsession in a file with enough substance to*have* a design (`_MIN_FILE_NLOC`). In a tiny module a long parameter list is@@ -60,7 +65,7 @@ class PrimitiveObsessionDetector:out.append(BiomarkerResult(biomarker_type=self.name,- severity=_severity(fn.param_count - fn.bound_param_count, threshold),+ severity=_severity(_counted(fn), threshold),function_name=fn.name,line_start=fn.start_line,line_end=fn.end_line,@@ -69,10 +74,12 @@ class PrimitiveObsessionDetector:"typed_param_count": typed,"primitive_param_count": primitive,"bound_param_count": fn.bound_param_count,+ "keyword_only_param_count": fn.keyword_only_param_count,},reason=(f"long parameter list: {fn.name} takes {fn.param_count} parameters"+ (f", {fn.bound_param_count} bound by the framework" if fn.bound_param_count else "")+ + (f", {fn.keyword_only_param_count} keyword-only" if fn.keyword_only_param_count else "")+ (f", {primitive} of {typed} typed ones scalars or strings" if typed else "")),)@@ -87,7 +94,7 @@ def _threshold(fn: FunctionComplexity) -> int | None:if fn.is_test_case or fn.signature_fixed:return Nonethreshold = _PARAM_THRESHOLD + (_CTOR_GRACE if fn.is_constructor else 0)- if fn.param_count - fn.bound_param_count < threshold:+ if _counted(fn) < threshold:return Nonetyped = fn.typed_param_countif typed and fn.primitive_param_count * 2 <= typed:@@ -95,6 +102,11 @@ def _threshold(fn: FunctionComplexity) -> int | None:return threshold+def _counted(fn: FunctionComplexity) -> int:+ """Parameters a caller passes by position: framework-bound and keyword-only ones left out."""+ return fn.param_count - fn.bound_param_count - fn.keyword_only_param_count++def _severity(param_count: int, threshold: int) -> Severity:if param_count >= threshold + 4:return Severity.HIGHdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex acc06bd85..d23585ae1 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -383,7 +383,15 @@ _C_SCALARS = frozenset(_PY = LanguageNodeMap(ctor_names=frozenset({"__init__"}),- fixed_signature_markers=frozenset({"override"}),+ # Click and Typer (``@cli.command()``, ``@click.option(...)``): the+ # parameters mirror the command's CLI options.+ fixed_signature_markers=frozenset({"override", "command", "group", "option", "argument"}),+ # FastAPI fills a parameter whose default or ``Annotated`` type calls one+ # of these. Read by callee name only, so a ``pathlib.Path(...)`` default+ # counts too; the cost is one missed finding, never a false one.+ bound_param_markers=frozenset(+ {"Query", "Depends", "Path", "Header", "Body", "Form", "Cookie", "File", "Security"}+ ),scalar_type_names=frozenset({"str", "int", "float", "bool", "bytes"}),function_kinds=frozenset({"function_definition", "async_function_definition"}),lambda_kinds=frozenset({"lambda"}),diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex 248880ab4..b40285b7a 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -57,10 +57,13 @@ class FunctionComplexity:# Of ``param_count``, the ones a framework binds by annotation# (``@PathVariable``); they are in neither count above.bound_param_count: int = 0+ # Of ``param_count``, the ones every call site must pass by name (Python+ # parameters after ``*`` or ``*args``).+ keyword_only_param_count: int = 0# A constructor, by node kind, conventional name, or its type's name.is_constructor: bool = False# The parameter list is set by another declaration (an override, an- # interface or trait implementation, a native binding).+ # interface or trait implementation, a native binding, a CLI command).signature_fixed: bool = False# Per-condition boolean-operator counts collected during the walk.# Empty when no branch/loop carries compound boolean expressions.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/signature.py b/packages/core/src/repowise/core/analysis/health/complexity/signature.pyindex d8a04c5d1..bac4b3615 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/signature.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/signature.py@@ -12,13 +12,16 @@ reads the tree with it.than this declaration, so "group these parameters" is advice nobody can takehere. Read from the declaration's modifier, annotation, attribute anddecorator nodes only, never from its name or from string arguments, so a- function *named* ``override`` is not one.+ function *named* ``override`` is not one. A Python method whose class's+ base, defined in the same file, declares the same name is an override too.- **typed / scalar parameters**: how many parameters declare a type, and howmany of those are a scalar or a string. An untyped parameter is in neithercount.- **bound parameters**: parameters whose own annotation says a framework fillsthem (``@PathVariable``), read the same way as a declaration's markers. Theystay in the declared count and leave the typed and scalar ones.+- **keyword-only parameters**: Python parameters after ``*`` or ``*args``.+ Every call site names them, so they carry no argument-order hazard."""from __future__ import annotations@@ -29,6 +32,8 @@ from typing import TYPE_CHECKINGfrom .ast_utils import _parameter_nodesif TYPE_CHECKING:+ from collections.abc import Iterator+from tree_sitter import Nodefrom .languages import LanguageNodeMap@@ -163,7 +168,80 @@ def is_signature_fixed(fn_node: Node, lmap: LanguageNodeMap) -> bool:return Trueif any(c.type in lmap.explicit_impl_kinds for c in fn_node.children):return True- return _in_trait_impl(fn_node, lmap) or _is_public_api(fn_node, lmap)+ return (+ _in_trait_impl(fn_node, lmap)+ or _is_public_api(fn_node, lmap)+ or _overrides_local_base(fn_node, lmap)+ )+++def _class_of_method(fn_node: Node, lmap: LanguageNodeMap) -> Node | None:+ holder = fn_node+ if holder.parent is not None and holder.parent.type in lmap.decorated_definition_kinds:+ holder = holder.parent+ body = holder.parent+ if body is None or body.parent is None or body.parent.type not in lmap.class_kinds:+ return None+ return body.parent+++def _undecorated(node: Node, lmap: LanguageNodeMap) -> Node:+ if node.type in lmap.decorated_definition_kinds:+ return node.child_by_field_name("definition") or node+ return node+++def _defines(cls: Node, name: str, lmap: LanguageNodeMap) -> bool:+ body = cls.child_by_field_name("body")+ members = (_undecorated(c, lmap) for c in (body.named_children if body is not None else ()))+ return any(m.type in lmap.function_kinds and _field_text(m, "name") == name for m in members)+++def _field_text(node: Node, field: str) -> str | None:+ child = node.child_by_field_name(field)+ return _text(child) if child is not None else None+++def _module_classes(node: Node, lmap: LanguageNodeMap) -> dict[str | None, Node]:+ root = node+ while root.parent is not None:+ root = root.parent+ tops = (_undecorated(c, lmap) for c in root.named_children)+ return {_field_text(c, "name"): c for c in tops if c.type in lmap.class_kinds}+++def _local_bases(cls: Node, module: dict[str | None, Node]) -> Iterator[Node]:+ """Every ancestor of *cls* named by a plain identifier and defined in *module*.++ A base must be defined above the class naming it: ``class Foo(Foo)`` that+ shadows an imported ``Foo`` names the import, not itself.+ """+ seen: set[str] = set()+ pending = [cls]+ while pending:+ current = pending.pop()+ bases = current.child_by_field_name("superclasses")+ for base in bases.named_children if bases is not None else ():+ name = _text(base)+ found = module.get(name) if base.type == "identifier" and name not in seen else None+ if found is not None and found.start_byte < current.start_byte:+ seen.add(name)+ pending.append(found)+ yield found+++def _overrides_local_base(fn_node: Node, lmap: LanguageNodeMap) -> bool:+ """A Python method whose name a base class in the same module declares.++ Reads the grammar's ``superclasses`` field, which only Python has, and+ module-level classes only; a base imported from elsewhere is not followed.+ """+ cls = _class_of_method(fn_node, lmap)+ name = _field_text(fn_node, "name")+ if cls is None or name is None or cls.child_by_field_name("superclasses") is None:+ return False+ module = _module_classes(cls, lmap)+ return any(_defines(base, name, lmap) for base in _local_bases(cls, module))def _param_type(param: Node) -> Node | None:@@ -221,7 +299,43 @@ def _is_bound(param: Node, lmap: LanguageNodeMap) -> bool:prev = param.prev_named_siblingif prev is not None and prev.type == "parameter_modifiers":words |= _leaf_words([prev])- return bool(words & lmap.bound_param_markers)+ return bool(words & lmap.bound_param_markers) or _bound_by_call(param, lmap)+++def _bound_by_call(param: Node, lmap: LanguageNodeMap) -> bool:+ """A Python parameter a framework fills through a marker call, as its+ default (``x: int = Query(0)``) or in its ``Annotated[...]`` type."""+ stack = [n for n in (param.child_by_field_name("value"), param.child_by_field_name("type")) if n]+ while stack:+ node = stack.pop()+ if node.type == "call":+ callee = _text(node.child_by_field_name("function") or node)+ if callee.rsplit(".", 1)[-1] in lmap.bound_param_markers:+ return True+ if node.type in ("type", "generic_type", "subscript", "type_parameter"):+ stack.extend(node.named_children)+ return False+++def keyword_only_param_count(params: Node | None, lmap: LanguageNodeMap) -> int:+ """Python parameters after a bare ``*`` or ``*args``, ``**kwargs`` included.+ A framework-bound one is left out: ``bound_param_count`` has it."""+ if params is None:+ return 0+ count = 0+ seen_star = False+ for param in _parameter_nodes(params):+ if seen_star:+ count += not _is_bound(param, lmap)+ elif param.type == "keyword_separator" or _is_args_splat(param):+ seen_star = True+ return count+++def _is_args_splat(param: Node) -> bool:+ # ``*args: int`` wraps the splat in a ``typed_parameter``.+ first = param.named_children[0] if param.type == "typed_parameter" else param+ return first.type == "list_splat_pattern"def bound_param_count(params: Node | None, lmap: LanguageNodeMap) -> int:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex e8e15aaff..89be85838 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -84,7 +84,13 @@ from .models import (# which imports it directly from this module.from .nloc import _count_file_nlocfrom .perf_walk import _collect_perf_hits, perf_pass_runs-from .signature import bound_param_count, is_constructor, is_signature_fixed, typed_param_counts+from .signature import (+ bound_param_count,+ is_constructor,+ is_signature_fixed,+ keyword_only_param_count,+ typed_param_counts,+)from .test_case import is_test_caseif TYPE_CHECKING:@@ -227,6 +233,7 @@ def walk_file(typed_param_count=typed,primitive_param_count=scalar,bound_param_count=bound_param_count(params, lmap),+ keyword_only_param_count=keyword_only_param_count(params, lmap),is_constructor=is_constructor(fn_node, name, lmap),signature_fixed=is_signature_fixed(fn_node, lmap),complex_conditions=conditions,diff --git a/tests/unit/health/test_primitive_obsession_scope.py b/tests/unit/health/test_primitive_obsession_scope.pyindex 353be2f4c..37f183d9c 100644--- a/tests/unit/health/test_primitive_obsession_scope.py+++ b/tests/unit/health/test_primitive_obsession_scope.py@@ -34,3 +34,19 @@ def test_a_helper_in_test_material_is_not_flagged(path: str, is_test: bool | Nondef test_the_same_signature_in_production_code_is_flagged() -> None:[finding] = PrimitiveObsessionDetector().detect(_ctx("src/graph.py", False))assert finding.function_name == "_add_edge"++[email protected](("keyword_only", "flagged"), [(2, False), (1, True)])+def test_keyword_only_parameters_are_not_counted(keyword_only: int, flagged: bool) -> None:+ helper = FunctionComplexity(+ "configure", 1, 12, ccn=1, max_nesting=0, cognitive=0, nloc=10,+ param_count=6, keyword_only_param_count=keyword_only,+ )+ ctx = FileContext(+ file_path="src/app.py", language="python", nloc=80, has_test_file=False, module=None,+ is_test=False, all_functions=(helper, _FILLER),+ )+ findings = PrimitiveObsessionDetector().detect(ctx)+ assert bool(findings) is flagged+ if findings:+ assert findings[0].reason.endswith("takes 6 parameters, 1 keyword-only")diff --git a/tests/unit/health/test_signature_facts.py b/tests/unit/health/test_signature_facts.pyindex 3ff5c733a..8edb70166 100644--- a/tests/unit/health/test_signature_facts.py+++ b/tests/unit/health/test_signature_facts.py@@ -287,3 +287,88 @@ def test_kotlin_constructor_parameter_list():ctor = next(c for c in body.named_children if c.type == "secondary_constructor")assert _count_parameters(ctor) == 2assert typed_param_counts(_parameter_list(ctor), get_language_map("kotlin")) == (2, 2)+++ "decorators",+ [+ "@click.command()\[email protected]('--a')\[email protected]('b')\n",+ "@cli.group()\n",+ "@app.command()\n",+ "@click.option('--a')\n",+ ],+)+def test_python_cli_command_signatures_are_fixed(decorators: str):+ fns = _fns("cli.py", "python", f"{decorators}def run({FIVE}):\n pass\n")+ assert fns["run"].signature_fixed+++def test_python_cli_marker_in_a_string_argument_fixes_nothing():+ fns = _fns("a.py", "python", f"@register('command')\ndef run({FIVE}):\n pass\n")+ assert not fns["run"].signature_fixed+++ ("signature", "keyword_only"),+ [+ (f"a, *, {FIVE}", 5),+ (f"a, *args: int, {FIVE}, **kw", 6),+ (f"a, *args, {FIVE}", 5),+ (f"{FIVE}, **kw", 0),+ (f"a, /, {FIVE}", 0),+ ],+)+def test_python_keyword_only_parameter_count(signature: str, keyword_only: int):+ fns = _fns("a.py", "python", f"def f({signature}):\n pass\n")+ assert fns["f"].keyword_only_param_count == keyword_only+++def test_python_method_overriding_a_base_in_the_same_file_is_fixed():+ source = (+ "class Base:\n"+ f" def run(self, {FIVE}):\n pass\n"+ "class Middle(Base):\n"+ " pass\n"+ "@dataclass\n"+ "class Child(Middle, metaclass=M):\n"+ " @cache\n"+ f" def run(self, {FIVE}):\n pass\n"+ f" def walk(self, {FIVE}):\n pass\n"+ "class Other(Imported):\n"+ f" def run(self, {FIVE}):\n pass\n"+ )+ fns = walk_file("a.py", "python", source.encode()).functions+ fixed = {(f.name, f.start_line): f.signature_fixed for f in fns}+ # The base itself, an override reached through Middle, a name Base lacks,+ # and a base imported from elsewhere, which is not followed.+ assert fixed == {+ ("run", 2): False,+ ("run", 9): True,+ ("walk", 11): False,+ ("run", 14): False,+ }+++def test_python_class_shadowing_an_imported_base_is_not_its_own_base():+ fns = _fns(+ "a.py",+ "python",+ f"from x import Foo\nclass Foo(Foo):\n def run(self, {FIVE}):\n pass\n",+ )+ assert not fns["run"].signature_fixed+++def test_python_fastapi_bound_parameters():+ fns = _fns(+ "routes.py",+ "python",+ "async def route(repo_id: str, limit: int = Query(200), q: Annotated[str, Query()] = '',\n"+ " s: Session = fastapi.Depends(get_db), name: str = 'x', *, h: str = Header(None),\n"+ " when: str = default_when()):\n pass\n",+ )+ route = fns["route"]+ assert route.param_count == 7+ assert route.bound_param_count == 4+ # ``h`` is bound, so the keyword-only count leaves it to ``bound_param_count``.+ assert route.keyword_only_param_count == 1+ assert (route.typed_param_count, route.primitive_param_count) == (3, 3)diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.pyindex 6150bafd6..b58f7e25d 100644--- a/tests/unit/health/test_structural_biomarkers.py+++ b/tests/unit/health/test_structural_biomarkers.py@@ -98,7 +98,7 @@ def test_primitive_obsession_finds_cpp_scalar_signature():assert finding.function_name == "f"assert finding.details == {"param_count": 7, "typed_param_count": 7, "primitive_param_count": 7,- "bound_param_count": 0,+ "bound_param_count": 0, "keyword_only_param_count": 0,}