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(dead-code): name a package dependent only when its link reaches the finding's file (#4358)
Raghav Chamadiya7e2b1f7822b4
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.mdindex 42da74c57..8cfc5e37e 100644--- a/docs/layers/DEAD_CODE.md+++ b/docs/layers/DEAD_CODE.md@@ -174,10 +174,13 @@ before returning it:repos.- Otherwise, if the finding is an unused export and another repo depends onthis one as a package, confidence is cut to 30% of its value with a note to- verify consumers.+ verify consumers. The note names a dependent only when its package link+ covers the file's package (or records no manifest) or its contract link (an+ HTTP route, a generated client) points at the file. The cut applies either way, because package links+ can miss a consumer.-The adjustment runs after tiering, so it lowers the displayed confidence-without moving a finding between tiers. `repo="all"` merges every workspace+The adjustment runs before tiering, so a lowered finding sits in the tier its+new confidence names and is never safe to delete. `repo="all"` merges every workspacerepo and tags each finding with its alias. The CLI has no cross-repo pass:`--repo <alias>` analyzes one repo in isolation (the primary repo by default).See [WORKSPACES.md](../scale/WORKSPACES.md) for how cross-repo data is built.diff --git a/packages/core/src/repowise/core/analysis/dead_code/serving.py b/packages/core/src/repowise/core/analysis/dead_code/serving.pyindex 1c49dc952..91d978667 100644--- a/packages/core/src/repowise/core/analysis/dead_code/serving.py+++ b/packages/core/src/repowise/core/analysis/dead_code/serving.py@@ -8,6 +8,7 @@ mappings, read through :func:`field`), plain dicts out; no session.from __future__ import annotationsimport json+import posixpathfrom collections.abc import Callablefrom dataclasses import dataclassfrom dataclasses import field as dataclass_field@@ -454,6 +455,10 @@ class CrossRepoLookup(Protocol):def get_repos_depending_on(self, repo_alias: str) -> list[str]: ...+ def get_package_consumers(self, repo_alias: str) -> list[dict]: ...++ def get_contract_links_as_provider(self, repo_alias: str, file_path: str) -> list[dict]: ...+def cross_repo_withdraws(lookup: CrossRepoLookup | None, alias: str | None, file_path: str, kind: Any@@ -497,10 +502,42 @@ def _adjust_one(finding: dict, lookup: CrossRepoLookup, alias: str) -> None:# Package-level dependents may consume an export without a file edge.if finding.get("kind") != "unused_export":return- depending = lookup.get_repos_depending_on(alias)- if depending:+ if lookup.get_repos_depending_on(alias):finding["confidence"] = round(finding["confidence"] * 0.3, 2)finding["safe_to_delete"] = False- finding["cross_repo_note"] = (- f"This export may be consumed by: {', '.join(depending)}. Verify before deletion."+ finding["cross_repo_note"] = _package_dependent_note(+ lookup, alias, finding.get("file_path", ""))+++def _package_dependent_note(lookup: CrossRepoLookup, alias: str, file_path: str) -> str:+ """Name only the dependents whose recorded link reaches *file_path*.++ The cut itself stays repo-wide: package links miss consumers (an+ unresolved PyPI pin, a CLI call), so they can name a consumer but never+ prove there is none.+ """+ reaching = {+ link["consumer_repo"]+ for link in lookup.get_contract_links_as_provider(alias, file_path)+ if link.get("consumer_repo") not in (None, alias)+ }+ reaching.update(+ link["source_repo"]+ for link in lookup.get_package_consumers(alias)+ if _inside_manifest(file_path, link.get("target_manifest"))+ )+ if reaching:+ return f"This export may be consumed by: {', '.join(sorted(reaching))}. Verify before deletion."+ return (+ "Confidence lowered: another workspace repo depends on this one, though no recorded "+ "package or contract link reaches this file. Verify before deletion."+ )+++def _inside_manifest(file_path: str, manifest: str | None) -> bool:+ """Whether *file_path* sits in the package *manifest* declares; unknown counts as inside."""+ if not manifest:+ return True+ root = posixpath.dirname(manifest)+ return not root or file_path.startswith(root + "/")diff --git a/tests/unit/dead_code/test_serving.py b/tests/unit/dead_code/test_serving.pyindex 281f541b4..43bd67d3c 100644--- a/tests/unit/dead_code/test_serving.py+++ b/tests/unit/dead_code/test_serving.py@@ -236,6 +236,12 @@ class _Lookup:def get_repos_depending_on(self, repo_alias: str) -> list[str]:return ["mobile"]+ def get_package_consumers(self, repo_alias: str) -> list[dict]:+ return [{"source_repo": "mobile", "target_manifest": "src/b/package.json"}]++ def get_contract_links_as_provider(self, repo_alias: str, file_path: str) -> list[dict]:+ return [{"consumer_repo": "web"}] if file_path == "src/a/two.py" else []+def test_adjust_cross_repo_lowers_consumed_findings() -> None:findings = [serialize_finding(r) for r in _ROWS]@@ -250,6 +256,33 @@ def test_adjust_cross_repo_lowers_consumed_findings() -> None:assert not by_path["src/b/five.py"]["safe_to_delete"]+def test_package_dependents_are_named_only_where_their_link_reaches() -> None:+ findings = [serialize_finding(r) for r in _ROWS]+ adjust_cross_repo(findings, _Lookup(), "api")+ by_path = {f["file_path"]: f for f in findings}+ # Inside the consumed package, and a contract provider: named.+ assert "consumed by: mobile." in by_path["src/b/five.py"]["cross_repo_note"]+ assert "consumed by: web." in by_path["src/a/two.py"]["cross_repo_note"]+ # Outside every link: nobody is named, yet the cut stays and safety is withdrawn.+ lone = [serialize_finding(_row("src/c/six.py", 0.9))]+ adjust_cross_repo(lone, _Lookup(), "api")+ assert "mobile" not in lone[0]["cross_repo_note"]+ assert lone[0]["confidence"] == 0.27+ assert not lone[0]["safe_to_delete"]+++class _UnscopedLookup(_Lookup):+ def get_package_consumers(self, repo_alias: str) -> list[dict]:+ return [{"source_repo": "mobile", "target_manifest": ""}]+++def test_a_package_link_with_no_manifest_names_its_dependent() -> None:+ # Unknown package scope is not evidence the file sits outside it.+ lone = [serialize_finding(_row("src/c/six.py", 0.9))]+ adjust_cross_repo(lone, _UnscopedLookup(), "api")+ assert "consumed by: mobile." in lone[0]["cross_repo_note"]++def test_adjusted_findings_are_tiered_by_their_lowered_confidence() -> None:findings = [serialize_finding(r) for r in _ROWS]adjust_cross_repo(findings, _Lookup(), "api")diff --git a/tests/unit/server/mcp/test_dead_code.py b/tests/unit/server/mcp/test_dead_code.pyindex 548a23a9f..25169e9be 100644--- a/tests/unit/server/mcp/test_dead_code.py+++ b/tests/unit/server/mcp/test_dead_code.py@@ -128,6 +128,12 @@ class _EveryFileConsumed:def get_repos_depending_on(self, repo_alias):return ["web"]+ def get_package_consumers(self, repo_alias):+ return []++ def get_contract_links_as_provider(self, repo_alias, file_path):+ return []+@pytest.mark.asyncioasync def test_cross_repo_cut_reaches_summary_and_rollups(setup_mcp, monkeypatch):