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 reporting C# types a project, a framework or a package consumer uses (#2967)

Raghav Chamadiya7f62f135fda8
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 b2946b924..ccfef3e39 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -53,7 +53,7 @@ from .constants import (
never_flag_path,
)
from .contract_methods import is_com_method_implementation, is_contract_method
-from .csharp_reachability import build_csharp_named_files
+from .csharp_reachability import build_csharp_named_files, build_csharp_named_types
from .dynamic_markers import (
find_dynamic_edge_files,
find_dynamic_import_files,
@@ -61,6 +61,7 @@ from .dynamic_markers import (
)
from .entry_shape import clamp_entry_shaped, drop_program_entries, is_program
from .file_reachability import (
+ CSHARP_SUFFIX,
PackageFileMap,
ReachabilityRescues,
build_package_file_map,
@@ -75,9 +76,11 @@ from .name_occurrences import (
clamp_named_types,
clamp_path_mentions,
clamp_unverified_absence,
+ demote_used_in_own_file,
drop_internals_used_in_own_file,
drop_reference_assembly_api,
)
+from .published_api import BuildFacts, demote_published_api
from .risk_factors import (
NO_GIT_SIGNAL_CONFIDENCE,
RISK_CAP_CONFIDENCE,
@@ -809,6 +812,23 @@ def _nested_class_used(node_data: dict, sym: dict) -> bool:
return f"{parent}.{name}" in (node_data.get("local_refs") or ())
+def _csharp_exports(findings: list[DeadCodeFindingData]) -> list[DeadCodeFindingData]:
+ """The unused-export findings in ``.cs`` files."""
+ return [
+ f
+ for f in findings
+ if f.kind is DeadCodeKind.UNUSED_EXPORT and f.file_path.endswith(CSHARP_SUFFIX)
+ ]
+
+
+def _names_by_file(findings: list[DeadCodeFindingData]) -> dict[str, set[str]]:
+ """File -> the symbol names *findings* report there."""
+ out: dict[str, set[str]] = {}
+ for f in findings:
+ out.setdefault(f.file_path, set()).add(f.symbol_name or "")
+ return out
+
+
def _symbol_span(data: dict) -> dict[str, int | None]:
"""``lines``/``start_line``/``end_line`` for a symbol finding.
@@ -971,8 +991,10 @@ class DeadCodeAnalyzer:
if on_step:
on_step("zombie_packages")
- # First: a C/C++ name written outside its declaration is a use, which
- # settles the finding before any clamp re-scores it.
+ # First: a C# type another file in its scope names is used, and a
+ # C/C++ name written outside its declaration is a use. Both settle the
+ # finding before any clamp re-scores it.
+ findings = self._drop_csharp_named_exports(findings)
findings = drop_preprocessed_named_elsewhere(
findings,
self._source_map,
@@ -1004,6 +1026,12 @@ class DeadCodeAnalyzer:
findings, self._source_map, self._public_top_level_names(findings)
)
+ findings = demote_published_api(
+ findings,
+ self._published_api_languages(findings, type_names),
+ BuildFacts(repo_root=self._repo_root, dotnet_index=self._dotnet_index),
+ )
+
min_conf = cfg.get("min_confidence", RISK_CAP_CONFIDENCE)
hidden_below_threshold = sum(1 for f in findings if f.confidence < min_conf)
findings = [f for f in findings if f.confidence >= min_conf]
@@ -1012,6 +1040,51 @@ class DeadCodeAnalyzer:
findings, hidden_below_threshold=hidden_below_threshold
)
+ def _drop_csharp_named_exports(
+ self, findings: list[DeadCodeFindingData]
+ ) -> list[DeadCodeFindingData]:
+ """Drop C# unused exports whose type a file that can see it names.
+
+ The symbol-level counterpart of the file rescue in
+ :func:`build_csharp_named_files`: a C# type is used from its own
+ namespace with no import, so "no importer" says nothing about it. A
+ project-scoped name is the same evidence the file pass drops on. One
+ its own file uses is capped below the floor instead (see
+ :func:`demote_used_in_own_file`). Returns a new list.
+ """
+ exports = _csharp_exports(findings)
+ if not exports:
+ return findings
+ named = build_csharp_named_types(
+ self.graph,
+ self._source_map,
+ _names_by_file(exports),
+ dotnet_index=self._dotnet_index,
+ repo_root=self._repo_root,
+ )
+ dropped = {id(f) for f in exports if (f.file_path, f.symbol_name) in named}
+ demote_used_in_own_file([f for f in exports if id(f) not in dropped], self._source_map)
+ return [f for f in findings if id(f) not in dropped]
+
+ def _published_api_languages(
+ self, findings: list[DeadCodeFindingData], type_names: dict[str, frozenset[str]]
+ ) -> dict[str, str]:
+ """Language of each file whose finding is about public API.
+
+ Every unused export is; an unreachable file only when it declares a
+ public type (*type_names*).
+ """
+ files = {
+ f.file_path
+ for f in findings
+ if f.kind is DeadCodeKind.UNUSED_EXPORT or type_names.get(f.file_path)
+ }
+ return {
+ path: self.graph.nodes[path].get("language", "")
+ for path in files
+ if self.graph.has_node(path)
+ }
+
# ------------------------------------------------------------------
# Detection methods
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py
index d6743a4aa..6e6ef82ff 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py
@@ -39,6 +39,7 @@ import os
import posixpath
import re
from collections.abc import Iterable, Mapping
+from collections.abc import Set as AbstractSet
from pathlib import Path, PurePosixPath
from typing import Any
@@ -337,46 +338,106 @@ def build_csharp_named_files(
# answer ``ReachabilityRescues`` gives a caller with no source at all.
return frozenset(candidates)
names = _NameIndex(_ProjectScopes(dotnet_index))
+ assembly_level: set[str] = set()
for path in candidates:
blob = source_map.get(path)
if blob is None and repo_root is not None:
blob = _read(repo_root, path)
- names.add_candidate(graph, path, blob)
- if names.waiting:
- names.declarers = _declaring_files(graph, names.types.keys())
- for path, blob in _corpus(source_map, dotnet_index, repo_root):
- names.scan(path, blob)
+ types, extensions = _declared_names(graph, path, blob)
+ if _is_assembly_level(blob, bool(types)):
+ assembly_level.add(path)
+ continue
+ names.add(path, {name: path for name in types}, {name: path for name in extensions})
+ names.scan_corpus(graph, source_map, dotnet_index, repo_root)
+ return frozenset(assembly_level | names.named)
+
+
+def build_csharp_named_types(
+ graph: Any,
+ source_map: Mapping[str, bytes],
+ wanted: Mapping[str, AbstractSet[str]],
+ *,
+ dotnet_index: Any | None = None,
+ repo_root: Path | None = None,
+) -> frozenset[tuple[str, str]]:
+ """The ``(path, name)`` pairs of *wanted* that another file in scope names.
+
+ The symbol-level form of :func:`build_csharp_named_files`, with the same
+ scope and the same rules, asked of one top-level type at a time: *wanted*
+ maps a ``.cs`` file to the public types the unused-export pass would
+ report there. A holder class counts as named when one of its extension
+ methods is invoked as a member. With no source at all nothing is named,
+ which leaves every finding as it was before this pass.
+ """
+ if not source_map and dotnet_index is None:
+ return frozenset()
+ names = _NameIndex(_ProjectScopes(dotnet_index))
+ for path, group in wanted.items():
+ extensions = {
+ method: (path, holder)
+ for method, holder in _extension_holders(graph, path)
+ if holder in group
+ }
+ types = {name.encode("ascii", "ignore"): (path, name) for name in group}
+ # ``[NotNullWhen(...)]`` names ``NotNullWhenAttribute``.
+ types.update(
+ (token[: -len(_ATTRIBUTE)], owner)
+ for token, owner in list(types.items())
+ if token.endswith(_ATTRIBUTE)
+ )
+ names.add(path, types, extensions)
+ names.scan_corpus(graph, source_map, dotnet_index, repo_root)
return frozenset(names.named)
+def _extension_holders(graph: Any, path: str) -> Iterable[tuple[bytes, str]]:
+ """``(extension method name, declaring class)`` for each one *path* declares."""
+ for data in _defined_symbols(graph, path):
+ if _is_extension_method(data) and data.get("parent_name"):
+ yield (data.get("name") or "").encode("ascii", "ignore"), data["parent_name"]
+
+
class _NameIndex:
- """Candidates by the names they declare, and which of them a file names."""
+ """Names some candidate declares, and which owners another file names.
+
+ An owner is what a match reports back: the file for the file-level pass,
+ ``(file, type)`` for the symbol-level one. Scope is always the file's.
+ """
def __init__(self, scopes: _ProjectScopes) -> None:
self.scopes = scopes
- self.named: set[str] = set()
- self.types: dict[bytes, list[str]] = {}
- self.extensions: dict[bytes, list[str]] = {}
+ self.named: set[Any] = set()
+ self.types: dict[bytes, list[tuple[str, Any]]] = {}
+ self.extensions: dict[bytes, list[tuple[str, Any]]] = {}
self.declarers: dict[bytes, set[str]] = {}
self._scope: dict[str, tuple[frozenset[str], frozenset[str] | None]] = {}
- @property
- def waiting(self) -> bool:
- return bool(self.types or self.extensions)
+ def add(self, path: str, types: Mapping[bytes, Any], extensions: Mapping[bytes, Any]) -> None:
+ """Register *path*'s names, each mapped to the owner a match marks."""
+ for name, owner in types.items():
+ if name:
+ self.types.setdefault(name, []).append((path, owner))
+ for name, owner in extensions.items():
+ if name:
+ self.extensions.setdefault(name, []).append((path, owner))
+ self._scope[path] = (_partner_paths(path) | {path}, self.scopes.seen_from(path))
- def add_candidate(self, graph: Any, path: str, blob: bytes | None) -> None:
- types, extensions = _declared_names(graph, path, blob)
- if _is_assembly_level(blob, bool(types)):
- self.named.add(path)
+ def scan_corpus(
+ self,
+ graph: Any,
+ source_map: Mapping[str, bytes],
+ dotnet_index: Any | None,
+ repo_root: Path | None,
+ ) -> None:
+ """Mark every owner some file of the scanned corpus names."""
+ if not (self.types or self.extensions):
return
- for name in types:
- self.types.setdefault(name, []).append(path)
- for name in extensions:
- self.extensions.setdefault(name, []).append(path)
- self._scope[path] = (_partner_paths(path) | {path}, self.scopes.seen_from(path))
+ self.declarers = _declaring_files(graph, self.types.keys())
+ for path, blob in _corpus(source_map, dotnet_index, repo_root):
+ self.scan(path, blob)
def scan(self, path: str, blob: bytes) -> None:
- """Mark the candidates *path* names.
+ """Mark the owners *path* names.
Matched on the raw bytes first and only re-matched with comments
blanked when that would name something: blanking is the expensive
@@ -388,8 +449,8 @@ class _NameIndex:
found = self._claimable(path, project, _code_only(blob))
self.named.update(found)
- def _claimable(self, path: str, project: str | None, blob: bytes) -> set[str]:
- found: set[str] = set()
+ def _claimable(self, path: str, project: str | None, blob: bytes) -> set[Any]:
+ found: set[Any] = set()
for token in set(_IDENT.findall(blob)) & self.types.keys():
# A file declaring the name is declaring it, not using it.
if path not in self.declarers.get(token, ()):
@@ -399,11 +460,13 @@ class _NameIndex:
found.update(self._visible(self.extensions[token], path, project))
return found
- def _visible(self, owners: list[str], user: str, project: str | None) -> Iterable[str]:
- for owner in owners:
+ def _visible(
+ self, owners: list[tuple[str, Any]], user: str, project: str | None
+ ) -> Iterable[Any]:
+ for path, owner in owners:
if owner in self.named:
continue
- not_users, projects = self._scope[owner]
+ not_users, projects = self._scope[path]
if user not in not_users and (projects is None or project in projects):
yield owner
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 8ba31e475..263da6f25 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
@@ -182,6 +182,34 @@ def _uses_in_own_file(
return out
+def demote_used_in_own_file(
+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]
+) -> None:
+ """Cap *findings* whose name their own file writes outside their span.
+
+ For an unused export no other file names: a use beside it (a request type
+ its endpoint takes, a helper the class below calls) means it is used and
+ at most exported wider than it needs to be. Kept below the review floor
+ with the line that uses it, rather than dropped, since a same-file use by
+ a symbol that is itself dead keeps it alive. Mutates in place.
+ """
+ by_file: dict[str, list[DeadCodeFindingData]] = {}
+ for finding in findings:
+ if finding.symbol_name and finding.file_path in source_map:
+ by_file.setdefault(finding.file_path, []).append(finding)
+ for path, pending in by_file.items():
+ verdicts = _uses_in_own_file(source_map, path, pending)
+ for finding in pending:
+ verdict = verdicts[id(finding)]
+ if verdict.answer is not _Answer.USED:
+ continue
+ finding.confidence = min(finding.confidence, UNVERIFIED_INTERNAL_CONFIDENCE)
+ finding.safe_to_delete = False
+ finding.evidence.append(
+ f"Used in its own file at {verdict.used_at}; at most it need not be public"
+ )
+
+
def searchable_token(name: str) -> bytes:
"""The searchable form of *name*, or empty when the scan cannot find it.
diff --git a/packages/core/src/repowise/core/analysis/dead_code/published_api.py b/packages/core/src/repowise/core/analysis/dead_code/published_api.py
new file mode 100644
index 000000000..18e123310
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/published_api.py
@@ -0,0 +1,133 @@
+"""Public API a repository ships as a package.
+
+A public symbol of a library that is packaged for others is used by code
+outside the repository, so no importer inside it says nothing about whether it
+is dead. Such a finding is not removed: it is kept below the default review
+floor with a line naming the package, so a reader asking for every candidate
+still sees it, labelled as published surface rather than as a cleanup item.
+
+Only a build that declares the package counts, never a guess from layout. The
+evidence is read per language from :data:`_PUBLISHED_ROOTS`, each entry
+returning ``{project dir: package name, or None when that project publishes
+nothing}``. A file belongs to its innermost project, and only that project's
+own build decides: a sample or test project nested in a packaged library's
+folder is not part of the package. Today that is .NET: a project that opts into packing (``IsPackable``,
+``PackageId``, ``GeneratePackageOnBuild``), or one that keeps a public-API
+baseline (``PublicAPI.Shipped.txt``, the analyzer file a library commits so
+every change to its shipped surface is reviewed).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from .models import DeadCodeFindingData, DeadCodeKind
+
+#: Where a published symbol lands: under ``RISK_CAP_CONFIDENCE``, so the
+#: default report and the stored index leave it out.
+PUBLISHED_API_CONFIDENCE = 0.3
+
+#: The public-API analyzer's baseline file, beside the project or in a folder
+#: of its own (``.PublicAPI/``).
+_API_BASELINE = "PublicAPI.Shipped.txt"
+
+
+@dataclass(frozen=True)
+class BuildFacts:
+ """What the per-language readers may consult; a new language adds a field."""
+
+ repo_root: Path | None
+ dotnet_index: Any | None
+
+
+def _relative(path: Path, root: Path) -> str | None:
+ try:
+ rel = path.resolve().relative_to(root.resolve()).as_posix()
+ except (OSError, ValueError):
+ return None
+ return "" if rel == "." else rel
+
+
+def _keeps_api_baseline(project_dir: Path) -> bool:
+ try:
+ folders = [project_dir, *(p for p in project_dir.iterdir() if p.is_dir())]
+ return any((folder / _API_BASELINE).is_file() for folder in folders)
+ except OSError:
+ return False
+
+
+def _dotnet_published(facts: BuildFacts) -> dict[str, str | None]:
+ """Every .NET project dir, mapped to the package it ships or None."""
+ index = facts.dotnet_index
+ if index is None:
+ return {}
+ root = Path(index.repo_path)
+ out: dict[str, str | None] = {}
+ for project in index.projects.values():
+ rel = _relative(project.project_dir, root)
+ if rel is None:
+ continue
+ name = project.published_id
+ if name is None and _keeps_api_baseline(project.project_dir):
+ name = project.assembly_name or project.path.stem
+ out[rel] = name
+ return out
+
+
+#: Language -> reader of the build files that declare a published package.
+#: A language without an entry has no published-surface rule yet.
+_PUBLISHED_ROOTS: dict[str, Callable[[BuildFacts], Mapping[str, str | None]]] = {
+ "csharp": _dotnet_published,
+ "vbnet": _dotnet_published,
+}
+
+
+def _package_of(path: str, roots: Mapping[str, str | None]) -> str | None:
+ """The package of the innermost project enclosing *path*, if it ships one."""
+ for parent in PurePosixPath(path).parents:
+ key = "" if str(parent) == "." else parent.as_posix()
+ if key in roots:
+ return roots[key]
+ return None
+
+
+def demote_published_api(
+ findings: list[DeadCodeFindingData],
+ languages: Mapping[str, str],
+ facts: BuildFacts,
+) -> list[DeadCodeFindingData]:
+ """Cap unused exports and unreachable files of a published package.
+
+ *languages* maps each file that may hold published API to its language;
+ the caller leaves out an unreachable file that declares no public type.
+ Mutates in place and returns the same list.
+ """
+ roots: dict[str, Mapping[str, str | None]] = {}
+ for finding in _published_candidates(findings):
+ language = languages.get(finding.file_path)
+ reader = _PUBLISHED_ROOTS.get(language or "")
+ if reader is None:
+ continue
+ if language not in roots:
+ roots[language] = reader(facts)
+ package = _package_of(finding.file_path, roots[language])
+ if package is None:
+ continue
+ finding.confidence = min(finding.confidence, PUBLISHED_API_CONFIDENCE)
+ finding.safe_to_delete = False
+ finding.evidence.append(
+ f"Public API of the published package '{package}': "
+ "code outside this repository can use it"
+ )
+ return findings
+
+
+def _published_candidates(findings: Iterable[DeadCodeFindingData]) -> Iterable[DeadCodeFindingData]:
+ return (
+ f
+ for f in findings
+ if f.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNREACHABLE_FILE)
+ )
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index 2d44b6af6..5e657ae33 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -23,6 +23,7 @@ from . import (
aspnet,
aws_lambda,
django,
+ dotnet_discovery,
express,
fastapi,
flask,
@@ -60,6 +61,7 @@ _HANDLERS: list[FrameworkHandler] = [
*fastapi.HANDLERS,
*flask.HANDLERS,
*aspnet.HANDLERS, # ASP.NET edges, then the any-C# extension-method scan
+ *dotnet_discovery.HANDLERS, # types a .NET framework finds by assembly scan
*rails.HANDLERS,
*laravel.HANDLERS,
*spring.HANDLERS,
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_discovery.py b/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_discovery.py
new file mode 100644
index 000000000..74889d952
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_discovery.py
@@ -0,0 +1,300 @@
+""".NET types a framework finds by scanning an assembly.
+
+``modelBuilder.ApplyConfigurationsFromAssembly(...)`` makes EF Core
+instantiate every ``IEntityTypeConfiguration<T>`` in the assembly;
+``AddFastEndpoints()`` does the same for every ``Endpoint<,>`` and
+``Validator<T>``, ``AddMediator()`` for every handler. No source names the
+discovered class, so the import graph sees nothing and dead code called every
+one of them unused.
+
+A type is wired here only on evidence: it derives from or implements a base
+the framework discovers (read from the parser's heritage, so the name is the
+declared base and not a naming convention), and a file of the type's project,
+or of a project that references it, makes that framework's registration call
+in code (a call in a comment or a string does not count). The edge runs from
+the registering file to the type's file and names only the discovered types, so
+a dead sibling type in the same file is still reported. MVC controllers are
+wired by :mod:`.aspnet`.
+
+A type a tool discovers with no call in code (EF's
+``IDesignTimeDbContextFactory``, found by ``dotnet ef``) makes its file a
+reachability root instead, when every top-level type in the file is one.
+
+Ceiling: with no .NET project index (no ``.csproj`` in the repository) the
+call is matched anywhere in the repository.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers.dotnet.index import get_or_build_index
+from ..type_names import bare_type_name
+from .base import _add_edge_if_new, read_text
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers import ResolverContext
+ from .base import DetectionContext
+
+
+@dataclass(frozen=True)
+class _Discovery:
+ """One framework: the bases it discovers and the calls that start it.
+
+ No calls means a tool, not code, does the discovering (``dotnet ef``), so a
+ file whose every top-level type derives from one of the bases is a root
+ rather than an edge target.
+
+ Bases are matched by short name: the parser's heritage drops a namespace
+ qualifier, and a ``global using`` in another file can bring the namespace
+ in, so neither can be checked per type. The registration call, or the
+ tool's own base name, is what keeps a short name from matching at random.
+ """
+
+ bases: frozenset[str]
+ calls: tuple[str, ...]
+
+
+#: Base names are as the heritage records them: generic arity dropped.
+_DISCOVERIES: tuple[_Discovery, ...] = (
+ # EF Core design-time services, instantiated by ``dotnet ef``.
+ _Discovery(
+ frozenset({"IDesignTimeDbContextFactory", "IDesignTimeServices"}),
+ (),
+ ),
+ # EF Core model configuration.
+ _Discovery(frozenset({"IEntityTypeConfiguration"}), ("ApplyConfigurationsFromAssembly",)),
+ # FastEndpoints: endpoints, validators, mappers, summaries, groups, processors.
+ _Discovery(
+ frozenset(
+ {
+ "Endpoint",
+ "EndpointWithoutRequest",
+ "Ep",
+ "Validator",
+ "Mapper",
+ "RequestMapper",
+ "ResponseMapper",
+ "Summary",
+ "Group",
+ "SubGroup",
+ "IGlobalPreProcessor",
+ "IGlobalPostProcessor",
+ "IPreProcessor",
+ "IPostProcessor",
+ }
+ ),
+ ("AddFastEndpoints",),
+ ),
+ # MediatR.
+ _Discovery(
+ frozenset(
+ {
+ "IRequestHandler",
+ "INotificationHandler",
+ "IStreamRequestHandler",
+ "IPipelineBehavior",
+ "IRequestPreProcessor",
+ "IRequestPostProcessor",
+ "IRequestExceptionHandler",
+ "IRequestExceptionAction",
+ }
+ ),
+ ("AddMediatR", "RegisterServicesFromAssembly", "RegisterServicesFromAssemblies",
+ "RegisterServicesFromAssemblyContaining"),
+ ),
+ # Mediator (source generated).
+ _Discovery(
+ frozenset(
+ {
+ "IRequestHandler",
+ "ICommandHandler",
+ "IQueryHandler",
+ "INotificationHandler",
+ "IStreamRequestHandler",
+ "IStreamCommandHandler",
+ "IStreamQueryHandler",
+ "IPipelineBehavior",
+ "IStreamPipelineBehavior",
+ }
+ ),
+ ("AddMediator",),
+ ),
+ # FluentValidation assembly registration.
+ _Discovery(
+ frozenset({"AbstractValidator"}),
+ ("AddValidatorsFromAssembly", "AddValidatorsFromAssemblies",
+ "AddValidatorsFromAssemblyContaining", "AddFluentValidation"),
+ ),
+ # MinimalApi.Endpoint.
+ _Discovery(frozenset({"IEndpoint"}), ("AddEndpoints",)),
+ # AutoMapper profiles.
+ _Discovery(frozenset({"Profile"}), ("AddAutoMapper",)),
+)
+
+_CALL_RE = re.compile(
+ r"\b(" + "|".join(sorted({c for d in _DISCOVERIES for c in d.calls})) + r")\s*[<(]"
+)
+
+#: A comment or a string literal, blanked so a call written in one is not read
+#: as the registration. Read from the text rather than the parsed call sites,
+#: which miss a call on a member chain in top-level statements
+#: (``builder.Services.AddMediator();`` in ``Program.cs``).
+_COMMENT_OR_STRING = re.compile(
+ # A C# 11 raw string (three or more quotes) first, so its quotes are not
+ # read as an empty string followed by code.
+ r'("{3,}).*?\1'
+ r"""|//[^\n]*|/\*.*?\*/|@"(?:[^"]|"")*"|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'""",
+ re.DOTALL,
+)
+
+
+def _calls_made(parsed: Any) -> set[str]:
+ """Registration calls written in *parsed*'s code, comments and strings excluded."""
+ text = read_text(parsed, encoding="utf-8-sig")
+ if not text:
+ return set()
+ return set(_CALL_RE.findall(_COMMENT_OR_STRING.sub(" ", text)))
+
+
+class _Projects:
+ """Which project holds a file, and which projects can see a project."""
+
+ def __init__(self, index: Any | None, repo_path: Path | None) -> None:
+ self._index = index
+ self._root = repo_path
+ self._seen_by: dict[Any, frozenset[Any]] = {}
+
+ def of(self, path: str) -> Any | None:
+ if self._index is None or self._root is None:
+ return None
+ project = self._index.project_for_file(self._root / path)
+ return None if project is None else project.path
+
+ def can_register(self, registrar: Any | None, owner: Any | None) -> bool:
+ """Whether a call in *registrar*'s project scans *owner*'s project.
+
+ Its own project or one it references, directly or transitively. With no
+ project for either side there is no scope to check.
+ """
+ if registrar is None or owner is None:
+ return True
+ return owner in self._closure(registrar)
+
+ def _closure(self, project: Any) -> frozenset[Any]:
+ cached = self._seen_by.get(project)
+ if cached is None:
+ cached = self._seen_by[project] = _reachable(project, self._index.referenced_projects)
+ return cached
+
+
+def _reachable(start: Any, step: Any) -> frozenset[Any]:
+ """*start* and everything *step* leads to from it, transitively."""
+ seen, stack = {start}, [start]
+ while stack:
+ fresh = set(step(stack.pop())) - seen
+ seen |= fresh
+ stack.extend(fresh)
+ return frozenset(seen)
+
+
+def _registrars(
+ cs_files: list[tuple[str, Any]], projects: _Projects
+) -> dict[str, list[tuple[str, Any]]]:
+ """Discovered base -> ``(file, project)`` of every file registering its framework."""
+ by_call: dict[str, list[tuple[str, Any]]] = {}
+ for path, parsed in sorted(cs_files, key=lambda item: item[0]):
+ for call in _calls_made(parsed):
+ by_call.setdefault(call, []).append((path, projects.of(path)))
+ out: dict[str, list[tuple[str, Any]]] = {}
+ for discovery in _DISCOVERIES:
+ sites = [site for call in discovery.calls for site in by_call.get(call, ())]
+ for base in discovery.bases if sites else ():
+ out.setdefault(base, []).extend(sites)
+ return out
+
+
+def _wired_types(
+ cs_files: list[tuple[str, Any]],
+ projects: _Projects,
+ registrars: dict[str, list[tuple[str, Any]]],
+) -> dict[tuple[str, str], list[str]]:
+ """``(registering file, type file)`` -> the discovered types the edge names."""
+ wired: dict[tuple[str, str], list[str]] = {}
+ for path, parsed in cs_files:
+ owner = projects.of(path)
+ for relation in getattr(parsed, "heritage", ()):
+ sites = registrars.get(bare_type_name(relation.parent_name), ())
+ source = next((f for f, p in sites if projects.can_register(p, owner)), path)
+ names = wired.setdefault((source, path), [])
+ if relation.child_name not in names:
+ names.append(relation.child_name)
+ return wired
+
+
+def _add_discovery_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]
+) -> int:
+ cs_files = [
+ (path, parsed)
+ for path, parsed in parsed_files.items()
+ if parsed.file_info.language == "csharp" and path in path_set
+ ]
+ _mark_tool_roots(graph, cs_files)
+ projects = _Projects(get_or_build_index(ctx), ctx.repo_path)
+ registrars = _registrars(cs_files, projects)
+ if not registrars:
+ return 0
+ wired = _wired_types(cs_files, projects, registrars)
+ # A type with no registrar in scope maps to its own file, which adds nothing.
+ return sum(_add_edge_if_new(graph, src, dst, names) for (src, dst), names in wired.items())
+
+
+_TYPE_KINDS = frozenset({"class", "struct", "record"})
+
+
+_TOOL_BASES = frozenset(b for d in _DISCOVERIES if not d.calls for b in d.bases)
+
+
+def _is_tool_root(parsed: Any) -> bool:
+ """Whether every top-level type of *parsed* is one a tool discovers."""
+ modules = {s.name for s in parsed.symbols if s.kind == "module"}
+ types = {
+ s.name
+ for s in parsed.symbols
+ if s.kind in _TYPE_KINDS and (not s.parent_name or s.parent_name in modules)
+ }
+ found = {
+ r.child_name
+ for r in getattr(parsed, "heritage", ())
+ if bare_type_name(r.parent_name) in _TOOL_BASES
+ }
+ return bool(types) and types <= found
+
+
+def _mark_tool_roots(graph: nx.DiGraph, cs_files: list[tuple[str, Any]]) -> None:
+ for path, parsed in cs_files:
+ if path in graph and _is_tool_root(parsed):
+ graph.nodes[path]["is_reachability_root"] = True
+
+
+class _AssemblyScanHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ return any(p.file_info.language == "csharp" for p in dctx.parsed_files.values())
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_discovery_edges(graph, parsed_files, ctx, path_set)
+
+
+HANDLERS = [_AssemblyScanHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index aa40b0aa7..b702da9f5 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -200,6 +200,10 @@ class EdgesMixin:
source_map=self._source_map,
)
+ # The .NET project index ``build()`` already made; handlers that scope
+ # by project read it instead of walking the tree for every .csproj again.
+ if getattr(self, "dotnet_index", None) is not None:
+ ctx._dotnet_index = self.dotnet_index
count = add_framework_edges(self._graph, self._parsed_files, ctx, tech_stack)
if count:
log.info("Framework edges added", count=count)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
index d738d0c8d..5b06e8bbd 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
@@ -74,6 +74,20 @@ class MSBuildProject:
"""Display name — the .csproj filename without extension."""
return self.path.stem
+ @property
+ def published_id(self) -> str | None:
+ """The id this project publishes a package under, or None when it does not.
+
+ Packability is opt-in, never assumed: an SDK-style project is packable
+ by default, so treating silence as yes would make every internal
+ project in a solution a published library.
+ """
+ if self.is_packable is False:
+ return None
+ if not (self.is_packable or self.generate_package_on_build or self.package_id is not None):
+ return None
+ return self.package_id or self.assembly_name or self.path.stem
+
# Strip XML namespace prefix from a tag — MSBuild docs say the namespace
# is optional in SDK-style projects but legacy projects use
diff --git a/packages/core/src/repowise/core/workspace/code_api.py b/packages/core/src/repowise/core/workspace/code_api.py
index 024f7430b..5c990db20 100644
--- a/packages/core/src/repowise/core/workspace/code_api.py
+++ b/packages/core/src/repowise/core/workspace/code_api.py
@@ -256,24 +256,6 @@ def _cargo(text: str, root: str) -> tuple[str, frozenset[str]] | None:
return name, frozenset({f"{root}/{entry}" if root else entry})
-def _nuget(project: Any, repo_path: Path, root: str) -> str | None:
- """The id a packable project publishes under, or None when it is not packable.
-
- Packability is opt-in, never assumed: an SDK-style project is packable by
- default, so treating silence as yes would make every internal project in a
- solution a published library.
- """
- if project.is_packable is False:
- return None
- if not (
- project.is_packable
- or project.generate_package_on_build
- or project.package_id is not None
- ):
- return None
- return project.package_id or project.assembly_name or project.path.stem
-
-
# ---------------------------------------------------------------------------
# Discovery
# ---------------------------------------------------------------------------
@@ -342,7 +324,7 @@ def find_published_packages(
if project is None or rel_manifest is None:
continue
root = rel_manifest.rsplit("/", 1)[0] if "/" in rel_manifest else ""
- package_id = _nuget(project, repo_path, root)
+ package_id = project.published_id
if package_id is None:
counts["code_unpublished_manifest"] = counts.get("code_unpublished_manifest", 0) + 1
continue
diff --git a/tests/unit/dead_code/test_csharp_reachability.py b/tests/unit/dead_code/test_csharp_reachability.py
index db318946b..ab10790c5 100644
--- a/tests/unit/dead_code/test_csharp_reachability.py
+++ b/tests/unit/dead_code/test_csharp_reachability.py
@@ -13,7 +13,10 @@ from pathlib import Path
import networkx as nx
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
-from repowise.core.analysis.dead_code.csharp_reachability import build_csharp_named_files
+from repowise.core.analysis.dead_code.csharp_reachability import (
+ build_csharp_named_files,
+ build_csharp_named_types,
+)
from repowise.core.analysis.dead_code.file_reachability import (
ReachabilityRescues,
is_file_reachable,
@@ -301,3 +304,97 @@ def test_a_wrapped_extension_signature_is_still_an_extension(tmp_path: Path) ->
"App/Main.cs", "class Main { void F(Builder b) => b.AddFallback(); }\n", types=("Main",)
)
assert "App/FallbackExtensions.cs" in repo.named()
+
+
+# ---- the same question per type, for unused exports ----------------------
+
+
+def _named_types(repo: _Repo, wanted: dict[str, set[str]]) -> frozenset[tuple[str, str]]:
+ return build_csharp_named_types(
+ repo.graph,
+ repo.source_map,
+ wanted,
+ dotnet_index=build_index(repo.root),
+ repo_root=repo.root,
+ )
+
+
+def test_only_the_named_type_of_a_file_is_named(tmp_path: Path) -> None:
+ """Per type, not per file: naming ``Used`` says nothing about ``Unused``."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Pair.cs", "class Used {}\nclass Unused {}\n", types=("Used", "Unused"))
+ repo.file("App/Main.cs", "class Main { object u = new Used(); }\n", types=("Main",))
+ assert _named_types(repo, {"App/Pair.cs": {"Used", "Unused"}}) == {("App/Pair.cs", "Used")}
+
+
+def test_a_type_is_not_named_from_a_project_that_cannot_see_it(tmp_path: Path) -> None:
+ repo = _two_projects(tmp_path, referenced=False)
+ repo.file("App/Main.cs", "class Main { object w = new Widget(); }\n", types=("Main",))
+ assert _named_types(repo, {"Lib/Widget.cs": {"Widget"}}) == frozenset()
+
+
+def test_an_extension_call_names_its_holder_type(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/SizeExtensions.cs",
+ "static class SizeExtensions { public static int Fit(this int v) => v; }\n",
+ types=("SizeExtensions",),
+ )
+ repo.graph.add_node(
+ "App/SizeExtensions.cs::SizeExtensions::Fit",
+ node_type="symbol",
+ name="Fit",
+ kind="method",
+ parent_name="SizeExtensions",
+ signature="Fit(this int v) -> int",
+ )
+ repo.graph.add_edge(
+ "App/SizeExtensions.cs", "App/SizeExtensions.cs::SizeExtensions::Fit", edge_type="defines"
+ )
+ repo.file("App/Main.cs", "class Main { int F(int s) => s.Fit(); }\n", types=("Main",))
+ wanted = {"App/SizeExtensions.cs": {"SizeExtensions"}}
+ assert _named_types(repo, wanted) == {("App/SizeExtensions.cs", "SizeExtensions")}
+
+
+def test_analyzer_drops_only_the_unnamed_export(tmp_path: Path) -> None:
+ """End to end: a type named by its project is no unused export; the other still is."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Types.cs", "public class Used {}\npublic class Unused {}\n")
+ for name in ("Used", "Unused"):
+ repo._symbol("App/Types.cs", name, kind="class", visibility="public")
+ repo.file("App/Program.cs", "class Program { object u = new Used(); }\n", types=("Program",))
+ report = DeadCodeAnalyzer(
+ repo.graph,
+ source_map=repo.source_map,
+ repo_root=tmp_path,
+ dotnet_index=build_index(tmp_path),
+ ).analyze({"min_confidence": 0.0})
+ exports = {f.symbol_name for f in report.findings if f.kind.value == "unused_export"}
+ assert "Unused" in exports
+ assert "Used" not in exports
+
+
+def test_an_export_used_only_in_its_own_file_is_demoted_not_dropped(tmp_path: Path) -> None:
+ """A request type its endpoint takes is used; at most it need not be public."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/Create.cs",
+ "public class CreateRequest {}\npublic class Create { void F(CreateRequest r) {} }\n",
+ )
+ repo._symbol(
+ "App/Create.cs", "CreateRequest", kind="class", visibility="public",
+ start_line=1, end_line=1,
+ )
+ report = DeadCodeAnalyzer(
+ repo.graph,
+ source_map=repo.source_map,
+ repo_root=tmp_path,
+ dotnet_index=build_index(tmp_path),
+ ).analyze({"min_confidence": 0.0})
+ (finding,) = [f for f in report.findings if f.symbol_name == "CreateRequest"]
+ assert finding.confidence < 0.4
+ assert "Used in its own file at App/Create.cs:2" in finding.evidence[-1]
diff --git a/tests/unit/dead_code/test_published_api.py b/tests/unit/dead_code/test_published_api.py
new file mode 100644
index 000000000..dd0ecafa1
--- /dev/null
+++ b/tests/unit/dead_code/test_published_api.py
@@ -0,0 +1,93 @@
+"""Public API of a published package is demoted, not reported as dead."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind
+from repowise.core.analysis.dead_code.published_api import (
+ PUBLISHED_API_CONFIDENCE,
+ BuildFacts,
+ demote_published_api,
+)
+from repowise.core.ingestion.resolvers.dotnet.index import build_index
+
+
+def _project(root: Path, rel: str, properties: str = "") -> None:
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ f'<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>{properties}</PropertyGroup></Project>'
+ )
+
+
+def _export(path: str, name: str) -> DeadCodeFindingData:
+ return DeadCodeFindingData(
+ kind=DeadCodeKind.UNUSED_EXPORT,
+ file_path=path,
+ symbol_name=name,
+ symbol_kind="class",
+ confidence=0.6,
+ reason=f"Public symbol '{name}' has no importers",
+ safe_to_delete=False,
+ evidence=[],
+ lines=None,
+ last_commit_at=None,
+ commit_count_90d=0,
+ primary_owner=None,
+ age_days=None,
+ )
+
+
+def _demote(root: Path, *findings: DeadCodeFindingData) -> list[DeadCodeFindingData]:
+ languages = {f.file_path: "csharp" for f in findings}
+ return demote_published_api(list(findings), languages, _facts(root))
+
+
+def _facts(root: Path) -> BuildFacts:
+ return BuildFacts(repo_root=root, dotnet_index=build_index(root))
+
+
+def test_a_packable_project_publishes_its_public_types(tmp_path: Path) -> None:
+ _project(tmp_path, "src/Lib/Lib.csproj", "<PackageId>Acme.Lib</PackageId>")
+ (finding,) = _demote(tmp_path, _export("src/Lib/Retry.cs", "RetrySyntax"))
+ assert finding.confidence == PUBLISHED_API_CONFIDENCE
+ assert "published package 'Acme.Lib'" in finding.evidence[-1]
+
+
+def test_an_api_baseline_marks_a_shipped_library(tmp_path: Path) -> None:
+ """``PublicAPI.Shipped.txt`` in a folder of its own, as Polly keeps it."""
+ _project(tmp_path, "src/Polly/Polly.csproj")
+ (tmp_path / "src/Polly/.PublicAPI").mkdir()
+ (tmp_path / "src/Polly/.PublicAPI/PublicAPI.Shipped.txt").write_text("Polly.Policy\n")
+ (finding,) = _demote(tmp_path, _export("src/Polly/Caching/AbsoluteTtl.cs", "AbsoluteTtl"))
+ assert finding.confidence == PUBLISHED_API_CONFIDENCE
+
+
+def test_an_app_project_is_left_alone(tmp_path: Path) -> None:
+ """An SDK project is packable by default; silence is not a publish opt-in."""
+ _project(tmp_path, "src/Web/Web.csproj")
+ _project(tmp_path, "src/Tool/Tool.csproj", "<IsPackable>false</IsPackable>")
+ web = _export("src/Web/ViewModels/LoginViewModel.cs", "LoginViewModel")
+ tool = _export("src/Tool/Thing.cs", "Thing")
+ _demote(tmp_path, web, tool)
+ assert web.confidence == 0.6 and tool.confidence == 0.6
+ assert web.evidence == [] and tool.evidence == []
+
+
+def test_a_language_without_a_rule_is_left_alone(tmp_path: Path) -> None:
+ _project(tmp_path, "src/Lib/Lib.csproj", "<PackageId>Acme.Lib</PackageId>")
+ finding = _export("src/Lib/tool.py", "helper")
+ demote_published_api([finding], {finding.file_path: "python"}, _facts(tmp_path))
+ assert finding.confidence == 0.6
+
+
+def test_a_project_nested_in_a_packaged_one_is_judged_on_its_own(tmp_path: Path) -> None:
+ """A samples project inside the library folder ships nothing."""
+ _project(tmp_path, "Lib/Lib.csproj", "<PackageId>My.Lib</PackageId>")
+ _project(tmp_path, "Lib/Samples/Sample.csproj")
+ sample = _export("Lib/Samples/Demo.cs", "Demo")
+ library = _export("Lib/Api.cs", "Api")
+ _demote(tmp_path, sample, library)
+ assert sample.confidence == 0.6 and sample.evidence == []
+ assert library.confidence == PUBLISHED_API_CONFIDENCE
diff --git a/tests/unit/ingestion/test_csharp_framework_edges.py b/tests/unit/ingestion/test_csharp_framework_edges.py
index 212396afa..9edcfcee1 100644
--- a/tests/unit/ingestion/test_csharp_framework_edges.py
+++ b/tests/unit/ingestion/test_csharp_framework_edges.py
@@ -241,6 +241,168 @@ public static class CatalogExtensions {
# ---------------------------------------------------------------------------
+class TestAssemblyScanDiscovery:
+ """A framework-discovered base plus that framework's registration call."""
+
+ def _edges(self, repo: Path, files: dict[str, str]) -> nx.DiGraph:
+ for rel, text in files.items():
+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)
+ (repo / rel).write_text(text)
+ parsed = _build_parsed_files(repo)
+ graph = nx.DiGraph()
+ graph.add_nodes_from(parsed)
+ add_framework_edges(graph, parsed, _ctx(repo, parsed), tech_stack=[])
+ return graph
+
+ _CONFIG = (
+ "using Microsoft.EntityFrameworkCore;\n"
+ "public class OrderConfiguration : IEntityTypeConfiguration<Order> {\n"
+ " public void Configure(EntityTypeBuilder<Order> b) {}\n}\n"
+ )
+
+ def test_ef_configuration_is_wired_from_the_assembly_scan(self, tmp_path: Path) -> None:
+ graph = self._edges(
+ tmp_path,
+ {
+ "Data/AppDbContext.cs": (
+ "public class AppDbContext : DbContext {\n"
+ " protected override void OnModelCreating(ModelBuilder m) =>\n"
+ " m.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);\n}\n"
+ ),
+ "Data/Config/OrderConfiguration.cs": self._CONFIG,
+ },
+ )
+ edge = graph.get_edge_data("Data/AppDbContext.cs", "Data/Config/OrderConfiguration.cs")
+ assert edge is not None and edge["edge_type"] == "framework"
+
+ def test_no_registration_call_means_no_edge(self, tmp_path: Path) -> None:
+ """The base alone is not evidence: nothing here scans the assembly."""
+ graph = self._edges(
+ tmp_path,
+ {
+ "Data/AppDbContext.cs": "public class AppDbContext : DbContext {}\n",
+ "Data/Config/OrderConfiguration.cs": self._CONFIG,
+ },
+ )
+ assert graph.in_degree("Data/Config/OrderConfiguration.cs") == 0
+
+ def test_fastendpoints_endpoint_and_validator(self, tmp_path: Path) -> None:
+ graph = self._edges(
+ tmp_path,
+ {
+ "Program.cs": "builder.Services.AddFastEndpoints().SwaggerDocument();\n",
+ "Cart/AddToCart.cs": (
+ "public class AddToCartEndpoint : Endpoint<AddToCartRequest, CartDto> {}\n"
+ "public class AddToCartValidator : Validator<AddToCartRequest> {}\n"
+ ),
+ },
+ )
+ edge = graph.get_edge_data("Program.cs", "Cart/AddToCart.cs")
+ assert edge is not None
+ assert sorted(edge["imported_names"]) == ["AddToCartEndpoint", "AddToCartValidator"]
+
+ def test_the_edge_names_only_the_discovered_type(self, tmp_path: Path) -> None:
+ """A dead sibling type in a handler's file is not vouched for."""
+ graph = self._edges(
+ tmp_path,
+ {
+ "Program.cs": "builder.Services.AddMediator();\n",
+ "Orders/CreateOrder.cs": (
+ "public class CreateOrderHandler : IRequestHandler<CreateOrder, int> {}\n"
+ "public class DeadSibling {}\n"
+ ),
+ },
+ )
+ edge = graph.get_edge_data("Program.cs", "Orders/CreateOrder.cs")
+ assert edge is not None and edge["imported_names"] == ["CreateOrderHandler"]
+
+ def test_a_registration_call_in_a_comment_or_string_does_not_count(
+ self, tmp_path: Path
+ ) -> None:
+ graph = self._edges(
+ tmp_path,
+ {
+ "Program.cs": (
+ "// builder.Services.AddMediator();\n"
+ 'var hint = "call AddMediator() to enable handlers";\n'
+ 'var doc = """\n services.AddMediator();\n """;\n'
+ ),
+ "Orders/CreateOrderHandler.cs": (
+ "public class CreateOrderHandler : IRequestHandler<CreateOrder, int> {}\n"
+ ),
+ },
+ )
+ assert graph.in_degree("Orders/CreateOrderHandler.cs") == 0
+
+ def test_a_project_the_registering_one_cannot_see_is_not_scanned(
+ self, tmp_path: Path
+ ) -> None:
+ sdk = '<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>{}</ItemGroup></Project>'
+ ref = '<ProjectReference Include="../Core/Core.csproj" />'
+ graph = self._edges(
+ tmp_path,
+ {
+ "App/App.csproj": sdk.format(ref),
+ "Core/Core.csproj": sdk.format(""),
+ "Other/Other.csproj": sdk.format(""),
+ "App/Program.cs": "builder.Services.AddMediator();\n",
+ "Core/CreateOrderHandler.cs": (
+ "public class CreateOrderHandler : IRequestHandler<CreateOrder, int> {}\n"
+ ),
+ "Other/StrayHandler.cs": (
+ "public class StrayHandler : IRequestHandler<Stray, int> {}\n"
+ ),
+ },
+ )
+ assert graph.has_edge("App/Program.cs", "Core/CreateOrderHandler.cs")
+ assert graph.in_degree("Other/StrayHandler.cs") == 0
+
+ def test_a_class_named_like_a_handler_is_not_a_handler(self, tmp_path: Path) -> None:
+ """Name patterns do not count; only the declared base does."""
+ graph = self._edges(
+ tmp_path,
+ {
+ "Program.cs": "builder.Services.AddMediator();\n",
+ "Orders/CreateOrderHandler.cs": "public class CreateOrderHandler {}\n",
+ },
+ )
+ assert graph.in_degree("Orders/CreateOrderHandler.cs") == 0
+
+
+class TestToolDiscoveredRoots:
+ """A type a tool finds with no call in code: its file is a root, not an edge target."""
+
+ _FACTORY = (
+ "using Microsoft.EntityFrameworkCore.Design;\n"
+ "namespace App.Data;\n"
+ "public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext> {\n"
+ " public AppDbContext CreateDbContext(string[] args) => null;\n}\n"
+ )
+
+ def _roots(self, repo: Path, files: dict[str, str]) -> set[str]:
+ for rel, text in files.items():
+ (repo / rel).write_text(text)
+ parsed = _build_parsed_files(repo)
+ graph = nx.DiGraph()
+ graph.add_nodes_from(parsed)
+ add_framework_edges(graph, parsed, _ctx(repo, parsed), tech_stack=[])
+ return {p for p, d in graph.nodes(data=True) if d.get("is_reachability_root")}
+
+ def test_design_time_factory_is_a_root(self, tmp_path: Path) -> None:
+ assert self._roots(tmp_path, {"Factory.cs": self._FACTORY}) == {"Factory.cs"}
+
+ def test_design_time_services_is_a_root(self, tmp_path: Path) -> None:
+ text = "public class DesignServices : IDesignTimeServices {}\n"
+ assert self._roots(tmp_path, {"Design.cs": text}) == {"Design.cs"}
+
+ def test_an_ordinary_class_is_not_a_root(self, tmp_path: Path) -> None:
+ assert self._roots(tmp_path, {"Plain.cs": "public class Plain : Base {}\n"}) == set()
+
+ def test_a_dead_sibling_keeps_the_file_judged(self, tmp_path: Path) -> None:
+ text = self._FACTORY + "public class Dead {}\n"
+ assert self._roots(tmp_path, {"Factory.cs": text}) == set()
+
+
class TestDotNetDynamicHints:
def test_di_registration_emits_interface_to_impl(self, tmp_path: Path) -> None:
(tmp_path / "IUserService.cs").write_text(