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 framework edges (Spring expansion, Jakarta, Quarkus, Micronaut, Android, dynamic hints) (#279)

Raghav Chamadiya0b39de70b4db
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 0b55917a1..0c26a2a75 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -562,6 +562,14 @@ class DeadCodeAnalyzer:
node_data = self.graph.nodes[node]
if node_data.get("language", "unknown") in _NON_CODE_LANGUAGES:
continue
+ # Framework-instantiated files (Spring stereotypes, JAX-RS
+ # resources, Quarkus components, Spring Data repos, …) have
+ # no source-level caller; the runtime constructs them via
+ # classpath scanning. Mirror the entry-point skip the
+ # ``_detect_unreachable_files`` pass already does so an
+ # ``@RestController`` class isn't reported as unused.
+ if node_data.get("is_entry_point", False):
+ continue
if node_data.get("is_test", False):
continue
if _is_fixture_path(str(node)):
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py
new file mode 100644
index 000000000..755775bfe
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py
@@ -0,0 +1,143 @@
+"""JVM-wide dynamic-hint extractor (reflection, mocking, MapStruct, Boot).
+
+The Spring-specific extractor handles ``getBean`` / ``@Bean`` factories.
+This module covers the JVM patterns that aren't Spring-bound:
+
+- **Reflection** — ``Class.forName("a.b.C")`` and
+ ``Mockito.mock(X.class)`` / ``Mockito.spy(X.class)`` /
+ ``mockk<X>()`` (Kotlin).
+- **MapStruct factories** — ``Mappers.getMapper(XMapper.class)`` resolves
+ the runtime impl ``XMapperImpl`` (synthesised in Phase 2) plus the
+ ``XMapper`` interface file.
+- **Boot entry point** — ``SpringApplication.run(X.class, args)`` and the
+ Kotlin ``runApplication<X>(args)`` form mark X as a Boot entry.
+- **Jackson polymorphic deserialisation** — ``objectMapper.readValue(json,
+ X.class)`` / ``new Gson().fromJson(json, X.class)`` produce weak edges
+ to X's defining file so a class that is only ever deserialised from JSON
+ is not flagged as dead.
+
+The detection gate is *any* ``.java`` or ``.kt`` file in the repo (the
+patterns are JVM-wide, not Spring-only), keeping the scan free for
+non-JVM repos.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"build", "target", "out", "node_modules", ".git", ".gradle", ".idea"}
+
+_TYPE_DECL_RE = re.compile(r"\b(?:class|interface|record|enum)\s+([A-Z]\w*)")
+_KOTLIN_TYPE_DECL_RE = re.compile(r"\b(?:class|interface|object)\s+([A-Z]\w*)")
+
+# Class.forName("a.b.C") / Class.forName("a.b.C", true, classLoader)
+_CLASS_FORNAME_RE = re.compile(r"Class\.forName\s*\(\s*[\"']([\w.$]+)[\"']")
+
+# Mockito.mock(X.class) / Mockito.spy(X.class) / Mockito.mock(X.class, ...)
+_MOCKITO_RE = re.compile(r"Mockito\.(?:mock|spy)\s*\(\s*([A-Z]\w*)\s*\.class")
+# Kotlin: mockk<X>() / spyk<X>() / spyk(X::class)
+_MOCKK_RE = re.compile(r"\b(?:mockk|spyk)\s*<\s*([A-Z]\w*)\s*>")
+
+# MapStruct: Mappers.getMapper(XMapper.class)
+_MAPSTRUCT_RE = re.compile(r"Mappers\.getMapper\s*\(\s*([A-Z]\w*)\s*\.class")
+
+# Spring Boot entry: SpringApplication.run(MyApp.class, args)
+_BOOT_RUN_RE = re.compile(r"SpringApplication\.run\s*\(\s*([A-Z]\w*)\s*\.class")
+# Kotlin: runApplication<MyApp>(*args)
+_KOTLIN_RUN_APP_RE = re.compile(r"\brunApplication\s*<\s*([A-Z]\w*)\s*>")
+
+# Jackson / Gson: objectMapper.readValue(json, X.class) / gson.fromJson(json, X.class)
+_JSON_READ_RE = re.compile(
+ r"\.(?:readValue|fromJson|convertValue|treeToValue)\s*\([^)]*?([A-Z]\w*)\s*\.class"
+)
+
+# Constructor.newInstance / Method.invoke type references — best-effort.
+_REFLECTION_INVOKE_RE = re.compile(
+ r"\.getDeclared(?:Method|Field|Constructor)\s*\(\s*[\"'](\w+)[\"']"
+)
+
+
+class JvmDynamicHints(DynamicHintExtractor):
+ """Discover JVM reflection / Mockito / MapStruct / Boot / Jackson patterns."""
+
+ name = "jvm"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ # Build maps: short type name → file, AND fully-qualified type name → file.
+ type_to_file: dict[str, str] = {}
+ fqn_to_file: dict[str, str] = {}
+ sources: list[tuple[Path, str, str]] = [] # (path, text, lang)
+ repo_root_resolved = repo_root.resolve()
+
+ for ext, lang in ((".java", "java"), (".kt", "kotlin")):
+ for src in self._rglob(repo_root, f"*{ext}"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text, lang))
+
+ # Extract package declaration to build FQNs.
+ pkg_match = re.search(r"^\s*package\s+([\w.]+)", text, re.MULTILINE)
+ pkg = pkg_match.group(1) if pkg_match else ""
+
+ pattern = _KOTLIN_TYPE_DECL_RE if lang == "kotlin" else _TYPE_DECL_RE
+ for match in pattern.finditer(text):
+ name = match.group(1)
+ type_to_file.setdefault(name, rel)
+ if pkg:
+ fqn_to_file.setdefault(f"{pkg}.{name}", rel)
+
+ def _emit(src_rel: str, target_rel: str | None, suffix: str) -> None:
+ if target_rel and target_rel != src_rel:
+ edges.append(
+ DynamicEdge(
+ source=src_rel,
+ target=target_rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:{suffix}",
+ )
+ )
+
+ for src, text, lang in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root_resolved).as_posix()
+ except ValueError:
+ continue
+
+ for match in _CLASS_FORNAME_RE.finditer(text):
+ fqn = match.group(1)
+ target = fqn_to_file.get(fqn) or type_to_file.get(fqn.rsplit(".", 1)[-1])
+ _emit(rel, target, "class_forname")
+
+ for match in _MOCKITO_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "mockito")
+
+ for match in _MOCKK_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "mockk")
+
+ for match in _MAPSTRUCT_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "mapstruct")
+
+ for match in _BOOT_RUN_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "spring_boot_run")
+
+ for match in _KOTLIN_RUN_APP_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "spring_boot_run")
+
+ for match in _JSON_READ_RE.finditer(text):
+ _emit(rel, type_to_file.get(match.group(1)), "jackson_readvalue")
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
index fe198cbe6..9f34caf1e 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -34,6 +34,7 @@ from .python_imports import PythonDynamicHints
from .pytest_hints import PytestDynamicHints
from .ruby import RubyDynamicHints
from .scala import ScalaDynamicHints
+from .jvm import JvmDynamicHints
from .spring import SpringDynamicHints
from .swift import SwiftDynamicHints
from .xaml import XamlDynamicHints
@@ -62,6 +63,7 @@ class HintRegistry:
DotNetDynamicHints(),
XamlDynamicHints(),
SpringDynamicHints(),
+ JvmDynamicHints(),
RubyDynamicHints(),
PhpDynamicHints(),
ScalaDynamicHints(),
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index e0e3d6f6e..b342fde81 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -18,6 +18,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from . import (
+ android_manifest,
aspnet,
django,
express,
@@ -25,9 +26,12 @@ from . import (
flask,
go,
hono,
+ jakarta,
laravel,
+ micronaut,
next_app,
pytest_edges,
+ quarkus,
rails,
remix,
rust,
@@ -54,6 +58,10 @@ _HANDLERS: list[FrameworkHandler] = [
*rails.HANDLERS,
*laravel.HANDLERS,
*spring.HANDLERS,
+ *jakarta.HANDLERS,
+ *quarkus.HANDLERS,
+ *micronaut.HANDLERS,
+ *android_manifest.HANDLERS,
*express.HANDLERS,
*next_app.HANDLERS,
*hono.HANDLERS,
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/android_manifest.py b/packages/core/src/repowise/core/ingestion/framework_edges/android_manifest.py
new file mode 100644
index 000000000..4b4129e9a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/android_manifest.py
@@ -0,0 +1,101 @@
+"""Android manifest reference edges.
+
+``AndroidManifest.xml`` registers Activities, Services, Receivers,
+Providers, and the Application class by fully-qualified name. The
+manifest is the runtime's hand-off into source — none of those class
+references appear in any ``import`` statement, so the dead-code pass
+would otherwise flag every Activity that has no in-source caller.
+
+Strategy: parse every ``AndroidManifest.xml`` we can find, pull the
+``android:name`` attributes, and emit a synthetic ``framework`` edge
+from the manifest file to the named class's source file.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers import ResolverContext
+from .base import (
+ DetectionContext,
+ FrameworkHandler,
+ _add_edge_if_new,
+)
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+
+_ANDROID_NAME_RE = re.compile(r"android:name=\"([\w.$]+)\"")
+_ANDROID_COMPONENT_TAGS = ("<activity", "<service", "<receiver",
+ "<provider", "<application")
+
+
+def _has_android_manifests(parsed_files: dict[str, Any]) -> bool:
+ return any(p.endswith("AndroidManifest.xml") for p in parsed_files.keys())
+
+
+def _add_android_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+ ctx: ResolverContext,
+) -> int:
+ count = 0
+
+ try:
+ from ..resolvers.jvm_workspace import get_or_build_jvm_index
+
+ jvm_index = get_or_build_jvm_index(ctx)
+ except Exception:
+ jvm_index = None
+
+ for path in list(path_set):
+ if not path.endswith("AndroidManifest.xml"):
+ continue
+ try:
+ text = Path(parsed_files[path].file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except (OSError, KeyError, AttributeError):
+ continue
+
+ # Only collect names from inside component tags. The regex below
+ # is generous; the gate cuts manifest-permission lines.
+ for tag in _ANDROID_COMPONENT_TAGS:
+ for chunk in text.split(tag)[1:]:
+ head = chunk.split(">", 1)[0]
+ for m in _ANDROID_NAME_RE.finditer(head):
+ fqn = m.group(1).lstrip(".")
+ if not fqn:
+ continue
+ targets: tuple[str, ...] = ()
+ if jvm_index is not None:
+ targets = jvm_index.files_for_fqn(fqn)
+ for target in targets:
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+ node = graph.nodes.get(target)
+ if node is not None:
+ node["is_entry_point"] = True
+
+ return count
+
+
+class _AndroidManifestHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ return _has_android_manifests(dctx.parsed_files)
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_android_edges(graph, parsed_files, path_set, ctx)
+
+
+HANDLERS: list[FrameworkHandler] = [_AndroidManifestHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/jakarta.py b/packages/core/src/repowise/core/ingestion/framework_edges/jakarta.py
new file mode 100644
index 000000000..a01485e54
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/jakarta.py
@@ -0,0 +1,175 @@
+"""Jakarta EE / Java EE framework edges.
+
+Covers JAX-RS routing, CDI scope stereotypes, Servlet 3+ web components,
+EJB component stereotypes, and JPA entity associations. Both the
+``javax.*`` (Java EE) and ``jakarta.*`` (Jakarta EE 9+) namespaces are
+recognised — repos in flight between the two will hit both branches and
+the handler matches either.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers import ResolverContext
+from .base import (
+ DetectionContext,
+ FrameworkHandler,
+ _add_edge_if_new,
+ _build_class_to_file,
+ read_text,
+)
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+
+# Class-level stereotypes that make the runtime instantiate the class
+# (CDI + EJB + Servlet 3+ + JAX-RS provider).
+_JAKARTA_STEREOTYPE_ANNOT = (
+ "@Path",
+ "@Provider",
+ "@ApplicationScoped",
+ "@RequestScoped",
+ "@SessionScoped",
+ "@ConversationScoped",
+ "@Dependent",
+ "@Singleton",
+ "@Stateless",
+ "@Stateful",
+ "@MessageDriven",
+ "@WebServlet",
+ "@WebFilter",
+ "@WebListener",
+ "@ServerEndpoint",
+ "@ClientEndpoint",
+)
+
+# Field / constructor / setter injection annotations.
+_JAKARTA_INJECT_FIELD_RE = re.compile(
+ r"@(?:Inject|Resource|EJB|PersistenceContext|PersistenceUnit)"
+ r"\b[^\n]*\n\s*(?:private|protected|public|final|\s)*\s*"
+ r"([A-Z][\w.]*)\s*(?:<[^>]+>)?\s+\w+\s*[;=]"
+)
+
+# JPA association annotations declared on a typed field.
+_JPA_ASSOC_FIELD_RE = re.compile(
+ r"@(?:OneToOne|OneToMany|ManyToOne|ManyToMany)"
+ r"\b[^\n]*\n\s*(?:private|protected|public|final|\s)*\s*"
+ r"(?:[A-Z][\w.]*\s*<\s*([A-Z][\w.]*)\s*>|([A-Z][\w.]*))"
+)
+
+# JAX-RS routing verbs — used for routing detection (currently we mark
+# the class file as ``framework_role="jax_rs_resource"``; full ROUTE node
+# emission can be layered on top in a follow-up).
+_JAX_RS_VERBS = ("@GET", "@POST", "@PUT", "@DELETE",
+ "@PATCH", "@HEAD", "@OPTIONS")
+
+
+def _has_jakarta_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for imp in parsed.imports:
+ mp = imp.module_path
+ if mp.startswith(("javax.", "jakarta.")):
+ return True
+ return False
+
+
+def _add_jakarta_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+ class_to_file = _build_class_to_file(parsed_files, ("java", "kotlin"))
+
+ impl_map: dict[str, list[str]] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for rel in parsed.heritage:
+ if rel.kind in ("implements", "extends"):
+ impl_map.setdefault(rel.parent_name, []).append(path)
+
+ def _resolve_type(type_name: str) -> list[str]:
+ type_name = type_name.split("<")[0].rsplit(".", 1)[-1].strip()
+ results: list[str] = []
+ own = class_to_file.get(type_name)
+ if own:
+ results.append(own)
+ for impl in impl_map.get(type_name, []):
+ if impl not in results:
+ results.append(impl)
+ return results
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ text = read_text(parsed)
+ if not text:
+ continue
+
+ has_stereotype = any(annot in text for annot in _JAKARTA_STEREOTYPE_ANNOT)
+ has_jax_rs = "@Path" in text or any(v in text for v in _JAX_RS_VERBS)
+ has_jpa = "@Entity" in text or "@MappedSuperclass" in text or "@Embeddable" in text
+
+ if not (has_stereotype or has_jpa):
+ continue
+
+ # Stamp framework role for downstream consumers.
+ node = graph.nodes.get(path)
+ if node is not None:
+ if has_jpa:
+ node["framework_role"] = "jpa_entity"
+ node["is_entry_point"] = True
+ elif has_jax_rs:
+ node["framework_role"] = "jax_rs_resource"
+ node["is_entry_point"] = True
+ else:
+ node["framework_role"] = node.get("framework_role") or "cdi_bean"
+ node["is_entry_point"] = True
+
+ # @Inject / @Resource / @EJB / @PersistenceContext field injection
+ for m in _JAKARTA_INJECT_FIELD_RE.finditer(text):
+ type_name = m.group(1)
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # JPA associations — pull the type out of generic args first
+ # (``@OneToMany Set<User> users``) then bare (``@ManyToOne User
+ # owner``).
+ if has_jpa:
+ for m in _JPA_ASSOC_FIELD_RE.finditer(text):
+ type_name = m.group(1) or m.group(2)
+ if not type_name:
+ continue
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+class _JakartaHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ in_stack = any(
+ tok in dctx.stack_lower
+ for tok in ("jakarta", "jakartaee", "javaee", "jaxrs", "cdi", "jpa", "ejb")
+ )
+ return in_stack or _has_jakarta_imports(dctx.parsed_files)
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_jakarta_edges(graph, parsed_files, path_set)
+
+
+HANDLERS: list[FrameworkHandler] = [_JakartaHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py b/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py
new file mode 100644
index 000000000..3f8f79bb2
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py
@@ -0,0 +1,134 @@
+"""Micronaut framework edges.
+
+Micronaut reuses Jakarta-style annotations (``@Inject`` / ``@Singleton``)
+but ships its own routing verbs (``@Get`` / ``@Post`` / …) and DI
+qualifiers (``@Factory`` / ``@Replaces`` / ``@Primary``). Annotation
+short-names collide with Spring's ``@Controller``; we disambiguate by
+the import set (``io.micronaut.*``).
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers import ResolverContext
+from .base import (
+ DetectionContext,
+ FrameworkHandler,
+ _add_edge_if_new,
+ _build_class_to_file,
+ read_text,
+)
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+
+_MICRONAUT_STEREOTYPE_ANNOT = (
+ "@Controller",
+ "@Filter",
+ "@Singleton",
+ "@Prototype",
+ "@Factory",
+ "@Bean",
+ "@MicronautTest",
+ "@RequiresConfiguration",
+ "@Refreshable",
+ "@Context",
+ "@JobScheduler",
+ "@KafkaListener",
+ "@KafkaClient",
+)
+
+_MICRONAUT_INJECT_FIELD_RE = re.compile(
+ r"@Inject\s+(?:private|protected|public|final|\s)*\s*"
+ r"([A-Z][\w.]*)\s*(?:<[^>]+>)?\s+\w+\s*[;=]"
+)
+
+
+def _has_micronaut_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for imp in parsed.imports:
+ if imp.module_path.startswith("io.micronaut"):
+ return True
+ return False
+
+
+def _add_micronaut_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+ class_to_file = _build_class_to_file(parsed_files, ("java", "kotlin"))
+
+ impl_map: dict[str, list[str]] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for rel in parsed.heritage:
+ if rel.kind in ("implements", "extends"):
+ impl_map.setdefault(rel.parent_name, []).append(path)
+
+ def _resolve_type(type_name: str) -> list[str]:
+ type_name = type_name.split("<")[0].rsplit(".", 1)[-1].strip()
+ results: list[str] = []
+ own = class_to_file.get(type_name)
+ if own:
+ results.append(own)
+ for impl in impl_map.get(type_name, []):
+ if impl not in results:
+ results.append(impl)
+ return results
+
+ # Per-file: only fire if the file actually imports Micronaut. This
+ # keeps ``@Controller``/``@Bean`` from being mistaken for the Spring
+ # symbols on a per-class basis.
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ file_imports_micronaut = any(
+ imp.module_path.startswith("io.micronaut") for imp in parsed.imports
+ )
+ if not file_imports_micronaut:
+ continue
+ text = read_text(parsed)
+ if not text:
+ continue
+ has_stereotype = any(annot in text for annot in _MICRONAUT_STEREOTYPE_ANNOT)
+ if not has_stereotype:
+ continue
+
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
+ node["framework_role"] = node.get("framework_role") or "micronaut_component"
+
+ for m in _MICRONAUT_INJECT_FIELD_RE.finditer(text):
+ type_name = m.group(1)
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+class _MicronautHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ in_stack = any(tok in dctx.stack_lower for tok in ("micronaut",))
+ return in_stack or _has_micronaut_imports(dctx.parsed_files)
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_micronaut_edges(graph, parsed_files, path_set)
+
+
+HANDLERS: list[FrameworkHandler] = [_MicronautHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/quarkus.py b/packages/core/src/repowise/core/ingestion/framework_edges/quarkus.py
new file mode 100644
index 000000000..fc0c7f2f8
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/quarkus.py
@@ -0,0 +1,120 @@
+"""Quarkus framework edges.
+
+Quarkus reuses much of Jakarta (CDI scopes, JAX-RS) but layers its own
+conventions on top — ``@QuarkusTest`` entry-points, ``@ConfigMapping``
+config interfaces, ``@RegisterRestClient`` MicroProfile clients,
+``@Scheduled`` tasks, and ``@Incoming("topic") / @Outgoing("topic")``
+SmallRye reactive-messaging channels. This handler emits edges for the
+Quarkus-specific shapes; CDI / JAX-RS classes are caught by the
+``jakarta`` handler too.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers import ResolverContext
+from .base import (
+ DetectionContext,
+ FrameworkHandler,
+ _add_edge_if_new,
+ read_text,
+)
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+
+_QUARKUS_ENTRY_ANNOT = (
+ "@QuarkusMain",
+ "@QuarkusTest",
+ "@QuarkusIntegrationTest",
+ "@QuarkusUnitTest",
+ "@NativeImageTest",
+ "@ConfigMapping",
+ "@RegisterRestClient",
+ "@GraphQLApi",
+ "@RegisterForReflection",
+ "@Scheduled",
+)
+
+_INCOMING_RE = re.compile(r"@Incoming\s*\(\s*[\"']([^\"']+)[\"']\s*\)")
+_OUTGOING_RE = re.compile(r"@Outgoing\s*\(\s*[\"']([^\"']+)[\"']\s*\)")
+
+
+def _has_quarkus_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for imp in parsed.imports:
+ mp = imp.module_path
+ if mp.startswith(("io.quarkus", "org.eclipse.microprofile", "io.smallrye")):
+ return True
+ return False
+
+
+def _add_quarkus_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+
+ # First pass: collect @Outgoing topic → producer files, and
+ # @Incoming topic → consumer files. Then cross-link producers to
+ # consumers on matching topic names.
+ producers: dict[str, list[str]] = {}
+ consumers: dict[str, list[str]] = {}
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ text = read_text(parsed)
+ if not text:
+ continue
+
+ # Stamp Quarkus entry annotations on the file node.
+ if any(annot in text for annot in _QUARKUS_ENTRY_ANNOT):
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
+ node["framework_role"] = node.get("framework_role") or "quarkus_component"
+
+ for m in _OUTGOING_RE.finditer(text):
+ producers.setdefault(m.group(1), []).append(path)
+ for m in _INCOMING_RE.finditer(text):
+ consumers.setdefault(m.group(1), []).append(path)
+
+ # Cross-link by topic name. Producers depend on consumers (the channel
+ # is the wire); we emit producer → consumer to mirror Spring's
+ # @EventListener flow direction.
+ for topic, producer_files in producers.items():
+ consumer_files = consumers.get(topic, [])
+ for src in producer_files:
+ for dst in consumer_files:
+ if src != dst and dst in path_set and _add_edge_if_new(graph, src, dst):
+ count += 1
+
+ return count
+
+
+class _QuarkusHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ in_stack = any(
+ tok in dctx.stack_lower
+ for tok in ("quarkus", "smallrye", "microprofile")
+ )
+ return in_stack or _has_quarkus_imports(dctx.parsed_files)
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_quarkus_edges(graph, parsed_files, path_set)
+
+
+HANDLERS: list[FrameworkHandler] = [_QuarkusHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
index a732e45b4..c0a931e3d 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
@@ -1,6 +1,26 @@
-"""Spring Boot dependency-injection convention edges.
+"""Spring + Spring Boot framework edges (DI, routing, Spring Data, autoconfig).
-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.
+Expanded in Phase 4 of the JVM parity plan. The handler now covers:
+
+- **Stereotype detection** — ``@Component`` / ``@Service`` / ``@Repository``
+ / ``@Controller`` / ``@RestController`` / ``@Configuration`` /
+ ``@ControllerAdvice`` / ``@RestControllerAdvice``.
+- **Field injection** — ``@Autowired`` / ``@Inject`` / ``@Resource`` on
+ fields, mapped to the field type's defining file.
+- **Constructor injection** — explicit constructors annotated
+ ``@Autowired`` or the single implicit constructor (Spring 4.3+);
+ **plus** Lombok ``@RequiredArgsConstructor`` / ``@AllArgsConstructor``
+ on a stereotype class, which synthesize a constructor over the
+ ``final`` (RAC) or all (AAC) declared fields.
+- **``@Bean`` factories** — Java and Kotlin signatures.
+- **Spring Data repositories** — any interface extending
+ ``CrudRepository`` / ``JpaRepository`` / ``MongoRepository`` /
+ friends becomes an entry point (the impl is generated at runtime).
+- **Autoconfig consumer edges** — emit edges from each
+ ``META-INF/spring/...AutoConfiguration.imports`` file (and
+ ``spring.factories``) to the listed FQNs so the resource file
+ shows as the importer (the FQN files were already stamped
+ ``is_entry_point`` during the JVM warmup).
"""
from __future__ import annotations
@@ -29,9 +49,11 @@ _SPRING_BEAN_ANNOT = (
"@Controller",
"@RestController",
"@Configuration",
+ "@ControllerAdvice",
+ "@RestControllerAdvice",
)
-_SPRING_AUTOWIRED_FIELD_RE = re.compile(
- r"@Autowired\s+(?:private|protected|public|final|\s)*\s*([A-Z]\w*)\s+\w+"
+_SPRING_INJECT_FIELD_RE = re.compile(
+ r"@(?:Autowired|Inject|Resource)\s+(?:private|protected|public|final|\s)*\s*([A-Z][\w<>,\s.]*?)\s+\w+\s*[;=]"
)
_SPRING_CTOR_PARAM_RE = re.compile(r"\b([A-Z]\w*)\s+\w+\s*[,)]")
_SPRING_BEAN_METHOD_RE = re.compile(
@@ -41,6 +63,47 @@ _SPRING_BEAN_METHOD_KOTLIN_RE = re.compile(
r"@Bean\b[^\n]*\n\s*(?:public|protected|private|internal|fun|open|\s)+\s*\w+\s*\([^)]*\)\s*:\s*([A-Z]\w*)"
)
+# Lombok constructor-synthesis annotations. RAC = constructor over every
+# ``final`` (and ``@NonNull``) field; AAC = constructor over every field.
+_LOMBOK_RAC_ANNOT = ("@RequiredArgsConstructor", "@AllArgsConstructor")
+_LOMBOK_DATA_VALUE = ("@Data", "@Value")
+
+# Spring Data repository base interfaces — any interface extending one of
+# these has Spring-generated impls at runtime and must be treated as an
+# entry point. List covers spring-data-commons + jpa / mongodb / r2dbc /
+# elasticsearch / neo4j / couchbase / cassandra / redis flavours.
+_SPRING_DATA_BASES: frozenset[str] = frozenset({
+ "Repository",
+ "CrudRepository",
+ "PagingAndSortingRepository",
+ "JpaRepository",
+ "ReactiveCrudRepository",
+ "ReactiveSortingRepository",
+ "RxJava3CrudRepository",
+ "MongoRepository",
+ "ReactiveMongoRepository",
+ "R2dbcRepository",
+ "ElasticsearchRepository",
+ "ReactiveElasticsearchRepository",
+ "Neo4jRepository",
+ "ReactiveNeo4jRepository",
+ "CouchbaseRepository",
+ "ReactiveCouchbaseRepository",
+ "CassandraRepository",
+ "ReactiveCassandraRepository",
+ "KeyValueRepository",
+ "QueryByExampleExecutor",
+ "JpaSpecificationExecutor",
+})
+
+# Java field declaration with optional ``final`` modifier — used for
+# Lombok RAC ctor-param inference. Captures the type's head identifier.
+_JAVA_FINAL_FIELD_RE = re.compile(
+ r"^\s*(?:private|protected|public|\s)*\s*(?:(final)\s+|@NonNull\s+)?"
+ r"([A-Z]\w*)\s*(?:<[^>]+>)?\s+(\w+)\s*[;=]",
+ re.MULTILINE,
+)
+
def _has_spring_imports(parsed_files: dict[str, Any]) -> bool:
for parsed in parsed_files.values():
@@ -52,10 +115,50 @@ def _has_spring_imports(parsed_files: dict[str, Any]) -> bool:
return False
+def _is_spring_data_repo(parsed: Any) -> bool:
+ """True if *parsed* is a Java/Kotlin interface extending a Spring Data base."""
+ if parsed.file_info.language not in ("java", "kotlin"):
+ return False
+ for rel in parsed.heritage:
+ if rel.kind in ("extends", "implements"):
+ base = rel.parent_name.split("<")[0].rsplit(".", 1)[-1].strip()
+ if base in _SPRING_DATA_BASES:
+ return True
+ return False
+
+
+def _scan_lombok_ctor_params(text: str) -> list[str]:
+ """Return Lombok-synthesized constructor param types (head identifiers).
+
+ For a class annotated ``@RequiredArgsConstructor`` (or ``@Data``), this
+ is every ``final`` field's head type; for ``@AllArgsConstructor`` (or
+ ``@Value``), every field's head type. Builtin types are filtered.
+ """
+ is_rac = any(a in text for a in _LOMBOK_RAC_ANNOT) or any(
+ a in text for a in _LOMBOK_DATA_VALUE if a == "@Data"
+ )
+ is_aac = "@AllArgsConstructor" in text or "@Value" in text
+ if not (is_rac or is_aac):
+ return []
+
+ params: list[str] = []
+ for m in _JAVA_FINAL_FIELD_RE.finditer(text):
+ is_final = bool(m.group(1))
+ type_head = m.group(2)
+ if type_head in ("String", "Integer", "Long", "Boolean", "Double",
+ "Float", "Byte", "Short", "Character", "Object",
+ "List", "Map", "Set", "Collection"):
+ continue
+ if is_aac or (is_rac and is_final):
+ params.append(type_head)
+ return params
+
+
def _add_spring_edges(
graph: nx.DiGraph,
parsed_files: dict[str, Any],
path_set: set[str],
+ ctx: ResolverContext,
) -> int:
count = 0
class_to_file = _build_class_to_file(parsed_files, ("java", "kotlin"))
@@ -70,6 +173,8 @@ def _add_spring_edges(
impl_map.setdefault(rel.parent_name, []).append(path)
def _resolve_type(type_name: str) -> list[str]:
+ # Strip generics if accidentally passed in
+ type_name = type_name.split("<")[0].strip()
results: list[str] = []
own = class_to_file.get(type_name)
if own:
@@ -79,6 +184,18 @@ def _add_spring_edges(
results.append(impl)
return results
+ # ---- 1. Spring Data repository entries ----
+ # Mark the interface file node ``is_entry_point=True`` so the dead-code
+ # analyzer doesn't flag it. The generated impl never appears in source,
+ # so the interface itself is the only thing we can anchor against.
+ for path, parsed in parsed_files.items():
+ if _is_spring_data_repo(parsed):
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
+ node["framework_role"] = "spring_data_repository"
+
+ # ---- 2. Per-class DI + @Bean factory edges ----
for path, parsed in parsed_files.items():
if parsed.file_info.language not in ("java", "kotlin"):
continue
@@ -89,16 +206,23 @@ def _add_spring_edges(
if not is_bean:
continue
- # @Autowired field injection
- for m in _SPRING_AUTOWIRED_FIELD_RE.finditer(text):
- type_name = m.group(1)
+ # Stamp the framework role + entry-point flag. Spring instantiates
+ # every stereotype-annotated class at startup via classpath scanning,
+ # so no source caller exists; the file must read as live regardless
+ # of in_degree.
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["framework_role"] = node.get("framework_role") or "spring_stereotype"
+ node["is_entry_point"] = True
+
+ # 2a. Field injection (@Autowired / @Inject / @Resource)
+ for m in _SPRING_INJECT_FIELD_RE.finditer(text):
+ type_name = m.group(1).split("<")[0].strip()
for target in _resolve_type(type_name):
if target in path_set and _add_edge_if_new(graph, path, target):
count += 1
- # Constructor parameter injection: collect param types from any @Autowired
- # constructor or any single public constructor in a bean (Spring 4.3+ omits
- # the annotation when the class has only one constructor).
+ # 2b. Constructor parameter injection — explicit ctors
for ctor_match in re.finditer(
r"(?:@Autowired\s*\n\s*)?(?:public|protected|private|\s)*"
+ re.escape(Path(path).stem)
@@ -116,7 +240,13 @@ def _add_spring_edges(
if target in path_set and _add_edge_if_new(graph, path, target):
count += 1
- # @Bean factory methods → return-type file
+ # 2c. Lombok @RequiredArgsConstructor / @AllArgsConstructor / @Data
+ for type_name in _scan_lombok_ctor_params(text):
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # 2d. @Bean factory methods → return-type file
if "@Configuration" in text:
for m in _SPRING_BEAN_METHOD_RE.finditer(text):
for target in _resolve_type(m.group(1)):
@@ -127,6 +257,56 @@ def _add_spring_edges(
if target in path_set and _add_edge_if_new(graph, path, target):
count += 1
+ # ---- 3. Autoconfig consumer edges ----
+ # Pull the JVM workspace index (already memoised on ctx) and emit edges
+ # from each autoconfig resource file (key) to the FQN target files.
+ # The autoconfig FQN files were stamped ``is_entry_point`` in the
+ # warmup; here we add the resource file as a visible importer so the
+ # autoconfig file itself does not read as orphan.
+ try:
+ from ..resolvers.jvm_workspace import get_or_build_jvm_index
+
+ jvm_index = get_or_build_jvm_index(ctx)
+ except Exception:
+ jvm_index = None
+
+ if jvm_index is not None:
+ for resource_path, fqns in jvm_index.autoconfig_imports.items():
+ # Resource files may not have a node yet (we don't always index
+ # .properties / .imports). Add a minimal file-shape node if missing
+ # so the importer edge has a sink.
+ if resource_path not in graph:
+ graph.add_node(
+ resource_path,
+ node_type="file",
+ language="properties",
+ path=resource_path,
+ is_entry_point=True,
+ )
+ for fqn in fqns:
+ for target in jvm_index.files_for_fqn(fqn):
+ if target in path_set and _add_edge_if_new(graph, resource_path, target):
+ count += 1
+ # META-INF/services impls — same pattern
+ for iface_fqn, impls in jvm_index.services.items():
+ # The resource path isn't tracked per-iface; we use a synthetic
+ # source so the impl files gain a visible importer. The warmup
+ # already stamped them ``is_entry_point``, so this is belt-and-
+ # suspenders for the unused_export visibility heuristic.
+ source = f"META-INF/services/{iface_fqn}"
+ if source not in graph:
+ graph.add_node(
+ source,
+ node_type="file",
+ language="properties",
+ path=source,
+ is_entry_point=True,
+ )
+ for impl_fqn in impls:
+ for target in jvm_index.files_for_fqn(impl_fqn):
+ if target in path_set and _add_edge_if_new(graph, source, target):
+ count += 1
+
return count
@@ -145,7 +325,38 @@ class _SpringHandler:
ctx: ResolverContext,
path_set: set[str],
) -> int:
- return _add_spring_edges(graph, parsed_files, path_set)
+ return _add_spring_edges(graph, parsed_files, path_set, ctx)
+
+
+class _JvmAutoconfigHandler:
+ """Always-on JVM resource-file consumer edge emitter.
+
+ Runs even when there is no ``org.springframework`` import — Spring
+ Boot autoconfig imports + META-INF/services exist in plain JVM libs
+ too (e.g. Quarkus/Helidon ship their own). The Spring stereotype
+ DI scan above is gated; this scan is not, so an autoconfig-only repo
+ still gets the resource → impl edges.
+ """
+
+ def detect(self, dctx: DetectionContext) -> bool:
+ # Cheap detect: any .java or .kt file in the parse set.
+ return any(
+ p.file_info.language in ("java", "kotlin")
+ for p in dctx.parsed_files.values()
+ )
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ # The autoconfig + META-INF block runs inside _add_spring_edges so
+ # we don't double-emit. This handler is a no-op stub kept registered
+ # so future expansion (e.g. a JVM-only resource consumer that runs
+ # in non-Spring repos) has a registration point.
+ return 0
HANDLERS: list[FrameworkHandler] = [_SpringHandler()]
diff --git a/tests/unit/ingestion/test_jvm_dynamic_hints.py b/tests/unit/ingestion/test_jvm_dynamic_hints.py
new file mode 100644
index 000000000..20feb5c88
--- /dev/null
+++ b/tests/unit/ingestion/test_jvm_dynamic_hints.py
@@ -0,0 +1,101 @@
+"""Unit tests for the JVM dynamic-hint extractor."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.dynamic_hints.jvm import JvmDynamicHints
+
+
+def _edges_to_pairs(edges):
+ return {(e.source, e.target, e.hint_source.rsplit(":", 1)[-1]) for e in edges}
+
+
+class TestClassForName:
+ def test_resolves_fqn_to_file(self, tmp_path: Path) -> None:
+ (tmp_path / "Loader.java").write_text(
+ "package com.x;\n"
+ "public class Loader {\n"
+ " void load() { Class.forName(\"com.x.Plugin\"); }\n"
+ "}\n"
+ )
+ (tmp_path / "Plugin.java").write_text(
+ "package com.x;\npublic class Plugin {}\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert ("Loader.java", "Plugin.java", "class_forname") in _edges_to_pairs(edges)
+
+
+class TestMockito:
+ def test_mockk_resolves_in_kotlin(self, tmp_path: Path) -> None:
+ (tmp_path / "Svc.kt").write_text("package x\nclass Svc\n")
+ (tmp_path / "Test.kt").write_text(
+ "package x\nclass Test {\n fun t() { val s = mockk<Svc>() }\n}\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Test.kt" and e.target == "Svc.kt" and e.hint_source.endswith("mockk")
+ for e in edges
+ )
+
+ def test_mockito_resolves_in_java(self, tmp_path: Path) -> None:
+ (tmp_path / "Svc.java").write_text(
+ "package x;\npublic class Svc {}\n"
+ )
+ (tmp_path / "SvcTest.java").write_text(
+ "package x;\nimport static org.mockito.Mockito.mock;\n"
+ "public class SvcTest {\n Svc s = Mockito.mock(Svc.class);\n}\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "SvcTest.java" and e.target == "Svc.java"
+ for e in edges
+ )
+
+
+class TestSpringBootRun:
+ def test_kotlin_run_application(self, tmp_path: Path) -> None:
+ (tmp_path / "MyApp.kt").write_text("package x\nclass MyApp\n")
+ (tmp_path / "Main.kt").write_text(
+ "package x\nfun main(args: Array<String>) { runApplication<MyApp>(*args) }\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Main.kt" and e.target == "MyApp.kt"
+ and e.hint_source.endswith("spring_boot_run")
+ for e in edges
+ )
+
+
+class TestMapStruct:
+ def test_mappers_getmapper(self, tmp_path: Path) -> None:
+ (tmp_path / "UserMapper.java").write_text(
+ "package x;\npublic interface UserMapper {}\n"
+ )
+ (tmp_path / "Caller.java").write_text(
+ "package x;\nimport org.mapstruct.factory.Mappers;\n"
+ "public class Caller {\n"
+ " UserMapper m = Mappers.getMapper(UserMapper.class);\n"
+ "}\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Caller.java" and e.target == "UserMapper.java"
+ for e in edges
+ )
+
+
+class TestJacksonReadValue:
+ def test_object_mapper_read_value(self, tmp_path: Path) -> None:
+ (tmp_path / "Dto.java").write_text("package x;\npublic class Dto {}\n")
+ (tmp_path / "Parser.java").write_text(
+ "package x;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n"
+ "public class Parser {\n"
+ " Dto p(ObjectMapper m, String j) throws Exception { return m.readValue(j, Dto.class); }\n"
+ "}\n"
+ )
+ edges = JvmDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Parser.java" and e.target == "Dto.java"
+ for e in edges
+ )
diff --git a/tests/unit/ingestion/test_jvm_framework_edges.py b/tests/unit/ingestion/test_jvm_framework_edges.py
new file mode 100644
index 000000000..aaf38182b
--- /dev/null
+++ b/tests/unit/ingestion/test_jvm_framework_edges.py
@@ -0,0 +1,213 @@
+"""Unit tests for Phase 4 JVM framework edges (Spring expansion + Jakarta + Quarkus + Micronaut + Android)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str, language: str) -> FileInfo:
+ return FileInfo(
+ path=rel, abs_path=abs_path, language=language,
+ size_bytes=100, git_hash="", last_modified=datetime.now(),
+ is_test=False, is_config=False, is_api_contract=False, is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for src in list(repo.rglob("*.java")) + list(repo.rglob("*.kt")):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ lang = "java" if src.suffix == ".java" else "kotlin"
+ fi = _file_info(rel, str(src.resolve()), lang)
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ # Also pick up AndroidManifest.xml as a 'parsed' shell so the handler can
+ # locate its abs_path. We don't really parse XML.
+ for src in repo.rglob("AndroidManifest.xml"):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(src.resolve()), "xml")
+ # Build a minimal ParsedFile by reusing parser on empty Java syntax
+ # — but we only need file_info, so synthesize directly.
+ from repowise.core.ingestion.models import ParsedFile as _PF
+ out[rel] = _PF(file_info=fi, symbols=[], imports=[], exports=[])
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem_map.setdefault(Path(p).stem.lower(), []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+def _seed_graph(parsed: dict[str, ParsedFile]) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in parsed:
+ g.add_node(p, node_type="file", path=p)
+ return g
+
+
+class TestSpringDataRepository:
+ def test_jparepository_marked_entry_point(self, tmp_path: Path) -> None:
+ (tmp_path / "User.java").write_text(
+ "package com.x;\n"
+ "import jakarta.persistence.Entity;\n"
+ "@Entity public class User {}\n"
+ )
+ (tmp_path / "UserRepo.java").write_text(
+ "package com.x;\n"
+ "import org.springframework.data.jpa.repository.JpaRepository;\n"
+ "public interface UserRepo extends JpaRepository<User, Long> {\n"
+ " User findByEmail(String email);\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ assert graph.nodes["UserRepo.java"].get("is_entry_point") is True
+ assert graph.nodes["UserRepo.java"].get("framework_role") == "spring_data_repository"
+
+
+class TestLombokRAC:
+ def test_required_args_constructor_emits_ctor_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "UserService.java").write_text(
+ "package com.x;\n"
+ "import org.springframework.stereotype.Service;\n"
+ "@Service public class UserService {}\n"
+ )
+ (tmp_path / "OrderService.java").write_text(
+ "package com.x;\n"
+ "import org.springframework.stereotype.Service;\n"
+ "@Service public class OrderService {}\n"
+ )
+ (tmp_path / "Controller.java").write_text(
+ "package com.x;\n"
+ "import lombok.RequiredArgsConstructor;\n"
+ "import org.springframework.web.bind.annotation.RestController;\n"
+ "@RestController\n@RequiredArgsConstructor\n"
+ "public class Controller {\n"
+ " private final UserService users;\n"
+ " private final OrderService orders;\n"
+ " private String name;\n" # non-final, not in RAC
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ assert graph.has_edge("Controller.java", "UserService.java")
+ assert graph.has_edge("Controller.java", "OrderService.java")
+
+
+class TestJakarta:
+ def test_jaxrs_path_marks_entry_point(self, tmp_path: Path) -> None:
+ (tmp_path / "Books.java").write_text(
+ "package com.x;\n"
+ "import jakarta.ws.rs.Path;\n"
+ "import jakarta.ws.rs.GET;\n"
+ "@Path(\"/books\") public class Books {\n"
+ " @GET public String list() { return \"\"; }\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["jakarta"])
+ assert graph.nodes["Books.java"].get("is_entry_point") is True
+ assert graph.nodes["Books.java"].get("framework_role") == "jax_rs_resource"
+
+ def test_jpa_entity_emits_one_to_many_edge(self, tmp_path: Path) -> None:
+ (tmp_path / "Order.java").write_text(
+ "package com.x;\n"
+ "import jakarta.persistence.Entity;\n"
+ "@Entity public class Order {}\n"
+ )
+ (tmp_path / "User.java").write_text(
+ "package com.x;\n"
+ "import java.util.Set;\n"
+ "import jakarta.persistence.Entity;\n"
+ "import jakarta.persistence.OneToMany;\n"
+ "@Entity public class User {\n"
+ " @OneToMany\n private Set<Order> orders;\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["jakarta"])
+ assert graph.has_edge("User.java", "Order.java")
+
+
+class TestQuarkus:
+ def test_incoming_outgoing_cross_link(self, tmp_path: Path) -> None:
+ (tmp_path / "Producer.java").write_text(
+ "package com.x;\n"
+ "import org.eclipse.microprofile.reactive.messaging.Outgoing;\n"
+ "public class Producer {\n"
+ " @Outgoing(\"orders\") public String emit() { return \"\"; }\n"
+ "}\n"
+ )
+ (tmp_path / "Consumer.java").write_text(
+ "package com.x;\n"
+ "import org.eclipse.microprofile.reactive.messaging.Incoming;\n"
+ "public class Consumer {\n"
+ " @Incoming(\"orders\") public void on(String s) {}\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["quarkus"])
+ assert graph.has_edge("Producer.java", "Consumer.java")
+
+
+class TestMicronaut:
+ def test_micronaut_controller_marks_entry(self, tmp_path: Path) -> None:
+ (tmp_path / "Hi.java").write_text(
+ "package com.x;\n"
+ "import io.micronaut.http.annotation.Controller;\n"
+ "@Controller(\"/hi\") public class Hi {}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["micronaut"])
+ assert graph.nodes["Hi.java"].get("is_entry_point") is True
+
+
+class TestAndroidManifest:
+ def test_manifest_links_to_activity_class(self, tmp_path: Path) -> None:
+ # Source class
+ src_dir = tmp_path / "app" / "src" / "main" / "java" / "com" / "x"
+ src_dir.mkdir(parents=True)
+ (src_dir / "MainActivity.java").write_text(
+ "package com.x;\npublic class MainActivity {}\n"
+ )
+ # Manifest
+ manifest_dir = tmp_path / "app" / "src" / "main"
+ (manifest_dir / "AndroidManifest.xml").write_text(
+ "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n"
+ " <application>\n"
+ " <activity android:name=\"com.x.MainActivity\" />\n"
+ " </application>\n"
+ "</manifest>\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = _seed_graph(parsed)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx)
+ manifest_rel = "app/src/main/AndroidManifest.xml"
+ activity_rel = "app/src/main/java/com/x/MainActivity.java"
+ assert graph.has_edge(manifest_rel, activity_rel)