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): count a call matching two or more provider repos as an ambiguous provider instead of linking it (#4654)
Raghav Chamadiya5f5c59332969
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex c1e5c2f77..0ff7a347b 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -134,7 +134,9 @@ links are appended after it.and gRPC service wildcards included. Strategy `exact_id`, `pattern_matched` for apattern subscription, `service_mapped` when the provider sits in the consumer'sresolved target. A target the map placed does not fall back to another repo that- serves the same path (`common.prefer_target_repo`).+ serves the same path (`common.prefer_target_repo`). An HTTP or gRPC call whose id+ two or more repos serve, with nothing placing it in one, links to none of them+ (`MatchState.refuse`, `meta['ambiguous_provider']`); the HTTP passes keep that rule.A package-less gRPC stub id (`grpc::CurrencyService/*`) meets the package-qualifiedproto id (`grpc::shop.CurrencyService/Convert`) on the service's last segment. A protodeclared in 2+ repos is served only by the repo that registers the service in codediff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.mdindex 9d42a0b6e..455c67d31 100644--- a/docs/reference/WORKSPACE_CONTRACTS.md+++ b/docs/reference/WORKSPACE_CONTRACTS.md@@ -39,7 +39,7 @@ follows from the strategy.| 1.0 | `shared_table` | exact | A service that only models a table, to the one service defining its schema || 1.0 | `service_mapped` | exact | The consumer's host or base token maps to the providing service || 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 | `ambiguous_path` | candidate | The base is unread and several services of one repo 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 | `gateway_route` | exact | A gateway's config forwards the path to the service: the gateway's own edge, and a call through it linked on the forwarded path |@@ -117,8 +117,10 @@ method whose body sends its string parameter through `HttpClient` is read with tbuilds. A client callwhose base URL is an unresolved placeholder (`fetch(\`${API_BASE}/users\`)`) matcheson the host-relative path; the link is **exact** when exactly one workspace service-provides that path (`unique_path`) and a lower-confidence **candidate** when the target-is ambiguous (`ambiguous_path`). A generic operational path (`/health`, `/healthz`, `/ready`,+provides that path (`unique_path`) and a lower-confidence **candidate** when several+services of one repo serve it (`ambiguous_path`). A call whose route two or more repos+serve, with no host or base naming one, links to none of them and is reported as+`ambiguous_provider`. A generic operational path (`/health`, `/healthz`, `/ready`,`/metrics`, `/status`, `/version`, `/actuator/info`, the root) names no service, so it linksonly to the repo its host or base resolves to or, with neither, to a server in the caller'sown repo; it never links to another repo by path alone.diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 8bc29a38f..0f2cc510b 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -344,6 +344,7 @@ The report covers:- `no_provider`, a dangling call: no provider anywhere declares a matching route/service/topic/table.- `unlinked`, a cross-service provider with a matching id exists, but no link formed (a candidate worth inspecting).- `external_host`, the call targets a literal third-party host (Stripe, Formspree, ...) that is not a workspace service, so it is intentionally excluded from matching.+ - `ambiguous_provider`, two or more repos serve the call's route and neither its host nor its base names one, so it links to none of them. A `contracts.service_bases` entry for its host or base, or a `manual_links` entry, places it.- **In-service consumers** (`in_service_consumers`, reason `internal_only`): the only matching provider is in the same repo + service. They are served, so they are counted apart and never listed as unmatched.- **Orphan providers**, endpoints declared but never consumed by any repo. One row per repo, service and id; a table declared in a model and a migration lists the second file under `other_files`.- **Weak links**, matched links below the confidence threshold.diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.pyindex 313c1a82c..9f163e0df 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py@@ -250,12 +250,14 @@ _HTTP_REASON_SHORT = {"no_provider": "match no declared route","unlinked": "match a route that did not link","external_host": "call a third-party host",+ "ambiguous_provider": "match a route two or more repos serve",}_REASON_LABELS = {"no_provider": "dangling: no repo declares the route, service, topic or table they use","unlinked": "matching provider exists but no link formed","external_host": "call a third-party host, outside the workspace",+ "ambiguous_provider": "ambiguous: two or more repos serve the route, nothing names one",}#: Reasons in reading order: dangling calls first, any other reason next,diff --git a/packages/core/src/repowise/core/report/sections/estate_contracts.py b/packages/core/src/repowise/core/report/sections/estate_contracts.pyindex b1e255ce5..431b33d33 100644--- a/packages/core/src/repowise/core/report/sections/estate_contracts.py+++ b/packages/core/src/repowise/core/report/sections/estate_contracts.py@@ -21,6 +21,7 @@ _METHOD = (_REASONS = {"no_provider": "no provider in the workspace","unlinked": "a provider exists, no link formed",+ "ambiguous_provider": "two or more repos serve it, none named",}diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 789b999ba..c60a29194 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -79,6 +79,8 @@ CONTRACTS_FILENAME = "contracts.json"# skips tooling and build files.# A data consumer in a file that opens SQLite carries ``meta['embedded']`` and# links only within its repo.+# An HTTP or gRPC consumer whose id two or more repos serve, with nothing+# placing it in one, carries ``meta['ambiguous_provider']`` and links to none.CONTRACTS_VERSION = 15#: ``meta["kind"]`` of a topic contract: the destination a broker call names.@@ -264,7 +266,9 @@ class ContractStore:#: Service-level edges (:attr:`.origins.LinkStrategy.HOST_ONLY`): a consumer#: whose host names a workspace repo while no route there serves its path;#: and a gateway's edge to each service it routes to- #: (:attr:`.origins.LinkStrategy.GATEWAY_ROUTE`, no consumer contract). Kept out of ``contract_links``, which only ever pairs two contracts.+ #: (:attr:`.origins.LinkStrategy.GATEWAY_ROUTE`, no consumer contract). Kept+ #: out of ``contract_links``, which pairs two contracts; a call linked+ #: through a gateway on its forwarded path is a ``gateway_route`` link there.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 thatdiff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.pyindex 7c978c05b..f59a00ffe 100644--- a/packages/core/src/repowise/core/workspace/diagnostics.py+++ b/packages/core/src/repowise/core/workspace/diagnostics.py@@ -30,7 +30,7 @@ from repowise.core.workspace.contracts import (same_service,)from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX-from repowise.core.workspace.matching.common import shared_idl+from repowise.core.workspace.matching.common import AMBIGUOUS_PROVIDER, shared_idlfrom repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT, outside_runtimefrom repowise.core.workspace.signature_schema import SCHEMA_SOURCE@@ -61,6 +61,9 @@ class UnmatchedReason:#: The call targets a literal third-party host (Stripe, Formspree, …) that is#: not a workspace service, so it is intentionally excluded from matching.EXTERNAL_HOST = "external_host"+ #: Two or more repos serve the call's route and neither its host nor its+ #: base says which one it reaches, so it links to none of them.+ AMBIGUOUS_PROVIDER = "ambiguous_provider"#: The closed set, for the wire copies that have to agree with it.@@ -69,6 +72,7 @@ UNMATCHED_REASON_VALUES = (UnmatchedReason.INTERNAL_ONLY,UnmatchedReason.UNLINKED,UnmatchedReason.EXTERNAL_HOST,+ UnmatchedReason.AMBIGUOUS_PROVIDER,)@@ -548,6 +552,8 @@ def _classify_unmatched("""Return the :class:`UnmatchedReason` for an unmatched *consumer*."""if consumer.meta.get("external"):return UnmatchedReason.EXTERNAL_HOST+ if consumer.meta.get(AMBIGUOUS_PROVIDER):+ return UnmatchedReason.AMBIGUOUS_PROVIDERcandidates = providers_by_norm_id.get(normalize_contract_id(consumer.contract_id))if not candidates:return UnmatchedReason.NO_PROVIDERdiff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.pyindex 9f98f28cc..43b9a4d16 100644--- a/packages/core/src/repowise/core/workspace/matching/__init__.py+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py@@ -20,7 +20,7 @@ from repowise.core.workspace.contracts import normalize_contract_idfrom repowise.core.workspace.origins import LinkStrategyfrom . import data, http, topic-from .common import MatchState, find_matching_keys, internal, prefer_target_repo+from .common import MatchState, find_matching_keys, internal, prefer_target_repo, spans_reposfrom .http import annotate_consumer_targetsif TYPE_CHECKING:@@ -41,12 +41,18 @@ class TypeMatcher:accepts: Callable[[Contract, Contract], bool] | None = Nonepasses: tuple[Callable[[MatchState], None], ...] = ()keys: Callable[[Contract, dict[str, list[Contract]]], list[str]] | None = None+ #: A consumer of the type reaches one provider: when its host or base does+ #: not place it and two or more repos serve its id, it links to none of+ #: them (:meth:`.common.MatchState.refuse`). Off for broadcasts and shared+ #: tables, where every repo on the id is a true end.+ one_provider_repo: bool = FalseMATCHERS: dict[str, TypeMatcher] = {"http": TypeMatcher(deferred=http.is_deferred,accepts=http.accepts,+ one_provider_repo=True,passes=(http.gateway_pass,http.base_resolved_pass,@@ -54,6 +60,7 @@ MATCHERS: dict[str, TypeMatcher] = {http.service_pass,),),+ "grpc": TypeMatcher(one_provider_repo=True),"topic": TypeMatcher(deferred=topic.is_binding,accepts=topic.accepts,@@ -66,25 +73,38 @@ MATCHERS: dict[str, TypeMatcher] = {_NO_RULES = TypeMatcher()+def _servers(state: MatchState, consumer: Contract, rules: TypeMatcher) -> list[Contract]:+ """Providers outside *consumer*'s own service that may serve it on its id.++ A provider in its own service marks it served instead.+ """+ if rules.keys is not None:+ keys = rules.keys(consumer, state.provider_index)+ else:+ keys = find_matching_keys(consumer.contract_id, state.provider_index)+ providers = [p for k in keys for p in state.provider_index[k]]+ servers: list[Contract] = []+ for provider in prefer_target_repo(providers, consumer):+ if internal(provider, consumer):+ state.mark_served(consumer)+ elif rules.accepts is None or rules.accepts(provider, consumer):+ servers.append(provider)+ return servers++def _exact_pass(state: MatchState) -> None:for consumer in state.consumers:rules = MATCHERS.get(consumer.contract_type, _NO_RULES)if rules.deferred is not None and rules.deferred(consumer):continue+ servers = _servers(state, consumer, rules)+ if rules.one_provider_repo and spans_repos(servers):+ state.refuse(consumer)+ continueown = normalize_contract_id(consumer.contract_id)- if rules.keys is not None:- keys = rules.keys(consumer, state.provider_index)- 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 None- for provider in prefer_target_repo(providers, consumer):- if internal(provider, consumer):- state.mark_served(consumer)- continue- if rules.accepts is not None and not rules.accepts(provider, consumer):- continue+ for provider in servers:# A key the type's own rule reached under another name (a pattern# subscription, the only `keys` rule today) links under the# provider's name. A new `keys` rule with another meaning names itsdiff --git a/packages/core/src/repowise/core/workspace/matching/common.py b/packages/core/src/repowise/core/workspace/matching/common.pyindex 31bcabe5f..c4b9146d1 100644--- a/packages/core/src/repowise/core/workspace/matching/common.py+++ b/packages/core/src/repowise/core/workspace/matching/common.py@@ -13,12 +13,21 @@ from repowise.core.workspace.contracts import ()from repowise.core.workspace.origins import LinkStrategy, link_confidence, match_type_for+#: ``meta`` key on a consumer two or more repos could serve, none of them+#: placed by its host or base: it links to none of them (see :meth:`MatchState.refuse`).+AMBIGUOUS_PROVIDER = "ambiguous_provider"+def internal(provider: Contract, consumer: Contract) -> bool:"""One program calling itself, which no pass links."""return same_service(provider.repo, provider.service, consumer.repo, consumer.service)+def spans_repos(providers: list[Contract]) -> bool:+ """Whether *providers* sit in two or more repos, so the route alone cannot pick one."""+ return len({p.repo for p in providers}) > 1++@dataclassclass MatchState:"""The provider index, the consumers to place, and the links placed so far.@@ -49,8 +58,11 @@ class MatchState:if c.role == "provider":if id(c) not in vendored:provider_index[normalize_contract_id(c.contract_id)].append(c)- elif not c.meta.get("external"):- consumers.append(c)+ else:+ # Stamped by this run's passes, never carried from a stored row.+ c.meta.pop(AMBIGUOUS_PROVIDER, None)+ if not c.meta.get("external"):+ consumers.append(c)return cls(provider_index, consumers)def unmatched(self, contract_type: str) -> list[Contract]:@@ -65,6 +77,14 @@ class MatchState:"""Mark *consumer* as served internally so later matching passes skip it."""self.matched.add(id(consumer))+ def refuse(self, consumer: Contract) -> None:+ """Link *consumer* to nothing: its route is served by two or more repos and+ neither its host nor its base says which one it calls. Later passes skip+ it, and diagnostics count it as an ambiguous provider, also when its own+ service declares the route too."""+ consumer.meta[AMBIGUOUS_PROVIDER] = True+ self.matched.add(id(consumer))+def add(self,consumer: Contract,@@ -262,8 +282,10 @@ def prefer_target_repo(providers: list[Contract], consumer: Contract) -> list[Co__all__ = [+ "AMBIGUOUS_PROVIDER","MatchState","find_matching_keys","internal","prefer_target_repo",+ "spans_repos",]diff --git a/packages/core/src/repowise/core/workspace/matching/http.py b/packages/core/src/repowise/core/workspace/matching/http.pyindex 5ee391b38..7f247cf76 100644--- a/packages/core/src/repowise/core/workspace/matching/http.py+++ b/packages/core/src/repowise/core/workspace/matching/http.py@@ -28,7 +28,7 @@ from repowise.core.workspace.service_names import (ServiceNameMap,)-from .common import find_matching_keys, internal, prefer_target_repo+from .common import find_matching_keys, internal, prefer_target_repo, spans_reposif TYPE_CHECKING:from collections.abc import Iterable@@ -335,6 +335,12 @@ def _methods_compatible(consumer_method: str, provider_method: str) -> bool:return consumer_method == provider_method or consumer_method == "*" or provider_method == "*"+def _method_fits(method: str, provider: Contract) -> bool:+ """Whether *provider*'s method serves a call made with *method*."""+ split = _split_http_id(normalize_contract_id(provider.contract_id))+ return split is not None and _methods_compatible(method, split[0])++def is_deferred(consumer: Contract) -> bool:"""A base-stripped or gateway-routed consumer skips the exact pass; its own pass owns it."""return bool(consumer.meta.get("base_stripped") or "route_path" in consumer.meta)@@ -401,7 +407,9 @@ def base_resolved_pass(state: MatchState) -> None:The strategy names how the target service was settled: a host or``service_bases`` target that narrows to a provider (``service_mapped``),the only service serving the path (``unique_path``), or neither, linking- every service that serves it (``ambiguous_path``, a candidate).+ every service that serves it (``ambiguous_path``, a candidate) when they+ share one repo. Services in two or more repos link to none+ (:meth:`.common.MatchState.refuse`)."""for consumer in state.unmatched("http"):if not consumer.meta.get("base_stripped") or "route_path" in consumer.meta:@@ -421,19 +429,31 @@ def base_resolved_pass(state: MatchState) -> None:target = consumer.meta.get("target_repo")narrowed = [p for p in providers if p.repo == target] if target else []if narrowed:- providers = narrowed- if narrowed:- strategy = LinkStrategy.SERVICE_MAPPED- elif len({(p.repo, p.service) for p in providers}) == 1:- strategy = LinkStrategy.UNIQUE_PATH+ providers, strategy = narrowed, LinkStrategy.SERVICE_MAPPED+ elif spans_repos(providers):+ # A target the workspace's own config placed stays unmatched, so+ # the service pass draws its edge to that repo.+ if not consumer.meta.get("target_evidence"):+ state.refuse(consumer)+ continueelse:- strategy = LinkStrategy.AMBIGUOUS_PATH+ strategy = _one_repo_strategy(providers)for provider in providers:state.add(consumer, provider, strategy)+def _one_repo_strategy(providers: list[Contract]) -> LinkStrategy:+ """``unique_path`` for one service of one repo, ``ambiguous_path`` for several."""+ if len({p.service for p in providers}) == 1:+ return LinkStrategy.UNIQUE_PATH+ return LinkStrategy.AMBIGUOUS_PATH++def candidate_pass(state: MatchState) -> None:- """Retry unmatched consumers after collapsing mount/version/base prefixes on both sides."""+ """Retry unmatched consumers after collapsing mount/version/base prefixes on both sides.++ A collapsed path two or more repos serve links to none of them.+ """candidate_index: dict[str, list[Contract]] = defaultdict(list)for key, providers in state.provider_index.items():split = _split_http_id(key)@@ -456,12 +476,15 @@ def candidate_pass(state: MatchState) -> None:if core in ("", "/"):continue- for provider in prefer_target_repo(candidate_index.get(core, []), consumer):- if internal(provider, consumer) or not accepts(provider, consumer):- continue- psplit = _split_http_id(normalize_contract_id(provider.contract_id))- if psplit is None or not _methods_compatible(method, psplit[0]):- continue+ servers = [+ p+ for p in prefer_target_repo(candidate_index.get(core, []), consumer)+ if not internal(p, consumer) and accepts(p, consumer) and _method_fits(method, p)+ ]+ if spans_repos(servers):+ state.refuse(consumer)+ continue+ for provider in servers:state.add(consumer, provider, LinkStrategy.PREFIX_STRIPPED)diff --git a/packages/core/src/repowise/core/workspace/origins.py b/packages/core/src/repowise/core/workspace/origins.pyindex 32cc16dec..22551faf9 100644--- a/packages/core/src/repowise/core/workspace/origins.py+++ b/packages/core/src/repowise/core/workspace/origins.py@@ -89,7 +89,8 @@ class LinkStrategy(StrEnum):GATEWAY_ROUTE = "gateway_route"#: 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.+ #: The consumer's base is unread and several services of one repo serve the path;+ #: linked to each. Services in two or more repos are not linked at all.AMBIGUOUS_PATH = "ambiguous_path"#: Matched only after stripping mount, version or base prefixes from both paths.PREFIX_STRIPPED = "prefix_stripped"diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex b6c9d472e..be706b840 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -172,7 +172,8 @@ class WorkspaceContractDetail(BaseModel):#: Links this contract participates in, on whichever side it plays.links: list[WorkspaceContractLinkEntry] = []#: Why this consumer matched no provider (``external_host``,- #: ``internal_only``, ``no_provider``), from the system graph's diagnostics.+ #: ``internal_only``, ``no_provider``, ``ambiguous_provider``), from the+ #: system graph's diagnostics.#: None for providers, for linked consumers, and when no graph is built.unmatched_reason: str | None = None@@ -378,7 +379,7 @@ class WorkspaceUnmatchedConsumer(BaseModel):file_path: strcontract_id: strcontract_type: str- reason: str # no_provider | internal_only | unlinked+ reason: str # no_provider | internal_only | unlinked | external_host | ambiguous_providerclass WorkspaceOrphanProvider(BaseModel):diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex 5dc857795..c6272c76e 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -302,7 +302,8 @@ export type UnmatchedReason =| "no_provider"| "internal_only"| "unlinked"- | "external_host";+ | "external_host"+ | "ambiguous_provider";export interface RepoDiagnostics {repo: string;diff --git a/packages/ui/src/workspace/contract-facts.ts b/packages/ui/src/workspace/contract-facts.tsindex 4c0b4de16..81eb845b2 100644--- a/packages/ui/src/workspace/contract-facts.ts+++ b/packages/ui/src/workspace/contract-facts.ts@@ -328,6 +328,13 @@ export const UNMATCHED_REASONS: Record<string, UnmatchedReasonCopy> = {"Calls to a literal third-party host, left out of matching on purpose. Nothing to fix unless the host is one of your own services.",actionable: false,},+ ambiguous_provider: {+ title: "Several repos serve this route",+ short: "several repos serve it",+ meaning:+ "Two or more repositories serve these routes and nothing in the call names one, so no link is drawn. A contracts.service_bases entry for the host or base, or a manual link, places them.",+ actionable: true,+ },};const UNKNOWN_REASON: UnmatchedReasonCopy = {@@ -396,6 +403,8 @@ export function unmatchedConsumerProse(reason: string | null, contract: Contractreturn `Nothing in this workspace declares ${contractHeading(contract)}. Check for a typo in the path, an endpoint that was renamed or removed, a service outside these repositories, or a route declared in a form extraction does not recognise.`;case "unlinked":return "A declaration with this id exists in another service, but no link was formed between the two. That is rare, and it points at a gap in the matcher rather than at the code.";+ case "ambiguous_provider":+ return "Two or more repositories serve this route, and neither the host nor the base of the call says which one it reaches, so no link is drawn to any of them. To place it, add a contracts.service_bases entry for its host or base, or a manual link.";default:return "This call matched no declaration, and no reason was recorded for it. Reasons come from the system graph, so a workspace that has not built one reports the count without the explanation.";}diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.tsindex 0bd71bb21..a3f3316af 100644--- a/packages/ui/src/workspace/system-map/system-map-model.ts+++ b/packages/ui/src/workspace/system-map/system-map-model.ts@@ -296,6 +296,7 @@ const UNMATCHED_REASON: Record<string, string> = {external_host: "call a third-party host",internal_only: "stay inside their own service",unlinked: "have a provider that did not link",+ ambiguous_provider: "match a route two or more repos serve",};/** "54 have no provider anywhere, 26 call a third-party host", largest first. */diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 96c367c2a..e61a035a1 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -1813,6 +1813,7 @@"unlinked": "unlinked","internal_only": "internal to one service","external_host": "external host",+ "ambiguous_provider": "several repos serve it","unknown": "no reason recorded","everyMatched": "every consumer matched a provider"},@@ -1888,6 +1889,7 @@"unlinked": "No link formed","internal_only": "Not a cross-repo link","external_host": "Outside this workspace",+ "ambiguous_provider": "Several repos serve this route","unknown": "No provider found"},"prose": {@@ -1900,6 +1902,7 @@"unmatchedExternalHostGeneric": "This call goes to a third-party host, which is not a service in this workspace. Calls to a literal external host are left out of matching on purpose, so there is nothing to link. If that host is one of your own services, add its repository to the workspace.","unmatchedInternalOnly": "The only declarations matching this call live in the same repository and the same service as the call itself, so it never crosses a boundary. Intra-service calls are left out of the link set on purpose: a link is a claim that two services depend on each other.","unmatchedNoProvider": "Nothing in this workspace declares {contract}. Check for a typo in the path, an endpoint that was renamed or removed, a service outside these repositories, or a route declared in a form extraction does not recognise.",+ "unmatchedAmbiguousProvider": "Two or more repositories serve this route, and neither the host nor the base of the call says which one it reaches, so no link is drawn to any of them. To place it, add a contracts.service_bases entry for its host or base, or a manual link.","unmatchedUnlinked": "A declaration with this id exists in another service, but no link was formed between the two. That is rare, and it points at a gap in the matcher rather than at the code.","unmatchedDefault": "This call matched no declaration, and no reason was recorded for it. Reasons come from the system graph, so a workspace that has not built one reports the count without the explanation."},diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 84c6312d9..c4f551a93 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -1813,6 +1813,7 @@"unlinked": "未建立链接","internal_only": "仅限同一服务内部","external_host": "外部主机",+ "ambiguous_provider": "多个仓库提供","unknown": "未记录原因","everyMatched": "每个消费方都匹配到了提供方"},@@ -1888,6 +1889,7 @@"unlinked": "未建立链接","internal_only": "不是跨仓库链接","external_host": "不在本工作区内",+ "ambiguous_provider": "多个仓库提供该路由","unknown": "未找到提供方"},"prose": {@@ -1900,6 +1902,7 @@"unmatchedExternalHostGeneric": "该调用发往第三方主机,而它不是本工作区中的服务。发往字面外部主机的调用按设计不参与匹配,因此没有可建立的链接。如果该主机是你自己的服务之一,请把它的仓库加入工作区。","unmatchedInternalOnly": "与该调用匹配的声明都位于同一仓库、同一服务内,因此它从未跨越边界。服务内部的调用按设计不进入链接集合:一条链接意味着两个服务互相依赖。","unmatchedNoProvider": "本工作区内没有任何内容声明 {contract}。请检查路径是否有拼写错误、端点是否被重命名或删除、该服务是否在这些仓库之外,或者路由是否以提取无法识别的方式声明。",+ "unmatchedAmbiguousProvider": "有两个或更多仓库提供该路由,而该调用的主机和基础地址都没有指明它调用的是哪一个,因此不会与其中任何一个建立链接。如需确定目标,请为其主机或基础地址添加 contracts.service_bases 条目,或添加手动链接。","unmatchedUnlinked": "另一个服务中存在具有该 id 的声明,但两者之间没有建立链接。这种情况很少见,它指向匹配器的缺口,而不是代码的问题。","unmatchedDefault": "该调用没有匹配到任何声明,也没有记录原因。原因来自系统图,因此尚未构建系统图的工作区只能报告数量,而无法给出解释。"},diff --git a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx b/packages/web/src/app/workspace/contracts/detail/contract-body.tsxindex cf2a7e9e9..a74de412a 100644--- a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx+++ b/packages/web/src/app/workspace/contracts/detail/contract-body.tsx@@ -184,6 +184,7 @@ const REASON_TITLE_KEYS: Record<string, string> = {unlinked: "detail.reasonTitle.unlinked",internal_only: "detail.reasonTitle.internal_only",external_host: "detail.reasonTitle.external_host",+ ambiguous_provider: "detail.reasonTitle.ambiguous_provider",};/**@@ -224,6 +225,8 @@ function unmatchedConsumerDescription(});case "unlinked":return t("detail.prose.unmatchedUnlinked");+ case "ambiguous_provider":+ return t("detail.prose.unmatchedAmbiguousProvider");default:return t("detail.prose.unmatchedDefault");}diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsxindex 5236bb8be..142ff6106 100644--- a/packages/web/src/app/workspace/contracts/page.tsx+++ b/packages/web/src/app/workspace/contracts/page.tsx@@ -283,6 +283,7 @@ const REASON_KEYS: Record<string, string> = {unlinked: "reasons.unlinked",internal_only: "reasons.internal_only",external_host: "reasons.external_host",+ ambiguous_provider: "reasons.ambiguous_provider",};/** Name why consumers went unmatched, since the count alone invites the wrong read. */diff --git a/tests/unit/workspace/test_ambiguous_provider.py b/tests/unit/workspace/test_ambiguous_provider.pynew file mode 100644index 000000000..3b9158a8b--- /dev/null+++ b/tests/unit/workspace/test_ambiguous_provider.py@@ -0,0 +1,117 @@+"""A call two or more repos could serve, with nothing naming one, links to none of them."""++from __future__ import annotations++from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.diagnostics import UnmatchedReason, build_diagnostics+from repowise.core.workspace.matching import annotate_consumer_targets, run_matching+from repowise.core.workspace.matching.common import AMBIGUOUS_PROVIDER+from repowise.core.workspace.origins import LinkStrategy+++def _c(repo: str, role: str, contract_id: str, contract_type: str = "http", **meta) -> Contract:+ return Contract(+ repo=repo,+ contract_id=contract_id,+ contract_type=contract_type,+ role=role,+ file_path=f"{role}.ts",+ symbol_name="x",+ confidence=0.9,+ meta=dict(meta),+ )+++def _match(contracts: list[Contract], service_bases: dict[str, str] | None = None):+ annotate_consumer_targets(contracts, service_bases)+ return run_matching(contracts).links+++def test_a_route_two_repos_serve_links_to_neither_and_reads_as_ambiguous() -> None:+ contracts = [+ _c("shop-a", "provider", "http::GET::/cart"),+ _c("shop-b", "provider", "http::GET::/cart"),+ _c("web", "consumer", "http::GET::/cart"),+ ]+ links = _match(contracts)+ assert links == []+ assert contracts[2].meta[AMBIGUOUS_PROVIDER] is True+ diag = build_diagnostics(contracts, links)+ assert [u.reason for u in diag.unmatched_consumers] == [UnmatchedReason.AMBIGUOUS_PROVIDER]+ assert diag.unmatched_by_reason == {UnmatchedReason.AMBIGUOUS_PROVIDER: 1}+++def test_a_host_that_names_one_repo_still_links_it() -> None:+ contracts = [+ _c("shop-a", "provider", "http::GET::/cart"),+ _c("shop-b", "provider", "http::GET::/cart"),+ _c("web", "consumer", "http::GET::/cart", host="cart-api"),+ ]+ links = _match(contracts, {"cart-api": "shop-a"})+ assert [(lk.provider_repo, lk.strategy) for lk in links] == [+ ("shop-a", LinkStrategy.SERVICE_MAPPED)+ ]+ assert AMBIGUOUS_PROVIDER not in contracts[2].meta+++def test_two_providers_in_one_repo_still_link() -> None:+ other = _c("shop", "provider", "http::GET::/cart")+ other.file_path = "routes/cart.ts"+ contracts = [_c("shop", "provider", "http::GET::/cart"), other, _c("web", "consumer", "http::GET::/cart")]+ assert {lk.provider_file for lk in _match(contracts)} == {"provider.ts", "routes/cart.ts"}+++def test_a_grpc_service_two_repos_serve_links_to_neither() -> None:+ contracts = [+ _c("pay-a", "provider", "grpc::shop.Payments/Charge", "grpc"),+ _c("pay-b", "provider", "grpc::shop.Payments/Charge", "grpc"),+ _c("checkout", "consumer", "grpc::shop.Payments/Charge", "grpc"),+ ]+ assert _match(contracts) == []+++def test_a_topic_two_repos_publish_links_to_both() -> None:+ contracts = [+ _c("orders", "provider", "topic::order-placed", "topic"),+ _c("returns", "provider", "topic::order-placed", "topic"),+ _c("mailer", "consumer", "topic::order-placed", "topic"),+ ]+ assert {lk.provider_repo for lk in _match(contracts)} == {"orders", "returns"}+++def test_a_prefix_stripped_route_two_repos_serve_links_to_neither() -> None:+ contracts = [+ _c("shop-a", "provider", "http::GET::/users"),+ _c("shop-b", "provider", "http::GET::/v1/users"),+ _c("web", "consumer", "http::GET::/api/v1/users"),+ ]+ assert _match(contracts) == []+ assert contracts[2].meta[AMBIGUOUS_PROVIDER] is True+++def test_the_mark_is_recomputed_on_every_run() -> None:+ contracts = [+ _c("shop-a", "provider", "http::GET::/cart"),+ _c("shop-b", "provider", "http::GET::/cart"),+ _c("web", "consumer", "http::GET::/cart"),+ ]+ _match(contracts)+ del contracts[1]+ links = _match(contracts)+ assert [lk.provider_repo for lk in links] == ["shop-a"]+ assert AMBIGUOUS_PROVIDER not in contracts[1].meta+++def test_a_mapped_target_serving_nothing_keeps_its_service_edge() -> None:+ contracts = [+ _c("shop-a", "provider", "http::GET::/cart"),+ _c("shop-b", "provider", "http::GET::/cart"),+ _c("cart", "provider", "http::GET::/other"),+ _c("web", "consumer", "http::GET::/cart", base_stripped=True, base_token="CART_URL"),+ ]+ annotate_consumer_targets(contracts)+ contracts[3].meta.update(target_repo="cart", target_via="compose", target_evidence="cart/compose.yml")+ state = run_matching(contracts)+ assert state.links == []+ assert AMBIGUOUS_PROVIDER not in contracts[3].meta+ assert [lk.provider_repo for lk in state.service_links] == ["cart"]diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.pyindex 819df8aad..4d693ce84 100644--- a/tests/unit/workspace/test_contracts.py+++ b/tests/unit/workspace/test_contracts.py@@ -25,6 +25,8 @@ from repowise.core.workspace.extractors.service_boundary import ()from repowise.core.workspace.extractors.socket import SocketExtractorfrom repowise.core.workspace.matching import annotate_consumer_targets, match_contracts+from repowise.core.workspace.matching.common import AMBIGUOUS_PROVIDER+from repowise.core.workspace.origins import LinkStrategy# ---------------------------------------------------------------------------# normalize_http_path@@ -1077,18 +1079,30 @@ class TestCandidateMatching:assert len(links) == 1assert links[0].match_type == "exact"- def test_base_stripped_consumer_ambiguous_is_candidate(self) -> None:- # The same stripped path provided by two distinct services is ambiguous —- # we can't tell which one the base points at, so both links are candidate.+ def test_base_stripped_consumer_two_services_of_one_repo_is_candidate(self) -> None:+ # Two services of one repo serve the stripped path: the repo is known,+ # the service is not, so both links are candidates.+ contracts = [+ self._c(repo="backend", role="provider", contract_id="http::GET::/resource",+ service="orders"),+ self._c(repo="backend", role="provider", contract_id="http::GET::/resource",+ service="billing", file_path="g.py"),+ self._c(repo="frontend", role="consumer", contract_id="http::GET::/resource",+ file_path="c.ts", meta={"base_stripped": True}),+ ]+ links = match_contracts(contracts)+ assert [lk.strategy for lk in links] == [LinkStrategy.AMBIGUOUS_PATH] * 2++ def test_base_stripped_consumer_two_repos_links_none(self) -> None:+ # Two repos serve the stripped path and the base names neither.contracts = [self._c(repo="backend", role="provider", contract_id="http::GET::/resource"),self._c(repo="payments", role="provider", contract_id="http::GET::/resource"),self._c(repo="frontend", role="consumer", contract_id="http::GET::/resource",file_path="c.ts", meta={"base_stripped": True}),]- links = match_contracts(contracts)- assert len(links) == 2- assert all(lk.match_type == "candidate" for lk in links)+ assert match_contracts(contracts) == []+ assert contracts[2].meta[AMBIGUOUS_PROVIDER] is Truedef test_base_stripped_consumer_resolved_by_service_bases(self) -> None:# An ambiguous stripped path is promoted to exact (and narrowed to the@@ -1173,7 +1187,7 @@ class TestCandidateMatching:assert len(links) == 1assert links[0].provider_repo == "backend"- def test_base_stripped_stale_service_base_stays_candidate(self) -> None:+ def test_base_stripped_stale_service_base_stays_ambiguous(self) -> None:# A service_bases target that matches no provider must fall back to the# ambiguity rule, not emit exact links to every service.contracts = [@@ -1183,9 +1197,8 @@ class TestCandidateMatching:file_path="c.ts", meta={"base_stripped": True, "base_token": "API_BASE"}),]annotate_consumer_targets(contracts, {"API_BASE": "typo_repo"})- links = match_contracts(contracts)- assert len(links) == 2- assert all(lk.match_type == "candidate" for lk in links)+ assert match_contracts(contracts) == []+ assert contracts[2].meta[AMBIGUOUS_PROVIDER] is Truedef test_method_mismatch_no_candidate(self) -> None:contracts = [diff --git a/tests/unit/workspace/test_origins.py b/tests/unit/workspace/test_origins.pyindex ee81e1095..f4cc11c77 100644--- a/tests/unit/workspace/test_origins.py+++ b/tests/unit/workspace/test_origins.py@@ -128,6 +128,13 @@ def _consumer(path: str, **meta) -> Contract:return _http("web", "consumer", path, ContractOrigin.NAME_HEURISTIC, **meta)+def _in_service(contract: Contract, service: str) -> Contract:+ """*contract* in *service* of its repo, in a file of its own."""+ contract.service = service+ contract.file_path = f"{service}/{contract.file_path}"+ return contract++@pytest.mark.parametrize(("contracts", "service_bases", "strategy"),[@@ -149,8 +156,8 @@ def _consumer(path: str, **meta) -> Contract:),([- _provider("users", "/users"),- _provider("admin", "/users"),+ _in_service(_provider("api", "/users"), "users"),+ _in_service(_provider("api", "/users"), "admin"),_consumer("/users", base_stripped=True),],{},