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): judge only real packages as zombies; count tool-config loads as uses (#2982)

Raghav Chamadiya73ee89aff1be
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 fd4f0be15..3347f97ef 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -11,7 +11,9 @@ this package.
from __future__ import annotations
+import contextlib
import fnmatch
+import os
import re
from collections.abc import Iterable, Iterator
from collections.abc import Set as AbstractSet
@@ -25,6 +27,7 @@ import structlog
from ...code_origin import is_build_file
from ...entry_candidacy import is_reachability_root
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
+from ...ingestion.package_roots import package_manifest_names
from ...ingestion.symbol_identity import base_symbol_id, overload_sets
from .c_name_uses import (
DEFINITION_HEADER_LINES,
@@ -42,6 +45,7 @@ from .constants import (
_NAMESPACE_IMPORT_LANGUAGES,
_NEVER_PACKAGE_DIRS,
_PREPROCESSED_LANGUAGES,
+ _PROJECT_FILE_SUFFIXES,
_PURE_WRAPPER_DECORATOR_ATTRS,
_PURE_WRAPPER_DECORATOR_MODULES,
_RUN_NOT_IMPORTED_LANGUAGES,
@@ -55,7 +59,7 @@ from .dynamic_markers import (
find_dynamic_import_files,
read_source_text,
)
-from .entry_shape import clamp_entry_shaped, drop_program_entries
+from .entry_shape import clamp_entry_shaped, drop_program_entries, is_program
from .file_reachability import (
PackageFileMap,
ReachabilityRescues,
@@ -2044,6 +2048,17 @@ class DeadCodeAnalyzer:
# and any other dotfile directory at the repo root.
if pkg in _NEVER_PACKAGE_DIRS or pkg.startswith("."):
return False
+ # A folder is a package only when it declares itself one: a Next.js
+ # ``app/``, a ``benchmarks/`` folder or a Go ``cmd/`` has no manifest
+ # and nothing is meant to import it.
+ if not self._has_package_manifest(pkg, files):
+ return False
+ # Tests are run, never imported, and so is a package that ships a
+ # program (a CLI started by its shebang). One program file is enough,
+ # even a stray script: this errs toward not calling a package dead.
+ files = [f for f in files if not self.graph.nodes.get(f, {}).get("is_test")]
+ if any(is_program(f, self._source_map.get(f, b"")) for f in files):
+ return False
# A real package contains at least one source file something could
# import. Config and data (YAML, JSON, MD, TOML) is metadata, and a
# folder of Dockerfiles, shell scripts and build files is run, never
@@ -2055,6 +2070,20 @@ class DeadCodeAnalyzer:
for f in files
)
+ def _has_package_manifest(self, pkg: str, files: list[str]) -> bool:
+ """Whether *pkg* holds a package manifest of its own, on disk or indexed.
+
+ A top-level folder whose manifest sits at the repository root (a
+ Python package built by the root ``pyproject.toml``) is the repository
+ itself, not a package of it, so it is never a candidate.
+ """
+ names = {f.partition("/")[2] for f in files if f.count("/") == 1}
+ if self._repo_root is not None:
+ with contextlib.suppress(OSError):
+ names.update(os.listdir(Path(self._repo_root) / pkg))
+ manifests = package_manifest_names()
+ return any(n in manifests or n.endswith(_PROJECT_FILE_SUFFIXES) for n in names)
+
def _has_cross_package_importer(self, pkg: str, files: list[str]) -> bool:
"""Whether anything outside *pkg* depends on a file inside it."""
for f in files:
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 55667e9a1..ba49dcba3 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -30,6 +30,12 @@ _DEAD_CODE_EXEMPT_LANGUAGES: frozenset[str] = (
# Extensions a JS tool's config file may take.
_JS_TOOL_EXTS: tuple[str, ...] = (".js", ".cjs", ".mjs", ".ts", ".cts", ".mts")
+# A JS tool's config file: ``<tool>.config.<ext>`` and variants like
+# ``jest.config.base.js``. Never flagged itself, and a reader of what it loads.
+_JS_TOOL_CONFIG_PATTERNS: tuple[str, ...] = (
+ *(f"*.config{ext}" for ext in _JS_TOOL_EXTS),
+ *(f"*.config.*{ext}" for ext in _JS_TOOL_EXTS),
+)
# Patterns that should never be flagged as dead. ``fnmatch`` ``*`` spans ``/``,
# so a leading ``*`` matches nested and repo-root paths alike.
@@ -60,8 +66,7 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
# variants like ``jest.config.base.js``), ``.<tool>rc.<ext>`` and pnpm's
# install hook. fnmatch ``*`` spans ``/``, so an ``*rc.<ext>`` file under a
# dot-directory is exempt too; an accepted recall loss.
- *(f"*.config{ext}" for ext in _JS_TOOL_EXTS),
- *(f"*.config.*{ext}" for ext in _JS_TOOL_EXTS),
+ *_JS_TOOL_CONFIG_PATTERNS,
*(f".*rc{ext}" for ext in _JS_TOOL_EXTS),
*(f"*/.*rc{ext}" for ext in _JS_TOOL_EXTS),
".pnpmfile.cjs",
@@ -996,6 +1001,32 @@ _RUNNER_FILE_NAMES: frozenset[str] = frozenset(
)
_RUNNER_DIRS: tuple[str, ...] = (".github/workflows/", ".circleci/", ".buildkite/")
_RUNNER_SUFFIXES: tuple[str, ...] = (".sh", ".bash", ".ps1", ".bat", ".cmd", ".dockerfile")
+# Tool configs that load files they name under a load key (below): the JS
+# tool configs above and the changesets config.
+_TOOL_CONFIG_PATHS: tuple[str, ...] = ("/.changeset/config.json",)
+# The keys under which a tool config names a file it loads: a test runner's
+# setup files, a bundler's entries, a docs site's sidebars, the changesets
+# changelog module. A path under any other key (``coverage.exclude``,
+# ``ignores``) or in a comment is not loaded.
+_TOOL_CONFIG_LOAD_KEYS: tuple[str, ...] = (
+ "setupFiles",
+ "setupFilesAfterEnv",
+ "globalSetup",
+ "globalTeardown",
+ "entry",
+ "entryPoints",
+ "input",
+ "sidebarPath",
+ "changelog",
+)
+
+
+def is_tool_config(path: str) -> bool:
+ """Whether *path* is a tool config that loads the files its load keys name."""
+ name = path.rpartition("/")[2]
+ return any(fnmatch.fnmatchcase(name, p) for p in _JS_TOOL_CONFIG_PATTERNS) or (
+ f"/{path}".endswith(_TOOL_CONFIG_PATHS)
+ )
def is_runner_file(path: str) -> bool:
@@ -1089,6 +1120,11 @@ _NEVER_PACKAGE_DIRS: frozenset[str] = frozenset(
)
+# Project files that declare a .NET package. Globs, so they cannot sit in the
+# registry's exact-name manifest list (see ``ingestion/package_roots.py``).
+_PROJECT_FILE_SUFFIXES: tuple[str, ...] = (".csproj", ".fsproj", ".vbproj")
+
+
# Path segments that indicate test fixture / sample data directories.
_FIXTURE_PATH_SEGMENTS: tuple[str, ...] = (
"fixture",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
index bdebf2bbf..4e90a226d 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
@@ -92,7 +92,8 @@ def _parse_python(path: str, blob: bytes) -> ast.Module | None:
def _program_reason(path: str, blob: bytes) -> str | None:
"""Why *blob* says it is a program: a shebang or a Python main guard."""
- if blob.startswith(b"#!"):
+ # ``#![`` opens a Rust inner attribute (``#![doc = ...]``), not a shebang.
+ if blob.startswith(b"#!") and not blob.startswith(b"#!["):
return "Starts with a shebang, so it is run directly rather than imported"
tree = _parse_python(path, blob) if b"__main__" in blob else None
if tree is not None and any(
diff --git a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
index b7cded96e..8ba31e475 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
@@ -45,12 +45,14 @@ where this answers it from the repository in front of us.
from __future__ import annotations
+import posixpath
import re
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from enum import Enum
-from .constants import is_runner_file
+from .constants import _TOOL_CONFIG_LOAD_KEYS, is_runner_file, is_tool_config
+from .entry_shape import export_shape
from .models import DeadCodeFindingData, DeadCodeKind
from .risk_factors import RISK_CAP_CONFIDENCE
@@ -444,26 +446,47 @@ def _files_naming(targets: set[str], source_map: dict[str, bytes]) -> dict[str,
named_in: dict[str, list[str]] = {}
for path, blob in sorted(source_map.items()):
- for target in _targets_in(blob, wanted, tails) - {path}:
+ base = path.rpartition("/")[0]
+ for target in _targets_in(blob, wanted, tails, base) - {path}:
named_in.setdefault(target, []).append(path)
return named_in
-def _targets_in(blob: bytes, wanted: dict[str, set[str]], tails: set[str]) -> set[str]:
- """The targets any path-shaped token of *blob* names."""
+def _targets_in(
+ blob: bytes, wanted: dict[str, set[str]], tails: set[str], base: str
+) -> set[str]:
+ """The targets any path-shaped token of *blob*, a file in *base*, names."""
return {
target
for match in _PATH_TOKEN_RE.finditer(blob)
- for target in _targets_named_by(match.group().decode("ascii"), wanted, tails)
+ for target in _targets_named_by(match.group().decode("ascii"), wanted, tails, base)
}
-def _targets_named_by(token: str, wanted: dict[str, set[str]], tails: set[str]) -> set[str]:
- """The targets one path-shaped *token* names, through any of its spellings."""
+def _targets_named_by(
+ token: str, wanted: dict[str, set[str]], tails: set[str], base: str
+) -> set[str]:
+ """The targets one path-shaped *token* names, through any of its spellings.
+
+ A tool resolves a relative path against the directory of the file that
+ writes it (``setupFiles: ["./vitest.setup.ts"]`` in ``src/vitest.config.ts``
+ is ``src/vitest.setup.ts``), so that resolution is one more spelling.
+ """
tail = token.strip(".").rpartition("/")[2]
if tail not in tails and tail.rpartition(".")[0] not in tails:
return set()
- return {target for spelling in _token_spellings(token) for target in wanted.get(spelling, ())}
+ spellings = _token_spellings(token)
+ if base and not token.startswith("/"):
+ # Not through ``_token_spellings``: its dot strip would eat the
+ # leading dot of a dot-directory (``.changeset/``).
+ resolved = posixpath.normpath(f"{base}/{token}")
+ spellings += [resolved, resolved.rpartition(".")[0]]
+ return {target for spelling in spellings for target in wanted.get(spelling, ())}
+
+
+#: What a file named by path can be used as: a file a runner loads, or a module
+#: whose exports a tool config reads.
+_PATH_LOADED_KINDS = frozenset({DeadCodeKind.UNREACHABLE_FILE, DeadCodeKind.UNUSED_EXPORT})
def clamp_path_mentions(
@@ -478,25 +501,68 @@ def clamp_path_mentions(
A mention in a doc is not proof of use, so that finding is capped to the
review tier. A CI workflow, build file, manifest or shell script runs or
ships what it names (``python scripts/emit_sample_dsl.py`` in a workflow),
- so a file one of those names is dropped.
+ so a file one of those names is dropped. A tool config that loads a module
+ reads what the module exports by default (a changesets changelog module,
+ a docs site's sidebars), so the unused exports of a default-exporting
+ module a tool config names are dropped too; a setup file the config runs
+ for its side effects keeps them.
One scan over the indexed source. That already holds JSON, YAML, Markdown,
shell and ``package.json``: each has a language spec, so ingestion reads
it. A file's mention of itself is not a use. Returns a new list; never
raises a confidence.
"""
- unreachable = [f for f in findings if f.kind is DeadCodeKind.UNREACHABLE_FILE]
- if not source_map or not unreachable:
+ in_scope = [f for f in findings if f.kind in _PATH_LOADED_KINDS]
+ if not source_map or not in_scope:
return findings
- named_in = _files_naming({f.file_path for f in unreachable}, source_map)
- run = {
- id(f) for f in unreachable if any(map(is_runner_file, named_in.get(f.file_path, ())))
- }
- for finding in unreachable:
- if id(finding) not in run:
+ named_in = _files_naming({f.file_path for f in in_scope}, source_map)
+ run = {id(f) for f in in_scope if _loaded(f, named_in.get(f.file_path, ()), source_map)}
+ kept = [f for f in findings if id(f) not in run]
+ for finding in kept:
+ if finding.kind is DeadCodeKind.UNREACHABLE_FILE:
_cap_named_by_path(finding, named_in.get(finding.file_path))
- return [f for f in findings if id(f) not in run]
+ return kept
+
+
+def _loaded(
+ finding: DeadCodeFindingData, namers: Iterable[str], source_map: dict[str, bytes]
+) -> bool:
+ """Whether *namers* load the file of *finding* in the way the finding denies.
+
+ A tool config is read only through its load keys, even when it is also a
+ runner by name (a bundler config is a build file): a path it mentions in a
+ comment or an ignore list is not loaded.
+ """
+ path = finding.file_path
+ configs = [n for n in namers if is_tool_config(n)]
+ loaders = [n for n in configs if _config_loads(n, path, source_map)]
+ if finding.kind is DeadCodeKind.UNREACHABLE_FILE:
+ others = (n for n in namers if n not in configs)
+ return bool(loaders) or any(map(is_runner_file, others))
+ return bool(loaders) and "default" in export_shape(path, frozenset(), source_map.get(path))
+
+
+#: ``<load key>: <value>`` in a tool config, the key quoted or bare; the value a
+#: string, a list or an object (``input: { main: "src/a.ts" }``).
+_LOAD_VALUE_RE = re.compile(
+ rb"""["']?\b(?:"""
+ + b"|".join(k.encode() for k in _TOOL_CONFIG_LOAD_KEYS)
+ + rb""")\b["']?\s*[:=]\s*(\[[^\]]*\]|\{[^}]*\}|"[^"]*"|'[^']*')"""
+)
+# Comments, so a path a config only mentions in one is not loaded. A ``//``
+# after ``:`` is a URL (``https://``), not a comment.
+_LINE_COMMENT_RE = re.compile(rb"(?<![:\w])//[^\n]*")
+_BLOCK_COMMENT_RE = re.compile(rb"/\*.*?\*/", re.DOTALL)
+
+
+def _config_loads(config: str, target: str, source_map: dict[str, bytes]) -> bool:
+ """Whether *config* names *target* under one of its load keys."""
+ text = _LINE_COMMENT_RE.sub(b"", _BLOCK_COMMENT_RE.sub(b"", source_map.get(config, b"")))
+ values = b"\n".join(m.group(1) for m in _LOAD_VALUE_RE.finditer(text))
+ wanted = {key: {target} for key in _path_keys(target)}
+ tails = {key.rpartition("/")[2] for key in wanted}
+ return target in _targets_in(values, wanted, tails, config.rpartition("/")[0])
def _cap_named_by_path(finding: DeadCodeFindingData, namers: list[str] | None) -> None:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 2ca5dbdb9..40199675b 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -196,6 +196,12 @@ _TS_CJS_EXPORTS_RE = re.compile(r"\bmodule\.exports\b|\bexports\s*[.\[]")
# publishes a name for a symbol the file declares itself; the other is a
# re-export the import pipeline already carries.
_TS_EXPORT_LIST_SOURCE_RE = re.compile(r"\bexport\s*\{([^}]*)\}\s*(from\b)?")
+# ``export default name`` with nothing after the name: the statement form of
+# ``export { name as default }``. A declaration (``export default function f``)
+# or an expression (``export default f()``) does not match.
+_TS_EXPORT_DEFAULT_NAME_RE = re.compile(
+ r"^[ \t]*export[ \t]+default[ \t]+([A-Za-z_$][\w$]*)[ \t]*;?[ \t]*\r?$", re.MULTILINE
+)
# Dropped outright rather than blanked: nothing downstream of the alias scan
# reads a line number, and collapsing a comment between a clause and its
@@ -249,11 +255,13 @@ def ts_export_aliases(src: str) -> dict[str, str]:
Clauses that do not rename are omitted: the two names agree, so the symbol
table already answers and an entry would only duplicate it.
+ ``export default name`` is the same clause written as a statement, so it is
+ recorded as ``{"default": name}``.
"""
- # Every alias is written ``local as exported``, so a file without that
- # token cannot hold one and need not be scanned. Most files do not, and
- # the scan is over the whole source.
- if " as " not in src:
+ # Every alias is written ``local as exported`` or ``export default name``,
+ # so a file with neither token cannot hold one and need not be scanned.
+ # Most files do not, and the scan is over the whole source.
+ if " as " not in src and "export default" not in src:
return {}
# Comments are stripped first, and this map is the reason it is worth the
@@ -262,17 +270,22 @@ def ts_export_aliases(src: str) -> dict[str, str]:
# a local symbol as some module's published API and mint a call edge to it.
cleaned = _TS_LINE_COMMENT.sub("", _TS_BLOCK_COMMENT.sub("", src))
- aliases: dict[str, str] = {}
+ pairs = [(m.group(1), "default") for m in _TS_EXPORT_DEFAULT_NAME_RE.finditer(cleaned)]
for m in _TS_EXPORT_LIST_SOURCE_RE.finditer(cleaned):
if m.group(2): # ``export { a as b } from "./x"`` — a re-export
continue
for part in m.group(1).split(","):
local, separator, exported = (p.strip() for p in part.partition(" as "))
- if not separator or not local.isidentifier() or not exported.isidentifier():
- continue
- # A name published twice under one spelling has no single answer,
- # and guessing costs a wrong edge where refusing costs none.
- aliases[exported] = local if aliases.get(exported, local) == local else ""
+ if separator:
+ pairs.append((local, exported))
+
+ aliases: dict[str, str] = {}
+ for local, exported in pairs:
+ if not local.isidentifier() or not exported.isidentifier():
+ continue
+ # A name published twice under one spelling has no single answer,
+ # and guessing costs a wrong edge where refusing costs none.
+ aliases[exported] = local if aliases.get(exported, local) == local else ""
return {exported: local for exported, local in aliases.items() if local}
diff --git a/tests/unit/dead_code/test_fp_rescues.py b/tests/unit/dead_code/test_fp_rescues.py
index 375d27f13..3ee08f7b2 100644
--- a/tests/unit/dead_code/test_fp_rescues.py
+++ b/tests/unit/dead_code/test_fp_rescues.py
@@ -131,6 +131,32 @@ def test_export_alias_without_importer_still_flagged(tmp_path: Path):
assert "Widget" in names
+def test_a_default_export_by_name_is_used_through_default(tmp_path: Path):
+ # ``export { default as cssQuery } from "./css"`` imports ``default``.
+ src = "const cssQuery = String.raw`(rule_set)`\n\nexport default cssQuery\n"
+ parsed = {"q/css.ts": _parsed_stub(tmp_path, "q/css.ts", src)}
+ g = _build_graph(
+ nodes={
+ "q/css.ts": _file_node([_sym("cssQuery"), _sym("unusedHelper", start_line=7)]),
+ "q/index.ts": _file_node([]),
+ },
+ edges=[
+ ("q/index.ts", "q/css.ts", {"edge_type": "imports", "imported_names": ["default"]}),
+ ],
+ )
+ names = _unused_export_names(DeadCodeAnalyzer(g, git_meta_map={}, parsed_files=parsed))
+ assert "cssQuery" not in names
+ assert "unusedHelper" in names
+
+
+def test_a_default_export_by_name_is_recorded_in_a_crlf_file():
+ from repowise.core.ingestion.extractors.visibility import ts_export_aliases
+
+ CRLF = chr(13) + chr(10) # a Windows checkout's line ending
+ src = "const cssQuery = 1" + CRLF + CRLF + "export default cssQuery" + CRLF
+ assert ts_export_aliases(src) == {"default": "cssQuery"}
+
+
def test_bundler_alias_shim_rescued(tmp_path: Path):
# Both alias shapes seen in the wild: a plain relative string and a
# bare segment fed through ``path.resolve(here, ...)``.
diff --git a/tests/unit/dead_code/test_line_counts.py b/tests/unit/dead_code/test_line_counts.py
index 6f688438c..5476b7133 100644
--- a/tests/unit/dead_code/test_line_counts.py
+++ b/tests/unit/dead_code/test_line_counts.py
@@ -7,6 +7,8 @@ the source; a count that cannot be made is ``None`` with an evidence line.
from __future__ import annotations
+from pathlib import Path
+
from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
from tests.unit.dead_code._helpers import _build_graph, _old_date
@@ -82,7 +84,11 @@ def test_unreadable_file_is_unknown_not_guessed():
assert by_path["pkg/a.py"].lines == 1
-def test_zombie_package_sums_real_file_lines():
+def test_zombie_package_sums_real_file_lines(tmp_path: Path):
+ # The manifests that make each folder a package, read from the checkout.
+ for pkg in ("pkgA", "pkgB"):
+ (tmp_path / pkg).mkdir()
+ (tmp_path / pkg / "pyproject.toml").write_text("[project]", encoding="utf-8")
g = _build_graph(
nodes={
"pkgA/one.py": _file(10),
@@ -91,9 +97,9 @@ def test_zombie_package_sums_real_file_lines():
}
)
source_map = {"pkgA/one.py": b"a\nb\n", "pkgA/two.py": b"c\n", "pkgB/three.py": b"d\n"}
- report = DeadCodeAnalyzer(g, git_meta_map={}, source_map=source_map).analyze(
- {"detect_unreachable_files": False, "detect_unused_exports": False}
- )
+ report = DeadCodeAnalyzer(
+ g, git_meta_map={}, source_map=source_map, repo_root=tmp_path
+ ).analyze({"detect_unreachable_files": False, "detect_unused_exports": False})
zombie = next(
f
for f in report.findings
diff --git a/tests/unit/dead_code/test_path_mentions.py b/tests/unit/dead_code/test_path_mentions.py
index 31dbfa3b8..18e10da37 100644
--- a/tests/unit/dead_code/test_path_mentions.py
+++ b/tests/unit/dead_code/test_path_mentions.py
@@ -127,3 +127,89 @@ def test_a_truly_dead_file_through_the_analyzer_keeps_full_confidence():
assert by_path["pkg/old.py"].confidence == 1.0
assert by_path["pkg/listed.py"].confidence == RISK_CAP_CONFIDENCE
assert by_path["pkg/listed.py"].safe_to_delete is False
+
+
+def _export(path: str, name: str) -> DeadCodeFindingData:
+ finding = _file(path)
+ finding.kind = DeadCodeKind.UNUSED_EXPORT
+ finding.symbol_name = name
+ return finding
+
+
+def test_a_relative_path_resolves_against_the_naming_files_directory():
+ config = 'export default { test: { setupFiles: ["./vitest.setup.ts"] } }\n'
+ assert _dropped("src/vitest.setup.ts", {"src/vitest.config.ts": config})
+
+
+def test_a_relative_path_from_a_doc_is_capped_not_dropped():
+ finding = _clamp("pkg/run.py", {"pkg/README.md": "Run `./run.py` by hand.\n"})
+ assert finding.confidence == RISK_CAP_CONFIDENCE
+
+
+def test_a_relative_path_never_reaches_a_sibling_directory():
+ config = 'export default { test: { setupFiles: ["./vitest.setup.ts"] } }\n'
+ finding = _clamp("web/vitest.setup.ts", {"src/vitest.config.ts": config})
+ assert finding.confidence == 1.0
+
+
+def test_the_changesets_changelog_module_and_its_exports_are_used():
+ config = '{"changelog": "./changelog-config.js", "commit": false}\n'
+ module = ".changeset/changelog-config.js"
+ source = {
+ ".changeset/config.json": config,
+ module: "const getReleaseLine = async () => ''\nconst fns = { getReleaseLine }\n"
+ "module.exports = fns\n",
+ }
+ findings = [_file(module), _export(module, "getReleaseLine")]
+ assert clamp_path_mentions(findings, {p: s.encode() for p, s in source.items()}) == []
+
+
+def test_a_setup_file_a_config_runs_keeps_its_unused_exports():
+ # vitest runs a setup file for its side effects; nothing reads its exports.
+ config = 'export default { test: { setupFiles: ["./vitest.setup.ts"] } }\n'
+ setup = "export function allowNetConnect() {}\nbeforeAll(() => {})\n"
+ source = {"src/vitest.config.ts": config, "src/vitest.setup.ts": setup}
+ finding = _export("src/vitest.setup.ts", "allowNetConnect")
+ assert clamp_path_mentions([finding], {p: s.encode() for p, s in source.items()}) == [finding]
+
+
+def test_an_export_a_manifest_lists_keeps_its_confidence():
+ # A coverage omit list in pyproject.toml names a file without loading it.
+ finding = _export("pkg/contrib/plugin.py", "setup")
+ source = {"pyproject.toml": b'omit = ["*pkg/contrib/plugin.py"]\n'}
+ assert clamp_path_mentions([finding], source) == [finding]
+
+
+def test_an_export_a_doc_names_by_path_keeps_its_confidence():
+ finding = _export("src/lib/api.ts", "helper")
+ source = {"docs/api.md": b"See src/lib/api.ts for the client.\n"}
+ assert clamp_path_mentions([finding], source) == [finding]
+ assert finding.confidence == 1.0
+
+
+def test_a_config_excluding_a_file_does_not_load_it():
+ config = "export default { test: { coverage: { exclude: ['src/legacy.ts'] } } }\n"
+ finding = _clamp("src/legacy.ts", {"vitest.config.ts": config})
+ assert finding.confidence == RISK_CAP_CONFIDENCE # a mention, not a load
+
+
+def test_a_lint_config_ignoring_a_file_does_not_load_it():
+ config = "export default [{ ignores: ['src/old.ts'] }]\n"
+ assert not _dropped("src/old.ts", {"eslint.config.js": config})
+
+
+def test_a_config_comment_does_not_load_a_file():
+ config = "// removed ./src/gone.ts last release\nexport default { entry: ['src/index.ts'] }\n"
+ assert not _dropped("src/gone.ts", {"tsup.config.ts": config})
+ assert _dropped("src/index.ts", {"tsup.config.ts": config})
+
+
+def test_a_bundler_config_that_is_also_a_runner_still_needs_a_load_key(monkeypatch):
+ # A bundler config may count as a runner by name (a build file); a path it
+ # only mentions in a comment must still not be read as loaded.
+ from repowise.core.analysis.dead_code import name_occurrences
+
+ monkeypatch.setattr(name_occurrences, "is_runner_file", lambda path: True)
+ config = "// removed ./src/gone.ts last release\nexport default { entry: ['src/index.ts'] }\n"
+ assert not _dropped("src/gone.ts", {"tsup.config.ts": config})
+ assert _dropped("src/index.ts", {"tsup.config.ts": config})
diff --git a/tests/unit/dead_code/test_script_entry_points.py b/tests/unit/dead_code/test_script_entry_points.py
index 77df57a45..73e2c6cdc 100644
--- a/tests/unit/dead_code/test_script_entry_points.py
+++ b/tests/unit/dead_code/test_script_entry_points.py
@@ -61,6 +61,10 @@ def test_a_folder_of_dockerfiles_is_not_a_zombie_package():
"docker/entrypoint.sh": {"language": "shell"},
"pkg/a.py": {"symbols": []},
"lib/b.py": {"symbols": []},
+ # Each folder declares itself a package; only the Dockerfiles differ.
+ "docker/pyproject.toml": {"language": "toml"},
+ "pkg/pyproject.toml": {"language": "toml"},
+ "lib/pyproject.toml": {"language": "toml"},
}
)
report = DeadCodeAnalyzer(graph).analyze({"min_confidence": 0.0})
diff --git a/tests/unit/dead_code/test_zombie_package_candidates.py b/tests/unit/dead_code/test_zombie_package_candidates.py
new file mode 100644
index 000000000..6ca8bdd60
--- /dev/null
+++ b/tests/unit/dead_code/test_zombie_package_candidates.py
@@ -0,0 +1,91 @@
+"""A zombie package is a real package nothing imports.
+
+A top-level folder is judged only when it declares itself a package with a
+manifest of its own, holds a source file that is not a test, and ships no
+program: a Next.js ``app/``, a ``benchmarks/`` folder, a test suite or a CLI
+started by its shebang is run, never imported.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def _zombies(
+ nodes: dict[str, dict],
+ source: dict[str, bytes] | None = None,
+ repo_root: Path | None = None,
+) -> set[str]:
+ nodes.setdefault("lib/index.ts", {"symbols": []})
+ report = DeadCodeAnalyzer(
+ _build_graph(nodes), git_meta_map={}, source_map=source, repo_root=repo_root
+ ).analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "min_confidence": 0.0,
+ }
+ )
+ return {f.file_path for f in report.findings if f.kind is DeadCodeKind.ZOMBIE_PACKAGE}
+
+
+def _manifest() -> dict:
+ return {"language": "json", "symbols": []}
+
+
+def test_a_folder_without_a_manifest_is_not_a_package():
+ nodes = {
+ "app/page.tsx": {"symbols": []},
+ "types/index.d.ts": {"symbols": []},
+ "benchmarks/run.ts": {"symbols": []},
+ }
+ assert _zombies(nodes) == set()
+
+
+def test_an_unimported_package_with_a_manifest_is_a_zombie():
+ nodes = {"old-lib/package.json": _manifest(), "old-lib/src/index.ts": {"symbols": []}}
+ assert _zombies(nodes) == {"old-lib"}
+
+
+def test_a_manifest_read_from_disk_counts(tmp_path: Path):
+ # Maven and Gradle manifests are not indexed; the checkout still has them.
+ (tmp_path / "api-client").mkdir()
+ (tmp_path / "api-client" / "pom.xml").write_text("<project/>", encoding="utf-8")
+ nodes = {"api-client/src/Client.java": {"language": "java", "symbols": []}}
+ assert _zombies(nodes, repo_root=tmp_path) == {"api-client"}
+
+
+def test_a_dotnet_project_file_is_a_manifest(tmp_path: Path):
+ (tmp_path / "Old.Lib").mkdir()
+ (tmp_path / "Old.Lib" / "Old.Lib.csproj").write_text("<Project/>", encoding="utf-8")
+ nodes = {"Old.Lib/Thing.cs": {"language": "csharp", "symbols": []}}
+ assert _zombies(nodes, repo_root=tmp_path) == {"Old.Lib"}
+
+
+def test_a_package_of_tests_is_run_not_imported():
+ nodes = {
+ "runtime-tests/package.json": _manifest(),
+ "runtime-tests/node/index.test.ts": {"is_test": True, "symbols": []},
+ }
+ assert _zombies(nodes) == set()
+
+
+def test_a_package_shipping_a_program_is_run_not_imported():
+ nodes = {
+ "evals/package.json": _manifest(),
+ "evals/src/cli.ts": {"symbols": []},
+ "evals/src/report.ts": {"symbols": []},
+ }
+ source = {"evals/src/cli.ts": b"#!/usr/bin/env node\nmain()\n", "evals/src/report.ts": b""}
+ assert _zombies(nodes, source) == set()
+
+
+def test_a_rust_inner_attribute_is_not_a_shebang():
+ from repowise.core.analysis.dead_code.entry_shape import is_program
+
+ assert is_program("lib.rs", b'#![doc(html_root_url = "https://docs.rs/x")]\npub fn f() {}\n') is False
+ assert is_program("bin/run", b"#!/usr/bin/env node\nmain()\n") is True
diff --git a/tests/unit/dead_code/test_zombie_packages.py b/tests/unit/dead_code/test_zombie_packages.py
index 74fd45076..a20253ff3 100644
--- a/tests/unit/dead_code/test_zombie_packages.py
+++ b/tests/unit/dead_code/test_zombie_packages.py
@@ -25,6 +25,9 @@ def test_zombie_package_detected():
"""A package with no incoming inter-package imports should be flagged as zombie."""
g = _build_graph(
nodes={
+ # A package declares itself with a manifest.
+ "pkgA/pyproject.toml": {"language": "toml", "symbols": []},
+ "pkgB/pyproject.toml": {"language": "toml", "symbols": []},
"pkgA/mod1.py": {
"is_entry_point": False,
"is_test": False,
@@ -93,6 +96,9 @@ def _zombie_graph() -> object:
"""
return _build_graph(
nodes={
+ # A package declares itself with a manifest.
+ "pkgA/pyproject.toml": {"language": "toml", "symbols": []},
+ "pkgB/pyproject.toml": {"language": "toml", "symbols": []},
"pkgA/alpha.py": {
"is_entry_point": False,
"is_test": False,