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.

feat(apex): dead code with platform entry points, and @IsTest test detection (#4416)

Raghav Chamadiya78e532453afc
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 24da4297b..c094faf84 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -986,6 +986,14 @@ Salesforce CLI coverage names a class or trigger, never a file, so it maps to
the one `.cls` or `.trigger` file of that name, ignoring case. A name two files
share, or no file has, stays unmapped.
+Apex dead code starts from triggers, tests, entry annotations such as
+`@AuraEnabled` and `@InvocableMethod`, `global` members and platform interfaces
+such as `Schedulable`. A class is live when a live class or any Salesforce
+metadata, Lightning or project file writes its name in any case, strings
+included, since `Type.forName` reaches classes by name. Ceiling: a mention in a
+comment counts as a use, and a class shaped like a Visualforce controller stays
+live.
+
Each flow (`.flow-meta.xml`, or a legacy `.flow` in a `flows/` directory) is
one symbol named by its API name, linked to the Apex invocable actions,
subflows, screen components and Apex-defined types it names. Apex
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 9a7605b86..8b0177a71 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -75,10 +75,9 @@ Scala, Elixir and F# have dedicated import resolvers with known gaps; see
\* COBOL is excluded from dead-code claims: JCL, schedulers and dynamic program
calls are entry paths the repository graph cannot observe.
Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
-resolved case-insensitively within each sfdx project's namespace, and is
-excluded from dead-code claims the same way until triggers, annotations and
-platform interfaces are modelled as entry points. Apex test coverage from the
-Salesforce CLI is read as a coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)).
+resolved case-insensitively within each sfdx project's namespace; its dead-code
+findings are review-only. Apex test coverage from the Salesforce CLI is read as a
+coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)).
Salesforce flows (`.flow-meta.xml`) are one symbol each, linked to the Apex
invocable actions, subflows and screen components they name.
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 0ae4e2314..586be4ee4 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -23,6 +23,7 @@ import structlog
from ...code_origin import code_origin
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
from ...ingestion.symbol_identity import base_symbol_id, overload_sets
+from .apex_reachability import ApexLiveness, settle_apex_findings
from .c_name_uses import (
DEFINITION_HEADER_LINES,
DeclarationSites,
@@ -170,6 +171,7 @@ class DeadCodeAnalyzer:
self._dotnet_index = dotnet_index
self._csharp_named_files: frozenset[str] | None = None
self._swift_named_files: frozenset[str] | None = None
+ self._apex_liveness: ApexLiveness | None = None
# C# classes a plugin host or container finds by type, built on first use.
self._csharp_discovered: frozenset[tuple[str, str]] | None = None
self._parsed_files = parsed_files or {}
@@ -282,8 +284,21 @@ class DeadCodeAnalyzer:
package_files=self._package_files,
csharp_named_files=self._csharp_named_files,
swift_named_files=self._swift_named_files,
+ apex_live_files=self._apex().live,
)
+ def _apex(self) -> ApexLiveness:
+ """Apex liveness, built on first use (see :mod:`apex_reachability`)."""
+ if self._apex_liveness is None:
+ self._apex_liveness = ApexLiveness(
+ self.graph,
+ self._source_map,
+ self._parsed_files,
+ self._repo_root,
+ frozenset(t.casefold().encode() for t in self._unindexed_identifier_tokens()),
+ )
+ return self._apex_liveness
+
def analyze(
self,
config: dict | None = None,
@@ -342,9 +357,10 @@ class DeadCodeAnalyzer:
def _settle(self, findings: list[DeadCodeFindingData]) -> list[DeadCodeFindingData]:
"""Drop, demote and clamp the pass findings on evidence the graph does not carry."""
- # 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.
+ # First: an Apex name written in any case, a C# type another file in
+ # its scope names, and a C/C++ name written outside its declaration are
+ # uses. Each settles the finding before any clamp re-scores it.
+ findings = settle_apex_findings(findings, self._apex(), self._source_map)
findings = self._drop_csharp_named_exports(findings)
findings = drop_preprocessed_named_elsewhere(
findings,
diff --git a/packages/core/src/repowise/core/analysis/dead_code/apex_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/apex_reachability.py
new file mode 100644
index 000000000..1a8f80157
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/apex_reachability.py
@@ -0,0 +1,463 @@
+"""Name-granular reachability for Apex.
+
+Apex has no imports, and the platform enters code no Apex source names (a
+trigger on DML, an ``@AuraEnabled`` call from Lightning, a scheduled job). So a
+``.cls`` file is live when it is a root (a test, an entry annotation or
+``global`` member, a platform interface) or when a live file names one of its
+types, compared case-folded, or lands a use edge on it. Every non-Apex file
+except docs, access grants and package manifests counts as live, which is how
+Lightning, Visualforce, flows and custom metadata reach a class.
+
+A fixpoint like the Swift pass: it only rescues, and two dead classes naming
+each other stay dead. Ceiling: a name in a comment or string counts as a use
+(strings because ``Type.forName('Foo')`` reaches classes that way).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
+from repowise.core.ids import file_path_of, is_external
+from repowise.core.support_paths import DOC_EXTENSIONS
+
+from ...entry_candidacy import is_reachability_root
+from ...ingestion.decorator_names import decorator_base
+from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
+from ...ingestion.traverser import is_output_dir
+from .constants import never_flag_path
+from .contract_methods import APEX_PLATFORM_TYPES
+from .file_reachability import has_dependency_importer
+from .models import DeadCodeFindingData, DeadCodeKind
+from .name_occurrences import IDENTIFIER_RE, MIN_ANSWERABLE_NAME_LEN
+from .risk_factors import UNPROVEN_EXPORT_CONFIDENCE
+
+APEX_LANGUAGE = "apex"
+
+#: Folded annotations whose member the platform or the test runner calls.
+_ENTRY_ANNOTATIONS: frozenset[str] = frozenset(
+ {
+ "auraenabled",
+ "invocablemethod",
+ "invocablevariable",
+ "restresource",
+ "httpget",
+ "httppost",
+ "httpput",
+ "httppatch",
+ "httpdelete",
+ "future",
+ "remoteaction",
+ "readonly",
+ "namespaceaccessible",
+ "istest",
+ "testsetup",
+ }
+)
+
+#: Opens a private member to tests in other files; a member rule, never a root.
+_TEST_VISIBLE = "testvisible"
+
+#: Modifiers that make a member callable from outside the org's source.
+_ENTRY_MODIFIERS: frozenset[str] = frozenset({"global", "webservice", "testmethod"})
+
+#: Top-level kinds a name use reaches (a trigger is a ``function``, never judged).
+_TYPE_KINDS: frozenset[str] = frozenset({"class", "interface", "enum"})
+
+#: Salesforce CLI state, and metadata types that cannot name an Apex class.
+_SKIP_DIRS: frozenset[str] = PRUNED_DIRS | frozenset(
+ {
+ ".sfdx", ".sf",
+ "fields", "layouts", "listViews", "compactLayouts", "recordTypes",
+ "objectTranslations", "translations", "reports", "reportTypes", "dashboards",
+ "standardValueSets", "standardValueSetTranslations", "globalValueSets",
+ "globalValueSetTranslations", "sharingRules", "matchingRules", "duplicateRules",
+ }
+)
+
+#: Unindexed metadata, markup and project configs that can name an Apex class.
+_METADATA_SUFFIXES: tuple[str, ...] = (
+ ".xml", ".page", ".component", ".cmp", ".app", ".evt", ".intf", ".design",
+ ".flow", ".object", ".email", ".workflow", ".tokens", ".yml", ".yaml", ".json",
+)
+
+#: Access grants and package manifests list classes without using them.
+_LISTING_SUFFIXES: tuple[str, ...] = (
+ ".profile-meta.xml", ".permissionset-meta.xml", ".permissionsetgroup-meta.xml",
+ ".mutingpermissionset-meta.xml", ".profile", ".permissionset", ".cls-meta.xml",
+ ".trigger-meta.xml",
+)
+_LISTING_NAMES: frozenset[str] = frozenset({"package.xml"})
+_LISTING_PREFIXES: tuple[str, ...] = ("destructivechanges",)
+
+#: Prose whose class names describe rather than use.
+_PROSE_SUFFIXES: tuple[str, ...] = tuple(DOC_EXTENSIONS | {".markdown", ".html", ".htm"})
+
+#: Read budget; past it the metadata is unread, so no Apex file is judged.
+_PER_FILE_BYTES = 2 * 1024 * 1024
+_TOTAL_BYTES = 256 * 1024 * 1024
+
+
+def _folded(name: str) -> bytes:
+ """*name* as the identifier scan yields it, folded."""
+ return name.casefold().encode("ascii", "ignore")
+
+
+def _folded_annotations(decorators: Iterable[str]) -> set[str]:
+ """Each annotation base in a modifiers blob, folded (``@IsTest`` -> ``istest``)."""
+ return {
+ decorator_base(token).casefold()
+ for blob in decorators
+ for token in str(blob).split("@")
+ if token.strip()
+ }
+
+
+def is_apex_entry_member(sym: Mapping[str, Any], *, as_root: bool = False) -> bool:
+ """Whether the runtime, a test or a subscriber reaches this Apex member by itself.
+
+ *as_root* asks whether the member also makes its class an entry point,
+ which ``@TestVisible`` does not.
+ """
+ if sym.get("language") != APEX_LANGUAGE:
+ return False
+ annotations = _folded_annotations(sym.get("decorators") or ())
+ if annotations & _ENTRY_ANNOTATIONS or (not as_root and _TEST_VISIBLE in annotations):
+ return True
+ return not _ENTRY_MODIFIERS.isdisjoint(sym.get("modifiers") or ())
+
+
+def _is_page_bound(sym: Mapping[str, Any]) -> bool:
+ """A Visualforce shape: an action returning ``PageReference``, or an extension
+ constructor taking a standard controller.
+
+ Ceiling: until Visualforce pages are parsed, a page naming the class may sit
+ outside the repository, so the shape alone keeps the class live. A helper
+ that merely returns a ``PageReference`` is kept live with it.
+ """
+ if sym.get("visibility") != "public":
+ return False
+ _head, arrow, returns = (sym.get("signature") or "").casefold().rpartition("->")
+ if arrow:
+ return returns.strip().rsplit(".", 1)[-1] == "pagereference"
+ # A constructor's signature has no return arrow.
+ return sym.get("kind") == "function" and (
+ "standardcontroller" in returns or "standardsetcontroller" in returns
+ )
+
+
+def _is_listing(path: str) -> bool:
+ lowered = PurePosixPath(path).name.lower()
+ return (
+ lowered in _LISTING_NAMES
+ or lowered.startswith(_LISTING_PREFIXES)
+ or lowered.endswith(_LISTING_SUFFIXES)
+ )
+
+
+def _is_metadata_record(lowered: str) -> bool:
+ # mdapi custom metadata records are ``customMetadata/<Type>.<Record>.md``.
+ return lowered.endswith(".md") and "/custommetadata/" in f"/{lowered}"
+
+
+def _is_doc(path: str) -> bool:
+ lowered = path.lower()
+ return lowered.endswith(_PROSE_SUFFIXES) and not _is_metadata_record(lowered)
+
+
+def _is_metadata(path: str) -> bool:
+ lowered = path.lower()
+ return lowered.endswith(_METADATA_SUFFIXES) or _is_metadata_record(lowered)
+
+
+def _mentions(blob: bytes, names: frozenset[bytes]) -> set[bytes]:
+ """The folded Apex type *names* written in *blob*."""
+ return {t for m in IDENTIFIER_RE.finditer(blob.lower()) if (t := m.group()) in names}
+
+
+def _metadata_paths(repo_root: Path, indexed: Mapping[str, bytes]) -> Iterable[str]:
+ """Repo-relative paths of unindexed Salesforce metadata, sorted for a stable budget."""
+ found: list[str] = []
+ for current, _dirs, files in walk_repo(repo_root, prune_dirs=_SKIP_DIRS, prune=is_output_dir):
+ rel_dir = current.relative_to(repo_root).as_posix()
+ for name in files:
+ rel = name if rel_dir == "." else f"{rel_dir}/{name}"
+ if rel not in indexed and _is_metadata(rel):
+ found.append(rel)
+ return sorted(found)
+
+
+class _ApexFacts:
+ """Declared top-level type names and folded name mentions, read once."""
+
+ def __init__(
+ self,
+ graph: Any,
+ files: list[str],
+ source_map: Mapping[str, bytes],
+ repo_root: Path | None,
+ unread: frozenset[bytes],
+ ) -> None:
+ self.declared: dict[str, set[bytes]] = {} # apex file -> folded top-level type names
+ nested = self._read_declarations(graph, files)
+ names = frozenset(nested.union(*self.declared.values()))
+ apex = set(files)
+ self.users: dict[bytes, set[str]] = {} # folded name -> apex files writing it
+ self.external: set[bytes] = set() # folded names written outside Apex
+ for path, blob in source_map.items():
+ if path in apex:
+ for name in _mentions(blob, names):
+ self.users.setdefault(name, set()).add(path)
+ elif not _is_listing(path) and not _is_doc(path):
+ self.external |= _mentions(blob, names)
+ # A name in a file ingestion skipped may be a use we could not read.
+ self.external |= names & unread
+ # Without the repository the metadata is unread, so nothing is judged.
+ self.complete = repo_root is not None and self._read_metadata(repo_root, source_map, names)
+
+ def _read_declarations(self, graph: Any, files: list[str]) -> set[bytes]:
+ """Fill :attr:`declared`; return the folded nested type names."""
+ nested: set[bytes] = set()
+ for path in files:
+ # The stem names the class, and a script kept as ``.cls`` that a config runs by path.
+ self.declared[path] = {_folded(PurePosixPath(path).stem)}
+ for data in _defined(graph, path):
+ name = _folded(data.get("name") or "")
+ if data.get("kind") not in _TYPE_KINDS or not name:
+ continue
+ if data.get("parent_name"):
+ nested.add(name)
+ else:
+ self.declared[path].add(name)
+ return nested
+
+ def _read_metadata(
+ self, repo_root: Path, source_map: Mapping[str, bytes], names: frozenset[bytes]
+ ) -> bool:
+ """Read metadata mentions; False when the budget ran out first."""
+ budget = _TOTAL_BYTES
+ for rel in _metadata_paths(repo_root, source_map):
+ if budget <= 0:
+ return False
+ if _is_listing(rel):
+ continue
+ try:
+ with open(repo_root / rel, "rb") as handle:
+ blob = handle.read(min(_PER_FILE_BYTES, budget))
+ except OSError:
+ continue
+ budget -= len(blob)
+ self.external |= _mentions(blob, names)
+ return True
+
+
+def _defined(graph: Any, path: str) -> Iterable[dict]:
+ return (graph.nodes.get(symbol, {}) for symbol in _defined_ids(graph, path))
+
+
+def _defined_ids(graph: Any, path: str) -> Iterable[str]:
+ for _path, symbol, edge in graph.out_edges(path, data=True):
+ if edge.get("edge_type") == "defines":
+ yield symbol
+
+
+def _apex_files(graph: Any) -> list[str]:
+ return [
+ node
+ for node, data in graph.nodes(data=True)
+ if isinstance(node, str)
+ and data.get("node_type", "file") == "file"
+ and data.get("language") == APEX_LANGUAGE
+ ]
+
+
+def _extends_platform_type(parsed: Any) -> bool:
+ """A class in the parsed file extends or implements a platform-instantiated type."""
+ return any(
+ (relation.parent_name or "").casefold() in APEX_PLATFORM_TYPES
+ for relation in getattr(parsed, "heritage", None) or ()
+ )
+
+
+def _is_root(graph: Any, path: str, parsed_files: Mapping[str, Any]) -> bool:
+ node = graph.nodes[path]
+ if (
+ is_reachability_root(node)
+ or node.get("is_test", False)
+ or never_flag_path(path)
+ or has_dependency_importer(graph, path)
+ ):
+ return True
+ parsed = parsed_files.get(path)
+ # Without the parse its heritage is unknown, which is not evidence of death.
+ if parsed is None or _extends_platform_type(parsed):
+ return True
+ return any(
+ is_apex_entry_member(data, as_root=True) or _is_page_bound(data)
+ for data in _defined(graph, path)
+ )
+
+
+class _Reach:
+ """The fixpoint: which candidates a live file reaches."""
+
+ def __init__(self, graph: Any, facts: _ApexFacts, candidates: set[str]) -> None:
+ self.graph = graph
+ self.facts = facts
+ self.candidates = candidates
+ self.reached: set[str] = set()
+
+ def run(self) -> frozenset[str]:
+ changed = True
+ while changed:
+ changed = False
+ for path in sorted(self.candidates - self.reached):
+ if self._named(path) or self._used(path):
+ self.reached.add(path)
+ changed = True
+ return frozenset(self.reached)
+
+ def _live(self, path: str) -> bool:
+ return path not in self.candidates or path in self.reached
+
+ def _named(self, path: str) -> bool:
+ """A live file writes a type name *path* declares (or the name cannot be searched)."""
+ facts = self.facts
+ for name in facts.declared.get(path, ()):
+ if len(name) < MIN_ANSWERABLE_NAME_LEN or name in facts.external:
+ return True
+ if any(user != path and self._live(user) for user in facts.users.get(name, ())):
+ return True
+ return False
+
+ def _used(self, path: str) -> bool:
+ """A use edge from a live file lands on a symbol *path* declares."""
+ for symbol in _defined_ids(self.graph, path):
+ for user, _symbol, use in self.graph.in_edges(symbol, data=True):
+ if use.get("edge_type") not in REACHABILITY_USE_EDGE_TYPES or is_external(user):
+ continue
+ source = file_path_of(user)
+ if source != path and self._live(source):
+ return True
+ return False
+
+
+class ApexLiveness:
+ """Which Apex files are live, and the folded name facts behind that answer."""
+
+ def __init__(
+ self,
+ graph: Any,
+ source_map: Mapping[str, bytes],
+ parsed_files: Mapping[str, Any],
+ repo_root: Path | None,
+ unread: frozenset[bytes] = frozenset(),
+ ) -> None:
+ """*unread* holds the folded identifiers of files ingestion skipped."""
+ files = _apex_files(graph)
+ self.files = frozenset(files)
+ self.facts: _ApexFacts | None = None
+ self.live = self.files
+ # Unread means unjudged: an Apex file, or the metadata, we could not read.
+ if not files or any(path not in source_map for path in files):
+ return
+ facts = _ApexFacts(graph, files, source_map, Path(repo_root) if repo_root else None, unread)
+ if not facts.complete:
+ return
+ self.facts = facts
+ candidates = {path for path in files if not _is_root(graph, path, parsed_files)}
+ self.live = self.files - candidates | _Reach(graph, facts, candidates).run()
+
+ def named_outside(self, name: str, path: str) -> bool:
+ """Whether a live file other than *path*, or any non-Apex file, writes *name*."""
+ if self.facts is None:
+ return True
+ folded = _folded(name)
+ if folded in self.facts.external:
+ return True
+ return any(user != path and user in self.live for user in self.facts.users.get(folded, ()))
+
+
+def _token_lines(blob: bytes) -> dict[bytes, list[int]]:
+ """``{folded identifier: line numbers}`` of one file, lines counted as the parser counts them."""
+ lines: dict[bytes, list[int]] = {}
+ for lineno, line in enumerate(blob.lower().split(b"\n"), start=1):
+ for token in {m.group() for m in IDENTIFIER_RE.finditer(line)}:
+ lines.setdefault(token, []).append(lineno)
+ return lines
+
+
+def settle_apex_findings(
+ findings: list[DeadCodeFindingData],
+ liveness: ApexLiveness,
+ source_map: Mapping[str, bytes],
+) -> list[DeadCodeFindingData]:
+ """Drop Apex symbol findings a case-folded name use answers; returns a new list.
+
+ A top-level type of a live file is used (that is what made the file live).
+ Any other type or private member is used when its own file writes its
+ name, any case, outside its declaration (an overload's header line is not
+ a use), and a nested type also when a live file names it (``Outer.Inner``).
+ What survives stays below deletion-ready: with no import statement, no
+ importer can show an Apex class unused.
+ """
+ token_lines: dict[str, dict[bytes, list[int]]] = {}
+ headers: dict[tuple[str, str], set[int]] = {}
+ for f in findings:
+ if f.symbol_name and f.file_path in liveness.files and f.start_line is not None:
+ headers.setdefault((f.file_path, f.symbol_name.casefold()), set()).add(f.start_line)
+
+ kept: list[DeadCodeFindingData] = []
+ for f in findings:
+ if not _is_apex_symbol_finding(f, liveness):
+ kept.append(f)
+ continue
+ if _apex_symbol_used(f, liveness, source_map, headers, token_lines):
+ continue
+ if f.kind is DeadCodeKind.UNUSED_EXPORT:
+ f.confidence = min(f.confidence, UNPROVEN_EXPORT_CONFIDENCE)
+ f.safe_to_delete = False
+ kept.append(f)
+ return kept
+
+
+def _is_apex_symbol_finding(f: DeadCodeFindingData, liveness: ApexLiveness) -> bool:
+ return (
+ f.file_path in liveness.files
+ and bool(f.symbol_name)
+ and f.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNUSED_INTERNAL)
+ )
+
+
+def _apex_symbol_used(
+ f: DeadCodeFindingData,
+ liveness: ApexLiveness,
+ source_map: Mapping[str, bytes],
+ headers: dict[tuple[str, str], set[int]],
+ token_lines: dict[str, dict[bytes, list[int]]],
+) -> bool:
+ assert f.symbol_name is not None
+ facts = liveness.facts
+ folded = _folded(f.symbol_name)
+ if len(folded) < MIN_ANSWERABLE_NAME_LEN:
+ return True # too short for the identifier scan, so unchecked
+ top_level = facts is not None and folded in facts.declared.get(f.file_path, ())
+ if f.kind is DeadCodeKind.UNUSED_EXPORT and top_level:
+ return f.file_path in liveness.live
+ blob = source_map.get(f.file_path)
+ if blob is None or f.start_line is None or f.end_line is None:
+ return True # unread, so unchecked
+ if f.file_path not in token_lines:
+ token_lines[f.file_path] = _token_lines(blob)
+ own = headers.get((f.file_path, f.symbol_name.casefold()), set())
+ # Written outside its own lines and outside a same-named sibling's header.
+ if any(
+ not f.start_line <= lineno <= f.end_line and lineno not in own
+ for lineno in token_lines[f.file_path].get(folded, ())
+ ):
+ return True
+ return f.kind is DeadCodeKind.UNUSED_EXPORT and liveness.named_outside(
+ f.symbol_name, 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.py
index 814f51b55..57b52e975 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -47,6 +47,10 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*.sh",
"*.bash",
"*.zsh",
+ # An Apex trigger is run by the platform on DML, and an anonymous-Apex
+ # script by a person or a CI job; nothing names either.
+ "*.trigger",
+ "*.apex",
"*__init__.py",
"*__main__.py",
"*conftest.py",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
index 5b4aca4f8..6cc8c87c7 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
@@ -285,6 +285,28 @@ _GODOT_CALLBACK_NAMES: frozenset[str] = frozenset({
})
+# Apex platform types the org runtime instantiates or calls into (from Setup,
+# an email service, a package install, ``sort()``), so a class extending or
+# implementing one is an entry point. Folded last segment, as heritage records it.
+APEX_PLATFORM_TYPES: frozenset[str] = frozenset({
+ # Async and scheduling
+ "schedulable", "queueable", "batchable", "finalizer",
+ # Collections and dynamic dispatch the runtime calls into
+ "comparable", "comparator", "iterable", "iterator", "callable",
+ # Test doubles the test runner calls
+ "stubprovider", "httpcalloutmock", "webservicemock",
+ # Configuration-registered handlers
+ "inboundemailhandler", "registrationhandler", "samljithandler",
+ "configurableselfreghandler", "logindiscoveryhandler",
+ "mydomainlogindiscoveryhandler", "authproviderpluginclass", "connectedappplugin",
+ "oauth2tokenexchangehandler", "installhandler", "uninstallhandler", "plugin",
+ "urlrewriter", "emailtemplateselector", "milestonetriggertimecalculator",
+ "quickactiondefaultshandler", "canvaslifecyclehandler", "eventcondition",
+ "asynccondition", "policycondition", "deploycallback", "cachebuilder",
+ "dynamicpicklist", "notificationaction",
+})
+
+
def is_contract_method(
sym_name: str,
sym_kind: str | None,
diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
index f25baa4b4..ba1404692 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
@@ -143,6 +143,9 @@ class ReachabilityRescues:
#: type reaches (see :mod:`swift_reachability`). ``None`` is "not checked"
#: and resolves a ``.swift`` file to reachable, as for C#.
swift_named_files: AbstractSet[str] | None = None
+ #: Apex files a root or a live file reaches (see :mod:`apex_reachability`).
+ #: ``None`` is "not checked" and resolves an Apex file to reachable.
+ apex_live_files: AbstractSet[str] | None = None
#: Prefix of an :class:`repowise.core.ids.ExternalId`, matched textually rather
@@ -319,13 +322,20 @@ def is_file_reachable(
return True if packages is None else is_jvm_file_reachable(path, graph, packages.jvm)
if is_cpp_path(path):
return True if packages is None else is_cpp_file_reachable(path, graph, packages.cpp)
- if path.endswith(CSHARP_SUFFIX) and (
- rescues.csharp_named_files is None or path in rescues.csharp_named_files
- ):
- return True
- if path.endswith(_SWIFT_SUFFIX) and (
- rescues.swift_named_files is None or path in rescues.swift_named_files
- ):
+ if _named_rescue(path, node_data, rescues):
return True
return has_dependency_importer(graph, path)
+
+
+def _named_rescue(path: str, node_data: Mapping[str, Any], rescues: ReachabilityRescues) -> bool:
+ """Whether *path*'s name-granular rescue (C#, Swift, Apex) reaches it; unchecked reaches."""
+ if path.endswith(CSHARP_SUFFIX):
+ named = rescues.csharp_named_files
+ elif path.endswith(_SWIFT_SUFFIX):
+ named = rescues.swift_named_files
+ elif node_data.get("language") == "apex":
+ named = rescues.apex_live_files
+ else:
+ return False
+ return named is None or path in named
diff --git a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_exports.py b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_exports.py
index c5f9f49a1..0109f6602 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_exports.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_exports.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any
from ....entry_candidacy import is_reachability_root
+from ..apex_reachability import is_apex_entry_member
from ..constants import (
_CONTAINER_USE_LANGUAGES,
_DEAD_CODE_EXEMPT_LANGUAGES,
@@ -273,6 +274,9 @@ class UnusedExportPass:
meta = self.ctx._framework_meta_annotations(sym.get("file_path", ""))
if _is_framework_registered(decorators, meta):
return True
+ # A ``global`` nested Apex class is reached by subscribers and ``Type.forName``.
+ if is_apex_entry_member(sym):
+ return True
if _declared_deliberately_unused(decorators):
return True
diff --git a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py
index 71dc2492b..4d36b80e8 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
+from ..apex_reachability import is_apex_entry_member
from ..constants import _DEAD_CODE_EXEMPT_LANGUAGES, _is_fixture_path
from ..contract_methods import is_contract_method
from ..decorator_rules import _declared_deliberately_unused, _is_framework_registered
@@ -17,8 +18,8 @@ if TYPE_CHECKING:
# Rust: the compiler's ``dead_code`` lint already reports these, with macro
# expansion and types a static graph cannot match. The exempt languages
-# (COBOL, Apex) are entered by a runtime the graph cannot see, as in the file
-# and export passes.
+# (COBOL) are entered by a runtime the graph cannot see, as in the file and
+# export passes.
_UNJUDGED_LANGUAGES = _DEAD_CODE_EXEMPT_LANGUAGES | {"rust"}
@@ -135,6 +136,9 @@ class UnusedInternalPass:
if self.ctx._name_matches_dynamic(sym_name, dynamic_patterns):
return False
+ # A private ``@future`` or ``@TestVisible`` Apex member: the platform or a test calls it.
+ if is_apex_entry_member(node_data):
+ return False
# A private ``@PostConstruct`` or ``@Scheduled`` method is called by
# the container, as in the export pass.
decorators = node_data.get("decorators") or []
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
index 876c7f5fe..b4bda4394 100644
--- a/packages/core/src/repowise/core/analysis/finding_registry.py
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -132,6 +132,7 @@ class LanguageGate:
_AUDIT_DATE = "2026-10-02"
_REAUDIT_DATE = "2026-10-15"
+_APEX_AUDIT_DATE = "2026-10-23"
_PREVIEW = "preview"
_NO_PLAN = "No judged plan was acceptable as written."
_NOT_A_COST = "Most judged opportunities were not real costs."
@@ -172,6 +173,7 @@ _GATE_ROWS: tuple[_GateRow, ...] = (
("dead_code", "c", 0.66, "35 judged findings from 2 C repos (lowest 0%)", "P/Invoke exports are unseen.", _PREVIEW, _REAUDIT_DATE),
("dead_code", "cpp", 0.68, "25 judged findings from 1 C++ repo", "Build-listed translation units and macro uses are unseen.", _PREVIEW, _REAUDIT_DATE),
("dead_code", "kotlin", 0.18, "34 judged findings from 2 Kotlin repos (lowest 0%)", "DI-bound classes are not roots.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "apex", 0.86, "51 judged findings from 6 Apex repos (lowest 0%)", "Deprecated stubs and example code read as dead.", _PREVIEW, _APEX_AUDIT_DATE),
("dead_code", "swift", 0.44, "71 judged findings from 2 Swift repos (lowest 10%)", "Cross-module function and extension-member uses are unseen.", _PREVIEW, _REAUDIT_DATE),
)
diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.py
index 7ec638fb7..00421693c 100644
--- a/packages/core/src/repowise/core/analysis/test_selection.py
+++ b/packages/core/src/repowise/core/analysis/test_selection.py
@@ -217,7 +217,7 @@ _DOC_SUFFIXES = DOC_EXTENSIONS | {"", ".markdown"}
_TEST_CODE_SUFFIXES = frozenset(
{".py", ".go", ".java", ".kt", ".kts", ".scala", ".groovy", ".rb", ".cs", ".fs"}
| {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"}
- | {".rs", ".php", ".swift", ".ex", ".exs", ".dart", ".c", ".cc", ".cpp"}
+ | {".rs", ".php", ".swift", ".ex", ".exs", ".dart", ".c", ".cc", ".cpp", ".cls"}
)
PYTHON_SUFFIXES = (".py",)
diff --git a/packages/core/src/repowise/core/code_origin.py b/packages/core/src/repowise/core/code_origin.py
index 0752fb27d..5f23394da 100644
--- a/packages/core/src/repowise/core/code_origin.py
+++ b/packages/core/src/repowise/core/code_origin.py
@@ -36,8 +36,10 @@ from .test_paths import is_test_related_path
__all__ = [
"CODE_ORIGINS",
+ "CONTENT_TEST_SUFFIXES",
"CodeOrigin",
"code_origin",
+ "declares_test",
"is_build_file",
"is_generated_header",
"is_migration_path",
@@ -785,7 +787,8 @@ def code_origin(
path.
*is_test* is the flag ingestion stored, when the caller has it. ``None``
- derives it from the path with the shared test classifier.
+ derives it from the path with the shared test classifier, and from *text*
+ where the content decides (:func:`declares_test`).
*project* is the repository's name, so its own release banner is not
taken for someone else's.
@@ -808,7 +811,7 @@ def code_origin(
and _third_party_header(header, project)
):
return "vendored"
- return _maintained_origin(normalized, name, dirs, is_test, repo_root)
+ return _maintained_origin(normalized, name, dirs, is_test, repo_root, header)
def _is_generated_content(name: str, dirs: list[str], header: str) -> bool:
@@ -819,18 +822,52 @@ def _is_generated_content(name: str, dirs: list[str], header: str) -> bool:
)
+# --------------------------------------------------------------------------
+# Test, by content
+# --------------------------------------------------------------------------
+
+#: Suffixes whose test status the file's content can decide.
+CONTENT_TEST_SUFFIXES: tuple[str, ...] = (".cls",)
+# An Apex ``@IsTest`` class is test code whatever its name. Comments and strings
+# are blanked first: ApexDoc and annotation arguments can quote the annotation.
+_APEX_CLASS_KEYWORD_RE = re.compile(r"\bclass\b", re.IGNORECASE)
+_APEX_IS_TEST_RE = re.compile(r"@istest\b", re.IGNORECASE)
+
+
+def declares_test(path: str, text: str | bytes | None) -> bool:
+ """Whether *text*, the head of the file at *path*, marks it test code.
+
+ An Apex class annotated ``@IsTest`` is; the annotation must sit before the
+ top-level ``class`` keyword, inside the first 4 KB like every content rule
+ here.
+ """
+ if not path.lower().endswith(CONTENT_TEST_SUFFIXES):
+ return False
+ # Imported here: the ingestion package imports this module.
+ from .ingestion.framework_routes import apex_code
+
+ code = apex_code(_header_text(text))
+ keyword = _APEX_CLASS_KEYWORD_RE.search(code)
+ return keyword is not None and _APEX_IS_TEST_RE.search(code, 0, keyword.start()) is not None
+
+
def _maintained_origin(
normalized: str,
name: str,
dirs: list[str],
is_test: bool | None,
repo_root: str | os.PathLike[str] | None,
+ header: str = "",
) -> CodeOrigin:
"""The origin of code this repository maintains: build, test, docs or
examples, tooling, or production, in that precedence."""
if _is_build_name(name, dirs, as_origin=True):
return "build"
- if is_test if is_test is not None else is_test_related_path(normalized):
+ if (
+ is_test
+ if is_test is not None
+ else is_test_related_path(normalized) or declares_test(normalized, header)
+ ):
return "test"
if _is_docs_example(normalized, dirs, repo_root):
return "docs_example"
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index b411bc2dc..a02b02b64 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -418,6 +418,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
import_node_types=[],
export_node_types=[],
visibility_fn=apex_visibility,
+ # ``global``, ``webservice``, ``testmethod``, ...; annotations stay decorators.
+ modifier_node_types=frozenset({"modifiers"}),
parent_extraction="nesting",
parent_class_types=frozenset(
{"class_declaration", "interface_declaration", "enum_declaration"}
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/apex.py b/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
index ba91a6e1a..adf9df430 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
@@ -20,12 +20,6 @@ SPEC = LanguageSpec(
# Apex has no import statement: every top-level class in a package
# directory is visible by name, so there is nothing for a resolver to read.
import_support="none",
- # Triggers, @AuraEnabled/@InvocableMethod/@RestResource members, platform
- # interfaces (Queueable, Batchable, ...) and global API are entered by the
- # org runtime, Lightning, Flows and managed-package subscribers, none of
- # which the static graph sees yet. Unused/unreachable claims stay off
- # until those entry points are modelled.
- dead_code_exempt=True,
# FooTest / FooTests. Foo_Test, Foo_TEST and Test_Foo already match the
# generic stem rules, which compare lowercased.
test_camel_suffixes=("Test", "Tests"),
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index e54e75f9f..c63083b56 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -32,7 +32,7 @@ import pathspec
import structlog
from pathspec.patterns.gitwildmatch import GitWildMatchPattern, GitWildMatchPatternError
-from ..code_origin import is_generated_header
+from ..code_origin import CONTENT_TEST_SUFFIXES, declares_test, is_generated_header
from ..dotnet_test_projects import DotnetTestProjects, read_dotnet_test_projects
from ..entry_candidacy import conventional_entry_stems, not_an_execution_start
from ..owned_paths import MANAGED_FILES, OWNED_PATTERNS, only_repowise_differs
@@ -900,6 +900,10 @@ class FileTraverser:
dotnet_projects=tables.dotnet_test_projects,
phpunit_roots=tables.phpunit_roots,
package_root=self._is_package_root_dir,
+ ) or (
+ # An Apex ``@IsTest`` class is test code whatever its name.
+ rel_str.lower().endswith(CONTENT_TEST_SUFFIXES)
+ and declares_test(rel_str, _read_head(abs_path))
)
entry = _is_entry_point(rel_str, abs_path, language) or manifest_entry
return FileInfo(
@@ -1215,6 +1219,15 @@ def _is_generated(abs_path: Path) -> bool:
return is_generated_header(header)
+def _read_head(abs_path: Path) -> bytes:
+ """The first 4 KB of a file, which is what a content rule reads; empty if unreadable."""
+ try:
+ with open(abs_path, "rb") as f:
+ return f.read(4096)
+ except OSError:
+ return b""
+
+
def _is_config_file(language: LanguageTag) -> bool:
return language in ("yaml", "toml", "json", "dockerfile", "makefile")
diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.py
index 446c304d1..544bf8660 100644
--- a/packages/core/src/repowise/core/test_paths.py
+++ b/packages/core/src/repowise/core/test_paths.py
@@ -745,6 +745,8 @@ _CLASS_TEST_SUFFIXES: dict[str, tuple[str, ...]] = {
".cs": ("Test", "Tests"),
".kt": ("Test", "Tests", "Spec"),
".scala": ("Spec", "Suite", "Test"),
+ # Apex names are case-insensitive and the corpora write all of these.
+ ".cls": ("Test", "Tests", "_Test", "_Tests", "_TEST"),
}
diff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.py
index d24f7ed5b..58c6fb034 100644
--- a/tests/unit/analysis/test_test_selection.py
+++ b/tests/unit/analysis/test_test_selection.py
@@ -1065,3 +1065,10 @@ def test_a_runner_gets_only_its_own_always_run_tests_and_hears_of_the_rest() ->
assert runner_args(upper, "pytest") == ["tests/test_b.py", "tests/TEST_C.PY"]
assert runner_notes(sel, "files") == []
assert runner_notes(_select(["uv.lock"], config=config), "pytest") == []
+
+
+def test_an_apex_test_class_is_test_code() -> None:
+ path = "force-app/main/default/classes/AccountServiceTest.cls"
+ assert is_runnable_test(path)
+ sel = _select([path], _tiers())
+ assert not any("is not code" in r for r in sel.reasons), sel.reasons
diff --git a/tests/unit/dead_code/test_apex_dead_code.py b/tests/unit/dead_code/test_apex_dead_code.py
new file mode 100644
index 000000000..5c6de5d45
--- /dev/null
+++ b/tests/unit/dead_code/test_apex_dead_code.py
@@ -0,0 +1,386 @@
+"""Apex dead code: entry points, case-folded name uses and metadata references.
+
+Apex has no import statement, so a class is reached by name: from a live Apex
+file, from Lightning/Visualforce/flow metadata, or by the platform itself
+(triggers, entry annotations, ``global``, platform interfaces). Controls keep
+the rescue from hiding dead code: a class only an access grant or a dead class
+names stays dead.
+"""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+from types import SimpleNamespace
+
+import networkx as nx
+import pytest
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.file_reachability import (
+ ReachabilityRescues,
+ is_file_reachable,
+)
+from repowise.core.code_origin import code_origin, declares_test
+from repowise.core.ingestion.models import HeritageRelation
+from repowise.core.test_paths import paired_test_names
+
+_CLASSES = "force-app/main/default/classes"
+
+
+def _file(
+ graph: nx.DiGraph, path: str, symbols: list[dict], *, is_test: bool = False
+) -> None:
+ graph.add_node(path, node_type="file", language="apex", is_test=is_test, symbol_count=1)
+ for sym in symbols:
+ sym_id = f"{path}::{sym['name']}" if not sym.get("parent_name") else (
+ f"{path}::{sym['parent_name']}::{sym['name']}"
+ )
+ graph.add_node(
+ sym_id,
+ node_type="symbol",
+ file_path=path,
+ language="apex",
+ visibility=sym.pop("visibility", "public"),
+ **sym,
+ )
+ graph.add_edge(path, sym_id, edge_type="defines")
+
+
+def _class(name: str, start: int = 1, end: int = 20, **extra) -> dict:
+ return {"name": name, "kind": "class", "start_line": start, "end_line": end, **extra}
+
+
+def _parsed(heritage: list[HeritageRelation] | None = None) -> SimpleNamespace:
+ return SimpleNamespace(heritage=heritage or [])
+
+
+def _analyze(
+ graph: nx.DiGraph,
+ sources: dict[str, str],
+ repo_root: Path | None = None,
+ heritage: dict[str, list[HeritageRelation]] | None = None,
+ *,
+ unindexed: list[tuple[str, str]] | None = None,
+):
+ # An empty checkout unless the test supplies one: metadata must be readable to judge.
+ repo_root = repo_root or Path(tempfile.mkdtemp())
+ parsed = {
+ path: _parsed((heritage or {}).get(path))
+ for path, data in graph.nodes(data=True)
+ if data.get("node_type") == "file"
+ }
+ return DeadCodeAnalyzer(
+ graph,
+ git_meta_map={},
+ parsed_files=parsed,
+ source_map={k: v.encode() for k, v in sources.items()},
+ repo_root=repo_root,
+ unindexed_source_files=unindexed,
+ ).analyze({"detect_zombie_packages": False, "min_confidence": 0.0})
+
+
+def _dead_files(report) -> set[str]:
+ return {f.file_path for f in report.findings if f.kind is DeadCodeKind.UNREACHABLE_FILE}
+
+
+def _flagged(report) -> set[tuple[str, str | None]]:
+ return {(f.kind.value, f.symbol_name) for f in report.findings}
+
+
+def _service_graph() -> tuple[nx.DiGraph, dict[str, str]]:
+ graph = nx.DiGraph()
+ _file(graph, f"{_CLASSES}/OrderService.cls", [_class("OrderService")])
+ _file(graph, f"{_CLASSES}/OrderServiceTest.cls", [_class("OrderServiceTest")], is_test=True)
+ sources = {
+ f"{_CLASSES}/OrderService.cls": "public class OrderService {\n}\n",
+ f"{_CLASSES}/OrderServiceTest.cls": "@IsTest class OrderServiceTest {}\n",
+ }
+ return graph, sources
+
+
+def test_a_class_nothing_names_is_unreachable() -> None:
+ graph, sources = _service_graph()
+ report = _analyze(graph, sources)
+ assert _dead_files(report) == {f"{_CLASSES}/OrderService.cls"}
+ export = next(f for f in report.findings if f.kind is DeadCodeKind.UNUSED_EXPORT)
+ assert export.symbol_name == "OrderService"
+ assert not export.safe_to_delete
+
+
+def test_a_name_written_in_another_case_is_a_use() -> None:
+ graph, sources = _service_graph()
+ sources[f"{_CLASSES}/OrderServiceTest.cls"] = (
+ "@IsTest class OrderServiceTest { static void t() { ORDERSERVICE.run(); } }\n"
+ )
+ assert _analyze(graph, sources).findings == []
+
+
+def test_lightning_and_metadata_files_name_classes(tmp_path: Path) -> None:
+ graph, sources = _service_graph()
+ # An LWC module imports the class through @salesforce/apex.
+ sources["force-app/main/default/lwc/orders/orders.js"] = (
+ "import place from '@salesforce/apex/OrderService.place';\n"
+ )
+ assert _analyze(graph, sources).findings == []
+
+ graph, sources = _service_graph()
+ flow = tmp_path / "force-app/main/default/flows/Place.flow-meta.xml"
+ flow.parent.mkdir(parents=True)
+ flow.write_text("<actionCalls><actionName>OrderService</actionName></actionCalls>")
+ assert _analyze(graph, sources, repo_root=tmp_path).findings == []
+
+
+def test_access_grants_and_docs_are_not_uses(tmp_path: Path) -> None:
+ graph, sources = _service_graph()
+ sources["docs/OrderService.md"] = "# OrderService\n"
+ grant = tmp_path / "force-app/main/default/permissionsets/Admin.permissionset-meta.xml"
+ grant.parent.mkdir(parents=True)
+ grant.write_text("<classAccesses><apexClass>OrderService</apexClass></classAccesses>")
+ (tmp_path / "manifest").mkdir()
+ (tmp_path / "manifest/package.xml").write_text("<members>OrderService</members>")
+ assert _dead_files(_analyze(graph, sources, repo_root=tmp_path)) == {
+ f"{_CLASSES}/OrderService.cls"
+ }
+
+
+ "member",
+ [
+ {"name": "place", "kind": "method", "decorators": ["@AuraEnabled(cacheable=true)\n public static"]},
+ {"name": "place", "kind": "method", "decorators": ["@invocableMethod(label='x')"]},
+ {"name": "place", "kind": "method", "modifiers": ["global", "static"]},
+ {"name": "place", "kind": "method", "modifiers": ["webservice", "static"]},
+ ],
+)
+def test_an_entry_member_makes_its_file_a_root(member: dict) -> None:
+ graph, sources = _service_graph()
+ path = f"{_CLASSES}/OrderService.cls"
+ sym_id = f"{path}::OrderService::place"
+ graph.add_node(
+ sym_id, node_type="symbol", file_path=path, language="apex", visibility="public",
+ parent_name="OrderService", start_line=2, end_line=3, **member,
+ )
+ graph.add_edge(path, sym_id, edge_type="defines")
+ assert _analyze(graph, sources).findings == []
+
+
+def test_a_platform_interface_makes_its_file_a_root() -> None:
+ graph, sources = _service_graph()
+ heritage = {
+ f"{_CLASSES}/OrderService.cls": [
+ HeritageRelation(child_name="OrderService", parent_name="Schedulable", kind="implements", line=1)
+ ]
+ }
+ assert _analyze(graph, sources, heritage=heritage).findings == []
+
+
+def test_uses_count_only_from_live_files() -> None:
+ graph, sources = _service_graph()
+ _file(graph, f"{_CLASSES}/Legacy.cls", [_class("Legacy")])
+ sources[f"{_CLASSES}/Legacy.cls"] = "public class Legacy { OrderService s; }\n"
+ assert _dead_files(_analyze(graph, sources)) == {
+ f"{_CLASSES}/OrderService.cls",
+ f"{_CLASSES}/Legacy.cls",
+ }
+ # Once a test names Legacy, both are live.
+ sources[f"{_CLASSES}/OrderServiceTest.cls"] = "@IsTest class OrderServiceTest { Legacy l; }\n"
+ assert _dead_files(_analyze(graph, sources)) == set()
+
+
+def test_triggers_and_anonymous_scripts_are_never_judged() -> None:
+ graph = nx.DiGraph()
+ _file(graph, "force-app/main/default/triggers/OrderTrigger.trigger",
+ [{"name": "OrderTrigger", "kind": "function", "start_line": 1, "end_line": 3}])
+ _file(graph, "scripts/apex/seed.apex", [])
+ assert _analyze(graph, {}).findings == []
+
+
+def _private_graph(source: str, **member: object) -> tuple[nx.DiGraph, dict[str, str]]:
+ graph = nx.DiGraph()
+ path = f"{_CLASSES}/OrderService.cls"
+ _file(graph, path, [_class("OrderService", modifiers=["global"])])
+ # A private method is never judged (members are reached through their
+ # type); a private nested class is.
+ sym = {"name": "Recalc", "kind": "class", "visibility": "private", "parent_name": "OrderService",
+ "start_line": 4, "end_line": 5, **member}
+ _file(graph, path, [sym])
+ return graph, {path: source}
+
+
+_UNUSED_PRIVATE = (
+ "global class OrderService {\n global void run() {\n }\n private class Recalc {\n }\n}\n"
+)
+
+
+def test_a_private_class_named_in_another_case_is_used() -> None:
+ source = _UNUSED_PRIVATE.replace("run() {\n", "run() {\n new RECALC();\n", 1)
+ # The use moved the class down a line.
+ graph, sources = _private_graph(source, start_line=5, end_line=6)
+ assert _analyze(graph, sources).findings == []
+
+
+def test_an_unused_private_class_is_reported() -> None:
+ graph, sources = _private_graph(_UNUSED_PRIVATE)
+ assert _flagged(_analyze(graph, sources)) == {("unused_internal", "Recalc")}
+
+
[email protected]("decorators", [["@TestVisible\n private"], ["@future\n private static"]])
+def test_a_private_member_the_platform_or_a_test_calls_is_not_reported(decorators) -> None:
+ source = _UNUSED_PRIVATE
+ graph, sources = _private_graph(source, decorators=decorators)
+ assert _analyze(graph, sources).findings == []
+
+
+def test_an_inner_class_named_in_its_own_file_is_used() -> None:
+ graph = nx.DiGraph()
+ path = f"{_CLASSES}/OrderService.cls"
+ _file(graph, path, [
+ _class("OrderService", end=6, modifiers=["global"]),
+ _class("Line", start=4, end=5, parent_name="OrderService"),
+ _class("Unused", start=6, end=6, parent_name="OrderService"),
+ ])
+ source = "global class OrderService {\n global LINE first() {\n return null; }\n public class Line {\n }\n public class Unused {} }\n"
+ report = _analyze(graph, {path: source})
+ assert _flagged(report) == {("unused_export", "Unused")}
+
+
+def test_an_unchecked_apex_file_is_reachable() -> None:
+ graph, _sources = _service_graph()
+ path = f"{_CLASSES}/OrderService.cls"
+ assert is_file_reachable(path, graph, ReachabilityRescues())
+ assert not is_file_reachable(path, graph, ReachabilityRescues(apex_live_files=frozenset()))
+
+
+class TestTestDetection:
+ def test_an_is_test_class_is_test_code_whatever_its_name(self) -> None:
+ text = "/**\n * Mentions class names.\n */\n@IsTest(SeeAllData=false)\nprivate class SampleHandler {}\n"
+ assert declares_test("classes/SampleHandler.cls", text)
+ assert code_origin("classes/SampleHandler.cls", text) == "test"
+
+ def test_the_annotation_in_a_comment_or_on_a_method_is_not_enough(self) -> None:
+ commented = "/** Use `@IsTest(SeeAllData=true)` in tests. */\npublic class ConnectApiWrapper {}\n"
+ method = "public class Util {\n @IsTest static void t() {}\n}\n"
+ assert not declares_test("classes/ConnectApiWrapper.cls", commented)
+ assert not declares_test("classes/Util.cls", method)
+ assert code_origin("classes/Util.cls", method) == "production"
+
+ def test_only_apex_classes_are_read(self) -> None:
+ assert not declares_test("src/Foo.java", "@IsTest class Foo {}")
+
+
+def test_apex_tests_pair_with_the_class_they_cover() -> None:
+ names = paired_test_names("force-app/main/default/classes/AccountService.cls")
+ assert {"AccountServiceTest.cls", "AccountService_Test.cls", "AccountService_TEST.cls",
+ "AccountService_Tests.cls", "AccountServiceTests.cls"} <= names
+
+
+def test_a_project_config_running_a_script_by_path_is_a_use(tmp_path: Path) -> None:
+ graph, sources = _service_graph()
+ (tmp_path / "cumulusci.yml").write_text(
+ "tasks:\n seed:\n options:\n path: force-app/main/default/classes/OrderService.cls\n"
+ )
+ assert _analyze(graph, sources, repo_root=tmp_path).findings == []
+
+
+def test_a_name_too_short_to_search_is_never_reported() -> None:
+ graph = nx.DiGraph()
+ path = f"{_CLASSES}/Matchers.cls"
+ _file(graph, path, [_class("Matchers", modifiers=["global"]), _class("Eq", start=2, end=2, parent_name="Matchers")])
+ report = _analyze(graph, {path: "global class Matchers {\n public class Eq {}\n}\n"})
+ assert report.findings == []
+
+
+def test_a_script_kept_as_a_class_file_is_named_by_its_path(tmp_path: Path) -> None:
+ # CumulusCI runs anonymous Apex stored as ``.cls`` by path; its only
+ # declared type is an exception class, not the file's stem.
+ graph = nx.DiGraph()
+ path = "datasets/rd2/load_settings.cls"
+ _file(graph, path, [_class("InitException", start=9, end=9)])
+ sources = {path: "public static void run() {}\npublic class InitException extends Exception {}\n"}
+ assert _dead_files(_analyze(graph, sources, repo_root=tmp_path)) == {path}
+ (tmp_path / "cumulusci.yml").write_text("tasks:\n seed:\n options:\n path: datasets/rd2/load_settings.cls\n")
+ assert _dead_files(_analyze(graph, sources, repo_root=tmp_path)) == set()
+
+
+ "member",
+ [
+ {"name": "save", "kind": "method", "signature": "save() -> PageReference"},
+ {"name": "OrderService", "kind": "function",
+ "signature": "OrderService(ApexPages.StandardController controller)"},
+ ],
+)
+def test_a_visualforce_shaped_class_is_a_root(member: dict) -> None:
+ # Pages are not parsed yet, so the controller shape keeps the class live.
+ graph, sources = _service_graph()
+ path = f"{_CLASSES}/OrderService.cls"
+ _file(graph, path, [{**member, "parent_name": "OrderService", "start_line": 2, "end_line": 3}])
+ assert _analyze(graph, sources).findings == []
+
+
+def test_a_global_nested_class_is_an_entry_point() -> None:
+ # Reached by ``Type.forName`` on a configured name, or by a subscriber.
+ graph = nx.DiGraph()
+ path = f"{_CLASSES}/Handlers.cls"
+ _file(graph, path, [
+ _class("Handlers", end=4, modifiers=["global"]),
+ _class("ToApex", start=2, end=3, parent_name="Handlers", modifiers=["global"]),
+ ])
+ assert _analyze(graph, {path: "global class Handlers {\n global class ToApex {\n }\n}\n"}).findings == []
+
+
+def test_a_test_visible_member_does_not_make_its_class_a_root() -> None:
+ graph, sources = _service_graph()
+ path = f"{_CLASSES}/OrderService.cls"
+ _file(graph, path, [{"name": "Cache", "kind": "class", "visibility": "private", "parent_name": "OrderService",
+ "start_line": 2, "end_line": 2, "decorators": ["@TestVisible\n private"]}])
+ report = _analyze(graph, sources)
+ assert _dead_files(report) == {path}
+ assert ("unused_internal", "Cache") not in _flagged(report)
+
+
+def test_metadata_past_the_read_budget_leaves_apex_unjudged(tmp_path: Path, monkeypatch) -> None:
+ from repowise.core.analysis.dead_code import apex_reachability
+
+ monkeypatch.setattr(apex_reachability, "_TOTAL_BYTES", 0)
+ (tmp_path / "flows").mkdir()
+ (tmp_path / "flows/Place.flow-meta.xml").write_text("<actionName>Other</actionName>")
+ graph, sources = _service_graph()
+ assert _analyze(graph, sources, repo_root=tmp_path).findings == []
+
+
+def test_a_quoted_annotation_does_not_make_a_test() -> None:
+ text = "@SuppressWarnings('@IsTest')\npublic class Foo {}\n"
+ assert not declares_test("classes/Foo.cls", text)
+
+
+def test_an_annotation_after_a_quoted_argument_still_makes_a_test() -> None:
+ text = "@SuppressWarnings('PMD.ApexDoc')\n@IsTest\nprivate class FooTests {}\n"
+ assert declares_test("classes/FooTests.cls", text)
+
+
+def test_without_the_repository_nothing_is_judged() -> None:
+ # The metadata that may name a class cannot be read, so unread means unjudged.
+ graph, sources = _service_graph()
+ report = DeadCodeAnalyzer(
+ graph, git_meta_map={}, parsed_files={p: _parsed() for p in graph.nodes if p.endswith(".cls")},
+ source_map={k: v.encode() for k, v in sources.items()}, repo_root=None,
+ ).analyze({"detect_zombie_packages": False, "min_confidence": 0.0})
+ assert report.findings == []
+
+
+def test_an_apex_file_missing_from_the_source_map_leaves_apex_unjudged() -> None:
+ graph, sources = _service_graph()
+ del sources[f"{_CLASSES}/OrderServiceTest.cls"]
+ assert _analyze(graph, sources).findings == []
+
+
+def test_a_name_in_a_file_ingestion_skipped_is_a_use(tmp_path: Path) -> None:
+ graph, sources = _service_graph()
+ bundle = tmp_path / "force-app/main/default/staticresources/app.js"
+ bundle.parent.mkdir(parents=True)
+ bundle.write_text("callApex('OrderService.place');")
+ rel = "force-app/main/default/staticresources/app.js"
+ report = _analyze(graph, sources, repo_root=tmp_path, unindexed=[(rel, "size")])
+ assert _dead_files(report) == set()
diff --git a/tests/unit/dead_code/test_cobol_external_entry.py b/tests/unit/dead_code/test_cobol_external_entry.py
index 68e9bec35..97f2dddb5 100644
--- a/tests/unit/dead_code/test_cobol_external_entry.py
+++ b/tests/unit/dead_code/test_cobol_external_entry.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import networkx as nx
-import pytest
from repowise.core.analysis.dead_code.analyzer import DeadCodeAnalyzer
@@ -60,11 +59,9 @@ def _private_method_graph(language: str) -> nx.DiGraph:
return graph
[email protected]("language", ["apex", "cobol"])
-def test_exempt_language_private_symbol_is_not_an_unused_internal(language: str) -> None:
- # Apex private symbols back triggers, @AuraEnabled and test classes the
- # graph cannot see yet, so the internal pass honours the exemption too.
- report = DeadCodeAnalyzer(_private_method_graph(language), git_meta_map={}).analyze(
+def test_exempt_language_private_symbol_is_not_an_unused_internal() -> None:
+ # The internal pass honours the exemption like the file and export passes.
+ report = DeadCodeAnalyzer(_private_method_graph("cobol"), git_meta_map={}).analyze(
{"detect_zombie_packages": False}
)
assert report.findings == []
diff --git a/tests/unit/ingestion/parser/golden/apex.json b/tests/unit/ingestion/parser/golden/apex.json
index f6e60a9bb..ba4c4c1a5 100644
--- a/tests/unit/ingestion/parser/golden/apex.json
+++ b/tests/unit/ingestion/parser/golden/apex.json
@@ -32,7 +32,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -55,7 +57,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -78,7 +82,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -101,7 +107,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -126,7 +134,10 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public",
+ "static"
+ ],
"alias_of": null
},
{
@@ -149,7 +160,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -172,7 +185,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "private"
+ ],
"alias_of": null
},
{
@@ -195,7 +210,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "private"
+ ],
"alias_of": null
},
{
@@ -218,7 +235,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -241,7 +260,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -264,7 +285,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
},
{
@@ -310,7 +333,9 @@
"type_parameter_count": null,
"extension_receiver": null,
"written_receiver": null,
- "modifiers": [],
+ "modifiers": [
+ "public"
+ ],
"alias_of": null
}
],
diff --git a/tests/unit/ingestion/parser/test_apex.py b/tests/unit/ingestion/parser/test_apex.py
index 2d3eea165..191beb050 100644
--- a/tests/unit/ingestion/parser/test_apex.py
+++ b/tests/unit/ingestion/parser/test_apex.py
@@ -108,6 +108,14 @@ class TestApexSymbols:
assert symbols["AccountService"].decorators[0].startswith("@IsTest")
assert symbols["helper"].decorators == []
+ def test_modifier_keywords_are_lowercased_without_annotations(self, parser: ASTParser) -> None:
+ symbols = _by_name(_parse(parser, CLASS_SOURCE))
+ assert symbols["find"].modifiers == ("global", "static")
+ assert symbols["ws"].modifiers == ("webservice", "static")
+ assert symbols["helper"].modifiers == ()
+ # ``with sharing`` is not a single keyword, and annotations stay decorators.
+ assert symbols["AccountService"].modifiers == ("public",)
+
def test_apexdoc(self, parser: ASTParser) -> None:
symbols = _by_name(_parse(parser, CLASS_SOURCE))
assert symbols["AccountService"].docstring == "Account operations."
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
index 72a9d3fcc..eb0fe0dd6 100644
--- a/tests/unit/ingestion/test_language_capabilities.py
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -263,9 +263,8 @@ class TestImportSupportTiers:
assert REGISTRY.import_support_for("klingon") == "none"
def test_runtime_entered_languages_are_exempt_from_static_dead_code_claims(self) -> None:
- # Apex until its platform entry points (triggers, annotations,
- # platform interfaces) are modelled.
- assert REGISTRY.dead_code_exempt_languages() == frozenset({"cobol", "apex"})
+ # Apex models its platform entry points instead (apex_reachability).
+ assert REGISTRY.dead_code_exempt_languages() == frozenset({"cobol"})
class TestLanguageTagParity:
diff --git a/tests/unit/server/mcp/test_preview_gates.py b/tests/unit/server/mcp/test_preview_gates.py
index 9ec51bc96..f62574fcb 100644
--- a/tests/unit/server/mcp/test_preview_gates.py
+++ b/tests/unit/server/mcp/test_preview_gates.py
@@ -51,7 +51,7 @@ def test_shipped_table_states():
expected = {
("health", "cpp"): "preview",
**{(layer, lang): "preview" for layer in ("refactoring", "performance") for lang in audited},
- **{("dead_code", lang): "preview" for lang in (*audited, "kotlin", "swift")},
+ **{("dead_code", lang): "preview" for lang in (*audited, "kotlin", "swift", "apex")},
}
assert states == expected
assert all(finding_registry.gates_on(layer) == () for layer in ("health", "refactoring",