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): stop file age lifting members of a path-loaded set (#2750)

Raghav Chamadiyaaa6466d2304f
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 715a632e3..07de93d1d 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
@@ -9,10 +9,14 @@ never imported in the first place:
a shebang) is started by a command, not by an import;
* three or more unreachable files in one directory exporting the same names
are a convention-loaded set (pages, handlers, migrations) whose loader the
- graph does not see.
-
-Each caps the finding to the review tier; none drops it. Shape is not proof of
-use, so the file stays listed as a candidate for a person to check.
+ graph does not see;
+* a file exporting everything such a set exports, plus more (a tool that
+ also exports its input type), belongs to the same set.
+
+Each caps the finding to the review tier; none drops it. The cap also stops
+"no commits in 90 days" lifting such a file to the high tier, since an
+untouched loaded file is not an unused one. Shape is not proof of use, so the
+file stays listed as a candidate for a person to check.
"""
from __future__ import annotations
@@ -107,6 +111,20 @@ def _cohorts(shapes: Mapping[str, frozenset[str]]) -> dict[str, int]:
return {p: len(ps) for ps in groups.values() if len(ps) >= MIN_COHORT_SIZE for p in ps}
+def _cohort_shapes(
+ shapes: Mapping[str, frozenset[str]], cohort_size: Mapping[str, int]
+) -> dict[str, set[frozenset[str]]]:
+ """Per directory, the export shapes of its cohorts.
+
+ A cohort, not one default-only file: a lone route stub beside an ordinary
+ component says nothing about how the component is loaded.
+ """
+ out: dict[str, set[frozenset[str]]] = defaultdict(set)
+ for path in cohort_size:
+ out[str(PurePosixPath(path).parent)].add(shapes[path])
+ return out
+
+
def clamp_entry_shaped(
findings: list[DeadCodeFindingData],
source_map: dict[str, bytes],
@@ -129,12 +147,19 @@ def clamp_entry_shaped(
for f in unreachable
}
cohort_size = _cohorts(shapes)
+ cohort_shapes = _cohort_shapes(shapes, cohort_size)
for finding in unreachable:
if finding.confidence <= RISK_CAP_CONFIDENCE:
continue
path = finding.file_path
- reason = _entry_reason(path, shapes[path], source_map.get(path), cohort_size.get(path))
+ reason = _entry_reason(
+ path,
+ shapes[path],
+ source_map.get(path),
+ cohort_size.get(path),
+ cohort_shapes.get(str(PurePosixPath(path).parent), set()),
+ )
if reason is None:
continue
finding.confidence = min(finding.confidence, RISK_CAP_CONFIDENCE)
@@ -144,7 +169,11 @@ def clamp_entry_shaped(
def _entry_reason(
- path: str, shape: frozenset[str], blob: bytes | None, cohort_size: int | None
+ path: str,
+ shape: frozenset[str],
+ blob: bytes | None,
+ cohort_size: int | None,
+ cohort_shapes: set[frozenset[str]],
) -> str | None:
"""The first entry shape *path* has, as an evidence line, or None."""
if shape == {"default"}:
@@ -157,4 +186,11 @@ def _entry_reason(
f"One of {cohort_size} unreachable files in its directory exporting "
f"the same names ({names}), the shape of a convention-loaded set"
)
+ if fits := [s for s in cohort_shapes if s < shape]:
+ # min() keeps the evidence line stable when two cohort shapes fit.
+ names = ", ".join(sorted(min(fits, key=sorted))[:3])
+ return (
+ f"Exports what a convention-loaded set in its directory exports ({names}) "
+ "and more, so it belongs to that set; its age is not evidence it is unused"
+ )
return None
diff --git a/tests/unit/dead_code/test_entry_shape.py b/tests/unit/dead_code/test_entry_shape.py
index e81e6003b..e61336479 100644
--- a/tests/unit/dead_code/test_entry_shape.py
+++ b/tests/unit/dead_code/test_entry_shape.py
@@ -210,3 +210,98 @@ def test_the_analyzer_applies_the_cap_and_keeps_the_finding():
by_path = {f.file_path: f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
assert by_path["pkg/old.py"].confidence == 1.0
assert by_path["pkg/run_once.py"].confidence == RISK_CAP_CONFIDENCE
+
+
+# --- members of a loaded set that export more --------------------------------------
+
+_TOOL = 'import { defineTool } from "kit"\n\nexport default defineTool({\n name: "x",\n})\n'
+_TYPED_TOOL = (
+ 'import { defineTool } from "kit"\n\n'
+ "export type SearchInput = { q: string }\n\n"
+ "export default defineTool<SearchInput>({\n"
+ ' name: "search",\n'
+ "})\n"
+)
+
+
+_TOOLS = {f"agent/tools/{n}.ts": _TOOL for n in ("fetch", "list", "read")}
+
+
+def test_a_default_export_with_more_beside_a_default_only_set_is_capped():
+ files = _TOOLS | {"agent/tools/search.ts": _TYPED_TOOL}
+ out = _clamp(files, {"agent/tools/search.ts": {"SearchInput"}})
+ assert all(_capped(f) for f in out.values())
+ assert "set in its directory exports (default)" in out["agent/tools/search.ts"].evidence[-1]
+
+
+def test_one_default_only_sibling_is_not_a_set():
+ files = {"components/Router.tsx": _TOOL, "components/Button.tsx": _TYPED_TOOL}
+ out = _clamp(files, {"components/Button.tsx": {"SearchInput"}})
+ assert _capped(out["components/Router.tsx"])
+ assert out["components/Button.tsx"].confidence == 1.0
+
+
+def test_the_same_file_without_a_loaded_set_stays_a_positive():
+ out = _clamp({"agent/tools/search.ts": _TYPED_TOOL}, {"agent/tools/search.ts": {"SearchInput"}})
+ assert out["agent/tools/search.ts"].confidence == 1.0
+
+
+def test_a_loaded_set_in_another_directory_does_not_count():
+ files = _TOOLS | {"lib/search.ts": _TYPED_TOOL}
+ out = _clamp(files, {"lib/search.ts": {"SearchInput"}})
+ assert out["lib/search.ts"].confidence == 1.0
+
+
+def test_a_file_missing_the_sets_export_is_not_a_member():
+ files = _TOOLS | {"agent/tools/util.ts": "export const q = 1\n"}
+ out = _clamp(files, {"agent/tools/util.ts": {"q"}})
+ assert out["agent/tools/util.ts"].confidence == 1.0
+
+
+def test_a_superset_of_a_cohort_shape_is_capped():
+ paths = ["handlers/a.py", "handlers/b.py", "handlers/c.py"]
+ files = {p: _handler(p) for p in paths}
+ files["handlers/d.py"] = _handler("d") + "\ndef helper():\n return 1\n"
+ names = {p: {"handle"} for p in paths} | {"handlers/d.py": {"handle", "helper"}}
+ out = _clamp(files, names)
+ assert _capped(out["handlers/d.py"])
+ assert "(handle)" in out["handlers/d.py"].evidence[-1]
+
+
+def test_a_script_sibling_does_not_make_a_loaded_set():
+ body = "def main():\n pass\n\nif __name__ == '__main__':\n main()\n"
+ files = {"tools/bump.py": body, "tools/lib.py": "def main():\n pass\n\ndef extra():\n pass\n"}
+ out = _clamp(files, {"tools/bump.py": {"main"}, "tools/lib.py": {"main", "extra"}})
+ assert _capped(out["tools/bump.py"])
+ assert out["tools/lib.py"].confidence == 1.0
+
+
+def test_the_analyzer_does_not_let_age_lift_a_loaded_set_member():
+ g = _build_graph(
+ nodes={
+ "src/main.ts": {"is_entry_point": True, "symbols": []},
+ **{p: {"symbols": []} for p in _TOOLS},
+ "agent/tools/search.ts": {"symbols": [{"name": "SearchInput", "visibility": "public"}]},
+ "lib/legacy.ts": {"symbols": [{"name": "helper", "visibility": "public"}]},
+ },
+ )
+ # 120 days untouched is the 0.8 rung of the age ladder.
+ stale = {"commit_count_90d": 0, "last_commit_at": _old_date(120), "age_days": 400}
+ source = {
+ "src/main.ts": b"export function main() {}\n",
+ **{p: s.encode() for p, s in _TOOLS.items()},
+ "agent/tools/search.ts": _TYPED_TOOL.encode(),
+ "lib/legacy.ts": b"export const helper = 1\n",
+ }
+ meta = {p: dict(stale) for p in source if p != "src/main.ts"}
+ report = DeadCodeAnalyzer(g, git_meta_map=meta, source_map=source).analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ }
+ )
+ by_path = {f.file_path: f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+ assert by_path["lib/legacy.ts"].confidence == 0.8
+ assert by_path["agent/tools/search.ts"].confidence == RISK_CAP_CONFIDENCE
+ assert by_path["agent/tools/search.ts"].safe_to_delete is False