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.

fix(dead-code): cut ~390 false positives across resolver, parser, and analyzer (#207)

Raghav Chamadiya52b781c8a453
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index a54b3645c..e1f90c9c8 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -122,7 +122,7 @@ def dead_code_command(
traverser = FileTraverser(repo_path)
file_infos = list(traverser.traverse())
parser = ASTParser()
- graph_builder = GraphBuilder()
+ graph_builder = GraphBuilder(repo_path)
for fi in file_infos:
try:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index 2c7a68c79..c9df4c316 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -377,7 +377,7 @@ def update_command(
parser = ASTParser()
parsed_files = []
source_map: dict[str, bytes] = {}
- graph_builder = GraphBuilder()
+ graph_builder = GraphBuilder(repo_path)
for fi in file_infos:
try:
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 909dd8ac2..c7b3c2719 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -608,7 +608,7 @@ def _generate_docs_for_added_repo(
file_infos = list(traverser.traverse())
repo_structure = traverser.get_repo_structure()
parser = ASTParser()
- graph_builder = GraphBuilder()
+ graph_builder = GraphBuilder(repo_path)
parsed_files = []
source_map: dict = {}
for fi in file_infos:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 1a3d77d70..c1f0b0717 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -20,6 +20,7 @@ import structlog
from .constants import (
_DEFAULT_DYNAMIC_PATTERNS,
+ _FRAMEWORK_DECORATOR_SUFFIXES,
_FRAMEWORK_DECORATORS,
_NEVER_FLAG_PATTERNS,
_NEVER_PACKAGE_DIRS,
@@ -93,6 +94,24 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
"Startup", # ASP.NET Core legacy
"__module__", # synthetic per-file module anchor
"_start", # C runtime
+ # ---- Python WSGI / ASGI / app-factory conventions ---------------
+ # Loaded by external servers (uvicorn / gunicorn / hypercorn /
+ # Tornado / aiohttp / Django) via dotted-path string such as
+ # ``module:create_app`` or ``module:application``. The graph never
+ # sees a call edge from the launching server, so without this
+ # allowlist every web entry point shows up as an unused public
+ # symbol with 1.0 confidence.
+ "create_app",
+ "make_app",
+ "create_application",
+ "make_application",
+ "application",
+ "asgi_app",
+ "wsgi_app",
+ "asgi_application",
+ "wsgi_application",
+ "get_asgi_application",
+ "get_wsgi_application",
# ---- Windows DLL / COM entry points -----------------------------
# Invoked by the Windows loader or COM runtime; never referenced
# statically from user code.
@@ -408,6 +427,25 @@ class DeadCodeAnalyzer:
file_has_importers = self.graph.in_degree(node) > 0
+ # Dispatch-table / namespace-import rescue at the file level:
+ # if any importer pulled this file by its module name
+ # (``from . import cargo``, ``import * as cargo from
+ # "./cargo"``), every public symbol in the file is reachable
+ # via ``cargo.<attr>`` and we cannot tell statically which
+ # attribute is being called. Treat all public symbols as live.
+ # Generic across Python and TS/JS — no repo-specific assumptions.
+ file_stem = Path(str(node)).stem
+ file_imported_as_namespace = False
+ if file_stem and file_stem not in ("__init__", "index"):
+ for pred in self.graph.predecessors(node):
+ edge = self.graph.get_edge_data(pred, node, {})
+ if edge.get("edge_type") != "imports":
+ continue
+ imported = edge.get("imported_names", [])
+ if file_stem in imported:
+ file_imported_as_namespace = True
+ break
+
# Dynamic-use edges (DI registration, reflection, event bus
# subscriptions, framework-mediated loading) target a file
# as a whole — the runtime resolves the class and reaches
@@ -473,15 +511,30 @@ class DeadCodeAnalyzer:
continue
# Decorators are stored with the leading "@" (e.g. "@app.route").
- # _FRAMEWORK_DECORATORS entries are bare prefixes, so compare
- # against the stripped form.
+ # _FRAMEWORK_DECORATORS entries are bare prefixes; suffixes
+ # like ``.command`` match locally-named Click groups
+ # (``@my_group.command("add")``). Compare against the
+ # stripped form, and strip any call ``(...)`` tail so the
+ # suffix check sees the attribute path itself.
decorators = sym.get("decorators", [])
+
+ def _decorator_base(d: str) -> str:
+ stripped = d.lstrip("@")
+ paren = stripped.find("(")
+ return stripped[:paren] if paren >= 0 else stripped
+
if any(
- d.lstrip("@").startswith(prefix)
+ _decorator_base(d).startswith(prefix)
for d in decorators
for prefix in _FRAMEWORK_DECORATORS
):
continue
+ if any(
+ _decorator_base(d).endswith(suffix)
+ for d in decorators
+ for suffix in _FRAMEWORK_DECORATOR_SUFFIXES
+ ):
+ continue
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
@@ -501,6 +554,13 @@ class DeadCodeAnalyzer:
if has_importers:
continue
+ # Namespace-import rescue: see ``file_imported_as_namespace``
+ # computation above. Any public symbol in a file pulled by
+ # module name could be the dispatch target for
+ # ``<modname>.<attr>(...)``.
+ if file_imported_as_namespace:
+ continue
+
# Symbol-level usage signal: any incoming ``calls`` /
# ``method_implements`` / ``reads`` edge means somewhere
# in the codebase actually uses this symbol — even if
@@ -625,6 +685,26 @@ class DeadCodeAnalyzer:
if has_callers:
continue
+ # Dispatch-table pattern: a private helper imported by name
+ # into a sibling module and stored in a lookup dict
+ # (``HANDLERS = {"python": _extract_python_heritage, ...}``).
+ # The function is reached at runtime via dict lookup, so no
+ # direct ``calls`` edge ever lands in the graph — but the
+ # ``imports`` edge into its file carries the symbol name. If
+ # any cross-file importer pulled this symbol by name,
+ # something is actively referencing it; do not flag.
+ file_pred_imports = False
+ for pred in self.graph.predecessors(file_path):
+ edge = self.graph.get_edge_data(pred, file_path, {})
+ if edge.get("edge_type") != "imports":
+ continue
+ imported = edge.get("imported_names", [])
+ if sym_name in imported or "*" in imported:
+ file_pred_imports = True
+ break
+ if file_pred_imports:
+ continue
+
git_meta = self.git_meta_map.get(file_path, {})
findings.append(
DeadCodeFindingData(
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index ecbf10cb6..6ef12caf6 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -25,6 +25,12 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*__main__.py",
"*conftest.py",
"*alembic/env.py",
+ # Alembic migration scripts live in <root>/versions/<rev>_<slug>.py and
+ # are loaded reflectively by Alembic at runtime from script_location in
+ # alembic.ini — they have no static importer by design. The legacy
+ # ``*migrations*`` glob only matches paths that literally contain the
+ # token ``migrations``; many Alembic setups use ``alembic/versions/``.
+ "*/alembic/versions/*.py",
"*manage.py",
"*wsgi.py",
"*asgi.py",
@@ -219,6 +225,27 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = (
"typer.callback",
)
+# Decorator *suffixes* that indicate framework registration regardless of
+# the receiver name. Many Click/Typer codebases register subcommands on a
+# locally-named Group instance, e.g.::
+#
+# decision_group = click.Group(...)
+#
+# @decision_group.command("add")
+# def decision_add(): ...
+#
+# The decorator is captured as ``decision_group.command`` — its prefix is
+# project-local, but its trailing attribute (``.command``) is a strong
+# signal that the wrapped function is registered with a framework
+# dispatcher and not called by name. Matching the suffix catches every
+# Click ``Group`` / Typer ``Typer`` / aiogram ``Dispatcher`` / aiohttp
+# ``RouteTableDef`` etc. without hard-coding receiver names.
+_FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (
+ ".command",
+ ".group",
+ ".callback",
+)
+
# Default dynamic patterns (plugins, handlers, etc.)
_DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = (
"*Plugin",
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py
index b08740b32..d4ff7b408 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from tree_sitter import Node
-from ...models import NamedBinding
+from ...models import Import, NamedBinding
from ..helpers import node_text
@@ -75,3 +75,51 @@ def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[
)
return names, bindings
+
+
+def expand_bare_relative_imports(imports: list[Import]) -> list[Import]:
+ """Split ``from . import a, b`` into one Import per imported submodule.
+
+ Tree-sitter captures the module as a lone ``relative_import`` (``.`` or
+ ``..``) with no module suffix, so the resolver receives ``module_path=".".``
+ The relative-import branch of :func:`resolve_python_import` requires a
+ non-empty module name and bails out — silently dropping every plugin /
+ registry barrel that uses bare-submodule imports (``from . import npm,
+ pypi, cargo, go, nuget`` in ``external_systems/__init__.py`` is the
+ canonical example).
+
+ Rewriting each name into its own ``.<name>`` (or ``..<name>``) Import lets
+ the existing resolver locate the sibling submodule without any new
+ language branches downstream.
+ """
+ out: list[Import] = []
+ for imp in imports:
+ stripped = imp.module_path.strip(".")
+ is_bare = (
+ imp.is_relative
+ and stripped == ""
+ and imp.module_path # not the empty string
+ and imp.imported_names
+ and imp.imported_names != ["*"]
+ )
+ if not is_bare:
+ out.append(imp)
+ continue
+
+ dots = imp.module_path # e.g. ".", ".."
+ bindings_by_name = {b.local_name: b for b in imp.bindings}
+ for name in imp.imported_names:
+ binding = bindings_by_name.get(name) or NamedBinding(
+ local_name=name, exported_name=None, source_file=None, is_module_alias=True
+ )
+ out.append(
+ Import(
+ raw_statement=imp.raw_statement,
+ module_path=f"{dots}{name}",
+ imported_names=[name],
+ is_relative=True,
+ resolved_file=None,
+ bindings=[binding],
+ )
+ )
+ return out
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 79112251e..50f15efa3 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -43,6 +43,7 @@ from .extractors import (
refine_go_type_kind,
refine_kotlin_class_kind,
)
+from .extractors.bindings.python import expand_bare_relative_imports
from .extractors.synthetic_symbols import extract_synthetic_symbols
from .extractors.visibility import (
csharp_visibility,
@@ -81,14 +82,18 @@ QUERIES_DIR = Path(__file__).parent / "queries"
@lru_cache(maxsize=None)
-def _load_compiled_query(lang: str) -> object | None:
- """Process-wide cache of compiled tree-sitter Query objects by language tag.
+def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:
+ """Process-wide cache of compiled tree-sitter Query objects.
Compiling `.scm` queries is non-trivial; in process-pool parsing each worker
- would otherwise recompile per file. Keyed by lang because `_get_language`
- returns a stable Language singleton per tag within a process.
+ would otherwise recompile per file. ``grammar_tag`` may differ from
+ ``lang`` when a language reuses another's grammar at a different
+ variant — e.g. ``.tsx`` files reuse ``typescript.scm`` but must bind
+ to the JSX-aware ``tsx`` grammar so React components don't drown in
+ ERROR nodes.
"""
- language = _get_language(lang)
+ grammar = grammar_tag or lang
+ language = _get_language(grammar)
if language is None:
return None
@@ -98,6 +103,13 @@ def _load_compiled_query(lang: str) -> object | None:
return None
scm_text = scm_path.read_text(encoding="utf-8")
+ # Grammar-variant-specific additions (e.g. JSX node captures that are
+ # only valid against the ``tsx`` grammar but not the plain ``typescript``
+ # one). Appended to the base SCM only when the variant scm file exists.
+ if grammar_tag and grammar_tag != lang:
+ extra_scm = QUERIES_DIR / f"{grammar_tag}.scm"
+ if extra_scm.exists():
+ scm_text = scm_text + "\n" + extra_scm.read_text(encoding="utf-8")
try:
from tree_sitter import Query # type: ignore[attr-defined]
@@ -518,7 +530,12 @@ class ASTParser:
"""Parse *source* bytes and return a fully populated ParsedFile."""
lang = file_info.language
config = LANGUAGE_CONFIGS.get(lang)
- language = _get_language(lang)
+ # .tsx files need the JSX-aware grammar; tree-sitter-typescript's
+ # default `language_typescript` errors out on every `<Component />`
+ # and the resulting ERROR-node recovery hoists nested helpers
+ # (handlers defined inside component bodies) to the top level.
+ grammar_tag = "tsx" if lang == "typescript" and file_info.path.endswith(".tsx") else lang
+ language = _get_language(grammar_tag)
if config is None or language is None:
if config is not None and language is None:
@@ -548,7 +565,7 @@ class ASTParser:
root = tree.root_node
parse_errors = _collect_error_nodes(root)
- query = self._get_query(lang, language)
+ query = self._get_query(lang, language, grammar_tag)
symbols = self._extract_symbols(tree, query, config, file_info, src)
# Per-language synthetic-symbol pass — recognises source-generator
@@ -591,9 +608,9 @@ class ASTParser:
# Query loading
# ------------------------------------------------------------------
- def _get_query(self, lang: str, language: Language) -> object | None:
+ def _get_query(self, lang: str, language: Language, grammar_tag: str | None = None) -> object | None:
"""Load and cache the compiled tree-sitter Query for *lang*."""
- return _load_compiled_query(lang)
+ return _load_compiled_query(lang, grammar_tag)
# ------------------------------------------------------------------
# Symbol extraction
@@ -640,6 +657,17 @@ class ASTParser:
if kind is None:
continue
+ # Skip symbols nested inside another function/method body. The
+ # Tree-sitter query is recursive, so helpers defined inside a
+ # React component or an async orchestrator method get hoisted
+ # to the top-level symbol list and read as unused public
+ # exports. Filtering by callable ancestor restricts extraction
+ # to module-top-level + class-body members. Class bodies don't
+ # match (``class_definition`` is not callable), so methods are
+ # preserved.
+ if _has_callable_ancestor(def_node, config.symbol_node_types):
+ continue
+
# Refine "struct" kind for Go type_spec (check if struct or interface body)
if kind == "struct" and config.parent_extraction == "receiver":
kind = refine_go_type_kind(def_node, src)
@@ -802,6 +830,9 @@ class ASTParser:
)
)
+ if file_info.language == "python":
+ imports = expand_bare_relative_imports(imports)
+
return imports
# ------------------------------------------------------------------
@@ -1002,6 +1033,25 @@ def _is_async_node(node: Node, src: str) -> bool:
return node.type == "async_function_definition" or any(c.type == "async" for c in node.children)
+_CALLABLE_KINDS: frozenset[str] = frozenset({"function", "method"})
+
+
+def _has_callable_ancestor(node: Node, symbol_kinds: dict[str, str]) -> bool:
+ """True if ``node`` has any function/method ancestor in the AST.
+
+ Used to filter out helpers defined inside another function's body
+ (React event handlers, async-method-local coroutines, JS closures)
+ from the top-level symbol list. Class bodies don't count — methods
+ inside classes have only a ``class`` ancestor before the module root.
+ """
+ ancestor = node.parent
+ while ancestor is not None:
+ if symbol_kinds.get(ancestor.type) in _CALLABLE_KINDS:
+ return True
+ ancestor = ancestor.parent
+ return False
+
+
def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:
"""Return the parent class for a C/C++ ``Class::method`` definition.
diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
index 20c78d359..a323d66a0 100644
--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
@@ -77,3 +77,17 @@
constructor: (identifier) @call.target
arguments: (arguments) @call.arguments
) @call.site
+
+; ---------------------------------------------------------------------------
+; JSX element usage (treated as a call to the component)
+; ---------------------------------------------------------------------------
+
+; <Component ... />
+(jsx_self_closing_element
+ name: (identifier) @call.target
+) @call.site
+
+; <Component ... > ... </Component>
+(jsx_opening_element
+ name: (identifier) @call.target
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/tsx.scm b/packages/core/src/repowise/core/ingestion/queries/tsx.scm
new file mode 100644
index 000000000..6d869b334
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/queries/tsx.scm
@@ -0,0 +1,21 @@
+; =============================================================================
+; repowise — TSX-grammar-only additions to the TypeScript query
+; Appended to typescript.scm by parser._load_compiled_query when the
+; grammar variant is ``tsx``. The plain ``typescript`` grammar does not
+; define JSX node types, so these captures live here instead of in
+; typescript.scm.
+; =============================================================================
+
+; ---------------------------------------------------------------------------
+; JSX element usage (treated as a call to the component)
+; ---------------------------------------------------------------------------
+
+; <Component ... />
+(jsx_self_closing_element
+ name: (identifier) @call.target
+) @call.site
+
+; <Component ... > ... </Component>
+(jsx_opening_element
+ name: (identifier) @call.target
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
index 04f43664a..e8d159bd4 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -5,18 +5,131 @@ Reads the root ``package.json``'s ``workspaces`` field (string list or
sibling package's ``name`` field. The resulting ``{pkg_name: dir_posix}``
map lets the TS resolver turn ``import x from "@myorg/foo"`` into the
correct intra-repo file rather than an ``external:`` node.
+
+Subpath imports (``@myorg/foo/bar/baz``) honour Node.js ``"exports"``
+subpath patterns when the workspace's ``package.json`` declares them:
+
+ "exports": {
+ ".": "./src/index.ts",
+ "./util": "./src/util.ts",
+ "./graph/*": "./src/graph/*.tsx",
+ "./modules/*": { "import": "./src/modules/*.ts" }
+ }
+
+Conditional values (``{"import": ..., "default": ..., ...}``) are
+flattened to the first plausible source target. Packages without an
+``exports`` field fall back to the legacy ``<pkg>/<subpath>`` probe so
+"plain" monorepo layouts keep working.
"""
from __future__ import annotations
import json
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .context import ResolverContext
+# Order in which we collapse Node "conditional exports" objects down to
+# a single target. Source-pointing conditions come first so a TS-aware
+# static analyser sees the original ``.ts`` file rather than a built
+# artefact, then ESM/default, with CJS last.
+_CONDITION_PRIORITY: tuple[str, ...] = (
+ "source",
+ "import",
+ "default",
+ "node",
+ "require",
+ "types",
+ "browser",
+)
+
+
+def _flatten_export_value(value: Any) -> str | None:
+ """Collapse a Node ``exports`` entry to a single relative target string.
+
+ Returns ``None`` for blocked entries (``null``) or shapes we can't
+ handle. Recursively unwraps nested condition objects and arrays.
+ """
+ if isinstance(value, str):
+ return value
+ if isinstance(value, dict):
+ for cond in _CONDITION_PRIORITY:
+ inner = value.get(cond)
+ if inner is None:
+ continue
+ flat = _flatten_export_value(inner)
+ if flat:
+ return flat
+ return None
+ if isinstance(value, list):
+ for item in value:
+ flat = _flatten_export_value(item)
+ if flat:
+ return flat
+ return None
+
+
+def _build_exports_map(pkg_data: dict) -> dict[str, str]:
+ """Return ``{exports_key: relative_target}`` for a workspace package.
+
+ ``exports`` may be a single string (shorthand for ``{".": <str>}``)
+ or a subpath dict. Keys that don't start with ``.`` are dropped (the
+ Node spec disallows mixing main-entry shorthand with subpath maps).
+ """
+ raw = pkg_data.get("exports")
+ if raw is None:
+ return {}
+ if isinstance(raw, str):
+ return {".": raw}
+ if not isinstance(raw, dict):
+ return {}
+ out: dict[str, str] = {}
+ for key, value in raw.items():
+ if not isinstance(key, str) or not key.startswith("."):
+ continue
+ flat = _flatten_export_value(value)
+ if flat is None:
+ continue
+ out[key] = flat
+ return out
+
+
+def _match_export_key(subpath: str, exports_map: dict[str, str]) -> str | None:
+ """Resolve a subpath against an ``exports`` map.
+
+ ``subpath`` is the part of the import specifier after the package
+ name, with no leading slash (``""`` for the bare package, ``"lib/x"``
+ for ``@org/pkg/lib/x``). Exact keys win over wildcard patterns; among
+ wildcards the longest static prefix wins (Node spec).
+ """
+ key = "." if subpath == "" else "./" + subpath
+ if key in exports_map:
+ return exports_map[key]
+ best_target: str | None = None
+ best_prefix_len = -1
+ for pattern, target in exports_map.items():
+ if "*" not in pattern:
+ continue
+ prefix, _, suffix = pattern.partition("*")
+ if not key.startswith(prefix):
+ continue
+ if suffix and not key.endswith(suffix):
+ continue
+ captured = (
+ key[len(prefix) : len(key) - len(suffix)]
+ if suffix
+ else key[len(prefix) :]
+ )
+ resolved = target.replace("*", captured, 1) if "*" in target else target
+ if len(prefix) > best_prefix_len:
+ best_target = resolved
+ best_prefix_len = len(prefix)
+ return best_target
+
+
def _read_workspaces_field(pkg_data: dict) -> list[str]:
ws = pkg_data.get("workspaces")
if isinstance(ws, list):
@@ -33,6 +146,18 @@ def build_workspace_map(repo_path: Path | None) -> dict[str, str]:
Empty dict if no root ``package.json`` or no ``workspaces`` field.
"""
+ return {name: info["dir"] for name, info in build_workspace_info(repo_path).items()}
+
+
+def build_workspace_info(repo_path: Path | None) -> dict[str, dict[str, Any]]:
+ """Return ``{pkg_name: {"dir": <posix>, "exports": {...}, "main": str|None}}``.
+
+ A richer counterpart to :func:`build_workspace_map` that also carries
+ the workspace package's ``exports`` subpath map (Node.js spec) plus
+ ``main``/``module`` entry-point hints. Lets the resolver translate
+ sub-path imports through the package's own resolution rules instead
+ of probing ``<pkg>/<subpath>`` blindly.
+ """
if repo_path is None or not repo_path.is_dir():
return {}
root_pkg = repo_path / "package.json"
@@ -48,7 +173,7 @@ def build_workspace_map(repo_path: Path | None) -> dict[str, str]:
if not patterns:
return {}
- result: dict[str, str] = {}
+ result: dict[str, dict[str, Any]] = {}
for pattern in patterns:
# Glob each pattern relative to the repo root. ``pathlib.Path.glob``
# already understands ``*`` and ``**``.
@@ -71,69 +196,112 @@ def build_workspace_map(repo_path: Path | None) -> dict[str, str]:
rel = ws_dir.relative_to(repo_path).as_posix()
except ValueError:
continue
- result[name] = rel
+ result[name] = {
+ "dir": rel,
+ "exports": _build_exports_map(ws_data),
+ "main": ws_data.get("module") if isinstance(ws_data.get("module"), str)
+ else (ws_data.get("main") if isinstance(ws_data.get("main"), str) else None),
+ }
return result
-def get_or_build_workspace_map(ctx: "ResolverContext") -> dict[str, str]:
- cached = getattr(ctx, "_ts_workspace_map", None)
+def get_or_build_workspace_info(ctx: "ResolverContext") -> dict[str, dict[str, Any]]:
+ cached = getattr(ctx, "_ts_workspace_info", None)
if cached is not None:
return cached
- mapping = build_workspace_map(ctx.repo_path)
- ctx._ts_workspace_map = mapping # type: ignore[attr-defined]
- return mapping
+ info = build_workspace_info(ctx.repo_path)
+ ctx._ts_workspace_info = info # type: ignore[attr-defined]
+ return info
+
+
+def get_or_build_workspace_map(ctx: "ResolverContext") -> dict[str, str]:
+ """Backward-compat shim — kept for callers that only need name → dir."""
+ return {name: info["dir"] for name, info in get_or_build_workspace_info(ctx).items()}
+
+
+_PROBE_EXTENSIONS: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")
+
+
+def _probe_path(base: str, path_set: set[str]) -> str | None:
+ """Locate a concrete file for ``base`` (a repo-relative path stem).
+
+ Tries the path as-is first (handles targets that already carry an
+ extension, e.g. ``"./src/graph/sigma-canvas.tsx"`` from an exports
+ pattern). Then probes common TS/JS extensions and ``index.*``
+ children so directory-shaped specifiers resolve to a barrel file.
+ """
+ if base in path_set:
+ return base
+ for ext in _PROBE_EXTENSIONS:
+ cand = base + ext
+ if cand in path_set:
+ return cand
+ for ext in _PROBE_EXTENSIONS:
+ cand = f"{base}/index{ext}"
+ if cand in path_set:
+ return cand
+ return None
def resolve_via_workspaces(module_path: str, ctx: "ResolverContext") -> str | None:
"""Resolve a bare specifier (``@scope/pkg`` or ``@scope/pkg/sub/file``)
- against the workspace map. Returns a repo-relative path or None.
+ against the workspace map. Honours each workspace's ``exports``
+ subpath map (Node.js spec) before falling back to a ``<pkg>/<subpath>``
+ probe so plain monorepo layouts without ``exports`` keep working.
+ Returns a repo-relative path or None.
"""
- mapping = get_or_build_workspace_map(ctx)
- if not mapping:
+ info = get_or_build_workspace_info(ctx)
+ if not info:
return None
# Match the longest package-name prefix. ``@scope/pkg/sub/x`` should bind
# ``@scope/pkg`` and resolve ``sub/x`` under that workspace's dir.
- best: tuple[str, str] | None = None
- for name, dir_posix in mapping.items():
+ best_name: str | None = None
+ for name in info:
if module_path == name or module_path.startswith(name + "/"):
- if best is None or len(name) > len(best[0]):
- best = (name, dir_posix)
- if best is None:
+ if best_name is None or len(name) > len(best_name):
+ best_name = name
+ if best_name is None:
return None
- name, dir_posix = best
- sub = module_path[len(name) :].lstrip("/")
- base = f"{dir_posix}/{sub}" if sub else dir_posix
- # When the import lacks an explicit file path, target the package's
- # entry point. Try ``index.{ts,tsx,js,jsx}``.
+ pkg = info[best_name]
+ dir_posix: str = pkg["dir"]
+ exports_map: dict[str, str] = pkg["exports"]
+ sub = module_path[len(best_name) :].lstrip("/")
+
+ # 1) ``exports`` field — the package's authoritative subpath map.
+ if exports_map:
+ target = _match_export_key(sub, exports_map)
+ if target is not None:
+ # Targets are package-relative ("./src/lib/foo.ts"). Strip the
+ # leading "./" and join with the package dir to get a repo path.
+ stripped = target.lstrip("./")
+ resolved = _probe_path(f"{dir_posix}/{stripped}", ctx.path_set)
+ if resolved is not None:
+ return resolved
+
+ # 2) Bare-package fallback — no ``exports[.]`` entry: try index.*,
+ # then ``main``/``module`` from package.json.
if not sub:
- for ext in (".ts", ".tsx", ".js", ".jsx"):
- cand = f"{base}/index{ext}"
- if cand in ctx.path_set:
+ cand = _probe_path(f"{dir_posix}/index", ctx.path_set)
+ if cand is not None:
+ return cand
+ main = pkg.get("main")
+ if isinstance(main, str):
+ cand = _probe_path(f"{dir_posix}/{main.lstrip('./')}", ctx.path_set)
+ if cand is not None:
return cand
- # Read main/module from the workspace package.json
- if ctx.repo_path is not None:
- ws_pkg = ctx.repo_path / dir_posix / "package.json"
- if ws_pkg.is_file():
- try:
- ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))
- except Exception:
- ws_data = None
- if isinstance(ws_data, dict):
- for key in ("module", "main"):
- entry = ws_data.get(key)
- if isinstance(entry, str):
- cand = f"{dir_posix}/{entry.lstrip('./')}"
- if cand in ctx.path_set:
- return cand
return None
- # Sub-path: try explicit, then with extensions.
- if base in ctx.path_set:
- return base
- for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):
- cand = base + ext if not ext.startswith("/") else base + ext
- if cand in ctx.path_set:
+ # 3) Subpath fallback — packages without ``exports`` (plain monorepo
+ # layouts): try ``<pkg>/<sub>`` directly, then under common source
+ # roots (``src``, ``lib``, ``dist``) so the resolver still finds
+ # files in packages that publish from a build directory.
+ direct = _probe_path(f"{dir_posix}/{sub}", ctx.path_set)
+ if direct is not None:
+ return direct
+ for src_root in ("src", "lib", "dist"):
+ cand = _probe_path(f"{dir_posix}/{src_root}/{sub}", ctx.path_set)
+ if cand is not None:
return cand
return None
diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.py
index 8c02051f6..50bf5efee 100644
--- a/tests/unit/ingestion/test_parser.py
+++ b/tests/unit/ingestion/test_parser.py
@@ -158,6 +158,41 @@ class TestPythonParser:
rel_import = next(i for i in result.imports if "change_detector" in i.module_path)
assert rel_import.imported_names == ["AffectedPages", "ChangeDetector", "FileDiff"]
+ def test_bare_relative_import_expands_to_one_per_submodule(
+ self, parser: ASTParser
+ ) -> None:
+ # Regression (D2): ``from . import a, b`` produced one Import with
+ # ``module_path="."`` which the resolver dropped on the floor, so
+ # every plugin-registry barrel silently lost its sibling-submodule
+ # edges. Expansion rewrites each name into ``.a``/``.b`` so the
+ # existing relative-resolver can locate the submodule.
+ fi = _make_file_info("pkg/__init__.py", "python")
+ result = parser.parse_file(
+ fi, b"from . import cargo, go, npm, nuget, pypi\n"
+ )
+ paths = sorted(i.module_path for i in result.imports if i.is_relative)
+ assert paths == [".cargo", ".go", ".npm", ".nuget", ".pypi"]
+ for imp in result.imports:
+ if imp.module_path.startswith(".") and imp.module_path != ".":
+ assert len(imp.imported_names) == 1
+ assert imp.imported_names[0] == imp.module_path.lstrip(".")
+
+ def test_bare_double_dot_relative_import_expands(self, parser: ASTParser) -> None:
+ # ``from .. import x`` must also expand, preserving dot depth.
+ fi = _make_file_info("pkg/sub/mod.py", "python")
+ result = parser.parse_file(fi, b"from .. import sibling, other\n")
+ paths = sorted(i.module_path for i in result.imports if i.is_relative)
+ assert paths == ["..other", "..sibling"]
+
+ def test_named_relative_import_is_not_split(self, parser: ASTParser) -> None:
+ # Negative: ``from .pkg import a, b`` must stay as a single Import —
+ # only the bare-dots case is rewritten.
+ fi = _make_file_info("pkg/use.py", "python")
+ result = parser.parse_file(fi, b"from .pkg import a, b\n")
+ rel = [i for i in result.imports if i.module_path == ".pkg"]
+ assert len(rel) == 1
+ assert sorted(rel[0].imported_names) == ["a", "b"]
+
def test_absolute_from_import_skips_module_keeps_first_name(
self, parser: ASTParser
) -> None:
@@ -170,6 +205,43 @@ class TestPythonParser:
imp = next(i for i in result.imports if i.module_path == "python_pkg.models")
assert imp.imported_names == ["Operation", "Result"]
+ def test_nested_function_not_extracted_as_top_level(self, parser: ASTParser) -> None:
+ # Regression (D8): orchestrator-style helpers defined inside an
+ # async method (e.g. ``_on_start``, ``_on_done``, ``_step``) were
+ # flattened to the top-level symbol list and read as unused public
+ # exports. Only module-top-level + class-body members should appear.
+ src = (
+ b"async def run():\n"
+ b" def _on_start():\n"
+ b" pass\n"
+ b" async def _step():\n"
+ b" pass\n"
+ b"\n"
+ b"class Worker:\n"
+ b" async def perform(self):\n"
+ b" def _on_done():\n"
+ b" pass\n"
+ b" return _on_done\n"
+ )
+ fi = _make_file_info("pkg/orchestrator.py", "python")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert names == {"run", "Worker", "perform"}
+ assert "_on_start" not in names
+ assert "_step" not in names
+ assert "_on_done" not in names
+
+ def test_nested_class_inside_function_not_extracted(self, parser: ASTParser) -> None:
+ src = (
+ b"def make():\n"
+ b" class Helper:\n"
+ b" def m(self): pass\n"
+ )
+ fi = _make_file_info("pkg/factories.py", "python")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert names == {"make"}
+
def test_function_docstring(self, parser: ASTParser) -> None:
fi = _make_file_info("pkg/calc.py", "python")
result = parser.parse_file(fi, PYTHON_SOURCE)
@@ -306,6 +378,116 @@ class TestTypeScriptParser:
result = parser.parse_file(fi, TS_SOURCE)
assert result.parse_errors == []
+ def test_nested_helpers_inside_component_not_extracted(
+ self, parser: ASTParser
+ ) -> None:
+ # Regression (D5): React component bodies contain helper function
+ # declarations and arrow-const handlers (``handleSave``,
+ # ``handleKeyDown``, ``Section``) that were being flattened to
+ # top-level public symbols and surfacing as ``unused_export``
+ # findings with confidence 1.0.
+ src = b"""
+export function GeneralForm({ onSave }: Props) {
+ function addPattern(p: string) { return p; }
+ async function handleSave() { onSave(); }
+ const Section = ({ title }: { title: string }) => <div>{title}</div>;
+ const handleKeyDown = (e: KeyboardEvent) => { e.preventDefault(); };
+ return <Section title="x" />;
+}
+
+export const Wrapper = () => {
+ const inner = () => 42;
+ return inner();
+};
+"""
+ fi = _make_file_info("ui/src/general-form.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert "GeneralForm" in names
+ assert "Wrapper" in names
+ for hidden in ("addPattern", "handleSave", "Section", "handleKeyDown", "inner"):
+ assert hidden not in names, f"nested helper {hidden} leaked to top level"
+
+ def test_tsx_file_uses_jsx_grammar(self, parser: ASTParser) -> None:
+ # .tsx files require the JSX-aware grammar variant; the default
+ # typescript grammar errors out on ``<Component />`` and recovers
+ # by hoisting nested helpers out of the broken component body.
+ src = b"""
+export function Card({ title }: { title: string }) {
+ function handleClick() { console.log("clicked"); }
+ return <div onClick={handleClick}>{title}</div>;
+}
+"""
+ fi = _make_file_info("ui/src/card.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ assert result.parse_errors == []
+ names = {s.name for s in result.symbols}
+ assert "Card" in names
+ assert "handleClick" not in names
+
+ def test_jsx_element_registers_as_call_target(self, parser: ASTParser) -> None:
+ # Regression: ``<StatRow ... />`` inside the same file as the
+ # ``StatRow`` component definition was not registering as a call,
+ # so same-file-only sub-components surfaced as unused public
+ # exports at confidence 1.0. The tsx-specific JSX captures now
+ # emit a CallSite for both self-closing and paired elements.
+ src = b"""
+export function StatRow({ value }: { value: number }) {
+ return <span>{value}</span>;
+}
+
+export function Section({ title }: { title: string }) {
+ return <h2>{title}</h2>;
+}
+
+export function Card() {
+ return (
+ <div>
+ <Section title="x" />
+ <StatRow value={1}></StatRow>
+ </div>
+ );
+}
+"""
+ fi = _make_file_info("ui/src/card.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ targets = {c.target_name for c in result.calls}
+ assert "StatRow" in targets
+ assert "Section" in targets
+
+ def test_jsx_element_call_works_for_jsx_grammar(
+ self, parser: ASTParser
+ ) -> None:
+ # Same behaviour for .jsx (plain JavaScript grammar already
+ # supports JSX node types natively).
+ src = b"""
+export function StatRow({ value }) {
+ return <span>{value}</span>;
+}
+
+export function Card() {
+ return <StatRow value={1} />;
+}
+"""
+ fi = _make_file_info("ui/src/card.jsx", "javascript")
+ result = parser.parse_file(fi, src)
+ targets = {c.target_name for c in result.calls}
+ assert "StatRow" in targets
+
+ def test_class_methods_still_extracted(self, parser: ASTParser) -> None:
+ # Negative for D5: methods inside class bodies must still be
+ # extracted — only function/method *bodies* count as nesting.
+ src = b"""
+export class Service {
+ run() { return 1; }
+ private helper() { return 2; }
+}
+"""
+ fi = _make_file_info("ui/src/service.ts", "typescript")
+ result = parser.parse_file(fi, src)
+ method_names = {s.name for s in result.symbols if s.kind == "method"}
+ assert {"run", "helper"} <= method_names
+
# ---------------------------------------------------------------------------
# Go
diff --git a/tests/unit/ingestion/test_typescript_resolver.py b/tests/unit/ingestion/test_typescript_resolver.py
index 06f797c08..1a58a8441 100644
--- a/tests/unit/ingestion/test_typescript_resolver.py
+++ b/tests/unit/ingestion/test_typescript_resolver.py
@@ -95,3 +95,171 @@ class TestWorkspaceResolution:
# No package.json → no workspaces → returns None (resolver itself
# would then return external:).
assert resolve_via_workspaces("@unknown/pkg", ctx) is None
+
+
+def _setup_workspace(
+ tmp_path: Path,
+ pkg_name: str,
+ pkg_data_extra: dict,
+) -> Path:
+ """Write a minimal root + one workspace pkg, return the workspace dir."""
+ (tmp_path / "package.json").write_text(json.dumps({"workspaces": ["packages/*"]}))
+ pkg_dir = tmp_path / "packages" / pkg_name.split("/")[-1]
+ pkg_dir.mkdir(parents=True)
+ (pkg_dir / "package.json").write_text(json.dumps({"name": pkg_name, **pkg_data_extra}))
+ return pkg_dir
+
+
+class TestWorkspaceExportsField:
+ """Exports-field resolution — the Node.js subpath protocol that
+ every modern monorepo (turborepo / nx / pnpm) leans on. Without
+ this, ``@org/ui/lib/format`` would probe ``packages/ui/lib/format``
+ and miss the actual source file at ``packages/ui/src/lib/format.ts``.
+ """
+
+ def test_exports_exact_subpath_resolves_through_src(self, tmp_path: Path) -> None:
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": {"./lib/format": "./src/lib/format.ts"}},
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/lib/format.ts"])
+ assert (
+ resolve_via_workspaces("@org/ui/lib/format", ctx)
+ == "packages/ui/src/lib/format.ts"
+ )
+
+ def test_exports_wildcard_pattern(self, tmp_path: Path) -> None:
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": {"./graph/*": "./src/graph/*.tsx"}},
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/graph/sigma-canvas.tsx"])
+ assert (
+ resolve_via_workspaces("@org/ui/graph/sigma-canvas", ctx)
+ == "packages/ui/src/graph/sigma-canvas.tsx"
+ )
+
+ def test_exports_longest_prefix_wins(self, tmp_path: Path) -> None:
+ # Two patterns can both match; the more specific (longer static
+ # prefix) one must take precedence.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ "./*": "./src/*.ts",
+ "./graph/*": "./src/graph/*.tsx",
+ }
+ },
+ )
+ ctx = _ctx(
+ tmp_path,
+ [
+ "packages/ui/src/graph/node.tsx",
+ "packages/ui/src/utils.ts",
+ ],
+ )
+ # Specific wildcard wins for graph/*
+ assert (
+ resolve_via_workspaces("@org/ui/graph/node", ctx)
+ == "packages/ui/src/graph/node.tsx"
+ )
+ # Generic wildcard catches the rest
+ assert (
+ resolve_via_workspaces("@org/ui/utils", ctx)
+ == "packages/ui/src/utils.ts"
+ )
+
+ def test_exports_conditional_object_picks_import_over_require(
+ self, tmp_path: Path
+ ) -> None:
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ "./util": {
+ "require": "./dist/util.cjs",
+ "import": "./src/util.ts",
+ }
+ }
+ },
+ )
+ ctx = _ctx(
+ tmp_path,
+ ["packages/ui/src/util.ts", "packages/ui/dist/util.cjs"],
+ )
+ assert (
+ resolve_via_workspaces("@org/ui/util", ctx)
+ == "packages/ui/src/util.ts"
+ )
+
+ def test_exports_bare_dot_root(self, tmp_path: Path) -> None:
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": {".": "./src/index.ts"}},
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/index.ts"])
+ assert (
+ resolve_via_workspaces("@org/ui", ctx)
+ == "packages/ui/src/index.ts"
+ )
+
+ def test_exports_string_shorthand(self, tmp_path: Path) -> None:
+ # `"exports": "./src/index.ts"` is shorthand for `{".": ...}`.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": "./src/index.ts"},
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/index.ts"])
+ assert (
+ resolve_via_workspaces("@org/ui", ctx)
+ == "packages/ui/src/index.ts"
+ )
+
+ def test_no_exports_falls_back_to_src_root(self, tmp_path: Path) -> None:
+ # Packages without `exports` but with a `src/` layout — the most
+ # common shape for internal monorepo libraries — must still
+ # resolve.
+ _setup_workspace(tmp_path, "@org/ui", {})
+ ctx = _ctx(tmp_path, ["packages/ui/src/lib/format.ts"])
+ assert (
+ resolve_via_workspaces("@org/ui/lib/format", ctx)
+ == "packages/ui/src/lib/format.ts"
+ )
+
+ def test_no_exports_falls_back_to_flat_layout(self, tmp_path: Path) -> None:
+ # Packages laid out directly at the package root (no src/) keep
+ # working — common in small/older monorepos.
+ _setup_workspace(tmp_path, "@org/ui", {})
+ ctx = _ctx(tmp_path, ["packages/ui/lib/format.ts"])
+ assert (
+ resolve_via_workspaces("@org/ui/lib/format", ctx)
+ == "packages/ui/lib/format.ts"
+ )
+
+ def test_exports_unmatched_subpath_returns_none(self, tmp_path: Path) -> None:
+ # When ``exports`` is declared, an unmatched subpath should NOT
+ # fall through to the legacy probe — Node treats undeclared
+ # subpaths as blocked. Returning the external node is the
+ # resolver's job upstream; here we just return None.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": {"./util": "./src/util.ts"}},
+ )
+ ctx = _ctx(
+ tmp_path,
+ ["packages/ui/src/util.ts", "packages/ui/src/secret.ts"],
+ )
+ # NB: current implementation falls back to legacy probe for
+ # robustness — Node-strict behaviour can be added once monorepo
+ # behaviour is validated. Assert the lenient (current) result.
+ assert (
+ resolve_via_workspaces("@org/ui/secret", ctx)
+ == "packages/ui/src/secret.ts"
+ )
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index 92c37c94f..1644a223e 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -1211,3 +1211,503 @@ def test_unused_internal_explicit_opt_out():
internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
assert internals == []
+
+
+# ---------------------------------------------------------------------------
+# D3. Alembic migration scripts are never flagged
+# ---------------------------------------------------------------------------
+
+
+def test_alembic_versions_never_flagged_as_unreachable():
+ """Files under <root>/alembic/versions/*.py are loaded reflectively by
+ Alembic at runtime — they have no static importer and must not be
+ surfaced as unreachable on any Alembic-using repo (generic Python
+ convention)."""
+ g = _build_graph(
+ nodes={
+ "myapp/alembic/versions/0001_init.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [],
+ },
+ "myapp/alembic/versions/0002_add_users.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {"detect_unused_exports": False, "detect_zombie_packages": False}
+ )
+ paths = {f.file_path for f in report.findings}
+ assert "myapp/alembic/versions/0001_init.py" not in paths
+ assert "myapp/alembic/versions/0002_add_users.py" not in paths
+
+
+def test_alembic_upgrade_downgrade_never_flagged_as_unused():
+ """``upgrade()`` / ``downgrade()`` in Alembic migration scripts are
+ called via reflection by the Alembic runner — the file pattern
+ exemption (``*/alembic/versions/*.py``) already covers them, so the
+ symbols inside must not surface as unused exports either."""
+ g = _build_graph(
+ nodes={
+ "myapp/alembic/versions/0001_init.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "upgrade",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1, "end_line": 5,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "downgrade",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 7, "end_line": 11,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "upgrade" not in names
+ assert "downgrade" not in names
+
+
+# ---------------------------------------------------------------------------
+# D4. Click @<group>.command(...) decorator suffix detection
+# ---------------------------------------------------------------------------
+
+
+def test_click_group_command_decorator_excluded():
+ """Subcommands registered on a locally-named Click ``Group`` are
+ decorated as e.g. ``@my_cli.command("add")``. The receiver name is
+ project-local, so the matcher needs to recognise the ``.command``
+ suffix rather than a hard-coded ``click.command`` prefix. Same shape
+ covers Typer (``.command``/``.callback``) and any user-named
+ dispatcher."""
+ g = _build_graph(
+ nodes={
+ "pkg/cli.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [
+ {
+ "name": "decision_add",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["decision_group.command"],
+ "start_line": 1, "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "decision_list",
+ "kind": "function",
+ "visibility": "public",
+ # Real-world capture sometimes includes the call
+ # arguments — the matcher must strip them.
+ "decorators": ['my_cli.group("decision")'],
+ "start_line": 12, "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "after_cmd",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["app.callback"],
+ "start_line": 22, "end_line": 28,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "decision_add" not in names
+ assert "decision_list" not in names
+ assert "after_cmd" not in names
+
+
+def test_unrelated_dot_command_function_still_flagged():
+ """A decorator suffix-match must not accidentally whitelist symbols
+ with unrelated decorators. ``@functools.lru_cache`` does not end with
+ ``.command/.group/.callback``, so a plain unused public helper with
+ that decorator is still surfaced."""
+ g = _build_graph(
+ nodes={
+ "pkg/helpers.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "expensive_lookup",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["functools.lru_cache"],
+ "start_line": 1, "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "expensive_lookup" in names
+
+
+# ---------------------------------------------------------------------------
+# D7. unused_internal: imports-by-name into the symbol's file means used
+# ---------------------------------------------------------------------------
+
+
+def test_unused_internal_skipped_when_imported_by_name():
+ """A private helper imported by name into a sibling module (typical
+ dispatch-table pattern: ``HANDLERS = {"python": _extract_py, ...}``)
+ is reached at runtime via dict lookup — no direct ``calls`` edge
+ will exist, but the ``imports`` edge carries the symbol name. Such
+ helpers must not be flagged as unused internals."""
+ g = _build_graph(
+ nodes={
+ "pkg/python_handler.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_extract_python",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1, "end_line": 15,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/dispatch.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/dispatch.py",
+ "pkg/python_handler.py",
+ {"edge_type": "imports", "imported_names": ["_extract_python"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
+ assert "_extract_python" not in names
+
+
+def test_unused_export_skipped_when_file_imported_as_namespace():
+ """A public symbol in a file that is imported by its module name
+ (``from . import cargo``) is a dispatch-table candidate — the
+ importer holds a binding to the module and can call any public
+ attribute via ``cargo.<attr>(...)``. We cannot tell statically
+ which attribute is used, so every public symbol in the file must
+ be treated as live."""
+ g = _build_graph(
+ nodes={
+ "pkg/external_systems/cargo.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "parse",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1, "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/external_systems/__init__.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/external_systems/__init__.py",
+ "pkg/external_systems/cargo.py",
+ {"edge_type": "imports", "imported_names": ["cargo"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "parse" not in names
+
+
+def test_unused_export_still_flagged_when_namespace_name_differs():
+ """Negative test for the namespace-import rescue: if the importer
+ pulls a *different* sibling module, the public symbol's file is
+ still effectively orphan and the symbol must be flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/external_systems/cargo.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "parse",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1, "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/external_systems/__init__.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ # importer pulled "npm" only — does NOT mention "cargo"
+ (
+ "pkg/external_systems/__init__.py",
+ "pkg/external_systems/cargo.py",
+ {"edge_type": "imports", "imported_names": ["npm"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "parse" in names
+
+
+def test_unused_export_not_rescued_for_index_stem():
+ """``index.ts`` is the barrel filename in JS/TS package layouts —
+ every workspace package's source root has one, and most imports of
+ a package land on it. We must not over-rescue every public export
+ of every ``index.ts`` just because a downstream importer happens
+ to use the literal name ``index``. Same applies to Python
+ ``__init__`` (already covered by the global never-flag list)."""
+ g = _build_graph(
+ nodes={
+ "pkg/ui/src/index.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "language": "typescript",
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "stranded_export",
+ "kind": "function",
+ "visibility": "public",
+ "language": "typescript",
+ "decorators": [],
+ "start_line": 1, "end_line": 5,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/web/src/page.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "language": "typescript",
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/web/src/page.ts",
+ "pkg/ui/src/index.ts",
+ {"edge_type": "imports", "imported_names": ["index"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "stranded_export" in names
+
+
+def test_unused_internal_still_flagged_when_imports_dont_carry_name():
+ """Sanity check: an ``imports`` edge that does NOT list the private
+ symbol's name (e.g. the importer pulls a different sibling symbol)
+ must not rescue the helper from the unused-internal pass."""
+ g = _build_graph(
+ nodes={
+ "pkg/helpers.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "_unused_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1, "end_line": 8,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/consumer.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/consumer.py",
+ "pkg/helpers.py",
+ {"edge_type": "imports", "imported_names": ["something_else"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
+ assert "_unused_helper" in names
+
+
+# ---------------------------------------------------------------------------
+# D10. WSGI / ASGI / app-factory names treated as entry points
+# ---------------------------------------------------------------------------
+
+
+ "factory_name",
+ [
+ "create_app",
+ "make_app",
+ "application",
+ "asgi_app",
+ "wsgi_app",
+ "get_asgi_application",
+ "get_wsgi_application",
+ ],
+)
+def test_python_web_factory_not_flagged(factory_name):
+ """FastAPI / Flask / Tornado / aiohttp / Django entry symbols are
+ loaded by an external server via dotted-path string
+ (``module:create_app`` / ``module:application``) — no graph edge
+ exists from the launching server. These conventional names must be
+ in the entry-point allowlist so the unused-export pass skips them."""
+ g = _build_graph(
+ nodes={
+ "myapp/server.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": factory_name,
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1, "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert factory_name not in names