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): lead with deletion-ready lines and link packages that import their own directory (#3884)

Raghav Chamadiya9cd45c1746b7
diff --git a/packages/api-client/src/types/dead-code.ts b/packages/api-client/src/types/dead-code.ts
index c5bd7c80b..ddb308a50 100644
--- a/packages/api-client/src/types/dead-code.ts
+++ b/packages/api-client/src/types/dead-code.ts
@@ -39,6 +39,8 @@ export interface DeadCodeSummaryResponse {
total_findings: number;
confidence_summary: Record<string, number>;
deletable_lines: number;
+ /** Deletion-ready findings, the ones `deletable_lines` sums. */
+ safe_to_delete_count?: number | null;
total_lines: number;
by_kind: Record<string, number>;
/** ISO 8601 UTC; `null`/absent = never ran or unknown (not an all-clear). */
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.py
index e36212308..232969ac9 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py
@@ -40,6 +40,10 @@ or docstring loads nothing). Three shapes are read:
template that starts with a hole adds nothing; one with a single-segment
prefix or more than :data:`_TEMPLATE_FANOUT_CAP` matches links the package
only. A call in a comment or docstring is skipped.
+* **A package importing its own directory** (``for m in
+ pkgutil.iter_modules(__path__): import_module(f"{__name__}.{m.name}")``):
+ every module the loop loads, read by
+ :mod:`~.python_package_listing`, uncapped.
The mechanism is repo-agnostic: plugin registries, ``importlib`` loaders,
entry-point dispatch tables and lazy CLI groups all reduce to these shapes.
@@ -57,6 +61,7 @@ from ..languages.python_modules import build_python_module_index
from ..languages.python_strings import PY_DYNAMIC_LOAD_MARKERS, defines_top_level, live_text
from ..source_text import source_bytes
from .base import DynamicEdge, DynamicHintExtractor
+from .python_package_listing import OWN_LISTING_RE, listed_children, listing_inputs
# Dotted strings only produce edges from files that load modules at run time,
# so plain dotted strings elsewhere never create spurious reachability.
@@ -117,6 +122,13 @@ class ModuleStringResolver:
self._source_of = source_of
self._attrs: dict[tuple[str, str], bool] = {}
self._templates: dict[str, list[str]] = {}
+ self._dotted: dict[str, str] | None = None
+
+ def module_of(self, path: str) -> str | None:
+ """The dotted name *path* is indexed under (its package for an ``__init__``)."""
+ if self._dotted is None:
+ self._dotted = {p: d for d, p in self.module_index.items()}
+ return self._dotted.get(path)
def has_attr(self, target: str, name: str) -> bool:
"""Whether a module defines, imports or lazily serves *name* at top level."""
@@ -233,6 +245,11 @@ def python_dynamic_refs(rel: str, blob: bytes, resolver: ModuleStringResolver) -
body = m.group(2) or m.group(4) + b"{}"
for target in resolver.template_targets(body.decode("ascii")):
_add_ref(refs, target, None)
+ # Every module listed and loaded loads at import time: no fan-out cap.
+ own = resolver.module_of(rel) if rel.endswith(_INIT_NAMES) else None
+ if own and OWN_LISTING_RE.search(blob):
+ for target in listed_children(blob, own, index):
+ _add_ref(refs, target, None)
refs.pop(rel, None)
return refs
@@ -259,7 +276,7 @@ def string_inputs(rel: str, blob: bytes) -> tuple:
if any(maybe_not_code for _, maybe_not_code in found):
code = live_text(rel, blob)
live = {m.group(0) for r in (_DOTTED_STRING_RE, _ATTR_STRING_RE) for m in r.finditer(code)}
- return gates, sorted(found), sorted(live)
+ return gates, sorted(found), sorted(live), listing_inputs(blob)
class PythonDynamicHints(DynamicHintExtractor):
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_package_listing.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_package_listing.py
new file mode 100644
index 000000000..43f32f321
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_package_listing.py
@@ -0,0 +1,334 @@
+"""A package ``__init__`` that imports the modules of its own directory.
+
+The plugin-directory idiom::
+
+ for info in pkgutil.iter_modules(__path__):
+ importlib.import_module(f"{__name__}.{info.name}")
+
+loads every module the listing yields, so each is reached with no import
+edge. Read from the syntax tree, never the raw text, so the listing and the
+load are tied: the load must sit in the body of the loop over the listing
+and name the loop's own module name. A lazy ``__getattr__`` table, or a load
+of some other name in the same file, links nothing.
+
+Shapes read:
+
+* the listing ``iter_modules(__path__)`` / ``walk_packages(__path__)``, alone
+ or wrapped (``sorted(m.name for m in iter_modules(__path__))``); only
+ ``__path__``, since any other path is not known to be this package;
+* the load ``f"{__name__}.{name}"``, ``__name__ + "." + name``,
+ ``import_module(f".{name}", package=__name__)`` (``__package__`` in place
+ of ``__name__`` in all three), or ``import_module(name)`` when the listing
+ was given the ``__name__ + "."`` prefix and so yields full names;
+* filters on the name before the load, in an ``if`` around it, an
+ ``if ...: continue`` guard or the comprehension's ``if``:
+ ``startswith`` / ``endswith``, ``name[0] == "_"``, ``==`` / ``in`` against
+ literals, and ``ispkg``. A condition on the name in any other shape
+ (``name in SKIP``) links nothing from that load.
+
+``walk_packages`` reaches every descendant only with the prefix: without it,
+recursing imports a subpackage by its bare name, which fails, so it yields
+the direct children alone.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from collections.abc import Callable
+
+# Cheap gate before parsing: a listing of ``__path__`` somewhere in the text.
+OWN_LISTING_RE = re.compile(rb"(?:iter_modules|walk_packages)\(\s*(?:path\s*=\s*)?__path__\b")
+
+_LISTERS = frozenset({"iter_modules", "walk_packages"})
+_LOADERS = frozenset({"import_module", "__import__"})
+_WRAPPERS = frozenset({"sorted", "list", "tuple", "set", "reversed"})
+_OWN = frozenset({"__name__", "__package__"})
+_INIT_NAMES = ("__init__.py", "__init__.pyi")
+
+# A filter on (the name the loop holds, whether that module is a package).
+_Filter = Callable[[str, bool], bool]
+
+
+class _Unknown:
+ """A condition on the name this reader cannot evaluate."""
+
+
+_UNKNOWN = _Unknown()
+_Classified = _Filter | _Unknown | None # None: the condition ignores the name
+
+
+def _call_name(node: ast.expr) -> str | None:
+ if isinstance(node, ast.Name):
+ return node.id
+ return node.attr if isinstance(node, ast.Attribute) else None
+
+
+def _arg(call: ast.Call, index: int, keyword: str) -> ast.expr | None:
+ if len(call.args) > index:
+ return call.args[index]
+ return next((k.value for k in call.keywords if k.arg == keyword), None)
+
+
+def _is_own(node: ast.expr | None) -> bool:
+ return isinstance(node, ast.Name) and node.id in _OWN
+
+
+def _is_dot(node: ast.expr) -> bool:
+ return isinstance(node, ast.Constant) and node.value == "."
+
+
+def _is_own_dot(node: ast.expr | None) -> bool:
+ """``__name__ + "."`` or ``f"{__name__}."``."""
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
+ return _is_own(node.left) and _is_dot(node.right)
+ if isinstance(node, ast.JoinedStr) and len(node.values) == 2:
+ head, dot = node.values
+ return isinstance(head, ast.FormattedValue) and _is_own(head.value) and _is_dot(dot)
+ return False
+
+
+class _Refs:
+ """How the loop's code spells the listed module's name and its ``ispkg``."""
+
+ def __init__(
+ self,
+ *,
+ names: frozenset[str] = frozenset(),
+ infos: frozenset[str] = frozenset(),
+ pkgs: frozenset[str] = frozenset(),
+ ) -> None:
+ self.names, self.infos, self.pkgs = names, infos, pkgs
+
+ def _field(self, node: ast.expr, attr: str, index: int) -> bool:
+ if isinstance(node, ast.Attribute):
+ return node.attr == attr and isinstance(node.value, ast.Name) and node.value.id in self.infos
+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
+ key = node.slice
+ return node.value.id in self.infos and isinstance(key, ast.Constant) and key.value == index
+ return False
+
+ def is_name(self, node: ast.expr) -> bool:
+ return (isinstance(node, ast.Name) and node.id in self.names) or self._field(node, "name", 1)
+
+ def is_pkg(self, node: ast.expr) -> bool:
+ return (isinstance(node, ast.Name) and node.id in self.pkgs) or self._field(node, "ispkg", 2)
+
+ def mentions(self, node: ast.expr) -> bool:
+ ids = self.names | self.infos | self.pkgs
+ return any(isinstance(n, ast.Name) and n.id in ids for n in ast.walk(node))
+
+
+def _target_refs(target: ast.expr) -> _Refs | None:
+ """``for info in ...`` or ``for _, name, ispkg in ...``."""
+ if isinstance(target, ast.Name):
+ return _Refs(infos=frozenset({target.id}))
+ if isinstance(target, ast.Tuple) and len(target.elts) == 3:
+ _, name, pkg = target.elts
+ if isinstance(name, ast.Name):
+ pkgs = frozenset({pkg.id}) if isinstance(pkg, ast.Name) else frozenset()
+ return _Refs(names=frozenset({name.id}), pkgs=pkgs)
+ return None
+
+
+def _listing(node: ast.expr) -> tuple[bool, bool] | None:
+ """``(recursive, full_names)`` for a listing of ``__path__``, else ``None``."""
+ if not isinstance(node, ast.Call) or _call_name(node.func) not in _LISTERS:
+ return None
+ path = _arg(node, 0, "path")
+ if not (isinstance(path, ast.Name) and path.id == "__path__"):
+ return None
+ prefix = _arg(node, 1, "prefix")
+ if prefix is not None and not _is_own_dot(prefix):
+ return None
+ full = prefix is not None
+ return (_call_name(node.func) == "walk_packages" and full), full
+
+
+def _strings(node: ast.expr) -> tuple[str, ...] | None:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return (node.value,)
+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
+ values = [e.value for e in node.elts if isinstance(e, ast.Constant)]
+ if len(values) == len(node.elts) and all(isinstance(v, str) for v in values):
+ return tuple(values)
+ return None
+
+
+def _negate(f: _Classified) -> _Classified:
+ if f is None or isinstance(f, _Unknown):
+ return f
+ return lambda v, p: not f(v, p)
+
+
+def _classify(test: ast.expr, refs: _Refs) -> _Classified:
+ """What a condition says about which listed names pass it."""
+ if not refs.mentions(test):
+ return None
+ if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not):
+ return _negate(_classify(test.operand, refs))
+ if isinstance(test, ast.BoolOp):
+ parts = [_classify(v, refs) for v in test.values]
+ if any(isinstance(f, _Unknown) for f in parts):
+ return _UNKNOWN
+ if isinstance(test.op, ast.Or) and None in parts:
+ return _UNKNOWN # a clause on something else may pass every name
+ fs = [f for f in parts if f is not None]
+ if isinstance(test.op, ast.And):
+ return lambda v, p: all(f(v, p) for f in fs)
+ return lambda v, p: any(f(v, p) for f in fs)
+ if refs.is_pkg(test):
+ return lambda v, p: p
+ if (
+ isinstance(test, ast.Call)
+ and isinstance(test.func, ast.Attribute)
+ and test.func.attr in ("startswith", "endswith")
+ and refs.is_name(test.func.value)
+ and len(test.args) == 1
+ and (lits := _strings(test.args[0])) is not None
+ ):
+ if test.func.attr == "startswith":
+ return lambda v, p: v.startswith(lits)
+ return lambda v, p: v.endswith(lits)
+ if isinstance(test, ast.Compare) and len(test.ops) == 1:
+ left, op, right = test.left, test.ops[0], test.comparators[0]
+ lits = _strings(right)
+ if lits is None:
+ return _UNKNOWN
+ if (
+ isinstance(left, ast.Subscript)
+ and refs.is_name(left.value)
+ and isinstance(left.slice, ast.Constant)
+ and left.slice.value == 0
+ and isinstance(op, (ast.Eq, ast.NotEq))
+ ):
+ first = lits[0]
+ return (lambda v, p: v[:1] == first) if isinstance(op, ast.Eq) else (
+ lambda v, p: v[:1] != first
+ )
+ if refs.is_name(left):
+ if isinstance(op, (ast.Eq, ast.In)):
+ return lambda v, p: v in lits
+ if isinstance(op, (ast.NotEq, ast.NotIn)):
+ return lambda v, p: v not in lits
+ return _UNKNOWN
+
+
+def _loop(node: ast.For | ast.AsyncFor) -> tuple[tuple[bool, bool], _Refs, list[_Classified]] | None:
+ """The listing a loop iterates, how its body names a module, and filters."""
+ it = node.iter
+ if isinstance(it, ast.Call) and _call_name(it.func) in _WRAPPERS and len(it.args) == 1:
+ it = it.args[0]
+ spec = _listing(it)
+ if spec is not None:
+ refs = _target_refs(node.target)
+ return (spec, refs, []) if refs else None
+ if isinstance(it, (ast.GeneratorExp, ast.ListComp, ast.SetComp)) and len(it.generators) == 1:
+ gen = it.generators[0]
+ spec, inner = _listing(gen.iter), _target_refs(gen.target)
+ if spec and inner and inner.is_name(it.elt) and isinstance(node.target, ast.Name):
+ filters = [_classify(c, inner) for c in gen.ifs]
+ return spec, _Refs(names=frozenset({node.target.id})), filters
+ return None
+
+
+def _is_child_load(call: ast.Call, refs: _Refs, full: bool) -> bool:
+ """Whether *call* imports the module the loop holds."""
+ if _call_name(call.func) not in _LOADERS or not call.args:
+ return False
+ arg = call.args[0]
+ if full:
+ return refs.is_name(arg)
+ relative = False
+ if isinstance(arg, ast.JoinedStr):
+ values = arg.values
+ last = values[-1] if values else None
+ if not (isinstance(last, ast.FormattedValue) and refs.is_name(last.value)):
+ return False
+ if len(values) == 3:
+ head = values[0]
+ return isinstance(head, ast.FormattedValue) and _is_own(head.value) and _is_dot(values[1])
+ relative = len(values) == 2 and _is_dot(values[0])
+ elif isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Add) and refs.is_name(arg.right):
+ if _is_own_dot(arg.left):
+ return True
+ relative = _is_dot(arg.left)
+ return relative and _is_own(_arg(call, 1, "package"))
+
+
+def _exits(body: list[ast.stmt]) -> bool:
+ return bool(body) and isinstance(body[-1], (ast.Continue, ast.Return, ast.Raise))
+
+
+def _loads(
+ stmts: list[ast.stmt], refs: _Refs, full: bool, guard: list[_Classified], out: list
+) -> None:
+ """Collect the filters guarding each load of the loop's module in *stmts*."""
+ for st in stmts:
+ if isinstance(st, ast.If):
+ f = _classify(st.test, refs)
+ _loads(st.body, refs, full, [*guard, f], out)
+ _loads(st.orelse, refs, full, [*guard, _negate(f)], out)
+ if _exits(st.body) and not st.orelse:
+ guard = [*guard, _negate(f)] # ``if name.startswith("_"): continue``
+ elif isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue # defined in the loop, not run by it
+ elif isinstance(st, (ast.For, ast.AsyncFor, ast.While, ast.With, ast.AsyncWith)):
+ _loads(st.body, refs, full, guard, out)
+ _loads(getattr(st, "orelse", []), refs, full, guard, out)
+ elif isinstance(st, ast.Try):
+ for block in (st.body, *(h.body for h in st.handlers), st.orelse, st.finalbody):
+ _loads(block, refs, full, guard, out)
+ elif any(
+ isinstance(n, ast.Call) and _is_child_load(n, refs, full) for n in ast.walk(st)
+ ):
+ out.append(guard)
+
+
+def _listing_loops(tree: ast.AST):
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.For, ast.AsyncFor)) and (loop := _loop(node)) is not None:
+ yield node, loop
+
+
+def _parse(blob: bytes) -> ast.AST | None:
+ try:
+ return ast.parse(blob)
+ except (SyntaxError, ValueError):
+ return None
+
+
+def listed_children(blob: bytes, own: str, module_index: dict[str, str]) -> list[str]:
+ """Files of the modules a package ``__init__`` imports from its own listing.
+
+ *own* is the package's dotted name; *module_index* maps dotted names to
+ files, as :func:`build_python_module_index` builds it.
+ """
+ tree = _parse(blob)
+ if tree is None:
+ return []
+ below = [(d, p) for d, p in module_index.items() if d.startswith(f"{own}.")]
+ linked: set[str] = set()
+ for node, ((recursive, full), refs, filters) in _listing_loops(tree):
+ guards: list[list[_Classified]] = []
+ _loads(node.body, refs, full, filters, guards)
+ for guard in guards:
+ if any(isinstance(f, _Unknown) for f in guard):
+ continue
+ checks = [f for f in guard if f is not None]
+ for dotted, path in below:
+ tail = dotted[len(own) + 1 :]
+ if "." in tail and not recursive:
+ continue
+ value = dotted if full else tail
+ if all(f(value, path.endswith(_INIT_NAMES)) for f in checks):
+ linked.add(path)
+ return sorted(linked)
+
+
+def listing_inputs(blob: bytes) -> tuple[str, ...]:
+ """The listing loops :func:`listed_children` reads, for comparing two versions."""
+ if not OWN_LISTING_RE.search(blob):
+ return ()
+ tree = _parse(blob)
+ return tuple(ast.dump(node) for node, _ in _listing_loops(tree)) if tree else ()
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index 9c0a43693..36b4ce94b 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -346,16 +346,18 @@ async def get_dead_code_summary(
# risk-factor logic existed (or in a config/bootstrap/database/environment
# file the allowlist missed) are not counted as deletion-ready.
# Totals sum the known counts; an unknown (NULL) count adds nothing.
- deletable_lines = sum(
- f.lines or 0
+ deletable = [
+ f
for f in findings
if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete, f.kind)
- )
+ ]
+ deletable_lines = sum(f.lines or 0 for f in deletable)
return {
"total_findings": len(findings),
"confidence_summary": summary,
"deletable_lines": deletable_lines,
+ "safe_to_delete_count": len(deletable),
"total_lines": total_lines,
"by_kind": by_kind,
"gated": gated,
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 8cb080fe1..50358db28 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -102,6 +102,8 @@ class DeadCodeSummaryResponse(BaseModel):
total_findings: int
confidence_summary: dict
deletable_lines: int
+ #: Deletion-ready findings, the ones ``deletable_lines`` sums.
+ safe_to_delete_count: int | None = None
total_lines: int
by_kind: dict
# When dead-code analysis last ran; None = never ran or unknown (not all-clear).
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.ts
index 0035e5f64..dbaaec624 100644
--- a/packages/types/src/dead-code.ts
+++ b/packages/types/src/dead-code.ts
@@ -121,6 +121,8 @@ export interface DeadCodeSummary {
total_findings: number;
confidence_summary: Record<string, number>;
deletable_lines: number;
+ /** Deletion-ready findings, the ones `deletable_lines` sums. Absent from older hosts. */
+ safe_to_delete_count?: number | null;
total_lines: number;
by_kind: Record<string, number>;
/**
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index d5f175293..ba69fd595 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1181,6 +1181,7 @@ export interface DeadCodeSummaryResponse {
total_findings: number;
confidence_summary: Record<string, unknown>;
deletable_lines: number;
+ safe_to_delete_count?: number | null;
total_lines: number;
by_kind: Record<string, unknown>;
analyzed_at?: string | null;
diff --git a/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx
index b29f6c702..b22b36ab4 100644
--- a/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx
+++ b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx
@@ -7,61 +7,106 @@ const SUMMARY: DeadCodeSummary = {
total_findings: 142,
confidence_summary: { high: 89, medium: 41, low: 12 },
deletable_lines: 4321,
+ safe_to_delete_count: 12,
total_lines: 91234,
by_kind: { unreachable_file: 12, unused_export: 88, zombie_package: 42 },
analyzed_at: new Date(Date.now() - 2 * 86_400_000).toISOString(),
};
+const prose = () => screen.getByText(/deletion-ready/, { selector: "span" }).closest("p")!;
+
describe("DeadCodeLede", () => {
- it("leads with the reclaimable line count", () => {
+ it("leads with the deletion-ready line count, not the flagged total", () => {
render(<DeadCodeLede summary={SUMMARY} />);
expect(screen.getByText("4,321")).toBeInTheDocument();
+ expect(screen.queryByText("91,234")).not.toBeInTheDocument();
expect(screen.getByText("lines")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "What Deletion-ready means" })).toBeInTheDocument();
});
- it("says the posture in one sentence, with when it was measured", () => {
+ it("names the deletion-ready findings, then the flagged rest as a quieter fact", () => {
render(<DeadCodeLede summary={SUMMARY} />);
- const prose = screen.getByText(/have no reachable caller/);
- expect(prose.textContent).toBe(
- "142 findings across 91,234 lines have no reachable caller. Analysed 2d ago.",
+ expect(prose().textContent).toBe(
+ "12 findings are deletion-ready. 130 more are flagged for review. Analysed 2d ago.",
+ );
+ expect(screen.getByText("130 more are flagged for review.").className).toMatch(/text-tertiary/);
+ });
+
+ it("drops the flagged sentence when every finding is deletion-ready", () => {
+ render(
+ <DeadCodeLede
+ summary={{ ...SUMMARY, total_findings: 1, safe_to_delete_count: 1, analyzed_at: null }}
+ />,
+ );
+ expect(prose().textContent).toBe("1 finding is deletion-ready.");
+ });
+
+ it("says plainly when nothing is deletion-ready, with the flagged total", () => {
+ render(
+ <DeadCodeLede
+ summary={{ ...SUMMARY, total_findings: 17, total_lines: 2029, deletable_lines: 0, safe_to_delete_count: 0 }}
+ />,
+ );
+ expect(screen.getByText("0")).toBeInTheDocument();
+ expect(prose().textContent).toBe(
+ "Nothing is deletion-ready right now. 17 findings across 2,029 lines are flagged for review. Analysed 2d ago.",
+ );
+ });
+
+ it("counts findings when the deletion-ready ones have no known size", () => {
+ render(<DeadCodeLede summary={{ ...SUMMARY, deletable_lines: 0, safe_to_delete_count: 2 }} />);
+ expect(prose().textContent).toMatch(/^2 findings are deletion-ready\. 140 more/);
+ expect(screen.getByText("2")).toBeInTheDocument();
+ expect(screen.getByText("findings")).toBeInTheDocument();
+ expect(screen.queryByText("lines")).not.toBeInTheDocument();
+ });
+
+ it("joins the sentences with the host's separator", () => {
+ render(<DeadCodeLede summary={{ ...SUMMARY, analyzed_at: null }} labels={{ separator: "" }} />);
+ expect(prose().textContent).toBe("12 findings are deletion-ready.130 more are flagged for review.");
+ });
+
+ it("falls back to the lines for a host that sends no count", () => {
+ const { safe_to_delete_count: _omit, ...older } = SUMMARY;
+ render(<DeadCodeLede summary={{ ...older, analyzed_at: null }} />);
+ expect(prose().textContent).toBe(
+ "These lines are deletion-ready. 142 findings across 91,234 lines are flagged in all.",
+ );
+ });
+
+ it("treats a host with no count and no lines as nothing deletion-ready", () => {
+ const { safe_to_delete_count: _omit, ...older } = SUMMARY;
+ render(<DeadCodeLede summary={{ ...older, deletable_lines: 0, analyzed_at: null }} />);
+ expect(prose().textContent).toBe(
+ "Nothing is deletion-ready right now. 142 findings across 91,234 lines are flagged for review.",
+ );
+ });
+
+ it("takes translated copy from the host", () => {
+ render(
+ <DeadCodeLede
+ summary={{ ...SUMMARY, analyzed_at: null }}
+ labels={{ label: "可删除", ready: (n) => `${n} 项发现可删除。`, moreFlagged: (n) => `另有 ${n} 项已标记,待审查。` }}
+ />,
);
+ expect(screen.getByText("12 项发现可删除。")).toBeInTheDocument();
+ expect(screen.getByText("另有 130 项已标记,待审查。")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "What 可删除 means" })).toBeInTheDocument();
});
it("carries no stat ribbon or confidence bar repeating the sentence", () => {
render(<DeadCodeLede summary={SUMMARY} />);
expect(screen.queryByText("High confidence")).not.toBeInTheDocument();
expect(screen.queryByLabelText("89 high confidence")).not.toBeInTheDocument();
- // The methodology sits behind the label's info tip instead of in prose.
- expect(screen.getByRole("button", { name: "What Reclaimable means" })).toBeInTheDocument();
});
it("drops the time rather than inventing one when the run is unknown", () => {
render(<DeadCodeLede summary={{ ...SUMMARY, analyzed_at: null }} />);
- expect(screen.getByText(/have no reachable caller/).textContent).not.toMatch(/Analysed/);
+ expect(prose().textContent).not.toMatch(/Analysed/);
});
it("renders no time for a host that does not report one", () => {
const { container } = render(<AnalysedAt at={undefined} />);
expect(container).toBeEmptyDOMElement();
});
-
- it("agrees in number for a single finding", () => {
- render(
- <DeadCodeLede
- summary={{ ...SUMMARY, total_findings: 1, total_lines: 12, deletable_lines: 1, analyzed_at: null }}
- />,
- );
- expect(screen.getByText(/no reachable caller/).textContent).toBe(
- "1 finding across 12 lines has no reachable caller.",
- );
- });
-
- it("shows flagged lines, not a zero, when nothing is deletion-ready", () => {
- render(<DeadCodeLede summary={{ ...SUMMARY, total_findings: 47, total_lines: 1669, deletable_lines: 0 }} />);
- expect(screen.getByText("1,669")).toBeInTheDocument();
- expect(screen.getByText(/have no reachable caller/).textContent).toBe(
- "47 findings have no reachable caller. None is deletion-ready yet, so review them before deleting. Analysed 2d ago.",
- );
- expect(screen.getByRole("button", { name: "What Flagged means" })).toBeInTheDocument();
- });
});
diff --git a/packages/ui/src/dead-code/dead-code-lede.tsx b/packages/ui/src/dead-code/dead-code-lede.tsx
index aa403a574..140f6a5ba 100644
--- a/packages/ui/src/dead-code/dead-code-lede.tsx
+++ b/packages/ui/src/dead-code/dead-code-lede.tsx
@@ -1,10 +1,11 @@
/**
- * The Dead Code tab's opening read: one figure (reclaimable lines) and one
- * sentence saying what it is a share of and when it was measured.
+ * The Dead Code tab's opening read: one figure (deletion-ready lines) and one
+ * sentence saying how much more is flagged and when it was measured.
*
- * Earlier versions added three paragraphs, a confidence bar and a five-stat
- * ribbon under the figure; every one of them restated the same three numbers.
- * The confidence methodology lives on the label's info tip instead.
+ * The figure is the deletion-ready share, never the flagged total: flagged
+ * includes low-confidence findings with known false-positive classes, so it
+ * overstates what can go. Flagged stays as the quieter second sentence.
+ * The confidence methodology lives on the label's info tip.
*/
import type { ReactNode } from "react";
@@ -13,19 +14,68 @@ import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
import { PageLede } from "../shared/page-lede";
import { formatDateTime, formatNumber, formatRelativeTimeOrNull } from "../lib/format";
+/** Counts a flagged sentence quotes. */
+export interface DeadCodeFlaggedCounts {
+ findings: number;
+ lines: number;
+}
+
+/** Every string the lede renders, so a host can translate it. */
+export interface DeadCodeLedeLabels {
+ label: string;
+ labelHint: string;
+ unit: string;
+ /** The unit when the figure is a finding count (deletion-ready findings of unknown size). */
+ findingsUnit: (count: number) => string;
+ /** Between the two sentences: a space in English, nothing in Chinese. */
+ separator: string;
+ /** No open findings. */
+ clean: string;
+ /** "12 findings are deletion-ready." */
+ ready: (count: number) => string;
+ /** Deletion-ready lines from a host that does not report the finding count. */
+ readyUncounted: string;
+ /** "130 more are flagged for review." */
+ moreFlagged: (count: number) => string;
+ /** The flagged total, after `readyUncounted`. */
+ flaggedInAll: (c: DeadCodeFlaggedCounts) => string;
+ /** Nothing deletion-ready, said as a plain fact. */
+ noneReady: string;
+ /** The flagged total, after `noneReady`. */
+ flaggedForReview: (c: DeadCodeFlaggedCounts) => string;
+}
+
+function plural(n: number, word: string): string {
+ return `${formatNumber(n)} ${word}${n === 1 ? "" : "s"}`;
+}
+
+const flagged = (c: DeadCodeFlaggedCounts) =>
+ `${plural(c.findings, "finding")} across ${plural(c.lines, "line")}`;
+const isAre = (n: number) => (n === 1 ? "is" : "are");
+
+export const DEFAULT_DEAD_CODE_LEDE_LABELS: DeadCodeLedeLabels = {
+ label: "Deletion-ready",
+ labelHint:
+ "Deletion-ready means high confidence and outside the config, bootstrap and environment paths we never delete from unreviewed. Confidence is a statement about the language, not a hedge: a Python entry point registered by name or a TypeScript symbol re-exported through a barrel file is invisible to a call-graph walk.",
+ unit: "lines",
+ findingsUnit: (count) => (count === 1 ? "finding" : "findings"),
+ separator: " ",
+ clean: "No open findings remain.",
+ ready: (count) => `${plural(count, "finding")} ${isAre(count)} deletion-ready.`,
+ readyUncounted: "These lines are deletion-ready.",
+ moreFlagged: (count) => `${formatNumber(count)} more ${isAre(count)} flagged for review.`,
+ flaggedInAll: (c) => `${flagged(c)} ${isAre(c.findings)} flagged in all.`,
+ noneReady: "Nothing is deletion-ready right now.",
+ flaggedForReview: (c) => `${flagged(c)} ${isAre(c.findings)} flagged for review.`,
+};
+
export interface DeadCodeLedeProps {
summary: DeadCodeSummary;
/** Rendered under the prose. The tab's one action. */
action?: ReactNode;
/** Replaces the posture sentence, e.g. with the all-clear state. */
children?: ReactNode;
-}
-
-const CONFIDENCE_HINT =
- "Deletion-ready means high confidence and outside the config, bootstrap and environment paths we never delete from unreviewed. Confidence is a statement about the language, not a hedge: a Python entry point registered by name or a TypeScript symbol re-exported through a barrel file is invisible to a call-graph walk.";
-
-function plural(n: number, word: string): string {
- return `${formatNumber(n)} ${word}${n === 1 ? "" : "s"}`;
+ labels?: Partial<DeadCodeLedeLabels>;
}
/** "Analysed 2d ago." with the exact time on hover, or nothing when unknown. */
@@ -42,35 +92,46 @@ export function AnalysedAt({ at }: { at: string | null | undefined }) {
);
}
-export function DeadCodeLede({ summary, action, children }: DeadCodeLedeProps) {
+/** The posture: the deletion-ready read, then the flagged total (or null). */
+function posture(summary: DeadCodeSummary, l: DeadCodeLedeLabels): [string, string | null] {
const findings = summary.total_findings;
- const strong = "font-semibold text-[var(--color-text-primary)]";
- const ready = summary.deletable_lines > 0;
+ const total = { findings, lines: summary.total_lines };
+ if (findings === 0) return [l.clean, null];
+ const ready = summary.safe_to_delete_count;
+ // The count when the host sends it, since a finding of unknown size adds
+ // no lines; the lines otherwise.
+ if (ready === 0 || (ready == null && summary.deletable_lines <= 0)) {
+ return [l.noneReady, l.flaggedForReview(total)];
+ }
+ if (ready == null) return [l.readyUncounted, l.flaggedInAll(total)];
+ const rest = findings - ready;
+ return [l.ready(ready), rest > 0 ? l.moreFlagged(rest) : null];
+}
+
+export function DeadCodeLede({ summary, action, children, labels }: DeadCodeLedeProps) {
+ const l = { ...DEFAULT_DEAD_CODE_LEDE_LABELS, ...labels };
+ const [lead, rest] = posture(summary, l);
+ const ready = summary.safe_to_delete_count ?? 0;
+ // Deletion-ready findings whose size is unknown add no lines: count them
+ // instead of showing "0 lines" beside "2 findings are deletion-ready".
+ const byCount = ready > 0 && summary.deletable_lines <= 0;
return (
<PageLede
- label={findings > 0 && !ready ? "Flagged" : "Reclaimable"}
- labelHint={CONFIDENCE_HINT}
- value={formatNumber(findings > 0 && !ready ? summary.total_lines : summary.deletable_lines)}
- unit="lines"
+ label={l.label}
+ labelHint={l.labelHint}
+ value={formatNumber(byCount ? ready : Math.max(summary.deletable_lines, 0))}
+ unit={byCount ? l.findingsUnit(ready) : l.unit}
layout="beside"
{...(action ? { action } : {})}
>
{children ?? (
<p>
- {findings === 0 ? (
- "No open findings remain."
- ) : ready ? (
- <>
- <strong className={strong}>{plural(findings, "finding")}</strong> across{" "}
- <strong className={strong}>{plural(summary.total_lines, "line")}</strong>{" "}
- {findings === 1 ? "has" : "have"} no reachable caller.
- </>
- ) : (
+ <span className="font-semibold text-[var(--color-text-primary)]">{lead}</span>
+ {rest && (
<>
- <strong className={strong}>{plural(findings, "finding")}</strong>{" "}
- {findings === 1 ? "has" : "have"} no reachable caller. None is deletion-ready yet,
- so review {findings === 1 ? "it" : "them"} before deleting.
+ {l.separator}
+ <span className="text-[var(--color-text-tertiary)]">{rest}</span>
</>
)}
<AnalysedAt at={summary.analyzed_at} />
diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsx
index e61743fd2..89b75c142 100644
--- a/packages/ui/src/dead-code/dead-code-view.tsx
+++ b/packages/ui/src/dead-code/dead-code-view.tsx
@@ -3,7 +3,7 @@
/**
* Dead Code view, on the section design language.
*
- * Three things, top to bottom: a lede with the reclaimable line count and one
+ * Three things, top to bottom: a lede with the deletion-ready line count and one
* posture sentence, the safe-to-delete list, and the full findings table with
* its status control in the section header. Carries the optimistic row patch
* + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and
@@ -37,7 +37,7 @@ import { OverviewSection } from "../overview/section";
import { AiPromptModal } from "../health/ai-prompt-modal";
import { buildDeadCodeAiPrompt } from "../health/ai-prompt-builder";
-import { AnalysedAt, DeadCodeLede } from "./dead-code-lede";
+import { AnalysedAt, DeadCodeLede, type DeadCodeLedeLabels } from "./dead-code-lede";
import { SafeToDeletePile } from "./safe-to-delete-pile";
import { FindingsTable } from "./findings-table";
import { DEAD_CODE_STATUS_LABELS } from "./finding-cells";
@@ -72,7 +72,14 @@ function RetryCard({
);
}
-export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {
+export function DeadCodeView({
+ adapter,
+ ledeLabels,
+}: {
+ adapter: DeadCodeAdapter;
+ /** The lede's copy, for a host that translates it. */
+ ledeLabels?: Partial<DeadCodeLedeLabels>;
+}) {
const [analyzing, setAnalyzing] = useState(false);
const [promptIds, setPromptIds] = useState<string[] | null>(null);
/** Which slice the findings table shows; the lede and the list stay open-only. */
@@ -351,7 +358,11 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {
{analyzeAction("Run analysis")}
</EmptyState>
) : (
- <DeadCodeLede summary={summary} action={analyzeAction("Re-analyze")}>
+ <DeadCodeLede
+ summary={summary}
+ action={analyzeAction("Re-analyze")}
+ {...(ledeLabels ? { labels: ledeLabels } : {})}
+ >
{clean ? (
<EmptyState
tone="positive"
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index baf06d15c..22a6af98d 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1092,6 +1092,20 @@
"byDirectory": "By directory",
"byDirectoryBody": "Where the matches concentrate, busiest directories first."
},
+ "deadCodeLede": {
+ "label": "Deletion-ready",
+ "labelHint": "Deletion-ready means high confidence and outside the config, bootstrap and environment paths we never delete from unreviewed. Confidence is a statement about the language, not a hedge: a Python entry point registered by name or a TypeScript symbol re-exported through a barrel file is invisible to a call-graph walk.",
+ "unit": "lines",
+ "findingsUnit": "{count, plural, one {finding} other {findings}}",
+ "separator": " ",
+ "clean": "No open findings remain.",
+ "ready": "{count, plural, one {# finding is} other {# findings are}} deletion-ready.",
+ "readyUncounted": "These lines are deletion-ready.",
+ "moreFlagged": "{count, plural, one {# more is} other {# more are}} flagged for review.",
+ "flaggedInAll": "{findings, plural, one {# finding} other {# findings}} across {lines, plural, one {# line} other {# lines}} {findings, plural, one {is} other {are}} flagged in all.",
+ "noneReady": "Nothing is deletion-ready right now.",
+ "flaggedForReview": "{findings, plural, one {# finding} other {# findings}} across {lines, plural, one {# line} other {# lines}} {findings, plural, one {is} other {are}} flagged for review."
+ },
"analysisTimeout": "Analysis is taking longer than expected. Reload to see the results.",
"syncStarted": "Sync started — findings refresh when it completes",
"syncFailed": "Couldn't start a sync",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 20a374c55..b51620354 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1092,6 +1092,20 @@
"byDirectory": "按目录",
"byDirectoryBody": "匹配集中的位置,按数量从多到少排列。"
},
+ "deadCodeLede": {
+ "label": "可删除",
+ "labelHint": "可删除指置信度高,且不在配置、引导和环境路径中,这些路径未经审查我们从不删除。置信度描述的是语言本身,而不是含糊其辞:按名称注册的 Python 入口点,或通过 barrel 文件重新导出的 TypeScript 符号,调用图遍历都看不到。",
+ "unit": "行",
+ "findingsUnit": "项发现",
+ "separator": "",
+ "clean": "没有待处理的发现。",
+ "ready": "{count, number} 项发现可删除。",
+ "readyUncounted": "这些行可删除。",
+ "moreFlagged": "另有 {count, number} 项已标记,待审查。",
+ "flaggedInAll": "共有 {findings, number} 项发现、{lines, number} 行被标记。",
+ "noneReady": "目前没有可删除的代码。",
+ "flaggedForReview": "{findings, number} 项发现(共 {lines, number} 行)已标记,待审查。"
+ },
"analysisTimeout": "分析耗时超出预期。请重新加载以查看结果。",
"syncStarted": "同步已开始 —— 完成后发现项会刷新",
"syncFailed": "无法启动同步",
diff --git a/packages/web/src/components/risk/dead-code-tab.test.tsx b/packages/web/src/components/risk/dead-code-tab.test.tsx
new file mode 100644
index 000000000..78d548dd2
--- /dev/null
+++ b/packages/web/src/components/risk/dead-code-tab.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { NextIntlClientProvider } from "next-intl";
+import { describe, expect, it, vi } from "vitest";
+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
+import { DeadCodeLede } from "@repowise-dev/ui/dead-code";
+import zhMessages from "../../../messages/zh-CN.json";
+import { useLedeLabels } from "./dead-code-tab";
+
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
+
+const SUMMARY: DeadCodeSummary = {
+ total_findings: 1420,
+ confidence_summary: {},
+ deletable_lines: 4321,
+ safe_to_delete_count: 12,
+ total_lines: 91234,
+ by_kind: {},
+ analyzed_at: null,
+};
+
+function Lede({ summary }: { summary: DeadCodeSummary }) {
+ return <DeadCodeLede summary={summary} labels={useLedeLabels()} />;
+}
+
+const NONE_READY = { ...SUMMARY, total_findings: 17, total_lines: 2029, deletable_lines: 0, safe_to_delete_count: 0 };
+
+describe("dead-code lede copy", () => {
+ it("reads the English catalog", () => {
+ const { container } = render(<Lede summary={SUMMARY} />);
+ expect(container.querySelector("p:has(> span)")?.textContent).toBe(
+ "12 findings are deletion-ready. 1,408 more are flagged for review.",
+ );
+ expect(screen.getByRole("button", { name: "What Deletion-ready means" })).toBeTruthy();
+ });
+
+ it("says plainly in English when nothing is deletion-ready", () => {
+ const { container } = render(<Lede summary={NONE_READY} />);
+ expect(container.querySelector("p:has(> span)")?.textContent).toBe(
+ "Nothing is deletion-ready right now. 17 findings across 2,029 lines are flagged for review.",
+ );
+ });
+
+ it("reads the zh-CN catalog", () => {
+ const { container } = render(
+ <NextIntlClientProvider locale="zh-CN" messages={zhMessages}>
+ <Lede summary={SUMMARY} />
+ <Lede summary={NONE_READY} />
+ </NextIntlClientProvider>,
+ );
+ expect([...container.querySelectorAll("p:has(> span)")].map((p) => p.textContent)).toEqual([
+ "12 项发现可删除。另有 1,408 项已标记,待审查。",
+ "目前没有可删除的代码。17 项发现(共 2,029 行)已标记,待审查。",
+ ]);
+ });
+});
diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsx
index c4bfe9e42..3122728f9 100644
--- a/packages/web/src/components/risk/dead-code-tab.tsx
+++ b/packages/web/src/components/risk/dead-code-tab.tsx
@@ -8,8 +8,13 @@
* injects the app-specific pieces so web and hosted render the same view.
*/
+import { useMemo } from "react";
import { useRouter } from "next/navigation";
-import { DeadCodeView, type DeadCodeAdapter } from "@repowise-dev/ui/dead-code";
+import {
+ DeadCodeView,
+ type DeadCodeAdapter,
+ type DeadCodeLedeLabels,
+} from "@repowise-dev/ui/dead-code";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getDeadCodeSummary,
@@ -47,6 +52,7 @@ async function waitForJob(jobId: string, timeoutMessage: string): Promise<void>
export function DeadCodeTab({ repoId }: { repoId: string }) {
const t = useTranslations("risk");
const router = useRouter();
+ const ledeLabels = useLedeLabels();
const prefix = `/repos/${repoId}`;
const adapter: DeadCodeAdapter = {
@@ -63,5 +69,27 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
navigate: (href) => router.push(href),
};
- return <DeadCodeView adapter={adapter} />;
+ return <DeadCodeView adapter={adapter} ledeLabels={ledeLabels} />;
+}
+
+/** The lede copy from the catalog; exported for its test. */
+export function useLedeLabels(): DeadCodeLedeLabels {
+ const t = useTranslations("risk.deadCodeLede");
+ return useMemo<DeadCodeLedeLabels>(
+ () => ({
+ label: t("label"),
+ labelHint: t("labelHint"),
+ unit: t("unit"),
+ findingsUnit: (count) => t("findingsUnit", { count }),
+ separator: t("separator"),
+ clean: t("clean"),
+ ready: (count) => t("ready", { count }),
+ readyUncounted: t("readyUncounted"),
+ moreFlagged: (count) => t("moreFlagged", { count }),
+ flaggedInAll: ({ findings, lines }) => t("flaggedInAll", { findings, lines }),
+ noneReady: t("noneReady"),
+ flaggedForReview: ({ findings, lines }) => t("flaggedForReview", { findings, lines }),
+ }),
+ [t],
+ );
}
diff --git a/tests/unit/ingestion/test_python_dead_code_fixes.py b/tests/unit/ingestion/test_python_dead_code_fixes.py
index 9bc27abf5..df1e1c5ef 100644
--- a/tests/unit/ingestion/test_python_dead_code_fixes.py
+++ b/tests/unit/ingestion/test_python_dead_code_fixes.py
@@ -446,3 +446,38 @@ def test_whole_module_hint_folded_into_an_import_marks_target_file_live() -> Non
)
assert not {"OllamaProvider", "app"} & _unused_export_names(g)
+
+
+def test_package_importing_its_own_path_listing_keeps_its_modules_reachable(
+ tmp_path: Path,
+) -> None:
+ """``for m in pkgutil.iter_modules(__path__): import_module(f"{__name__}.{m.name}")``
+ loads every module in the package, so none of them is unreachable and
+ their exports stay live; a module outside the package is still flagged."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/main.py": "from pkg import sections\n",
+ "pkg/sections/__init__.py": (
+ "import importlib\nimport pkgutil\n"
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n'
+ ),
+ "pkg/sections/alpha.py": "class AlphaSection:\n pass\n",
+ "pkg/sections/beta.py": "def register():\n pass\n",
+ "pkg/orphan.py": "def lonely():\n pass\n",
+ }
+ for path, src in sources.items():
+ (tmp_path / path).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / path).write_text(src)
+ builder = GraphBuilder()
+ for path, src in sources.items():
+ builder.add_file(_PARSER.parse_file(_file_info(path), src.encode("utf-8")))
+ builder.build()
+ builder.add_dynamic_edges(PythonDynamicHints().extract(tmp_path))
+ graph = builder.graph()
+
+ unreachable = _unreachable_paths(graph)
+ assert "pkg/sections/alpha.py" not in unreachable
+ assert "pkg/sections/beta.py" not in unreachable
+ assert "pkg/orphan.py" in unreachable
+ assert not {"AlphaSection", "register"} & _unused_export_names(graph)
diff --git a/tests/unit/ingestion/test_python_string_registry_hints.py b/tests/unit/ingestion/test_python_string_registry_hints.py
index d2388668f..402c23871 100644
--- a/tests/unit/ingestion/test_python_string_registry_hints.py
+++ b/tests/unit/ingestion/test_python_string_registry_hints.py
@@ -218,6 +218,221 @@ def test_wide_or_one_segment_template_links_the_package_only() -> None:
}
+_SECTIONS = {
+ "src/app/__init__.py": "",
+ "src/app/sections/a.py": "",
+ "src/app/sections/b.py": "",
+ "src/app/sections/sub/__init__.py": "",
+ "src/app/sections/sub/deep.py": "",
+ "src/app/other.py": "",
+}
+_SECTIONS_PKG = "src/app/sections/__init__.py"
+_CHILDREN = {
+ "src/app/sections/a.py": (),
+ "src/app/sections/b.py": (),
+ "src/app/sections/sub/__init__.py": (),
+}
+
+
+def _sections(init: str, **extra: str) -> dict[str, str]:
+ return {**_SECTIONS, _SECTIONS_PKG: "import importlib\nimport pkgutil\n" + init, **extra}
+
+
+def test_package_importing_its_own_path_listing_reaches_every_child() -> None:
+ for load in (
+ 'importlib.import_module(f"{__name__}.{_m.name}")',
+ 'importlib.import_module(__name__ + "." + _m.name)',
+ 'importlib.import_module(f".{_m.name}", package=__name__)',
+ 'importlib.import_module("." + _m.name, __name__)',
+ 'importlib.import_module(f"{__package__}.{_m.name}")',
+ ):
+ files = _sections(f"for _m in pkgutil.iter_modules(__path__):\n {load}\n")
+ assert _refs(files, _SECTIONS_PKG) == _CHILDREN, load
+
+
+def test_walk_packages_with_name_prefix_reaches_every_descendant() -> None:
+ files = _sections(
+ 'for _m in pkgutil.walk_packages(__path__, __name__ + "."):\n'
+ " importlib.import_module(_m.name)\n"
+ )
+ assert _refs(files, _SECTIONS_PKG) == {**_CHILDREN, "src/app/sections/sub/deep.py": ()}
+
+
+def test_own_path_listing_is_not_capped() -> None:
+ many = {f"src/app/sections/p{i}.py": "" for i in range(60)}
+ files = _sections(
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n',
+ **many,
+ )
+ assert set(many) <= set(_refs(files, _SECTIONS_PKG))
+
+
+def test_listing_loop_that_skips_private_names_does_not_link_them() -> None:
+ private = {"src/app/sections/_helpers.py": "", "src/app/sections/sub/_impl.py": ""}
+ skipping = _sections(
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' if not _m.name.startswith("_"):\n'
+ ' importlib.import_module(f".{_m.name}", __package__)\n',
+ **private,
+ )
+ assert _refs(skipping, _SECTIONS_PKG) == _CHILDREN
+ # With no such filter the loop loads them too.
+ loading_all = _sections(
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n',
+ **private,
+ )
+ assert _refs(loading_all, _SECTIONS_PKG) == {**_CHILDREN, "src/app/sections/_helpers.py": ()}
+
+
+def test_a_load_outside_the_listing_loop_links_nothing() -> None:
+ for init in (
+ # The listing feeds a name list; a separate loop loads its own names.
+ "NAMES = [m.name for m in pkgutil.iter_modules(__path__)]\n"
+ 'for n in ["a"]:\n'
+ ' importlib.import_module(f"{__name__}.{n}")\n',
+ # A lazy table in the same file as a listing.
+ "NAMES = [m.name for m in pkgutil.iter_modules(__path__)]\n"
+ '_LAZY = {"A": "a"}\n'
+ "def __getattr__(name):\n"
+ ' return importlib.import_module(f"{__name__}.{_LAZY[name]}")\n',
+ # Inside the loop, but not the loop's name.
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' importlib.import_module(f"{__name__}.{OTHER}")\n',
+ ):
+ assert _refs(_sections(init), _SECTIONS_PKG) == {}, init
+
+
+def test_a_name_guard_links_only_the_names_it_passes() -> None:
+ files = _sections(
+ "for _m in pkgutil.iter_modules(__path__):\n"
+ ' if _m.name == "a":\n'
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n'
+ )
+ assert _refs(files, _SECTIONS_PKG) == {"src/app/sections/a.py": ()}
+
+
+def test_an_unrelated_import_beside_a_full_name_listing_links_nothing() -> None:
+ files = _sections(
+ 'for _m in pkgutil.walk_packages(__path__, __name__ + "."):\n'
+ " print(_m.name)\n"
+ 'importlib.import_module("json")\n'
+ )
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+_EXTRA = {"src/app/sections/_helpers.py": "", "src/app/sections/test_a.py": ""}
+_LOOP = "for _m in pkgutil.iter_modules(__path__):\n"
+_LOAD = 'importlib.import_module(f"{__name__}.{_m.name}")\n'
+_ALL = {**_CHILDREN, **{path: () for path in _EXTRA}}
+
+
+def test_skip_filters_are_read_from_the_loop_body() -> None:
+ for body, expected in (
+ (f' if _m.name[0] != "_":\n {_LOAD}', {
+ k: v for k, v in _ALL.items() if "/_helpers" not in k
+ }),
+ (f' if _m.name.startswith("__"):\n continue\n {_LOAD}', _ALL),
+ (f' if not _m.name.startswith("test"):\n {_LOAD}', {
+ k: v for k, v in _ALL.items() if "/test_a" not in k
+ }),
+ (f" if _m.ispkg:\n {_LOAD}", {"src/app/sections/sub/__init__.py": ()}),
+ # A filter the reader cannot evaluate links nothing from that load.
+ (f" if _m.name not in SKIP:\n {_LOAD}", {}),
+ # A skip in a comment or string is not a filter.
+ (f' # if _m.name.startswith("_"): continue\n "startswith(\'_\')"\n {_LOAD}', _ALL),
+ ):
+ assert _refs(_sections(_LOOP + body, **_EXTRA), _SECTIONS_PKG) == expected, body
+
+
+def test_a_filtered_comprehension_listing_links_what_passes() -> None:
+ files = _sections(
+ "for name in sorted(m.name for m in pkgutil.iter_modules(__path__) if m.name != 'b'):\n"
+ " importlib.import_module(f'.{name}', __package__)\n"
+ )
+ assert _refs(files, _SECTIONS_PKG) == {
+ "src/app/sections/a.py": (),
+ "src/app/sections/sub/__init__.py": (),
+ }
+
+
+def test_relative_load_anchored_on_something_else_links_nothing() -> None:
+ files = _sections(
+ _LOOP + " importlib.import_module(f'.{_m.name}', __name__.rpartition('.')[0])\n"
+ )
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+def test_walk_packages_without_a_prefix_yields_children_only() -> None:
+ # Recursing imports ``sub`` by its bare name, which fails, so
+ # ``sub.deep`` is never listed.
+ files = _sections(
+ "for _m in pkgutil.walk_packages(__path__):\n"
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n'
+ )
+ assert _refs(files, _SECTIONS_PKG) == _CHILDREN
+
+
+def test_listing_some_other_path_keeps_the_cap() -> None:
+ many = {f"src/app/sections/p{i}.py": "" for i in range(60)}
+ files = _sections(
+ "for _m in pkgutil.iter_modules([PLUGIN_DIR]):\n"
+ ' importlib.import_module(f"{__name__}.{_m.name}")\n',
+ **many,
+ )
+ # Over the cap with no listing to vouch for it: the package only, which
+ # is this file, so nothing.
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+def test_own_path_listing_without_an_import_adds_nothing() -> None:
+ files = _sections(
+ "NAMES = [m.name for m in pkgutil.iter_modules(__path__)]\n"
+ 'NAMED = list(pkgutil.walk_packages(__path__, __name__ + "."))\n'
+ )
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+def test_own_path_listing_in_a_comment_adds_nothing() -> None:
+ files = _sections(
+ "# for _m in pkgutil.walk_packages(__path__, __name__ + '.'):\n"
+ "importlib.import_module(NAME)\n"
+ )
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+def test_lazy_getattr_table_on_the_own_name_adds_nothing() -> None:
+ # Spells the same load but reaches only the modules its table names.
+ files = _sections(
+ '_LAZY = {"A": "a"}\n'
+ "def __getattr__(name):\n"
+ ' return getattr(importlib.import_module(f"{__name__}.{_LAZY[name]}"), name)\n'
+ )
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
+def test_own_name_template_in_a_plain_module_adds_nothing() -> None:
+ loader = "src/app/sections/loader.py"
+ files = _sections(
+ "",
+ **{
+ loader: (
+ "import importlib\n"
+ "def load(name):\n"
+ ' importlib.import_module(f"{__name__}.{name}")\n'
+ ' importlib.import_module(f"{__package__}.{name}")\n'
+ )
+ },
+ )
+ assert _refs(files, loader) == {}
+
+
+def test_relative_template_without_an_anchor_adds_nothing() -> None:
+ files = _sections('importlib.import_module(f".{NAME}")\n')
+ assert _refs(files, _SECTIONS_PKG) == {}
+
+
def _hint(source: str, target: str, names: tuple[str, ...] = ()) -> DynamicEdge:
return DynamicEdge(source, target, "dynamic_uses", "python_dynamic_import", imported_names=names)
diff --git a/tests/unit/persistence/test_dead_code_crud.py b/tests/unit/persistence/test_dead_code_crud.py
index 2524ed17f..ae8ddde5a 100644
--- a/tests/unit/persistence/test_dead_code_crud.py
+++ b/tests/unit/persistence/test_dead_code_crud.py
@@ -442,6 +442,8 @@ async def test_unknown_line_count_is_stored_as_null_and_summed_as_nothing(async_
summary = await dead_code_crud.get_dead_code_summary(async_session, repo.id)
assert summary["total_lines"] == 19
assert summary["deletable_lines"] == 19
+ # Both are deletion-ready; the count includes the one of unknown size.
+ assert summary["safe_to_delete_count"] == 2
async def test_unknown_line_count_is_stored_as_null(async_session):