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): give the cross-repo contract layer a front door (#1880)
Raghav Chamadiya3064a2a43ff2
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 0531940f7..c2229c692 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -151,7 +151,12 @@ def _render_target_risk(projected: dict, requested: tuple[str, ...]) -> None:):_print_list(label, directive.get(key) or [])for label, key in _DIRECTIVE_RECORD_BLOCKS:- _print_records(label, directive.get(key) or [], key)+ _print_records(+ label,+ directive.get(key) or [],+ key,+ truncated=directive.get(f"{key}_truncated") or 0,+ )targets = projected.get("targets") or {}for name in requested:@@ -353,7 +358,7 @@ def _record_text(key: str, entry: dict) -> str:return str(entry)-def _print_records(label: str, values: list, key: str) -> None:+def _print_records(label: str, values: list, key: str, truncated: int = 0) -> None:"""A directive block whose entries are dicts, one line each."""from rich.markup import escape@@ -363,6 +368,8 @@ def _print_records(label: str, values: list, key: str) -> None:for entry in values:text = _record_text(key, entry) if isinstance(entry, dict) else str(entry)console.print(f" {escape(str(text))}")+ if truncated:+ console.print(f" [dim]... and {truncated} more[/dim]")def _ordinal(n: int) -> str:diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex 6645a99a9..74ef4548e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -3,6 +3,7 @@from __future__ import annotationsimport time+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -86,6 +87,7 @@ def _workspace_update(from .mode import _resolve_index_only_modestart = time.monotonic()+ started_at = datetime.now(UTC)ws_root = target.ws_rootws_config = target.ws_configrepo_alias = target.repo_filter@@ -192,6 +194,7 @@ def _workspace_update(repo_filter=repo_alias,docs_aliases=docs_aliases,start=start,+ started_at=started_at,agents_md=agents_md,verbose=verbose,docs_flag=docs_flag,@@ -249,6 +252,8 @@ def _workspace_update(from .reporting import show_workspace_completion+ _print_breaking_changes(ws_root, started_at)+show_workspace_completion(ws_name=ws_root.name,updated=updated,@@ -260,6 +265,52 @@ def _workspace_update()+def _print_breaking_changes(ws_root: Path, started_at: datetime) -> None:+ """One line naming the contracts this update broke, if any.++ The report is written by the cross-repo hooks during this run, so it is only+ ours when it was stamped after we started; an older one belongs to a+ previous update and saying nothing beats attributing it here.+ """+ from rich.markup import escape++ from repowise.core.workspace.breaking_change import (+ SEVERITY_BREAKING,+ load_breaking_change_report,+ )++ report = load_breaking_change_report(ws_root)+ if report is None or not report.ran or not report.changes:+ return+ try:+ if datetime.fromisoformat(report.generated_at or "") < started_at:+ return+ except (TypeError, ValueError):+ return+ # Counted the way `workspace check` gates, so the two never contradict.+ gating = [+ c+ for c in report.changes+ if c.severity == SEVERITY_BREAKING+ and any(ic.repo != c.provider_repo for ic in c.impacted_consumers)+ ]+ repos = sorted(+ {ic.repo for c in gating for ic in c.impacted_consumers if ic.repo != c.provider_repo}+ )+ others = len(report.changes) - len(gating)+ if not gating:+ console.print(+ f"\n[dim]{others} contract change(s) recorded; none breaks another repo.[/dim]"+ )+ return+ console.print(+ f"\n[yellow]![/yellow] {len(gating)} breaking contract change(s) impacting "+ f"{escape(', '.join(repos))}"+ + (f", plus {others} non-breaking" if others else "")+ + ". [dim]repowise workspace check[/dim]"+ )++def _workspace_docs_update(*,ws_root: Path,@@ -267,6 +318,7 @@ def _workspace_docs_update(repo_filter: str | None,docs_aliases: set[str],start: float,+ started_at: datetime,agents_md: bool | None,verbose: bool,docs_flag: bool | None,@@ -466,6 +518,7 @@ def _workspace_docs_update(f"[green]Workspace update complete[/green]: {summary} "f"[dim]({time.monotonic() - start:.1f}s)[/dim]")+ _print_breaking_changes(ws_root, started_at)def _refresh_workspace_editor_project_files(diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.pyindex 5b40b20a9..1f38d29fa 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py@@ -1170,19 +1170,36 @@ def workspace_diagnostics(@workspace_group.command("check")@click.argument("path", required=False, default=None)+ "--breaking/--no-breaking",+ default=True,+ help="Fail on breaking contract changes from the last workspace update.",+)@format_option(help="Output format. ``json`` emits the raw conformance report.")@json_option()-def workspace_check(path: str | None, fmt: str, as_json: bool) -> None:- """Architecture lint — fail on dependency-rule violations or cycles.+def workspace_check(path: str | None, breaking: bool, fmt: str, as_json: bool) -> None:+ """Architecture lint — fail on rule violations, cycles, or broken contracts.Checks the declared ``conformance`` rules in ``.repowise-workspace.yaml``against the system graph and detects circular service dependencies. Exitsnon-zero when any violation or cycle is found, so it can gate CI. Reads (andrecomputes from) the system graph built by 'repowise update --workspace', soediting rules and re-running picks them up without a full re-index.++ Also fails on the breaking contract changes the last workspace update+ detected — a removed endpoint or a retyped field a consumer in another repo+ still calls. Unlike the rules above these need nothing declared, so+ ``--no-breaking`` is there for a pipeline that wants only its own rules+ enforced. They are read from that update's report, not recomputed here."""import sys+ from rich.markup import escape++ from repowise.core.workspace.breaking_change import (+ SEVERITY_BREAKING,+ load_breaking_change_report,+ )from repowise.core.workspace.conformance import (build_conformance_report,tags_by_repo_from_config,@@ -1206,9 +1223,34 @@ def workspace_check(path: str | None, fmt: str, as_json: bool) -> None:tags_by_repo_from_config(ws_config),)+ # Gate on wire-incompatible changes that endanger another repo. A warning+ # severity is source-compat only and must not fail a build.+ bc_report = load_breaking_change_report(ws_root) if breaking else None+ bc_ran = bc_report is not None and bc_report.ran+ breaking_changes = (+ [+ c+ for c in bc_report.changes+ if c.severity == SEVERITY_BREAKING+ and any(ic.repo != c.provider_repo for ic in c.impacted_consumers)+ ]+ if bc_ran+ else []+ )+if fmt == "json":- emit_json(report.to_dict())- if report.has_findings:+ payload = report.to_dict()+ if breaking:+ payload["breaking_changes"] = [c.to_dict() for c in breaking_changes]+ # The conformance half is recomputed now; this half is an artifact+ # of arbitrary age, so it carries its own stamp.+ payload["breaking_changes_generated_at"] = (+ bc_report.generated_at if bc_report is not None else None+ )+ # False = never detected, so the empty list above is not a pass.+ payload["breaking_changes_available"] = bc_ran+ emit_json(payload)+ if report.has_findings or breaking_changes:sys.exit(1)return@@ -1250,18 +1292,42 @@ def workspace_check(path: str | None, fmt: str, as_json: bool) -> None:loop = " -> ".join([*c.nodes, c.nodes[0]]) if c.nodes else ""console.print(f" [red]{loop}[/red]")- if not report.has_findings:+ # Breaking contract changes+ if breaking_changes:+ stamp = bc_report.generated_at if bc_report is not None else None+ console.print(+ f"\n[red]✗ {len(breaking_changes)} breaking contract change(s)[/red]"+ + (f" [dim](detected {stamp})[/dim]" if stamp else "")+ + "[red]:[/red]"+ )+ for c in breaking_changes:+ cross = [ic for ic in c.impacted_consumers if ic.repo != c.provider_repo]+ repos = sorted({ic.repo for ic in cross})+ console.print(+ f" [red]{escape(c.contract_id)}[/red] ([dim]{escape(c.contract_type)}[/dim]) "+ f"{escape(c.kind)}: {escape(c.detail)}"+ )+ console.print(+ f" [dim]{escape(c.provider_repo)}/{escape(c.provider_file)} -> "+ f"{len(cross)} consumer(s) in {escape(', '.join(repos))}[/dim]"+ )++ if not report.has_findings and not breaking_changes:if rule_count:console.print(f"\n[green]✓[/green] No violations of {rule_count} rule(s); no dependency cycles.")else:console.print("\n[green]✓[/green] No dependency cycles.")+ if bc_ran:+ console.print("[green]✓[/green] No breaking contract changes.")return+ # Only claim a breaking-change count when a detection pass produced one.+ tail = f", {len(breaking_changes)} breaking contract change(s)" if bc_ran else ""console.print(f"\n[red]Architecture check failed:[/red] {len(report.violations)} violation(s), "- f"{len(report.cycles)} cycle(s)."+ f"{len(report.cycles)} cycle(s){tail}.")sys.exit(1)diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex ad3831450..c943cbc4c 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -41,6 +41,10 @@ class CrossRepoEnricher:self._contract_links: list[dict] = []self._contract_provider_index: dict[tuple[str, str], list[dict]] = defaultdict(list)self._contract_consumer_index: dict[tuple[str, str], list[dict]] = defaultdict(list)+ # Keyed by the ingestion symbol id, so a caller holding a symbol can+ # 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)# System graph — the service-granular structure built during workspace# update. Read-only pass-through; views over it live in core/types.@@ -186,6 +190,14 @@ class CrossRepoEnricher:continueself._contract_provider_index[provider_key].append(link)self._contract_consumer_index[consumer_key].append(link)+ provider_symbol = link.get("provider_symbol_id")+ if provider_symbol:+ self._link_provider_symbol_index[provider_symbol].append(link)++ for contract in self._contracts:+ symbol_id = contract.get("symbol_id")+ if symbol_id:+ self._contract_symbol_index[symbol_id].append(contract)_log.debug("Contract enricher loaded: %d contracts, %d links",@@ -265,6 +277,8 @@ class CrossRepoEnricher:self._contract_links = []self._contract_provider_index = defaultdict(list)self._contract_consumer_index = defaultdict(list)+ self._contract_symbol_index = defaultdict(list)+ self._link_provider_symbol_index = defaultdict(list)self._system_graph = Noneself._breaking_changes = Noneself._breaking_changes_by_repo = defaultdict(list)@@ -477,6 +491,18 @@ class CrossRepoEnricher:"""Contract links where this file is the consumer (depends on providers)."""return self._contract_consumer_index.get((repo_alias, file_path), [])+ def get_contracts_for_symbol(self, symbol_id: str) -> list[dict]:+ """Contracts bound to this ingestion symbol id, across every repo.++ A symbol id is repo-relative, so the same string can name a symbol in+ more than one repo; the caller decides what to do with several hits.+ """+ return self._contract_symbol_index.get(symbol_id, [])++ def get_contract_links_by_provider_symbol(self, symbol_id: str) -> list[dict]:+ """Contract links whose provider is this symbol — the consumers it has."""+ return self._link_provider_symbol_index.get(symbol_id, [])+def get_contract_summary(self) -> dict:"""High-level contract stats for the overview footer."""by_type: dict[str, int] = defaultdict(int)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.pyindex b2bbe922b..39a7f4863 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@@ -9,6 +9,7 @@ services carry an impact ``score`` and a ``distance``.from __future__ import annotations+from collections import defaultdictfrom typing import Anyfrom repowise.core.registry import mcp_tool_registry as mcp@@ -21,6 +22,11 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta#: tight and report the true count in ``total_impacted``._MCP_IMPACTED_LIMIT = 25+#: How many symbol-level consumers each symbol target carries inline. The+#: service-level ``impacted`` list already covers the breadth; this block is the+#: precise hop, so it stays short.+_SYMBOL_CONSUMER_LIMIT = 10+@mcp.tool(requires_workspace=True)async def get_blast_radius(@@ -36,8 +42,14 @@ async def get_blast_radius(co-change. Call before changing a high-fan-out provider to see who consumesit across repo boundaries.+ A target may also be a symbol id ("path/to/file.ts::Name"). It resolves to+ the service that publishes that symbol, and ``symbol_targets`` additionally+ names the consuming *symbols* on the far side of each contract link, which+ is the one hop the service-level graph cannot express.+Args:- targets: node ids ("repo" or "repo::service/path") or repo aliases.+ targets: node ids ("repo" or "repo::service/path"), repo aliases, or+ symbol ids of a published symbol.max_depth: reachability depth (1-8, default 3).include_behavioral: include co-change (behavioral) edges (default true)."""@@ -58,13 +70,17 @@ async def get_blast_radius("_meta": _build_meta(),}- from repowise.core.workspace.blast_radius import cross_repo_blast_radius+ from repowise.core.workspace.blast_radius import cross_repo_blast_radius, resolve_targetsfrom repowise.core.workspace.system_graph import SystemGraphgraph = SystemGraph.from_dict(raw)+ # Only targets the node/alias resolver rejected are tried as symbol ids, so+ # a string that already names a node keeps its existing meaning.+ _, unresolved = resolve_targets(graph, targets)+ symbol_targets, effective = _resolve_symbol_targets(enricher, graph, targets, unresolved)result = cross_repo_blast_radius(graph,- targets,+ effective,max_depth=max(1, min(max_depth, 8)),include_behavioral=include_behavioral,)@@ -82,12 +98,20 @@ async def get_blast_radius(f"None of the requested targets matched a service in the graph: "f"{result.unresolved_targets}.")+ # After the override: an unmatched-targets response must not claim consumers.+ if symbol_targets and result.targets:+ consumers = sum(t["consumer_count"] for t in symbol_targets)+ summary += (+ f" {len(symbol_targets)} symbol target(s) have {consumers} "+ f"consumer(s) across the contract links."+ )- return {+ payload = {"targets": result.targets,"target_repos": result.target_repos,"impacted": impacted,- "impacted_truncated": max(0, len(result.impacted) - len(impacted)),+ # Against the true total: result.impacted is itself already capped.+ "impacted_truncated": max(0, result.total_impacted - len(impacted)),"impacted_repos": result.impacted_repos,"structural_count": result.structural_count,"behavioral_count": result.behavioral_count,@@ -97,3 +121,101 @@ async def get_blast_radius("summary": summary,"_meta": _build_meta(),}+ if symbol_targets:+ payload["symbol_targets"] = symbol_targets+ return payload+++def _graph_node_for(nodes_by_repo: dict[str, list[Any]], contract: dict[str, Any]) -> str | None:+ """The system-graph node that carries *contract*, or ``None``.++ Resolved by longest service-path prefix over the graph's own nodes, the+ inverse of the ``assign_service`` walk that built them. ``Contract.service``+ is a different derivation and does not always name a node.+ """+ path = (contract.get("file_path") or "").replace("\\", "/")+ best: str | None = None+ best_len = -1+ for node in nodes_by_repo.get(contract.get("repo") or "", ()):+ service = node.service_path+ if service is None:+ if best_len < 0:+ best, best_len = node.id, 0+ elif path.startswith(service + "/") and len(service) > best_len:+ best, best_len = node.id, len(service)+ return best+++def _resolve_symbol_targets(+ enricher: Any,+ graph: Any,+ targets: list[str],+ unresolved: list[str],+) -> tuple[list[dict[str, Any]], list[str]]:+ """Expand symbol-id targets into graph nodes plus their symbol-level consumers.++ Returns the per-symbol blocks and the target list to traverse from: the+ caller's targets with each matched symbol id swapped for the node(s) that+ publish it. A symbol id matching nothing is left in place, so it still lands+ in the result's ``unresolved_targets``.+ """+ blocks: list[dict[str, Any]] = []+ replacements: dict[str, list[str]] = {}+ nodes_by_repo: dict[str, list[Any]] = defaultdict(list)+ for node in graph.nodes:+ nodes_by_repo[node.repo].append(node)+ for raw in dict.fromkeys(unresolved):+ # Providers only: a consumer contract's symbol calls a surface rather+ # than publishing one, so it has no downstream to traverse.+ contracts = [+ c+ for c in enricher.get_contracts_for_symbol(raw)+ if c.get("role") == "provider"+ ]+ nodes = sorted({node for c in contracts if (node := _graph_node_for(nodes_by_repo, c))})+ if not nodes:+ continue+ # Both indexes are repo-blind, so scope the links to the repos actually+ # traversed; otherwise the count includes a namesake's consumers.+ repos = sorted({c["repo"] for c in contracts if c.get("repo")})+ links = [+ lk+ for lk in enricher.get_contract_links_by_provider_symbol(raw)+ if lk.get("provider_repo") in set(repos)+ ]+ consumers = [+ {+ "provider_repo": link.get("provider_repo"),+ "repo": link.get("consumer_repo"),+ "file": link.get("consumer_file"),+ "contract_id": link.get("contract_id"),+ "contract_type": link.get("contract_type"),+ "match_type": link.get("match_type"),+ "confidence": link.get("confidence"),+ # An import sits at file scope, so code contracts carry none.+ **({"symbol_id": sid} if (sid := link.get("consumer_symbol_id")) else {}),+ }+ for link in links[:_SYMBOL_CONSUMER_LIMIT]+ ]+ block: dict[str, Any] = {+ "symbol_id": raw,+ "nodes": nodes,+ "contract_ids": sorted(+ {c["contract_id"] for c in contracts if c.get("contract_id")}+ ),+ "consumers": consumers,+ "consumer_count": len(links),+ "consumers_truncated": max(0, len(links) - len(consumers)),+ }+ # Symbol ids are repo-relative, so one id can name two symbols.+ if len(repos) > 1:+ block["ambiguous_in_repos"] = repos+ blocks.append(block)+ replacements[raw] = nodes++ if not replacements:+ return [], targets+ effective: list[str] = []+ for raw in targets:+ effective.extend(replacements.get(raw, [raw]))+ return blocks, effectivediff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 4e89c9b2c..7604479a5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -24,6 +24,7 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._budget import OmissionCollector, fit_to_budgetfrom repowise.server.mcp_server._helpers import (_get_repo,+ _is_workspace_mode,_resolve_repo_context,_unsupported_repo_all,)@@ -38,12 +39,20 @@ _IMPACTED_TESTS_LIMIT = 10#: per-file blocks in this response stay the same size._PRIOR_FIXES_LIMIT = 10+#: Caps on the cross-repo block. It answers "does this commit cross a repo+#: boundary", not "list every consumer" — get_blast_radius is the tool for the+#: full traversal, so both lists stay short and report their own overflow.+_CROSS_REPO_BREAKING_LIMIT = 5+_CROSS_REPO_CONSUMER_LIMIT = 10+# Cheapest loss first; the score, its drivers and fix_history's numbers are the-# answer and never shed.+# answer and never shed. cross_repo outlives the run-list: a test list is+# recoverable by running the suite, a broken consumer in another repo is not._SHED_ORDER: tuple[str, ...] = ("exclude_patterns","prior_fixes","impacted_tests",+ "cross_repo","fix_history.files",)@@ -58,25 +67,27 @@ async def get_change_risk() -> dict:"""Score a live commit, ``base..head`` range, or uncommitted work.- Use this for a pre-merge read on a commit or PR range. Distinct from- ``get_risk``, which scores indexed files and PR blast radius. The filters- below also apply to the percentile baseline.+ For a pre-merge read on a commit or PR range; ``get_risk`` scores indexed+ files instead. The filters also apply to the percentile baseline.- Lead with ``fix_history``: the recency-weighted bug-fix record of the files- touched, ``files`` naming where the pressure sits. It separates a surgical- edit to a bug magnet from a bulk rename of files that never break. ``score`` measures diff size and spread, not where the change lands- (see ``score_measures``); calibrated per commit, so a PR-sized change reads- high by construction. ``risk_percentile`` ranks that shape against recent+ Lead with ``fix_history``: the recency-weighted bug-fix record of the+ touched files, ``files`` naming where the pressure sits. It separates a+ surgical edit to a bug magnet from a bulk rename. ``score`` measures diff+ size and spread, not where the change lands (see ``score_measures``),+ calibrated per commit; ``risk_percentile`` ranks that shape against recentcommits.- ``impacted_tests.tests_to_run`` names the tests for this change;- ``missing_tests`` the uncovered lines. ``basis``: ``measured`` = a coverage- map proves those tests run the changed *lines*; ``inferred`` = test files- the graph shows reaching it (candidates, file-level). No map is never- "untested": ``no_map`` means run the suite. On ``truncated``, expand+ ``impacted_tests.tests_to_run`` names the tests to run; ``missing_tests``+ the uncovered lines. ``basis``: ``measured`` = a coverage map proves those+ tests run the changed *lines*; ``inferred`` = test files the graph shows+ reaching it (file-level candidates). No map is never "untested":+ ``no_map`` means run the suite. On ``truncated``, expand``omission_marker`` for the tail. ``prior_fixes``counts past fixes whose lines overlap this diff.+ ``cross_repo`` (workspace mode) names other repos' consumers of the changed+ files and what broke, as of the last workspace update.+Args:revspec: Commit or ``base..head`` range to score. Omit it to score theuncommitted change, or ``HEAD`` when the working tree is clean.@@ -115,11 +126,12 @@ async def get_change_risk(# extensions + riskignore + request excludes), so nothing downstream# disagrees with the score about which files the change touches. Read once# and shared: both blocks below need it and git is the expensive part.- # Skipped entirely without an index, because neither block can say anything- # then and the git call is the expensive half of this response.+ # The test and fix blocks need the index; the cross-repo block needs only+ # workspace contracts, so an unindexed member still gets one rather than+ # going silently blind. Nothing else pays the git call.changed: dict[str, set[int]] = {}changed_error: tuple[str, str] | None = None- if getattr(ctx, "session_factory", None) is not None:+ if getattr(ctx, "session_factory", None) is not None or _has_contract_data():changed, changed_error = await _changed_in_scope(str(ctx.path),revspec,@@ -134,6 +146,9 @@ async def get_change_risk(prior_fixes = await _prior_fixes_block(ctx, changed)if prior_fixes is not None:payload["prior_fixes"] = prior_fixes+ cross_repo = _cross_repo_block(getattr(ctx, "alias", ""), sorted(changed))+ if cross_repo is not None:+ payload["cross_repo"] = cross_repo# source: live_git marks that the *score* is computed from the working# checkout's git. The two blocks above are index-backed, so the freshness# fields do apply to them, scoped to the change's files. None (not []) when@@ -207,6 +222,142 @@ def _filter_changed(return out+def _has_contract_data() -> bool:+ """Whether workspace contracts are loaded, so the cross-repo block can speak."""+ from repowise.server.mcp_server import _state++ if not _is_workspace_mode():+ return False+ enricher = _state._cross_repo_enricher+ return bool(enricher is not None and getattr(enricher, "has_contract_data", False))+++def _cross_repo_block(alias: str, changed_files: list[str]) -> dict[str, Any] | None:+ """What this commit does to consumers in other repos, or ``None``.++ A commit that changes a published signature is the same class of fact as+ its fix history, so it belongs beside it. Two sources, both from the last+ ``repowise update --workspace``: the contract links whose provider file this+ commit touched (who calls it), and the breaking-change report entries+ attributed to those same files (what broke). ``None`` outside workspace+ mode, without artifacts, or when the commit touches no published file, so+ the block never appears just to say nothing. Never raises.+ """+ try:+ from repowise.server.mcp_server import _state++ if not changed_files or not _is_workspace_mode():+ return None+ enricher = _state._cross_repo_enricher+ if enricher is None or not getattr(enricher, "has_contract_data", False):+ return None++ touched = set(changed_files)+ consumers: list[dict[str, Any]] = []+ seen: set[tuple[str, str, str, str]] = set()+ for path in changed_files:+ for link in enricher.get_contract_links_as_provider(alias, path):+ if link.get("consumer_repo") == alias:+ continue+ # Keyed by contract too: collapsing loses a contract_id.+ key = (+ link.get("consumer_repo") or "",+ link.get("consumer_file") or "",+ link.get("contract_id") or "",+ path,+ )+ if key in seen:+ continue+ seen.add(key)+ consumers.append(+ {+ "provider_file": path,+ "repo": link.get("consumer_repo"),+ "file": link.get("consumer_file"),+ "contract_id": link.get("contract_id"),+ "contract_type": link.get("contract_type"),+ "match_type": link.get("match_type"),+ **(+ {"provider_symbol_id": psid}+ if (psid := link.get("provider_symbol_id"))+ else {}+ ),+ **(+ {"symbol_id": sid}+ if (sid := link.get("consumer_symbol_id"))+ else {}+ ),+ }+ )++ breaking: list[dict[str, Any]] = []+ breaking_total = 0+ has_breaking_report = bool(getattr(enricher, "has_breaking_changes", False))+ if has_breaking_report:+ for change in enricher.get_breaking_changes_for_repo(alias):+ if change.get("provider_file") not in touched:+ continue+ cross = [+ c for c in change.get("impacted_consumers", []) if c.get("repo") != alias+ ]+ if not cross:+ continue+ breaking_total += 1+ if len(breaking) >= _CROSS_REPO_BREAKING_LIMIT:+ continue+ breaking.append(+ {+ "contract_id": change.get("contract_id"),+ "type": change.get("contract_type"),+ "kind": change.get("kind"),+ "severity": change.get("severity"),+ "detail": change.get("detail"),+ "provider_file": change.get("provider_file"),+ "impacted_repos": sorted({c.get("repo") or "" for c in cross}),+ **(+ {"provider_symbol_id": psid}+ if (psid := change.get("provider_symbol_id"))+ else {}+ ),+ }+ )++ if not consumers and not breaking:+ return None+ report = enricher.get_breaking_changes() or {}+ # A removed endpoint has no current link, so its repos survive only on+ # the breaking side.+ repos = sorted(+ {c["repo"] for c in consumers if c.get("repo")}+ | {r for b in breaking for r in b["impacted_repos"] if r}+ )+ summary = (+ f"{len(consumers)} consumer link(s) in {len(repos)} other repo(s) touch the "+ f"files this change edits"+ )+ if breaking_total:+ summary += f"; {breaking_total} of the changed contracts broke them."+ elif has_breaking_report:+ summary += "; the last workspace update found no break in them."+ else:+ summary += "; no breaking-change report has been built for them."+ return {+ "consumers": consumers[:_CROSS_REPO_CONSUMER_LIMIT],+ "consumers_truncated": max(0, len(consumers) - _CROSS_REPO_CONSUMER_LIMIT),+ "consumer_repos": repos,+ "breaking_changes": breaking,+ "breaking_changes_truncated": breaking_total - len(breaking),+ # False = no detection pass ran, so the empty list is silence.+ "breaking_changes_available": has_breaking_report,+ # Stamps the breaking half only; the consumer list comes from the+ # contract artifact, which carries no exposed stamp.+ "breaking_changes_as_of": report.get("generated_at") or None,+ "summary": summary,+ }+ except Exception:+ return None++def _empty_impacted(status: str, summary: str) -> dict[str, Any]:"""Uniform impacted-tests block for the degraded (no tests to name) paths."""return {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.pyindex c08540f72..632faee54 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@@ -54,30 +54,37 @@ _WILL_BREAK_TESTS_LIMIT = 3_TESTS_TO_RUN_LIMIT = 10-def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:+def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], int]:"""Breaking-change half of the PR directive: incompatible provider changes.Reads the persisted breaking-change report (current HEAD vs the previouslyindexed contracts), filtered to providers in the changed repo, and reports- each change with the consumers it endangers across repos. Returns an empty- list when not in workspace mode or no report is available. Never raises.+ each change with the consumers it endangers across repos. Carries every+ contract type the report holds, ``code`` (a published package symbol)+ included. Returns ``(changes, dropped)`` where ``dropped`` counts the+ cross-repo changes the cap left out — a shared-package bump can produce+ more than the cap, and the ids sort by contract type, so silence here would+ read as "nothing else broke". Empty when not in workspace mode or no report+ is available. Never raises."""out: list[dict[str, Any]] = []+ dropped = 0try:if not _is_workspace_mode():- return out+ return out, 0enricher = _state._cross_repo_enricherif enricher is None or not getattr(enricher, "has_breaking_changes", False):- return out+ return out, 0for change in enricher.get_breaking_changes_for_repo(repo_alias):- if len(out) >= _BC_PROVIDER_LIMIT:- breakconsumers = change.get("impacted_consumers", [])# Only surface changes that actually endanger a cross-repo consumer —# an internal-only removed endpoint isn't a cross-repo break.cross = [c for c in consumers if c.get("repo") != repo_alias]if not cross:continue+ if len(out) >= _BC_PROVIDER_LIMIT:+ dropped += 1+ continueout.append({"contract_id": change.get("contract_id"),@@ -85,6 +92,15 @@ def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:"kind": change.get("kind"),"severity": change.get("severity"),"detail": change.get("detail"),+ "provider_file": change.get("provider_file"),+ # The changed symbol itself, when the contract bound to one.+ # It is what the reader passes to get_symbol to see the+ # signature that broke.+ **(+ {"provider_symbol_id": psid}+ if (psid := change.get("provider_symbol_id"))+ else {}+ ),"impacted_consumers": [# symbol_id only when the contract bound to one: it is# what the reader can pass to get_symbol, and a null@@ -100,8 +116,8 @@ def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:})except Exception:- return []- return out+ return [], 0+ return out, droppeddef _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:@@ -396,7 +412,7 @@ def _build_pr_directive(# Breaking-change guard — incompatible provider changes (removed route /# field, type change, ...) in this repo and the consumers they endanger.# Schema-level truth, distinct from the topology-level will_break_consumers.- breaking_changes = _breaking_change_directive(alias)+ breaking_changes, breaking_changes_dropped = _breaking_change_directive(alias)bc_suffix = ""if breaking_changes:bc_consumers = sum(len(b["impacted_consumers"]) for b in breaking_changes)@@ -404,6 +420,8 @@ def _build_pr_directive(f" Breaking changes: {len(breaking_changes)} provider contract(s) changed "f"incompatibly, endangering {bc_consumers} consumer(s).")+ if breaking_changes_dropped:+ bc_suffix += f" {breaking_changes_dropped} more not listed."# Architecture conformance — declared dependency-rule violations and# dependency cycles this repo participates in. Governance-level truth,@@ -427,6 +445,7 @@ def _build_pr_directive("will_break_consumers": will_break_consumers,"missing_cross_repo_cochanges": missing_cross_repo_cochanges,"breaking_changes": breaking_changes,+ "breaking_changes_truncated": breaking_changes_dropped,"conformance_violations": conformance_violations,"dependency_cycles": dependency_cycles,"governance_risk": governance_risk,diff --git a/tests/unit/cli/test_update_workspace_breaking_line.py b/tests/unit/cli/test_update_workspace_breaking_line.pynew file mode 100644index 000000000..161181443--- /dev/null+++ b/tests/unit/cli/test_update_workspace_breaking_line.py@@ -0,0 +1,102 @@+"""The one line `repowise update --workspace` prints when contracts broke."""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest++from repowise.cli.commands.update_cmd.workspace import _print_breaking_changes+from repowise.core.workspace.breaking_change import (+ BreakingChange,+ BreakingChangeReport,+ ImpactedConsumer,+ save_breaking_change_report,+)++STAMP = datetime(2026, 8, 23, 12, 0, tzinfo=UTC)+++def _save(+ root: Path,+ *,+ generated_at: str | None,+ severity: str = "breaking",+ consumer_repo: str = "frontend",+) -> None:+ save_breaking_change_report(+ BreakingChangeReport(+ generated_at=generated_at,+ changes=[+ BreakingChange(+ kind="removed_endpoint",+ severity=severity,+ contract_id="code::@acme/types::Order",+ contract_type="code",+ provider_repo="api",+ provider_file="src/types.ts",+ provider_symbol="Order",+ provider_service=None,+ detail="code::@acme/types::Order was removed",+ impacted_consumers=[+ ImpactedConsumer(+ repo=consumer_repo,+ service=None,+ node_id=consumer_repo,+ file="src/api.ts",+ symbol="@acme/types:Order",+ match_type="exact",+ confidence=0.9,+ )+ ],+ )+ ],+ ),+ root,+ )+++def test_reports_a_report_this_update_wrote(tmp_path: Path, capsys: pytest.CaptureFixture[str]):+ _save(tmp_path, generated_at=(STAMP + timedelta(seconds=5)).isoformat())+ _print_breaking_changes(tmp_path, STAMP)+ out = capsys.readouterr().out+ assert "1 breaking contract change(s)" in out+ assert "frontend" in out+ assert "workspace check" in out+++def test_silent_on_a_report_from_a_previous_update(+ tmp_path: Path, capsys: pytest.CaptureFixture[str]+):+ """A stale artifact belongs to an earlier run and must not be attributed here."""+ _save(tmp_path, generated_at=(STAMP - timedelta(hours=1)).isoformat())+ _print_breaking_changes(tmp_path, STAMP)+ assert capsys.readouterr().out == ""+++def test_silent_when_detection_never_ran(tmp_path: Path, capsys: pytest.CaptureFixture[str]):+ _save(tmp_path, generated_at=None)+ _print_breaking_changes(tmp_path, STAMP)+ assert capsys.readouterr().out == ""+++def test_silent_without_a_report(tmp_path: Path, capsys: pytest.CaptureFixture[str]):+ _print_breaking_changes(tmp_path, STAMP)+ assert capsys.readouterr().out == ""+++def test_a_warning_is_not_announced_as_a_break(tmp_path: Path, capsys: pytest.CaptureFixture[str]):+ """`workspace check` would pass on this, so the line must not alarm."""+ _save(tmp_path, generated_at=(STAMP + timedelta(seconds=5)).isoformat(), severity="warning")+ _print_breaking_changes(tmp_path, STAMP)+ out = capsys.readouterr().out+ assert "none breaks another repo" in out+ assert "breaking contract change" not in out+++def test_an_internal_only_break_is_not_announced(tmp_path: Path, capsys: pytest.CaptureFixture[str]):+ """Same filter `workspace check` gates on, so the two never contradict."""+ _save(tmp_path, generated_at=(STAMP + timedelta(seconds=5)).isoformat(), consumer_repo="api")+ _print_breaking_changes(tmp_path, STAMP)+ assert "none breaks another repo" in capsys.readouterr().outdiff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.pyindex 78dc49ced..a02c06800 100644--- a/tests/unit/cli/test_workspace_cmd.py+++ b/tests/unit/cli/test_workspace_cmd.py@@ -613,3 +613,238 @@ class TestWorkspaceCheck:result = runner.invoke(cli, ["workspace", "check", "--help"])assert result.exit_code == 0assert "non-zero" in result.output or "CI" in result.output+++# ---------------------------------------------------------------------------+# workspace check — breaking contract changes+# ---------------------------------------------------------------------------+++class TestWorkspaceCheckBreaking:+ """`check` fails on breaking contract changes without any rule declared."""++ def _write_config(self, root: Path) -> None:+ data = {+ "version": 1,+ "default_repo": "frontend",+ "repos": [+ {"path": "frontend", "alias": "frontend"},+ {"path": "api", "alias": "api"},+ ],+ }+ (root / WORKSPACE_CONFIG_FILENAME).write_text(+ yaml.dump(data, default_flow_style=False), encoding="utf-8"+ )++ def _save_graph(self, root: Path) -> None:+ from repowise.core.workspace.system_graph import (+ SystemGraph,+ SystemNode,+ save_system_graph,+ )++ save_system_graph(+ SystemGraph(+ nodes=[+ SystemNode(id=n, repo=n, service_path=None, name=n)+ for n in ("api", "frontend")+ ]+ ),+ root,+ )++ def _save_report(+ self,+ root: Path,+ *,+ consumer_repo: str,+ severity: str = "breaking",+ extra_consumers: tuple[str, ...] = (),+ ) -> None:+ from repowise.core.workspace.breaking_change import (+ BreakingChange,+ BreakingChangeReport,+ ImpactedConsumer,+ save_breaking_change_report,+ )++ save_breaking_change_report(+ BreakingChangeReport(+ generated_at="2026-08-23T00:00:00+00:00",+ changes=[+ BreakingChange(+ kind="removed_endpoint",+ severity=severity,+ contract_id="code::@acme/types::Order",+ contract_type="code",+ provider_repo="api",+ provider_file="src/types.ts",+ provider_symbol="Order",+ provider_service=None,+ detail="code::@acme/types::Order was removed",+ impacted_consumers=[+ ImpactedConsumer(+ repo=repo,+ service=None,+ node_id=repo,+ file=f"src/{i}.ts",+ symbol="@acme/types:Order",+ match_type="exact",+ confidence=0.9,+ )+ for i, repo in enumerate((consumer_repo, *extra_consumers))+ ],+ )+ ],+ ),+ root,+ )++ def test_breaking_change_fails_check_by_default(self, runner, tmp_path):+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 1, result.output+ assert "code::@acme/types::Order" in result.output+ assert "1 breaking contract change(s)" in result.output++ def test_no_breaking_flag_restores_the_old_gate(self, runner, tmp_path):+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--no-breaking"])+ assert result.exit_code == 0, result.output+ assert "@acme/types::Order" not in result.output++ def test_internal_only_change_does_not_fail(self, runner, tmp_path):+ """A provider whose only consumer is its own repo is not a cross-repo break."""+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="api")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 0, result.output+ assert "No breaking contract changes" in result.output++ def test_json_carries_the_breaking_changes(self, runner, tmp_path):+ import json++ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--json"])+ assert result.exit_code == 1+ data = json.loads(result.output)+ assert data["violation_count"] == 0+ assert [c["contract_id"] for c in data["breaking_changes"]] == [+ "code::@acme/types::Order"+ ]++ def test_no_report_leaves_check_silent(self, runner, tmp_path):+ """Nothing said when the workspace has never run a detection pass."""+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 0, result.output+ assert "breaking contract" not in result.output++ def test_a_warning_severity_does_not_fail_the_build(self, runner, tmp_path):+ """A removed request field is source-compat only, not wire-incompatible."""+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend", severity="warning")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 0, result.output+ assert "No breaking contract changes" in result.output++ def test_the_consumer_count_is_the_cross_repo_one(self, runner, tmp_path):+ """Two of the three consumers are in the provider's own repo."""+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(+ tmp_path, consumer_repo="frontend", extra_consumers=("api", "api")+ )+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 1, result.output+ assert "1 consumer(s) in frontend" in result.output++ def test_the_report_stamp_is_shown_beside_the_finding(self, runner, tmp_path):+ """The graph is recomputed now; this artifact can be any age."""+ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert "2026-08-23T00:00:00+00:00" in result.output++ def test_json_stamps_the_breaking_half_separately(self, runner, tmp_path):+ import json++ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ self._save_report(tmp_path, consumer_repo="frontend")+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--json"])+ data = json.loads(result.output)+ assert data["breaking_changes_generated_at"] == "2026-08-23T00:00:00+00:00"+ assert data["breaking_changes_available"] is True++ def test_json_says_when_nothing_ever_looked(self, runner, tmp_path):+ """An empty list without this flag reads as a pass in CI."""+ import json++ self._write_config(tmp_path)+ self._save_graph(tmp_path)+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--json"])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["breaking_changes"] == []+ assert data["breaking_changes_available"] is False++ def test_the_failure_line_omits_a_count_nothing_produced(self, runner, tmp_path):+ """With no report there is no 0 to claim."""+ self._write_config_with_rule_and_violation(tmp_path)+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])+ assert result.exit_code == 1+ assert "breaking contract change(s)." not in result.output+ assert "cycle(s)." in result.output++ def _write_config_with_rule_and_violation(self, root: Path) -> None:+ from repowise.core.workspace.system_graph import (+ SystemEdge,+ SystemGraph,+ SystemNode,+ save_system_graph,+ )++ data = {+ "version": 1,+ "default_repo": "frontend",+ "repos": [+ {"path": "frontend", "alias": "frontend"},+ {"path": "api", "alias": "api"},+ ],+ "conformance": {"rules": [{"source": "frontend", "target": "api"}]},+ }+ (root / WORKSPACE_CONFIG_FILENAME).write_text(+ yaml.dump(data, default_flow_style=False), encoding="utf-8"+ )+ save_system_graph(+ SystemGraph(+ nodes=[+ SystemNode(id=n, repo=n, service_path=None, name=n)+ for n in ("api", "frontend")+ ],+ edges=[+ SystemEdge(+ id="frontend->api:http",+ source="frontend",+ target="api",+ kind="http",+ match_type="exact",+ confidence=1.0,+ weight=1,+ structural=True,+ )+ ],+ ),+ root,+ )diff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pyindex bb634c6ca..537414501 100644--- a/tests/unit/server/test_mcp_blast_radius.py+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -25,6 +25,7 @@ def _enricher_with_graph(tmp_path: Path) -> CrossRepoEnricher:file_path="routes.py",symbol_name="get_users",confidence=0.9,+ symbol_id="routes.py::get_users",),Contract(repo="frontend",@@ -34,6 +35,7 @@ def _enricher_with_graph(tmp_path: Path) -> CrossRepoEnricher:file_path="client.ts",symbol_name="fetchUsers",confidence=0.8,+ symbol_id="client.ts::fetchUsers",),]links = [@@ -50,6 +52,8 @@ def _enricher_with_graph(tmp_path: Path) -> CrossRepoEnricher:consumer_file="client.ts",consumer_symbol="fetchUsers",consumer_service=None,+ provider_symbol_id="routes.py::get_users",+ consumer_symbol_id="client.ts::fetchUsers",),]overlay = CrossRepoOverlay(@@ -64,8 +68,18 @@ def _enricher_with_graph(tmp_path: Path) -> CrossRepoEnricher:)graph = build_system_graph(contracts, links, overlay, {}, generated_at="t")(tmp_path / "system_graph.json").write_text(json.dumps(graph.to_dict()), 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",)@@ -196,11 +210,12 @@ def test_breaking_change_directive_reports_impacted_consumers(tmp_path: Path):_state._registry = object()_state._cross_repo_enricher = _enricher_with_breaking(tmp_path)try:- directive = _breaking_change_directive("backend")+ directive, dropped = _breaking_change_directive("backend")finally:_state._registry = prev_registry_state._cross_repo_enricher = prev_enricherassert len(directive) == 1+ assert dropped == 0assert directive[0]["kind"] == "removed_endpoint"assert directive[0]["severity"] == "breaking"assert directive[0]["impacted_consumers"][0]["repo"] == "frontend"@@ -215,7 +230,7 @@ def test_breaking_change_directive_empty_for_other_repo(tmp_path: Path):_state._cross_repo_enricher = _enricher_with_breaking(tmp_path)try:# 'frontend' is a consumer, not the provider of the change → no directive.- assert _breaking_change_directive("frontend") == []+ assert _breaking_change_directive("frontend") == ([], 0)finally:_state._registry = prev_registry_state._cross_repo_enricher = prev_enricher@@ -227,7 +242,7 @@ def test_breaking_change_directive_empty_outside_workspace():prev = _state._registry_state._registry = Nonetry:- assert _breaking_change_directive("backend") == []+ assert _breaking_change_directive("backend") == ([], 0)finally:_state._registry = prev@@ -245,3 +260,145 @@ async def test_no_system_graph_returns_error(tmp_path: Path):_state._cross_repo_enricher = prev_enricherassert "error" in resultassert "system graph" in result["error"]+++async def test_symbol_target_resolves_to_publishing_service(workspace_state):+ """A symbol id names the service that publishes it, not a node id."""+ result = await get_blast_radius(["routes.py::get_users"])+ assert result["targets"] == ["backend"]+ assert result["unresolved_targets"] == []+ assert {n["id"] for n in result["impacted"]} == {"frontend"}+++async def test_symbol_target_names_the_consuming_symbol(workspace_state):+ """The hop the service graph cannot express: which symbol calls it."""+ result = await get_blast_radius(["routes.py::get_users"])+ blocks = result["symbol_targets"]+ assert len(blocks) == 1+ assert blocks[0]["symbol_id"] == "routes.py::get_users"+ assert blocks[0]["nodes"] == ["backend"]+ assert blocks[0]["contract_ids"] == ["http::GET::/users"]+ assert blocks[0]["consumers"] == [+ {+ "provider_repo": "backend",+ "repo": "frontend",+ "file": "client.ts",+ "contract_id": "http::GET::/users",+ "contract_type": "http",+ "match_type": "exact",+ "confidence": 0.8,+ "symbol_id": "client.ts::fetchUsers",+ }+ ]+ assert blocks[0]["consumers_truncated"] == 0+ assert blocks[0]["consumer_count"] == 1+ assert "ambiguous_in_repos" not in blocks[0]+ assert result["summary"].endswith(+ " 1 symbol target(s) have 1 consumer(s) across the contract links."+ )+++async def test_unknown_symbol_id_stays_unresolved(workspace_state):+ """A symbol-shaped string bound to no contract is not silently absorbed."""+ result = await get_blast_radius(["routes.py::no_such_handler"])+ assert result["unresolved_targets"] == ["routes.py::no_such_handler"]+ assert result["targets"] == []+ assert "symbol_targets" not in result+++async def test_node_target_carries_no_symbol_block(workspace_state):+ """Existing node/alias targets keep their exact previous response shape."""+ result = await get_blast_radius(["backend"])+ assert "symbol_targets" not in result+++def _breaking_enricher(tmp_path: Path, contracts, links) -> CrossRepoEnricher:+ """An enricher whose report is 'every one of these providers was removed'."""+ from repowise.core.workspace.breaking_change import detect_breaking_changes+ from repowise.core.workspace.contracts import ContractStore++ report = detect_breaking_changes(+ ContractStore(contracts=contracts, contract_links=links),+ ContractStore(),+ generated_at="t",+ )+ (tmp_path / "breaking_changes.json").write_text(json.dumps(report.to_dict()), encoding="utf-8")+ return CrossRepoEnricher(+ tmp_path / "cross_repo_edges.json",+ breaking_changes_path=tmp_path / "breaking_changes.json",+ )+++def _code_provider(name: str) -> Contract:+ return Contract(+ repo="backend",+ contract_id=f"code::@acme/types::{name}",+ contract_type="code",+ role="provider",+ file_path="src/types.ts",+ symbol_name=name,+ confidence=0.9,+ service="packages/types",+ symbol_id=f"src/types.ts::{name}",+ )+++def _code_link(name: str) -> ContractLink:+ return ContractLink(+ contract_id=f"code::@acme/types::{name}",+ contract_type="code",+ match_type="exact",+ confidence=0.9,+ provider_repo="backend",+ provider_file="src/types.ts",+ provider_symbol=name,+ provider_service="packages/types",+ consumer_repo="frontend",+ consumer_file="src/api.ts",+ consumer_symbol=f"@acme/types:{name}",+ consumer_service=None,+ provider_symbol_id=f"src/types.ts::{name}",+ )+++def _run_directive(tmp_path: Path, contracts, links, alias: str = "backend"):+ from repowise.server.mcp_server.tool_risk import _breaking_change_directive++ prev_registry = _state._registry+ prev_enricher = _state._cross_repo_enricher+ _state._registry = object()+ _state._cross_repo_enricher = _breaking_enricher(tmp_path, contracts, links)+ try:+ return _breaking_change_directive(alias)+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+++def test_directive_carries_code_contracts_with_a_traversable_provider(tmp_path: Path):+ """A removed published symbol is a cross-repo break like a removed route."""+ directive, dropped = _run_directive(tmp_path, [_code_provider("Order")], [_code_link("Order")])+ assert dropped == 0+ assert len(directive) == 1+ entry = directive[0]+ assert entry["type"] == "code"+ assert entry["kind"] == "removed_endpoint"+ assert entry["provider_file"] == "src/types.ts"+ assert entry["provider_symbol_id"] == "src/types.ts::Order"+ assert entry["impacted_consumers"] == [+ {"repo": "frontend", "service": None, "file": "src/api.ts"}+ ]+++def test_directive_reports_what_the_provider_cap_left_out(tmp_path: Path):+ """A shared-package bump exceeds the cap; the count must not go silent."""+ names = [f"Type{i}" for i in range(7)]+ directive, dropped = _run_directive(+ tmp_path, [_code_provider(n) for n in names], [_code_link(n) for n in names]+ )+ assert len(directive) == 5+ assert dropped == 2diff --git a/tests/unit/server/test_mcp_blast_radius_symbols.py b/tests/unit/server/test_mcp_blast_radius_symbols.pynew file mode 100644index 000000000..e2297a7a8--- /dev/null+++ b/tests/unit/server/test_mcp_blast_radius_symbols.py@@ -0,0 +1,237 @@+"""Symbol-id targets in get_blast_radius, and the enricher indexes behind them."""++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.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_blast_radius import (+ _SYMBOL_CONSUMER_LIMIT,+ get_blast_radius,+)+++def _enricher(tmp_path: Path, contracts, links, boundaries=None) -> CrossRepoEnricher:+ graph = build_system_graph(+ contracts, links, CrossRepoOverlay(), boundaries or {}, generated_at="t"+ )+ (tmp_path / "system_graph.json").write_text(json.dumps(graph.to_dict()), 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 _provider(+ *,+ repo: str = "backend",+ contract_id: str = "code::@acme/types::Order",+ file_path: str = "src/types.ts",+ name: str = "Order",+ service: str | None = None,+ symbol_id: str | None = None,+) -> Contract:+ return Contract(+ repo=repo,+ contract_id=contract_id,+ contract_type="code",+ role="provider",+ file_path=file_path,+ symbol_name=name,+ confidence=0.9,+ service=service,+ symbol_id=symbol_id or f"{file_path}::{name}",+ )+++def _consumer(+ *,+ repo: str = "frontend",+ contract_id: str = "code::@acme/types::Order",+ file_path: str = "src/api.ts",+ service: str | None = None,+) -> Contract:+ return Contract(+ repo=repo,+ contract_id=contract_id,+ contract_type="code",+ role="consumer",+ file_path=file_path,+ symbol_name="@acme/types:Order",+ confidence=0.9,+ service=service,+ )+++def _link(provider: Contract, consumer: Contract) -> ContractLink:+ return ContractLink(+ contract_id=provider.contract_id,+ contract_type="code",+ match_type="exact",+ confidence=0.9,+ provider_repo=provider.repo,+ provider_file=provider.file_path,+ provider_symbol=provider.symbol_name,+ provider_service=provider.service,+ consumer_repo=consumer.repo,+ consumer_file=consumer.file_path,+ consumer_symbol=consumer.symbol_name,+ consumer_service=consumer.service,+ provider_symbol_id=provider.symbol_id,+ )+++async def test_a_consumer_symbol_is_not_a_publisher(tmp_path: Path):+ """A call site names a contract it consumes; it publishes no downstream."""+ provider = _provider()+ consumer = _consumer()+ consumer.symbol_id = "src/api.ts::useOrder"+ with _in_workspace(_enricher(tmp_path, [provider, consumer], [])):+ result = await get_blast_radius(["src/api.ts::useOrder"])+ assert result["unresolved_targets"] == ["src/api.ts::useOrder"]+ assert result["targets"] == []+ assert "symbol_targets" not in result+++async def test_an_ambiguous_symbol_id_says_so(tmp_path: Path):+ """Symbol ids are repo-relative, so one id can name two published symbols."""+ contracts = [+ _provider(+ repo=repo,+ contract_id=f"code::@acme/{repo}::main",+ file_path="src/index.ts",+ name="main",+ )+ for repo in ("api", "worker")+ ]+ with _in_workspace(_enricher(tmp_path, contracts, [])):+ result = await get_blast_radius(["src/index.ts::main"])+ block = result["symbol_targets"][0]+ assert block["ambiguous_in_repos"] == ["api", "worker"]+ assert block["nodes"] == ["api", "worker"]+ assert result["targets"] == ["api", "worker"]+++async def test_symbol_consumers_are_capped_and_counted(tmp_path: Path):+ over = _SYMBOL_CONSUMER_LIMIT + 4+ provider = _provider()+ consumers = [_consumer(file_path=f"src/api{i}.ts") for i in range(over)]+ links = [_link(provider, c) for c in consumers]+ with _in_workspace(_enricher(tmp_path, [provider, *consumers], links)):+ result = await get_blast_radius(["src/types.ts::Order"])+ block = result["symbol_targets"][0]+ assert len(block["consumers"]) == _SYMBOL_CONSUMER_LIMIT+ assert block["consumer_count"] == over+ assert block["consumers_truncated"] == 4+ # The summary reports the true count, not the capped list's length.+ assert f"{over} consumer(s) across the contract links" in result["summary"]+++async def test_a_service_scoped_symbol_resolves_to_its_service_node(tmp_path: Path):+ """Graph nodes come from service boundaries, not from ``Contract.service``."""+ from repowise.core.workspace.extractors.service_boundary import ServiceBoundary++ provider = _provider(file_path="packages/types/src/types.ts", service="packages/types")+ consumer = _consumer(file_path="app/src/api.ts", service="app")+ boundaries = {+ "backend": [ServiceBoundary(service_path="packages/types", service_name="types")],+ "frontend": [ServiceBoundary(service_path="app", service_name="app")],+ }+ enricher = _enricher(tmp_path, [provider, consumer], [_link(provider, consumer)], boundaries)+ with _in_workspace(enricher):+ result = await get_blast_radius(["packages/types/src/types.ts::Order"])+ assert result["symbol_targets"][0]["nodes"] == ["backend::packages/types"]+ assert result["targets"] == ["backend::packages/types"]+ assert {n["id"] for n in result["impacted"]} == {"frontend::app"}+++async def test_a_stale_contract_service_does_not_invent_a_node(tmp_path: Path):+ """``Contract.service`` naming no node falls back to the repo node."""+ provider = _provider(file_path="src/types.ts", service="packages/gone")+ with _in_workspace(_enricher(tmp_path, [provider], [])):+ result = await get_blast_radius(["src/types.ts::Order"])+ assert result["symbol_targets"][0]["nodes"] == ["backend"]+ assert result["unresolved_targets"] == []+++async def test_a_symbol_target_alongside_a_node_target_keeps_both(tmp_path: Path):+ provider = _provider()+ consumer = _consumer()+ with _in_workspace(_enricher(tmp_path, [provider, consumer], [_link(provider, consumer)])):+ result = await get_blast_radius(["frontend", "src/types.ts::Order"])+ assert result["targets"] == ["backend", "frontend"]+ assert [b["symbol_id"] for b in result["symbol_targets"]] == ["src/types.ts::Order"]+++async def test_a_repeated_symbol_target_is_reported_once(tmp_path: Path):+ provider = _provider()+ consumer = _consumer()+ with _in_workspace(_enricher(tmp_path, [provider, consumer], [_link(provider, consumer)])):+ result = await get_blast_radius(["src/types.ts::Order", "src/types.ts::Order"])+ assert len(result["symbol_targets"]) == 1+ assert "1 symbol target(s) have 1 consumer(s)" in result["summary"]+++async def test_a_nested_symbol_id_resolves(tmp_path: Path):+ """The three-segment form the parser mints for a method on a class."""+ provider = _provider(+ contract_id="http::GET::/users",+ file_path="UsersController.cs",+ name="aspnet:GET /users",+ symbol_id="UsersController.cs::UsersController::GetUsers",+ )+ with _in_workspace(_enricher(tmp_path, [provider], [])):+ result = await get_blast_radius(["UsersController.cs::UsersController::GetUsers"])+ assert result["targets"] == ["backend"]+ assert result["symbol_targets"][0]["nodes"] == ["backend"]+++def test_enricher_symbol_indexes_survive_a_reload(tmp_path: Path):+ """reload() runs in the job executor; a missed reset would double every row."""+ provider = _provider()+ consumer = _consumer()+ enricher = _enricher(tmp_path, [provider, consumer], [_link(provider, consumer)])+ assert len(enricher.get_contracts_for_symbol("src/types.ts::Order")) == 1+ enricher.reload()+ assert len(enricher.get_contracts_for_symbol("src/types.ts::Order")) == 1+ assert len(enricher.get_contract_links_by_provider_symbol("src/types.ts::Order")) == 1+ assert enricher.get_contracts_for_symbol("nope.ts::Nope") == []diff --git a/tests/unit/server/test_mcp_change_risk_cross_repo.py b/tests/unit/server/test_mcp_change_risk_cross_repo.pynew file mode 100644index 000000000..e94e221cd--- /dev/null+++ b/tests/unit/server/test_mcp_change_risk_cross_repo.py@@ -0,0 +1,321 @@+"""The cross-repo consequence get_change_risk attaches to a scored commit."""++from __future__ import annotations++import json+from pathlib import Path++from repowise.core.workspace.breaking_change import (+ BreakingChange,+ BreakingChangeReport,+ ImpactedConsumer,+)+from repowise.core.workspace.contracts import Contract, ContractLink+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._enrichment import CrossRepoEnricher+from repowise.server.mcp_server.tool_change_risk import _cross_repo_block++PROVIDER_FILE = "packages/types/src/order.ts"+++def _link(consumer_repo: str = "frontend", consumer_file: str = "src/api.ts") -> ContractLink:+ return ContractLink(+ contract_id="code::@acme/types::Order",+ contract_type="code",+ match_type="exact",+ confidence=0.9,+ provider_repo="api",+ provider_file=PROVIDER_FILE,+ provider_symbol="Order",+ provider_service="packages/types",+ consumer_repo=consumer_repo,+ consumer_file=consumer_file,+ consumer_symbol="@acme/types:Order",+ consumer_service=None,+ provider_symbol_id=f"{PROVIDER_FILE}::Order",+ )+++def _report(consumer_repo: str = "frontend") -> BreakingChangeReport:+ return BreakingChangeReport(+ generated_at="2026-08-23T00:00:00+00:00",+ changes=[+ BreakingChange(+ kind="removed_endpoint",+ severity="breaking",+ contract_id="code::@acme/types::Order",+ contract_type="code",+ provider_repo="api",+ provider_file=PROVIDER_FILE,+ provider_symbol="Order",+ provider_symbol_id=f"{PROVIDER_FILE}::Order",+ provider_service="packages/types",+ detail="code::@acme/types::Order was removed",+ impacted_consumers=[+ ImpactedConsumer(+ repo=consumer_repo,+ service=None,+ node_id=consumer_repo,+ file="src/api.ts",+ symbol="@acme/types:Order",+ match_type="exact",+ confidence=0.9,+ )+ ],+ )+ ],+ )+++def _enricher(+ tmp_path: Path,+ links: list[ContractLink],+ report: BreakingChangeReport | None = None,+) -> CrossRepoEnricher:+ contracts = [+ Contract(+ repo="api",+ contract_id="code::@acme/types::Order",+ contract_type="code",+ role="provider",+ file_path=PROVIDER_FILE,+ symbol_name="Order",+ confidence=0.9,+ service="packages/types",+ symbol_id=f"{PROVIDER_FILE}::Order",+ )+ ]+ (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",+ )+ bc_path = None+ if report is not None:+ bc_path = tmp_path / "breaking_changes.json"+ bc_path.write_text(json.dumps(report.to_dict()), encoding="utf-8")+ return CrossRepoEnricher(+ tmp_path / "cross_repo_edges.json",+ contracts_path=tmp_path / "contracts.json",+ breaking_changes_path=bc_path,+ )+++def _block(enricher: CrossRepoEnricher | None, changed: list[str], *, workspace: bool = True):+ prev_registry = _state._registry+ prev_enricher = _state._cross_repo_enricher+ _state._registry = object() if workspace else None+ _state._cross_repo_enricher = enricher+ try:+ return _cross_repo_block("api", changed)+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+++def test_names_the_consumers_of_a_touched_provider_file(tmp_path: Path):+ block = _block(_enricher(tmp_path, [_link()]), [PROVIDER_FILE])+ assert block["consumer_repos"] == ["frontend"]+ assert block["consumers"] == [+ {+ "provider_file": PROVIDER_FILE,+ "repo": "frontend",+ "file": "src/api.ts",+ "contract_id": "code::@acme/types::Order",+ "contract_type": "code",+ "match_type": "exact",+ "provider_symbol_id": f"{PROVIDER_FILE}::Order",+ }+ ]+ assert block["breaking_changes"] == []+++def test_no_report_is_reported_as_silence_not_as_an_all_clear(tmp_path: Path):+ """Nothing has looked, so the block must not say nothing was found."""+ block = _block(_enricher(tmp_path, [_link()]), [PROVIDER_FILE])+ assert block["breaking_changes_available"] is False+ assert block["breaking_changes_as_of"] is None+ assert block["summary"] == (+ "1 consumer link(s) in 1 other repo(s) touch the files this change edits"+ "; no breaking-change report has been built for them."+ )+++def test_a_clean_report_is_reported_as_an_all_clear(tmp_path: Path):+ clean = BreakingChangeReport(generated_at="2026-08-23T00:00:00+00:00")+ block = _block(_enricher(tmp_path, [_link()], clean), [PROVIDER_FILE])+ assert block["breaking_changes_available"] is True+ assert block["summary"].endswith("; the last workspace update found no break in them.")+++def test_an_unstamped_report_is_silence_not_an_all_clear(tmp_path: Path):+ """A file exists but no pass produced it; zero changes prove nothing."""+ never_ran = BreakingChangeReport(generated_at=None)+ block = _block(_enricher(tmp_path, [_link()], never_ran), [PROVIDER_FILE])+ assert block["breaking_changes_available"] is False+ assert block["breaking_changes_as_of"] is None+ assert block["summary"].endswith("; no breaking-change report has been built for them.")+++def test_carries_the_break_attributed_to_that_file(tmp_path: Path):+ """Driven through real detection: a removal leaves no *current* link."""+ from repowise.core.workspace.breaking_change import detect_breaking_changes+ from repowise.core.workspace.contracts import Contract, ContractStore++ previous = ContractStore(+ contracts=[+ Contract(+ repo="api",+ contract_id="code::@acme/types::Order",+ contract_type="code",+ role="provider",+ file_path=PROVIDER_FILE,+ symbol_name="Order",+ confidence=0.9,+ service="packages/types",+ symbol_id=f"{PROVIDER_FILE}::Order",+ )+ ],+ contract_links=[_link()],+ )+ report = detect_breaking_changes(+ previous, ContractStore(), generated_at="2026-08-23T00:00:00+00:00"+ )+ # The contract is gone, so the current store has no link for it.+ block = _block(_enricher(tmp_path, [], report), [PROVIDER_FILE])+ assert len(block["breaking_changes"]) == 1+ entry = block["breaking_changes"][0]+ assert entry["type"] == "code"+ assert entry["kind"] == "removed_endpoint"+ assert entry["impacted_repos"] == ["frontend"]+ assert entry["provider_symbol_id"] == f"{PROVIDER_FILE}::Order"+ assert block["breaking_changes_as_of"] == "2026-08-23T00:00:00+00:00"+ # consumers is empty, but the repo count must still come from the break.+ assert block["consumers"] == []+ assert block["consumer_repos"] == ["frontend"]+ assert block["summary"] == (+ "0 consumer link(s) in 1 other repo(s) touch the files this change edits"+ "; 1 of the changed contracts broke them."+ )+++def test_absent_when_the_commit_touches_no_published_file(tmp_path: Path):+ assert _block(_enricher(tmp_path, [_link()]), ["src/unrelated.ts"]) is None+++def test_absent_for_a_same_repo_consumer(tmp_path: Path):+ """An in-repo consumer is not a cross-repo consequence."""+ enricher = _enricher(tmp_path, [_link(consumer_repo="api")], _report(consumer_repo="api"))+ assert _block(enricher, [PROVIDER_FILE]) is None+++def test_absent_outside_workspace_mode(tmp_path: Path):+ enricher = _enricher(tmp_path, [_link()])+ assert _block(enricher, [PROVIDER_FILE], workspace=False) is None+++def test_absent_without_an_enricher():+ assert _block(None, [PROVIDER_FILE]) is None+++def test_one_row_per_consumer_file_not_per_link(tmp_path: Path):+ """Two links to the same consumer file collapse; two files stay two rows."""+ links = [_link(), _link(), _link(consumer_file="src/other.ts")]+ block = _block(_enricher(tmp_path, links), [PROVIDER_FILE])+ assert [c["file"] for c in block["consumers"]] == ["src/api.ts", "src/other.ts"]+++def test_two_contracts_between_the_same_files_stay_two_rows(tmp_path: Path):+ """Collapsing them would silently drop a contract_id."""+ other = _link()+ other.contract_id = "code::@acme/types::Invoice"+ block = _block(_enricher(tmp_path, [_link(), other]), [PROVIDER_FILE])+ assert [c["contract_id"] for c in block["consumers"]] == [+ "code::@acme/types::Order",+ "code::@acme/types::Invoice",+ ]+++def test_consumer_list_is_capped_and_says_by_how_much(tmp_path: Path):+ from repowise.server.mcp_server.tool_change_risk import _CROSS_REPO_CONSUMER_LIMIT++ over = _CROSS_REPO_CONSUMER_LIMIT + 3+ links = [_link(consumer_file=f"src/api{i}.ts") for i in range(over)]+ block = _block(_enricher(tmp_path, links), [PROVIDER_FILE])+ assert len(block["consumers"]) == _CROSS_REPO_CONSUMER_LIMIT+ assert block["consumers_truncated"] == 3+ assert f"{over} consumer link(s)" in block["summary"]+++def test_breaking_list_is_capped_and_says_by_how_much(tmp_path: Path):+ from repowise.core.workspace.breaking_change import detect_breaking_changes+ from repowise.core.workspace.contracts import Contract, ContractStore+ from repowise.server.mcp_server.tool_change_risk import _CROSS_REPO_BREAKING_LIMIT++ over = _CROSS_REPO_BREAKING_LIMIT + 2+ names = [f"Type{i}" for i in range(over)]+ previous = ContractStore(+ contracts=[+ Contract(+ repo="api",+ contract_id=f"code::@acme/types::{n}",+ contract_type="code",+ role="provider",+ file_path=PROVIDER_FILE,+ symbol_name=n,+ confidence=0.9,+ symbol_id=f"{PROVIDER_FILE}::{n}",+ )+ for n in names+ ],+ contract_links=[+ ContractLink(+ contract_id=f"code::@acme/types::{n}",+ contract_type="code",+ match_type="exact",+ confidence=0.9,+ provider_repo="api",+ provider_file=PROVIDER_FILE,+ provider_symbol=n,+ provider_service=None,+ consumer_repo="frontend",+ consumer_file="src/api.ts",+ consumer_symbol=f"@acme/types:{n}",+ consumer_service=None,+ )+ for n in names+ ],+ )+ report = detect_breaking_changes(previous, ContractStore(), generated_at="t")+ block = _block(_enricher(tmp_path, [], report), [PROVIDER_FILE])+ assert len(block["breaking_changes"]) == _CROSS_REPO_BREAKING_LIMIT+ assert block["breaking_changes_truncated"] == 2+ assert f"{over} of the changed contracts broke them" in block["summary"]+++def test_cross_repo_participates_in_the_response_ceiling(tmp_path: Path):+ """A payload block outside the shed order can never be shed (#1876)."""+ from repowise.server.mcp_server._budget import OmissionCollector, fit_to_budget+ from repowise.server.mcp_server.tool_change_risk import _SHED_ORDER++ assert "cross_repo" in _SHED_ORDER+ # Shed after the run-list, before fix_history's numbers.+ assert _SHED_ORDER.index("impacted_tests") < _SHED_ORDER.index("cross_repo")+ assert _SHED_ORDER.index("cross_repo") < _SHED_ORDER.index("fix_history.files")++ payload = {+ "score": 7.0,+ "fix_history": {"density": 1.0, "files": ["f.py"]},+ "impacted_tests": {"tests_to_run": ["t.py"]},+ "cross_repo": {"consumers": [{"repo": "frontend", "pad": "x" * 400}] * 200},+ }+ collector = OmissionCollector("get_change_risk", repo_root=tmp_path)+ fit_to_budget(payload, _SHED_ORDER, collector)+ assert "cross_repo" not in payload+ assert payload["truncated"] is True+ # The score and its drivers are the answer and survive.+ assert payload["fix_history"]["density"] == 1.0