Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): resolve local Maven package dependencies (#2231)
Raghav Chamadiyaaef2d4296e05
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex c557ed71a..7056f1c98 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -289,7 +289,24 @@ excluded from matching and reported under the `external_host` diagnostics reason### Package Dependency Scanning-Reads package manifests (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `.csproj`) to detect when one repo depends on another as a package. Maven `pom.xml` is not scanned, so a Maven repo gets no package edges.+Reads package manifests (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`,+`.csproj`, and Maven `pom.xml`) to detect when one repo depends on another as a+package or project.++Maven matching is filesystem-only and coordinate-based. Repowise resolves local+reactor modules, local parents, properties, and dependency-management versions,+then links an active direct compile/runtime dependency only when exactly one+selected workspace project publishes that `groupId:artifactId`. Test, provided,+system, optional, profile-only, ambiguous, and external dependencies do not create+production package edges. Bounded diagnostics retain the reason for Maven+non-matches. When a repository has a root `pom.xml`, only that declared reactor is+eligible; unrelated nested example or fixture POMs are not treated as producers.++This does **not** execute Maven, read user settings, download artifacts, resolve+plugins/transitive dependencies/imported BOMs, or infer generated sources. A Maven+package edge is also not a published symbol-level code API or a runnable Maven+target recommendation; those capabilities are reported separately and remain+unsupported.---diff --git a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py b/packages/core/src/repowise/core/ingestion/external_systems/__init__.pyindex d2c07ddd3..e5cc0e728 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py@@ -15,6 +15,7 @@ never raise on malformed input.from __future__ import annotationsfrom collections.abc import Iterable+from contextlib import suppressfrom pathlib import Pathfrom types import ModuleType@@ -77,14 +78,21 @@ def extract_external_systems(candidates = list(manifest_paths) if manifest_paths is not None else _discover(repo_root)records: list[ExternalSystemRecord] = []+ maven_paths: list[Path] = []for path in candidates:parser = _parser_for(path)if parser is None:continue+ if parser is maven:+ maven_paths.append(path)+ continuetry:records.extend(parser.parse(path, repo_root))except Exception: # parser bugs must not break ingestioncontinue+ if maven_paths:+ with suppress(Exception): # parser bugs must not break ingestion+ records.extend(maven.parse_many(maven_paths, repo_root))return _deduplicate(records)diff --git a/packages/core/src/repowise/core/ingestion/external_systems/maven.py b/packages/core/src/repowise/core/ingestion/external_systems/maven.pyindex becd63540..e92e02553 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/maven.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/maven.py@@ -1,145 +1,69 @@-"""Parse Maven ``pom.xml`` manifests.+"""Parse Maven ``pom.xml`` manifests without executing Maven.-Reads ``<dependency>`` entries from ``<dependencies>`` blocks and handles-``<modules>`` for reactor discovery. Properties (``${...}``) are resolved-when declared in the same POM or a parent POM within the same repo.+The shared local model resolves a bounded subset of parent inheritance,+properties, and dependency management. Reactor discovery is performed by+callers that already own a pruned repository walk."""from __future__ import annotations-import re-import xml.etree.ElementTree as ETfrom pathlib import Pathfrom .base import ExternalSystemRecordfrom .classifier import classify, display_name_forfrom .io_kind import classify_io_kind+from .maven_model import load_maven_reactorfilenames: tuple[str, ...] = ("pom.xml",)ecosystem: str = "maven"-_NS = re.compile(r"\{[^}]*\}")+_DEV_SCOPES = frozenset({"test", "provided", "system"})-def _strip_ns(tag: str) -> str:- return _NS.sub("", tag)+def parse_many(+ manifest_paths: list[Path] | tuple[Path, ...],+ repo_root: Path,+) -> list[ExternalSystemRecord]:+ """Return effective direct dependencies for several POMs in one model pass.+ Local parents are read when referenced from inside ``repo_root``. Only+ requested manifests contribute records; parents loaded solely for+ inheritance remain implementation context.+ """-def _find(el: ET.Element, local_name: str) -> ET.Element | None:- for child in el:- if _strip_ns(child.tag) == local_name:- return child- return None---def _find_text(el: ET.Element, local_name: str) -> str:- child = _find(el, local_name)- return (child.text or "").strip() if child is not None else ""---def _find_all(el: ET.Element, local_name: str) -> list[ET.Element]:- return [child for child in el if _strip_ns(child.tag) == local_name]---def _collect_properties(root: ET.Element) -> dict[str, str]:- props: dict[str, str] = {}- props_el = _find(root, "properties")- if props_el is not None:- for child in props_el:- key = _strip_ns(child.tag)- if child.text:- props[key] = child.text.strip()- gid = _find_text(root, "groupId")- aid = _find_text(root, "artifactId")- ver = _find_text(root, "version")- if gid:- props.setdefault("project.groupId", gid)- if aid:- props.setdefault("project.artifactId", aid)- if ver:- props.setdefault("project.version", ver)- return props---_PROP_RE = re.compile(r"\$\{([^}]+)\}")---def _resolve_props(value: str, props: dict[str, str]) -> str:- def _repl(m: re.Match) -> str:- return props.get(m.group(1), m.group(0))-- resolved = _PROP_RE.sub(_repl, value)- if resolved != value and "${" in resolved:- resolved = _PROP_RE.sub(_repl, resolved)- return resolved---_TEST_SCOPES = frozenset({"test", "provided", "system"})---def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:- try:- tree = ET.parse(manifest_path)- except Exception:- return []-- root = tree.getroot()- declared_in = manifest_path.relative_to(repo_root).as_posix()- props = _collect_properties(root)-- # Inherit parent properties- parent = _find(root, "parent")- if parent is not None:- parent_ver = _find_text(parent, "version")- if parent_ver:- props.setdefault("project.parent.version", parent_ver)- props.setdefault("project.version", parent_ver)-- # Collect managed dependency versions- dep_mgmt = _find(root, "dependencyManagement")- managed: dict[str, str] = {}- if dep_mgmt is not None:- deps_el = _find(dep_mgmt, "dependencies")- if deps_el is not None:- for dep in _find_all(deps_el, "dependency"):- g = _resolve_props(_find_text(dep, "groupId"), props)- a = _resolve_props(_find_text(dep, "artifactId"), props)- v = _resolve_props(_find_text(dep, "version"), props)- if g and a and v:- managed[f"{g}:{a}"] = v+ requested = {path.resolve() for path in manifest_paths}+ reactor = load_maven_reactor(repo_root, tuple(requested))records: list[ExternalSystemRecord] = []- seen: set[str] = set()-- for deps_el in _find_all(root, "dependencies"):- for dep in _find_all(deps_el, "dependency"):- group_id = _resolve_props(_find_text(dep, "groupId"), props)- artifact_id = _resolve_props(_find_text(dep, "artifactId"), props)- if not group_id or not artifact_id:- continue- name = f"{group_id}:{artifact_id}"- if name in seen:+ seen: set[tuple[str, str]] = set()+ for project in reactor.projects:+ if (repo_root / project.manifest).resolve() not in requested:+ continue+ for dependency in project.dependencies:+ key = (dependency.coordinate, dependency.declared_in)+ if dependency.has_unresolved_coordinate or key in seen:continue- seen.add(name)-- version = _resolve_props(_find_text(dep, "version"), props)- if not version or "${" in version:- version = managed.get(name, version or None)-- scope = _find_text(dep, "scope").lower()- is_dev = scope in _TEST_SCOPES-+ seen.add(key)records.append(ExternalSystemRecord(- name=name,+ name=dependency.coordinate,ecosystem=ecosystem,- declared_in=declared_in,- version=version if version and "${" not in version else None,- display_name=display_name_for(artifact_id),- category=classify(artifact_id),- io_kind=classify_io_kind(artifact_id),- is_dev_dep=is_dev,+ declared_in=dependency.declared_in,+ version=dependency.version,+ display_name=display_name_for(dependency.artifact_id),+ category=classify(dependency.artifact_id),+ io_kind=classify_io_kind(dependency.artifact_id),+ is_dev_dep=dependency.scope in _DEV_SCOPES,+ extras={+ "scope": dependency.scope,+ "optional": str(dependency.optional).lower(),+ "type": dependency.dependency_type,+ },))-return records+++def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:+ """Return effective direct dependencies declared by one POM."""+ return parse_many([manifest_path], repo_root)diff --git a/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py b/packages/core/src/repowise/core/ingestion/external_systems/maven_model.pynew file mode 100644index 000000000..f58290add--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py@@ -0,0 +1,622 @@+"""Bounded, filesystem-only Maven POM model resolution.++This module deliberately implements a small Maven subset. It reads POM XML+already present in a repository and resolves local parents, reactor modules,+properties, and dependency-management entries. It never invokes Maven,+loads settings, downloads artifacts, or attempts transitive resolution.+"""++from __future__ import annotations++import re+import xml.etree.ElementTree as ET+from dataclasses import dataclass, field+from pathlib import Path++_NS = re.compile(r"\{[^}]*\}")+_PROP_RE = re.compile(r"\$\{([^}]+)\}")+_MAX_PARENT_DEPTH = 16+_MAX_PROPERTY_PASSES = 8+++@dataclass(frozen=True)+class MavenDependency:+ group_id: str+ artifact_id: str+ version: str | None+ scope: str+ optional: bool+ dependency_type: str+ classifier: str+ declared_in: str+ has_unresolved_structural_metadata: bool = False++ @property+ def coordinate(self) -> str:+ return f"{self.group_id}:{self.artifact_id}"++ @property+ def has_unresolved_coordinate(self) -> bool:+ return "${" in self.group_id or "${" in self.artifact_id+++@dataclass(frozen=True)+class MavenProject:+ group_id: str+ artifact_id: str+ version: str | None+ packaging: str+ manifest: str+ modules: tuple[str, ...]+ dependencies: tuple[MavenDependency, ...]++ @property+ def coordinate(self) -> str:+ return f"{self.group_id}:{self.artifact_id}"++ @property+ def has_unresolved_coordinate(self) -> bool:+ return "${" in self.group_id or "${" in self.artifact_id+++@dataclass(frozen=True)+class MavenModelDiagnostic:+ manifest: str+ code: str+ detail: str = ""+++@dataclass(frozen=True)+class MavenReactor:+ projects: tuple[MavenProject, ...] = ()+ diagnostics: tuple[MavenModelDiagnostic, ...] = ()+ declared_manifests: tuple[str, ...] = ()+++@dataclass+class _RawDependency:+ group_id: str+ artifact_id: str+ version: str+ scope: str+ optional: str+ dependency_type: str+ classifier: str+++@dataclass+class _RawPom:+ path: Path+ relative_path: str+ group_id: str+ artifact_id: str+ version: str+ packaging: str+ parent_group_id: str+ parent_artifact_id: str+ parent_version: str+ parent_path: Path | None+ external_parent_detail: str+ properties: dict[str, str] = field(default_factory=dict)+ managed: list[_RawDependency] = field(default_factory=list)+ dependencies: list[_RawDependency] = field(default_factory=list)+ modules: list[str] = field(default_factory=list)+++@dataclass+class _EffectivePom:+ project: MavenProject+ properties: dict[str, str]+ raw_properties: dict[str, str]+ managed_entries: tuple[tuple[_RawDependency, str], ...]+ dependency_entries: tuple[tuple[_RawDependency, str], ...]+++def _strip_ns(tag: str) -> str:+ return _NS.sub("", tag)+++def _find(element: ET.Element, local_name: str) -> ET.Element | None:+ return next(+ (child for child in element if _strip_ns(child.tag) == local_name),+ None,+ )+++def _find_text(element: ET.Element, local_name: str) -> str:+ child = _find(element, local_name)+ return (child.text or "").strip() if child is not None else ""+++def _dependencies(element: ET.Element | None) -> list[_RawDependency]:+ if element is None:+ return []+ dependencies = _find(element, "dependencies")+ if dependencies is None:+ return []+ result: list[_RawDependency] = []+ for dependency in dependencies:+ if _strip_ns(dependency.tag) != "dependency":+ continue+ result.append(+ _RawDependency(+ group_id=_find_text(dependency, "groupId"),+ artifact_id=_find_text(dependency, "artifactId"),+ version=_find_text(dependency, "version"),+ scope=_find_text(dependency, "scope"),+ optional=_find_text(dependency, "optional"),+ dependency_type=_find_text(dependency, "type"),+ classifier=_find_text(dependency, "classifier"),+ )+ )+ return result+++def _is_within(path: Path, root: Path) -> bool:+ try:+ path.relative_to(root)+ except ValueError:+ return False+ return True+++def _parse_raw(+ manifest_path: Path,+ repo_root: Path,+ diagnostics: list[MavenModelDiagnostic],+) -> _RawPom | None:+ try:+ root = ET.parse(manifest_path).getroot()+ except (ET.ParseError, OSError) as exc:+ diagnostics.append(+ MavenModelDiagnostic(+ manifest=_relative(manifest_path, repo_root),+ code="malformed_pom",+ detail=type(exc).__name__,+ )+ )+ return None++ parent = _find(root, "parent")+ parent_path: Path | None = None+ external_parent_detail = ""+ parent_group_id = parent_artifact_id = parent_version = ""+ if parent is not None:+ parent_group_id = _find_text(parent, "groupId")+ parent_artifact_id = _find_text(parent, "artifactId")+ parent_version = _find_text(parent, "version")+ relative = _find(parent, "relativePath")+ # Maven defaults to ../pom.xml. An explicitly empty element disables+ # local parent lookup and leaves the parent external to this model.+ if relative is None:+ relative_text: str | None = "../pom.xml"+ else:+ relative_text = (relative.text or "").strip() or None+ if relative_text is not None:+ candidate = (manifest_path.parent / relative_text).resolve()+ if candidate.is_dir():+ candidate /= "pom.xml"+ root_resolved = repo_root.resolve()+ if _is_within(candidate, root_resolved):+ parent_path = candidate+ else:+ external_parent_detail = (+ f"{parent_group_id}:{parent_artifact_id}:{parent_version} "+ f"(outside repository: {relative_text})"+ )+ else:+ external_parent_detail = (+ f"{parent_group_id}:{parent_artifact_id}:{parent_version} (local lookup disabled)"+ )++ properties: dict[str, str] = {}+ props = _find(root, "properties")+ if props is not None:+ for child in props:+ if child.text is not None:+ properties[_strip_ns(child.tag)] = child.text.strip()++ modules: list[str] = []+ modules_element = _find(root, "modules")+ if modules_element is not None:+ modules = [+ (module.text or "").strip()+ for module in modules_element+ if _strip_ns(module.tag) == "module" and (module.text or "").strip()+ ]++ return _RawPom(+ path=manifest_path.resolve(),+ relative_path=_relative(manifest_path, repo_root),+ group_id=_find_text(root, "groupId"),+ artifact_id=_find_text(root, "artifactId"),+ version=_find_text(root, "version"),+ packaging=_find_text(root, "packaging") or "jar",+ parent_group_id=parent_group_id,+ parent_artifact_id=parent_artifact_id,+ parent_version=parent_version,+ parent_path=parent_path,+ external_parent_detail=external_parent_detail,+ properties=properties,+ managed=_dependencies(_find(root, "dependencyManagement")),+ dependencies=_dependencies(root),+ modules=modules,+ )+++def _relative(path: Path, repo_root: Path) -> str:+ try:+ return path.resolve().relative_to(repo_root.resolve()).as_posix()+ except (OSError, ValueError):+ return path.name+++def _resolve(value: str, properties: dict[str, str]) -> str:+ current = value+ for _ in range(_MAX_PROPERTY_PASSES):+ resolved = _PROP_RE.sub(+ lambda match: properties.get(match.group(1), match.group(0)), current+ )+ if resolved == current:+ break+ current = resolved+ return current+++def _resolve_properties(properties: dict[str, str]) -> dict[str, str]:+ resolved = dict(properties)+ for _ in range(_MAX_PROPERTY_PASSES):+ changed = False+ for key, value in tuple(resolved.items()):+ new_value = _resolve(value, resolved)+ if new_value != value:+ resolved[key] = new_value+ changed = True+ if not changed:+ break+ return resolved+++def load_maven_reactor(+ repo_root: Path,+ manifest_paths: list[Path] | tuple[Path, ...],+) -> MavenReactor:+ """Resolve the supported local Maven model for the supplied POM files.++ Parent POMs referenced by those files are read on demand when they remain+ inside ``repo_root``. Reactor module POMs should be supplied by the+ caller's existing bounded repository walk; missing declared modules are+ reported and never discovered with a second unbounded scan.+ """++ root = repo_root.resolve()+ diagnostics: list[MavenModelDiagnostic] = []+ raw_by_path: dict[Path, _RawPom] = {}+ pending = sorted({path.resolve() for path in manifest_paths})++ while pending:+ path = pending.pop(0)+ if path in raw_by_path or not _is_within(path, root):+ continue+ raw = _parse_raw(path, root, diagnostics)+ if raw is None:+ continue+ raw_by_path[path] = raw+ if raw.external_parent_detail:+ diagnostics.append(+ MavenModelDiagnostic(+ manifest=raw.relative_path,+ code="external_parent_unsupported",+ detail=raw.external_parent_detail,+ )+ )+ if raw.parent_path is not None and raw.parent_path not in raw_by_path:+ if raw.parent_path.is_file():+ pending.append(raw.parent_path)+ else:+ diagnostics.append(+ MavenModelDiagnostic(+ manifest=raw.relative_path,+ code="unresolved_parent",+ detail=_relative(raw.parent_path, root),+ )+ )++ for raw in raw_by_path.values():+ if raw.parent_path is not None and raw.parent_path not in raw_by_path:+ diagnostics.append(+ MavenModelDiagnostic(+ manifest=raw.relative_path,+ code="unresolved_parent",+ detail=_relative(raw.parent_path, root),+ )+ )++ cache: dict[Path, _EffectivePom | None] = {}+ failed: set[Path] = set()+ failure_codes: dict[Path, str] = {}++ def build(path: Path, stack: tuple[Path, ...]) -> _EffectivePom | None:+ if path in failed:+ return None+ if path in cache:+ return cache[path]+ raw = raw_by_path.get(path)+ if raw is None:+ return None+ if path in stack:+ diagnostics.append(MavenModelDiagnostic(raw.relative_path, "parent_cycle"))+ cycle_paths = stack[stack.index(path) :]+ failed.update(cycle_paths)+ for invalid_path in cycle_paths:+ cache[invalid_path] = None+ failure_codes[invalid_path] = "parent_cycle"+ return None+ if len(stack) >= _MAX_PARENT_DEPTH:+ diagnostics.append(MavenModelDiagnostic(raw.relative_path, "parent_depth_exceeded"))+ depth_paths = set(stack) | {path}+ next_path = raw.parent_path+ while next_path in raw_by_path and next_path not in depth_paths:+ depth_paths.add(next_path)+ next_path = raw_by_path[next_path].parent_path+ failed.update(depth_paths)+ for invalid_path in depth_paths:+ cache[invalid_path] = None+ failure_codes[invalid_path] = "parent_depth_exceeded"+ return None++ has_local_parent = raw.parent_path is not None and raw.parent_path in raw_by_path+ parent = (+ build(raw.parent_path, (*stack, path))+ if raw.parent_path is not None and has_local_parent+ else None+ )+ if has_local_parent and parent is None:+ assert raw.parent_path is not None+ failure_code = failure_codes.get(raw.parent_path, "invalid_parent_chain")+ diagnostics.append(+ MavenModelDiagnostic(+ raw.relative_path,+ failure_code,+ _relative(raw.parent_path, root),+ )+ )+ failed.add(path)+ failure_codes[path] = failure_code+ cache[path] = None+ return None+ if parent is not None:+ declared_parent = (+ _resolve(raw.parent_group_id, parent.properties),+ _resolve(raw.parent_artifact_id, parent.properties),+ _resolve(raw.parent_version, parent.properties),+ )+ effective_parent = (+ parent.project.group_id,+ parent.project.artifact_id,+ parent.project.version or "",+ )+ coordinates_match = all(+ declared == effective or not declared or "${" in declared+ for declared, effective in zip(+ declared_parent,+ effective_parent,+ strict=True,+ )+ )+ if not coordinates_match:+ diagnostics.append(+ MavenModelDiagnostic(+ raw.relative_path,+ "parent_coordinate_mismatch",+ f"declared={':'.join(declared_parent)} local={':'.join(effective_parent)}",+ )+ )+ parent = None+ raw_properties = dict(parent.raw_properties) if parent is not None else {}+ raw_properties.update(raw.properties)+ properties = dict(raw_properties)++ parent_group = parent.project.group_id if parent is not None else raw.parent_group_id+ parent_artifact = (+ parent.project.artifact_id if parent is not None else raw.parent_artifact_id+ )+ parent_version = (+ (parent.project.version or "") if parent is not None else raw.parent_version+ )+ if parent_group:+ properties.setdefault("project.parent.groupId", parent_group)+ properties.setdefault("pom.parent.groupId", parent_group)+ if parent_artifact:+ properties.setdefault("project.parent.artifactId", parent_artifact)+ properties.setdefault("pom.parent.artifactId", parent_artifact)+ if parent_version:+ properties.setdefault("project.parent.version", parent_version)+ properties.setdefault("pom.parent.version", parent_version)++ properties = _resolve_properties(properties)+ group_id = _resolve(raw.group_id or parent_group, properties)+ artifact_id = _resolve(raw.artifact_id, properties)+ version = _resolve(raw.version or parent_version, properties)+ builtins = {+ "project.groupId": group_id,+ "pom.groupId": group_id,+ "project.artifactId": artifact_id,+ "pom.artifactId": artifact_id,+ "project.version": version,+ "pom.version": version,+ }+ properties.update({key: value for key, value in builtins.items() if value})+ properties = _resolve_properties(properties)+ group_id = _resolve(group_id, properties)+ artifact_id = _resolve(artifact_id, properties)+ version = _resolve(version, properties)++ managed_entries = list(parent.managed_entries) if parent is not None else []+ managed_entries.extend((dependency, raw.relative_path) for dependency in raw.managed)+ managed: dict[tuple[str, str, str, str], str] = {}+ for dependency, _declared_in in managed_entries:+ dep_group = _resolve(dependency.group_id, properties)+ dep_artifact = _resolve(dependency.artifact_id, properties)+ dep_version = _resolve(dependency.version, properties)+ dep_type = _resolve(dependency.dependency_type, properties).strip().lower() or "jar"+ dep_classifier = _resolve(dependency.classifier, properties).strip()+ if dep_group and dep_artifact and dep_version and "${" not in dep_version:+ managed[(dep_group, dep_artifact, dep_type, dep_classifier)] = dep_version++ dependency_entries = list(parent.dependency_entries) if parent is not None else []+ dependency_entries.extend(+ (dependency, raw.relative_path) for dependency in raw.dependencies+ )+ dependencies_by_key: dict[tuple[str, str, str, str], MavenDependency] = {}+ for dependency, declared_in in dependency_entries:+ dep_group = _resolve(dependency.group_id, properties)+ dep_artifact = _resolve(dependency.artifact_id, properties)+ coordinate = f"{dep_group}:{dep_artifact}"+ dep_type = _resolve(dependency.dependency_type, properties).strip().lower() or "jar"+ dep_classifier = _resolve(dependency.classifier, properties).strip()+ dep_version = _resolve(dependency.version, properties)+ if not dep_version:+ dep_version = managed.get((dep_group, dep_artifact, dep_type, dep_classifier), "")+ unresolved_version = "${" in dep_version+ dep_scope = _resolve(dependency.scope, properties).strip().lower() or "compile"+ dep_optional_text = _resolve(dependency.optional, properties).strip().lower()+ dep_optional = dep_optional_text == "true"+ unresolved_metadata = any(+ "${" in value for value in (dep_scope, dep_optional_text, dep_type, dep_classifier)+ )+ dep = MavenDependency(+ group_id=dep_group,+ artifact_id=dep_artifact,+ version=dep_version if dep_version and not unresolved_version else None,+ scope=dep_scope,+ optional=dep_optional,+ dependency_type=dep_type,+ classifier=dep_classifier,+ declared_in=declared_in,+ has_unresolved_structural_metadata=unresolved_metadata,+ )+ if not dep.group_id or not dep.artifact_id or dep.has_unresolved_coordinate:+ diagnostics.append(+ MavenModelDiagnostic(+ declared_in,+ "unresolved_dependency_coordinate",+ coordinate,+ )+ )+ if unresolved_version:+ diagnostics.append(+ MavenModelDiagnostic(+ declared_in,+ "unresolved_dependency_version",+ dep_version,+ )+ )+ if unresolved_metadata:+ diagnostics.append(+ MavenModelDiagnostic(+ declared_in,+ "unresolved_dependency_metadata",+ coordinate,+ )+ )+ dependencies_by_key[+ (dep.group_id, dep.artifact_id, dep.dependency_type, dep.classifier)+ ] = dep++ dependencies = list(dependencies_by_key.values())++ modules: list[str] = []+ for module in raw.modules:+ resolved_module = _resolve(module, properties)+ module_path = (raw.path.parent / resolved_module).resolve()+ if module_path.is_dir():+ module_path /= "pom.xml"+ if not _is_within(module_path, root) or module_path not in raw_by_path:+ diagnostics.append(+ MavenModelDiagnostic(+ raw.relative_path,+ "unresolved_module",+ resolved_module,+ )+ )+ continue+ modules.append(_relative(module_path, root))++ project = MavenProject(+ group_id=group_id,+ artifact_id=artifact_id,+ version=version if version and "${" not in version else None,+ packaging=_resolve(raw.packaging, properties),+ manifest=raw.relative_path,+ modules=tuple(modules),+ dependencies=tuple(dependencies),+ )+ if not group_id or not artifact_id or project.has_unresolved_coordinate:+ diagnostics.append(+ MavenModelDiagnostic(+ raw.relative_path,+ "unresolved_project_coordinate",+ project.coordinate,+ )+ )+ if "${" in version:+ diagnostics.append(+ MavenModelDiagnostic(+ raw.relative_path,+ "unresolved_project_version",+ version,+ )+ )+ cache[path] = _EffectivePom(+ project=project,+ properties=properties,+ raw_properties=raw_properties,+ managed_entries=tuple(managed_entries),+ dependency_entries=tuple(dependency_entries),+ )+ return cache[path]++ for path in sorted(raw_by_path):+ build(path, ())++ projects = tuple(+ effective.project for path in sorted(cache) if (effective := cache[path]) is not None+ )+ declared_manifests: list[str] = []+ root_manifest = root / "pom.xml"+ if root_manifest in raw_by_path:+ pending_manifests = [root_manifest]+ seen_manifests: set[Path] = set()+ while pending_manifests:+ manifest_path = pending_manifests.pop(0)+ if manifest_path in seen_manifests:+ continue+ seen_manifests.add(manifest_path)+ raw = raw_by_path.get(manifest_path)+ if raw is None:+ continue+ declared_manifests.append(raw.relative_path)+ effective = cache.get(manifest_path)+ module_properties = (+ effective.properties+ if effective is not None+ else _resolve_properties(raw.properties)+ )+ for module in raw.modules:+ module_path = (raw.path.parent / _resolve(module, module_properties)).resolve()+ if module_path.is_dir():+ module_path /= "pom.xml"+ if module_path in raw_by_path:+ pending_manifests.append(module_path)+ elif root_manifest.is_file():+ # A malformed physical root still establishes the reactor boundary.+ # Do not promote unrelated nested example/fixture POMs to standalone+ # workspace projects merely because the root could not be parsed.+ declared_manifests.append("pom.xml")+ unique_diagnostics = tuple(dict.fromkeys(diagnostics))+ return MavenReactor(+ projects=projects,+ diagnostics=unique_diagnostics,+ declared_manifests=tuple(declared_manifests),+ )diff --git a/packages/core/src/repowise/core/workspace/__init__.py b/packages/core/src/repowise/core/workspace/__init__.pyindex d91f8e1a1..820c6345f 100644--- a/packages/core/src/repowise/core/workspace/__init__.py+++ b/packages/core/src/repowise/core/workspace/__init__.py@@ -44,6 +44,7 @@ _EXPORTS: dict[str, str] = {"CrossRepoCoChange": "cross_repo","CrossRepoOverlay": "cross_repo","CrossRepoPackageDep": "cross_repo",+ "CrossRepoPackageDiagnostic": "cross_repo","load_overlay": "cross_repo","run_cross_repo_analysis": "cross_repo","save_overlay": "cross_repo",diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.pyindex d2fe489a9..b3bf37c48 100644--- a/packages/core/src/repowise/core/workspace/cross_repo.py+++ b/packages/core/src/repowise/core/workspace/cross_repo.py@@ -67,6 +67,10 @@ _MAX_EDGES_PER_REPO_PAIR: int = 50# Per-session cap on files paired per side, guarding the O(N*M) cross-product# against sprawling release/codemod sessions._MAX_FILES_PER_SESSION_SIDE: int = 20+# Package non-matches are useful evidence but ordinary workspaces can declare+# thousands of external libraries. Persist a deterministic sample plus the+# uncapped total so diagnostics cannot make the overlay unbounded.+_MAX_PACKAGE_DIAGNOSTICS: int = 200# ---------------------------------------------------------------------------@@ -177,7 +181,20 @@ class CrossRepoPackageDep:source_repo: strtarget_repo: strsource_manifest: str- kind: str # npm_local_path, pip_path, cargo_path, go_replace+ kind: str # npm_local_path, pip_path, cargo_path, go_replace, maven_coordinate+ target_package: str = ""+ target_manifest: str = ""+ requested_version: str | None = None+ scope: str = ""+ resolution_basis: str = ""+++@dataclass+class CrossRepoPackageDiagnostic:+ repo: str+ source_manifest: str+ code: str+ detail: str = ""@dataclass@@ -186,6 +203,7 @@ class CrossRepoOverlay:generated_at: str = ""co_changes: list[CrossRepoCoChange] = field(default_factory=list)package_deps: list[CrossRepoPackageDep] = field(default_factory=list)+ package_diagnostics: list[CrossRepoPackageDiagnostic] = field(default_factory=list)repo_summaries: dict[str, dict] = field(default_factory=dict)#: How many pairs cleared the strength/session thresholds before#: ``_MAX_EDGES`` / ``_MAX_EDGES_PER_REPO_PAIR`` trimmed ``co_changes``.@@ -194,6 +212,7 @@ class CrossRepoOverlay:#: session before pairing, so pairs involving an evicted file are in#: neither number.total_co_changes: int = 0+ total_package_diagnostics: int = 0def to_dict(self) -> dict:return {@@ -201,8 +220,11 @@ class CrossRepoOverlay:"generated_at": self.generated_at,"co_changes": [asdict(c) for c in self.co_changes],"package_deps": [asdict(d) for d in self.package_deps],+ "package_diagnostics": [asdict(d) for d in self.package_diagnostics],"repo_summaries": self.repo_summaries,"total_co_changes": self.total_co_changes or len(self.co_changes),+ "total_package_diagnostics": self.total_package_diagnostics+ or len(self.package_diagnostics),}@classmethod@@ -213,8 +235,15 @@ class CrossRepoOverlay:generated_at=data.get("generated_at", ""),co_changes=co_changes,package_deps=[CrossRepoPackageDep(**d) for d in data.get("package_deps", [])],+ package_diagnostics=[+ CrossRepoPackageDiagnostic(**d) for d in data.get("package_diagnostics", [])+ ],repo_summaries=data.get("repo_summaries", {}),total_co_changes=data.get("total_co_changes", len(co_changes)),+ total_package_diagnostics=data.get(+ "total_package_diagnostics",+ len(data.get("package_diagnostics", [])),+ ),)@@ -529,9 +558,7 @@ def detect_cross_repo_co_changes(continuelast_ts = pair_last_ts.get((src_repo, src_file, tgt_repo, tgt_file), 0)last_date = (- datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")- if last_ts > 0- else ""+ datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d") if last_ts > 0 else "")results.append(CrossRepoCoChange(@@ -582,10 +609,20 @@ def _resolve_target_repo("""Resolve a relative path reference to a repo alias, or None."""try:target_abs = (source_repo_path / relative_ref).resolve()- for alias, repo_path in repo_paths.items():- if target_abs == repo_path.resolve() or str(target_abs).startswith(- str(repo_path.resolve())- ):+ # Most-specific root first makes physically nested selected repos+ # deterministic. Path.relative_to supplies the separator-aware+ # containment check that string prefixes (``lib`` vs ``lib-old``) do not.+ roots = sorted(+ repo_paths.items(),+ key=lambda item: len(item[1].parts),+ reverse=True,+ )+ for alias, repo_path in roots:+ try:+ target_abs.relative_to(repo_path)+ except ValueError:+ continue+ else:return aliasexcept Exception:# A manifest reference that cannot be resolved to a path is the one@@ -801,11 +838,12 @@ def _scan_go_mod(_CSPROJ_SKIP_DIRS = frozenset({"bin", "obj", ".vs", "packages", "node_modules", ".git", "TestResults"})+_CSPROJ_SKIP_DIRS_LOWER = frozenset(name.lower() for name in _CSPROJ_SKIP_DIRS)@dataclassclass _CsprojIndex:- """Every ``.csproj`` in the workspace, walked and parsed exactly once.+ """Project manifests in the workspace, walked and parsed exactly once.``_scan_csproj`` needs two things: the assembly-name → repo-alias map(built from *all* repos) and the current repo's own project files. Built@@ -819,27 +857,53 @@ class _CsprojIndex:# Parsed once and shared; ElementTree instances are only ever read.trees: dict[Path, Any] = field(default_factory=dict)by_repo: dict[str, list[Path]] = field(default_factory=dict)+ poms_by_repo: dict[str, list[Path]] = field(default_factory=dict)assembly_to_repo: dict[str, str] = field(default_factory=dict)-def _walk_csproj(repo_root: Path, index: _CsprojIndex) -> list[Path]:- """Walk one repo for ``.csproj`` files, parsing each into *index.trees*."""+def _walk_project_manifests(+ repo_root: Path,+ index: _CsprojIndex,+) -> tuple[list[Path], list[Path]]:+ """Collect Maven and .NET project manifests in one pruned repo walk."""from xml.etree import ElementTree as ET- from repowise.core.fs_walk import iter_glob+ from repowise.core.fs_walk import PRUNED_DIRS, walk_repo- found: list[Path] = []- # Each *selected* workspace repo is walked from its own root; iter_glob's- # nested-git pruning keeps any physically-nested unselected repo out.- for csproj in iter_glob(repo_root, "*.csproj"):- if any(part in _CSPROJ_SKIP_DIRS for part in csproj.parts):- continue- try:- index.trees[csproj] = ET.parse(csproj)- except (ET.ParseError, OSError):- continue- found.append(csproj)- return found+ csprojects: list[Path] = []+ poms: list[Path] = []+ # ``packages`` is a .NET package cache convention but also a legitimate+ # Maven module directory, so it cannot be pruned for the shared walk.+ prune = PRUNED_DIRS | {+ "target",+ "dist",+ "build",+ "bin",+ "obj",+ ".vs",+ "TestResults",+ }+ for dirpath, _dirnames, filenames in walk_repo(repo_root, prune_dirs=prune):+ for filename in sorted(filenames):+ path = dirpath / filename+ if filename == "pom.xml":+ poms.append(path)+ elif filename.lower().endswith(".csproj"):+ relative_dirs = path.relative_to(repo_root).parts[:-1]+ if any(part.lower() in _CSPROJ_SKIP_DIRS_LOWER for part in relative_dirs):+ continue+ try:+ index.trees[path] = ET.parse(path)+ except (ET.ParseError, OSError):+ continue+ csprojects.append(path)+ return csprojects, poms+++def _walk_csproj(repo_root: Path, index: _CsprojIndex) -> list[Path]:+ """Compatibility wrapper for a standalone .NET project scan."""+ projects, _poms = _walk_project_manifests(repo_root, index)+ return projectsdef _assembly_name(tree: Any, csproj: Path) -> str:@@ -857,10 +921,11 @@ def _index_csproj_files(repo_paths: dict[str, Path]) -> _CsprojIndex:# Insertion order matches the previous per-alias rebuild, so a name# defined in two repos still resolves to the last repo in repo_paths.for alias, path in repo_paths.items():- found = _walk_csproj(path, index)+ found, poms = _walk_project_manifests(path, index)for csproj in found:index.assembly_to_repo[_assembly_name(index.trees[csproj], csproj)] = aliasindex.by_repo[alias] = found+ index.poms_by_repo[alias] = pomsreturn index@@ -950,34 +1015,123 @@ def detect_package_dependencies(repo_paths: dict[str, Path],) -> list[CrossRepoPackageDep]:"""Scan all repos for manifest-based cross-repo dependencies."""+ dependencies, _diagnostics, _total_diagnostics = detect_package_dependencies_with_diagnostics(+ repo_paths+ )+ return dependencies+++def detect_package_dependencies_with_diagnostics(+ repo_paths: dict[str, Path],+) -> tuple[+ list[CrossRepoPackageDep],+ list[CrossRepoPackageDiagnostic],+ int,+]:+ """Scan package manifests and retain bounded Maven non-match evidence."""+results: list[CrossRepoPackageDep] = []- seen: set[tuple[str, str, str]] = set() # (source, target, kind)+ seen: set[tuple[str, str, str, str, str]] = set()+ resolved_repo_paths = {alias: path.resolve() for alias, path in repo_paths.items()}# One walk per repo, shared across every alias. The .csproj scan is the- # only manifest scanner that walks the tree rather than reading a fixed- # root file, and it needs a workspace-wide view, so building its index- # per repo re-walked every tree once per repo.- csproj_index = _index_csproj_files(repo_paths)+ # only existing manifest scanner that walks the tree rather than reading+ # a fixed root file. The same pass now inventories Maven POMs as well.+ project_index = _index_csproj_files(resolved_repo_paths)- for alias, path in repo_paths.items():+ for alias, path in resolved_repo_paths.items():for scanner in (_scan_package_json,_scan_pyproject_toml,_scan_cargo_toml,_scan_go_mod,):- for dep in scanner(path, repo_paths, alias):- key = (dep.source_repo, dep.target_repo, dep.kind)+ for dep in scanner(path, resolved_repo_paths, alias):+ key = (+ dep.source_repo,+ dep.target_repo,+ dep.source_manifest,+ dep.kind,+ dep.target_package,+ )if key not in seen:seen.add(key)results.append(dep)- for dep in _scan_csproj(path, repo_paths, alias, csproj_index=csproj_index):- key = (dep.source_repo, dep.target_repo, dep.kind)+ for dep in _scan_csproj(+ path,+ resolved_repo_paths,+ alias,+ csproj_index=project_index,+ ):+ key = (+ dep.source_repo,+ dep.target_repo,+ dep.source_manifest,+ dep.kind,+ dep.target_package,+ )if key not in seen:seen.add(key)results.append(dep)- return results+ from .maven_dependencies import detect_maven_dependencies++ maven_links, maven_diagnostics = detect_maven_dependencies(+ resolved_repo_paths,+ project_index.poms_by_repo,+ )+ for link in maven_links:+ dep = CrossRepoPackageDep(+ source_repo=link.source_repo,+ target_repo=link.target_repo,+ source_manifest=link.source_manifest,+ kind="maven_coordinate",+ target_package=link.target_package,+ target_manifest=link.target_manifest,+ requested_version=link.requested_version,+ scope=link.scope,+ resolution_basis=link.resolution_basis,+ )+ key = (+ dep.source_repo,+ dep.target_repo,+ dep.source_manifest,+ dep.kind,+ dep.target_package,+ )+ if key not in seen:+ seen.add(key)+ results.append(dep)++ results.sort(+ key=lambda dep: (+ dep.source_repo,+ dep.target_repo,+ dep.source_manifest,+ dep.kind,+ dep.target_package,+ )+ )+ diagnostics = sorted(+ (+ CrossRepoPackageDiagnostic(+ repo=item.repo,+ source_manifest=item.manifest,+ code=item.code,+ detail=item.detail,+ )+ for item in maven_diagnostics+ ),+ key=lambda item: (+ item.code == "external_coordinate",+ item.repo,+ item.source_manifest,+ item.code,+ item.detail,+ ),+ )+ total_diagnostics = len(diagnostics)+ return results, diagnostics[:_MAX_PACKAGE_DIAGNOSTICS], total_diagnostics# ---------------------------------------------------------------------------@@ -989,6 +1143,7 @@ def _build_repo_summaries(repo_paths: dict[str, Path],co_changes: list[CrossRepoCoChange],package_deps: list[CrossRepoPackageDep],+ package_diagnostics: list[CrossRepoPackageDiagnostic] | None = None,) -> dict[str, dict]:"""Build per-repo summary stats."""summaries: dict[str, dict] = {}@@ -1002,9 +1157,17 @@ def _build_repo_summaries(edge_counts[pd.source_repo] += 1edge_counts[pd.target_repo] += 1+ diagnostic_counts: dict[str, int] = defaultdict(int)+ diagnostic_codes: dict[str, set[str]] = defaultdict(set)+ for diagnostic in package_diagnostics or []:+ diagnostic_counts[diagnostic.repo] += 1+ diagnostic_codes[diagnostic.repo].add(diagnostic.code)+for alias in repo_paths:summaries[alias] = {"cross_repo_edge_count": edge_counts.get(alias, 0),+ "package_diagnostics_emitted": diagnostic_counts.get(alias, 0),+ "package_diagnostic_codes": sorted(diagnostic_codes.get(alias, set())),}return summaries@@ -1021,9 +1184,7 @@ def save_overlay(overlay: CrossRepoOverlay, workspace_root: Path) -> Path:out_path = data_dir / CROSS_REPO_EDGES_FILENAME# Atomic: the MCP enricher reads these artifacts from a separate# process and must never observe a half-written file.- atomic_write_text(- out_path, json.dumps(overlay.to_dict(), indent=2, ensure_ascii=False)- )+ atomic_write_text(out_path, json.dumps(overlay.to_dict(), indent=2, ensure_ascii=False))return out_path@@ -1097,23 +1258,31 @@ async def run_cross_repo_analysis(# Co-change detection (CPU-bound git subprocess calls)import asyncio- co_changes, total_co_changes = await asyncio.to_thread(- detect_cross_repo_co_changes, repo_paths- )+ co_changes, total_co_changes = await asyncio.to_thread(detect_cross_repo_co_changes, repo_paths)# Package dependency detection (file I/O)- package_deps = await asyncio.to_thread(detect_package_dependencies, repo_paths)+ package_deps, package_diagnostics, total_package_diagnostics = await asyncio.to_thread(+ detect_package_dependencies_with_diagnostics,+ repo_paths,+ )# Build summaries- repo_summaries = _build_repo_summaries(repo_paths, co_changes, package_deps)+ repo_summaries = _build_repo_summaries(+ repo_paths,+ co_changes,+ package_deps,+ package_diagnostics,+ )overlay = CrossRepoOverlay(version=_OVERLAY_VERSION,generated_at=datetime.now(UTC).isoformat(),co_changes=co_changes,package_deps=package_deps,+ package_diagnostics=package_diagnostics,repo_summaries=repo_summaries,total_co_changes=total_co_changes,+ total_package_diagnostics=total_package_diagnostics,)# Persistdiff --git a/packages/core/src/repowise/core/workspace/maven_dependencies.py b/packages/core/src/repowise/core/workspace/maven_dependencies.pynew file mode 100644index 000000000..022f932bc--- /dev/null+++ b/packages/core/src/repowise/core/workspace/maven_dependencies.py@@ -0,0 +1,179 @@+"""Resolve local Maven coordinates into cross-repository package links."""++from __future__ import annotations++from collections import defaultdict+from dataclasses import dataclass+from pathlib import Path++from repowise.core.ingestion.external_systems.maven_model import (+ MavenModelDiagnostic,+ MavenProject,+ load_maven_reactor,+)++_STRUCTURAL_SCOPES = frozenset({"compile", "runtime"})+++@dataclass(frozen=True)+class MavenWorkspaceLink:+ source_repo: str+ target_repo: str+ source_manifest: str+ target_manifest: str+ target_package: str+ requested_version: str | None+ scope: str+ resolution_basis: str = "unique_workspace_coordinate"+++@dataclass(frozen=True)+class MavenWorkspaceDiagnostic:+ repo: str+ manifest: str+ code: str+ detail: str = ""+++def _workspace_diagnostic(+ alias: str,+ diagnostic: MavenModelDiagnostic,+) -> MavenWorkspaceDiagnostic:+ return MavenWorkspaceDiagnostic(+ repo=alias,+ manifest=diagnostic.manifest,+ code=diagnostic.code,+ detail=diagnostic.detail,+ )+++def _declared_reactor_projects(+ projects: tuple[MavenProject, ...],+ declared_manifests: tuple[str, ...],+) -> tuple[MavenProject, ...]:+ """Prefer the root reactor over unrelated nested example/fixture POMs."""+ if "pom.xml" in declared_manifests:+ by_manifest = {project.manifest: project for project in projects}+ return tuple(+ project+ for manifest in declared_manifests+ if (project := by_manifest.get(manifest)) is not None+ )++ by_manifest = {project.manifest: project for project in projects}+ root = by_manifest.get("pom.xml")+ if root is None:+ return projects++ selected: list[MavenProject] = []+ pending = [root.manifest]+ seen: set[str] = set()+ while pending:+ manifest = pending.pop(0)+ if manifest in seen:+ continue+ seen.add(manifest)+ project = by_manifest.get(manifest)+ if project is None:+ continue+ selected.append(project)+ pending.extend(project.modules)+ return tuple(selected)+++def detect_maven_dependencies(+ repo_paths: dict[str, Path],+ poms_by_repo: dict[str, list[Path]],+) -> tuple[list[MavenWorkspaceLink], list[MavenWorkspaceDiagnostic]]:+ """Return exact local Maven links and honest non-match diagnostics.++ ``poms_by_repo`` must come from the caller's bounded workspace scan. A+ dependency matches only one effective project coordinate across the+ entire selected workspace; duplicate producers are ambiguous and do not+ create an edge.+ """++ projects_by_repo: dict[str, tuple[MavenProject, ...]] = {}+ diagnostics: list[MavenWorkspaceDiagnostic] = []+ producers: dict[str, list[tuple[str, MavenProject]]] = defaultdict(list)++ for alias in sorted(repo_paths):+ reactor = load_maven_reactor(+ repo_paths[alias],+ tuple(sorted(poms_by_repo.get(alias, []))),+ )+ projects_by_repo[alias] = _declared_reactor_projects(+ reactor.projects, reactor.declared_manifests+ )+ has_root_reactor = "pom.xml" in reactor.declared_manifests+ selected_manifests = (+ set(reactor.declared_manifests)+ if has_root_reactor+ else {project.manifest for project in projects_by_repo[alias]}+ )+ diagnostics.extend(+ _workspace_diagnostic(alias, item)+ for item in reactor.diagnostics+ if not has_root_reactor or item.manifest in selected_manifests+ )+ for project in projects_by_repo[alias]:+ if project.has_unresolved_coordinate or not project.group_id or not project.artifact_id:+ continue+ producers[project.coordinate].append((alias, project))++ links: list[MavenWorkspaceLink] = []+ for source_alias in sorted(projects_by_repo):+ for source_project in projects_by_repo[source_alias]:+ for dependency in source_project.dependencies:+ if (+ dependency.optional+ or dependency.has_unresolved_structural_metadata+ or dependency.scope not in _STRUCTURAL_SCOPES+ or dependency.dependency_type == "pom"+ or dependency.has_unresolved_coordinate+ or not dependency.group_id+ or not dependency.artifact_id+ ):+ continue++ matches = producers.get(dependency.coordinate, [])+ if not matches:+ diagnostics.append(+ MavenWorkspaceDiagnostic(+ repo=source_alias,+ manifest=source_project.manifest,+ code="external_coordinate",+ detail=dependency.coordinate,+ )+ )+ continue+ if len(matches) != 1:+ locations = ",".join(+ f"{alias}:{project.manifest}" for alias, project in matches+ )+ diagnostics.append(+ MavenWorkspaceDiagnostic(+ repo=source_alias,+ manifest=source_project.manifest,+ code="ambiguous_coordinate",+ detail=f"{dependency.coordinate} -> {locations}",+ )+ )+ continue++ target_alias, target_project = matches[0]+ if target_alias == source_alias:+ continue+ links.append(+ MavenWorkspaceLink(+ source_repo=source_alias,+ target_repo=target_alias,+ source_manifest=source_project.manifest,+ target_manifest=target_project.manifest,+ target_package=dependency.coordinate,+ requested_version=dependency.version,+ scope=dependency.scope,+ )+ )++ return links, list(dict.fromkeys(diagnostics))diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.pyindex 7f18ea1a4..7661cacd1 100644--- a/packages/core/src/repowise/core/workspace/system_graph.py+++ b/packages/core/src/repowise/core/workspace/system_graph.py@@ -398,14 +398,17 @@ def build_system_graph(# 3. Package-dependency edges — the dependent repo imports the dependency.for dep in overlay.package_deps:source = builder.resolve_node(dep.source_repo, dep.source_manifest)- target = builder.resolve_node(dep.target_repo, None)+ target = builder.resolve_node(dep.target_repo, dep.target_manifest or None)+ reference = ":".join(+ part for part in (dep.kind, dep.target_package, dep.source_manifest) if part+ )builder.add_edge(source=source,target=target,kind="package",match_type="exact",confidence=1.0,- ref=f"{dep.kind}:{dep.source_manifest}",+ ref=reference,)# 4. Co-change edges — behavioral, undirected, lower trust.diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex 520002903..c33b49feb 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -29,6 +29,8 @@ class CrossRepoEnricher:self._co_changes: list[dict] = []self._total_co_changes: int = 0self._package_deps: list[dict] = []+ self._package_diagnostics: list[dict] = []+ self._total_package_diagnostics: int = 0self._repo_summaries: dict[str, dict] = {}self._cross_repo_analysis: dict = {"status": "unavailable",@@ -122,10 +124,20 @@ class CrossRepoEnricher:# above. Equal to len(self._co_changes) when nothing was dropped.self._total_co_changes = data.get("total_co_changes", len(self._co_changes))self._package_deps = data.get("package_deps", [])+ self._package_diagnostics = data.get("package_diagnostics", [])+ self._total_package_diagnostics = data.get(+ "total_package_diagnostics",+ len(self._package_diagnostics),+ )self._repo_summaries = data.get("repo_summaries", {})self._cross_repo_analysis = {"status": (- "partial" if self._total_co_changes > len(self._co_changes) else "available"+ "partial"+ if (+ self._total_co_changes > len(self._co_changes)+ or self._total_package_diagnostics > len(self._package_diagnostics)+ )+ else "available"),"contract_version": data.get("version", 1),"generated_at": data.get("generated_at"),@@ -137,6 +149,10 @@ class CrossRepoEnricher:"source_co_changes_total": self._total_co_changes,"source_co_changes_emitted": len(self._co_changes),"source_truncated": self._total_co_changes > len(self._co_changes),+ "package_diagnostics_total": self._total_package_diagnostics,+ "package_diagnostics_emitted": len(self._package_diagnostics),+ "package_diagnostics_truncated": self._total_package_diagnostics+ > len(self._package_diagnostics),}# Build co-change index: (repo, file) -> list of partner dicts@@ -193,6 +209,11 @@ class CrossRepoEnricher:"target_repo": tgt_repo,"source_manifest": pd.get("source_manifest", ""),"kind": pd.get("kind", ""),+ "target_package": pd.get("target_package", ""),+ "target_manifest": pd.get("target_manifest", ""),+ "requested_version": pd.get("requested_version"),+ "scope": pd.get("scope", ""),+ "resolution_basis": pd.get("resolution_basis", ""),})# Reverse: who depends on target_repo@@ -203,6 +224,11 @@ class CrossRepoEnricher:"target_repo": tgt_repo,"source_manifest": pd.get("source_manifest", ""),"kind": pd.get("kind", ""),+ "target_package": pd.get("target_package", ""),+ "target_manifest": pd.get("target_manifest", ""),+ "requested_version": pd.get("requested_version"),+ "scope": pd.get("scope", ""),+ "resolution_basis": pd.get("resolution_basis", ""),})if malformed_co_changes or malformed_package_deps:@@ -349,6 +375,8 @@ class CrossRepoEnricher:self._co_changes = []self._total_co_changes = 0self._package_deps = []+ self._package_diagnostics = []+ self._total_package_diagnostics = 0self._repo_summaries = {}self._cross_repo_analysis = {"status": "unavailable",@@ -394,7 +422,12 @@ class CrossRepoEnricher:@propertydef has_data(self) -> bool:"""True if any cross-repo signals are available."""- return bool(self._co_changes or self._package_deps or self._contract_links)+ return bool(+ self._co_changes+ or self._package_deps+ or self._package_diagnostics+ or self._contract_links+ )@propertydef has_contract_data(self) -> bool:@@ -522,7 +555,8 @@ class CrossRepoEnricher:def get_package_deps(self, repo_alias: str) -> list[dict]:"""Return package dependencies where *repo_alias* depends on other repos.- Each dict: ``{target_repo, source_manifest, kind}``.+ Maven rows also carry coordinate, version, scope, target manifest,+ and resolution-basis evidence."""return self._package_dep_index.get(repo_alias, [])@@ -556,6 +590,15 @@ class CrossRepoEnricher:return {"co_change_count": len(self._co_changes),"package_dep_count": len(self._package_deps),+ "package_diagnostic_count": self._total_package_diagnostics,+ "package_diagnostics_emitted": len(self._package_diagnostics),+ "package_diagnostic_codes": sorted(+ {+ diagnostic.get("code", "")+ for diagnostic in self._package_diagnostics+ if diagnostic.get("code")+ }+ ),"top_connections": top_connections,}diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 7b5c41ed3..b077646dd 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -41,6 +41,9 @@ class WorkspaceRepoEntry(BaseModel):class WorkspaceCrossRepoSummary(BaseModel):co_change_count: int = 0package_dep_count: int = 0+ package_diagnostic_count: int = 0+ package_diagnostics_emitted: int = 0+ package_diagnostic_codes: list[str] = []top_connections: list[dict] = []diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex bf6d4c44c..0996e2d81 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2835,6 +2835,9 @@ export interface WorkspaceContractsResponse {export interface WorkspaceCrossRepoSummary {co_change_count?: number;package_dep_count?: number;+ package_diagnostic_count?: number;+ package_diagnostics_emitted?: number;+ package_diagnostic_codes?: string[];top_connections?: Record<string, unknown>[];}diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex 8f609f027..aa52057ea 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -20,6 +20,9 @@ export interface RepoStats {export interface WorkspaceCrossRepoSummary {co_change_count: number;package_dep_count: number;+ package_diagnostic_count?: number;+ package_diagnostics_emitted?: number;+ package_diagnostic_codes?: string[];top_connections: Array<{ repos: string[]; edge_count: number }>;}@@ -72,6 +75,11 @@ export interface WorkspacePackageDepEntry {target_repo: string;target_package: string;kind: string;+ /** Maven evidence; absent for path-based ecosystems. */+ target_manifest?: string;+ requested_version?: string | null;+ scope?: string;+ resolution_basis?: string;}// ---------------------------------------------------------------------------diff --git a/packages/ui/__tests__/workspace/cross-repo-summary.test.tsx b/packages/ui/__tests__/workspace/cross-repo-summary.test.tsxnew file mode 100644index 000000000..76b404fe3--- /dev/null+++ b/packages/ui/__tests__/workspace/cross-repo-summary.test.tsx@@ -0,0 +1,25 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { CrossRepoSummary } from "../../src/workspace/cross-repo-summary.js";++describe("CrossRepoSummary", () => {+ it("makes bounded Maven non-matches visible", () => {+ render(+ <CrossRepoSummary+ crossRepo={{+ co_change_count: 0,+ package_dep_count: 0,+ package_diagnostic_count: 240,+ package_diagnostics_emitted: 200,+ package_diagnostic_codes: ["external_coordinate"],+ top_connections: [],+ }}+ contracts={null}+ />,+ );++ expect(+ screen.getByText("240 Maven non-matches; 200 retained"),+ ).toBeInTheDocument();+ });+});diff --git a/packages/ui/__tests__/workspace/package-deps-table.test.tsx b/packages/ui/__tests__/workspace/package-deps-table.test.tsxindex 986266120..b98cdcbf4 100644--- a/packages/ui/__tests__/workspace/package-deps-table.test.tsx+++ b/packages/ui/__tests__/workspace/package-deps-table.test.tsx@@ -1,4 +1,4 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import { render, screen } from "@testing-library/react";import type { WorkspacePackageDepEntry } from "@repowise-dev/types/workspace";import { PackageDepsTable } from "../../src/workspace/package-deps-table.js";@@ -42,4 +42,51 @@ describe("PackageDepsTable (virtualized)", () => {screen.getByText(/no cross-repo package dependencies/i),).toBeInTheDocument();});++ it("shows Maven coordinate and resolution evidence", () => {+ render(+ <PackageDepsTable+ deps={[+ dep({+ source_manifest: "app/pom.xml",+ target_package: "com.acme:shared",+ kind: "maven_coordinate",+ resolution_basis: "unique_workspace_coordinate",+ }),+ ]}+ />,+ );++ expect(screen.getByText("com.acme:shared")).toBeInTheDocument();+ expect(screen.getByText("maven_coordinate")).toBeInTheDocument();+ expect(screen.getByText("unique_workspace_coordinate")).toBeInTheDocument();+ });++ it("keeps distinct Maven artifacts as distinct virtual rows", () => {+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ render(+ <PackageDepsTable+ deps={[+ dep({+ source_manifest: "app/pom.xml",+ target_package: "com.acme:shared-one",+ target_manifest: "shared-one/pom.xml",+ kind: "maven_coordinate",+ }),+ dep({+ source_manifest: "app/pom.xml",+ target_package: "com.acme:shared-two",+ target_manifest: "shared-two/pom.xml",+ kind: "maven_coordinate",+ }),+ ]}+ />,+ );++ const warnings = consoleError.mock.calls.flat().join(" ");+ consoleError.mockRestore();+ expect(screen.getByText("com.acme:shared-one")).toBeInTheDocument();+ expect(screen.getByText("com.acme:shared-two")).toBeInTheDocument();+ expect(warnings).not.toContain("same key");+ });});diff --git a/packages/ui/src/workspace/cross-repo-summary.tsx b/packages/ui/src/workspace/cross-repo-summary.tsxindex d5f74ee08..a5d909cb8 100644--- a/packages/ui/src/workspace/cross-repo-summary.tsx+++ b/packages/ui/src/workspace/cross-repo-summary.tsx@@ -18,6 +18,9 @@ export function CrossRepoSummary({ crossRepo, contracts }: CrossRepoSummaryProps.map(([k, v]) => `${v} ${k}`).join(", "): undefined;+ const packageDescription = crossRepo?.package_diagnostic_count+ ? `${crossRepo.package_diagnostic_count} Maven non-matches; ${crossRepo.package_diagnostics_emitted ?? 0} retained`+ : undefined;return (<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">@@ -29,6 +32,7 @@ export function CrossRepoSummary({ crossRepo, contracts }: CrossRepoSummaryProps<MetricCardlabel="Package Deps"value={crossRepo?.package_dep_count ?? 0}+ {...(packageDescription ? { description: packageDescription } : {})}icon={<Package className="h-4 w-4 text-[var(--color-accent-secondary)]" />}/><MetricCarddiff --git a/packages/ui/src/workspace/package-deps-table.tsx b/packages/ui/src/workspace/package-deps-table.tsxindex 1f7274105..a6fe3c088 100644--- a/packages/ui/src/workspace/package-deps-table.tsx+++ b/packages/ui/src/workspace/package-deps-table.tsx@@ -44,6 +44,14 @@ export function PackageDepsTable({ deps }: PackageDepsTableProps) {<Badge variant="default" className="text-xs">{d.target_repo}</Badge>+ {d.target_package ? (+ <span+ className="mt-1 block max-w-[260px] truncate font-mono text-xs text-[var(--color-text-secondary)]"+ title={d.target_package}+ >+ {d.target_package}+ </span>+ ) : null}</td><tdclassName={`px-3 py-2 text-left font-mono text-xs text-[var(--color-text-secondary)] max-w-[280px] ${HIDE_BELOW_MD}`}@@ -55,7 +63,12 @@ export function PackageDepsTable({ deps }: PackageDepsTableProps) {<tdclassName={`px-3 py-2 text-left text-xs text-[var(--color-text-secondary)] ${HIDE_BELOW_MD}`}>- {d.kind}+ <span>{d.kind}</span>+ {d.resolution_basis ? (+ <span className="block text-[var(--color-text-tertiary)]">+ {d.resolution_basis}+ </span>+ ) : null}</td></tr>);@@ -64,7 +77,7 @@ export function PackageDepsTable({ deps }: PackageDepsTableProps) {<VirtualizedTable<WorkspacePackageDepEntry>rows={deps}rowKey={(d) =>- `${d.source_repo}|${d.target_repo}|${d.source_manifest}|${d.kind}`+ `${d.source_repo}|${d.target_repo}|${d.source_manifest}|${d.kind}|${d.target_package ?? ""}|${d.target_manifest ?? ""}`}header={header}renderRow={renderRow}diff --git a/tests/unit/ingestion/test_maven_reader.py b/tests/unit/ingestion/test_maven_reader.pyindex fa6ea79f8..642e51921 100644--- a/tests/unit/ingestion/test_maven_reader.py+++ b/tests/unit/ingestion/test_maven_reader.py@@ -4,6 +4,10 @@ from __future__ import annotationsfrom pathlib import Path+from repowise.core.ingestion.external_systems import (+ extract_external_systems,+ maven_model,+)from repowise.core.ingestion.external_systems.maven import parse@@ -138,3 +142,67 @@ class TestMavenParse:records = parse(pom, tmp_path)assert len(records) == 1assert records[0].version == "2.0.0"++ def test_child_project_properties_use_child_builtins(self, tmp_path: Path) -> None:+ parent_dir = tmp_path / "parent"+ child_dir = tmp_path / "child"+ parent_dir.mkdir()+ child_dir.mkdir()+ (parent_dir / "pom.xml").write_text(+ """<project><groupId>com.example</groupId>+ <artifactId>parent</artifactId><version>1.0.0</version></project>""",+ encoding="utf-8",+ )+ child = child_dir / "pom.xml"+ child.write_text(+ """<project>+ <parent><groupId>com.example</groupId><artifactId>parent</artifactId>+ <version>1.0.0</version><relativePath>../parent/pom.xml</relativePath></parent>+ <artifactId>child</artifactId><version>2.0.0</version>+ <properties><dependency.version>${project.version}</dependency.version></properties>+ <dependencies><dependency><groupId>com.example</groupId><artifactId>shared</artifactId>+ <version>${dependency.version}</version></dependency></dependencies>+</project>""",+ encoding="utf-8",+ )++ records = parse(child, tmp_path)++ assert len(records) == 1+ assert records[0].version == "2.0.0"++ def test_external_extraction_parses_each_pom_once(+ self,+ tmp_path: Path,+ monkeypatch,+ ) -> None:+ root = _pom(+ tmp_path,+ """<project><groupId>com.example</groupId><artifactId>parent</artifactId>+ <version>1</version><packaging>pom</packaging>+ <modules><module>child</module></modules></project>""",+ )+ child = tmp_path / "child" / "pom.xml"+ child.parent.mkdir()+ child.write_text(+ """<project><parent><groupId>com.example</groupId><artifactId>parent</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>child</artifactId><dependencies><dependency>+ <groupId>org.example</groupId><artifactId>library</artifactId><version>2</version>+ </dependency></dependencies></project>""",+ encoding="utf-8",+ )+ parsed: list[Path] = []+ real_parse = maven_model.ET.parse++ def counting_parse(path):+ parsed.append(Path(path))+ return real_parse(path)++ monkeypatch.setattr(maven_model.ET, "parse", counting_parse)++ records = extract_external_systems(tmp_path, [root, child])++ assert [record.name for record in records] == ["org.example:library"]+ assert len(parsed) == 2+ assert set(parsed) == {root.resolve(), child.resolve()}diff --git a/tests/unit/server/test_mcp_workspace.py b/tests/unit/server/test_mcp_workspace.pyindex 3c12a974d..08315e640 100644--- a/tests/unit/server/test_mcp_workspace.py+++ b/tests/unit/server/test_mcp_workspace.py@@ -801,6 +801,61 @@ def test_enricher_get_cross_repo_summary(enricher_data):assert len(summary["top_connections"]) >= 1+def test_enricher_serves_maven_evidence_and_bounded_diagnostics(tmp_path):+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher++ path = tmp_path / "cross_repo_edges.json"+ path.write_text(+ json.dumps(+ {+ "version": 2,+ "package_deps": [+ {+ "source_repo": "consumer",+ "target_repo": "producer",+ "source_manifest": "app/pom.xml",+ "target_manifest": "shared/pom.xml",+ "target_package": "com.acme:shared",+ "requested_version": "1.2.0",+ "scope": "compile",+ "resolution_basis": "unique_workspace_coordinate",+ "kind": "maven_coordinate",+ }+ ],+ "package_diagnostics": [+ {+ "repo": "consumer",+ "source_manifest": "pom.xml",+ "code": "external_coordinate",+ "detail": "org.example:outside",+ }+ ],+ "total_package_diagnostics": 4,+ }+ ),+ encoding="utf-8",+ )++ enricher = CrossRepoEnricher(path)++ assert enricher.get_package_deps("consumer") == [+ {+ "target_repo": "producer",+ "source_manifest": "app/pom.xml",+ "kind": "maven_coordinate",+ "target_package": "com.acme:shared",+ "target_manifest": "shared/pom.xml",+ "requested_version": "1.2.0",+ "scope": "compile",+ "resolution_basis": "unique_workspace_coordinate",+ }+ ]+ summary = enricher.get_cross_repo_summary()+ assert summary["package_diagnostic_count"] == 4+ assert summary["package_diagnostics_emitted"] == 1+ assert summary["package_diagnostic_codes"] == ["external_coordinate"]++# ---------------------------------------------------------------------------# MCP tool enrichment with cross-repo data# ---------------------------------------------------------------------------diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex d00384faa..18f636f50 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -329,6 +329,9 @@ class TestGetWorkspace:data = resp.json()assert data["cross_repo_summary"]["co_change_count"] == 1assert data["cross_repo_summary"]["package_dep_count"] == 1+ assert data["cross_repo_summary"]["package_diagnostic_count"] == 0+ assert data["cross_repo_summary"]["package_diagnostics_emitted"] == 0+ assert data["cross_repo_summary"]["package_diagnostic_codes"] == []@pytest.mark.asyncioasync def test_contract_summary(self, tmp_path: Path) -> None:diff --git a/tests/unit/workspace/test_dotnet_workspace.py b/tests/unit/workspace/test_dotnet_workspace.pyindex a8550f6d6..1bf41f401 100644--- a/tests/unit/workspace/test_dotnet_workspace.py+++ b/tests/unit/workspace/test_dotnet_workspace.py@@ -53,7 +53,9 @@ class TestAspNetHttpExtraction:))contracts = HttpExtractor().extract(tmp_path, repo_alias="api")- provider_paths = {(c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"}+ provider_paths = {+ (c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"+ }assert ("GET", "/api/users/{param}") in provider_pathsassert ("POST", "/api/users") in provider_paths@@ -155,8 +157,9 @@ class TestGrpcDotnetExtraction:# ----------------------------------------------------------------------------def _csproj(deps: list[str] = (), assembly_name: str | None = None,- packages: list[str] = ()) -> str:+def _csproj(+ deps: list[str] = (), assembly_name: str | None = None, packages: list[str] = ()+) -> str:refs = "\n".join(f' <ProjectReference Include="{p}" />' for p in deps)pkgs = "\n".join(f' <PackageReference Include="{p}" Version="1.0.0" />' for p in packages)asm = f"<AssemblyName>{assembly_name}</AssemblyName>" if assembly_name else ""@@ -195,9 +198,7 @@ class TestScanCsproj:)deps = _scan_csproj(repos["api"], repos, alias="api")assert any(- d.source_repo == "api"- and d.target_repo == "shared"- and d.kind == "dotnet_project_ref"+ d.source_repo == "api" and d.target_repo == "shared" and d.kind == "dotnet_project_ref"for d in deps)@@ -205,9 +206,7 @@ class TestScanCsproj:repos = self._two_repo_workspace(tmp_path)# api consumes the published Acme.Common NuGet package whose# AssemblyName lives in `shared-libs`.- (repos["api"] / "src" / "Api" / "Api.csproj").write_text(- _csproj(packages=["Acme.Common"])- )+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))deps = _scan_csproj(repos["api"], repos, alias="api")assert any(d.source_repo == "api"@@ -244,28 +243,40 @@ class TestScanCsproj:to be found once."""repos = self._two_repo_workspace(tmp_path)- (repos["api"] / "src" / "Api" / "Api.csproj").write_text(- _csproj(packages=["Acme.Common"])- )+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))walked: list[Path] = []- real_iter_glob = fs_walk.iter_glob+ real_walk_repo = fs_walk.walk_repo- def counting_iter_glob(root, patterns, **kwargs):- if patterns == "*.csproj":- walked.append(Path(root))- return real_iter_glob(root, patterns, **kwargs)+ def counting_walk_repo(root, **kwargs):+ walked.append(Path(root))+ return real_walk_repo(root, **kwargs)- monkeypatch.setattr(fs_walk, "iter_glob", counting_iter_glob)+ monkeypatch.setattr(fs_walk, "walk_repo", counting_walk_repo)deps = detect_package_dependencies(repos)assert len(walked) == len(repos), (- f"expected one *.csproj walk per repo ({len(repos)}), got {len(walked)}: {walked}"+ f"expected one project-manifest walk per repo ({len(repos)}), "+ f"got {len(walked)}: {walked}")# The saving must not have cost us the dependency itself.assert any(d.kind == "dotnet_nuget_internal" for d in deps)+ def test_shared_walk_ignores_csproj_files_in_packages_cache(self, tmp_path: Path) -> None:+ repos = self._two_repo_workspace(tmp_path)+ cached = repos["api"] / "packages" / "cached"+ cached.mkdir(parents=True)+ (cached / "Cached.csproj").write_text(+ _csproj(assembly_name="Acme.Cached", packages=["Acme.Common"])+ )++ index = _index_csproj_files(repos)+ deps = detect_package_dependencies(repos)++ assert all("packages" not in path.parts for path in index.by_repo["api"])+ assert all(dep.source_manifest != "packages/cached/Cached.csproj" for dep in deps)+def test_shared_index_matches_standalone_scan(self, tmp_path: Path) -> None:"""A shared index must produce exactly what an isolated scan produces."""repos = self._two_repo_workspace(tmp_path)@@ -294,12 +305,8 @@ class TestScanCsproj:repos = self._two_repo_workspace(tmp_path)rival = tmp_path / "rival-libs"(rival / "src" / "Common").mkdir(parents=True)- (rival / "src" / "Common" / "Rival.csproj").write_text(- _csproj(assembly_name="Acme.Common")- )- (repos["api"] / "src" / "Api" / "Api.csproj").write_text(- _csproj(packages=["Acme.Common"])- )+ (rival / "src" / "Common" / "Rival.csproj").write_text(_csproj(assembly_name="Acme.Common"))+ (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))# "shared" then "rival": last one to claim the name owns it.ordered = {"api": repos["api"], "shared": repos["shared"], "rival": rival}@@ -316,12 +323,8 @@ class TestScanCsproj:repos = self._two_repo_workspace(tmp_path)other = tmp_path / "other-api"(other / "src" / "Api").mkdir(parents=True)- (other / "src" / "Api" / "Other.csproj").write_text(- _csproj(packages=["Acme.Common"])- )+ (other / "src" / "Api" / "Other.csproj").write_text(_csproj(packages=["Acme.Common"]))# repo_paths["api"] holds no .csproj at all; the scanned tree does.- deps = _scan_csproj(- other, repos, alias="api", csproj_index=_index_csproj_files(repos)- )+ deps = _scan_csproj(other, repos, alias="api", csproj_index=_index_csproj_files(repos))assert [d.target_repo for d in deps] == ["shared"]assert deps[0].source_manifest == "src/Api/Other.csproj"diff --git a/tests/unit/workspace/test_maven_workspace.py b/tests/unit/workspace/test_maven_workspace.pynew file mode 100644index 000000000..8c437c53d--- /dev/null+++ b/tests/unit/workspace/test_maven_workspace.py@@ -0,0 +1,746 @@+"""Cross-repository Maven coordinate detection and evidence tests."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from repowise.core.ingestion.external_systems.maven_model import load_maven_reactor+from repowise.core.workspace.cross_repo import (+ CrossRepoOverlay,+ CrossRepoPackageDep,+ CrossRepoPackageDiagnostic,+ detect_package_dependencies,+ detect_package_dependencies_with_diagnostics,+ load_overlay,+ save_overlay,+)+++def _write(repo: Path, relative: str, body: str) -> Path:+ path = repo / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ return path+++def _project(+ group: str,+ artifact: str,+ version: str = "1.0.0",+ dependencies: str = "",+) -> str:+ return f"""<project>+ <groupId>{group}</groupId>+ <artifactId>{artifact}</artifactId>+ <version>{version}</version>+ {dependencies}+</project>"""+++def _dependency(+ group: str,+ artifact: str,+ *,+ version: str = "1.0.0",+ scope: str = "",+ optional: bool = False,+) -> str:+ scope_xml = f"<scope>{scope}</scope>" if scope else ""+ optional_xml = "<optional>true</optional>" if optional else ""+ return f"""<dependency>+ <groupId>{group}</groupId><artifactId>{artifact}</artifactId>+ <version>{version}</version>{scope_xml}{optional_xml}+ </dependency>"""+++def test_reactor_parent_properties_create_evidenced_package_edge(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(+ producer,+ "pom.xml",+ """<project>+ <groupId>com.acme</groupId><artifactId>producer-reactor</artifactId>+ <version>${revision}</version><packaging>pom</packaging>+ <properties><revision>1.4.0</revision></properties>+ <modules><module>shared-lib</module></modules>+</project>""",+ )+ _write(+ producer,+ "shared-lib/pom.xml",+ """<project>+ <parent>+ <groupId>com.acme</groupId><artifactId>producer-reactor</artifactId>+ <version>${revision}</version><relativePath>../pom.xml</relativePath>+ </parent>+ <artifactId>shared-lib</artifactId>+</project>""",+ )+ _write(+ consumer,+ "pom.xml",+ f"""<project>+ <groupId>com.acme</groupId><artifactId>consumer</artifactId><version>1</version>+ <properties><shared.version>1.4.0</shared.version></properties>+ <dependencies>+ {_dependency("com.acme", "shared-lib", version="${shared.version}")}+ {_dependency("junit", "junit", scope="test")}+ {_dependency("com.acme", "optional-tool", optional=True)}+ </dependencies>+ <profiles><profile><id>inactive</id><dependencies>+ {_dependency("com.acme", "profile-only")}+ </dependencies></profile></profiles>+</project>""",+ )++ deps, diagnostics, total = detect_package_dependencies_with_diagnostics(+ {"producer": producer, "consumer": consumer}+ )++ assert len(deps) == 1+ dep = deps[0]+ assert dep.source_repo == "consumer"+ assert dep.target_repo == "producer"+ assert dep.source_manifest == "pom.xml"+ assert dep.target_manifest == "shared-lib/pom.xml"+ assert dep.kind == "maven_coordinate"+ assert dep.target_package == "com.acme:shared-lib"+ assert dep.requested_version == "1.4.0"+ assert dep.scope == "compile"+ assert dep.resolution_basis == "unique_workspace_coordinate"+ assert diagnostics == []+ assert total == 0+ reversed_deps = detect_package_dependencies({"consumer": consumer, "producer": producer})+ assert reversed_deps == deps+++def test_inherited_dependency_management_resolves_version(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared", "2.1.0"))+ _write(+ consumer,+ "pom.xml",+ """<project>+ <groupId>com.acme</groupId><artifactId>consumer-parent</artifactId>+ <version>1</version><packaging>pom</packaging>+ <dependencyManagement><dependencies><dependency>+ <groupId>com.acme</groupId><artifactId>shared</artifactId><version>2.1.0</version>+ </dependency></dependencies></dependencyManagement>+ <modules><module>app</module></modules>+</project>""",+ )+ _write(+ consumer,+ "app/pom.xml",+ """<project>+ <parent><groupId>com.acme</groupId><artifactId>consumer-parent</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>app</artifactId>+ <dependencies><dependency>+ <groupId>com.acme</groupId><artifactId>shared</artifactId>+ </dependency></dependencies>+</project>""",+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert len(deps) == 1+ assert deps[0].requested_version == "2.1.0"+ assert deps[0].source_manifest == "app/pom.xml"+++def test_parent_artifact_builtin_resolves_dependency_coordinate(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("org.openmrs.module", "module-api"))+ _write(+ consumer,+ "pom.xml",+ """<project><groupId>org.openmrs.module</groupId><artifactId>module</artifactId>+ <version>1</version><packaging>pom</packaging><modules><module>omod</module></modules></project>""",+ )+ _write(+ consumer,+ "omod/pom.xml",+ """<project><parent><groupId>org.openmrs.module</groupId><artifactId>module</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent><artifactId>omod</artifactId>+ <dependencies><dependency><groupId>org.openmrs.module</groupId>+ <artifactId>${project.parent.artifactId}-api</artifactId><version>1</version>+ </dependency></dependencies></project>""",+ )++ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics(+ {"producer": producer, "consumer": consumer}+ )++ assert [dep.target_package for dep in deps] == ["org.openmrs.module:module-api"]+ assert "unresolved_dependency_coordinate" not in {diagnostic.code for diagnostic in diagnostics}+++def test_inherited_dependency_is_attributed_to_each_effective_consumer(+ tmp_path: Path,+) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ f"""<project><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><packaging>pom</packaging>+ <modules><module>one</module><module>two</module></modules>+ <dependencies>{_dependency("com.acme", "shared")}</dependencies>+</project>""",+ )+ for child in ("one", "two"):+ _write(+ consumer,+ f"{child}/pom.xml",+ f"""<project><parent><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>{child}</artifactId></project>""",+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert [dep.source_manifest for dep in deps] == [+ "one/pom.xml",+ "pom.xml",+ "two/pom.xml",+ ]+++def test_child_dependency_override_replaces_inherited_dependency(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ f"""<project><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><packaging>pom</packaging><modules><module>app</module></modules>+ <dependencies>{_dependency("com.acme", "shared")}</dependencies></project>""",+ )+ _write(+ consumer,+ "app/pom.xml",+ f"""<project><parent><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>app</artifactId>+ <dependencies>{_dependency("com.acme", "shared", scope="test")}</dependencies>+</project>""",+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert [dep.source_manifest for dep in deps] == ["pom.xml"]+++def test_inherited_dependency_expressions_use_child_properties(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared", "2.1.0"))+ inherited = """<dependency><groupId>${dep.group}</groupId><artifactId>shared</artifactId>+ <version>${dep.version}</version><scope>${dep.scope}</scope>+ <optional>${dep.optional}</optional><type>${dep.type}</type></dependency>"""+ _write(+ consumer,+ "pom.xml",+ f"""<project><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><packaging>pom</packaging>+ <properties><dep.group>com.acme</dep.group><dep.version>1.0.0</dep.version>+ <dep.scope>compile</dep.scope><dep.optional>false</dep.optional><dep.type>jar</dep.type></properties>+ <modules><module>included</module><module>optional</module><module>bom</module></modules>+ <dependencies>{inherited}</dependencies></project>""",+ )+ child_template = """<project><parent><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>{artifact}</artifactId><properties>{properties}</properties></project>"""+ _write(+ consumer,+ "included/pom.xml",+ child_template.format(+ artifact="included",+ properties="<dep.version>2.1.0</dep.version><dep.scope>runtime</dep.scope>",+ ),+ )+ _write(+ consumer,+ "optional/pom.xml",+ child_template.format(+ artifact="optional",+ properties="<dep.optional>true</dep.optional>",+ ),+ )+ _write(+ consumer,+ "bom/pom.xml",+ child_template.format(artifact="bom", properties="<dep.type>pom</dep.type>"),+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ by_manifest = {dep.source_manifest: dep for dep in deps}+ assert set(by_manifest) == {"included/pom.xml", "pom.xml"}+ assert by_manifest["included/pom.xml"].requested_version == "2.1.0"+ assert by_manifest["included/pom.xml"].scope == "runtime"++[email protected]("metadata", ["scope", "optional", "type", "classifier"])+def test_unresolved_structural_metadata_refuses_edge(tmp_path: Path, metadata: str) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ f"""<project><groupId>com.acme</groupId><artifactId>consumer</artifactId>+ <version>1</version><dependencies><dependency><groupId>com.acme</groupId>+ <artifactId>shared</artifactId><version>1</version>+ <{metadata}>${{missing.{metadata}}}</{metadata}></dependency></dependencies></project>""",+ )++ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics(+ {"producer": producer, "consumer": consumer}+ )++ assert deps == []+ assert "unresolved_dependency_metadata" in {diagnostic.code for diagnostic in diagnostics}+++def test_classified_child_dependency_does_not_override_inherited_jar(+ tmp_path: Path,+) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ f"""<project><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><packaging>pom</packaging><modules><module>app</module></modules>+ <dependencies>{_dependency("com.acme", "shared")}</dependencies></project>""",+ )+ _write(+ consumer,+ "app/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent><artifactId>app</artifactId>+ <dependencies><dependency><groupId>com.acme</groupId><artifactId>shared</artifactId>+ <version>1</version><classifier>tests</classifier><scope>test</scope></dependency></dependencies>+</project>""",+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert [dep.source_manifest for dep in deps] == ["app/pom.xml", "pom.xml"]+++def test_duplicate_producer_coordinate_is_ambiguous(tmp_path: Path) -> None:+ first = tmp_path / "first"+ second = tmp_path / "second"+ consumer = tmp_path / "consumer"+ _write(first, "pom.xml", _project("com.acme", "shared"))+ _write(second, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=f"<dependencies>{_dependency('com.acme', 'shared')}</dependencies>",+ ),+ )++ deps, diagnostics, total = detect_package_dependencies_with_diagnostics(+ {"first": first, "second": second, "consumer": consumer}+ )++ assert deps == []+ assert total == 1+ assert diagnostics[0].code == "ambiguous_coordinate"+ assert "first:pom.xml" in diagnostics[0].detail+ assert "second:pom.xml" in diagnostics[0].detail+++ ("scope", "optional", "expected"),+ [+ ("", False, True),+ ("runtime", False, True),+ ("test", False, False),+ ("provided", False, False),+ ("system", False, False),+ ("compile", True, False),+ ],+)+def test_only_production_scopes_create_edges(+ tmp_path: Path,+ scope: str,+ optional: bool,+ expected: bool,+) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=(+ "<dependencies>"+ + _dependency("com.acme", "shared", scope=scope, optional=optional)+ + "</dependencies>"+ ),+ ),+ )++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert bool(deps) is expected+++def test_distinct_consumer_manifests_keep_distinct_evidence(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "shared"))+ _write(+ consumer,+ "pom.xml",+ """<project><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><packaging>pom</packaging>+ <modules><module>one</module><module>two</module></modules></project>""",+ )++ def child(artifact: str) -> str:+ return f"""<project>+ <parent><groupId>com.acme</groupId><artifactId>apps</artifactId>+ <version>1</version><relativePath>../pom.xml</relativePath></parent>+ <artifactId>{artifact}</artifactId><dependencies>+ {_dependency("com.acme", "shared")}+ </dependencies></project>"""++ _write(consumer, "one/pom.xml", child("one"))+ _write(consumer, "two/pom.xml", child("two"))++ deps = detect_package_dependencies({"producer": producer, "consumer": consumer})++ assert [dep.source_manifest for dep in deps] == ["one/pom.xml", "two/pom.xml"]+++def test_root_reactor_ignores_unlisted_nested_fixture_poms(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", _project("com.acme", "real-project"))+ _write(+ producer,+ "fixtures/pom.xml",+ _project("com.acme", "fixture-only"),+ )+ _write(+ consumer,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=(+ "<dependencies>" + _dependency("com.acme", "fixture-only") + "</dependencies>"+ ),+ ),+ )++ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics(+ {"producer": producer, "consumer": consumer}+ )++ assert deps == []+ assert [diagnostic.code for diagnostic in diagnostics] == ["external_coordinate"]+++def test_malformed_root_does_not_promote_nested_fixture_pom(tmp_path: Path) -> None:+ producer = tmp_path / "producer"+ consumer = tmp_path / "consumer"+ _write(producer, "pom.xml", "<project>")+ _write(+ producer,+ "fixtures/pom.xml",+ _project("com.acme", "fixture-only"),+ )+ _write(+ consumer,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=(+ "<dependencies>" + _dependency("com.acme", "fixture-only") + "</dependencies>"+ ),+ ),+ )++ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics(+ {"producer": producer, "consumer": consumer}+ )++ assert deps == []+ assert {diagnostic.code for diagnostic in diagnostics} == {+ "external_coordinate",+ "malformed_pom",+ }+++def test_malformed_and_unmatched_poms_are_diagnostic_not_edges(tmp_path: Path) -> None:+ broken = tmp_path / "broken"+ consumer = tmp_path / "consumer"+ _write(broken, "pom.xml", "<project>")+ _write(+ consumer,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=f"<dependencies>{_dependency('com.vendor', 'external')}</dependencies>",+ ),+ )++ deps, diagnostics, total = detect_package_dependencies_with_diagnostics(+ {"broken": broken, "consumer": consumer}+ )++ assert deps == []+ assert total == 2+ assert {diagnostic.code for diagnostic in diagnostics} == {+ "external_coordinate",+ "malformed_pom",+ }+++def test_unresolved_properties_and_modules_are_diagnostic(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ _write(+ repo,+ "pom.xml",+ """<project>+ <groupId>com.acme</groupId><artifactId>root</artifactId>+ <version>${missing.version}</version>+ <modules><module>${missing.module}</module></modules>+ <dependencies><dependency>+ <groupId>${missing.group}</groupId><artifactId>shared</artifactId>+ <version>${missing.dependency.version}</version>+ </dependency></dependencies>+</project>""",+ )++ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert deps == []+ assert {diagnostic.code for diagnostic in diagnostics} >= {+ "unresolved_project_version",+ "unresolved_module",+ "unresolved_dependency_coordinate",+ "unresolved_dependency_version",+ }+++def test_local_parent_cycle_is_bounded_and_diagnostic(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ _write(+ repo,+ "one/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>two</artifactId>+ <version>1</version><relativePath>../two/pom.xml</relativePath></parent>+ <artifactId>one</artifactId></project>""",+ )+ _write(+ repo,+ "two/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>one</artifactId>+ <version>1</version><relativePath>../one/pom.xml</relativePath></parent>+ <artifactId>two</artifactId></project>""",+ )++ manifests = sorted(repo.rglob("pom.xml"))+ reactor = load_maven_reactor(repo, manifests)+ deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert deps == []+ assert reactor.projects == ()+ assert "parent_cycle" in {diagnostic.code for diagnostic in diagnostics}+++def test_declared_failed_module_keeps_parent_failure_diagnostic(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ _write(+ repo,+ "pom.xml",+ """<project><groupId>com.acme</groupId><artifactId>root</artifactId><version>1</version>+ <packaging>pom</packaging><modules><module>child</module></modules></project>""",+ )+ _write(+ repo,+ "child/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>one</artifactId>+ <version>1</version><relativePath>../parents/one/pom.xml</relativePath></parent>+ <artifactId>child</artifactId></project>""",+ )+ _write(+ repo,+ "parents/one/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>two</artifactId>+ <version>1</version><relativePath>../two/pom.xml</relativePath></parent>+ <groupId>com.acme</groupId><artifactId>one</artifactId><version>1</version></project>""",+ )+ _write(+ repo,+ "parents/two/pom.xml",+ """<project><parent><groupId>com.acme</groupId><artifactId>one</artifactId>+ <version>1</version><relativePath>../one/pom.xml</relativePath></parent>+ <groupId>com.acme</groupId><artifactId>two</artifactId><version>1</version></project>""",+ )++ _deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert any(+ diagnostic.source_manifest == "child/pom.xml" and diagnostic.code == "parent_cycle"+ for diagnostic in diagnostics+ )+++def test_mismatched_local_parent_is_not_used(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ _write(+ repo,+ "parent/pom.xml",+ _project("com.acme", "actual-parent", "1"),+ )+ _write(+ repo,+ "child/pom.xml",+ """<project><parent><groupId>com.acme</groupId>+ <artifactId>different-parent</artifactId><version>1</version>+ <relativePath>../parent/pom.xml</relativePath></parent>+ <artifactId>child</artifactId></project>""",+ )++ _deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert "parent_coordinate_mismatch" in {diagnostic.code for diagnostic in diagnostics}+++def test_parent_depth_is_bounded(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ for index in range(18):+ parent = ""+ if index < 17:+ parent = f"""<parent><groupId>com.acme</groupId>+ <artifactId>level-{index + 1}</artifactId><version>1</version>+ <relativePath>../level-{index + 1}/pom.xml</relativePath></parent>"""+ _write(+ repo,+ f"level-{index}/pom.xml",+ f"""<project>{parent}<groupId>com.acme</groupId>+ <artifactId>level-{index}</artifactId><version>1</version></project>""",+ )++ manifests = sorted(repo.rglob("pom.xml"))+ reactor = load_maven_reactor(repo, manifests)+ _deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert reactor.projects == ()+ assert "parent_depth_exceeded" in {diagnostic.code for diagnostic in diagnostics}+++def test_external_parent_is_explicitly_diagnostic(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ _write(+ repo,+ "pom.xml",+ """<project><parent><groupId>org.example</groupId><artifactId>remote-parent</artifactId>+ <version>1</version><relativePath/></parent><artifactId>child</artifactId></project>""",+ )++ _deps, diagnostics, _total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert "external_parent_unsupported" in {diagnostic.code for diagnostic in diagnostics}+++def test_external_diagnostics_are_capped_with_honest_total(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ dependencies = "".join(_dependency("org.example", f"library-{index}") for index in range(230))+ _write(+ repo,+ "pom.xml",+ _project(+ "com.acme",+ "consumer",+ dependencies=f"<dependencies>{dependencies}</dependencies>",+ ),+ )++ _deps, diagnostics, total = detect_package_dependencies_with_diagnostics({"repo": repo})++ assert len(diagnostics) == 200+ assert total == 230+ assert {diagnostic.code for diagnostic in diagnostics} == {"external_coordinate"}+++def test_overlay_round_trip_preserves_maven_evidence_and_diagnostics(+ tmp_path: Path,+) -> None:+ overlay = CrossRepoOverlay(+ package_deps=[+ CrossRepoPackageDep(+ source_repo="consumer",+ target_repo="producer",+ source_manifest="app/pom.xml",+ kind="maven_coordinate",+ target_package="com.acme:shared",+ target_manifest="shared/pom.xml",+ requested_version="1.2.0",+ scope="runtime",+ resolution_basis="unique_workspace_coordinate",+ )+ ],+ package_diagnostics=[+ CrossRepoPackageDiagnostic(+ repo="consumer",+ source_manifest="pom.xml",+ code="external_coordinate",+ detail="org.example:outside",+ )+ ],+ total_package_diagnostics=3,+ )++ save_overlay(overlay, tmp_path)+ restored = load_overlay(tmp_path)++ assert restored is not None+ assert restored.package_deps == overlay.package_deps+ assert restored.package_diagnostics == overlay.package_diagnostics+ assert restored.total_package_diagnostics == 3+++def test_path_dependency_uses_separator_aware_repo_containment(tmp_path: Path) -> None:+ app = tmp_path / "app"+ lib = tmp_path / "lib"+ lib_old = tmp_path / "lib-old"+ app.mkdir()+ lib.mkdir()+ lib_old.mkdir()+ (app / "package.json").write_text(+ json.dumps({"dependencies": {"legacy": "file:../lib-old"}}),+ encoding="utf-8",+ )++ deps = detect_package_dependencies({"app": app, "lib": lib, "lib-old": lib_old})++ assert len(deps) == 1+ assert deps[0].target_repo == "lib-old"diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.pyindex abfb679e1..cf835875d 100644--- a/tests/unit/workspace/test_system_graph.py+++ b/tests/unit/workspace/test_system_graph.py@@ -209,6 +209,29 @@ def test_package_dep_edge_points_dependent_to_dependency():assert edge.confidence == 1.0+def test_maven_package_edge_keeps_coordinate_evidence():+ overlay = CrossRepoOverlay(+ package_deps=[+ CrossRepoPackageDep(+ source_repo="consumer",+ target_repo="producer",+ source_manifest="app/pom.xml",+ target_manifest="shared/pom.xml",+ target_package="com.acme:shared",+ requested_version="1.2.0",+ scope="compile",+ resolution_basis="unique_workspace_coordinate",+ kind="maven_coordinate",+ )+ ]+ )++ graph = build_system_graph([], [], overlay, {})+ edge = _edges_by_key(graph)[("consumer", "producer", "package")]++ assert edge.contract_refs == ["maven_coordinate:com.acme:shared:app/pom.xml"]++def test_cochange_edge_is_behavioral_and_undirected():overlay = CrossRepoOverlay(co_changes=[