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): read Next.js handlers exported from a brace list, mark Supabase calls third-party, keep tooling out of miss counts (#4589)
Raghav Chamadiya78f3dff1c809
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex a3ec018ee..c1e5c2f77 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -127,7 +127,9 @@ links are appended after it.internal DNS name such as `catalog.svc.cluster.local`), and the service-name map.The consumer's `meta` records `target_repo`, `target_via` (the source) and, for amap entry, `target_evidence` (the file). A public dotted host nothing maps is- `external` and never linked.+ `external` and never linked. So is a call whose base token and path match a+ `matching/third_party.py` row (`${SUPABASE_URL}/rest/v1/...`) and that nothing+ above placed.3. **Exact pass** (`matching/__init__.py::_exact_pass`): normalized ids, HTTP methodand gRPC service wildcards included. Strategy `exact_id`, `pattern_matched` for apattern subscription, `service_mapped` when the provider sits in the consumer's@@ -287,6 +289,7 @@ Details the table compresses:| Service-name sources | `service_names/__init__.py` `SOURCES`, sorted by name | `name`, `filenames`, optional `under` and `marker`, `read` | `test_service_names.py` || Evidence rules | `graph_evidence.py` `_RULES` | One function returning a reason or `None` | `test_graph_evidence.py` || Network probe | `network_probe.py` `PROBE_ROWS`, sorted by language | `language`, `extensions`, `tokens`, `hash_comments` | `test_network_probe.py` |+| Third-party services | `matching/third_party.py` `THIRD_PARTY_SERVICES`, sorted by name | `name`, `base_words`, `paths` | `test_third_party_services.py` || Edge kinds | `system_graph.py` `_CONTRACT_TYPE_TO_EDGE_KIND` | Contract type to edge kind | `test_system_graph.py::test_contract_type_to_edge_kind` || Package ecosystems | `manifests.py` `ECOSYSTEMS` | Service markers and an optional manifest scanner | `test_manifests.py` |diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 76b257100..fa1571c74 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -229,6 +229,9 @@ A route or topic that exists only in a test is a fixture, not a service contractCalls to a literalthird-party host (Stripe, Formspree, ...) that is not a workspace service areexcluded from matching and reported under the `external_host` diagnostics reason.+So is a call through a base variable that names a well-known service, on that+service's API paths (`${SUPABASE_URL}/rest/v1/...`), unless the workspace maps the+variable to one of its repos.**MassTransit.** A message is routed by its .NET type, so its contract id is`topic::<namespace>:<type>` (lowercased), not a string. A type counts as a message@@ -341,7 +344,7 @@ The report covers:- **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.-- **Extraction coverage**: how many contracts came from the parsed symbol table (`index`) versus a text dialect (`regex`), and how many HTTP client calls were located but could not be resolved to an endpoint. The HTTP coverage percentage is calls resolved over calls located, plus one per file that makes a network call (a client library, channel or raw request) no dialect read, so an unsupported client lowers the figure instead of dropping out of it. Each such file counts once, so it is a floor on what was missed, not total recall. It is the figure that turns a large orphan-provider count from alarming into explained. A call read is not a call linked, so the headline leads with the HTTP calls that linked to another service (`http_consumers_linked`, `http_link_coverage`, same denominator) and then says where the read but unlinked calls went.+- **Extraction coverage**: how many contracts came from the parsed symbol table (`index`) versus a text dialect (`regex`), and how many HTTP client calls were located but could not be resolved to an endpoint. The HTTP coverage percentage is calls resolved over calls located, plus one per file that makes a network call (a client library, channel or raw request) no dialect read, so an unsupported client lowers the figure instead of dropping out of it. Each such file counts once, so it is a floor on what was missed, not total recall. Files classed as tooling or build (`scripts/`, `.github/`, migrations, build configs) are left out of the probe, and a call from one that linked nothing is left out of every count, since it is not a call of the running system. It is the figure that turns a large orphan-provider count from alarming into explained. A call read is not a call linked, so the headline leads with the HTTP calls that linked to another service (`http_consumers_linked`, `http_link_coverage`, same denominator) and then says where the read but unlinked calls went.The same data is available over REST at `GET /api/workspace/diagnostics` and is embedded in the system graph artifact's `diagnostics` block.diff --git a/packages/core/src/repowise/core/code_origin.py b/packages/core/src/repowise/core/code_origin.pyindex 1e6812208..6512dd696 100644--- a/packages/core/src/repowise/core/code_origin.py+++ b/packages/core/src/repowise/core/code_origin.py@@ -779,9 +779,22 @@ def is_migration_path(path: str) -> bool:return split is not None and _is_migration_dir(split[2])+# A ``scripts/`` folder inside a served static tree holds the browser scripts+# the product ships (Spring Boot's ``resources/static/scripts``, a ``public/``+# folder), not developer tooling.+_SERVED_DIRS = frozenset({"static", "public", "assets", "_static"})+_SERVED_SCRIPTS_DIR = "scripts"+++def _is_tooling_dir(i: int, d: str, dirs: list[str]) -> bool:+ if d not in _TOOLING_DIR_TOKENS:+ return False+ return d != _SERVED_SCRIPTS_DIR or _SERVED_DIRS.isdisjoint(dirs[:i])++def _is_tooling(name: str, dirs: list[str]) -> bool:return (- any(d in _TOOLING_DIR_TOKENS for d in dirs)+ any(_is_tooling_dir(i, d, dirs) for i, d in enumerate(dirs))or bool(dirs and dirs[0] in _TOOLING_ROOT_DIRS)or _is_migration_dir(dirs)or (not dirs and name in _TOOLING_ROOT_NAMES)diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.pyindex e7821b862..83954fe7b 100644--- a/packages/core/src/repowise/core/ingestion/framework_routes.py+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py@@ -1188,10 +1188,22 @@ def _exported_names(content: str, pattern: re.Pattern[str]) -> list[tuple[str, i# The App Router takes the verb from the exported name and the path from the# file's location, so a route handler's text holds no path literal at all.-_NEXT_HANDLER_RE = re.compile(- _EXPORT_HEAD + r"(?P<name>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b",+_NEXT_VERBS = r"GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS"+_NEXT_HANDLER_RE = re.compile(_EXPORT_HEAD + rf"(?P<name>{_NEXT_VERBS})\b", re.MULTILINE)++# The same handlers exported from a brace list: destructured from a library's+# handler object (`export const { GET, POST } = handlers`) or named in an export+# list (`export { handler as GET }`, `export { GET } from "./auth"`).+_NEXT_HANDLER_LIST_RE = re.compile(+ r"^[^\S\n]*(?P<export>export)\s+(?:(?:const|let|var)\s+)?\{(?P<body>[^}]*)\}",re.MULTILINE,)+# A verb the list binds under its own name. One followed by `:` is a key the+# destructuring renames, one followed by `as` is exported under another name,+# and one after an inline `type` modifier exports only a type.+_NEXT_LISTED_VERB_RE = re.compile(+ rf"(?<![\w$.])(?P<type>type\s+)?(?P<name>{_NEXT_VERBS})\b(?!\s*(?::|as\b))"+)def next_app_router_file(rel_path: str) -> bool:@@ -1228,7 +1240,17 @@ def next_route_path(rel_path: str) -> str | None:def next_route_verbs(content: str) -> list[tuple[str, int]]:"""``(verb, offset)`` per exported handler, in declaration order."""- return _exported_names(content, _NEXT_HANDLER_RE)+ found = _exported_names(content, _NEXT_HANDLER_RE)+ for m in _NEXT_HANDLER_LIST_RE.finditer(content):+ listed = _NEXT_LISTED_VERB_RE.finditer(m.group("body"))+ found += [(v.group("name"), m.start("export")) for v in listed if not v.group("type")]+ seen: set[str] = set()+ out: list[tuple[str, int]] = []+ for verb, offset in sorted(found, key=lambda pair: pair[1]):+ if verb not in seen:+ seen.add(verb)+ out.append((verb, offset))+ return out# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex f6bcb39e0..789b999ba 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -75,6 +75,8 @@ CONTRACTS_FILENAME = "contracts.json"# (see :mod:`.network_probe`). Gateway routes (Spring Cloud Gateway, Zuul)# rewrite the calls they forward and add gateway-to-service service links.# Go routes from chi, fiber, gorilla/mux and Go 1.22 method patterns are read.+# Next.js route handlers exported from a brace list are read, and the probe+# skips tooling and build files.# A data consumer in a file that opens SQLite carries ``meta['embedded']`` and# links only within its repo.CONTRACTS_VERSION = 15@@ -593,6 +595,7 @@ async def run_contract_extraction(from .extractors.masstransit import MessageTypeIndexfrom .matching import annotate_consumer_targets, run_matchingfrom .matching.base_paths import apply_base_paths+ from .matching.third_party import mark_third_party_callsfrom .service_names import ServiceNameMap, build_service_name_map, service_names_fingerprintcontract_config = ws_config.contracts@@ -676,6 +679,7 @@ async def run_contract_extraction(names = await asyncio.to_thread(build_service_name_map, repo_paths, workspace_root)apply_base_paths(all_contracts, names.base_paths)annotate_consumer_targets(all_contracts, contract_config.service_bases, names)+ mark_third_party_calls(all_contracts)matched = run_matching(all_contracts, names.routes)links = matched.linksdiff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.pyindex 54bd60c24..56eb68fb0 100644--- a/packages/core/src/repowise/core/workspace/diagnostics.py+++ b/packages/core/src/repowise/core/workspace/diagnostics.py@@ -31,7 +31,7 @@ from repowise.core.workspace.contracts import ()from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEXfrom repowise.core.workspace.matching.common import shared_idl-from repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT+from repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT, outside_runtimefrom repowise.core.workspace.signature_schema import SCHEMA_SOURCE# ---------------------------------------------------------------------------@@ -575,6 +575,8 @@ def build_diagnostics(contract. Omitting it costs the coverage figures, not the rest."""stats_by_repo = extraction_stats or {}+ matched_consumers, matched_providers, weak_links = _matched_endpoints(links)+ contracts = _runtime_contracts(contracts, matched_consumers)# A vendored proto copy is counted with its repo's rows, never as an orphan.vendored = shared_idl(contracts)providers = [c for c in contracts if c.role == "provider" and id(c) not in vendored]@@ -617,17 +619,6 @@ def build_diagnostics())- # Matched endpoint sets (normalized) ------------------------------------- matched_consumers: set[tuple[str, str, str]] = set()- matched_providers: set[tuple[str, str, str]] = set()- weak_links = 0- for lk in links:- consumer_id = lk.consumer_contract_id or lk.contract_id- matched_consumers.add(_contract_key(lk.consumer_repo, lk.consumer_file, consumer_id))- matched_providers.add(_contract_key(lk.provider_repo, lk.provider_file, lk.contract_id))- if lk.confidence <= WEAK_LINK_CONFIDENCE_THRESHOLD:- weak_links += 1-providers_by_norm_id: dict[str, list[Contract]] = defaultdict(list)for p in providers:providers_by_norm_id[normalize_contract_id(p.contract_id)].append(p)@@ -718,6 +709,43 @@ def build_diagnostics()+def _matched_endpoints(+ links: list[ContractLink],+) -> tuple[set[tuple[str, str, str]], set[tuple[str, str, str]], int]:+ """Normalized (consumer, provider) endpoint keys the links reach, and the weak count."""+ consumers: set[tuple[str, str, str]] = set()+ providers: set[tuple[str, str, str]] = set()+ weak = 0+ for lk in links:+ consumer_id = lk.consumer_contract_id or lk.contract_id+ consumers.add(_contract_key(lk.consumer_repo, lk.consumer_file, consumer_id))+ providers.add(_contract_key(lk.provider_repo, lk.provider_file, lk.contract_id))+ if lk.confidence <= WEAK_LINK_CONFIDENCE_THRESHOLD:+ weak += 1+ return consumers, providers, weak+++def _runtime_contracts(+ contracts: list[Contract], matched_consumers: set[tuple[str, str, str]]+) -> list[Contract]:+ """*contracts* less the unlinked consumers in tooling and build files.++ A script polling a dev server is not a call of the running system, so it is+ left out of every count here, as the network probe leaves those files out+ of its own. One that linked stays: the link shows it reaches a service.+ Ceiling: the origin is path-only, so a product folder named ``tools/`` or+ ``scripts/`` reads as tooling too; a classifier that reads the package+ layout would narrow it, and it belongs in ``code_origin`` when it comes.+ """+ return [+ c+ for c in contracts+ if c.role != "consumer"+ or _contract_key(c.repo, c.file_path, c.contract_id) in matched_consumers+ or not outside_runtime(c.file_path)+ ]++def _unmatched_consumers(consumers: list[Contract],matched_consumers: set[tuple[str, str, str]],diff --git a/packages/core/src/repowise/core/workspace/matching/third_party.py b/packages/core/src/repowise/core/workspace/matching/third_party.pynew file mode 100644index 000000000..67e61d4f4--- /dev/null+++ b/packages/core/src/repowise/core/workspace/matching/third_party.py@@ -0,0 +1,75 @@+"""Well-known third-party services a call reaches through a configured base URL.++A literal public host (``api.stripe.com``) already reads as third-party during+target resolution. A call written against a base variable has no host to read,+so ``${SUPABASE_URL}/rest/v1/todos`` would count as a call no workspace route+serves. A service family whose base variable and API paths are both distinctive+is declared here as one row, and such a call is marked third-party instead.++Both must hold: the base token names the service and the path starts with one of+the service's API prefixes. A target the service-name map or ``service_bases``+already placed in a workspace repo is left alone, so a self-hosted copy that is+a workspace member keeps its links. Adding a service is one row.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from collections.abc import Iterable++ from repowise.core.workspace.contracts import Contract+++@dataclass(frozen=True)+class ThirdPartyService:+ """One service family, as data."""++ name: str+ #: Words one of which the base token holds, compared lower-cased with+ #: separators dropped, so ``SUPABASE_URL``, ``supabaseUrl`` and+ #: ``settings.supabase_url`` all read ``supabase``.+ base_words: tuple[str, ...]+ #: Path prefixes the service's API serves. A call must start with one.+ paths: tuple[str, ...]+++#: One row per service family, sorted by name.+THIRD_PARTY_SERVICES: tuple[ThirdPartyService, ...] = (+ ThirdPartyService(+ "supabase",+ ("supabase",),+ ("/auth/v1/", "/rest/v1/", "/storage/v1/", "/functions/v1/", "/realtime/v1/"),+ ),+)++_SEPARATORS_RE = re.compile(r"[^a-z0-9]")+++def third_party_service(base_token: str, path: str) -> str | None:+ """The service a call on *base_token* to *path* reaches, or None."""+ token = _SEPARATORS_RE.sub("", base_token.lower())+ for row in THIRD_PARTY_SERVICES:+ if any(w in token for w in row.base_words) and path.startswith(row.paths):+ return row.name+ return None+++def mark_third_party_calls(contracts: Iterable[Contract]) -> None:+ """Mark each unplaced HTTP consumer a :data:`THIRD_PARTY_SERVICES` row names.++ Runs after :func:`.http.annotate_consumer_targets`, which clears and+ recomputes ``meta['external']`` every run, so this mark is recomputed too.+ """+ for c in contracts:+ if c.role != "consumer" or c.contract_type != "http":+ continue+ meta = c.meta+ token = meta.get("base_token")+ if not token or meta.get("external") or meta.get("target_repo"):+ continue+ if third_party_service(str(token), str(meta.get("path", ""))) is not None:+ meta["external"] = Truediff --git a/packages/core/src/repowise/core/workspace/network_probe.py b/packages/core/src/repowise/core/workspace/network_probe.pyindex a819c28d1..8bdb914d9 100644--- a/packages/core/src/repowise/core/workspace/network_probe.py+++ b/packages/core/src/repowise/core/workspace/network_probe.py@@ -12,6 +12,8 @@ says that something was missed and where. Ceilings, stated so they read asintent: only extensions some extractor walks are probed; a token in a stringliteral still counts (comments are masked); a file whose calls were located butnot resolved can be counted here and in ``http_consumer_unresolved`` both.+Tooling and build files (:func:`outside_runtime`) are skipped: a script calling+a dev server is not a call the running system misses.Adding a client library or a language is one entry in :data:`PROBE_ROWS`."""@@ -24,12 +26,25 @@ from dataclasses import dataclassfrom functools import cachefrom repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect+from repowise.core.code_origin import CodeOrigin, path_originfrom repowise.core.workspace.extractors import langsfrom repowise.core.workspace.extractors.base import SourceFile#: The ``extraction_stats`` key the probe writes, per repo.UNRECOGNISED_CALL_FILES_STAT = "call_files_unrecognised"+#: Origins whose code runs at development or build time, never in the deployed+#: system: a script calling a dev server is no missed service call.+OUTSIDE_RUNTIME_ORIGINS: frozenset[CodeOrigin] = frozenset({"tooling", "build"})+++def outside_runtime(rel_path: str) -> bool:+ """Whether :func:`..code_origin.path_origin` puts *rel_path* outside the running system.++ Read by the probe and by the diagnostics, so both leave out the same files.+ """+ return path_origin(rel_path) in OUTSIDE_RUNTIME_ORIGINS+@dataclass(frozen=True)class ProbeRow:@@ -159,6 +174,8 @@ def count_unrecognised_call_files() -> int:"""Files in *files* with a network-call token and no consumer contract.+ Tooling and build files (:func:`outside_runtime`) are not counted.+*consumer_files* are the paths a consumer contract came from. One regexsearch per remaining file of a probed language; only a hit pays for thecomment mask that confirms it.@@ -167,7 +184,7 @@ def count_unrecognised_call_files(count = 0for rel_path, suffix, content in files:entry = table.get(suffix)- if entry is None or rel_path in consumer_files:+ if entry is None or rel_path in consumer_files or outside_runtime(rel_path):continuepattern, hash_comments = entryif not pattern.search(content):diff --git a/tests/unit/test_code_origin.py b/tests/unit/test_code_origin.pyindex 51588dcda..62e2702a8 100644--- a/tests/unit/test_code_origin.py+++ b/tests/unit/test_code_origin.py@@ -78,6 +78,10 @@ _OWN_HEADER = (("tutorial_01/app.py", "docs_example"),("scripts/release.py", "tooling"),(".github/scripts/label.js", "tooling"),+ # Browser scripts a served static tree ships are product code.+ ("src/main/resources/static/scripts/pages/OwnerDetailsPage.js", "production"),+ ("public/scripts/app.js", "production"),+ ("scripts/public/seed.py", "tooling"),("tools/gen.go", "tooling"),# Dart's ``tool/`` (flutter samples' CI scripts), but not a shipped one.("tool/ci_script.dart", "tooling"),diff --git a/tests/unit/workspace/test_diagnostics.py b/tests/unit/workspace/test_diagnostics.pyindex e9c0f33bd..115badd2d 100644--- a/tests/unit/workspace/test_diagnostics.py+++ b/tests/unit/workspace/test_diagnostics.py@@ -335,3 +335,26 @@ def test_coverage_is_not_stated_before_the_probe_ran():diag = build_diagnostics([_consumer("web", "http::GET::/u")], [], {"web": {}})assert diag.unrecognised_call_files is Noneassert diag.http_consumer_coverage is None+++def test_an_unlinked_call_from_a_script_is_left_out_of_every_count():+ contracts = [+ _consumer("web", "http::GET::/docs", file="scripts/docs-parity.mjs"),+ _consumer("web", "http::GET::/missing", file="src/app.ts"),+ ]+ diag = build_diagnostics(contracts, [])+ assert [u.file_path for u in diag.unmatched_consumers] == ["src/app.ts"]+ assert diag.total_consumers == 1+ assert diag.http_consumers_read == 1+++def test_a_linked_call_from_a_script_still_counts():+ contracts = [+ _provider("api", "http::GET::/users"),+ _consumer("web", "http::GET::/users", file="scripts/seed.py"),+ ]+ link = _link("http::GET::/users", "api", "web")+ link.consumer_file = "scripts/seed.py"+ diag = build_diagnostics(contracts, [link])+ assert diag.http_consumers_linked == 1+ assert diag.http_consumers_read == 1diff --git a/tests/unit/workspace/test_framework_dialects.py b/tests/unit/workspace/test_framework_dialects.pyindex 9239427e8..3b5714443 100644--- a/tests/unit/workspace/test_framework_dialects.py+++ b/tests/unit/workspace/test_framework_dialects.py@@ -317,6 +317,23 @@ class TestNextAppRecognition:verbs = [v for v, _off in next_route_verbs(NEXT_ROUTE_TS)]assert verbs == ["GET", "POST"]+ def test_a_brace_list_exports_the_verbs_it_binds(self) -> None:+ # A library hands back the handlers: fumadocs search, Auth.js, NextAuth.+ def verbs(src: str) -> list[str]:+ return [v for v, _off in next_route_verbs(src)]++ assert verbs("export const { GET } = createFromSource(source);\n") == ["GET"]+ assert verbs("export const { GET, POST } = handlers;\n") == ["GET", "POST"]+ assert verbs("export { handler as GET, handler as POST };\n") == ["GET", "POST"]+ assert verbs('export { GET, POST } from "@/auth";\n') == ["GET", "POST"]++ def test_a_brace_list_that_renames_the_verb_away_exports_none(self) -> None:+ assert next_route_verbs("export { GET as handler };\n") == []+ assert next_route_verbs("export const { GET: get } = h;\n") == []+ assert next_route_verbs("export type { GET };\n") == []+ assert [v for v, _ in next_route_verbs('export { type GET, POST } from "./h";\n')] == ["POST"]+ assert next_route_verbs("// export const { GET } = h;\n") == []+class TestNextAppContracts:def test_one_file_yields_one_contract_per_exported_verb(self, tmp_path: Path) -> None:diff --git a/tests/unit/workspace/test_network_probe.py b/tests/unit/workspace/test_network_probe.pyindex 946dc5962..1326ebc8c 100644--- a/tests/unit/workspace/test_network_probe.py+++ b/tests/unit/workspace/test_network_probe.py@@ -78,3 +78,13 @@ def test_a_fetch_method_declaration_is_not_a_call_but_real_calls_are():def test_files_with_no_network_token_or_language_are_ignored():files = {"util.js": "export const add = (a, b) => a + b;\n", "schema.sql": "SELECT 1;\n"}assert _count(files) == 0+++def test_tooling_and_build_files_are_not_counted():+ # A script polling a dev server, or a build config, is no missed service call.+ files = {+ "scripts/warm_cache.py": "import httpx\nhttpx.get(url)\n",+ ".github/scripts/notify.js": "fetch(url);\n",+ "src/client.js": "fetch(url);\n",+ }+ assert _count(files) == 1diff --git a/tests/unit/workspace/test_third_party_services.py b/tests/unit/workspace/test_third_party_services.pynew file mode 100644index 000000000..f3a83b178--- /dev/null+++ b/tests/unit/workspace/test_third_party_services.py@@ -0,0 +1,69 @@+"""Calls through a configured base URL to a well-known third-party service."""++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+from repowise.core.workspace.matching.third_party import (+ THIRD_PARTY_SERVICES,+ mark_third_party_calls,+ third_party_service,+)+++def _call(path: str, base_token: str | None, repo: str = "web") -> Contract:+ meta = {"method": "GET", "path": path}+ if base_token:+ meta["base_token"] = base_token+ return Contract(+ repo=repo,+ contract_id=f"http::GET::{path}",+ contract_type="http",+ role="consumer",+ file_path="src/lib/blog.ts",+ symbol_name="fetch",+ confidence=0.85,+ meta=meta,+ )+++def test_every_row_declares_what_the_rule_needs():+ names = [row.name for row in THIRD_PARTY_SERVICES]+ assert names == sorted(names)+ assert len(set(names)) == len(names)+ for row in THIRD_PARTY_SERVICES:+ assert row.base_words and all(w == w.lower() and w.isalnum() for w in row.base_words)+ assert row.paths and all(p.startswith("/") for p in row.paths)+++def test_a_supabase_base_and_api_path_name_supabase():+ assert third_party_service("SUPABASE_URL", "/rest/v1/content_topics") == "supabase"+ assert third_party_service("supabase_url", "/auth/v1/.well-known/jwks.json") == "supabase"+ assert third_party_service("supabaseUrl", "/storage/v1/object/x") == "supabase"+++def test_both_the_base_and_the_path_must_agree():+ assert third_party_service("API_BASE", "/rest/v1/content_topics") is None+ assert third_party_service("SUPABASE_URL", "/api/posts") is None+++def test_a_marked_call_reads_as_third_party_in_the_diagnostics():+ calls = [_call("/rest/v1/content_topics", "SUPABASE_URL"), _call("/rest/v1/x", None)]+ annotate_consumer_targets(calls)+ mark_third_party_calls(calls)+ reasons = {u.contract_id: u.reason for u in build_diagnostics(calls, []).unmatched_consumers}+ assert reasons == {+ "http::GET::/rest/v1/content_topics": UnmatchedReason.EXTERNAL_HOST,+ "http::GET::/rest/v1/x": UnmatchedReason.NO_PROVIDER,+ }+++def test_a_base_the_workspace_places_is_left_alone():+ # A self-hosted copy that is a workspace member keeps its links.+ call = _call("/rest/v1/content_topics", "SUPABASE_URL")+ other = _call("/x", None, repo="supabase")+ annotate_consumer_targets([call, other], {"SUPABASE_URL": "supabase"})+ mark_third_party_calls([call, other])+ assert not call.meta.get("external")+ assert call.meta["target_repo"] == "supabase"