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(ingestion): resolve Python imports that hid live code as dead (#244)
Raghav Chamadiyaadada543474c
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex ddb8ac706..43145c4b7 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -51,7 +51,7 @@ All eight languages support:- Heritage extraction (class/interface/trait/record inheritance chains)- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)-- Per-language dynamic-hint extractors (Django/Pytest/Node for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)+- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields → PascalCase property, `[RelayCommand]` methods → `<Name>Command`)- For C/C++ only: visibility tracked from access specifiers (`public:` / `private:` / `protected:`), `static` file-scope storage class, and export attributes (`__declspec(dllexport)`, `__attribute__((visibility("default")))`); COM / I-prefixed bases emit `implements` edges (rest are `extends`); Windows DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`) are never flagged as dead- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml→xaml `dynamic_uses` edges@@ -143,7 +143,9 @@ Extension/filename -> LanguageTag (via LanguageRegistry)|vGraphBuilder resolves imports:- Python: dotted module paths, __init__.py, src/ layout+ Python: dotted module paths via a source-root-aware module index+ (src/ + monorepo packages/*/src + PEP 420 namespace+ packages), __init__.py re-export barrels, stem fallbackTS/JS: relative paths, tsconfig aliases, node_modulesGo: go.mod module path strippingRust: crate::/self::/super::, mod.rs probing@@ -316,6 +318,7 @@ into each subpackage rather than editing monoliths.```ingestion/languages/ # LanguageRegistry + LanguageSpec (identity data)+ python_modules.py # dotted-module ↔ file index (src / monorepo / PEP 420)extractors/ # Per-language AST extractionvisibility.py # symbol visibility (public/private/protected)signatures.py # human-readable signature building@@ -329,7 +332,8 @@ ingestion/python.py ts_js.py java.py go.py rust.py cpp.pykotlin.py ruby.py swift.py csharp.py scala.py php.pyresolvers/ # Per-language import resolution- python.py # dotted imports, __init__.py, src/ layout+ python.py # dotted imports via module index: __init__.py+ # barrels, src/ + monorepo packages/*/src, namespace pkgstypescript.py # multi-ext probe, tsconfig aliasesgo.py # go.mod module path strippingrust.py # crate::/self::/super::, mod.rs probing@@ -345,7 +349,7 @@ ingestion/dynamic_hints/ # Per-language dynamic-edge extractorsbase.py # DynamicHintExtractor + DynamicEdgeregistry.py # HintRegistry- django.py pytest_hints.py node.py dotnet.py+ django.py pytest_hints.py python_imports.py node.py dotnet.pyspring.py ruby.py php.py scala.py swift.py c.py luau.py go.pyparser.py # ASTParser (language-agnostic orchestration)graph.py # GraphBuilder (import/call/heritage resolution)diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.pynew file mode 100644index 000000000..38f542215--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py@@ -0,0 +1,102 @@+"""Dynamic-import hints for Python.++Static import resolution sees ``import x`` / ``from x import y`` but is+blind to runtime-resolved imports — the registry / plugin pattern where a+module is named by a *string* and loaded with ``importlib.import_module``+(``getattr`` then pulls the class out by name). The canonical shape::++ _PROVIDERS = {+ "ollama": ("my_pkg.providers.ollama", "OllamaProvider"),+ }+ module = importlib.import_module(_PROVIDERS[name][0])+ cls = getattr(module, _PROVIDERS[name][1])++Nothing statically imports ``my_pkg.providers.ollama`` or ``OllamaProvider``,+so dead-code analysis would flag both the module and the class as unused.++This extractor recovers those edges generically: in any file that uses+dynamic-import machinery, every quoted string that resolves to a real+in-repo module (via :func:`python_modules.build_python_module_index`) yields+a ``dynamic_uses`` edge to that module's file. The analyzer then treats the+target file as runtime-loaded and stops flagging its public members.++Gating on the presence of dynamic-import machinery (rather than emitting an+edge for any dotted string that happens to match a module) keeps the signal+precise: a dotted string in a log message or docstring of an ordinary module+is ignored. The mechanism is repo-agnostic — it works for any Python plugin+registry, ``importlib`` loader, or entry-point dispatch table.+"""++from __future__ import annotations++import re+from pathlib import Path++from ..languages.python_modules import build_python_module_index+from .base import DynamicEdge, DynamicHintExtractor++# Tokens that signal a file performs runtime module loading. An edge is only+# emitted from files that contain at least one of these, so plain dotted+# strings elsewhere never create spurious reachability.+_DYNAMIC_IMPORT_MARKERS: tuple[str, ...] = (+ "importlib",+ "import_module",+ "__import__",+ "import_string", # Werkzeug / Flask / Django utilities+ "load_entry_point",+ "entry_points(", # importlib.metadata plugin discovery+ "pkgutil",+ "pkg_resources",+)++# A quoted dotted path of two or more identifier segments — i.e. something+# shaped like ``a.b`` / ``pkg.sub.mod``. Single-segment names are too+# ambiguous (and resolve via ordinary stem matching anyway).+_DOTTED_STRING_RE = re.compile(r"""['"]([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)+)['"]""")+++class PythonDynamicHints(DynamicHintExtractor):+ name = "python_dynamic_import"++ def extract(self, repo_root: Path) -> list[DynamicEdge]:+ rel_by_abs: dict[Path, str] = {}+ for py in self._rglob(repo_root, "*.py"):+ try:+ rel = py.relative_to(repo_root).as_posix()+ except ValueError:+ continue+ rel_by_abs[py] = rel++ if not rel_by_abs:+ return []++ module_index = build_python_module_index(rel_by_abs.values())+ if not module_index:+ return []++ edges: list[DynamicEdge] = []+ for abs_path, rel in rel_by_abs.items():+ try:+ text = abs_path.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ if not any(marker in text for marker in _DYNAMIC_IMPORT_MARKERS):+ continue++ seen: set[str] = set()+ for match in _DOTTED_STRING_RE.finditer(text):+ dotted = match.group(1)+ if dotted in seen:+ continue+ seen.add(dotted)+ target = module_index.get(dotted)+ if target and target != rel:+ edges.append(+ DynamicEdge(+ source=rel,+ target=target,+ edge_type="dynamic_uses",+ hint_source=self.name,+ )+ )+ return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.pyindex 84eebc209..e823f7c50 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py@@ -28,6 +28,7 @@ from .go import GoDynamicHintsfrom .luau import LuauDynamicHintsfrom .node import NodeDynamicHintsfrom .php import PhpDynamicHints+from .python_imports import PythonDynamicHintsfrom .pytest_hints import PytestDynamicHintsfrom .ruby import RubyDynamicHintsfrom .scala import ScalaDynamicHints@@ -53,6 +54,7 @@ class HintRegistry:self._extractors = extractors or [DjangoDynamicHints(),PytestDynamicHints(),+ PythonDynamicHints(),NodeDynamicHints(),DotNetDynamicHints(),XamlDynamicHints(),@@ -80,24 +82,18 @@ class HintRegistry:return edgeswith ThreadPoolExecutor(max_workers=self._max_workers) as pool:- futures = {- pool.submit(self._run_one, ex, repo_root): ex for ex in self._extractors- }+ futures = {pool.submit(self._run_one, ex, repo_root): ex for ex in self._extractors}for future in as_completed(futures):ex = futures[future]try:got = future.result()except Exception as e:- log.warning(- "dynamic_hints_failed", extractor=ex.name, error=str(e)- )+ log.warning("dynamic_hints_failed", extractor=ex.name, error=str(e))continueedges.extend(got)log.debug("dynamic_hints", extractor=ex.name, count=len(got))return edges@staticmethod- def _run_one(- extractor: DynamicHintExtractor, repo_root: Path- ) -> list[DynamicEdge]:+ def _run_one(extractor: DynamicHintExtractor, repo_root: Path) -> list[DynamicEdge]:return extractor.extract(repo_root)diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.pyindex d4ff7b408..65fbe88eb 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py@@ -38,7 +38,17 @@ def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[exported = node_text(name_node, src)local = node_text(alias_node, src) if alias_node else exportedif is_from_import:- names.append(local)+ # ``imported_names`` must carry the *exported* name — the+ # name as it exists in the target module — because that's+ # what downstream matches against: the dead-code analyzer+ # compares it to the source symbol / submodule name, and+ # ``expand_bare_relative_imports`` uses it to locate the+ # submodule file. The local alias is preserved on the+ # binding (``local_name``) for call resolution. Recording+ # the alias here instead made ``from . import levels as+ # _levels`` resolve to a non-existent ``_levels`` module+ # and hid every ``levels.py`` symbol from reachability.+ names.append(exported)bindings.append(NamedBinding(local_name=local, exported_name=exported, source_file=None))@@ -107,10 +117,13 @@ def expand_bare_relative_imports(imports: list[Import]) -> list[Import]:continuedots = imp.module_path # e.g. ".", ".."- bindings_by_name = {b.local_name: b for b in imp.bindings}+ # ``imported_names`` holds exported (original) submodule names, so key+ # the bindings by exported name — keeping the alias-preserving binding+ # for ``from . import sub as alias`` instead of dropping it.+ bindings_by_name = {(b.exported_name or 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+ local_name=name, exported_name=name, source_file=None, is_module_alias=True)out.append(Import(diff --git a/packages/core/src/repowise/core/ingestion/languages/python_modules.py b/packages/core/src/repowise/core/ingestion/languages/python_modules.pynew file mode 100644index 000000000..a9027910f--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/python_modules.py@@ -0,0 +1,154 @@+"""Python module-path ↔ file-path mapping (import semantics).++Maps a fully-qualified dotted module name (``pkg.sub.mod``) to the+repo-relative file that defines it, and vice versa, by deriving each+``.py`` file's *importable* dotted name from its package chain.++The mapping is purely structural — it reads a set of repo-relative POSIX+paths and the presence of ``__init__.py`` files, with no filesystem access+and no repo-specific assumptions. Because the dotted name is computed+relative to each file's *source root* (the first ancestor directory that is+not itself a package), the same logic resolves:++* **flat layouts** — ``foo/bar.py`` → ``foo.bar`` (root is the source root);+* **src layouts** — ``src/pkg/mod.py`` → ``pkg.mod``;+* **monorepo layouts** — ``packages/core/src/pkg/mod.py`` → ``pkg.mod``.++This is what lets absolute imports such as+``from repowise.core.providers.llm.base import BaseProvider`` resolve to+``packages/core/src/repowise/core/providers/llm/base.py`` — a path the naive+``{dotted}.py`` / ``src/{dotted}.py`` probes never reach.++Shared by the Python import resolver (:mod:`resolvers.python`) and the+Python dynamic-import hints extractor+(:mod:`dynamic_hints.python_imports`).+"""++from __future__ import annotations++from collections.abc import Iterable+from pathlib import PurePosixPath++_PY_SUFFIXES = (".py", ".pyi")++# Path segments that mark a file as a low-value resolution target. Mirrors+# the stem-disambiguation policy in ``graph/_stem.py``: a loose module under+# ``tests/`` / ``fixtures/`` / ``examples/`` that happens to derive the same+# dotted name as a real package module must never win the mapping. Kept local+# (rather than imported from ``graph``) to avoid an import cycle — the graph+# package depends on this module through the resolver.+_LOW_VALUE_PATH_SEGMENTS = frozenset(+ {+ "tests",+ "test",+ "_tests",+ "__tests__",+ "testing",+ "test_apps",+ "testdata",+ "test_data",+ "fixtures",+ "examples",+ "example",+ "samples",+ "sample",+ "scripts",+ "benchmarks",+ "bench",+ "docs",+ "doc",+ }+)+++def _index_priority(path: str) -> tuple[int, int, str]:+ """Sort key for choosing among files that derive the same dotted name.++ Lower sorts first: prefer non-test/non-fixture paths, then shallower+ paths, then a stable lexicographic tiebreak.+ """+ parts = path.split("/")+ low_value = 1 if any(seg in _LOW_VALUE_PATH_SEGMENTS for seg in parts) else 0+ return (low_value, len(parts), path)+++def _is_package_dir(dir_posix: str, path_set: frozenset[str] | set[str]) -> bool:+ """True if *dir_posix* contains an ``__init__.py`` (i.e. is a package)."""+ init = f"{dir_posix}/__init__.py" if dir_posix not in ("", ".") else "__init__.py"+ return init in path_set+++def dotted_module_for(path: str, path_set: frozenset[str] | set[str]) -> str | None:+ """Return the dotted module name *path* is importable as, or ``None``.++ Two strategies, in order:++ 1. **``src`` source root.** If the path contains a ``src`` directory that+ is not itself a package, everything below the last such ``src`` is the+ module path. This is the standard ``src``-layout and the monorepo+ ``packages/*/src`` layout, and — crucially — it also resolves PEP 420+ *namespace packages* (a top-level package dir with no ``__init__.py``,+ as used to share one import namespace across several distributions),+ which the ``__init__``-chain alone cannot see.++ 2. **Regular-package chain.** Otherwise, the file must be a genuine package+ member (an ``__init__.py``, or living in a directory that has one); the+ name is the chain of ``__init__``-bearing directories down to the file.++ Loose modules in non-package directories with no ``src`` root (e.g.+ ``vendor/util.py``) return ``None`` on purpose — they are not reliably+ importable by a fully-qualified dotted path, and resolving them is the job+ of the flat-/src-layout candidates and the stem-map heuristics (which+ encode richer disambiguation: parent-dir match, test-fixture demotion).+ Claiming them here would override those with a weaker guess.+ """+ p = PurePosixPath(path)+ if p.suffix not in _PY_SUFFIXES:+ return None++ is_init = p.name in ("__init__.py", "__init__.pyi")+ dir_parts = list(p.parts[:-1])++ # Strategy 1 — strip up to and including the last real ``src`` root.+ for i in range(len(dir_parts) - 1, -1, -1):+ if dir_parts[i] != "src":+ continue+ src_dir = "/".join(dir_parts[: i + 1])+ if _is_package_dir(src_dir, path_set):+ continue # a package literally named ``src`` — not a source root+ comps = dir_parts[i + 1 :] + ([] if is_init else [p.stem])+ return ".".join(comps) if comps else None++ # Strategy 2 — regular-package ``__init__`` chain.+ if not is_init and not _is_package_dir(p.parent.as_posix(), path_set):+ return None+ parts: list[str] = [] if is_init else [p.stem]+ cur = p.parent+ while str(cur) not in ("", ".") and _is_package_dir(cur.as_posix(), path_set):+ parts.append(cur.name)+ cur = cur.parent+ if not parts:+ return None+ parts.reverse()+ return ".".join(parts)+++def build_python_module_index(paths: Iterable[str]) -> dict[str, str]:+ """Map dotted module name → repo-relative file path for every Python file.++ When two files derive the same dotted name (a real package module and a+ like-named loose module under ``tests/`` / ``fixtures/``, or namespace+ packages split across roots) the higher-priority path wins+ deterministically — see :func:`_index_priority` — so resolution never+ depends on iteration order.+ """+ path_set = paths if isinstance(paths, (set, frozenset)) else set(paths)+ index: dict[str, str] = {}+ for p in path_set:+ dotted = dotted_module_for(p, path_set)+ if not dotted:+ continue+ current = index.get(dotted)+ if current is None or _index_priority(p) < _index_priority(current):+ index[dotted] = p+ return indexdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/python.py b/packages/core/src/repowise/core/ingestion/resolvers/python.pyindex 7e3924a31..9b76e8fdf 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/python.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/python.py@@ -4,9 +4,24 @@ from __future__ import annotationsfrom pathlib import Path+from ..languages.python_modules import build_python_module_indexfrom .context import ResolverContext+def _module_index(ctx: ResolverContext) -> dict[str, str]:+ """Source-root-aware dotted-module → path index, built once per context.++ Cached on the context (mirrors the lazy per-language index pattern used+ by the PHP / TS / Kotlin resolvers) so the index is computed a single+ time across every Python import in a build.+ """+ idx = getattr(ctx, "_python_module_index", None)+ if idx is None:+ idx = build_python_module_index(ctx.path_set)+ ctx._python_module_index = idx+ return idx++def resolve_python_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:"""Resolve a Python import to a repo-relative file path."""importer_dir = Path(importer_path).parent@@ -27,7 +42,20 @@ def resolve_python_import(module_path: str, importer_path: str, ctx: ResolverConreturn creturn None- # Absolute import: try obvious filesystem layouts+ # Absolute import: resolve via the source-root-aware module index first.+ # This maps the fully-qualified dotted name to its defining file no+ # matter how deeply the source root is nested (``src/``,+ # ``packages/*/src/``, …) — the case the naive layout probes below miss,+ # and the reason cross-package imports such as+ # ``from repowise.core.persistence.models import SecurityFinding`` used+ # to fall through to an ambiguous stem match.+ hit = _module_index(ctx).get(module_path)+ if hit:+ return hit++ # Fallback: obvious flat / single-``src`` filesystem layouts. Kept as a+ # belt-and-suspenders path for PEP 420 namespace packages (no+ # ``__init__.py``) that the index cannot derive a dotted name for.dotted = module_path.replace(".", "/")candidates = [f"{dotted}.py",diff --git a/tests/unit/ingestion/test_python_dead_code_fixes.py b/tests/unit/ingestion/test_python_dead_code_fixes.pynew file mode 100644index 000000000..1d1273754--- /dev/null+++ b/tests/unit/ingestion/test_python_dead_code_fixes.py@@ -0,0 +1,296 @@+"""Regression tests: Python ingestion fixes for dead-code false positives.++Each test reproduces a real false positive the dead-code analyzer reported+on a monorepo (``packages/*/src`` layout) and asserts the symbol is no+longer flagged. They drive the *real* parser, GraphBuilder and analyzer —+no mocking of the resolution path — so they verify the end-to-end behaviour+without running a full ``repowise init``.++The four classes of false positive, and the fix each exercises:++* base class reached only through an absolute cross-module import →+ source-root-aware module index (``languages/python_modules.py``);+* model reached through a *cross-package* absolute import (server → core) →+ same module index;+* submodule used via an aliased namespace import+ (``from . import levels as _levels``) → exported-name binding fix;+* class loaded by string via ``importlib`` → Python dynamic-import hints.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion.dynamic_hints.python_imports import PythonDynamicHints+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.languages.python_modules import (+ build_python_module_index,+ dotted_module_for,+)+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _file_info(path: str) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="python",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _graph_from_sources(sources: dict[str, str]) -> nx.DiGraph:+ """Parse each ``path -> source`` and build a real dependency graph."""+ builder = GraphBuilder()+ for path, src in sources.items():+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))+ builder.add_file(parsed)+ return builder.build()+++def _unused_export_names(graph: nx.DiGraph) -> set[str]:+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})+ return {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}+++def _unreachable_paths(graph: nx.DiGraph) -> set[str]:+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})+ return {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}+++# ---------------------------------------------------------------------------+# Module index — the structural core of the resolution fix+# ---------------------------------------------------------------------------+++class TestPythonModuleIndex:+ def test_dotted_name_strips_monorepo_source_root(self) -> None:+ paths = {+ "packages/core/src/myrepo/__init__.py",+ "packages/core/src/myrepo/sub/__init__.py",+ "packages/core/src/myrepo/sub/mod.py",+ }+ assert dotted_module_for("packages/core/src/myrepo/sub/mod.py", paths) == "myrepo.sub.mod"++ def test_init_maps_to_package_name(self) -> None:+ paths = {+ "src/pkg/__init__.py",+ "src/pkg/sub/__init__.py",+ }+ assert dotted_module_for("src/pkg/sub/__init__.py", paths) == "pkg.sub"++ def test_flat_layout(self) -> None:+ paths = {"app/__init__.py", "app/mod.py"}+ assert dotted_module_for("app/mod.py", paths) == "app.mod"++ def test_namespace_package_under_src(self) -> None:+ """A PEP 420 namespace package (top dir has no ``__init__.py``) under a+ monorepo ``src`` root still yields its full dotted name — the layout+ repowise itself uses (``repowise`` is a namespace package shared by+ the core/server/cli distributions)."""+ paths = {+ # note: NO ``packages/core/src/ns/__init__.py`` — namespace package+ "packages/core/src/ns/core/__init__.py",+ "packages/core/src/ns/core/mod.py",+ }+ assert dotted_module_for("packages/core/src/ns/core/mod.py", paths) == "ns.core.mod"++ def test_package_literally_named_src_is_not_a_root(self) -> None:+ paths = {"src/__init__.py", "src/mod.py"}+ # ``src`` has an __init__.py, so it is a real package, not a root.+ assert dotted_module_for("src/mod.py", paths) == "src.mod"++ def test_loose_module_without_src_is_unindexed(self) -> None:+ paths = {"vendor/util.py"}+ assert dotted_module_for("vendor/util.py", paths) is None++ def test_index_round_trips_dotted_to_path(self) -> None:+ paths = {+ "packages/a/src/lib/__init__.py",+ "packages/a/src/lib/core.py",+ }+ idx = build_python_module_index(paths)+ assert idx["lib.core"] == "packages/a/src/lib/core.py"+ assert idx["lib"] == "packages/a/src/lib/__init__.py"+++# ---------------------------------------------------------------------------+# 1. Base class reached only via an absolute import (BaseProvider pattern)+# ---------------------------------------------------------------------------+++def test_base_class_imported_absolutely_in_monorepo_not_flagged() -> None:+ sources = {+ "packages/core/src/myrepo/__init__.py": "",+ "packages/core/src/myrepo/providers/__init__.py": "",+ "packages/core/src/myrepo/providers/base.py": (+ "class BaseProvider:\n def run(self):\n return 1\n"+ ),+ "packages/core/src/myrepo/providers/anthropic.py": (+ "from myrepo.providers.base import BaseProvider\n\n\n"+ "class AnthropicProvider(BaseProvider):\n pass\n"+ ),+ }+ graph = _graph_from_sources(sources)++ base = "packages/core/src/myrepo/providers/base.py"+ assert base not in _unreachable_paths(graph)+ assert "BaseProvider" not in _unused_export_names(graph)+++# ---------------------------------------------------------------------------+# 2. Model reached via a cross-package absolute import (SecurityFinding)+# ---------------------------------------------------------------------------+++def test_cross_package_absolute_import_keeps_symbol_live() -> None:+ sources = {+ "packages/core/src/myrepo/__init__.py": "",+ "packages/core/src/myrepo/persistence/__init__.py": "",+ "packages/core/src/myrepo/persistence/models.py": ("class SecurityFinding:\n id = 0\n"),+ "packages/server/src/myrepo/server/__init__.py": "",+ "packages/server/src/myrepo/server/routers/__init__.py": "",+ "packages/server/src/myrepo/server/routers/security.py": (+ "from myrepo.persistence.models import SecurityFinding\n\n\n"+ "def list_findings():\n return SecurityFinding\n"+ ),+ }+ graph = _graph_from_sources(sources)+ assert "SecurityFinding" not in _unused_export_names(graph)+++# ---------------------------------------------------------------------------+# 3. Submodule used via aliased namespace import (build_levelN_coros)+# ---------------------------------------------------------------------------+++def test_aliased_namespace_import_rescues_module_symbols() -> None:+ sources = {+ "packages/core/src/myrepo/__init__.py": "",+ "packages/core/src/myrepo/gen/__init__.py": "",+ "packages/core/src/myrepo/gen/levels.py": (+ "def build_level4_coros(run):\n return []\n\n\n"+ "def build_level7_coros(run):\n return []\n"+ ),+ "packages/core/src/myrepo/gen/orchestrate.py": (+ "from . import levels as _levels\n\n\n"+ "def run(self):\n"+ " a = _levels.build_level4_coros(self)\n"+ " b = _levels.build_level7_coros(self)\n"+ " return a + b\n"+ ),+ }+ graph = _graph_from_sources(sources)+ flagged = _unused_export_names(graph)+ assert "build_level4_coros" not in flagged+ assert "build_level7_coros" not in flagged+++def test_aliased_namespace_import_records_exported_module_name() -> None:+ """The import edge carries the *module* name (``levels``), not the alias."""+ sources = {+ "pkg/__init__.py": "",+ "pkg/levels.py": "def f():\n return 1\n",+ "pkg/orchestrate.py": "from . import levels as _levels\n",+ }+ graph = _graph_from_sources(sources)+ edge = graph.get_edge_data("pkg/orchestrate.py", "pkg/levels.py")+ assert edge is not None, "aliased namespace import should resolve to the submodule"+ assert "levels" in edge.get("imported_names", [])+++# ---------------------------------------------------------------------------+# 4. Class loaded by string via importlib (OllamaProvider)+# ---------------------------------------------------------------------------+++def test_python_dynamic_hints_emit_edge_for_importlib_string(tmp_path: Path) -> None:+ pkg = tmp_path / "pkg"+ (pkg / "providers").mkdir(parents=True)+ (pkg / "__init__.py").write_text("")+ (pkg / "providers" / "__init__.py").write_text("")+ (pkg / "providers" / "ollama.py").write_text("class OllamaProvider:\n pass\n")+ (pkg / "registry.py").write_text(+ "import importlib\n"+ "_PROVIDERS = {'ollama': ('pkg.providers.ollama', 'OllamaProvider')}\n"+ "def get(name):\n"+ " mod_path, cls = _PROVIDERS[name]\n"+ " return getattr(importlib.import_module(mod_path), cls)\n"+ )++ edges = PythonDynamicHints().extract(tmp_path)+ pairs = {(e.source, e.target, e.edge_type) for e in edges}+ assert (+ "pkg/registry.py",+ "pkg/providers/ollama.py",+ "dynamic_uses",+ ) in pairs+++def test_python_dynamic_hints_ignore_dotted_strings_without_loader(+ tmp_path: Path,+) -> None:+ """A dotted string in a file with no dynamic-import machinery is inert."""+ pkg = tmp_path / "pkg"+ pkg.mkdir(parents=True)+ (pkg / "__init__.py").write_text("")+ (pkg / "target.py").write_text("X = 1\n")+ (pkg / "doc.py").write_text(+ "MESSAGE = 'see pkg.target for details'\n" # mentions a real module, but no loader+ )++ edges = PythonDynamicHints().extract(tmp_path)+ assert all(e.source != "pkg/doc.py" for e in edges)+++def test_dynamic_use_edge_marks_target_file_live() -> None:+ """An incoming ``dynamic_uses`` edge keeps every public export of the+ target file out of the unused-export results (analyzer contract that the+ Python dynamic-hints edges rely on)."""+ g = nx.DiGraph()+ g.add_node(+ "pkg/registry.py",+ node_type="file",+ language="python",+ is_test=False,+ is_entry_point=False,+ )+ g.add_node(+ "pkg/ollama.py",+ node_type="file",+ language="python",+ is_test=False,+ is_entry_point=False,+ )+ sym = "pkg/ollama.py::OllamaProvider"+ g.add_node(+ sym,+ node_type="symbol",+ kind="class",+ name="OllamaProvider",+ visibility="public",+ decorators=[],+ start_line=1,+ end_line=20,+ file_path="pkg/ollama.py",+ language="python",+ )+ g.add_edge("pkg/ollama.py", sym, edge_type="defines")+ g.add_edge("pkg/registry.py", "pkg/ollama.py", edge_type="dynamic_uses")++ assert "OllamaProvider" not in _unused_export_names(g)