Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(mcp): name how each cross-repo link was matched and how far the estate graph can be trusted (#4588)

Raghav Chamadiyaf27539d16561
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index d29aee5ef..a3ec018ee 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -147,7 +147,10 @@ links are appended after it.
5. **Service links**: `service_pass` gives each HTTP consumer whose target is a
workspace repo, but whose path no provider serves, one `host_only` link with no
provider file. These live in `ContractStore.service_links`, apart from
- `contract_links`. A target that only equals a repo alias draws none.
+ `contract_links`. A target that only equals a repo alias draws none. A gateway's
+ edge to each service it routes to is a `gateway_route` service link, while a
+ consumer call routed through that gateway to a served route is a `gateway_route`
+ link in `contract_links`.
6. **Manual links** from `contracts.manual_links` are appended with strategy
`manual`.
@@ -208,6 +211,7 @@ does with it:
| Conformance, `workspace check` | `cycles_determined: false`; "dependency cycles not determined", exit 0 | "no dependency cycles among the edges detected (partial evidence)" |
| Blast radius | `evidence` attached | `evidence` attached |
| MCP `get_architecture`, `get_blast_radius`, `get_conformance`, REST | Carry the same `evidence` block | Same |
+| MCP `get_risk`, `get_change_risk` cross-repo parts | `graph_evidence` with state and reason | Same |
In every state, blast radius lists in `undetermined_targets` each target the walked
adjacency has no edge at, so an empty impact set there reads as not seen.
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 85f9b2ca5..cb4e19cdb 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -371,7 +371,7 @@ Per file:
| `changes` | `recent_changes`, `recent_changes_total`, as in [get_context](#changes) |
| `tests` | Typed `test_recommendations` |
| `blast` | `pr_blast_radius`: transitive files, co-change warnings, test gaps, structural score; reviewers stay in the directive |
-| `graph` | `dependents` (direct vs transitive), `consumers` (typed contract consumers), `cross_repo_links`, `impact_surface`, `direct_risks`, `relationship_analysis` (empty vs unavailable or partial) |
+| `graph` | `dependents` (direct vs transitive), `consumers` (typed contract consumers), `cross_repo_links` (contract rows carry `strategy` and `origin`, see [cross-repo link rows](#cross-repo-link-rows)), `impact_surface`, `direct_risks`, `relationship_analysis` (empty vs unavailable or partial) |
| `churn` | `change_magnitude`, `risk_type`, `change_pattern` |
| `scales` | Unit, range and calibration per scalar; identical every call |
@@ -406,7 +406,7 @@ Notes:
- **Measured `test_recommendations`** match a changed file, not its lines (`evidence[].match: "file"`); a test file gone or changed since measurement carries `stale: true` and `stale_reason`.
- **`reach`:** bands an uncalibrated 0 to 10 heuristic that never sees the diff; not a probability. The raw `pr_blast_radius.structural_impact_score` needs `include=["blast", "scales"]`.
-In workspace mode the directive adds `will_break_consumers` (structural reach only), `missing_cross_repo_cochanges`, `breaking_changes` (provider incompatibilities since the last index with impacted consumers; a link does not prove field use), `conformance_violations` and `dependency_cycles`; dropped when no workspace is loaded.
+In workspace mode the directive adds `will_break_consumers` (structural reach only), `missing_cross_repo_cochanges`, `breaking_changes` (provider incompatibilities since the last index with impacted consumers; a link does not prove field use), `conformance_violations` and `dependency_cycles`; dropped when no workspace is loaded. `cross_repo_relationship_analysis` carries `graph_evidence` and this repo's `http_calls`.
---
@@ -510,8 +510,9 @@ Groups changed files over index edges, co-change pairs and (for a range) shared
### cross_repo
-- `consumers[]`: `provider_file`, consumer `repo`, `file`, `contract_id`, `contract_type`, `match_type`, and `tests` (`state` `measured`, `inferred`, `none` or `unresolved`; up to 5 `tests_to_run`).
+- `consumers[]`: `provider_file`, consumer `repo`, `file`, `contract_id`, `contract_type`, `match_type`, `strategy`, `origin`, and `tests` (`state` `measured`, `inferred`, `none` or `unresolved`; up to 5 `tests_to_run`).
- `breaking_changes[]`: `contract_id`, `kind`, `severity`, `detail`, `impacted_repos`. `breaking_changes_available` says whether detection ran, so empty is not an all-clear.
+- `graph_evidence` and `http_calls` for the changed repo, as in [workspace tools](#workspace-tools).
- Absent outside workspace mode or when no published file changed.
---
@@ -722,11 +723,17 @@ Any of `alias`, `path`, `absolute_path` passes unchanged as `repo`. Single-repo
### `get_blast_radius`
-Impacted services with `score` (0 to 1 relative path weight, uncalibrated), `distance` (hops), `structural` (real dependency vs co-change only) and edge kinds; `impact_score_semantics`, `impacted_repos`, `structural_count`, `behavioral_count`, `total_impacted`, unresolved targets. `symbol_targets[].consumers[]` names consuming symbols per contract link, each with a `get_change_risk`-shaped `tests` block.
+Impacted services with `score` (0 to 1 relative path weight, uncalibrated), `distance` (hops), `structural` (real dependency vs co-change only) and edge kinds; `impact_score_semantics`, `impacted_repos`, `structural_count`, `behavioral_count`, `total_impacted`, unresolved targets. `symbol_targets[].consumers[]` names consuming symbols per contract link, with `strategy` and `origin`, each with a `get_change_risk`-shaped `tests` block. `evidence` is the graph's evidence state.
### `get_architecture`
-`score` (1 to 10; higher is lower coupling, smaller core), `architecture_type` (`core-periphery`, `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size`, `core_ratio`, `core_members`, `cycle_count`, `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral), `summary`.
+`score` (1 to 10; higher is lower coupling, smaller core), `architecture_type` (`core-periphery`, `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size`, `core_ratio`, `core_members`, `cycle_count`, `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral), `evidence`, `http_calls`, `summary`.
+
+### Cross-repo link rows
+
+A contract link row carries `strategy`, the rule that matched it (`exact_id`, `unique_path`, `gateway_route`, `host_only` and the rest of `LinkStrategy`), and `origin`, how the contract at the row's far end was read (`route_registration`, `client_call`, `sql_string` and the rest of `ContractOrigin`). Both are omitted on an artifact written before they were stored. `match_type` derives from `strategy`, so a `unique_path` or `gateway_route` link still reads `exact` there. Values are in [WORKSPACE_CONTRACTS.md](WORKSPACE_CONTRACTS.md).
+
+`graph_evidence` is `{state, reason}`, present only when the state is `partial` or `insufficient`; `reason` lists the evidence reason codes (`isolated_services`, `repos_without_contracts` and the rest of `graph_evidence`). `http_calls` counts HTTP calls `read`, `not_linked` and `in_service`, workspace wide on `get_architecture` (which adds `linked`) and for the changed repo on `get_risk` and `get_change_risk`; calls served inside their own service are counted apart, never as not linked. The counts are separate figures, not a partition of `read`.
### `get_conformance`
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
index 68e8b6a41..313c1a82c 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
@@ -236,8 +236,7 @@ def _print_call_coverage(diag: ExtractionDiagnostics) -> None:
def _unlinked_http_split(diag: ExtractionDiagnostics) -> str:
"""Where the read but unlinked HTTP calls went, workspace wide."""
- counts = Counter(u.reason for u in diag.unmatched_consumers if u.contract_type == "http")
- in_service = sum(1 for u in diag.in_service_consumers if u.contract_type == "http")
+ counts, in_service = diag.http_unlinked()
parts = [
f"{n} {_HTTP_REASON_SHORT.get(reason, reason)}"
for reason, n in sorted(counts.items(), key=lambda kv: _reason_rank(kv[0]))
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index 2ce308b7d..54bd60c24 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -389,6 +389,23 @@ class ExtractionDiagnostics:
seen = self.http_consumers_read + self.http_consumers_unresolved + missed
return seen or None
+ def http_unlinked(self, repo: str | None = None) -> tuple[dict[str, int], int]:
+ """Read HTTP calls that linked to no other service: per reason, and in-service.
+
+ A call served inside its own repo and service is counted apart, never as
+ unmatched. *repo* narrows both counts to one member.
+ """
+ by_reason: dict[str, int] = defaultdict(int)
+ for u in self.unmatched_consumers:
+ if u.contract_type == "http" and repo in (None, u.repo):
+ by_reason[u.reason] += 1
+ in_service = sum(
+ 1
+ for u in self.in_service_consumers
+ if u.contract_type == "http" and repo in (None, u.repo)
+ )
+ return dict(by_reason), in_service
+
@property
def http_link_coverage(self) -> float | None:
"""Share of the calls seen that linked to another service's provider.
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
index fa395e7ae..61f6dc517 100644
--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -119,10 +119,16 @@ class CrossRepoEnricher:
# cross the contract link without scanning every contract.
self._contract_symbol_index: dict[str, list[dict]] = defaultdict(list)
self._link_provider_symbol_index: dict[str, list[dict]] = defaultdict(list)
+ # (repo, file, contract_id, role) -> origin, so a link row can name how
+ # each of its ends was read.
+ self._contract_origin_index: dict[tuple[Any, Any, Any, Any], str] = {}
# Service-granular system graph from the workspace update. Read-only;
# views over it live in core/types.
self._system_graph: dict | None = None
+ # Read once per loaded graph: its evidence brief and parsed diagnostics.
+ self._evidence_brief: Any = _ABSENT
+ self._parsed_diagnostics: Any = _ABSENT
# Provider changes from the latest update that break consumers, with the
# impacted consumer files. Read-only.
@@ -355,6 +361,15 @@ class CrossRepoEnricher:
symbol_id = contract.get("symbol_id")
if symbol_id:
self._contract_symbol_index[symbol_id].append(contract)
+ origin = contract.get("origin")
+ if origin:
+ key = (
+ contract.get("repo"),
+ contract.get("file_path"),
+ contract.get("contract_id"),
+ contract.get("role"),
+ )
+ self._contract_origin_index[key] = origin
_log.debug(
"Contract enricher loaded: %d contracts, %d links",
@@ -370,6 +385,7 @@ class CrossRepoEnricher:
def _ingest_system_graph(self, graph: dict) -> None:
self._system_graph = graph
+ self._evidence_brief = self._parsed_diagnostics = _ABSENT
_log.debug(
"System graph loaded: %d nodes, %d edges",
len(graph.get("nodes", [])),
@@ -543,6 +559,7 @@ class CrossRepoEnricher:
)
payload = metrics.to_dict()
payload["repo_provenance"] = self._system_graph.get("repo_provenance", {})
+ payload["http_calls"] = self.http_call_split()
return payload
def get_diagnostics(self) -> dict | None:
@@ -551,6 +568,92 @@ class CrossRepoEnricher:
return None
return self._system_graph.get("diagnostics")
+ def graph_evidence_brief(self) -> dict | None:
+ """The graph's evidence ``state`` and ``reason`` codes when short of measured.
+
+ Core's :func:`graph_evidence`, the one every view reads; ``None`` when
+ measured or without a graph, so a default response stays flat.
+ """
+ if self._evidence_brief is _ABSENT:
+ self._evidence_brief = None
+ if self._system_graph is not None:
+ from repowise.core.workspace.graph_evidence import (
+ EVIDENCE_MEASURED,
+ graph_evidence,
+ )
+ from repowise.core.workspace.system_graph import SystemGraph
+
+ try:
+ evidence = graph_evidence(SystemGraph.from_dict(self._system_graph))
+ # Measured needs no caveat; otherwise the reason codes, not prose.
+ if evidence.state != EVIDENCE_MEASURED:
+ self._evidence_brief = {
+ "state": evidence.state,
+ "reason": ", ".join(r.code for r in evidence.reasons),
+ }
+ except Exception:
+ # An additive field: a bad graph never hides the block it rides on.
+ _log.debug("Graph evidence unavailable", exc_info=True)
+ return self._evidence_brief
+
+ def _diagnostics_model(self) -> Any:
+ """The graph's diagnostics as :class:`ExtractionDiagnostics`, parsed once; else ``None``."""
+ if self._parsed_diagnostics is _ABSENT:
+ self._parsed_diagnostics = None
+ if raw := self.get_diagnostics():
+ from repowise.core.workspace.diagnostics import ExtractionDiagnostics
+
+ try:
+ self._parsed_diagnostics = ExtractionDiagnostics.from_dict(raw)
+ except Exception:
+ # An additive field: unreadable diagnostics drop only the counts.
+ _log.debug("Extraction diagnostics unreadable", exc_info=True)
+ return self._parsed_diagnostics
+
+ def http_call_split(self, repo: str | None = None) -> dict | None:
+ """HTTP calls read, and of those not linked how many are served in-service.
+
+ ``not_linked`` excludes in-service calls, which ``in_service`` counts, as
+ the CLI diagnostics headline does. ``linked`` is workspace wide, so only
+ an unscoped call carries it. ``None`` without diagnostics, or for a
+ *repo* with no HTTP call.
+ """
+ diag = self._diagnostics_model()
+ if diag is None:
+ return None
+ by_reason, in_service = diag.http_unlinked(repo)
+ read = sum(
+ r.consumers_by_type.get("http", 0)
+ for r in diag.repo_breakdown
+ if repo in (None, r.repo)
+ )
+ split: dict[str, Any] = {"read": read}
+ if repo is None and diag.http_consumers_linked is not None:
+ split["linked"] = diag.http_consumers_linked
+ split["not_linked"] = sum(by_reason.values())
+ split["in_service"] = in_service
+ # A repo that read no HTTP call has nothing to split.
+ return split if repo is None or any(split.values()) else None
+
+ def link_provenance(self, link: dict, side: str) -> dict[str, str]:
+ """``strategy`` of *link* and ``origin`` of its *side* end, each only when stored.
+
+ Values pass through from :mod:`repowise.core.workspace.origins`; a store
+ written before either existed yields neither key.
+ """
+ contract_id = (
+ link.get("consumer_contract_id") or link.get("contract_id")
+ if side == "consumer"
+ else link.get("contract_id")
+ )
+ origin = self._contract_origin_index.get(
+ (link.get(f"{side}_repo"), link.get(f"{side}_file"), contract_id, side)
+ )
+ return {
+ **({"strategy": strategy} if (strategy := link.get("strategy")) else {}),
+ **({"origin": origin} if origin else {}),
+ }
+
def get_cross_repo_partners(self, repo_alias: str, file_path: str) -> list[dict]:
"""Return cross-repo co-change partners for a file.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
index b64e6be96..0fd37d9ba 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -90,6 +90,8 @@ def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
"conformance_violations": metrics.get("conformance_violations", 0),
"role_breakdown": breakdown,
"evidence": evidence or None,
+ # Calls read but linked to no other service, in-service ones apart.
+ **({"http_calls": calls} if (calls := metrics.get("http_calls")) else {}),
"summary": _summary(metrics, evidence),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
index 85c549eef..2999496c7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
@@ -278,6 +278,7 @@ async def _resolve_symbol_targets(
"contract_type": link.get("contract_type"),
"match_type": link.get("match_type"),
"confidence": link.get("confidence"),
+ **enricher.link_provenance(link, "consumer"),
# An import sits at file scope, so code contracts carry none.
**({"symbol_id": sid} if (sid := link.get("consumer_symbol_id")) else {}),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py
index 4aad57320..49b5218a2 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py
@@ -51,6 +51,7 @@ def _cross_repo_consumers(enricher: Any, alias: str, changed_files: list[str]) -
"contract_id": link.get("contract_id"),
"contract_type": link.get("contract_type"),
"match_type": link.get("match_type"),
+ **enricher.link_provenance(link, "consumer"),
**_present("provider_symbol_id", link.get("provider_symbol_id")),
**_present("symbol_id", link.get("consumer_symbol_id")),
}
@@ -218,6 +219,9 @@ def _cross_repo_block(
"breaking_changes_available": has_breaking_report,
# Dates the breaking half only; contract links carry no stamp.
"breaking_changes_as_of": report.get("generated_at") or None,
+ # How far to trust the estate's edge set, and this repo's unlinked calls.
+ **_present("graph_evidence", enricher.graph_evidence_brief()),
+ **_present("http_calls", enricher.http_call_split(alias)),
"summary": summary,
}
except Exception:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
index eaaebbd44..858b4a696 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
@@ -326,6 +326,15 @@ def _cross_repo_relationships(
"reason": "live_repository_heads_not_compared",
},
**({"reason": "per_edge_match_provenance_not_retained"} if structural else {}),
+ # How far to trust the edge set, and this repo's unlinked calls.
+ **(
+ {"graph_evidence": evidence}
+ if (evidence := enricher.graph_evidence_brief())
+ else {}
+ ),
+ **(
+ {"http_calls": split} if (split := enricher.http_call_split(repo_alias)) else {}
+ ),
},
}
except Exception:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
index ced2e75a8..ce4072a03 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
@@ -18,7 +18,10 @@ from repowise.server.mcp_server._helpers import (
_RELATIONSHIP_LIMIT = 5
-def _contract_consumer(link: dict, provider_repo: str, provider_file: str) -> dict:
+def _contract_consumer(
+ link: dict, provider_repo: str, provider_file: str, provenance: dict | None = None
+) -> dict:
+ """A consumer row; *provenance* is the link's strategy and the consumer's origin."""
row = {
"source_repository": provider_repo,
"source_file": provider_file,
@@ -37,10 +40,14 @@ def _contract_consumer(link: dict, provider_repo: str, provider_file: str) -> di
for key in ("match_type", "confidence"):
if link.get(key) is not None:
row[key] = link[key]
+ row.update(provenance or {})
return row
-def _contract_provider(link: dict, consumer_repo: str, consumer_file: str) -> dict:
+def _contract_provider(
+ link: dict, consumer_repo: str, consumer_file: str, provenance: dict | None = None
+) -> dict:
+ """A provider row; *provenance* is the link's strategy and the provider's origin."""
row = {
"source_repository": link["provider_repo"],
"source_file": link["provider_file"],
@@ -59,6 +66,7 @@ def _contract_provider(link: dict, consumer_repo: str, consumer_file: str) -> di
for key in ("match_type", "confidence"):
if link.get(key) is not None:
row[key] = link[key]
+ row.update(provenance or {})
return row
@@ -159,16 +167,21 @@ def _cross_repo_links(
provider_links: list[dict],
consumer_links: list[dict],
package_consumers: list[dict],
+ enricher: Any = None,
) -> list[dict]:
"""Every cross-repo row for *target*, contract evidence first."""
+
+ def provenance(link: dict, side: str) -> dict | None:
+ return enricher.link_provenance(link, side) if enricher is not None else None
+
links = [
*(
- _contract_consumer(link, alias, target)
+ _contract_consumer(link, alias, target, provenance(link, "consumer"))
for link in provider_links
if link.get("consumer_repo") != alias
),
*(
- _contract_provider(link, alias, target)
+ _contract_provider(link, alias, target, provenance(link, "provider"))
for link in consumer_links
if link.get("provider_repo") != alias
),
@@ -291,7 +304,10 @@ def _enrich_target(
package_consumers = enricher.get_package_consumers(alias)
graph_collector = collector if include_graph else None
- consumers = [_contract_consumer(link, alias, target) for link in provider_links]
+ consumers = [
+ _contract_consumer(link, alias, target, enricher.link_provenance(link, "consumer"))
+ for link in provider_links
+ ]
_set_capped(r, "consumers", consumers, graph_collector, target)
r["relationship_analysis"]["consumers"] = {
**contract_state,
@@ -299,7 +315,7 @@ def _enrich_target(
"evidence_kind": "contract",
}
links = _cross_repo_links(
- alias, target, cross_partners, provider_links, consumer_links, package_consumers
+ alias, target, cross_partners, provider_links, consumer_links, package_consumers, enricher
)
_set_capped(r, "cross_repo_links", links, graph_collector, target)
r["relationship_analysis"]["cross_repo"] = _combined_analysis(
diff --git a/tests/unit/server/test_mcp_cross_repo_link_provenance.py b/tests/unit/server/test_mcp_cross_repo_link_provenance.py
new file mode 100644
index 000000000..8c806fe24
--- /dev/null
+++ b/tests/unit/server/test_mcp_cross_repo_link_provenance.py
@@ -0,0 +1,250 @@
+"""How a cross-repo link was matched, and how far to trust the estate, in the MCP tools."""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.contracts import Contract, ContractLink
+from repowise.core.workspace.cross_repo import CrossRepoOverlay
+from repowise.core.workspace.diagnostics import (
+ ExtractionDiagnostics,
+ RepoDiagnostics,
+ UnmatchedConsumer,
+)
+from repowise.core.workspace.system_graph import build_system_graph
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+from repowise.server.mcp_server.tool_architecture import architecture_payload
+from repowise.server.mcp_server.tool_blast_radius import get_blast_radius
+from repowise.server.mcp_server.tool_change_risk import _cross_repo_block
+from repowise.server.mcp_server.tool_risk.directives import _cross_repo_relationships
+from repowise.server.mcp_server.tool_risk.enrichment import _cross_repo_links
+
+PROVIDER_FILE = "src/routes.py"
+CONSUMER_FILE = "src/api.ts"
+PROVIDER_ID = "http::GET::/api/orders"
+CONSUMER_ID = "http::GET::/orders"
+
+
+def _contracts(*, origins: bool = True) -> list[Contract]:
+ return [
+ Contract(
+ repo="api",
+ contract_id=PROVIDER_ID,
+ contract_type="http",
+ role="provider",
+ file_path=PROVIDER_FILE,
+ symbol_name="list_orders",
+ confidence=0.9,
+ symbol_id=f"{PROVIDER_FILE}::list_orders",
+ origin="route_registration" if origins else None,
+ ),
+ Contract(
+ repo="web",
+ contract_id=CONSUMER_ID,
+ contract_type="http",
+ role="consumer",
+ file_path=CONSUMER_FILE,
+ symbol_name="fetchOrders",
+ confidence=0.75,
+ origin="client_call" if origins else None,
+ ),
+ ]
+
+
+def _link(*, strategy: str | None = "prefix_stripped") -> ContractLink:
+ return ContractLink(
+ contract_id=PROVIDER_ID,
+ contract_type="http",
+ match_type="candidate",
+ confidence=0.6,
+ provider_repo="api",
+ provider_file=PROVIDER_FILE,
+ provider_symbol="list_orders",
+ provider_service=None,
+ consumer_repo="web",
+ consumer_file=CONSUMER_FILE,
+ consumer_symbol="fetchOrders",
+ consumer_service=None,
+ provider_symbol_id=f"{PROVIDER_FILE}::list_orders",
+ consumer_contract_id=CONSUMER_ID,
+ strategy=strategy,
+ )
+
+
+def _diagnostics(*, legacy: bool = False) -> dict:
+ """Two HTTP calls in web: one matching nothing, one served in its own service."""
+ dangling = UnmatchedConsumer("web", "src/a.ts", "http::GET::/x", "http", "no_provider")
+ in_service = UnmatchedConsumer("web", "src/b.ts", "http::GET::/y", "http", "internal_only")
+ diag = ExtractionDiagnostics(
+ repo_breakdown=[
+ RepoDiagnostics(repo="api", providers_by_type={"http": 1}),
+ RepoDiagnostics(repo="web", consumers_by_type={"http": 3}),
+ ],
+ unmatched_consumers=[dangling],
+ in_service_consumers=[in_service],
+ http_consumers_linked=1,
+ ).to_dict()
+ if legacy:
+ # Written before in-service calls were split out: listed as unmatched.
+ diag["unmatched_consumers"].append(diag.pop("in_service_consumers")[0])
+ return diag
+
+
+def _enricher(
+ tmp_path: Path,
+ *,
+ origins: bool = True,
+ strategy: str | None = "prefix_stripped",
+ legacy_diagnostics: bool = False,
+ unread_repo: bool = True,
+) -> CrossRepoEnricher:
+ contracts = _contracts(origins=origins)
+ links = [_link(strategy=strategy)]
+ graph = build_system_graph(contracts, links, CrossRepoOverlay(), {}, generated_at="t")
+ raw_graph = {**graph.to_dict(), "diagnostics": _diagnostics(legacy=legacy_diagnostics)}
+ # A walked repo with no contracts leaves the evidence partial.
+ walked = ("api", "web", "mongo") if unread_repo else ("api", "web")
+ raw_graph["repo_provenance"] = {alias: {"head": "h"} for alias in walked}
+ (tmp_path / "system_graph.json").write_text(json.dumps(raw_graph), encoding="utf-8")
+ (tmp_path / "contracts.json").write_text(
+ json.dumps(
+ {
+ "contracts": [c.to_dict() for c in contracts],
+ "contract_links": [lk.to_dict() for lk in links],
+ }
+ ),
+ encoding="utf-8",
+ )
+ return CrossRepoEnricher(
+ tmp_path / "cross_repo_edges.json",
+ contracts_path=tmp_path / "contracts.json",
+ system_graph_path=tmp_path / "system_graph.json",
+ )
+
+
+def _in_workspace(enricher: CrossRepoEnricher):
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = enricher
+ try:
+ yield
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+
+
+def test_a_link_names_its_strategy_and_each_ends_origin(tmp_path: Path):
+ enricher = _enricher(tmp_path)
+ link = enricher.contract_links[0]
+ # The consumer end is found under its own contract id, not the provider's.
+ assert enricher.link_provenance(link, "consumer") == {
+ "strategy": "prefix_stripped",
+ "origin": "client_call",
+ }
+ assert enricher.link_provenance(link, "provider") == {
+ "strategy": "prefix_stripped",
+ "origin": "route_registration",
+ }
+
+
+def test_an_artifact_without_strategy_or_origin_omits_both(tmp_path: Path):
+ enricher = _enricher(tmp_path, origins=False, strategy=None)
+ assert enricher.link_provenance(enricher.contract_links[0], "consumer") == {}
+ with _in_workspace(enricher):
+ block = _cross_repo_block("api", [PROVIDER_FILE])
+ row = block["consumers"][0]
+ assert row["match_type"] == "candidate"
+ assert "strategy" not in row and "origin" not in row
+
+
+async def test_blast_radius_consumer_rows_carry_strategy_and_origin(tmp_path: Path):
+ with _in_workspace(_enricher(tmp_path)):
+ payload = await get_blast_radius(targets=[f"{PROVIDER_FILE}::list_orders"])
+ row = payload["symbol_targets"][0]["consumers"][0]
+ assert (row["strategy"], row["origin"]) == ("prefix_stripped", "client_call")
+ assert payload["evidence"]["state"]
+
+
+def test_change_risk_block_carries_strategy_evidence_and_the_repos_calls(tmp_path: Path):
+ with _in_workspace(_enricher(tmp_path)):
+ block = _cross_repo_block("api", [PROVIDER_FILE])
+ assert block["consumers"][0]["strategy"] == "prefix_stripped"
+ assert block["consumers"][0]["origin"] == "client_call"
+ assert block["graph_evidence"] == {"state": "partial", "reason": "repos_without_contracts"}
+ # api reads no HTTP call, so it has nothing to split.
+ assert "http_calls" not in block
+
+
+def test_get_risk_rows_and_analysis_carry_provenance_and_evidence(tmp_path: Path):
+ enricher = _enricher(tmp_path)
+ rows = _cross_repo_links(
+ "web",
+ CONSUMER_FILE,
+ [],
+ [],
+ enricher.get_contract_links_as_consumer("web", CONSUMER_FILE),
+ [],
+ enricher,
+ )
+ assert (rows[0]["strategy"], rows[0]["origin"]) == ("prefix_stripped", "route_registration")
+ with _in_workspace(enricher):
+ analysis = _cross_repo_relationships("web")["analysis"]
+ assert analysis["graph_evidence"] == {"state": "partial", "reason": "repos_without_contracts"}
+ assert analysis["http_calls"] == {"read": 3, "not_linked": 1, "in_service": 1}
+
+
[email protected]("legacy", [False, True])
+def test_in_service_calls_are_counted_apart_from_not_linked(tmp_path: Path, legacy: bool):
+ enricher = _enricher(tmp_path, legacy_diagnostics=legacy)
+ assert enricher.http_call_split() == {
+ "read": 3,
+ "linked": 1,
+ "not_linked": 1,
+ "in_service": 1,
+ }
+ payload = architecture_payload(enricher.get_architecture_metrics())
+ assert payload["http_calls"]["in_service"] == 1
+
+
+def test_evidence_and_calls_are_absent_without_a_graph():
+ enricher = CrossRepoEnricher.from_data(contracts={"contracts": [], "contract_links": []})
+ assert enricher.graph_evidence_brief() is None
+ assert enricher.http_call_split() is None
+
+
+def test_evidence_brief_is_core_state_with_its_reason_codes(tmp_path: Path):
+ from repowise.core.workspace.graph_evidence import graph_evidence
+ from repowise.core.workspace.system_graph import SystemGraph
+
+ enricher = _enricher(tmp_path)
+ core = graph_evidence(SystemGraph.from_dict(enricher.get_system_graph()))
+ assert enricher.graph_evidence_brief() == {
+ "state": core.state,
+ "reason": ", ".join(r.code for r in core.reasons),
+ }
+
+
+def test_a_measured_graph_adds_no_evidence_field(tmp_path: Path):
+ enricher = _enricher(tmp_path, unread_repo=False)
+ assert enricher.graph_evidence_brief() is None
+ with _in_workspace(enricher):
+ block = _cross_repo_block("api", [PROVIDER_FILE])
+ analysis = _cross_repo_relationships("web")["analysis"]
+ assert "graph_evidence" not in block
+ assert "graph_evidence" not in analysis
+
+
+def test_unreadable_diagnostics_drop_only_the_counts():
+ graph = {"nodes": [], "edges": [], "diagnostics": {"repo_breakdown": [{"repo": 1}], "x": None}}
+ graph["diagnostics"]["symbol_identity"] = {"provider": None} # from_dict cannot read it
+ enricher = CrossRepoEnricher.from_data(system_graph=graph)
+ assert enricher.http_call_split() is None
+ assert enricher.get_diagnostics() is graph["diagnostics"]