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): find which repo serves a host from compose, Kubernetes, Spring and Aspire config (#4495)
Raghav Chamadiya445af5548704
diff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.mdindex e8dcf83e4..bfb13b80b 100644--- a/docs/reference/WORKSPACE_CONTRACTS.md+++ b/docs/reference/WORKSPACE_CONTRACTS.md@@ -39,6 +39,7 @@ follows from the strategy.| 1.0 | `unique_path` | exact | The consumer's base is unread and one service serves the path || 0.6 | `ambiguous_path` | candidate | The base is unread and several services serve the path; linked to each || 0.6 | `prefix_stripped` | candidate | Matched only after stripping mount, version or base prefixes |+| 0.5 | `host_only` | candidate | The host names a workspace service, but no route there serves the path; a service-level edge || 1.0 | `manual` | manual | Declared in the workspace config |A new dialect picks an existing origin, not a number. A system-graph edge carries the@@ -106,6 +107,28 @@ on the host-relative path; the link is **exact** when exactly one workspace servprovides that path (`unique_path`) and a lower-confidence **candidate** when the targetis ambiguous (`ambiguous_path`).+## Service names++A consumer that names its target (`http://catalogue:8080/...`, `${CATALOGUE_URL}/...`) is+resolved to a repo in this order: a `contracts.service_bases` entry, a repo alias (also as+the leading label of `<name>.svc.cluster.local`), then the service-name map the workspace+reads from its own config. A host the map places links with strategy `service_mapped`; when+no route in that repo serves the path, the call becomes a `host_only` service-level edge in+the system graph (kept in `service_links`, apart from route links). The consumer's `meta`+records `target_via` (the source) and `target_evidence` (the file).++| Source | Files read | Name | Repo |+|---|---|---|---|+| `aspire_apphost` | `AppHost.cs`, `Program.cs` holding `DistributedApplication.CreateBuilder` | `AddProject("catalog-api", "../Catalog.API")`, or `AddProject<Projects.X>(...)` through the AppHost's `<ProjectReference>` | The project's directory |+| `compose` | `docker-compose*.yml`, `compose*.yml` | Service name, `container_name`, `hostname`; `environment` keys whose value is an address | `build` context (or its Dockerfile's directory), else an image basename equal to a repo alias |+| `k8s_service` | `*.yaml` under `k8s/`, `deploy/`, `manifests/`, ... | `kind: Service` `metadata.name` | A selector or label value equal to a repo alias, else the manifest's repo when it declares no other Service |+| `spring_application_name` | `application` / `bootstrap` `.yml` or `.properties` | `spring.application.name` | The module the file sits in |++Each repo is walked once per update for these file names; test, example and build-output+directories are skipped, and files at the workspace root are read too. A name two files+place in different repos is left unmapped rather than guessed. To override or fill a gap, add+the host or base token to `service_bases`, which always wins.+## Contracts over REST`GET /api/workspace/contracts` lists contracts and links,diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 36a661526..ab6371570 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -202,6 +202,9 @@ contracts:contract_project_pattern: '(?:.+\.)?contracts'# Map a consumer base token or absolute host to the repo it targets, so a# call whose base is unresolved at parse time links as an exact match.+ # Most names are found without this, from compose, Kubernetes, Spring and+ # Aspire config (see WORKSPACE_CONTRACTS.md, "Service names"); an entry+ # here always wins.service_bases:API_BASE: backend # ${API_BASE}/... -> the "backend" repoapi.example.com: backend # https://api.example.com/... -> "backend"diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex eaba2e88a..dfa6a6055 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -68,7 +68,9 @@ CONTRACTS_FILENAME = "contracts.json"# Version 14 adds MassTransit message-type topic contracts (C# and VB.NET).# Version 15 stamps each contract with its origin and each link with its# strategy (see :mod:`.origins`), and stops linking a Laravel job class to a-# publisher that is not Laravel.+# publisher that is not Laravel; HTTP consumers resolve hosts through the+# service-name map (:mod:`.service_names`), and ``service_links`` holds the+# service-level edges for calls whose host is known but whose route is not.CONTRACTS_VERSION = 15#: ``meta["kind"]`` of a topic contract: the destination a broker call names.@@ -251,6 +253,14 @@ class ContractStore:#: A repo absent from here has never been extracted by a provenance-aware#: run and must be re-extracted rather than trusted.repo_provenance: dict[str, dict[str, str]] = field(default_factory=dict)+ #: Service-level edges (:attr:`.origins.LinkStrategy.HOST_ONLY`): a consumer+ #: whose host names a workspace repo while no route there serves its path.+ #: Kept out of ``contract_links``, which only ever pairs two contracts.+ service_links: list[ContractLink] = field(default_factory=list)+ #: The service-name map matching used (:mod:`.service_names`): each name, its+ #: repo, and the source and file that placed it, plus the fingerprint that+ #: lets a run re-reading no repo reuse it.+ service_names: dict[str, Any] = field(default_factory=dict)def to_dict(self) -> dict[str, Any]:return {@@ -258,6 +268,8 @@ class ContractStore:"generated_at": self.generated_at,"contracts": [c.to_dict() for c in self.contracts],"contract_links": [lk.to_dict() for lk in self.contract_links],+ "service_links": [lk.to_dict() for lk in self.service_links],+ "service_names": self.service_names,"extraction_stats": self.extraction_stats,"repo_provenance": self.repo_provenance,}@@ -275,6 +287,8 @@ class ContractStore:# freshness", so the next run re-extracts everything — the safe# direction for a one-off cost.repo_provenance=data.get("repo_provenance", {}),+ service_links=[ContractLink.from_dict(lk) for lk in data.get("service_links", [])],+ service_names=data.get("service_names", {}),)def rows_for_repo(self, alias: str) -> list[Contract]:@@ -570,7 +584,8 @@ async def run_contract_extraction(from .extractors import build_message_type_indexfrom .extractors.base import make_exclude_predicatefrom .extractors.masstransit import MessageTypeIndex- from .matching import annotate_consumer_targets, match_contracts+ from .matching import annotate_consumer_targets, run_matching+ from .service_names import ServiceNameMap, build_service_name_map, service_names_fingerprintcontract_config = ws_config.contractsexclude = make_exclude_predicate(tuple(contract_config.exclude_globs))@@ -644,8 +659,16 @@ async def run_contract_extraction()# Resolve each consumer's target service / third-party host, then match.- annotate_consumer_targets(all_contracts, contract_config.service_bases)- links = match_contracts(all_contracts)+ # The name map is read from repo files, so a run that re-reads no repo (a+ # settings-only change) reuses the stored map when its fingerprint holds.+ names_fp = service_names_fingerprint(heads, workspace_root)+ if not to_extract and prior.service_names.get("fingerprint") == names_fp:+ names = ServiceNameMap.from_dict(prior.service_names)+ else:+ names = await asyncio.to_thread(build_service_name_map, repo_paths, workspace_root)+ annotate_consumer_targets(all_contracts, contract_config.service_bases, names)+ matched = run_matching(all_contracts)+ links = matched.links# Merge manual linksif contract_config.manual_links:@@ -658,6 +681,8 @@ async def run_contract_extraction(contract_links=links,extraction_stats=extraction_stats,repo_provenance=provenance,+ service_links=matched.service_links,+ service_names=names.to_dict(names_fp),)out_path = save_contract_store(store, workspace_root)diff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.pyindex 099394d19..947ad9ce1 100644--- a/packages/core/src/repowise/core/workspace/matching/__init__.py+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py@@ -45,7 +45,7 @@ class TypeMatcher:MATCHERS: dict[str, TypeMatcher] = {"http": TypeMatcher(deferred=http.is_deferred,- passes=(http.base_resolved_pass, http.candidate_pass),+ passes=(http.base_resolved_pass, http.candidate_pass, http.service_pass),),"topic": TypeMatcher(deferred=topic.is_binding,@@ -70,6 +70,8 @@ def _exact_pass(state: MatchState) -> None:else:keys = find_matching_keys(consumer.contract_id, state.provider_index)providers = [p for k in keys for p in state.provider_index[k]]+ # A host or base token that names the provider's repo is what joined them.+ target = consumer.meta.get("target_repo") if consumer.meta.get("target_via") else Nonefor provider in prefer_target_repo(providers, consumer):if internal(provider, consumer):state.mark_served(consumer)@@ -81,12 +83,17 @@ def _exact_pass(state: MatchState) -> None:# provider's name. A new `keys` rule with another meaning names its# own strategy here.aliased = rules.keys is not None and normalize_contract_id(provider.contract_id) != own- strategy = LinkStrategy.PATTERN_MATCHED if aliased else LinkStrategy.EXACT_ID+ if aliased:+ strategy = LinkStrategy.PATTERN_MATCHED+ elif provider.repo == target:+ strategy = LinkStrategy.SERVICE_MAPPED+ else:+ strategy = LinkStrategy.EXACT_IDstate.add(consumer, provider, strategy, via_alias=aliased)-def match_contracts(contracts: list[Contract]) -> list[ContractLink]:- """Match providers to consumers across repos.+def run_matching(contracts: list[Contract]) -> MatchState:+ """Match providers to consumers across repos; the state holds links and service links.The exact pass runs first for every type, then each registered type's ownpasses in registry order. Target resolution for HTTP consumers is read from@@ -97,7 +104,12 @@ def match_contracts(contracts: list[Contract]) -> list[ContractLink]:for rules in MATCHERS.values():for run in rules.passes:run(state)- return state.links+ return state+++def match_contracts(contracts: list[Contract]) -> list[ContractLink]:+ """The route-level links :func:`run_matching` makes."""+ return run_matching(contracts).links__all__ = [@@ -105,4 +117,5 @@ __all__ = ["TypeMatcher","annotate_consumer_targets","match_contracts",+ "run_matching",]diff --git a/packages/core/src/repowise/core/workspace/matching/common.py b/packages/core/src/repowise/core/workspace/matching/common.pyindex 6c9dc6128..ccc1869ba 100644--- a/packages/core/src/repowise/core/workspace/matching/common.py+++ b/packages/core/src/repowise/core/workspace/matching/common.py@@ -32,6 +32,9 @@ class MatchState:links: list[ContractLink] = field(default_factory=list)seen: set[tuple[str, ...]] = field(default_factory=set)matched: set[int] = field(default_factory=set)+ #: Service-level edges for consumers whose target repo is known but whose+ #: route is not (:func:`.http.service_pass`); never mixed into ``links``.+ service_links: list[ContractLink] = field(default_factory=list)@classmethoddef build(cls, contracts: list[Contract]) -> MatchState:@@ -156,13 +159,21 @@ def prefer_target_repo(providers: list[Contract], consumer: Contract) -> list[Co"""Narrow *providers* to the consumer's resolved ``target_repo`` when set.Falls back to the full list if the target declares no matching provider, so- a stale/typo'd ``service_bases`` entry never silently drops a real link.+ a stale/typo'd ``service_bases`` entry never silently drops a real link. A+ target the service-name map placed (it carries ``target_evidence``) does+ not fall back: the file named that repo, so a same-path route elsewhere is+ not the call's destination."""target = consumer.meta.get("target_repo")if not target:return providerspreferred = [p for p in providers if p.repo == target]- return preferred or providers+ if preferred or consumer.meta.get("target_evidence"):+ # A target the workspace's own config placed does not fall back to+ # another repo that happens to serve the path; the service pass draws+ # the dependency instead.+ return preferred+ return providers__all__ = [diff --git a/packages/core/src/repowise/core/workspace/matching/http.py b/packages/core/src/repowise/core/workspace/matching/http.pyindex 875471181..2fd4c6ece 100644--- a/packages/core/src/repowise/core/workspace/matching/http.py+++ b/packages/core/src/repowise/core/workspace/matching/http.py@@ -12,8 +12,9 @@ import refrom collections import defaultdictfrom typing import TYPE_CHECKING-from repowise.core.workspace.contracts import normalize_contract_id-from repowise.core.workspace.origins import LinkStrategy+from repowise.core.workspace.contracts import ContractLink, normalize_contract_id+from repowise.core.workspace.origins import LinkStrategy, link_confidence, match_type_for+from repowise.core.workspace.service_names import ENV, HOST, ServiceName, ServiceNameMapfrom .common import find_matching_keys, internal, prefer_target_repo@@ -81,73 +82,108 @@ _INTERNAL_HOST_SUFFIXES = (".local", ".internal", ".svc.cluster.local")# ---------------------------------------------------------------------------+#: ``meta["target_via"]`` for a target that came from config or a repo alias+#: rather than from a :mod:`..service_names` source.+VIA_SERVICE_BASES = "service_bases"+VIA_REPO_ALIAS = "repo_alias"++def _resolve_consumer_target(consumer: Contract,repo_aliases: set[str],service_bases: dict[str, str],-) -> tuple[str | None, bool]:- """Resolve a consumer's target repo and whether it is a third-party call.+ names: ServiceNameMap,+) -> tuple[str | None, bool, ServiceName | None]:+ """Resolve a consumer's target repo, whether it is a third-party call, and why.- Returns ``(target_repo, is_external)``:+ Returns ``(target_repo, is_external, via)``, *via* naming the entry that+ settled the target (its ``source``: ``service_bases``, ``repo_alias`` or a+ service-name source such as ``compose``):- ``service_bases`` (host or ``${BASE}`` token) wins first;- a host equal to a workspace repo alias, or an internal-DNS host whoseleading label is a repo alias (``backend.svc.cluster.local``), is internal;- - localhost and bare unknown hostnames (e.g. a docker-compose service we- can't map) return ``(None, False)`` so path matching still applies;+ - a host or internal-DNS label the service-name map places, and a base+ token it knows as an address key (``CATALOGUE_URL``), resolve to that repo;+ - localhost and bare unknown hostnames (a compose service nothing maps)+ return ``(None, False, None)`` so path matching still applies;- any other *public* dotted host is third-party (``is_external=True``)."""meta = consumer.metahost = meta.get("host")if host:if host in service_bases:- return service_bases[host], False- if host in repo_aliases:- return host, False+ return service_bases[host], False, ServiceName(host, HOST, service_bases[host], VIA_SERVICE_BASES, "")if host in _LOCALHOST_HOSTS:- return None, False- if host.endswith(_INTERNAL_HOST_SUFFIXES):- label = host.split(".")[0]- return (label, False) if label in repo_aliases else (None, False)- if "." not in host:- return None, False # bare unknown hostname, not necessarily third-party- return None, True # public dotted host, unmapped → third-party+ return None, False, None+ internal_dns = host not in repo_aliases and host.endswith(_INTERNAL_HOST_SUFFIXES)+ label = host.split(".")[0] if internal_dns else host+ mapped = names.lookup(label, HOST)+ if label in repo_aliases:+ # A map entry agreeing with the alias is the evidence; the alias alone is a name match.+ if mapped is not None and mapped.repo == label:+ return label, False, mapped+ return label, False, ServiceName(label, HOST, label, VIA_REPO_ALIAS, "")+ if mapped is not None:+ return mapped.repo, False, mapped+ if label != host or "." not in host:+ return None, False, None # unmapped internal or bare hostname, not third-party+ return None, True, None # public dotted host, unmapped → third-partytoken = meta.get("base_token")- if token and token.lower() in service_bases:- return service_bases[token.lower()], False- return None, False+ if token:+ if token.lower() in service_bases:+ repo = service_bases[token.lower()]+ return repo, False, ServiceName(token.lower(), ENV, repo, VIA_SERVICE_BASES, "")+ mapped = names.lookup(token, ENV)+ if mapped is not None:+ return mapped.repo, False, mapped+ return None, False, Nonedef annotate_consumer_targets(contracts: list[Contract],service_bases: dict[str, str] | None = None,+ names: ServiceNameMap | None = None,) -> None:"""Stamp each HTTP consumer's ``meta`` with its resolved target / external bit.Mutates the contracts in place so both :func:`..match_contracts` and thediagnostics builder read one resolution. ``service_bases`` maps a base token- or host (case-insensitive) to a repo alias.-- The two keys this owns are cleared before being recomputed, so the result is- a function of *contracts* and *service_bases* alone and not of whatever a- previous run stamped. That matters now that incremental extraction carries- contracts forward: a consumer resolved to ``gamma`` keeps that ``meta`` when- it is reused, and if ``gamma`` has since left the workspace the resolution- no longer fires — so without the clear, the stale target survives and the- contract claims to call a repo that is not in the workspace any more.+ or host (case-insensitive) to a repo alias and always wins; *names* is the+ workspace's :class:`..service_names.ServiceNameMap`, read after the repo+ aliases. A target that is a workspace repo also gets ``target_via`` (the+ source that placed it) and, from a service-name source, ``target_evidence``+ (the file), which is what lets :func:`service_pass` draw a service-level edge.++ The keys this owns are cleared before being recomputed, so the result is+ a function of *contracts*, *service_bases* and *names* alone and not of+ whatever a previous run stamped. That matters now that incremental+ extraction carries contracts forward: a consumer resolved to ``gamma`` keeps+ that ``meta`` when it is reused, and if ``gamma`` has since left the+ workspace the resolution no longer fires — so without the clear, the stale+ target survives and the contract claims to call a repo that is not in the+ workspace any more."""- repo_aliases = {c.repo for c in contracts}+ names = names or ServiceNameMap()+ repo_aliases = {c.repo for c in contracts} | names.repossb = {k.lower(): v for k, v in (service_bases or {}).items()}for c in contracts:if c.role != "consumer" or c.contract_type != "http":continue- c.meta.pop("target_repo", None)- c.meta.pop("external", None)- target, external = _resolve_consumer_target(c, repo_aliases, sb)+ for key in _TARGET_KEYS:+ c.meta.pop(key, None)+ target, external, via = _resolve_consumer_target(c, repo_aliases, sb, names)if external:c.meta["external"] = Trueelif target:c.meta["target_repo"] = target+ if via is not None and target in repo_aliases:+ c.meta["target_via"] = via.source+ if via.file:+ c.meta["target_evidence"] = via.file+++_TARGET_KEYS = ("target_repo", "external", "target_via", "target_evidence")# ---------------------------------------------------------------------------@@ -269,9 +305,52 @@ def candidate_pass(state: MatchState) -> None:state.add(consumer, provider, LinkStrategy.PREFIX_STRIPPED)+def service_pass(state: MatchState) -> None:+ """Draw a service-level edge for each consumer whose target is known but whose route is not.++ The host (or base token) places the call in a workspace repo, yet no+ provider there, or anywhere, serves its path: the dependency is real, the+ route is unread. Each such consumer gets one :attr:`LinkStrategy.HOST_ONLY`+ link to the target repo with no provider file, kept apart from route links+ in :attr:`.common.MatchState.service_links`.+ """+ seen: set[tuple[str, ...]] = set()+ for consumer in state.unmatched("http"):+ meta = consumer.meta+ target = meta.get("target_repo")+ via = meta.get("target_via")+ # A host that only equals a repo name is not evidence enough for an edge.+ if not target or not via or via == VIA_REPO_ALIAS or target == consumer.repo:+ continue+ key = (consumer.repo, consumer.file_path, normalize_contract_id(consumer.contract_id), target)+ if key in seen:+ continue+ seen.add(key)+ name = meta.get("host") or meta.get("base_token") or target+ state.service_links.append(+ ContractLink(+ contract_id=consumer.contract_id,+ contract_type=consumer.contract_type,+ match_type=match_type_for(LinkStrategy.HOST_ONLY),+ confidence=link_confidence(LinkStrategy.HOST_ONLY, consumer.confidence),+ provider_repo=target,+ provider_file="",+ provider_symbol=f"{name} ({meta['target_via']})",+ provider_service=None,+ consumer_repo=consumer.repo,+ consumer_file=consumer.file_path,+ consumer_symbol=consumer.symbol_name,+ consumer_service=consumer.service,+ consumer_symbol_id=consumer.symbol_id,+ strategy=LinkStrategy.HOST_ONLY,+ )+ )++__all__ = ["annotate_consumer_targets","base_resolved_pass","candidate_pass","is_deferred",+ "service_pass",]diff --git a/packages/core/src/repowise/core/workspace/origins.py b/packages/core/src/repowise/core/workspace/origins.pyindex 309b3f37f..7d675b141 100644--- a/packages/core/src/repowise/core/workspace/origins.py+++ b/packages/core/src/repowise/core/workspace/origins.py@@ -80,6 +80,9 @@ class LinkStrategy(StrEnum):SHARED_TABLE = "shared_table"#: The consumer's host or base token maps to the providing service.SERVICE_MAPPED = "service_mapped"+ #: The consumer's host or base token maps to a service, but no route there serves+ #: its path: a service-level dependency, not a route link.+ HOST_ONLY = "host_only"#: The consumer's base is unread and exactly one service serves the path.UNIQUE_PATH = "unique_path"#: The consumer's base is unread and several services serve the path; linked to each.@@ -98,6 +101,7 @@ STRATEGY_CONFIDENCE: dict[LinkStrategy, float] = {LinkStrategy.BINDING_ROUTED: 1.0,LinkStrategy.SHARED_TABLE: 1.0,LinkStrategy.SERVICE_MAPPED: 1.0,+ LinkStrategy.HOST_ONLY: 0.5,LinkStrategy.UNIQUE_PATH: 1.0,LinkStrategy.AMBIGUOUS_PATH: 0.6,LinkStrategy.PREFIX_STRIPPED: 0.6,@@ -105,7 +109,9 @@ STRATEGY_CONFIDENCE: dict[LinkStrategy, float] = {LinkStrategy.MANIFEST: 1.0,}-_CANDIDATE = frozenset({LinkStrategy.AMBIGUOUS_PATH, LinkStrategy.PREFIX_STRIPPED})+_CANDIDATE = frozenset(+ {LinkStrategy.AMBIGUOUS_PATH, LinkStrategy.PREFIX_STRIPPED, LinkStrategy.HOST_ONLY}+)def origin_confidence(origin: str) -> float:diff --git a/packages/core/src/repowise/core/workspace/service_names/__init__.py b/packages/core/src/repowise/core/workspace/service_names/__init__.pynew file mode 100644index 000000000..2e9696092--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/__init__.py@@ -0,0 +1,282 @@+"""The service-name map: which workspace repo serves a hostname or logical service name.++A consumer calls ``http://catalogue:8080/...`` or ``${CATALOGUE_URL}/...``; the+deploy and framework config in the workspace says which repo that is. Each+source in :data:`SOURCES` reads a few config files (gated by file name, found in+one pruned walk per repo plus the workspace root's own files) and states+:class:`.base.Claim` rows; :func:`build_service_name_map` turns them into one+entry per name, recording the source and file that produced it.++A name two sources (or two files) place in different repos is dropped rather+than guessed. Manual ``contracts.service_bases`` entries are not part of the map:+the matcher (:func:`..matching.http.annotate_consumer_targets`) consults them+first, so a configured entry always wins.++Adding a source is one module declaring a :class:`.base.ServiceNameSource` and+one line in :data:`SOURCES`, kept sorted by name.+"""++from __future__ import annotations++import hashlib+import json+import logging+import os+from collections import defaultdict+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Any++from repowise.core.fs_walk import PRUNED_DIRS, walk_repo++from . import aspire, compose, k8s_service, spring+from .base import ENV, HOST, Claim, ServiceNameSource, SourceFile++_log = logging.getLogger("repowise.workspace.service_names")++SOURCES: tuple[ServiceNameSource, ...] = (+ aspire.SOURCE,+ compose.SOURCE,+ k8s_service.SOURCE,+ spring.SOURCE,+)++# Test, example and build-output trees declare services that are not the+# workspace's: an example compose file or a test application.yml would map a+# real name to the wrong repo.+_PRUNE = PRUNED_DIRS | {+ "test",+ "tests",+ "__tests__",+ "testdata",+ "fixtures",+ "e2e",+ "example",+ "examples",+ "sample",+ "samples",+ "bin",+ "obj",+ "target",+ "dist",+ "build",+}+_MAX_BYTES = 512_000+++@dataclass(frozen=True)+class ServiceName:+ """One resolved name: the repo serving it and the source and file that said so."""++ name: str+ kind: str+ repo: str+ source: str+ file: str+++@dataclass+class ServiceNameMap:+ """Names to repos, by kind (:data:`.base.HOST` or :data:`.base.ENV`)."""++ entries: dict[tuple[str, str], ServiceName] = field(default_factory=dict)+ #: Every workspace repo alias the map was built over.+ repos: frozenset[str] = frozenset()+ #: Names claimed for more than one repo, and those repos: left unmapped.+ ambiguous: dict[tuple[str, str], tuple[str, ...]] = field(default_factory=dict)++ def lookup(self, name: str, kind: str = HOST) -> ServiceName | None:+ return self.entries.get((kind, name.lower()))++ def to_dict(self, fingerprint: str = "") -> dict[str, Any]:+ return {+ "fingerprint": fingerprint,+ "repos": sorted(self.repos),+ "entries": [asdict(e) for _, e in sorted(self.entries.items())],+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> ServiceNameMap:+ entries = [ServiceName(**e) for e in data.get("entries", [])]+ return cls(+ entries={(e.kind, e.name): e for e in entries},+ repos=frozenset(data.get("repos", [])),+ )+++def service_names_fingerprint(heads: dict[str, str | None], workspace_root: Path | None) -> str:+ """What the map depends on when every repo is clean: each repo's HEAD, the+ workspace root's gated files, and the registered sources."""+ root_files: list[tuple[str, int, int]] = []+ if workspace_root is not None:+ try:+ for p in sorted(workspace_root.iterdir()):+ if p.is_file() and any(s.gates(p.name, ()) for s in SOURCES):+ st = p.stat()+ root_files.append((p.name, st.st_size, st.st_mtime_ns))+ except OSError:+ pass+ payload = [sorted(heads.items()), root_files, [s.name for s in SOURCES]]+ return hashlib.sha256(json.dumps(payload, default=str).encode()).hexdigest()[:16]+++@dataclass(frozen=True)+class _Found:+ source: ServiceNameSource+ claim: Claim+ file_repo: str | None+ evidence: str+++def _read(path: Path) -> str | None:+ try:+ if path.stat().st_size > _MAX_BYTES:+ return None+ return path.read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ return None+++def _claims_in(path: Path, parent_dirs: tuple[str, ...]) -> list[tuple[ServiceNameSource, Claim]]:+ out: list[tuple[ServiceNameSource, Claim]] = []+ text: str | None = None+ for source in SOURCES:+ if not source.gates(path.name, parent_dirs):+ continue+ if text is None and (text := _read(path)) is None:+ return out # read once, however many sources gate it+ if not source.marker or source.marker in text:+ out.extend((source, c) for c in source.read(SourceFile(path, text)))+ return out+++def _walk(alias: str, root: Path) -> list[_Found]:+ found: list[_Found] = []+ for dirpath, _dirs, filenames in walk_repo(root, prune_dirs=_PRUNE):+ rel_dir = dirpath.relative_to(root)+ parents = tuple(p.lower() for p in rel_dir.parts)+ for filename in sorted(filenames):+ path = dirpath / filename+ for source, claim in _claims_in(path, parents):+ found.append(_Found(source, claim, alias, f"{alias}/{(rel_dir / filename).as_posix()}"))+ return found+++def _workspace_root_files(workspace_root: Path) -> list[_Found]:+ """Claims in files at the workspace root itself, where a whole-estate compose file lives."""+ found: list[_Found] = []+ try:+ entries = sorted(p for p in workspace_root.iterdir() if p.is_file())+ except OSError:+ return found+ for path in entries:+ for source, claim in _claims_in(path, ()):+ found.append(_Found(source, claim, None, path.name))+ return found+++def _path_key(path: Path) -> str:+ # Case-insensitive on every OS: an AppHost or compose file written on+ # Windows names ``../Catalog.API`` for a checkout that may be ``catalog.api``.+ return os.path.abspath(path).casefold()+++class _Resolver:+ def __init__(self, repo_paths: dict[str, Path]) -> None:+ self.roots = sorted(+ ((_path_key(p), a) for a, p in repo_paths.items()),+ key=lambda r: -len(r[0]),+ )+ self.aliases = {a.lower(): a for a in repo_paths}++ def repo_at(self, path: Path) -> str | None:+ target = _path_key(path)+ for root, alias in self.roots: # deepest root first: a nested repo wins+ if target == root or target.startswith(root + os.sep):+ return alias+ return None++ def named(self, aliases: tuple[str, ...]) -> str | None:+ return next((self.aliases[a] for a in aliases if a in self.aliases), None)+++def _settle(+ claimed: dict[tuple[str, str], dict[str, tuple[str, str]]],+ out: ServiceNameMap,+) -> None:+ for key, by_repo in claimed.items():+ if len(by_repo) == 1:+ [(repo, (source, evidence))] = by_repo.items()+ out.entries[key] = ServiceName(key[1], key[0], repo, source, evidence)+ else:+ out.ambiguous[key] = tuple(sorted(by_repo))+++def build_service_name_map(+ repo_paths: dict[str, Path], workspace_root: Path | None = None+) -> ServiceNameMap:+ """Read every source in every repo (and the workspace root's files) into one map."""+ found: list[_Found] = []+ for alias, root in repo_paths.items():+ found.extend(_walk(alias, root))+ if workspace_root is not None and workspace_root.resolve() not in {+ p.resolve() for p in repo_paths.values()+ }:+ found.extend(_workspace_root_files(workspace_root))++ resolver = _Resolver(repo_paths)+ out = ServiceNameMap(repos=frozenset(repo_paths))+ claimed: dict[tuple[str, str], dict[str, tuple[str, str]]] = defaultdict(dict)+ own: dict[tuple[str, str], set[str]] = defaultdict(set)+ deferred_own: list[tuple[_Found, str]] = []+ refs: list[_Found] = []++ def claim(f: _Found, repo: str) -> None:+ claimed[(f.claim.kind, f.claim.name)].setdefault(repo, (f.source.name, f.evidence))++ for f in found:+ c = f.claim+ if c.ref is not None:+ refs.append(f)+ continue+ if c.own_repo and f.file_repo is not None:+ # Counted however the claim resolves: a manifest beside others is not sole.+ own[(f.source.name, f.file_repo)].add(c.name)+ repo = resolver.repo_at(c.at) if c.at is not None else None+ repo = repo or resolver.named(c.aliases)+ if repo is not None:+ claim(f, repo)+ elif c.own_repo and f.file_repo is not None:+ deferred_own.append((f, f.file_repo))+ for f, repo in deferred_own:+ if len(own[(f.source.name, repo)]) == 1:+ claim(f, repo)+ _settle(claimed, out)++ # An env key resolves through the finished host map, then the repo aliases.+ # Ceiling: keys and names are workspace-wide, not scoped to the stack that+ # declares them; two stacks reusing a name collide and are dropped. Scoping+ # by compose project is the upgrade if estates mix unrelated stacks.+ env_claimed: dict[tuple[str, str], dict[str, tuple[str, str]]] = defaultdict(dict)+ for f in refs:+ ref = f.claim.ref or ""+ hit = out.lookup(ref, HOST)+ repo = hit.repo if hit is not None else resolver.named((ref,))+ if repo is not None:+ env_claimed[(ENV, f.claim.name)].setdefault(repo, (f.source.name, f.evidence))+ _settle(env_claimed, out)++ if out.ambiguous:+ _log.debug("Service names left unmapped (claimed for several repos): %s", out.ambiguous)+ return out+++__all__ = [+ "ENV",+ "HOST",+ "SOURCES",+ "ServiceName",+ "ServiceNameMap",+ "build_service_name_map",+ "service_names_fingerprint",+]diff --git a/packages/core/src/repowise/core/workspace/service_names/aspire.py b/packages/core/src/repowise/core/workspace/service_names/aspire.pynew file mode 100644index 000000000..99faa91b4--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/aspire.py@@ -0,0 +1,68 @@+""".NET Aspire AppHost: ``AddProject`` names the service every reference resolves by.++``builder.AddProject("catalog-api", "../Catalog.API/Catalog.API.csproj")`` (and+eShop's ``AddDotnetProject`` helper of the same shape) places ``catalog-api`` in+the repo at that path. ``AddProject<Projects.Catalog_API>("catalog-api")``+names a generated type instead; it is resolved through the AppHost project's+own ``<ProjectReference>`` entries, whose file names generate those types+(``.`` and ``-`` become ``_``). ``WithReference`` only hands that name to+another project, so it adds no name of its own.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from pathlib import Path++from .base import Claim, ServiceNameSource, SourceFile, join_config_path++_ADD_PROJECT_RE = re.compile(+ r"\.Add(?:Dotnet)?Project\s*(?:<\s*(?:global::)?([\w.]+)\s*>)?\s*\(\s*"+ r"\"([^\"]+)\"(?:\s*,\s*@?\"([^\"]+)\")?"+)+_PROJECT_REF_RE = re.compile(r"<ProjectReference\s+Include\s*=\s*\"([^\"]+\.csproj)\"", re.IGNORECASE)+++def _project_dir(apphost_dir: Path, ref: str) -> Path:+ path = join_config_path(apphost_dir, ref)+ return path.parent if path.suffix.lower() == ".csproj" else path+++def _generated_types(apphost_dir: Path) -> dict[str, Path]:+ """``Projects.<Name>`` type -> project directory, from the AppHost's project references."""+ types: dict[str, Path] = {}+ for csproj in sorted(apphost_dir.glob("*.csproj")):+ try:+ text = csproj.read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ continue+ for ref in _PROJECT_REF_RE.findall(text):+ path = _project_dir(apphost_dir, ref)+ stem = Path(ref.replace("\\", "/")).stem+ types[re.sub(r"[.\-]", "_", stem).lower()] = path+ return types+++def read(file: SourceFile) -> Iterable[Claim]:+ apphost_dir = file.path.parent+ types: dict[str, Path] | None = None+ for type_name, name, path in _ADD_PROJECT_RE.findall(file.text):+ # With a generated type, a second string is a launch profile ("https"), not a path.+ if path and (not type_name or path.lower().endswith(".csproj") or "/" in path.replace("\\", "/")):+ yield Claim(name=name.lower(), at=_project_dir(apphost_dir, path))+ elif type_name:+ if types is None:+ types = _generated_types(apphost_dir)+ at = types.get(type_name.rsplit(".", 1)[-1].lower())+ if at is not None:+ yield Claim(name=name.lower(), at=at)+++SOURCE = ServiceNameSource(+ name="aspire_apphost",+ # The two entry-point names Aspire templates use; one per project, so cheap to read.+ filenames=("AppHost.cs", "Program.cs"),+ marker="DistributedApplication.CreateBuilder",+ read=read,+)diff --git a/packages/core/src/repowise/core/workspace/service_names/base.py b/packages/core/src/repowise/core/workspace/service_names/base.pynew file mode 100644index 000000000..1dc8e5c6d--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/base.py@@ -0,0 +1,123 @@+"""What a service-name source declares, and what it hands the engine.++A source is data: the file names it reads (its gate), the directories they+must sit under, a marker the text must contain before it is parsed, and one+``read`` function that turns a file's text into :class:`Claim` rows. The engine+in :mod:`.` walks each repo once, evaluates every gate once per file, and+turns claims into ``name -> repo`` entries, so a new source is one module and+one registry line.+"""++from __future__ import annotations++import fnmatch+import re+from collections.abc import Callable, Iterable+from dataclasses import dataclass, field+from pathlib import Path, PurePath+from typing import TypeVar++_P = TypeVar("_P", bound=PurePath)++#: A name a consumer uses as its URL host (``http://catalogue:8080``).+HOST = "host"+#: A config key whose value names a host (``CATALOGUE_URL: http://catalogue:8080``),+#: matched against a consumer's unresolved base token (``${CATALOGUE_URL}``).+ENV = "env"+++@dataclass(frozen=True)+class Claim:+ """One file's statement that *name* is served by some repo.++ Where it points, tried in order: ``at`` (the directory the service is+ built from; the repo holding it serves *name*), ``aliases`` (repo aliases+ the file names for it, such as an image basename or a selector label; the+ first one in the workspace wins), ``ref`` (an :data:`ENV` key's host,+ resolved through the finished host map), and ``own_repo`` (the repo holding+ the file, kept only when it is the only name the source places in that+ repo this way, so a deploy repo listing every service claims none).+ """++ name: str+ kind: str = HOST+ at: Path | None = None+ aliases: tuple[str, ...] = ()+ ref: str | None = None+ own_repo: bool = False+++@dataclass(frozen=True)+class SourceFile:+ """A gated file handed to a source's ``read``."""++ path: Path+ text: str+++@dataclass(frozen=True)+class ServiceNameSource:+ """One place service names are declared: compose, Kubernetes, Spring, Aspire, ...++ ``filenames`` are case-insensitive globs on the file's own name; ``under``,+ when set, requires an ancestor directory (inside the repo) with one of+ those names; ``marker`` must occur in the text before ``read`` parses it.+ A gateway source would add a path rewrite to its claims for the matcher to+ apply; nothing here assumes a claim is a plain host.+ """++ name: str+ filenames: tuple[str, ...]+ read: Callable[[SourceFile], Iterable[Claim]]+ under: frozenset[str] = frozenset()+ marker: str = ""+ _gate: re.Pattern[str] = field(init=False, repr=False, compare=False)++ def __post_init__(self) -> None:+ pattern = "|".join(fnmatch.translate(g.lower()) for g in self.filenames)+ object.__setattr__(self, "_gate", re.compile(pattern) if pattern else re.compile(r"(?!)"))++ def gates(self, filename: str, parent_dirs: tuple[str, ...]) -> bool:+ """True when a file with this name under these (lowercased) directories is read."""+ if not self._gate.match(filename.lower()):+ return False+ return not self.under or any(d in self.under for d in parent_dirs)+++def join_config_path(base: _P, ref: str) -> _P:+ """*ref*, a path written in a config file, joined onto *base* on any OS.++ Config written on Windows (an AppHost's ``..\Catalog.API``, a compose+ ``build: .\cart``) is indexed on Linux too, where a backslash is not a+ separator, so both separators split it here.+ """+ parts = [p for p in ref.replace("\\", "/").split("/") if p not in ("", ".")]+ return base.joinpath(*parts)+++_URL_HOST_RE = re.compile(r"^[a-z][a-z0-9+.-]*://(?:[^@/]*@)?([A-Za-z0-9][^/:?#]*)", re.IGNORECASE)+_HOST_PORT_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_.-]*):\d+/?$")+_BARE_HOST_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_.-]*)$")+# A bare word is an address only under a key that says so: ``CART_HOST: cart``+# is, ``MYSQL_USER: gva`` is not.+_ADDRESS_KEY_RE = re.compile(+ r"(?:^|_)(?:HOST|HOSTNAME|URL|URI|ADDR|ADDRESS|ENDPOINT|SERVER|SERVICE)$", re.IGNORECASE+)+++def host_of(key: str, value: str) -> str | None:+ """The host config entry *key* = *value* names, or None when it is not an address.++ ``http://cart:8080/x`` and ``cart:8080`` name ``cart`` under any key; a bare+ ``cart`` only under an address-like key (``CART_HOST``, ``CART_URL``).+ """+ value = value.strip().strip("'\"")+ if "${" in value or "{{" in value:+ return None+ m = _URL_HOST_RE.match(value) or _HOST_PORT_RE.match(value)+ if m is None and _ADDRESS_KEY_RE.search(key):+ m = _BARE_HOST_RE.match(value)+ return m.group(1).lower() if m else None+++__all__ = ["ENV", "HOST", "Claim", "ServiceNameSource", "SourceFile", "host_of", "join_config_path"]diff --git a/packages/core/src/repowise/core/workspace/service_names/compose.py b/packages/core/src/repowise/core/workspace/service_names/compose.pynew file mode 100644index 000000000..530b2b7e2--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/compose.py@@ -0,0 +1,93 @@+"""docker-compose: a service is the repo its build context (or image) names.++``services.catalogue.build.context: ../catalogue`` puts the name ``catalogue``+in the repo at that path; a ``dockerfile`` narrows it to the Dockerfile's+directory. A service with no build names a repo only through its image's+basename (``org/cart:1.2`` -> ``cart``). ``container_name`` and ``hostname``+are the same container under another name. Every ``environment`` value that+reads as an address (``CATALOGUE_URL: http://catalogue:8080``) makes its key a+reference to that host.+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Iterator+from pathlib import Path+from typing import Any++from .base import ENV, Claim, ServiceNameSource, SourceFile, host_of, join_config_path+from .yaml_docs import load_yaml_docs++_PLACEHOLDER_RE = re.compile(r"\$\{[^}]*\}")+++def _image_basename(image: str) -> str | None:+ name = _PLACEHOLDER_RE.sub("", image).rsplit("/", 1)[-1]+ name = name.split("@", 1)[0].split(":", 1)[0].strip()+ return name or None+++def _build_dir(build: Any, base: Path) -> Path | None:+ if isinstance(build, str):+ context, dockerfile = build, None+ elif isinstance(build, dict):+ context, dockerfile = build.get("context", "."), build.get("dockerfile")+ else:+ return None+ if not isinstance(context, str) or "$" in context or "://" in context or context.startswith("git@"):+ return None+ where = join_config_path(base, context)+ if isinstance(dockerfile, str) and "$" not in dockerfile and "/" in dockerfile.replace("\\", "/"):+ where = join_config_path(where, dockerfile).parent+ return where+++def _environment(env: Any) -> Iterator[tuple[str, str]]:+ if isinstance(env, dict):+ for key, value in env.items():+ if isinstance(value, str):+ yield str(key), value+ elif isinstance(env, list):+ for item in env:+ if isinstance(item, str) and "=" in item:+ key, value = item.split("=", 1)+ yield key, value+++def _service_claims(svc: str, conf: dict[str, Any], base: Path) -> Iterator[Claim]:+ names = {svc.lower()}+ for key in ("container_name", "hostname"):+ value = conf.get(key)+ # A dotted hostname is a public name the container answers to, not a service name.+ if isinstance(value, str) and "$" not in value and "." not in value:+ names.add(value.lower())+ at = _build_dir(conf["build"], base) if "build" in conf else None+ image = conf.get("image")+ aliases = () if at is not None or not isinstance(image, str) else (_image_basename(image),)+ aliases = tuple(a for a in aliases if a)+ if at is not None or aliases:+ for name in sorted(names):+ yield Claim(name=name, at=at, aliases=aliases)+ for key, value in _environment(conf.get("environment")):+ host = host_of(key, value)+ if host:+ yield Claim(name=key.lower(), kind=ENV, ref=host)+++def read(file: SourceFile) -> Iterable[Claim]:+ for doc in load_yaml_docs(file.text):+ services = doc.get("services") if isinstance(doc, dict) else None+ if not isinstance(services, dict):+ continue+ for svc, conf in services.items():+ if isinstance(svc, str) and isinstance(conf, dict):+ yield from _service_claims(svc, conf, file.path.parent)+++SOURCE = ServiceNameSource(+ name="compose",+ filenames=("docker-compose*.yml", "docker-compose*.yaml", "compose*.yml", "compose*.yaml"),+ marker="services",+ read=read,+)diff --git a/packages/core/src/repowise/core/workspace/service_names/k8s_service.py b/packages/core/src/repowise/core/workspace/service_names/k8s_service.pynew file mode 100644index 000000000..d97fc80f6--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/k8s_service.py@@ -0,0 +1,59 @@+"""Kubernetes ``Service`` manifests: the DNS name a cluster gives a workload.++A Service's ``metadata.name`` is the host its callers use. It names a repo+through a selector or label value equal to a repo alias (``app: catalogue``);+otherwise it is the repo holding the manifest, but only when that repo+declares no other Service, since a deploy repo lists every service. Helm+templates do not parse as YAML and are skipped; their rendered names are not+known without the chart's values.+"""++from __future__ import annotations++from collections.abc import Iterable+from typing import Any++from .base import Claim, ServiceNameSource, SourceFile+from .yaml_docs import load_yaml_docs++_LABEL_KEYS = ("app", "app.kubernetes.io/name")+++def _labels(*maps: Any) -> tuple[str, ...]:+ out: list[str] = []+ for m in maps:+ if isinstance(m, dict):+ out.extend(str(m[k]).lower() for k in _LABEL_KEYS if isinstance(m.get(k), str))+ return tuple(dict.fromkeys(out))+++def read(file: SourceFile) -> Iterable[Claim]:+ if "{{" in file.text:+ return+ for doc in load_yaml_docs(file.text):+ if not isinstance(doc, dict) or doc.get("kind") != "Service":+ continue+ meta = doc.get("metadata") or {}+ name = meta.get("name") if isinstance(meta, dict) else None+ if not isinstance(name, str) or not name:+ continue+ spec = doc.get("spec") or {}+ if isinstance(spec, dict) and spec.get("type") == "ExternalName":+ continue # an alias for a host outside the cluster, served by no repo here+ selector = spec.get("selector") if isinstance(spec, dict) else None+ yield Claim(+ name=name.lower(),+ aliases=_labels(selector, meta.get("labels")),+ own_repo=True,+ )+++SOURCE = ServiceNameSource(+ name="k8s_service",+ filenames=("*.yaml", "*.yml"),+ under=frozenset(+ {"k8s", "kubernetes", "kube", "manifests", "deploy", "deployment", "deployments", "kustomize"}+ ),+ marker="kind: Service",+ read=read,+)diff --git a/packages/core/src/repowise/core/workspace/service_names/spring.py b/packages/core/src/repowise/core/workspace/service_names/spring.pynew file mode 100644index 000000000..fae0a8977--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/spring.py@@ -0,0 +1,54 @@+"""Spring ``spring.application.name``: the name Eureka, Feign and ``lb://`` use.++Read from a module's ``application`` or ``bootstrap`` file (YAML or+properties); the name belongs to the module the file sits in. A config+server's ``<app>.yml`` is not read: it configures an app that lives elsewhere,+so it says nothing about which repo serves the name.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from typing import Any++from .base import Claim, ServiceNameSource, SourceFile+from .yaml_docs import load_yaml_docs++_PROPERTY_RE = re.compile(r"^\s*spring\.application\.name\s*[=:]\s*(\S+)\s*$", re.MULTILINE)+++def _yaml_name(doc: Any) -> Any:+ if not isinstance(doc, dict):+ return None+ if "spring.application.name" in doc:+ return doc["spring.application.name"]+ node: Any = doc+ for key in ("spring", "application", "name"):+ node = node.get(key) if isinstance(node, dict) else None+ return node+++def read(file: SourceFile) -> Iterable[Claim]:+ if file.path.suffix.lower() == ".properties":+ found = _PROPERTY_RE.findall(file.text)+ else:+ found = [_yaml_name(doc) for doc in load_yaml_docs(file.text)]+ names = {n.strip().lower() for n in found if isinstance(n, str) and n.strip() and "$" not in n}+ if len(names) == 1: # profiles naming the app differently: no one name to trust+ yield Claim(name=names.pop(), at=file.path.parent)+++SOURCE = ServiceNameSource(+ name="spring_application_name",+ filenames=(+ "application.yml",+ "application.yaml",+ "application.properties",+ "bootstrap.yml",+ "bootstrap.yaml",+ "bootstrap.properties",+ ),+ marker="name",+ read=read,+)diff --git a/packages/core/src/repowise/core/workspace/service_names/yaml_docs.py b/packages/core/src/repowise/core/workspace/service_names/yaml_docs.pynew file mode 100644index 000000000..e95586d5a--- /dev/null+++ b/packages/core/src/repowise/core/workspace/service_names/yaml_docs.py@@ -0,0 +1,16 @@+"""Every YAML document in a file, or none when it does not parse."""++from __future__ import annotations++from typing import Any+++def load_yaml_docs(text: str) -> list[Any]:+ """The file's documents; ``[]`` for a template or anything else that does not parse."""+ import yaml++ loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)+ try:+ return [d for d in yaml.load_all(text, Loader=loader) if d is not None]+ except yaml.YAMLError:+ return []diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.pyindex f7965f88f..a502b19ab 100644--- a/packages/core/src/repowise/core/workspace/system_graph.py+++ b/packages/core/src/repowise/core/workspace/system_graph.py@@ -421,12 +421,15 @@ def build_system_graph(version: int = 2,generated_at: str = "",repo_provenance: dict[str, dict[str, str]] | None = None,+ service_links: list[ContractLink] | None = None,) -> SystemGraph:"""Assemble the service-granular system graph (pure, no I/O).Nodes are derived from each contract's service boundary; edges from matched- contract links (consumer→provider), package dependencies (dependent→- dependency), and cross-repo co-changes (undirected, behavioral).+ contract links (consumer→provider), service-level links (a consumer to the+ repo its host names, no route known; :attr:`.origins.LinkStrategy.HOST_ONLY`),+ package dependencies (dependent→dependency), and cross-repo co-changes+ (undirected, behavioral)."""if diagnostics is None:diagnostics = build_diagnostics(contracts, links)@@ -437,10 +440,11 @@ def build_system_graph(for c in contracts:builder.count_contract(c)- # 2. Contract edges — the consumer calls the provider.- for lk in links:+ # 2. Contract edges — the consumer calls the provider (or, for a service+ # link, the provider's repo: no provider file, so its repo-root node).+ for lk in [*links, *(service_links or ())]:source = builder.resolve_node(lk.consumer_repo, lk.consumer_file)- target = builder.resolve_node(lk.provider_repo, lk.provider_file)+ target = builder.resolve_node(lk.provider_repo, lk.provider_file or None)builder.add_edge(source=source,target=target,@@ -568,6 +572,7 @@ async def run_system_graph_build(diagnostics,generated_at=datetime.now(UTC).isoformat(),repo_provenance=store.repo_provenance,+ service_links=store.service_links,)out_path = save_system_graph(graph, workspace_root)diff --git a/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/AppHost.cs b/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/AppHost.csnew file mode 100644index 000000000..33b25fb98--- /dev/null+++ b/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/AppHost.cs@@ -0,0 +1,38 @@+using System.Net.Sockets;++var builder = DistributedApplication.CreateBuilder(args);++// Add SQL Server container+var sqlServer = builder.AddSqlServer("sqlserver")+ .WithLifetime(ContainerLifetime.Persistent);++// Add the database+var cleanArchDb = sqlServer.AddDatabase("cleanarchitecture");++// Papercut SMTP container for email testing+var papercut = builder.AddContainer("papercut", "jijiechen/papercut", "latest")+ .WithEndpoint("smtp", e =>+ {+ e.TargetPort = 25; // container port+ e.Port = 25; // host port+ e.Protocol = ProtocolType.Tcp;+ e.UriScheme = "smtp";+ })+ .WithEndpoint("ui", e =>+ {+ e.TargetPort = 37408;+ e.Port = 37408;+ e.UriScheme = "http";+ });++// Add the web project with the database connection+builder.AddProject<Projects.Clean_Architecture_Web>("web")+ .WithReference(cleanArchDb)+ .WithEnvironment("ASPNETCORE_ENVIRONMENT", builder.Environment.EnvironmentName)+ .WithEnvironment("Papercut__Smtp__Url", papercut.GetEndpoint("smtp"))+ .WaitFor(cleanArchDb)+ .WaitFor(papercut);++builder+ .Build()+ .Run();diff --git a/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/Clean.Architecture.AspireHost.csproj b/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/Clean.Architecture.AspireHost.csprojnew file mode 100644index 000000000..86f5a3421--- /dev/null+++ b/tests/fixtures/service_names/clean/Clean.Architecture.AspireHost/Clean.Architecture.AspireHost.csproj@@ -0,0 +1,24 @@+<Project Sdk="Aspire.AppHost.Sdk/13.0.0">++ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <IsAspireHost>true</IsAspireHost>+ <UserSecretsId>c540eeb6-e06b-4456-a539-be58dd8b88c7</UserSecretsId>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Aspire.Hosting.AppHost" />+ <PackageReference Include="Aspire.Hosting.SqlServer" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\Clean.Architecture.Web\Clean.Architecture.Web.csproj" />+ </ItemGroup>+ <ItemGroup>+ <!-- The IsAspireProjectResource attribute tells .NET Aspire to treat this+ reference as a standard project reference and not attempt to generate+ a metadata file -->+ <ProjectReference Include="..\Clean.Architecture.ServiceDefaults\Clean.Architecture.ServiceDefaults.csproj" IsAspireProjectResource="false" />+ </ItemGroup>++</Project>diff --git a/tests/fixtures/service_names/clean/Clean.Architecture.Web/.keep b/tests/fixtures/service_names/clean/Clean.Architecture.Web/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/basket.api/.keep b/tests/fixtures/service_names/eshop/basket.api/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/catalog.api/.keep b/tests/fixtures/service_names/eshop/catalog.api/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/eshop.apphost/AppHost.cs b/tests/fixtures/service_names/eshop/eshop.apphost/AppHost.csnew file mode 100644index 000000000..6650f9090--- /dev/null+++ b/tests/fixtures/service_names/eshop/eshop.apphost/AppHost.cs@@ -0,0 +1,117 @@+using System.IO.Pipes;+using eShop.AppHost;++var builder = DistributedApplication.CreateBuilder(args);++builder.AddForwardedHeaders();+builder.AddAzureContainerAppEnvironment("aca");++var redis = builder.AddRedis("redis");+var rabbitMq = builder.AddRabbitMQ("eventbus")+ .WithLifetime(ContainerLifetime.Persistent);+var postgres = builder.AddPostgres("postgres")+ .WithImage("ankane/pgvector")+ .WithImageTag("latest")+ .WithLifetime(ContainerLifetime.Persistent);++var catalogDb = postgres.AddDatabase("catalogdb");+var identityDb = postgres.AddDatabase("identitydb");+var orderDb = postgres.AddDatabase("orderingdb");+var webhooksDb = postgres.AddDatabase("webhooksdb");++var launchProfileName = ShouldUseHttpForEndpoints() ? "http" : "https";++// Services+var identityApi = builder.AddDotnetProject("identity-api", "../Identity.API", o => o.LaunchProfileName = launchProfileName)+ .WithExternalHttpEndpoints()+ .WithReference(identityDb)+ .WithHttpHealthCheck("/health");++var identityEndpoint = identityApi.GetEndpoint(launchProfileName);++var basketApi = builder.AddDotnetProject("basket-api", "../Basket.API")+ .WithReference(redis)+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WithEnvironment("Identity__Url", identityEndpoint);+redis.WithParentRelationship(basketApi);++var catalogApi = builder.AddDotnetProject("catalog-api", "../Catalog.API")+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WithReference(catalogDb);++var orderingApi = builder.AddDotnetProject("ordering-api", "../Ordering.API")+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WithReference(orderDb).WaitFor(orderDb)+ .WithHttpHealthCheck("/health")+ .WithEnvironment("Identity__Url", identityEndpoint);++builder.AddDotnetProject("order-processor", "../OrderProcessor")+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WithReference(orderDb)+ .WaitFor(orderingApi); // wait for the orderingApi to be ready because that contains the EF migrations++builder.AddDotnetProject("payment-processor", "../PaymentProcessor")+ .WithReference(rabbitMq).WaitFor(rabbitMq);++var webHooksApi = builder.AddDotnetProject("webhooks-api", "../Webhooks.API")+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WithReference(webhooksDb)+ .WithEnvironment("Identity__Url", identityEndpoint);++// Reverse proxies+builder.AddYarp("mobile-bff")+ .WithExternalHttpEndpoints()+ .ConfigureMobileBffRoutes(catalogApi, orderingApi, identityApi);++// Apps+var webhooksClient = builder.AddDotnetProject("webhooksclient", "../WebhookClient", o => o.LaunchProfileName = launchProfileName)+ .WithReference(webHooksApi)+ .WithEnvironment("IdentityUrl", identityEndpoint);++var webApp = builder.AddDotnetProject("webapp", "../WebApp", o => o.LaunchProfileName = launchProfileName)+ .WithExternalHttpEndpoints()+ .WithUrls(c => c.Urls.ForEach(u => u.DisplayText = $"Online Store ({u.Endpoint?.EndpointName})"))+ .WithReference(basketApi)+ .WithReference(catalogApi)+ .WithReference(orderingApi)+ .WithReference(rabbitMq).WaitFor(rabbitMq)+ .WaitFor(identityApi)+ .WithEnvironment("IdentityUrl", identityEndpoint);++// Set UseFoundry=true to provision Microsoft Foundry for chat and embeddings.+bool useFoundry = Extensions.IsFoundryEnabled(builder.Configuration);+if (useFoundry)+{+ builder.AddFoundry(catalogApi, webApp);+}++bool useOllama = false;+if (useOllama)+{+ builder.AddOllama(catalogApi, webApp);+}++// Wire up the callback urls (self referencing)+webApp.WithEnvironment("CallBackUrl", webApp.GetEndpoint(launchProfileName));+webhooksClient.WithEnvironment("CallBackUrl", webhooksClient.GetEndpoint(launchProfileName));++// Identity has a reference to all of the apps for callback urls, this is a cyclic reference+identityApi.WithEnvironment("BasketApiClient", basketApi.GetEndpoint("http"))+ .WithEnvironment("OrderingApiClient", orderingApi.GetEndpoint("http"))+ .WithEnvironment("WebhooksApiClient", webHooksApi.GetEndpoint("http"))+ .WithEnvironment("WebhooksWebClient", webhooksClient.GetEndpoint(launchProfileName))+ .WithEnvironment("WebAppClient", webApp.GetEndpoint(launchProfileName));++builder.Build().Run();++// For test use only.+// Looks for an environment variable that forces the use of HTTP for all the endpoints. We+// are doing this for ease of running the Playwright tests in CI.+static bool ShouldUseHttpForEndpoints()+{+ const string EnvVarName = "ESHOP_USE_HTTP_ENDPOINTS";+ var envValue = Environment.GetEnvironmentVariable(EnvVarName);++ // Attempt to parse the environment variable value; return true if it's exactly "1".+ return int.TryParse(envValue, out int result) && result == 1;+}diff --git a/tests/fixtures/service_names/eshop/identity.api/.keep b/tests/fixtures/service_names/eshop/identity.api/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/ordering.api/.keep b/tests/fixtures/service_names/eshop/ordering.api/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/orderprocessor/.keep b/tests/fixtures/service_names/eshop/orderprocessor/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/paymentprocessor/.keep b/tests/fixtures/service_names/eshop/paymentprocessor/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/webapp/.keep b/tests/fixtures/service_names/eshop/webapp/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/webhookclient/.keep b/tests/fixtures/service_names/eshop/webhookclient/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshop/webhooks.api/.keep b/tests/fixtures/service_names/eshop/webhooks.api/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshoponweb/docker-compose.yml b/tests/fixtures/service_names/eshoponweb/docker-compose.ymlnew file mode 100644index 000000000..b2623af36--- /dev/null+++ b/tests/fixtures/service_names/eshoponweb/docker-compose.yml@@ -0,0 +1,25 @@+version: '3.4'++services:+ eshopwebmvc:+ image: ${DOCKER_REGISTRY-}eshopwebmvc+ build:+ context: .+ dockerfile: src/Web/Dockerfile+ depends_on:+ - "sqlserver"+ eshoppublicapi:+ image: ${DOCKER_REGISTRY-}eshoppublicapi+ build:+ context: .+ dockerfile: src/PublicApi/Dockerfile+ depends_on:+ - "sqlserver"+ sqlserver:+ image: mcr.microsoft.com/azure-sql-edge+ ports:+ - "1433:1433"+ environment:+ - SA_PASSWORD=@someThingComplicated1234+ - ACCEPT_EULA=Y+diff --git a/tests/fixtures/service_names/eshoponweb/src/PublicApi/.keep b/tests/fixtures/service_names/eshoponweb/src/PublicApi/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/eshoponweb/src/Web/.keep b/tests/fixtures/service_names/eshoponweb/src/Web/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/gva/deploy/docker-compose/docker-compose.yaml b/tests/fixtures/service_names/gva/deploy/docker-compose/docker-compose.yamlnew file mode 100644index 000000000..1e304c2e1--- /dev/null+++ b/tests/fixtures/service_names/gva/deploy/docker-compose/docker-compose.yaml@@ -0,0 +1,90 @@+version: "3"++# 声明一个名为network的networks,subnet为network的子网地址,默认网关是177.7.0.1+networks:+ network:+ ipam:+ driver: default+ config:+ - subnet: '177.7.0.0/16'++# 设置mysql,redis持久化保存+volumes:+ mysql:+ redis:++services:+ web:+ build:+ context: ../../web+ dockerfile: ./Dockerfile+ container_name: gva-web+ restart: always+ ports:+ - '8080:8080'+ depends_on:+ - server+ command: [ 'nginx-debug', '-g', 'daemon off;' ]+ networks:+ network:+ ipv4_address: 177.7.0.11++ server:+ build:+ context: ../../server+ dockerfile: ./Dockerfile+ container_name: gva-server+ restart: always+ ports:+ - '8888:8888'+ depends_on:+ mysql:+ condition: service_healthy+ redis:+ condition: service_healthy+ links:+ - mysql+ - redis+ networks:+ network:+ ipv4_address: 177.7.0.12++ mysql:+ image: mysql:8.0.21 # 如果您是 arm64 架构:如 MacOS 的 M1,请修改镜像为 image: mysql/mysql-server:8.0.21+ container_name: gva-mysql+ command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci #设置utf8字符集+ restart: always+ ports:+ - "13306:3306" # host物理直接映射端口为13306+ environment:+ #MYSQL_ROOT_PASSWORD: 'Aa@6447985' # root管理员用户密码+ MYSQL_DATABASE: 'qmPlus' # 初始化启动时要创建的数据库的名称+ MYSQL_USER: 'gva'+ MYSQL_PASSWORD: 'Aa@6447985'+ healthcheck:+ test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "gva", "-pAa@6447985"]+ interval: 10s+ timeout: 5s+ retries: 3+ volumes:+ - mysql:/var/lib/mysql+ networks:+ network:+ ipv4_address: 177.7.0.13++ redis:+ image: redis:6.0.6+ container_name: gva-redis # 容器名+ restart: always+ ports:+ - '16379:6379'+ healthcheck:+ test: ["CMD-SHELL", "redis-cli ping | grep PONG || exit 1"]+ interval: 10s+ timeout: 5s+ retries: 3+ volumes:+ - redis:/data+ networks:+ network:+ ipv4_address: 177.7.0.14diff --git a/tests/fixtures/service_names/gva/server/.keep b/tests/fixtures/service_names/gva/server/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/gva/web/.keep b/tests/fixtures/service_names/gva/web/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/petclinic/k8s/db.yml b/tests/fixtures/service_names/petclinic/k8s/db.ymlnew file mode 100644index 000000000..789d5f067--- /dev/null+++ b/tests/fixtures/service_names/petclinic/k8s/db.yml@@ -0,0 +1,73 @@+---+apiVersion: v1+kind: Secret+metadata:+ name: demo-db+type: servicebinding.io/postgresql+stringData:+ type: "postgresql"+ provider: "postgresql"+ host: "demo-db"+ port: "5432"+ database: "petclinic"+ username: "user"+ password: "pass"++---+apiVersion: v1+kind: Service+metadata:+ name: demo-db+spec:+ ports:+ - port: 5432+ selector:+ app: demo-db++---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: demo-db+ labels:+ app: demo-db+spec:+ selector:+ matchLabels:+ app: demo-db+ template:+ metadata:+ labels:+ app: demo-db+ spec:+ containers:+ - image: postgres:18.4+ name: postgresql+ env:+ - name: POSTGRES_USER+ valueFrom:+ secretKeyRef:+ name: demo-db+ key: username+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: demo-db+ key: password+ - name: POSTGRES_DB+ valueFrom:+ secretKeyRef:+ name: demo-db+ key: database+ ports:+ - containerPort: 5432+ name: postgresql+ livenessProbe:+ tcpSocket:+ port: postgresql+ readinessProbe:+ tcpSocket:+ port: postgresql+ startupProbe:+ tcpSocket:+ port: postgresqldiff --git a/tests/fixtures/service_names/petclinic/k8s/petclinic.yml b/tests/fixtures/service_names/petclinic/k8s/petclinic.ymlnew file mode 100644index 000000000..a5677cd06--- /dev/null+++ b/tests/fixtures/service_names/petclinic/k8s/petclinic.yml@@ -0,0 +1,64 @@+---+apiVersion: v1+kind: Service+metadata:+ name: petclinic+spec:+ type: NodePort+ ports:+ - port: 80+ targetPort: 8080+ selector:+ app: petclinic++---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: petclinic+ labels:+ app: petclinic+spec:+ replicas: 1+ selector:+ matchLabels:+ app: petclinic+ template:+ metadata:+ labels:+ app: petclinic+ spec:+ containers:+ - name: workload+ image: dsyer/petclinic+ env:+ - name: SPRING_PROFILES_ACTIVE+ value: postgres+ - name: SERVICE_BINDING_ROOT+ value: /bindings+ - name: SPRING_APPLICATION_JSON+ value: |+ {+ "management.endpoint.health.probes.add-additional-paths": true+ }+ ports:+ - name: http+ containerPort: 8080+ livenessProbe:+ httpGet:+ path: /livez+ port: http+ readinessProbe:+ httpGet:+ path: /readyz+ port: http+ volumeMounts:+ - mountPath: /bindings/secret+ name: binding+ readOnly: true+ volumes:+ - name: binding+ projected:+ sources:+ - secret:+ name: demo-dbdiff --git a/tests/fixtures/service_names/robotshop/cart/.keep b/tests/fixtures/service_names/robotshop/cart/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/catalogue/.keep b/tests/fixtures/service_names/robotshop/catalogue/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/dispatch/.keep b/tests/fixtures/service_names/robotshop/dispatch/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/docker-compose.yaml b/tests/fixtures/service_names/robotshop/docker-compose.yamlnew file mode 100644index 000000000..a77a6131e--- /dev/null+++ b/tests/fixtures/service_names/robotshop/docker-compose.yaml@@ -0,0 +1,172 @@+version: '3'+services:+ mongodb:+ build:+ context: mongo+ image: ${REPO}/rs-mongodb:${TAG}+ networks:+ - robot-shop+ logging: &logging+ driver: "json-file"+ options:+ max-size: "25m"+ max-file: "2"+ redis:+ image: redis:6.2-alpine+ networks:+ - robot-shop+ logging:+ <<: *logging+ rabbitmq:+ image: rabbitmq:3.8-management-alpine+ networks:+ - robot-shop+ logging:+ <<: *logging+ catalogue:+ build:+ context: catalogue+ image: ${REPO}/rs-catalogue:${TAG}+ depends_on:+ - mongodb+ networks:+ - robot-shop+ healthcheck:+ test: [ "CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/health" ]+ interval: 10s+ timeout: 10s+ retries: 3+ logging:+ <<: *logging+ user:+ build:+ context: user+ image: ${REPO}/rs-user:${TAG}+ depends_on:+ - mongodb+ - redis+ networks:+ - robot-shop+ healthcheck:+ test: [ "CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/health" ]+ interval: 10s+ timeout: 10s+ retries: 3+ logging:+ <<: *logging+ cart:+ build:+ context: cart+ image: ${REPO}/rs-cart:${TAG}+ depends_on:+ - redis+ networks:+ - robot-shop+ healthcheck:+ test: [ "CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/health" ]+ interval: 10s+ timeout: 10s+ retries: 3+ logging:+ <<: *logging+ mysql:+ build:+ context: mysql+ image: ${REPO}/rs-mysql-db:${TAG}+ cap_add:+ - NET_ADMIN+ networks:+ - robot-shop+ logging:+ <<: *logging+ shipping:+ build:+ context: shipping+ image: ${REPO}/rs-shipping:${TAG}+ depends_on:+ - mysql+ networks:+ - robot-shop+ healthcheck:+ test: ["CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/health"]+ interval: 10s+ timeout: 10s+ retries: 3+ logging:+ <<: *logging+ ratings:+ build:+ context: ratings+ image: ${REPO}/rs-ratings:${TAG}+ environment:+ APP_ENV: prod+ networks:+ - robot-shop+ depends_on:+ - mysql+ healthcheck:+ test: ["CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost/_health"]+ interval: 10s+ timeout: 10s+ retries: 3+ logging:+ <<: *logging+ payment:+ build:+ context: payment+ image: ${REPO}/rs-payment:${TAG}+ depends_on:+ - rabbitmq+ networks:+ - robot-shop+ healthcheck:+ test: ["CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/health"]+ interval: 10s+ timeout: 10s+ retries: 3+ # Uncomment to change payment gateway+ #environment:+ #PAYMENT_GATEWAY: "https://www.worldpay.com"+ logging:+ <<: *logging+ dispatch:+ build:+ context: dispatch+ image: ${REPO}/rs-dispatch:${TAG}+ depends_on:+ - rabbitmq+ networks:+ - robot-shop+ logging:+ <<: *logging+ web:+ build:+ context: web+ args:+ # agent key to download tracing libs+ KEY: ${INSTANA_AGENT_KEY}+ image: ${REPO}/rs-web:${TAG}+ depends_on:+ - catalogue+ - user+ - shipping+ - payment+ ports:+ - "8080:8080"+ networks:+ - robot-shop+ healthcheck:+ test: [ "CMD", "curl", "-H", "X-INSTANA-SYNTHETIC: 1", "-f", "http://localhost:8080/" ]+ interval: 10s+ timeout: 10s+ retries: 3+ # Uncomment to enable Instana EUM+ # environment:+ # INSTANA_EUM_KEY: <your eum key>+ # INSTANA_EUM_REPORTING_URL: <your reporting url>+ logging:+ <<: *logging++networks:+ robot-shop:+diff --git a/tests/fixtures/service_names/robotshop/mongo/.keep b/tests/fixtures/service_names/robotshop/mongo/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/mysql/.keep b/tests/fixtures/service_names/robotshop/mysql/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/payment/.keep b/tests/fixtures/service_names/robotshop/payment/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/ratings/.keep b/tests/fixtures/service_names/robotshop/ratings/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/shipping/.keep b/tests/fixtures/service_names/robotshop/shipping/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/user/.keep b/tests/fixtures/service_names/robotshop/user/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/robotshop/web/.keep b/tests/fixtures/service_names/robotshop/web/.keepnew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/service_names/spring_pm/account-service/src/main/resources/bootstrap.yml b/tests/fixtures/service_names/spring_pm/account-service/src/main/resources/bootstrap.ymlnew file mode 100644index 000000000..6a843ce0c--- /dev/null+++ b/tests/fixtures/service_names/spring_pm/account-service/src/main/resources/bootstrap.yml@@ -0,0 +1,9 @@+spring:+ application:+ name: account-service+ cloud:+ config:+ uri: http://config:8888+ fail-fast: true+ password: ${CONFIG_SERVICE_PASSWORD}+ username: userdiff --git a/tests/fixtures/service_names/spring_pm/account-service/src/test/resources/bootstrap.yml b/tests/fixtures/service_names/spring_pm/account-service/src/test/resources/bootstrap.ymlnew file mode 100644index 000000000..5fde57fd8--- /dev/null+++ b/tests/fixtures/service_names/spring_pm/account-service/src/test/resources/bootstrap.yml@@ -0,0 +1,3 @@+eureka:+ client:+ enabled: false\ No newline at end of filediff --git a/tests/fixtures/service_names/spring_pm/auth-service/src/main/resources/bootstrap.yml b/tests/fixtures/service_names/spring_pm/auth-service/src/main/resources/bootstrap.ymlnew file mode 100644index 000000000..a0180e803--- /dev/null+++ b/tests/fixtures/service_names/spring_pm/auth-service/src/main/resources/bootstrap.yml@@ -0,0 +1,9 @@+spring:+ application:+ name: auth-service+ cloud:+ config:+ uri: http://config:8888+ fail-fast: true+ password: ${CONFIG_SERVICE_PASSWORD}+ username: userdiff --git a/tests/fixtures/service_names/spring_pm/auth-service/src/test/resources/bootstrap.yml b/tests/fixtures/service_names/spring_pm/auth-service/src/test/resources/bootstrap.ymlnew file mode 100644index 000000000..5fde57fd8--- /dev/null+++ b/tests/fixtures/service_names/spring_pm/auth-service/src/test/resources/bootstrap.yml@@ -0,0 +1,3 @@+eureka:+ client:+ enabled: false\ No newline at end of filediff --git a/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/account-service.yml b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/account-service.ymlnew file mode 100644index 000000000..209425d5c--- /dev/null+++ b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/account-service.yml@@ -0,0 +1,26 @@+security:+ oauth2:+ client:+ clientId: account-service+ clientSecret: ${ACCOUNT_SERVICE_PASSWORD}+ accessTokenUri: http://auth-service:5000/uaa/oauth/token+ grant-type: client_credentials+ scope: server++spring:+ data:+ mongodb:+ host: account-mongodb+ username: user+ password: ${MONGODB_PASSWORD}+ database: piggymetrics+ port: 27017++server:+ servlet:+ context-path: /accounts+ port: 6000++feign:+ hystrix:+ enabled: true\ No newline at end of filediff --git a/tests/unit/workspace/test_service_names.py b/tests/unit/workspace/test_service_names.pynew file mode 100644index 000000000..ee855431f--- /dev/null+++ b/tests/unit/workspace/test_service_names.py@@ -0,0 +1,441 @@+"""The service-name map: sources, precedence, and what the matcher does with it."""++from __future__ import annotations++import importlib+import pkgutil+import posixpath+from pathlib import Path, PurePosixPath++import pytest++import repowise.core.workspace.service_names as service_names+from repowise.core.workspace.contracts import Contract, ContractStore+from repowise.core.workspace.cross_repo import CrossRepoOverlay+from repowise.core.workspace.matching import annotate_consumer_targets, run_matching+from repowise.core.workspace.origins import LinkStrategy, link_confidence+from repowise.core.workspace.service_names import (+ ENV,+ HOST,+ SOURCES,+ ServiceNameMap,+ build_service_name_map,+ service_names_fingerprint,+)+from repowise.core.workspace.service_names.base import (+ ServiceNameSource,+ host_of,+ join_config_path,+)+from repowise.core.workspace.system_graph import build_system_graph++FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "service_names"+++def _repos(root: Path, *names: str) -> dict[str, Path]:+ return {n.rsplit("/", 1)[-1]: root / n for n in names}+++def _mapped(m: ServiceNameMap, kind: str = HOST) -> dict[str, tuple[str, str]]:+ return {n: (e.repo, e.source) for (k, n), e in m.entries.items() if k == kind}+++# ---------------------------------------------------------------------------+# Registry contract+# ---------------------------------------------------------------------------+++def test_registry_is_sorted_unique_and_every_source_module_is_registered() -> None:+ names = [s.name for s in SOURCES]+ assert names == sorted(names) and len(set(names)) == len(names)+ registered = {id(s) for s in SOURCES}+ for info in pkgutil.iter_modules(service_names.__path__):+ module = importlib.import_module(f"{service_names.__name__}.{info.name}")+ source = getattr(module, "SOURCE", None)+ if source is not None:+ assert id(source) in registered, f"{info.name}.SOURCE is not in SOURCES"++[email protected]("source", SOURCES, ids=lambda s: s.name)+def test_every_source_declares_a_gate(source: ServiceNameSource) -> None:+ assert source.filenames and callable(source.read)+ # A glob that admits any file of a type must narrow by directory or marker,+ # so the walk reads a few config files, never every source file.+ for glob in source.filenames:+ if glob.startswith("*"):+ assert source.under or source.marker, (source.name, glob)+ assert source.marker or source.under or all("*" not in g for g in source.filenames)+++def test_only_gated_files_are_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ repo = tmp_path / "svc"+ (repo / "src").mkdir(parents=True)+ for i in range(50):+ (repo / "src" / f"m{i}.py").write_text("x = 1\n")+ (repo / "src" / f"c{i}.yaml").write_text("a: 1\n")+ (repo / "docker-compose.yml").write_text("services: {}\n")+ seen: list[str] = []+ real = service_names._read+ monkeypatch.setattr(service_names, "_read", lambda p: seen.append(p.name) or real(p))+ build_service_name_map({"svc": repo})+ assert seen == ["docker-compose.yml"]+++# ---------------------------------------------------------------------------+# Sources, on real files+# ---------------------------------------------------------------------------+++def test_compose_at_the_workspace_root_maps_build_contexts() -> None:+ root = FIXTURES / "robotshop"+ repos = _repos(root, "catalogue", "cart", "user", "mongo", "mysql", "shipping",+ "ratings", "payment", "dispatch", "web")+ hosts = _mapped(build_service_name_map(repos, root))+ assert hosts["mongodb"] == ("mongo", "compose")+ assert hosts["catalogue"] == ("catalogue", "compose")+ assert "redis" not in hosts and "rabbitmq" not in hosts # images, no repo+++def test_compose_context_and_container_name() -> None:+ root = FIXTURES / "gva"+ m = build_service_name_map({"gva": root, "web": root / "web", "server": root / "server"})+ hosts = _mapped(m)+ assert hosts["server"] == ("server", "compose")+ assert hosts["gva-web"] == ("web", "compose")+ assert "mysql" not in hosts+ assert not _mapped(m, ENV) # MYSQL_USER: 'gva' is not an address+++def test_compose_dockerfile_narrows_a_shared_context() -> None:+ root = FIXTURES / "eshoponweb"+ m = build_service_name_map(+ {"web": root / "src" / "Web", "publicapi": root / "src" / "PublicApi"}, root+ )+ assert _mapped(m) == {+ "eshopwebmvc": ("web", "compose"),+ "eshoppublicapi": ("publicapi", "compose"),+ }+++def test_compose_environment_addresses_become_token_entries(tmp_path: Path) -> None:+ for r in ("deploy", "catalogue", "cart"):+ (tmp_path / r).mkdir()+ (tmp_path / "deploy" / "docker-compose.yml").write_text(+ "services:\n"+ " catalogue: {build: ../catalogue}\n"+ " cart:\n"+ " build: {context: ../cart}\n"+ " environment:\n"+ " CATALOGUE_URL: http://catalogue:8080\n"+ " MYSQL_USER: cart\n"+ " web:\n"+ " image: nginx\n"+ " environment: ['CART_HOST=cart', 'API=https://api.stripe.com']\n"+ )+ m = build_service_name_map(_repos(tmp_path, "deploy", "catalogue", "cart"))+ assert _mapped(m, ENV) == {+ "catalogue_url": ("catalogue", "compose"),+ "cart_host": ("cart", "compose"),+ }+++def test_a_name_claimed_for_two_repos_is_left_unmapped(tmp_path: Path) -> None:+ for r in ("a", "b"):+ (tmp_path / r).mkdir()+ (tmp_path / r / "docker-compose.yml").write_text("services:\n api: {build: .}\n")+ m = build_service_name_map(_repos(tmp_path, "a", "b"))+ assert m.lookup("api") is None+ assert m.ambiguous[(HOST, "api")] == ("a", "b")+++def test_k8s_service_by_selector_label_and_never_a_sibling_by_location() -> None:+ m = build_service_name_map({"petclinic": FIXTURES / "petclinic"})+ # demo-db sits in the same repo beside another Service: not its own.+ assert _mapped(m) == {"petclinic": ("petclinic", "k8s_service")}+++def test_k8s_service_alone_in_its_repo_and_helm_templates(tmp_path: Path) -> None:+ (tmp_path / "orders" / "k8s").mkdir(parents=True)+ (tmp_path / "orders" / "k8s" / "svc.yaml").write_text(+ "apiVersion: v1\nkind: Service\nmetadata:\n name: orders-api\nspec:\n ports: [{port: 80}]\n"+ )+ (tmp_path / "chart" / "deploy").mkdir(parents=True)+ (tmp_path / "chart" / "deploy" / "svc.yaml").write_text(+ "kind: Service\nmetadata:\n name: {{ .Values.name }}\n"+ )+ hosts = _mapped(build_service_name_map(_repos(tmp_path, "orders", "chart")))+ assert hosts == {"orders-api": ("orders", "k8s_service")}+++def test_spring_application_name_from_main_resources_only(tmp_path: Path) -> None:+ root = FIXTURES / "spring_pm"+ hosts = _mapped(+ build_service_name_map(_repos(root, "account-service", "auth-service", "config"))+ )+ assert hosts == {+ "account-service": ("account-service", "spring_application_name"),+ "auth-service": ("auth-service", "spring_application_name"),+ }+++def test_spring_properties_and_test_resources(tmp_path: Path) -> None:+ res = tmp_path / "shipping" / "src" / "main" / "resources"+ res.mkdir(parents=True)+ (res / "application.properties").write_text("spring.application.name=shipping-svc\n")+ test_res = tmp_path / "shipping" / "src" / "test" / "resources"+ test_res.mkdir(parents=True)+ (test_res / "application.properties").write_text("spring.application.name=other\n")+ hosts = _mapped(build_service_name_map(_repos(tmp_path, "shipping")))+ assert hosts == {"shipping-svc": ("shipping", "spring_application_name")}+++def test_aspire_add_project_with_a_path() -> None:+ root = FIXTURES / "eshop"+ aliases = ["eshop.apphost", "catalog.api", "basket.api", "ordering.api", "identity.api",+ "orderprocessor", "paymentprocessor", "webhooks.api", "webhookclient", "webapp"]+ hosts = _mapped(build_service_name_map(_repos(root, *aliases)))+ assert hosts["catalog-api"] == ("catalog.api", "aspire_apphost")+ assert hosts["webhooksclient"] == ("webhookclient", "aspire_apphost")+ assert len(hosts) == 9+ assert "eventbus" not in hosts and "redis" not in hosts # infrastructure, not projects+++def test_aspire_add_project_by_generated_type() -> None:+ root = FIXTURES / "clean"+ m = build_service_name_map(+ _repos(root, "Clean.Architecture.AspireHost", "Clean.Architecture.Web")+ )+ assert _mapped(m) == {"web": ("Clean.Architecture.Web", "aspire_apphost")}+++ ("key", "value", "host"),+ [+ ("CATALOGUE_URL", "http://catalogue:8080/api", "catalogue"),+ ("ANY", "cart:8080", "cart"),+ ("CART_HOST", "cart", "cart"),+ ("MYSQL_USER", "cart", None),+ ("CART_URL", "${CART}", None),+ ("ASPNETCORE_URLS", "http://+:8080", None),+ ],+)+def test_host_of(key: str, value: str, host: str | None) -> None:+ assert host_of(key, value) == host+++# ---------------------------------------------------------------------------+# Matching+# ---------------------------------------------------------------------------+++def _http(repo: str, role: str, path: str, method: str = "GET", **meta) -> Contract:+ return Contract(+ repo=repo,+ contract_id=f"http::{method}::{path}",+ contract_type="http",+ role=role,+ file_path=f"{repo}/{role}.java",+ symbol_name=path,+ confidence=0.85 if role == "provider" else 0.75,+ meta={"method": method, "path": path, **meta},+ )+++def _names(**entries: str) -> ServiceNameMap:+ from repowise.core.workspace.service_names import ServiceName++ m = ServiceNameMap(repos=frozenset(entries.values()) | {"web"})+ for name, repo in entries.items():+ kind, _, name = name.rpartition("__")+ kind = kind or HOST+ m.entries[(kind, name)] = ServiceName(name, kind, repo, "compose", "deploy/compose.yml")+ return m+++def test_a_mapped_host_narrows_a_shared_path_and_names_the_rule() -> None:+ contracts = [+ _http("account", "provider", "/{param}"),+ _http("statistics", "provider", "/{param}"),+ _http("web", "consumer", "/{param}", host="statistics-service"),+ ]+ annotate_consumer_targets(contracts, {}, _names(**{"statistics-service": "statistics"}))+ consumer = contracts[-1]+ assert consumer.meta["target_via"] == "compose"+ assert consumer.meta["target_evidence"] == "deploy/compose.yml"+ state = run_matching(contracts)+ assert [(lk.provider_repo, lk.strategy) for lk in state.links] == [+ ("statistics", LinkStrategy.SERVICE_MAPPED)+ ]+ assert state.service_links == []+++def test_service_bases_win_over_the_map() -> None:+ contracts = [+ _http("a", "provider", "/x"),+ _http("b", "provider", "/x"),+ _http("web", "consumer", "/x", host="api"),+ ]+ annotate_consumer_targets(contracts, {"api": "b"}, _names(api="a"))+ assert contracts[-1].meta["target_via"] == "service_bases"+ [link] = run_matching(contracts).links+ assert link.provider_repo == "b"+++def test_a_token_resolves_through_an_env_entry() -> None:+ contracts = [+ _http("a", "provider", "/x"),+ _http("b", "provider", "/x"),+ _http("web", "consumer", "/x", base_stripped=True, base_token="CATALOGUE_URL"),+ ]+ annotate_consumer_targets(contracts, {}, _names(env__catalogue_url="b"))+ [link] = run_matching(contracts).links+ assert (link.provider_repo, link.strategy) == ("b", LinkStrategy.SERVICE_MAPPED)+++def test_a_known_host_with_an_unread_route_is_a_service_level_edge() -> None:+ contracts = [+ _http("auth", "provider", "/users", "POST"),+ _http("web", "consumer", "/uaa/users", "POST", host="auth-service"),+ _http("web", "consumer", "/nowhere", host="unmapped"),+ ]+ annotate_consumer_targets(contracts, {}, _names(**{"auth-service": "auth"}))+ state = run_matching(contracts)+ assert state.links == []+ [svc] = state.service_links+ assert (svc.consumer_repo, svc.provider_repo, svc.provider_file) == ("web", "auth", "")+ assert (svc.strategy, svc.match_type) == (LinkStrategy.HOST_ONLY, "candidate")+ assert svc.confidence == link_confidence(LinkStrategy.HOST_ONLY, 0.75)++ store = ContractStore(contracts=contracts, service_links=state.service_links)+ assert ContractStore.from_dict(store.to_dict()).service_links == state.service_links++ graph = build_system_graph(contracts, [], CrossRepoOverlay(), {}, service_links=state.service_links)+ [edge] = graph.edges+ assert (edge.source, edge.target, edge.kind, edge.strategy) == (+ "web",+ "auth",+ "http",+ LinkStrategy.HOST_ONLY,+ )+ assert edge.structural+++def test_no_service_edge_to_a_repo_outside_the_workspace() -> None:+ contracts = [+ _http("a", "provider", "/x"),+ _http("web", "consumer", "/y", base_stripped=True, base_token="API_BASE"),+ ]+ annotate_consumer_targets(contracts, {"API_BASE": "typo_repo"})+ assert "target_via" not in contracts[-1].meta+ assert run_matching(contracts).service_links == []+++def test_a_mapped_public_looking_host_is_internal_and_others_stay_external() -> None:+ contracts = [+ _http("a", "provider", "/x"),+ _http("web", "consumer", "/x", host="api.stripe.com"),+ _http("web", "consumer", "/x", host="orders.svc.cluster.local"),+ ]+ annotate_consumer_targets(contracts, {}, _names(orders="a"))+ assert contracts[1].meta.get("external") is True+ assert contracts[2].meta["target_repo"] == "a"+++def test_an_absent_map_changes_nothing() -> None:+ contracts = [_http("a", "provider", "/x"), _http("web", "consumer", "/x", host="svc")]+ annotate_consumer_targets(contracts)+ assert "target_repo" not in contracts[-1].meta+ [link] = run_matching(contracts).links+ assert link.strategy == LinkStrategy.EXACT_ID+++def test_aspire_launch_profile_is_not_a_path(tmp_path: Path) -> None:+ host = tmp_path / "host"+ host.mkdir()+ (tmp_path / "catalog").mkdir()+ (host / "host.csproj").write_text(+ r'<Project><ItemGroup><ProjectReference Include="..\catalog\Catalog.API.csproj" />'+ "</ItemGroup></Project>"+ )+ (host / "AppHost.cs").write_text(+ "var b = DistributedApplication.CreateBuilder(args);\n"+ 'b.AddProject<Projects.Catalog_API>("catalog-api", "https");\n'+ )+ m = build_service_name_map(_repos(tmp_path, "host", "catalog"))+ assert _mapped(m) == {"catalog-api": ("catalog", "aspire_apphost")}+++def test_k8s_external_name_service_is_not_a_repo(tmp_path: Path) -> None:+ (tmp_path / "pay" / "k8s").mkdir(parents=True)+ (tmp_path / "pay" / "k8s" / "svc.yaml").write_text(+ "kind: Service\nmetadata: {name: stripe-api}\n"+ "spec: {type: ExternalName, externalName: api.stripe.com}\n"+ )+ assert _mapped(build_service_name_map(_repos(tmp_path, "pay"))) == {}+++def test_a_host_equal_to_a_repo_name_alone_draws_no_service_edge() -> None:+ contracts = [_http("api", "provider", "/x"), _http("web", "consumer", "/y", host="api")]+ annotate_consumer_targets(contracts)+ assert contracts[-1].meta["target_via"] == "repo_alias"+ assert run_matching(contracts).service_links == []+ # The same name placed by config is evidence.+ annotate_consumer_targets(contracts, {}, _names(api="api"))+ assert contracts[-1].meta["target_via"] == "compose"+ assert len(run_matching(contracts).service_links) == 1+++def test_a_mapped_target_does_not_fall_back_to_another_repo() -> None:+ contracts = [+ _http("other", "provider", "/health"),+ _http("catalogue", "provider", "/products"),+ _http("web", "consumer", "/health", host="catalogue-svc"),+ ]+ annotate_consumer_targets(contracts, {}, _names(**{"catalogue-svc": "catalogue"}))+ state = run_matching(contracts)+ assert state.links == []+ assert [lk.provider_repo for lk in state.service_links] == ["catalogue"]+++def test_the_stored_map_round_trips_and_its_fingerprint_tracks_its_inputs(tmp_path: Path) -> None:+ root = FIXTURES / "robotshop"+ repos = _repos(root, "catalogue", "mongo")+ m = build_service_name_map(repos, root)+ again = ServiceNameMap.from_dict(m.to_dict("fp"))+ assert again.entries == m.entries and again.repos == m.repos++ heads = {"a": "1", "b": "2"}+ (tmp_path / "README.md").write_text("x")+ fp = service_names_fingerprint(heads, tmp_path)+ assert service_names_fingerprint(heads, tmp_path) == fp+ (tmp_path / "notes.txt").write_text("not a gated file")+ assert service_names_fingerprint(heads, tmp_path) == fp+ assert service_names_fingerprint({**heads, "b": "3"}, tmp_path) != fp+ (tmp_path / "docker-compose.yml").write_text("services: {}\n")+ assert service_names_fingerprint(heads, tmp_path) != fp+++ ("ref", "expected"),+ [+ (r"..\Catalog.API\Catalog.API.csproj", "/w/Catalog.API/Catalog.API.csproj"),+ ("../cart", "/w/cart"),+ (r".\src\Web", "/w/host/src/Web"),+ ],+)+def test_config_paths_written_on_windows_resolve_on_any_os(ref: str, expected: str) -> None:+ # PurePosixPath keeps a backslash as a literal character on every OS.+ joined = join_config_path(PurePosixPath("/w/host"), ref)+ assert posixpath.normpath(str(joined)) == expected+++def test_a_backslash_path_with_other_case_finds_its_repo(tmp_path: Path) -> None:+ host = tmp_path / "eshop.apphost"+ host.mkdir()+ (tmp_path / "catalog.api").mkdir()+ (host / "AppHost.cs").write_text(+ "var b = DistributedApplication.CreateBuilder(args);\n"+ r'b.AddProject("catalog-api", @"..\Catalog.API\Catalog.API.csproj");' "\n"+ )+ m = build_service_name_map(_repos(tmp_path, "eshop.apphost", "catalog.api"))+ assert _mapped(m) == {"catalog-api": ("catalog.api", "aspire_apphost")}