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: JVM dead-code hardening (reachability, never-flag, contracts, framework annotations) (#275)

Raghav Chamadiya22a55ed58384
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 826495484..0b55917a1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -29,6 +29,7 @@ from .constants import (
)
from .contract_methods import is_contract_method
from .go_reachability import build_go_package_files, is_go_file_reachable
+from .jvm_reachability import build_jvm_package_files, is_jvm_file_reachable
# Symbol kinds that cannot be independently imported by name in any
# supported language. Flagging them as "unused exports" is a guaranteed
@@ -199,6 +200,20 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
"clientAction",
# ---- SvelteKit page/layout module exports (distinctive names) ----
"trailingSlash",
+ # ---- JVM (Java + Kotlin) runtime / serialization / contract anchors ----
+ # ``main`` is already covered above; these are the rest of the names
+ # the JVM resolves through reflection / serialization / Lombok-equivalent
+ # generation, never through static call edges. ``INSTANCE`` is the
+ # Kotlin ``object Foo`` singleton field; the JVM accesses it directly.
+ "serialVersionUID",
+ "readObject",
+ "writeObject",
+ "readObjectNoData",
+ "readResolve",
+ "writeReplace",
+ "canEqual", # Lombok-equivalent generated method
+ "INSTANCE", # Kotlin object singleton field
+ "Companion", # Kotlin companion-object accessor
})
from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_files
from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
@@ -290,6 +305,9 @@ class DeadCodeAnalyzer:
# Lazily-built ``.go`` package-directory → file-node map, used by the
# Go package-granular reachability hook (see ``go_reachability``).
self._go_package_files: dict[str, list[str]] | None = None
+ # Lazily-built JVM (``.java`` + ``.kt``) package-directory map; see
+ # :mod:`jvm_reachability`.
+ self._jvm_package_files: dict[str, list[str]] | None = None
def _go_packages(self) -> dict[str, list[str]]:
"""Return the cached Go package map, building it on first use."""
@@ -297,6 +315,12 @@ class DeadCodeAnalyzer:
self._go_package_files = build_go_package_files(self.graph)
return self._go_package_files
+ def _jvm_packages(self) -> dict[str, list[str]]:
+ """Return the cached JVM package map, building it on first use."""
+ if self._jvm_package_files is None:
+ self._jvm_package_files = build_jvm_package_files(self.graph)
+ return self._jvm_package_files
+
def analyze(
self,
config: dict | None = None,
@@ -442,8 +466,15 @@ class DeadCodeAnalyzer:
# importer can still be live (entry-package sibling next to
# main.go, or a package whose siblings carry the import). Delegate
# to the Go helper instead of the raw file-level in_degree check.
- if str(node).endswith(".go"):
- if is_go_file_reachable(str(node), self.graph, self._go_packages()):
+ node_str = str(node)
+ if node_str.endswith(".go"):
+ if is_go_file_reachable(node_str, self.graph, self._go_packages()):
+ continue
+ elif node_str.endswith(".java") or node_str.endswith(".kt"):
+ # JVM reachability is package-aware too: sibling-rescued
+ # packages plus stereotype-annotated / ``main``-carrying
+ # files surface as live even with no direct importer.
+ if is_jvm_file_reachable(node_str, self.graph, self._jvm_packages()):
continue
elif self.graph.in_degree(node) > 0:
continue
@@ -867,6 +898,29 @@ class DeadCodeAnalyzer:
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
+ # Framework-decorator skip — same shape as unused-export. A
+ # private ``@PostConstruct``/``@EventListener``/``@Scheduled``
+ # method is invoked by the container, not by a source call.
+ decorators = node_data.get("decorators") or []
+ if decorators:
+ def _dec_base(d: str) -> str:
+ stripped = d.lstrip("@")
+ paren = stripped.find("(")
+ return stripped[:paren] if paren >= 0 else stripped
+
+ if any(
+ _dec_base(d).startswith(prefix)
+ for d in decorators
+ for prefix in _FRAMEWORK_DECORATORS
+ ):
+ continue
+ if any(
+ _dec_base(d).endswith(suffix)
+ for d in decorators
+ for suffix in _FRAMEWORK_DECORATOR_SUFFIXES
+ ):
+ continue
+
has_callers = any(
self.graph.get_edge_data(pred, node, {}).get("edge_type") == "calls"
for pred in self.graph.predecessors(node)
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 8d84fe0bc..5d1b90baf 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -381,6 +381,77 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*/+error.svelte",
# ESM declaration outputs in dist trees.
"*/dist/*.d.ts",
+ # ---- JVM (Java + Kotlin) conventions ---------------------------------
+ # JPMS module descriptors and package-info files declare no importable
+ # symbols by design — they exist to carry module/package metadata that
+ # the JVM consumes via reflection at link/load time.
+ "*/module-info.java",
+ "module-info.java",
+ "*/package-info.java",
+ "package-info.java",
+ # Gradle / Maven test source sets. ``fnmatch`` ``*`` spans ``/`` so a
+ # leading ``*`` matches both nested module trees and repo-root layouts.
+ # The ``*Test`` and ``*Tests`` globs catch project-specific source-set
+ # names (``apacheTest``, ``eclipseTest``, ``frayTest``, ``intTest``,
+ # ``functionalTest``, ``smokeTest`` …) without an explicit allowlist.
+ "*/src/test/java/*",
+ "*/src/test/kotlin/*",
+ "*/src/integrationTest/*",
+ "*/src/it/*",
+ "*/src/intTest/*",
+ "*/src/e2eTest/*",
+ "*/src/functionalTest/*",
+ "*/src/smokeTest/*",
+ "*/src/acceptanceTest/*",
+ "*/src/jmh/*",
+ "*/src/perfTest/*",
+ "*/src/*Test/java/*",
+ "*/src/*Tests/java/*",
+ "*/src/*Test/kotlin/*",
+ "*/src/*Tests/kotlin/*",
+ # Repo-root variants (single-module project).
+ "src/test/java/*",
+ "src/test/kotlin/*",
+ "src/integrationTest/*",
+ "src/intTest/*",
+ "src/*Test/java/*",
+ "src/*Tests/java/*",
+ # File-suffix conventions for tests dropped outside a standard source
+ # set (TestNG, JUnit, Spock, ArchUnit, pact-jvm, jqwik).
+ "*Test.java",
+ "*Tests.java",
+ "*IT.java",
+ "*ITCase.java",
+ "*TestCase.java",
+ "*FrayTest.java",
+ "*Benchmark.java",
+ "*Spec.java",
+ "*Specification.java",
+ "*Test.kt",
+ "*Tests.kt",
+ "*IT.kt",
+ "*Spec.kt",
+ "*Specification.kt",
+ # Generated source roots emitted by Gradle / Maven / KAPT / KSP /
+ # annotation-processors / GraalVM AOT. Wired in at build time by the
+ # JVM toolchain, never imported by static source.
+ "*/build/generated/*",
+ "*/build/generated-src/*",
+ "*/target/generated-sources/*",
+ "*/target/generated-test-sources/*",
+ "*/build/generated/source/kapt/*",
+ "*/build/generated/source/kaptKotlin/*",
+ "*/build/generated/source/ksp/*",
+ "*/build/generated/aotSources/*",
+ # Generated-name suffixes that have unambiguous tool ownership.
+ "*_Generated.java",
+ "*$Generated.java",
+ "*MapperImpl.java", # MapStruct compile-time impl
+ "*Dagger*.java",
+ "*AutoValue_*.java",
+ "*ServiceGrpc.java",
+ "*OuterClass.java", # protoc generated outer class
+ "*$WrapperImpl.java",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
@@ -429,6 +500,116 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = (
# Typer — same shape.
"typer.command",
"typer.callback",
+ # ---- JVM: Spring / Jakarta / Quarkus / Micronaut stereotypes ----
+ # Bare-name match against the stripped ``@Foo`` form. A class or
+ # method bearing one of these is wired into the container / route
+ # table / event bus by reflection — never imported by source name.
+ "Component",
+ "Service",
+ "Repository",
+ "Controller",
+ "RestController",
+ "Configuration",
+ "ControllerAdvice",
+ "RestControllerAdvice",
+ "Mapper", # MapStruct + MyBatis
+ "SpringBootApplication",
+ "SpringBootConfiguration",
+ "EnableAutoConfiguration",
+ "Configurable",
+ "Endpoint",
+ "RestControllerEndpoint",
+ "WebMvcTest",
+ "DataJpaTest",
+ "Entity",
+ "MappedSuperclass",
+ "Embeddable",
+ "Converter", # JPA AttributeConverter
+ "QuarkusMain",
+ "QuarkusTest",
+ "QuarkusIntegrationTest",
+ "NativeImageTest",
+ "MicronautApplication",
+ "MicronautTest",
+ "Path", # JAX-RS
+ "Provider",
+ "WebServlet",
+ "WebFilter",
+ "WebListener",
+ "ApplicationScoped",
+ "RequestScoped",
+ "SessionScoped",
+ "Singleton",
+ "Stateless",
+ "Stateful",
+ "Dependent",
+ "Factory",
+ "Bean",
+ # ---- JVM: lifecycle / event / scheduling / messaging callbacks --
+ "PostConstruct",
+ "PreDestroy",
+ "EventListener",
+ "TransactionalEventListener",
+ "Scheduled",
+ "Schedule", # Quarkus
+ "JmsListener",
+ "KafkaListener",
+ "RabbitListener",
+ "SqsListener",
+ "StreamListener",
+ "Incoming",
+ "Outgoing",
+ "OnOpen",
+ "OnClose",
+ "OnMessage",
+ "OnError",
+ "PactTestFor",
+ "Pact",
+ # ---- JVM: test method markers -----------------------------------
+ "Test",
+ "ParameterizedTest",
+ "RepeatedTest",
+ "TestFactory",
+ "TestTemplate",
+ "BeforeAll",
+ "AfterAll",
+ "BeforeEach",
+ "AfterEach",
+ "Before",
+ "After",
+ "BeforeClass",
+ "AfterClass",
+ "DataProvider",
+ "ArchTest",
+ "Container", # Testcontainers
+ "DynamicTest",
+ "JsonCreator", # Jackson factory method — reflectively invoked
+ "JsonProperty",
+ "Mojo", # Maven plugin entry
+ "Goal",
+ "RegisterForReflection",
+ # ---- JVM: routing / HTTP-verb annotations -----------------------
+ # A method bearing one of these is a route handler — invoked by the
+ # framework dispatcher, not by source. Treated as an entry point.
+ "RequestMapping",
+ "GetMapping",
+ "PostMapping",
+ "PutMapping",
+ "DeleteMapping",
+ "PatchMapping",
+ "MessageMapping",
+ "SubscribeMapping",
+ "ExceptionHandler",
+ "InitBinder",
+ "ModelAttribute",
+ "GET", # JAX-RS / Quarkus / Micronaut
+ "POST",
+ "PUT",
+ "DELETE",
+ "PATCH",
+ "HEAD",
+ "OPTIONS",
+ "Route",
)
# Decorator *suffixes* that indicate framework registration regardless of
@@ -452,6 +633,8 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (
".callback",
)
+
+
# Default dynamic patterns (plugins, handlers, etc.)
_DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = (
"*Plugin",
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 5955dc852..4d294bdcd 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
@@ -58,6 +58,55 @@ _COM_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
_COM_LANGUAGES: frozenset[str] = frozenset({"cpp", "c", "csharp", "rust"})
+# Method names reserved by JVM ``Object`` / ``Serializable`` / ``Comparable`` /
+# ``Cloneable`` contracts and by language-emitted synthesis (Kotlin data
+# classes' ``componentN``/``copy``, enum classes' ``values``/``valueOf``,
+# Lombok-generated ``canEqual``). Each is dispatched by the JVM through
+# vtable, the serialization machinery, the reflective ``Object`` API, or
+# language-emitted runtime helpers — never via a static call edge the
+# graph can observe. A live class with no other inbound edges should not
+# read as dead simply because it overrode ``equals`` and ``hashCode``.
+_JVM_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
+ # java.lang.Object overrides
+ "equals",
+ "hashCode",
+ "toString",
+ "clone",
+ "finalize",
+ # java.lang.Comparable / Comparator
+ "compareTo",
+ "compare",
+ # java.io.Serializable / Externalizable
+ "readObject",
+ "writeObject",
+ "readObjectNoData",
+ "readResolve",
+ "writeReplace",
+ "readExternal",
+ "writeExternal",
+ # Lombok-generated equality helper
+ "canEqual",
+ # Kotlin data-class synthesised members (also valid as a Java record
+ # accessor pattern when the name happens to collide)
+ "copy",
+ # Enum-class static helpers emitted by ``javac`` / Kotlin
+ "values",
+ "valueOf",
+ # ``componentN()`` accessors emitted by Kotlin data classes — names
+ # are ``component1`` .. ``component22``. Listed individually below.
+})
+
+# Kotlin data-class ``componentN`` accessors — ``component1`` through
+# ``component22`` is the practical ceiling (Kotlin stdlib's ``Tuple``
+# limit). Listed explicitly so a single set lookup covers the case.
+_JVM_CONTRACT_METHOD_NAMES = _JVM_CONTRACT_METHOD_NAMES | frozenset(
+ f"component{i}" for i in range(1, 23)
+)
+
+
+_JVM_LANGUAGES: frozenset[str] = frozenset({"java", "kotlin"})
+
+
def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None) -> bool:
"""Return True if *sym_name* is a reserved contract-method name in *language*.
@@ -71,6 +120,8 @@ def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None
# language combination is restrictive enough on its own.
if sym_kind not in ("method", "function"):
return False
- if language not in _COM_LANGUAGES:
- return False
- return sym_name in _COM_CONTRACT_METHOD_NAMES
+ if language in _COM_LANGUAGES and sym_name in _COM_CONTRACT_METHOD_NAMES:
+ return True
+ if language in _JVM_LANGUAGES and sym_name in _JVM_CONTRACT_METHOD_NAMES:
+ return True
+ return False
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index ac1d8541b..34cfa7b89 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -99,12 +99,71 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
'"use server"',
'"use client"',
),
- ".java": ("Class.forName(", "ServiceLoader.load("),
+ ".java": (
+ # Core reflection
+ "Class.forName(",
+ "ServiceLoader.load(",
+ ".loadClass(",
+ ".getContextClassLoader(",
+ "Method.invoke(",
+ ".invoke(",
+ "Constructor.newInstance(",
+ ".newInstance(",
+ ".getMethod(",
+ ".getDeclaredMethod(",
+ ".getField(",
+ ".getDeclaredField(",
+ "Proxy.newProxyInstance(",
+ # Test / mock / JSON / mapping factories that resolve concrete
+ # types at runtime by their .class literal
+ "Mockito.mock(",
+ "Mockito.spy(",
+ "Mappers.getMapper(",
+ ".readValue(",
+ ".fromJson(",
+ # Spring Boot bootstrap + container lookups
+ "SpringApplication.run(",
+ ".getBean(",
+ # DI annotations whose mere presence implies framework wiring
+ "@Autowired",
+ "@Inject",
+ "@Resource",
+ "@Bean",
+ "@ConfigurationProperties",
+ "@Value(",
+ "@RegisterForReflection",
+ "@JsonCreator",
+ "@JsonSubTypes",
+ # SnakeYAML / Jackson polymorphic loading
+ "TypeReference<",
+ ),
".kt": (
"Class.forName(",
"ServiceLoader.load(",
"KClass.createInstance(",
"::class.java",
+ "::class.objectInstance",
+ ".loadClass(",
+ "Method.invoke(",
+ ".invoke(",
+ ".newInstance(",
+ "Mockito.mock(",
+ "Mockito.spy(",
+ "mockk<",
+ "mockk(",
+ "Mappers.getMapper(",
+ ".readValue(",
+ ".fromJson(",
+ "runApplication<", # Spring Boot Kotlin bootstrap
+ "SpringApplication.run(",
+ ".getBean(",
+ "@Autowired",
+ "@Inject",
+ "@Resource",
+ "@Bean",
+ "@ConfigurationProperties",
+ "@RegisterForReflection",
+ "@JsonCreator",
),
".rb": (
"autoload ",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
new file mode 100644
index 000000000..ba9fbb2d8
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py
@@ -0,0 +1,176 @@
+"""Package-granular reachability for JVM source (Java + Kotlin).
+
+The generic unreachable-file pass treats ``in_degree == 0`` as dead. For
+JVM source that view misses three real shapes:
+
+- **Sibling-rescued packages.** Java's import resolver fans out to every
+ file in a package, so an imported package is normally all-or-nothing.
+ But Lombok / record / data-class synthesis and Kotlin top-level files
+ occasionally land in a package whose other files carry the importer
+ edge — package-level reachability rescues them as a belt-and-suspenders
+ pass that mirrors :mod:`go_reachability`.
+- **Stereotype-annotated classes.** A class with ``@Component`` /
+ ``@Service`` / ``@RestController`` / ``@Entity`` / ``@QuarkusMain`` /
+ ``@SpringBootApplication`` (and friends) is instantiated by the runtime
+ via reflection — never by a static call edge. The graph stores those
+ annotations as decorators on the class symbol; the helper checks the
+ file's defined symbols.
+- **``main(String[])`` carriers.** A file declaring a ``public static void
+ main(String[])`` is the JAR entry point.
+
+META-INF/services, JPMS ``provides ... with``, and Spring Boot autoconfig
+imports are *not* re-checked here — those are stamped as
+``is_entry_point`` on the file node during the JVM warmup (see
+:mod:`graph_warmups`), and the analyzer's existing entry-point skip
+honours them before reaching this hook.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from typing import Any
+
+# Class-level annotation names (without the leading ``@``) that mark the
+# bearing class as runtime-instantiated. Kept compact; full Spring
+# stereotype recognition + meta-annotation resolution lands in Phase 4
+# framework_edges. Anything matched here is "the runtime will load this".
+_STEREOTYPE_ANNOTATIONS: frozenset[str] = frozenset({
+ "Component",
+ "Service",
+ "Repository",
+ "Controller",
+ "RestController",
+ "Configuration",
+ "ControllerAdvice",
+ "RestControllerAdvice",
+ "SpringBootApplication",
+ "SpringBootConfiguration",
+ "EnableAutoConfiguration",
+ "Mapper", # MapStruct + MyBatis
+ "Entity",
+ "MappedSuperclass",
+ "Embeddable",
+ "Converter",
+ "QuarkusMain",
+ "QuarkusTest",
+ "QuarkusIntegrationTest",
+ "MicronautApplication",
+ "MicronautTest",
+ "WebMvcTest",
+ "DataJpaTest",
+ "WebServlet",
+ "WebFilter",
+ "WebListener",
+ "Path", # JAX-RS
+ "Provider",
+ "ApplicationScoped",
+ "RequestScoped",
+ "SessionScoped",
+ "Singleton",
+ "Stateless",
+ "Stateful",
+ "Dependent",
+ "Factory",
+ "Endpoint",
+ "RestControllerEndpoint",
+ "RegisterForReflection",
+})
+
+
+def _pkg_dir(node: str) -> str:
+ """Repo-relative POSIX directory of a JVM source file ("" = repo root)."""
+ parent = PurePosixPath(node).parent.as_posix()
+ return "" if parent == "." else parent
+
+
+def build_jvm_package_files(graph: Any) -> dict[str, list[str]]:
+ """Group every ``.java`` and ``.kt`` file node in *graph* by directory.
+
+ Directory is the JVM compilation unit's package on disk (modulo the
+ ``src/main/java`` vs ``src/main/kotlin`` srcDir prefix — both languages
+ live alongside each other in the same package directory).
+ """
+ packages: dict[str, list[str]] = {}
+ for node in graph.nodes():
+ s = str(node)
+ if not (s.endswith(".java") or s.endswith(".kt")):
+ continue
+ packages.setdefault(_pkg_dir(s), []).append(s)
+ return packages
+
+
+def _annotation_base(decorator: str) -> str:
+ """Strip ``@``, generic args, and arg list from a decorator string."""
+ s = decorator.lstrip("@")
+ for sep in ("(", "<"):
+ pos = s.find(sep)
+ if pos >= 0:
+ s = s[:pos]
+ # Spring annotations may be FQN ('org.springframework.stereotype.Service');
+ # we match the bare type name.
+ if "." in s:
+ s = s.rsplit(".", 1)[1]
+ return s
+
+
+def _file_defines_entry_class(graph: Any, file_node: str) -> bool:
+ """True if *file_node* defines a class with a stereotype annotation
+ or a ``main`` method.
+ """
+ for succ in graph.successors(file_node):
+ succ_data = graph.nodes.get(succ, {})
+ if succ_data.get("node_type") != "symbol":
+ continue
+ edge = graph.get_edge_data(file_node, succ, {})
+ if edge.get("edge_type") != "defines":
+ continue
+ # Stereotype annotation on a class / record / object.
+ decorators = succ_data.get("decorators") or []
+ for dec in decorators:
+ if _annotation_base(dec) in _STEREOTYPE_ANNOTATIONS:
+ return True
+ # ``main`` method — JAR / Kotlin file entry point.
+ if (
+ succ_data.get("kind") in ("method", "function")
+ and succ_data.get("name") == "main"
+ ):
+ return True
+ return False
+
+
+def is_jvm_file_reachable(
+ node: str,
+ graph: Any,
+ package_files: dict[str, list[str]],
+) -> bool:
+ """Return True if a JVM source file is reachable beyond ``in_degree``.
+
+ Called from the analyzer only for ``.java`` / ``.kt`` nodes that have
+ already passed the generic skips (entry point, test, never-flag). The
+ file is rescued when:
+
+ - it has an inbound graph edge (degenerate fast path);
+ - any sibling in the same package directory has an inbound edge or is
+ an entry-point file (sibling-rescued package);
+ - it defines a class annotated with a runtime-loaded stereotype
+ (Spring/Jakarta/Quarkus/Micronaut/JPA);
+ - it defines a ``main`` method.
+ """
+ if graph.in_degree(node) > 0:
+ return True
+
+ if _file_defines_entry_class(graph, node):
+ return True
+
+ for sibling in package_files.get(_pkg_dir(node), ()):
+ if sibling == node:
+ continue
+ sib_data = graph.nodes.get(sibling, {})
+ if graph.in_degree(sibling) > 0:
+ return True
+ if sib_data.get("is_entry_point", False):
+ return True
+ if _file_defines_entry_class(graph, sibling):
+ return True
+
+ return False
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index 07164e5a9..a8dc224b5 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -37,7 +37,29 @@ Warmup = Callable[["ResolverContext"], None]
def _warmup_jvm(ctx: "ResolverContext") -> None:
from .resolvers.jvm_workspace import get_or_build_jvm_index
- get_or_build_jvm_index(ctx)
+ index = get_or_build_jvm_index(ctx)
+ graph = getattr(ctx, "graph", None)
+ if graph is None:
+ return
+
+ # Collect every FQN that is reached by a *resource* mechanism the
+ # graph cannot see: META-INF/services lines, JPMS ``provides ... with``
+ # directives (both merged into ``index.services``), and Spring Boot
+ # autoconfig imports (Boot-2 ``spring.factories``, Boot-3 ``.imports``).
+ # Stamp the defining file node as ``is_entry_point`` so the
+ # unreachable-file pass treats it as live without a per-language
+ # check on every node.
+ entry_fqns: set[str] = set()
+ for impls in index.services.values():
+ entry_fqns.update(impls)
+ for fqns in index.autoconfig_imports.values():
+ entry_fqns.update(fqns)
+
+ for fqn in entry_fqns:
+ for path in index.files_for_fqn(fqn):
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
def _warmup_dotnet(ctx: "ResolverContext") -> None:
diff --git a/tests/unit/analysis/test_jvm_reachability.py b/tests/unit/analysis/test_jvm_reachability.py
new file mode 100644
index 000000000..615352362
--- /dev/null
+++ b/tests/unit/analysis/test_jvm_reachability.py
@@ -0,0 +1,383 @@
+"""Regression tests: JVM package-aware reachability + never-flag rules.
+
+Asserts:
+
+- ``is_jvm_file_reachable`` rescues siblings of an imported package and
+ files defining stereotype-annotated classes / ``main`` carriers;
+- never-flag globs cover ``module-info.java``, ``package-info.java``,
+ test source-set patterns (``apacheTest``, ``intTest``, …), and the
+ Gradle / Maven generated-source roots;
+- JVM contract methods (``equals``, ``hashCode``, ``readObject``,
+ ``componentN``, …) are protected;
+- ``_FRAMEWORK_DECORATORS`` skips Spring stereotype / JUnit / Spring
+ routing decorators in both unused-export and unused-internal passes.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.constants import (
+ _FRAMEWORK_DECORATORS,
+ _NEVER_FLAG_PATTERNS,
+)
+from repowise.core.analysis.dead_code.contract_methods import is_contract_method
+from repowise.core.analysis.dead_code.jvm_reachability import (
+ build_jvm_package_files,
+ is_jvm_file_reachable,
+)
+
+
+# ---------------------------------------------------------------------------
+# Graph helper
+# ---------------------------------------------------------------------------
+
+
+def _build_graph(nodes: dict[str, dict], edges: list | None = None) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for name, attrs in nodes.items():
+ attrs = dict(attrs)
+ sym_list = attrs.pop("symbols", [])
+ g.add_node(name, **attrs)
+ for sym in sym_list:
+ sym_id = f"{name}::{sym['name']}"
+ g.add_node(sym_id, node_type="symbol", file_path=name, **sym)
+ g.add_edge(name, sym_id, edge_type="defines")
+ for edge in edges or []:
+ if len(edge) == 3:
+ g.add_edge(edge[0], edge[1], **(edge[2]))
+ else:
+ g.add_edge(edge[0], edge[1])
+ return g
+
+
+def _java_file(**overrides: object) -> dict:
+ base = {
+ "language": "java",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ }
+ base.update(overrides)
+ return base
+
+
+def _kt_file(**overrides: object) -> dict:
+ base = {
+ "language": "kotlin",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ }
+ base.update(overrides)
+ return base
+
+
+# ---------------------------------------------------------------------------
+# is_jvm_file_reachable
+# ---------------------------------------------------------------------------
+
+
+class TestJvmFileReachable:
+ def test_in_degree_positive_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "pkg/A.java": _java_file(),
+ "pkg/B.java": _java_file(),
+ },
+ edges=[("pkg/B.java", "pkg/A.java", {"edge_type": "imports"})],
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("pkg/A.java", graph, pkgs) is True
+
+ def test_sibling_with_importer_rescues(self) -> None:
+ graph = _build_graph(
+ {
+ "app/svc/User.java": _java_file(),
+ "app/svc/Helper.java": _java_file(),
+ "app/web/Controller.java": _java_file(),
+ },
+ edges=[
+ ("app/web/Controller.java", "app/svc/User.java", {"edge_type": "imports"}),
+ ],
+ )
+ pkgs = build_jvm_package_files(graph)
+ # Helper.java has no direct importer but its sibling User.java does.
+ assert is_jvm_file_reachable("app/svc/Helper.java", graph, pkgs) is True
+
+ def test_stereotype_annotated_class_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "app/svc/UserService.java": _java_file(
+ symbols=[{
+ "name": "UserService",
+ "kind": "class",
+ "visibility": "public",
+ "decorators": ["@Service"],
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("app/svc/UserService.java", graph, pkgs) is True
+
+ def test_spring_boot_application_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "app/App.java": _java_file(
+ symbols=[{
+ "name": "App",
+ "kind": "class",
+ "visibility": "public",
+ "decorators": ["@SpringBootApplication"],
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("app/App.java", graph, pkgs) is True
+
+ def test_main_method_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "app/Launcher.java": _java_file(
+ symbols=[{
+ "name": "main",
+ "kind": "method",
+ "visibility": "public",
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("app/Launcher.java", graph, pkgs) is True
+
+ def test_fqn_qualified_annotation_recognised(self) -> None:
+ graph = _build_graph(
+ {
+ "app/User.java": _java_file(
+ symbols=[{
+ "name": "User",
+ "kind": "class",
+ "visibility": "public",
+ "decorators": ["@jakarta.persistence.Entity"],
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("app/User.java", graph, pkgs) is True
+
+ def test_orphan_non_annotated_class_is_unreachable(self) -> None:
+ graph = _build_graph(
+ {
+ "lib/Dead.java": _java_file(
+ symbols=[{
+ "name": "Dead",
+ "kind": "class",
+ "visibility": "public",
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("lib/Dead.java", graph, pkgs) is False
+
+ def test_kotlin_object_with_companion_main_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "app/Main.kt": _kt_file(
+ symbols=[{
+ "name": "main",
+ "kind": "function",
+ "visibility": "public",
+ "language": "kotlin",
+ }],
+ ),
+ },
+ )
+ pkgs = build_jvm_package_files(graph)
+ assert is_jvm_file_reachable("app/Main.kt", graph, pkgs) is True
+
+
+# ---------------------------------------------------------------------------
+# Never-flag patterns
+# ---------------------------------------------------------------------------
+
+
+def _matches_any(path: str) -> bool:
+ return any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+
+class TestJvmNeverFlag:
+ def test_module_info_never_flagged(self) -> None:
+ assert _matches_any("app/src/main/java/module-info.java")
+ assert _matches_any("module-info.java")
+
+ def test_package_info_never_flagged(self) -> None:
+ assert _matches_any("lib/src/main/java/com/example/package-info.java")
+
+ def test_caffeine_test_source_sets_never_flagged(self) -> None:
+ # These exact paths surface as false positives in the baseline.
+ assert _matches_any(
+ "caffeine/src/apacheTest/java/com/foo/CacheTest.java"
+ )
+ assert _matches_any(
+ "caffeine/src/eclipseTest/java/com/foo/SuiteTest.java"
+ )
+ assert _matches_any(
+ "caffeine/src/frayTest/java/com/foo/SomeFrayTest.java"
+ )
+
+ def test_integration_test_source_set(self) -> None:
+ assert _matches_any("module/src/integrationTest/java/com/foo/IT.java")
+ assert _matches_any("module/src/it/java/com/foo/IT.java")
+
+ def test_test_suffix_files(self) -> None:
+ assert _matches_any("UserServiceTest.java")
+ assert _matches_any("PluginIT.java")
+ assert _matches_any("WidgetSpec.kt")
+
+ def test_generated_roots_never_flagged(self) -> None:
+ assert _matches_any("module/build/generated/foo/Bar.java")
+ assert _matches_any(
+ "module/build/generated/source/kapt/main/com/foo/Generated.java"
+ )
+ assert _matches_any("module/target/generated-sources/Q_User.java")
+
+ def test_ordinary_main_source_not_flagged(self) -> None:
+ # Don't accidentally never-flag normal main source.
+ assert not _matches_any("module/src/main/java/com/foo/Helper.java")
+ assert not _matches_any("module/src/main/kotlin/com/foo/Helper.kt")
+
+
+# ---------------------------------------------------------------------------
+# Contract methods
+# ---------------------------------------------------------------------------
+
+
+class TestJvmContractMethods:
+ def test_equals_hashcode_protected(self) -> None:
+ assert is_contract_method("equals", "method", "java")
+ assert is_contract_method("hashCode", "method", "java")
+ assert is_contract_method("toString", "method", "java")
+
+ def test_serialization_protected(self) -> None:
+ for n in ("readObject", "writeObject", "readResolve", "writeReplace"):
+ assert is_contract_method(n, "method", "java")
+
+ def test_kotlin_data_class_synthesised_protected(self) -> None:
+ assert is_contract_method("component1", "method", "kotlin")
+ assert is_contract_method("component12", "method", "kotlin")
+ assert is_contract_method("copy", "method", "kotlin")
+
+ def test_enum_helpers_protected(self) -> None:
+ assert is_contract_method("values", "method", "java")
+ assert is_contract_method("valueOf", "method", "java")
+
+ def test_unrelated_language_not_protected(self) -> None:
+ assert not is_contract_method("equals", "method", "python")
+
+
+# ---------------------------------------------------------------------------
+# Framework decorators recognised
+# ---------------------------------------------------------------------------
+
+
+class TestJvmFrameworkDecorators:
+ def test_spring_stereotypes_present(self) -> None:
+ for d in ("Component", "Service", "Repository", "RestController",
+ "SpringBootApplication", "Configuration"):
+ assert d in _FRAMEWORK_DECORATORS
+
+ def test_routing_annotations_present(self) -> None:
+ for d in ("GetMapping", "PostMapping", "RequestMapping",
+ "MessageMapping", "ExceptionHandler"):
+ assert d in _FRAMEWORK_DECORATORS
+
+ def test_test_markers_present(self) -> None:
+ for d in ("Test", "ParameterizedTest", "BeforeEach", "AfterAll"):
+ assert d in _FRAMEWORK_DECORATORS
+
+ def test_lifecycle_and_messaging_present(self) -> None:
+ for d in ("PostConstruct", "PreDestroy", "EventListener",
+ "Scheduled", "KafkaListener"):
+ assert d in _FRAMEWORK_DECORATORS
+
+
+# ---------------------------------------------------------------------------
+# End-to-end via DeadCodeAnalyzer
+# ---------------------------------------------------------------------------
+
+
+class TestJvmEndToEnd:
+ def test_service_annotated_class_not_flagged_unreachable(self) -> None:
+ graph = _build_graph(
+ {
+ "app/svc/UserService.java": _java_file(
+ symbols=[{
+ "name": "UserService",
+ "kind": "class",
+ "visibility": "public",
+ "decorators": ["@Service"],
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({"detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False})
+ kinds = [f.kind for f in report.findings]
+ assert DeadCodeKind.UNREACHABLE_FILE not in kinds
+
+ def test_module_info_not_flagged(self) -> None:
+ graph = _build_graph(
+ {
+ "lib/src/main/java/module-info.java": _java_file(),
+ },
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({"detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False})
+ kinds = [f.kind for f in report.findings]
+ assert DeadCodeKind.UNREACHABLE_FILE not in kinds
+
+ def test_private_post_construct_method_not_flagged_internal(self) -> None:
+ # A private @PostConstruct method has no caller in source, but the
+ # container invokes it. Should NOT be flagged unused_internal.
+ graph = _build_graph(
+ {
+ "app/svc/UserService.java": _java_file(
+ symbols=[{
+ "name": "init",
+ "kind": "method",
+ "visibility": "private",
+ "decorators": ["@PostConstruct"],
+ "language": "java",
+ }],
+ ),
+ },
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({"detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "detect_unreachable_files": False,
+ "detect_unused_internals": True})
+ # The init method should not surface as unused_internal.
+ kinds = [(f.kind, f.symbol_name) for f in report.findings]
+ assert (DeadCodeKind.UNUSED_INTERNAL, "init") not in kinds