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): stop git age alone putting C# files in the high tier (#2910)
Raghav Chamadiya7b2be463b1f2
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.mdindex 845af1458..bf479dc54 100644--- a/docs/layers/DEAD_CODE.md+++ b/docs/layers/DEAD_CODE.md@@ -84,6 +84,10 @@ Rust helper is never flagged here. And the `lines` count on file and package finestimate (symbol count times ten), not a real line count, so treat the"reclaimable lines" roll-up as an order of magnitude rather than a figure.+A .NET reference assembly (`ref/*.cs`) is the compile-time API of a library.+Its files are never reported, and neither is a C# file or type it lists: that+is public API, used outside the repository.+### A C or C++ name written anywhere else is a useC, C++ and Objective-C symbols are used in ways that carry no edge: a callback@@ -113,10 +117,17 @@ one added last week. Confidence starts from git activity:| No commits in 90 days, but the file is under 30 days old | `0.55` (may be work in progress) || Still being committed to | `0.40` |-Then it only ever goes down. Two caps apply:+Then it only ever goes down. These caps apply:- **Dynamic imports nearby.** If any file in the same directory uses a runtimeloader, confidence is capped at `0.40`.+- **Imported by namespace.** A C# `using` names a namespace, never a file, and+ a same-namespace `new T()` needs no `using` at all, so a C# file is capped at+ `0.40` whatever its age.+- **Its type is named elsewhere.** When another file writes the name of a type+ the file declares, confidence is capped at `0.40` and the evidence names+ that file: Java, C# and Swift use a type from its own package or module+ without an import.- **Runtime-load risk factors.** If the path looks like config, environment,bootstrap, database, script, or runtime-asset code, confidence is capped at`0.40` and the finding carries an evidence line explaining why. These arediff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex f6f408eb3..2176ea833 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -37,6 +37,7 @@ from .constants import (_DELIBERATELY_UNUSED_ANNOTATIONS,_FRAMEWORK_DECORATOR_SUFFIXES,_FRAMEWORK_DECORATORS,+ _NAMESPACE_IMPORT_LANGUAGES,_NEVER_PACKAGE_DIRS,_PREPROCESSED_LANGUAGES,_PURE_WRAPPER_DECORATOR_ATTRS,@@ -60,9 +61,11 @@ from .file_reachability import (from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReportfrom .name_occurrences import (IDENTIFIER_RE,+ clamp_named_types,clamp_path_mentions,clamp_unverified_absence,drop_internals_used_in_own_file,+ drop_reference_assembly_api,)from .risk_factors import (NO_GIT_SIGNAL_CONFIDENCE,@@ -411,6 +414,12 @@ _UNCALLABLE_TYPE_KINDS: frozenset[str] = frozenset(#: C/C++ symbol kinds a bare ``class Env;`` / ``struct Options;`` can carry.#: Paired with ``is_declaration`` this identifies a type forward declaration,#: which is never a deletable unit — see the guard in ``_detect_unused_exports``.+#: Kinds that declare a type, which Java and C# use from their own package or+#: namespace without an import.+_TYPE_DECLARATION_KINDS: frozenset[str] = frozenset(+ {"class", "interface", "struct", "enum", "record", "trait", "object"}+)+_CPP_TYPE_DECLARATION_KINDS: frozenset[str] = frozenset({"class",@@ -761,6 +770,18 @@ def _is_declaration_only(sym: dict) -> bool:_LINES_UNKNOWN = "Line count unavailable: source was not read"+#: ``(days, confidence)`` rungs for a file with no commit in 90 days, oldest+#: first. ``_is_old`` uses strict >, so days-1 gives >= semantics: a year or+#: more untouched is 1.0, very likely dead.+_GIT_AGE_RUNGS: tuple[tuple[int, float], ...] = ((364, 1.0), (179, 0.9), (89, 0.8))+++def _is_public_top_level(sym: dict, kinds: AbstractSet[str] | None) -> bool:+ if sym.get("visibility") != "public" or sym.get("parent_name"):+ return False+ return kinds is None or sym.get("kind") in kinds++def _symbol_span(data: dict) -> dict[str, int | None]:"""``lines``/``start_line``/``end_line`` for a symbol finding.@@ -929,6 +950,9 @@ class DeadCodeAnalyzer:findings = clamp_unverified_absence(findings, self._source_map)findings = drop_internals_used_in_own_file(findings, self._source_map)findings = clamp_path_mentions(findings, self._source_map)+ type_names = self._public_top_level_names(findings, kinds=_TYPE_DECLARATION_KINDS)+ findings = drop_reference_assembly_api(findings, self._source_map, type_names)+ findings = clamp_named_types(findings, self._source_map, type_names)findings = clamp_entry_shaped(findings, self._source_map, self._public_top_level_names(findings))@@ -1105,21 +1129,11 @@ class DeadCodeAnalyzer:age_days = git_meta.get("age_days")primary_owner = git_meta.get("primary_owner_name")- # _is_old uses strict >, so pass days-1 to get >= semantics.- if no_git_signal:- confidence = NO_GIT_SIGNAL_CONFIDENCE- elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=364):- confidence = 1.0 # Untouched for a year+ — very likely dead- elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=179):- confidence = 0.9- elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=89):- confidence = 0.8- elif commit_90d == 0 and age_days is not None and age_days < 30:- confidence = 0.55 # Recently created — may be WIP- elif commit_90d == 0:- confidence = 0.7- else:- confidence = 0.4+ confidence = (+ NO_GIT_SIGNAL_CONFIDENCE+ if no_git_signal+ else self._git_age_confidence(commit_90d, last_commit, age_days)+ )# The ladder above is an evidence scale, not a tier boundary: its rungs# stay literal so moving a threshold does not silently re-score how@@ -1140,6 +1154,12 @@ class DeadCodeAnalyzer:if risk_factors:confidence = min(confidence, RISK_CAP_CONFIDENCE)+ # A namespace-imported file is reached without an edge (a same-namespace+ # ``new T()``), so no edge says little and its age says nothing more.+ namespace_imported = node_data.get("language") in _NAMESPACE_IMPORT_LANGUAGES+ if namespace_imported:+ confidence = min(confidence, RISK_CAP_CONFIDENCE)+# A whole file is a review candidate, never deletion-ready: see# ``REVIEW_ONLY_KINDS``. Confidence still ranks it.safe = False@@ -1154,6 +1174,10 @@ class DeadCodeAnalyzer:risk_line = risk_evidence(risk_factors)if risk_line:evidence.append(risk_line)+ if namespace_imported:+ evidence.append(+ "Imported by namespace, not by file, so having no importer is weak evidence"+ )lines = self._file_line_count(node)if lines is None:evidence.append(_LINES_UNKNOWN)@@ -1175,6 +1199,20 @@ class DeadCodeAnalyzer:risk_factors=list(risk_factors),)+ def _git_age_confidence(+ self, commit_90d: int, last_commit: Any, age_days: int | None+ ) -> float:+ """The git-age evidence ladder for a file no edge reaches."""+ if commit_90d != 0:+ return 0.4+ if last_commit:+ for days, confidence in _GIT_AGE_RUNGS:+ if self._is_old(last_commit, days=days):+ return confidence+ if age_days is not None and age_days < 30:+ return 0.55 # Recently created — may be WIP+ return 0.7+def _member_is_used(self, sym_id: str, language: str | None) -> bool:"""True when this container declares a method something else uses.@@ -1245,14 +1283,14 @@ class DeadCodeAnalyzer:]def _public_top_level_names(- self, findings: list[DeadCodeFindingData]+ self, findings: list[DeadCodeFindingData], kinds: AbstractSet[str] | None = None) -> dict[str, frozenset[str]]:- """Top-level public symbol names of each unreachable file in *findings*."""+ """Top-level public symbol names (of *kinds*, if given) of each unreachable file."""return {f.file_path: frozenset(sym["name"]for _, sym in self._defined_symbols(f.file_path)- if sym.get("visibility") == "public" and not sym.get("parent_name")+ if _is_public_top_level(sym, kinds))for f in findingsif f.kind is DeadCodeKind.UNREACHABLE_FILE and self.graph.has_node(f.file_path)diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 80aa32aac..d0c167d54 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -122,6 +122,10 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*AssemblyInfo.vb","*/My Project/*.vb","*ApplicationEvents.vb", # My.MyApplication hooks, raised by the VB runtime+ # .NET reference assemblies: compile-time API stubs (``throw null`` bodies)+ # the build packs as the public surface. Nothing imports them, and every+ # type they list is public API.+ "*/ref/*.cs","*MauiProgram.cs", # MAUI app entry — invoked by host, not imported"*App.xaml.cs","*AppShell.xaml.cs",@@ -964,6 +968,11 @@ _PURE_WRAPPER_DECORATOR_ATTRS: frozenset[str] = frozenset(# is a deliberate act._CONTAINER_USE_LANGUAGES: frozenset[str] = frozenset({"csharp"})+# Languages whose imports name a namespace, never a file, so a file no edge+# reaches is not evidence that nothing uses it: a same-namespace ``new T()``+# needs no ``using``, and one ``using`` stands for every file of the namespace.+_NAMESPACE_IMPORT_LANGUAGES: frozenset[str] = frozenset({"csharp"})+# Languages whose symbols the preprocessor reaches without naming them: a# ``typedef struct _X {...} X`` tag used only through ``X``, a function called# through a ``#define`` alias or a ``##``-pasted name, an icall table entry.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.pyindex f533bad67..ace627edb 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@@ -46,6 +46,7 @@ where this answers it from the repository in front of us.from __future__ import annotationsimport re+from collections.abc import Mappingfrom dataclasses import dataclassfrom enum import Enum@@ -493,3 +494,105 @@ def clamp_path_mentions(finding.safe_to_delete = Falsefinding.evidence.append(f"Named by path in {where}, which may load it without an import")return findings+++def _is_reference_assembly(path: str) -> bool:+ """A .NET reference-assembly source: ``src/libraries/X/ref/X.cs``."""+ return path.endswith(".cs") and "/ref/" in f"/{path}"+++def _writers(+ source_map: dict[str, bytes], names: Mapping[int, frozenset[str]]+) -> dict[bytes, set[str]]:+ """For every searchable name in *names*, the files of *source_map* writing it."""+ tokens = {_token(name) for group in names.values() for name in group} - {b""}+ return occurrence_files(source_map, tokens)+++def drop_reference_assembly_api(+ findings: list[DeadCodeFindingData],+ source_map: dict[str, bytes],+ type_names: Mapping[str, frozenset[str]],+) -> list[DeadCodeFindingData]:+ """Drop C# findings whose type a reference assembly lists.++ A ``ref/*.cs`` file is the compile-time surface of a .NET library: every+ type it names is public API, used by code outside the repository, so+ neither the type nor the file declaring it is dead. *type_names* maps an+ unreachable file to the types it declares. Returns a new list.+ """+ references = {p: b for p, b in source_map.items() if _is_reference_assembly(p)}+ names = {+ id(f): _type_names_of(f, type_names)+ for f in findings+ if f.file_path.endswith(".cs") and not _is_reference_assembly(f.file_path)+ }+ if not references or not names:+ return findings+ listed = _writers(references, names)+ return [+ f+ for f in findings+ if not any(_token(name) in listed for name in names.get(id(f), ()))+ ]+++def clamp_named_types(+ findings: list[DeadCodeFindingData],+ source_map: dict[str, bytes],+ type_names: Mapping[str, frozenset[str]],+) -> list[DeadCodeFindingData]:+ """Cap unreachable files whose types another file names.++ The file-level counterpart of :func:`clamp_unverified_absence`. A Java or+ C# type is used from its own package or namespace without any import, so+ a file no edge reaches but whose type another file writes has not been+ shown unused. Capped to the review tier, never dropped: a name is not+ proof of use. Mutates in place and returns the same list.+ """+ candidates = [+ f+ for f in findings+ if f.kind is DeadCodeKind.UNREACHABLE_FILE+ and f.confidence > RISK_CAP_CONFIDENCE+ and type_names.get(f.file_path)+ ]+ if not candidates or not source_map:+ return findings+ names = {id(f): type_names[f.file_path] for f in candidates}+ writers = _writers(source_map, names)+ for finding in candidates:+ written = _first_writer(finding.file_path, names[id(finding)], writers)+ if written is None:+ continue+ path, name = written+ finding.confidence = min(finding.confidence, RISK_CAP_CONFIDENCE)+ finding.evidence.append(+ f"Its type '{name}' is written in {path}, which may use it without an import"+ )+ return findings+++def _first_writer(+ file_path: str, names: frozenset[str], writers: dict[bytes, set[str]]+) -> tuple[str, str] | None:+ """The first ``(path, name)`` where another file writes one of *names*."""+ return min(+ (+ (path, name)+ for name in names+ for path in writers.get(_token(name), ())+ if path != file_path and not _is_own_type_sibling(path, file_path)+ ),+ default=None,+ )+++def _type_names_of(+ finding: DeadCodeFindingData, type_names: Mapping[str, frozenset[str]]+) -> frozenset[str]:+ if finding.kind is DeadCodeKind.UNREACHABLE_FILE:+ return type_names.get(finding.file_path, frozenset())+ if finding.kind is DeadCodeKind.UNUSED_EXPORT and finding.symbol_name:+ return frozenset({finding.symbol_name})+ return frozenset()diff --git a/tests/unit/dead_code/test_csharp_file_confidence.py b/tests/unit/dead_code/test_csharp_file_confidence.pynew file mode 100644index 000000000..98f769dd0--- /dev/null+++ b/tests/unit/dead_code/test_csharp_file_confidence.py@@ -0,0 +1,100 @@+"""C# files: no importer edge is weak evidence, and reference-assembly API is never dead.++From dotnet/runtime: 274 C# files reported unreachable at 1.0 on git age alone+(a servicing branch leaves nearly every file untouched for a year), among them+``FileConfigurationExtensions.cs``, whose public ``SetBasePath`` the library's+``ref/`` assembly lists.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE+from tests.unit.dead_code._helpers import _build_graph, _old_date++_STALE = {"commit_count_90d": 0, "last_commit_at": _old_date(800), "age_days": 900}+++def _cls(name: str, language: str) -> dict:+ return {+ "name": name,+ "kind": "class",+ "visibility": "public",+ "decorators": [],+ "start_line": 3,+ "end_line": 9,+ "language": language,+ }+++def _analyze(nodes: dict, source_map: dict[str, bytes]):+ graph = _build_graph(nodes)+ analyzer = DeadCodeAnalyzer(+ graph, git_meta_map={path: dict(_STALE) for path in nodes}, source_map=source_map+ )+ return analyzer.analyze({"detect_zombie_packages": False, "min_confidence": 0.0})+++def _file_finding(report, path):+ return next(+ (f for f in report.findings if f.kind is DeadCodeKind.UNREACHABLE_FILE and f.file_path == path),+ None,+ )+++def test_csharp_file_is_capped_to_the_review_tier_whatever_its_age():+ path = "src/Linq/ExceptQueryOperator.cs"+ report = _analyze(+ {path: {"language": "csharp", "symbols": [_cls("ExceptQueryOperator", "csharp")]}},+ {path: b"namespace Linq;\n\ninternal sealed class ExceptQueryOperator\n{\n}\n"},+ )+ finding = _file_finding(report, path)+ assert finding.confidence == pytest.approx(RISK_CAP_CONFIDENCE)+ assert any("Imported by namespace" in line for line in finding.evidence)+++def test_type_listed_in_a_reference_assembly_is_never_dead():+ src = "src/libraries/Config.FileExtensions/src/FileConfigurationExtensions.cs"+ ref = "src/libraries/Config.FileExtensions/ref/Config.FileExtensions.cs"+ report = _analyze(+ {+ src: {"language": "csharp", "symbols": [_cls("FileConfigurationExtensions", "csharp")]},+ ref: {"language": "csharp", "symbols": [_cls("FileConfigurationExtensions", "csharp")]},+ },+ {+ src: b"namespace C;\n\npublic static class FileConfigurationExtensions\n{\n}\n",+ ref: b"namespace C\n{\n public static class FileConfigurationExtensions { }\n}\n",+ },+ )+ # Neither the source file, nor its type, nor the reference stub itself.+ assert report.findings == []+++def test_file_whose_type_another_file_names_is_capped():+ # A Swift type is used across its module without an import.+ path = "Sources/App/FilterType.swift"+ user = "Sources/App/FilterRef.swift"+ report = _analyze(+ {+ path: {"language": "swift", "symbols": [_cls("FilterType", "swift")]},+ user: {"language": "swift", "is_entry_point": True},+ },+ {+ path: b"import Foundation\n\npublic enum FilterType { case a }\n",+ user: b"struct FilterRef { var t: FilterType }\n",+ },+ )+ finding = _file_finding(report, path)+ assert finding.confidence == pytest.approx(RISK_CAP_CONFIDENCE)+ assert any("FilterRef.swift" in line for line in finding.evidence)+++def test_file_whose_types_nothing_names_keeps_its_age_score():+ path = "pkg/orphan.py"+ report = _analyze(+ {path: {"language": "python", "symbols": [_cls("Orphan", "python")]}},+ {path: b"\n\nclass Orphan:\n pass\n", "pkg/other.py": b"x = 1\n"},+ )+ assert _file_finding(report, path).confidence == pytest.approx(1.0)