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
fix(workspace): a generic path such as /health never links to another repo by path alone (#4586)
Raghav Chamadiyad541837e4274
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex f624f7860..d29aee5ef 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -141,6 +141,9 @@ links are appended after it.4. **Type passes**, in `MATCHERS` order: HTTP `gateway_pass` (`gateway_route`),`base_resolved_pass`, `candidate_pass` (`unique_path`, `ambiguous_path`, `prefix_stripped`) and `service_pass`; topic`binding_pass` (`binding_routed`); data `shared_table_pass` (`shared_table`).+ HTTP's `accepts` (`matching/http.py`) holds every pass to one rule: a generic+ operational path (`/health`, `/metrics`, the root) links only to the consumer's+ resolved target repo, or with none to its own repo.5. **Service links**: `service_pass` gives each HTTP consumer whose target is aworkspace repo, but whose path no provider serves, one `host_only` link with noprovider file. These live in `ContractStore.service_links`, apart fromdiff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.mdindex 2b0ef7b0d..62532e63f 100644--- a/docs/reference/WORKSPACE_CONTRACTS.md+++ b/docs/reference/WORKSPACE_CONTRACTS.md@@ -118,7 +118,10 @@ builds. 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 serviceprovides that path (`unique_path`) and a lower-confidence **candidate** when the target-is ambiguous (`ambiguous_path`).+is ambiguous (`ambiguous_path`). A generic operational path (`/health`, `/healthz`, `/ready`,+`/metrics`, `/status`, `/version`, `/actuator/info`, the root) names no service, so it links+only to the repo its host or base resolves to or, with neither, to a server in the caller's+own repo; it never links to another repo by path alone.## Service namesdiff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.pyindex e4fc3cf1c..9f98f28cc 100644--- a/packages/core/src/repowise/core/workspace/matching/__init__.py+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py@@ -46,6 +46,7 @@ class TypeMatcher:MATCHERS: dict[str, TypeMatcher] = {"http": TypeMatcher(deferred=http.is_deferred,+ accepts=http.accepts,passes=(http.gateway_pass,http.base_resolved_pass,diff --git a/packages/core/src/repowise/core/workspace/matching/http.py b/packages/core/src/repowise/core/workspace/matching/http.pyindex 7d6c182db..5ee391b38 100644--- a/packages/core/src/repowise/core/workspace/matching/http.py+++ b/packages/core/src/repowise/core/workspace/matching/http.py@@ -50,6 +50,33 @@ if TYPE_CHECKING:_MOUNT_PREFIX_SEGMENTS = frozenset({"api", "rest"})_VERSION_SEGMENT_RE = re.compile(r"^v\d+$")+# Segments of the operational endpoints nearly every service serves (health,+# readiness, liveness, metrics, version, Spring's actuator). A path made only of+# these, after the mount prefixes above, names no service: two services both+# answer ``/health``, so a call to it links only where a host or base placed it,+# or with neither inside the caller's own repo (:func:`accepts`).+_GENERIC_SEGMENTS = frozenset(+ {+ "health",+ "healthz",+ "healthcheck",+ "health-check",+ "ready",+ "readyz",+ "readiness",+ "live",+ "livez",+ "liveness",+ "alive",+ "ping",+ "metrics",+ "status",+ "version",+ "info",+ "actuator",+ }+)+# Request paths ending in these suffixes are static assets, never API contracts.# They are excluded from the candidate pass so a ``fetch('/static/app.js')``# can't spuriously link to a provider route that shares a suffix. ``.json`` and@@ -276,6 +303,33 @@ def _is_static_asset_path(path: str) -> bool:return last.endswith(_STATIC_ASSET_SUFFIXES)+def _is_generic_path(path: str) -> bool:+ """True when *path* is the root or only operational segments (``/health``, ``/api/v1/metrics``).++ Leading mount and version prefixes and leading unresolved ``{param}``+ segments are stripped first, so ``/{param}/status`` is generic: the+ unresolved segment cannot place the call, and the rest names no service.+ """+ segments = [s for s in _candidate_http_path(path).split("/") if s]+ if not segments:+ return not path.strip("/") # the root; a bare ``/{param}`` or ``/api/v1`` is not generic+ return all(s in _GENERIC_SEGMENTS for s in segments)+++def accepts(provider: Contract, consumer: Contract) -> bool:+ """Whether *provider* may serve *consumer* when the path alone joins them.++ A generic path (:func:`_is_generic_path`) links only to the consumer's+ resolved target repo, or, with no target, to a provider in the consumer's+ own repo (a script probing the server it ships beside). Any other path+ is accepted.+ """+ split = _split_http_id(normalize_contract_id(consumer.contract_id))+ if split is None or not _is_generic_path(consumer.meta.get("route_path", split[1]).lower()):+ return True+ return provider.repo == (consumer.meta.get("target_repo") or consumer.repo)++def _methods_compatible(consumer_method: str, provider_method: str) -> bool:"""HTTP methods match if equal or either side is the ``*`` wildcard."""return consumer_method == provider_method or consumer_method == "*" or provider_method == "*"@@ -357,7 +411,7 @@ def base_resolved_pass(state: MatchState) -> None:pfor k in matching_keysfor p in state.provider_index[k]- if not internal(p, consumer)+ if not internal(p, consumer) and accepts(p, consumer)]if not providers:continue@@ -403,7 +457,7 @@ def candidate_pass(state: MatchState) -> None:continuefor provider in prefer_target_repo(candidate_index.get(core, []), consumer):- if internal(provider, consumer):+ if internal(provider, consumer) or not accepts(provider, consumer):continuepsplit = _split_http_id(normalize_contract_id(provider.contract_id))if psplit is None or not _methods_compatible(method, psplit[0]):@@ -454,6 +508,7 @@ def service_pass(state: MatchState) -> None:__all__ = [+ "accepts","annotate_consumer_targets","base_resolved_pass","candidate_pass",diff --git a/tests/unit/workspace/test_generic_path_matching.py b/tests/unit/workspace/test_generic_path_matching.pynew file mode 100644index 000000000..63c953675--- /dev/null+++ b/tests/unit/workspace/test_generic_path_matching.py@@ -0,0 +1,72 @@+"""A generic operational path (``/health``, ``/metrics``) never links across repos by path alone."""++from __future__ import annotations++import pytest++from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.matching import annotate_consumer_targets, match_contracts+from repowise.core.workspace.origins import ORIGIN_CONFIDENCE, ContractOrigin, LinkStrategy+++def _http(repo: str, role: str, path: str, service: str | None = None, **meta) -> Contract:+ origin = ContractOrigin.ROUTE_REGISTRATION if role == "provider" else ContractOrigin.NAME_HEURISTIC+ return Contract(+ repo=repo,+ contract_id=f"http::GET::{path}",+ contract_type="http",+ role=role,+ file_path=f"{repo}/{service or 'app'}.ts",+ symbol_name=path,+ confidence=ORIGIN_CONFIDENCE[origin],+ meta={"method": "GET", "path": path, **meta},+ origin=origin,+ service=service,+ )+++def _links(contracts: list[Contract], service_bases: dict[str, str] | None = None):+ annotate_consumer_targets(contracts, service_bases)+ return [(link.provider_repo, link.strategy) for link in match_contracts(contracts)]+++ ("consumer_path", "provider_path", "meta"),+ [+ ("/health", "/health", {"base_stripped": True, "base_token": "url"}), # unique_path+ ("/healthz", "/healthz", {}), # exact pass, relative call+ ("/api/v1/metrics", "/metrics", {}), # candidate pass+ ("/", "/", {"base_stripped": True}),+ ("/actuator/health", "/actuator/health", {"host": "localhost"}),+ ("/{param}/status", "/{param}/status", {}),+ ("/{param}/health", "/health", {}),+ ],+)+def test_generic_path_does_not_link_to_another_repo(consumer_path, provider_path, meta) -> None:+ contracts = [_http("backend", "provider", provider_path), _http("web", "consumer", consumer_path, **meta)]+ assert _links(contracts) == []+++def test_generic_path_links_where_the_base_names_the_repo() -> None:+ contracts = [+ _http("backend", "provider", "/health"),+ _http("web", "consumer", "/health", base_stripped=True, base_token="backend_url"),+ ]+ assert _links(contracts, {"BACKEND_URL": "backend"}) == [("backend", LinkStrategy.SERVICE_MAPPED)]+++def test_generic_path_prefers_the_server_in_its_own_repo() -> None:+ contracts = [+ _http("backend", "provider", "/health"),+ _http("tool", "provider", "/health", service="server"),+ _http("tool", "consumer", "/health", service="cli", base_stripped=True),+ ]+ assert _links(contracts) == [("tool", LinkStrategy.UNIQUE_PATH)]+++ "path", ["/health/coordinator", "/status/{param}", "/repos/{param}/health", "/{param}", "/api/{param}"]+)+def test_a_specific_path_still_links_by_path(path: str) -> None:+ contracts = [_http("backend", "provider", path), _http("web", "consumer", path, base_stripped=True)]+ assert _links(contracts) == [("backend", LinkStrategy.UNIQUE_PATH)]