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): breaking-change guard for cross-repo contracts (#514)
Raghav Chamadiya883fde42e967
diff --git a/docs/CHANGE_RISK.md b/docs/CHANGE_RISK.mdindex dafec1dbe..5da9c2d61 100644--- a/docs/CHANGE_RISK.md+++ b/docs/CHANGE_RISK.md@@ -99,3 +99,15 @@ ranking (one named constant, `BEHAVIORAL_EDGE_WEIGHT`, in`packages/core/src/repowise/core/workspace/blast_radius.py`). See[Cross-Repo Blast Radius](WORKSPACES.md#cross-repo-blast-radius) for the fullmodel.++The directive carries a third cross-repo field, `breaking_changes`, when a+provider contract in the changed repo changed *incompatibly* (a removed route or+field, a type or field-number change, a newly-required field). Where+`will_break_consumers` is topology ("who depends on this repo"),+`breaking_changes` is schema-level truth ("this specific contract changed in a+way that breaks these consumers"), each entry listing the changed contract and+the consumer files it endangers across repos. It is computed by diffing the+current contracts against the previously-indexed set during+`repowise update --workspace`; non-breaking changes (an added optional field, a+new endpoint) never appear. See+[Breaking-Change Guard](WORKSPACES.md#breaking-change-guard) for the full model.diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex e2977ba36..7c5c1d6f3 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -216,6 +216,7 @@ When `changed_files` is passed, the response leads with a `directive` block. In- `will_break_consumers` — services in *other* repos that depend on this one (structural impact), each with `repo`, `service`, `distance`, `score`, and the edge kinds carrying the impact.- `missing_cross_repo_cochanges` — services in other repos that historically co-change with this one but aren't in the diff.+- `breaking_changes` — provider contracts in this repo that changed *incompatibly* since the last index (a removed route or field, a type or field-number change, a newly-required field), each with the changed `contract_id`, the change `kind`/`severity`, and the `impacted_consumers` (repo, service, file) it endangers across repos. Schema-level truth, distinct from the topology-level `will_break_consumers`; non-breaking changes (added optional field, new endpoint) never appear. See [Breaking-Change Guard](WORKSPACES.md#breaking-change-guard).**When to use:** Before modifying files — especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.@@ -355,6 +356,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:- **API contract links** (HTTP, gRPC, topics) between repos- **Package dependencies** between repos- **Cross-repo blast radius** via the workspace-only `get_blast_radius` tool, and a cross-repo `directive` in `get_risk` PR-mode+- **Breaking-change guard** — incompatible provider-contract changes and the consumers they endanger, in the `get_risk` PR-mode `breaking_changes` directive---diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.mdindex b04db279a..5fb35ee0f 100644--- a/docs/WORKSPACES.md+++ b/docs/WORKSPACES.md@@ -303,6 +303,32 @@ Use it three ways:---+## Breaking-Change Guard++Where blast radius answers *what could be affected*, the breaking-change guard answers a sharper question: **did a provider change in a way that actually breaks its consumers?** On every `repowise update --workspace`, the freshly-extracted contracts are diffed against the previously-indexed set and each incompatible provider change is reported with the exact consumer files that call it.++Detected change kinds (a registry — adding a kind is one new rule, never an `if/elif`):++| Kind | Severity | Fires when |+|------|----------|-----------|+| `removed_endpoint` | breaking | A provider route / gRPC method / topic that existed before is gone |+| `removed_field` | breaking (response) / warning (request) | A request or response field disappeared |+| `field_type_changed` | breaking | A field's type changed (e.g. `string → int64`) |+| `field_number_changed` | breaking | A proto field's wire number changed |+| `field_required` | breaking | A field became required, or a new required field was added |++**Non-breaking changes never flag** — an added *optional* field, a widened set, or a brand-new endpoint produces no record. Field-level diffs need a contract *schema*; today gRPC carries one (proto message fields, recovered by the existing proto parser), and HTTP gains field-level checks when an OpenAPI spec is present. Route-level removal is detected for every transport from the contract id alone.++Impacted consumers are resolved from the matched contract links — the same provider↔consumer evidence the [system graph](#system-graph)'s edges are built from — so impact is endpoint-precise (the consumer file that calls the changed contract) and direct (the first reachability hop, which is exactly what a contract break endangers; transitive ripple stays the job of blast radius).++Use it three ways:++- **REST** — `GET /api/workspace/breaking-changes` returns the report from the most recent update (filterable by `repo` or `severity`). Each change carries its provider, detail, and impacted consumers with both code sides.+- **MCP** — the `get_risk` PR-mode directive gains a `breaking_changes` block listing the provider contracts that changed incompatibly in the diff's repo and the consumers they endanger, across repos.+- **System Map** — toggle **Breaking changes** above the map: changed providers are badged with their breaking count, the consumers they endanger are badged *at risk*, and the seams between them are highlighted (additive overlay — the map stays whole). A side panel lists each change with both the provider and consumer files.++---+## MCP IntegrationWorkspace init automatically registers MCP servers with Claude Desktop and Claude Code. The MCP server is workspace-aware:@@ -324,6 +350,7 @@ my-workspace/cross_repo_edges.json # Co-change pairs and package depscontracts.json # Extracted API contracts and linkssystem_graph.json # Service-granular system graph + diagnostics+ breaking_changes.json # Breaking provider changes vs the last index.claude/CLAUDE.md # Workspace-level CLAUDE.md for AI editorsbackend/diff --git a/packages/core/src/repowise/core/workspace/breaking_change.py b/packages/core/src/repowise/core/workspace/breaking_change.pynew file mode 100644index 000000000..64782e9da--- /dev/null+++ b/packages/core/src/repowise/core/workspace/breaking_change.py@@ -0,0 +1,609 @@+"""Breaking-change guard — diff a workspace's provider contracts across updates.++When ``repowise update --workspace`` re-extracts contracts, this module diffs the+freshly-extracted set against the *previously persisted* one and reports the+provider changes that break consumers across repos: a removed endpoint, a removed+or retyped request/response field, a reused field number, a newly-required field.+Each :class:`BreakingChange` resolves its impacted consumers from the matched+contract links — the same provider→consumer evidence the system graph's edges are+built from — so a break is reported with the exact consumer files that call it.++**Honest non-goals.** A *non*-breaking change (an added optional field, a widened+type, a new endpoint) produces no record. Impact is intentionally *direct*: a+contract break endangers the consumers of that contract, which is exactly the+first hop the cross-repo blast radius would surface — so we read it straight from+the links rather than re-walking the graph. Transitive ripple stays the job of+``get_blast_radius`` / the map overlay.++**Extensibility (the D10 / PR #505 bar).** Diff rules live in two registries —+contract-level (:data:`_CONTRACT_RULES`) and field-level (:data:`_FIELD_RULES`).+Adding a new breaking-change kind is a new ``@contract_rule`` / ``@field_rule``+function, never an ``if/elif`` in the engine. The engine only walks providers,+dispatches to the registries, and attaches impact.++Pure and I/O-free except the thin ``save`` / ``load`` helpers and the+``run_breaking_change_detection`` orchestrator at the bottom.+"""++from __future__ import annotations++import json+import logging+from collections.abc import Callable, Iterable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from repowise.core.workspace.config import WORKSPACE_DATA_DIR, ensure_workspace_data_dir+from repowise.core.workspace.contract_schema import ContractSchema, SchemaField+from repowise.core.workspace.contracts import (+ Contract,+ ContractLink,+ ContractStore,+ normalize_contract_id,+)++_log = logging.getLogger("repowise.workspace.breaking_change")++# ---------------------------------------------------------------------------+# Constants (single source of truth)+# ---------------------------------------------------------------------------++BREAKING_CHANGES_FILENAME = "breaking_changes.json"++#: Severity levels. ``breaking`` = wire/contract-incompatible (consumers break);+#: ``warning`` = source-compatibility risk (e.g. a removed request field a proto3+#: server simply ignores) that still merits a look.+SEVERITY_BREAKING = "breaking"+SEVERITY_WARNING = "warning"+++# ---------------------------------------------------------------------------+# Data models+# ---------------------------------------------------------------------------+++def _node_id(repo: str, service: str | None) -> str:+ """System-graph node id for a (repo, service) pair — mirrors system_graph."""+ return repo if not service else f"{repo}::{service}"+++@dataclass+class ImpactedConsumer:+ """A consumer endangered by a provider's breaking change.++ Resolved from the matched contract link, so ``file``/``symbol`` point at the+ exact code that calls the changed contract. ``node_id`` is the system-graph+ node (for map badging); ``match_type`` carries how confidently the link was+ matched (an ``exact`` consumer is more certainly broken than a ``candidate``).+ """++ repo: str+ service: str | None+ node_id: str+ file: str+ symbol: str+ match_type: str+ confidence: float++ def to_dict(self) -> dict[str, Any]:+ return {+ "repo": self.repo,+ "service": self.service,+ "node_id": self.node_id,+ "file": self.file,+ "symbol": self.symbol,+ "match_type": self.match_type,+ "confidence": self.confidence,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> ImpactedConsumer:+ return cls(+ repo=data.get("repo", ""),+ service=data.get("service"),+ node_id=data.get("node_id", ""),+ file=data.get("file", ""),+ symbol=data.get("symbol", ""),+ match_type=data.get("match_type", "exact"),+ confidence=data.get("confidence", 0.0),+ )+++@dataclass+class BreakingChange:+ """One incompatible provider change and the consumers it endangers."""++ kind: str # registry key — removed_endpoint | removed_field | ...+ severity: str # SEVERITY_BREAKING | SEVERITY_WARNING+ contract_id: str+ contract_type: str # http | grpc | topic+ provider_repo: str+ provider_file: str+ provider_symbol: str+ provider_service: str | None+ detail: str # human-readable one-liner+ field_name: str | None = None+ old_value: str | None = None+ new_value: str | None = None+ impacted_consumers: list[ImpactedConsumer] = field(default_factory=list)++ @property+ def provider_node_id(self) -> str:+ return _node_id(self.provider_repo, self.provider_service)++ def to_dict(self) -> dict[str, Any]:+ d: dict[str, Any] = {+ "kind": self.kind,+ "severity": self.severity,+ "contract_id": self.contract_id,+ "contract_type": self.contract_type,+ "provider_repo": self.provider_repo,+ "provider_file": self.provider_file,+ "provider_symbol": self.provider_symbol,+ "provider_service": self.provider_service,+ "provider_node_id": self.provider_node_id,+ "detail": self.detail,+ "impacted_consumers": [c.to_dict() for c in self.impacted_consumers],+ }+ if self.field_name is not None:+ d["field_name"] = self.field_name+ if self.old_value is not None:+ d["old_value"] = self.old_value+ if self.new_value is not None:+ d["new_value"] = self.new_value+ return d++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> BreakingChange:+ return cls(+ kind=data["kind"],+ severity=data.get("severity", SEVERITY_BREAKING),+ contract_id=data.get("contract_id", ""),+ contract_type=data.get("contract_type", ""),+ provider_repo=data.get("provider_repo", ""),+ provider_file=data.get("provider_file", ""),+ provider_symbol=data.get("provider_symbol", ""),+ provider_service=data.get("provider_service"),+ detail=data.get("detail", ""),+ field_name=data.get("field_name"),+ old_value=data.get("old_value"),+ new_value=data.get("new_value"),+ impacted_consumers=[+ ImpactedConsumer.from_dict(c) for c in data.get("impacted_consumers", [])+ ],+ )+++@dataclass+class BreakingChangeReport:+ """The full set of breaking changes from one workspace update + rollups."""++ version: int = 1+ generated_at: str = ""+ changes: list[BreakingChange] = field(default_factory=list)++ @property+ def has_changes(self) -> bool:+ return bool(self.changes)++ @property+ def breaking_count(self) -> int:+ return sum(1 for c in self.changes if c.severity == SEVERITY_BREAKING)++ @property+ def warning_count(self) -> int:+ return sum(1 for c in self.changes if c.severity == SEVERITY_WARNING)++ @property+ def impacted_repos(self) -> list[str]:+ repos: set[str] = set()+ for c in self.changes:+ for ic in c.impacted_consumers:+ repos.add(ic.repo)+ return sorted(repos)++ @property+ def impacted_services(self) -> list[str]:+ services: set[str] = set()+ for c in self.changes:+ for ic in c.impacted_consumers:+ services.add(ic.node_id)+ return sorted(services)++ @property+ def total_impacted_consumers(self) -> int:+ return sum(len(c.impacted_consumers) for c in self.changes)++ def to_dict(self) -> dict[str, Any]:+ return {+ "version": self.version,+ "generated_at": self.generated_at,+ "changes": [c.to_dict() for c in self.changes],+ "total": len(self.changes),+ "breaking_count": self.breaking_count,+ "warning_count": self.warning_count,+ "impacted_repos": self.impacted_repos,+ "impacted_services": self.impacted_services,+ "total_impacted_consumers": self.total_impacted_consumers,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> BreakingChangeReport:+ return cls(+ version=data.get("version", 1),+ generated_at=data.get("generated_at", ""),+ changes=[BreakingChange.from_dict(c) for c in data.get("changes", [])],+ )+++# ---------------------------------------------------------------------------+# Rule registries (plugin shape — add a kind = add a decorated function)+# ---------------------------------------------------------------------------+++@dataclass+class _RawChange:+ """A rule's verdict before provider/consumer context is attached."""++ kind: str+ severity: str+ detail: str+ field_name: str | None = None+ old_value: str | None = None+ new_value: str | None = None+++#: Contract-level rule: sees the previous and current provider contract for one+#: normalized contract id (either may be ``None`` for added/removed endpoints).+ContractRule = Callable[["Contract | None", "Contract | None"], Iterable[_RawChange]]++#: Field-level rule: sees one field's previous + current state on a given side.+FieldRule = Callable[["_FieldDiff"], "_RawChange | None"]++_CONTRACT_RULES: list[ContractRule] = []+_FIELD_RULES: list[FieldRule] = []+++def contract_rule(fn: ContractRule) -> ContractRule:+ """Register a contract-level diff rule."""+ _CONTRACT_RULES.append(fn)+ return fn+++def field_rule(fn: FieldRule) -> FieldRule:+ """Register a field-level diff rule."""+ _FIELD_RULES.append(fn)+ return fn+++@dataclass+class _FieldDiff:+ """One field's previous/current state on a request or response side."""++ side: str # "request" | "response"+ prev: SchemaField | None+ curr: SchemaField | None+++# -- contract-level rules ---------------------------------------------------+++@contract_rule+def _removed_endpoint(prev: Contract | None, curr: Contract | None) -> list[_RawChange]:+ """A provider contract that existed before and is gone now.++ Covers a removed route/method (HTTP), a removed ``service/method`` (gRPC),+ and a removed topic — the contract id encodes all three, so a vanished id is+ a removed surface regardless of transport.+ """+ if prev is not None and curr is None:+ return [+ _RawChange(+ kind="removed_endpoint",+ severity=SEVERITY_BREAKING,+ detail=f"{prev.contract_id} was removed",+ )+ ]+ return []+++# -- field-level rules ------------------------------------------------------+++@field_rule+def _removed_field(diff: _FieldDiff) -> _RawChange | None:+ """A field present before and gone now.++ A removed *response* field breaks consumers that read it; a removed *request*+ field is a source-compat warning (a server simply stops reading it).+ """+ if diff.prev is not None and diff.curr is None:+ severity = SEVERITY_BREAKING if diff.side == "response" else SEVERITY_WARNING+ return _RawChange(+ kind="removed_field",+ severity=severity,+ detail=f"{diff.side} field '{diff.prev.name}' was removed",+ field_name=diff.prev.name,+ old_value=diff.prev.type,+ )+ return None+++@field_rule+def _field_type_changed(diff: _FieldDiff) -> _RawChange | None:+ """A field whose type changed — wire-incompatible on either side."""+ if diff.prev is not None and diff.curr is not None and diff.prev.type != diff.curr.type:+ return _RawChange(+ kind="field_type_changed",+ severity=SEVERITY_BREAKING,+ detail=(+ f"{diff.side} field '{diff.curr.name}' type changed "+ f"{diff.prev.type} → {diff.curr.type}"+ ),+ field_name=diff.curr.name,+ old_value=diff.prev.type,+ new_value=diff.curr.type,+ )+ return None+++@field_rule+def _field_number_changed(diff: _FieldDiff) -> _RawChange | None:+ """A field whose wire number (proto tag) changed — silently corrupts data."""+ if (+ diff.prev is not None+ and diff.curr is not None+ and diff.prev.number is not None+ and diff.curr.number is not None+ and diff.prev.number != diff.curr.number+ ):+ return _RawChange(+ kind="field_number_changed",+ severity=SEVERITY_BREAKING,+ detail=(+ f"{diff.side} field '{diff.curr.name}' number changed "+ f"{diff.prev.number} → {diff.curr.number}"+ ),+ field_name=diff.curr.name,+ old_value=str(diff.prev.number),+ new_value=str(diff.curr.number),+ )+ return None+++@field_rule+def _field_required_tightened(diff: _FieldDiff) -> _RawChange | None:+ """A field that newly requires a value — an added or made-required field.++ An optional→required change, or a brand-new required field, forces callers to+ supply something they previously omitted. An added *optional* field never+ fires here (the non-breaking case the guard must stay quiet about).+ """+ if (+ diff.curr is not None+ and diff.curr.required+ and (diff.prev is None or not diff.prev.required)+ ):+ action = "added as required" if diff.prev is None else "became required"+ return _RawChange(+ kind="field_required",+ severity=SEVERITY_BREAKING,+ detail=f"{diff.side} field '{diff.curr.name}' {action}",+ field_name=diff.curr.name,+ new_value=diff.curr.type,+ )+ return None+++# ---------------------------------------------------------------------------+# Schema diffing (pure)+# ---------------------------------------------------------------------------+++def _diff_field_side(+ side: str, prev: list[SchemaField], curr: list[SchemaField]+) -> list[_RawChange]:+ """Run every field rule over the union of field names on one side."""+ prev_by_name = {f.name: f for f in prev}+ curr_by_name = {f.name: f for f in curr}+ raws: list[_RawChange] = []+ for name in list(prev_by_name) + [n for n in curr_by_name if n not in prev_by_name]:+ diff = _FieldDiff(side=side, prev=prev_by_name.get(name), curr=curr_by_name.get(name))+ for rule in _FIELD_RULES:+ raw = rule(diff)+ if raw is not None:+ raws.append(raw)+ return raws+++def _diff_schemas(prev: ContractSchema, curr: ContractSchema) -> list[_RawChange]:+ """Diff request and response field sets of two schemas."""+ return _diff_field_side("request", prev.request_fields, curr.request_fields) + _diff_field_side(+ "response", prev.response_fields, curr.response_fields+ )+++# ---------------------------------------------------------------------------+# Impact resolution (reuses the contract links the graph edges are built from)+# ---------------------------------------------------------------------------+++def _index_providers(contracts: list[Contract]) -> dict[str, Contract]:+ """Map normalized contract id → provider contract (last write wins)."""+ out: dict[str, Contract] = {}+ for c in contracts:+ if c.role == "provider":+ out[normalize_contract_id(c.contract_id)] = c+ return out+++def _index_links(links: list[ContractLink]) -> dict[str, list[ContractLink]]:+ """Map normalized contract id → matched links (provider↔consumer)."""+ out: dict[str, list[ContractLink]] = {}+ for lk in links:+ out.setdefault(normalize_contract_id(lk.contract_id), []).append(lk)+ return out+++def _resolve_impacted(+ norm_id: str,+ current_links: dict[str, list[ContractLink]],+ previous_links: dict[str, list[ContractLink]],+) -> list[ImpactedConsumer]:+ """Direct consumers of a changed contract, from the matched links.++ Prefers the current links; for a *removed* endpoint there is no current+ provider (hence no current link), so we fall back to the previous links,+ which still record who used to call it. De-duplicated by consumer node+file.+ """+ links = current_links.get(norm_id) or previous_links.get(norm_id) or []+ seen: set[tuple[str, str]] = set()+ consumers: list[ImpactedConsumer] = []+ for lk in links:+ node_id = _node_id(lk.consumer_repo, lk.consumer_service)+ key = (node_id, lk.consumer_file)+ if key in seen:+ continue+ seen.add(key)+ consumers.append(+ ImpactedConsumer(+ repo=lk.consumer_repo,+ service=lk.consumer_service,+ node_id=node_id,+ file=lk.consumer_file,+ symbol=lk.consumer_symbol,+ match_type=lk.match_type,+ confidence=lk.confidence,+ )+ )+ consumers.sort(key=lambda c: (-c.confidence, c.node_id, c.file))+ return consumers+++# ---------------------------------------------------------------------------+# Engine (pure)+# ---------------------------------------------------------------------------+++def detect_breaking_changes(+ previous: ContractStore,+ current: ContractStore,+ *,+ version: int = 1,+ generated_at: str = "",+) -> BreakingChangeReport:+ """Diff *previous* vs *current* provider contracts into a report (pure).++ Walks every provider contract id seen in either store, dispatches the+ contract-level and (when both sides carry a schema) field-level rules, and+ attaches each change's direct cross-repo consumers from the matched links.+ """+ prev_providers = _index_providers(previous.contracts)+ curr_providers = _index_providers(current.contracts)+ current_links = _index_links(current.contract_links)+ previous_links = _index_links(previous.contract_links)++ changes: list[BreakingChange] = []+ for norm_id in sorted(set(prev_providers) | set(curr_providers)):+ prev_c = prev_providers.get(norm_id)+ curr_c = curr_providers.get(norm_id)++ raws: list[_RawChange] = []+ for rule in _CONTRACT_RULES:+ raws.extend(rule(prev_c, curr_c))+ if prev_c is not None and curr_c is not None:+ prev_schema = prev_c.schema+ curr_schema = curr_c.schema+ if prev_schema is not None and curr_schema is not None:+ raws.extend(_diff_schemas(prev_schema, curr_schema))++ if not raws:+ continue++ rep = prev_c or curr_c+ assert rep is not None # guaranteed: norm_id came from one of the maps+ impacted = _resolve_impacted(norm_id, current_links, previous_links)+ for raw in raws:+ changes.append(+ BreakingChange(+ kind=raw.kind,+ severity=raw.severity,+ contract_id=rep.contract_id,+ contract_type=rep.contract_type,+ provider_repo=rep.repo,+ provider_file=rep.file_path,+ provider_symbol=rep.symbol_name,+ provider_service=rep.service,+ detail=raw.detail,+ field_name=raw.field_name,+ old_value=raw.old_value,+ new_value=raw.new_value,+ impacted_consumers=impacted,+ )+ )++ # Stable order: breaking before warning, then by contract id + kind.+ changes.sort(key=lambda c: (c.severity != SEVERITY_BREAKING, c.contract_id, c.kind))+ return BreakingChangeReport(version=version, generated_at=generated_at, changes=changes)+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------+++def save_breaking_change_report(report: BreakingChangeReport, workspace_root: Path) -> Path:+ """Write the report to ``.repowise-workspace/breaking_changes.json``."""+ data_dir = ensure_workspace_data_dir(workspace_root)+ out_path = data_dir / BREAKING_CHANGES_FILENAME+ out_path.write_text(+ json.dumps(report.to_dict(), indent=2, ensure_ascii=False),+ encoding="utf-8",+ )+ return out_path+++def load_breaking_change_report(workspace_root: Path) -> BreakingChangeReport | None:+ """Load the report, or ``None`` if missing/unparseable."""+ path = workspace_root / WORKSPACE_DATA_DIR / BREAKING_CHANGES_FILENAME+ if not path.is_file():+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ return BreakingChangeReport.from_dict(data)+ except Exception:+ _log.warning("Failed to load breaking-change report from %s", path, exc_info=True)+ return None+++# ---------------------------------------------------------------------------+# Orchestrator+# ---------------------------------------------------------------------------+++def run_breaking_change_detection(+ workspace_root: Path,+ previous: ContractStore,+ current: ContractStore,+ *,+ generated_at: str = "",+) -> BreakingChangeReport:+ """Diff the previous vs current contract stores and persist the report.++ Called from ``run_cross_repo_hooks`` with the contract store as it was on+ disk *before* this update overwrote it (``previous``) and the freshly+ extracted store (``current``).+ """+ report = detect_breaking_changes(previous, current, generated_at=generated_at)+ out_path = save_breaking_change_report(report, workspace_root)+ _log.info(+ "Breaking-change detection complete: %d change(s) (%d breaking) impacting "+ "%d consumer(s) across %d repo(s) → %s",+ len(report.changes),+ report.breaking_count,+ report.total_impacted_consumers,+ len(report.impacted_repos),+ out_path,+ )+ return reportdiff --git a/packages/core/src/repowise/core/workspace/contract_schema.py b/packages/core/src/repowise/core/workspace/contract_schema.pynew file mode 100644index 000000000..670e5d989--- /dev/null+++ b/packages/core/src/repowise/core/workspace/contract_schema.py@@ -0,0 +1,88 @@+"""Schema-level shape for a contract — the request/response field structure.++A :class:`Contract` carries the *identity* of an API surface (its method + path,+its ``service/method``, its topic). This module adds the optional *shape*: the+fields a request or response carries, when a parser can recover them. Only the+gRPC ``.proto`` dialect populates this today (message fields, reusing the+existing proto parser); HTTP gains a schema when an OpenAPI spec is present — a+new :class:`ContractSchema` ``source`` slots in without touching the consumers+here or the breaking-change rules that read it.++Kept deliberately transport-neutral so one diff engine+(:mod:`repowise.core.workspace.breaking_change`) can reason over every schema the+same way: a field has a ``name``, a ``type``, whether it is ``required``, and an+optional wire ``number`` (proto) for field-number-reuse detection.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any+++@dataclass(frozen=True)+class SchemaField:+ """One field in a request or response shape.++ ``number`` is the proto field tag (``None`` for transports without one).+ ``repeated`` carries proto list-ness; it is informational for diffing.+ """++ name: str+ type: str+ required: bool = False+ number: int | None = None+ repeated: bool = False++ def to_dict(self) -> dict[str, Any]:+ d: dict[str, Any] = {"name": self.name, "type": self.type}+ if self.required:+ d["required"] = True+ if self.number is not None:+ d["number"] = self.number+ if self.repeated:+ d["repeated"] = True+ return d++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> SchemaField:+ return cls(+ name=data["name"],+ type=data.get("type", ""),+ required=bool(data.get("required", False)),+ number=data.get("number"),+ repeated=bool(data.get("repeated", False)),+ )+++@dataclass+class ContractSchema:+ """The structured request/response shape of a contract, when recoverable.++ ``source`` records which parser produced it (``"proto"`` / ``"openapi"``) so+ a diff never compares shapes captured by two different extraction strategies+ as if they were the same fidelity.+ """++ source: str+ request_fields: list[SchemaField] = field(default_factory=list)+ response_fields: list[SchemaField] = field(default_factory=list)++ @property+ def is_empty(self) -> bool:+ return not self.request_fields and not self.response_fields++ def to_dict(self) -> dict[str, Any]:+ return {+ "source": self.source,+ "request_fields": [f.to_dict() for f in self.request_fields],+ "response_fields": [f.to_dict() for f in self.response_fields],+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> ContractSchema:+ return cls(+ source=data.get("source", ""),+ request_fields=[SchemaField.from_dict(f) for f in data.get("request_fields", [])],+ response_fields=[SchemaField.from_dict(f) for f in data.get("response_fields", [])],+ )diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex e756f4cad..2375a1f62 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -24,6 +24,7 @@ from repowise.core.workspace.config import (WorkspaceConfig,ensure_workspace_data_dir,)+from repowise.core.workspace.contract_schema import ContractSchema_log = logging.getLogger("repowise.workspace.contracts")@@ -52,6 +53,9 @@ class Contract:confidence: float # 0.7–0.9 based on extraction strategyservice: str | None = None # service boundary path (monorepo)meta: dict = field(default_factory=dict)+ # Optional request/response shape — populated by dialects that can recover+ # it (proto message fields today). Drives schema-level breaking-change diffs.+ schema: ContractSchema | None = Nonedef to_dict(self) -> dict[str, Any]:d = asdict(self)@@ -59,10 +63,15 @@ class Contract:del d["service"]if not d["meta"]:del d["meta"]+ if self.schema is None or self.schema.is_empty:+ d.pop("schema", None)+ else:+ d["schema"] = self.schema.to_dict()return d@classmethoddef from_dict(cls, data: dict[str, Any]) -> Contract:+ raw_schema = data.get("schema")return cls(repo=data["repo"],contract_id=data["contract_id"],@@ -73,6 +82,7 @@ class Contract:confidence=data["confidence"],service=data.get("service"),meta=data.get("meta", {}),+ schema=ContractSchema.from_dict(raw_schema) if raw_schema else None,)@@ -142,9 +152,7 @@ class ContractStore:version=data.get("version", 1),generated_at=data.get("generated_at", ""),contracts=[Contract.from_dict(c) for c in data.get("contracts", [])],- contract_links=[- ContractLink.from_dict(lk) for lk in data.get("contract_links", [])- ],+ contract_links=[ContractLink.from_dict(lk) for lk in data.get("contract_links", [])],)@@ -213,10 +221,29 @@ _CANDIDATE_CONFIDENCE_FACTOR = 0.6# can't spuriously link to a provider route that shares a suffix. ``.json`` and# ``.xml`` are intentionally absent — real APIs serve those._STATIC_ASSET_SUFFIXES = (- ".js", ".mjs", ".cjs", ".css", ".map", ".html", ".htm",- ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp", ".avif",- ".woff", ".woff2", ".ttf", ".eot", ".otf",- ".pdf", ".txt", ".wasm",+ ".js",+ ".mjs",+ ".cjs",+ ".css",+ ".map",+ ".html",+ ".htm",+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".svg",+ ".ico",+ ".webp",+ ".avif",+ ".woff",+ ".woff2",+ ".ttf",+ ".eot",+ ".otf",+ ".pdf",+ ".txt",+ ".wasm",)@@ -232,10 +259,9 @@ def _find_matching_keys(# HTTP wildcard: consumer http::*::/path matches any method on that pathif normalized.startswith("http::*::"):- path_suffix = normalized[len("http::*::"):]+ path_suffix = normalized[len("http::*::") :]return [- k for k in provider_index- if k.startswith("http::") and k.endswith(f"::{path_suffix}")+ k for k in provider_index if k.startswith("http::") and k.endswith(f"::{path_suffix}")]# HTTP: check for wildcard providers (http::*::/path from Go HandleFunc)@@ -291,11 +317,7 @@ def _is_static_asset_path(path: str) -> bool:def _methods_compatible(consumer_method: str, provider_method: str) -> bool:"""HTTP methods match if equal or either side is the ``*`` wildcard."""- return (- consumer_method == provider_method- or consumer_method == "*"- or provider_method == "*"- )+ return consumer_method == provider_method or consumer_method == "*" or provider_method == "*"def _same_repo_same_service(provider: Contract, consumer: Contract) -> bool:@@ -450,35 +472,39 @@ def _build_manual_links(result: list[ContractLink] = []for ml in manual_links:if ml.from_role == "consumer":- result.append(ContractLink(- contract_id=ml.contract_id,- contract_type=ml.contract_type,- match_type="manual",- confidence=1.0,- provider_repo=ml.to_repo,- provider_file="",- provider_symbol="",- provider_service=None,- consumer_repo=ml.from_repo,- consumer_file="",- consumer_symbol="",- consumer_service=None,- ))+ result.append(+ ContractLink(+ contract_id=ml.contract_id,+ contract_type=ml.contract_type,+ match_type="manual",+ confidence=1.0,+ provider_repo=ml.to_repo,+ provider_file="",+ provider_symbol="",+ provider_service=None,+ consumer_repo=ml.from_repo,+ consumer_file="",+ consumer_symbol="",+ consumer_service=None,+ )+ )else:- result.append(ContractLink(- contract_id=ml.contract_id,- contract_type=ml.contract_type,- match_type="manual",- confidence=1.0,- provider_repo=ml.from_repo,- provider_file="",- provider_symbol="",- provider_service=None,- consumer_repo=ml.to_repo,- consumer_file="",- consumer_symbol="",- consumer_service=None,- ))+ result.append(+ ContractLink(+ contract_id=ml.contract_id,+ contract_type=ml.contract_type,+ match_type="manual",+ confidence=1.0,+ provider_repo=ml.from_repo,+ provider_file="",+ provider_symbol="",+ provider_service=None,+ consumer_repo=ml.to_repo,+ consumer_file="",+ consumer_symbol="",+ consumer_service=None,+ )+ )return result@@ -581,9 +607,9 @@ async def run_contract_extraction(return contracts- results = await asyncio.gather(*[- _extract_one_repo(alias, path) for alias, path in repo_paths.items()- ])+ results = await asyncio.gather(+ *[_extract_one_repo(alias, path) for alias, path in repo_paths.items()]+ )all_contracts: list[Contract] = []for repo_contracts in results:all_contracts.extend(repo_contracts)diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py b/packages/core/src/repowise/core/workspace/extractors/grpc/proto.pyindex d835ff803..1918dfc60 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py@@ -3,12 +3,21 @@Parses ``.proto`` service/rpc declarations into provider contracts. Uses abrace-depth counter so braces inside comments, options, or message bodies don'tbreak service-block extraction.++Beyond service/method identity, this dialect also recovers the **message field+shape** of each rpc's request and response (name, type, field number, label) and+attaches it as a :class:`~repowise.core.workspace.contract_schema.ContractSchema`+so the breaking-change guard can diff field-level changes (a removed or retyped+field, a reused field number). Message parsing reuses the same brace-depth walk+as service parsing — no new parser."""from __future__ import annotationsimport re-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, NamedTuple++from repowise.core.workspace.contract_schema import ContractSchema, SchemaFieldfrom ..langs import PROTOfrom .dialect import make_grpc_contract@@ -19,17 +28,37 @@ if TYPE_CHECKING:from ..base import ScanContext-def _extract_service_blocks(content: str) -> list[tuple[str, str]]:- """Extract ``(service_name, body)`` pairs from a ``.proto`` file.+class ProtoMethod(NamedTuple):+ """One ``rpc`` declaration: method name + request/response message types."""++ name: str+ request_type: str+ response_type: str- Uses brace-depth counting so nested braces in comments, options, or- message bodies don't break parsing.++def _strip_comments(content: str) -> str:+ """Remove ``//`` and ``/* */`` comments so field/rpc regexes stay simple.++ Block-comment removal preserves newlines so brace-depth walking over the+ original is unaffected; this stripped copy is only used for line-oriented+ field and rpc parsing.+ """+ content = re.sub(r"/\*.*?\*/", "", content, flags=re.DOTALL)+ content = re.sub(r"//[^\n]*", "", content)+ return content+++def _extract_blocks(content: str, keyword: str) -> list[tuple[str, str]]:+ """Extract ``(name, body)`` pairs for every ``<keyword> Name { ... }`` block.++ Uses brace-depth counting so nested braces in comments, options, or nested+ message bodies don't break parsing. Shared by service and message parsing."""results: list[tuple[str, str]] = []- header_re = re.compile(r"service\s+(\w+)\s*\{")+ header_re = re.compile(rf"\b{keyword}\s+(\w+)\s*\{{")for header_match in header_re.finditer(content):- service_name = header_match.group(1)+ name = header_match.group(1)body_start = header_match.end()depth = 1pos = body_start@@ -37,7 +66,6 @@ def _extract_service_blocks(content: str) -> list[tuple[str, str]]:in_block_comment = Falsewhile pos < len(content) and depth > 0:ch = content[pos]- # Track comment state to ignore braces inside commentsif in_line_comment:if ch == "\n":in_line_comment = False@@ -57,30 +85,129 @@ def _extract_service_blocks(content: str) -> list[tuple[str, str]]:depth -= 1pos += 1if depth != 0:- continue # incomplete/malformed service block+ continue # incomplete/malformed blockbody = content[body_start : pos - 1]- results.append((service_name, body))+ results.append((name, body))return results-def _parse_proto_file(content: str) -> tuple[str, list[tuple[str, str, list[str]]]]:- """Parse a proto file, returning ``(package, services)``.-- Each service is ``(service_name, full_service_path, [method_names])``.+def _extract_service_blocks(content: str) -> list[tuple[str, str]]:+ """Extract ``(service_name, body)`` pairs from a ``.proto`` file."""+ return _extract_blocks(content, "service")+++#: A scalar/typed field: ``[label] <type> <name> = <number>;``. The type allows+#: dotted/qualified names (``foo.Bar``). Not line-anchored — multiple fields can+#: share a line. ``map<...>`` fields are matched separately so the ``<...>``+#: doesn't confuse the type capture.+_FIELD_RE = re.compile(+ r"(?:(repeated|optional|required)\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)\s*;",+)+_MAP_FIELD_RE = re.compile(+ r"map\s*<[^>]+>\s+(\w+)\s*=\s*(\d+)\s*;",+)++#: Innermost nested ``message``/``enum`` block — removed so a parent message's+#: field scan never absorbs a nested type's fields. ``oneof`` is unwrapped (its+#: members ARE the message's fields) by :data:`_ONEOF_RE`.+_NESTED_BLOCK_RE = re.compile(r"\b(?:message|enum)\s+\w+\s*\{[^{}]*\}")+_ONEOF_RE = re.compile(r"\boneof\s+\w+\s*\{([^{}]*)\}")+++def _flatten_message_body(body: str) -> str:+ """Strip comments, drop nested message/enum blocks, unwrap oneof groups.++ Leaves a flat body whose remaining ``;``-terminated statements are exactly+ the message's own fields (including oneof members), so the field regex never+ misattributes a nested type's fields or trips over block braces."""- pkg_match = re.search(r"^\s*package\s+([\w.]+)\s*;", content, re.MULTILINE)+ body = _strip_comments(body)+ prev = ""+ while prev != body:+ prev = body+ body = _NESTED_BLOCK_RE.sub(" ", body)+ body = _ONEOF_RE.sub(lambda m: f" {m.group(1)} ", body)+ return body+++def _parse_message_fields(body: str) -> list[SchemaField]:+ """Parse the field declarations of a message body (excluding nested types)."""+ body = _flatten_message_body(body)+ fields: list[SchemaField] = []+ seen: set[str] = set()+ for m in _FIELD_RE.finditer(body):+ label, ftype, name, number = m.group(1), m.group(2), m.group(3), m.group(4)+ if name in seen:+ continue+ seen.add(name)+ fields.append(+ SchemaField(+ name=name,+ type=ftype,+ required=label == "required",+ number=int(number),+ repeated=label == "repeated",+ )+ )+ for m in _MAP_FIELD_RE.finditer(body):+ name, number = m.group(1), m.group(2)+ if name in seen:+ continue+ seen.add(name)+ fields.append(SchemaField(name=name, type="map", number=int(number)))+ return fields+++def _parse_messages(content: str) -> dict[str, list[SchemaField]]:+ """Map every top-level/nested message name to its parsed fields."""+ messages: dict[str, list[SchemaField]] = {}+ for name, body in _extract_blocks(content, "message"):+ messages[name] = _parse_message_fields(body)+ return messages+++def _short_type(type_name: str) -> str:+ """Reduce a possibly-qualified message type to its bare name for lookup."""+ return type_name.rsplit(".", 1)[-1]+++def _parse_rpcs(body: str) -> list[ProtoMethod]:+ """Parse ``rpc Name (Req) returns (Res);`` declarations in a service body."""+ rpc_re = re.compile(+ r"rpc\s+(\w+)\s*\(\s*(?:stream\s+)?([\w.]+)\s*\)\s*"+ r"returns\s*\(\s*(?:stream\s+)?([\w.]+)\s*\)",+ )+ methods: list[ProtoMethod] = []+ for m in rpc_re.finditer(body):+ methods.append(+ ProtoMethod(name=m.group(1), request_type=m.group(2), response_type=m.group(3))+ )+ return methods+++class _ParsedService(NamedTuple):+ name: str+ full_path: str+ methods: list[ProtoMethod]+++def _parse_proto_file(+ content: str,+) -> tuple[str, list[_ParsedService], dict[str, list[SchemaField]]]:+ """Parse a proto file, returning ``(package, services, messages)``."""+ stripped = _strip_comments(content)+ pkg_match = re.search(r"^\s*package\s+([\w.]+)\s*;", stripped, re.MULTILINE)package = pkg_match.group(1) if pkg_match else ""- services: list[tuple[str, str, list[str]]] = []- rpc_re = re.compile(r"rpc\s+(\w+)\s*\(")+ messages = _parse_messages(content)+ services: list[_ParsedService] = []for svc_name, body in _extract_service_blocks(content):full_path = f"{package}.{svc_name}" if package else svc_name- methods = [m.group(1) for m in rpc_re.finditer(body)]- services.append((svc_name, full_path, methods))+ services.append(_ParsedService(svc_name, full_path, _parse_rpcs(body)))- return package, services+ return package, services, messagesclass ProtoDialect:@@ -88,23 +215,29 @@ class ProtoDialect:extensions = PROTOdef extract(self, ctx: ScanContext) -> list[Contract]:- package, services = _parse_proto_file(ctx.content)+ package, services, messages = _parse_proto_file(ctx.content)out: list[Contract] = []- for svc_name, full_path, methods in services:- for method in methods:- out.append(- make_grpc_contract(- ctx,- contract_id=f"grpc::{full_path}/{method}",- role="provider",- symbol_name=f"{full_path}/{method}",- confidence=0.85,- meta={- "package": package,- "service": svc_name,- "method": method,- "source": "proto",- },- )+ for svc in services:+ for method in svc.methods:+ contract = make_grpc_contract(+ ctx,+ contract_id=f"grpc::{svc.full_path}/{method.name}",+ role="provider",+ symbol_name=f"{svc.full_path}/{method.name}",+ confidence=0.85,+ meta={+ "package": package,+ "service": svc.name,+ "method": method.name,+ "source": "proto",+ },+ )+ schema = ContractSchema(+ source="proto",+ request_fields=messages.get(_short_type(method.request_type), []),+ response_fields=messages.get(_short_type(method.response_type), []),)+ if not schema.is_empty:+ contract.schema = schema+ out.append(contract)return outdiff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex de07f953c..3cfff09cd 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -83,12 +83,14 @@ def _acquire_lock(repo_path: Path, target_commit: str | None) -> None:try:(repo_path / ".repowise").mkdir(parents=True, exist_ok=True)_lock_path(repo_path).write_text(- _json.dumps({- "pid": os.getpid(),- "pid_create_token": process_create_token(os.getpid()),- "target_commit": target_commit,- "started_at": time.time(),- }),+ _json.dumps(+ {+ "pid": os.getpid(),+ "pid_create_token": process_create_token(os.getpid()),+ "target_commit": target_commit,+ "started_at": time.time(),+ }+ ),encoding="utf-8",)except OSError:@@ -101,6 +103,7 @@ def _release_lock(repo_path: Path) -> None:except OSError:pass+# ---------------------------------------------------------------------------# Data models# ---------------------------------------------------------------------------@@ -319,17 +322,22 @@ async def _incremental_repo_update(if pattern not in merged_excludes:merged_excludes.append(pattern)- parsed_files, _source_map, graph_builder, _structure, file_count, git_meta_map = (- await rebuild_graph_and_git(- repo_path,- file_diffs,- cfg,- merged_excludes,- git_tier=state.get("git_tier"),- include_submodules=bool(state.get("include_submodules", False)),- include_nested_repos=bool(state.get("include_nested_repos", False)),- log=_log.info,- )+ (+ parsed_files,+ _source_map,+ graph_builder,+ _structure,+ file_count,+ git_meta_map,+ ) = await rebuild_graph_and_git(+ repo_path,+ file_diffs,+ cfg,+ merged_excludes,+ git_tier=state.get("git_tier"),+ include_submodules=bool(state.get("include_submodules", False)),+ include_nested_repos=bool(state.get("include_nested_repos", False)),+ log=_log.info,)partial_health_report, dead_code_report = run_partial_analysis(@@ -507,13 +515,18 @@ async def update_workspace(for entry in entries:abs_path = (workspace_root / entry.path).resolve()if not abs_path.is_dir():- results.append(RepoUpdateResult(- alias=entry.alias, updated=False, skipped_reason="missing_directory",- ))+ results.append(+ RepoUpdateResult(+ alias=entry.alias,+ updated=False,+ skipped_reason="missing_directory",+ )+ )continue# Check staleness against stored commit in state.jsonimport json+state_path = abs_path / ".repowise" / "state.json"stored_commit = Noneif state_path.is_file():@@ -524,13 +537,18 @@ async def update_workspace(passis_stale, current_head, commits_behind = check_repo_staleness(- abs_path, stored_commit,+ abs_path,+ stored_commit,)if not is_stale:- results.append(RepoUpdateResult(- alias=entry.alias, updated=False, skipped_reason="up_to_date",- ))+ results.append(+ RepoUpdateResult(+ alias=entry.alias,+ updated=False,+ skipped_reason="up_to_date",+ )+ )continue# First-time indexing path: previously this short-circuited with@@ -569,13 +587,14 @@ async def update_workspace(_log.info("workspace_update: skipping %s — update already in flight ""(pid=%s target=%s elapsed=%ds)",- alias, existing.get("pid"), target_short, elapsed,+ alias,+ existing.get("pid"),+ target_short,+ elapsed,)# Record pending so the running update can roll forward.try:- (path / ".repowise" / ".update.pending").write_text(- new_head, encoding="utf-8"- )+ (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")except OSError:passreturn RepoUpdateResult(@@ -599,6 +618,7 @@ async def update_workspace(# Update state.json with new commitif result.updated and new_head:import json as _json+state_path = path / ".repowise" / "state.json"state: dict[str, Any] = {}if state_path.is_file():@@ -618,7 +638,8 @@ async def update_workspace()state_path.parent.mkdir(parents=True, exist_ok=True)state_path.write_text(- _json.dumps(state, indent=2), encoding="utf-8",+ _json.dumps(state, indent=2),+ encoding="utf-8",)# Update workspace config entry@@ -644,9 +665,13 @@ async def update_workspace(changed_aliases: list[str] = []for r in update_results:if isinstance(r, Exception):- results.append(RepoUpdateResult(- alias="unknown", updated=False, error=str(r),- ))+ results.append(+ RepoUpdateResult(+ alias="unknown",+ updated=False,+ error=str(r),+ )+ )else:results.append(r)if r.updated:@@ -683,7 +708,8 @@ async def run_cross_repo_hooks(if len(ws_config.repos) < 2:return- from .contracts import ContractStore, run_contract_extraction+ from .breaking_change import run_breaking_change_detection+ from .contracts import ContractStore, load_contract_store, run_contract_extractionfrom .cross_repo import CrossRepoOverlay, run_cross_repo_analysisfrom .system_graph import run_system_graph_build@@ -693,7 +719,12 @@ async def run_cross_repo_hooks(except Exception:_log.warning("Cross-repo analysis failed", exc_info=True)- # Phase 4: Contract extraction+ # Snapshot the contracts as they stand on disk BEFORE extraction overwrites+ # them — this is the cheapest honest "previous" state for the breaking-change+ # diff (no contract history needed; the last index is the baseline).+ previous_store = load_contract_store(workspace_root) or ContractStore()++ # Contract extraction (overwrites contracts.json).store = ContractStore()try:store = await run_contract_extraction(ws_config, workspace_root, changed_repos)@@ -706,3 +737,10 @@ async def run_cross_repo_hooks(await run_system_graph_build(ws_config, workspace_root, store, overlay)except Exception:_log.warning("System graph build failed", exc_info=True)++ # Breaking-change guard — diff the previous (on-disk) contracts against the+ # freshly extracted set and persist the impacted-consumer report.+ try:+ run_breaking_change_detection(workspace_root, previous_store, store)+ except Exception:+ _log.warning("Breaking-change detection failed", exc_info=True)diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 8766a314e..7de31e500 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -308,6 +308,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:except Exception as exc:logger.warning("workspace_stale_job_reset_failed", extra={"error": str(exc)})+ from repowise.core.workspace.breaking_change import BREAKING_CHANGES_FILENAMEfrom repowise.core.workspace.contracts import CONTRACTS_FILENAMEfrom repowise.core.workspace.system_graph import SYSTEM_GRAPH_FILENAMEfrom repowise.server.mcp_server._enrichment import CrossRepoEnricher@@ -315,10 +316,12 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:cross_repo_path = _Path(ws_root) / WORKSPACE_DATA_DIR / "cross_repo_edges.json"contracts_path = _Path(ws_root) / WORKSPACE_DATA_DIR / CONTRACTS_FILENAMEsystem_graph_path = _Path(ws_root) / WORKSPACE_DATA_DIR / SYSTEM_GRAPH_FILENAME+ breaking_changes_path = _Path(ws_root) / WORKSPACE_DATA_DIR / BREAKING_CHANGES_FILENAMEenricher = CrossRepoEnricher(cross_repo_path,contracts_path=contracts_path,system_graph_path=system_graph_path,+ breaking_changes_path=breaking_changes_path,)if enricher.has_data or enricher.has_contract_data or enricher.has_system_graph:app.state.cross_repo_enricher = enricherdiff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex e8ce07f0e..defb54b3b 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -10,7 +10,6 @@ import jsonimport loggingfrom collections import defaultdictfrom pathlib import Path-from typing import Any_log = logging.getLogger("repowise.mcp.enrichment")@@ -23,6 +22,7 @@ class CrossRepoEnricher:data_path: Path,contracts_path: Path | None = None,system_graph_path: Path | None = None,+ breaking_changes_path: Path | None = None,) -> None:self._co_changes: list[dict] = []self._package_deps: list[dict] = []@@ -44,15 +44,23 @@ class CrossRepoEnricher:# update. Read-only pass-through; views over it live in core/types.self._system_graph: dict | None = None+ # Breaking-change report — provider changes from the most recent update+ # that break consumers, with the impacted consumer files. Read-only.+ self._breaking_changes: dict | None = None+ self._breaking_changes_by_repo: dict[str, list[dict]] = defaultdict(list)+self._data_path = data_pathself._contracts_path = contracts_pathself._system_graph_path = system_graph_path+ self._breaking_changes_path = breaking_changes_pathself._load(data_path)if contracts_path is not None:self._load_contracts(contracts_path)if system_graph_path is not None:self._load_system_graph(system_graph_path)+ if breaking_changes_path is not None:+ self._load_breaking_changes(breaking_changes_path)def _load(self, data_path: Path) -> None:"""Parse JSON and build indexes."""@@ -178,6 +186,27 @@ class CrossRepoEnricher:len(self._system_graph.get("edges", [])),)+ def _load_breaking_changes(self, breaking_changes_path: Path) -> None:+ """Parse ``breaking_changes.json`` and index changes by provider repo."""+ if not breaking_changes_path.is_file():+ _log.debug("No breaking-change report at %s", breaking_changes_path)+ return+ try:+ self._breaking_changes = json.loads(breaking_changes_path.read_text(encoding="utf-8"))+ except Exception:+ _log.warning(+ "Failed to parse breaking changes at %s", breaking_changes_path, exc_info=True+ )+ return+ for change in self._breaking_changes.get("changes", []):+ repo = change.get("provider_repo")+ if repo:+ self._breaking_changes_by_repo[repo].append(change)+ _log.debug(+ "Breaking-change report loaded: %d change(s)",+ len(self._breaking_changes.get("changes", [])),+ )+def reload(self) -> None:"""Re-read JSON files from disk and rebuild all indexes.@@ -197,12 +226,16 @@ class CrossRepoEnricher:self._contract_provider_index = defaultdict(list)self._contract_consumer_index = defaultdict(list)self._system_graph = None+ self._breaking_changes = None+ self._breaking_changes_by_repo = defaultdict(list)self._load(self._data_path)if self._contracts_path is not None:self._load_contracts(self._contracts_path)if self._system_graph_path is not None:self._load_system_graph(self._system_graph_path)+ if self._breaking_changes_path is not None:+ self._load_breaking_changes(self._breaking_changes_path)_log.info("Cross-repo enricher reloaded: %d co-change edges, %d package deps, %d contract links",@@ -230,6 +263,19 @@ class CrossRepoEnricher:"""Return the raw system graph dict (nodes, edges, diagnostics)."""return self._system_graph+ @property+ def has_breaking_changes(self) -> bool:+ """True if a breaking-change report has been loaded."""+ return self._breaking_changes is not None++ def get_breaking_changes(self) -> dict | None:+ """Return the raw breaking-change report (changes + rollups)."""+ return self._breaking_changes++ def get_breaking_changes_for_repo(self, repo_alias: str) -> list[dict]:+ """Return breaking changes whose provider lives in *repo_alias*."""+ return self._breaking_changes_by_repo.get(repo_alias, [])+def get_diagnostics(self) -> dict | None:"""Return just the extraction diagnostics block of the system graph."""if self._system_graph is None:diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 16b2108ce..b31f9bce0 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -282,6 +282,7 @@ async def _lifespan(server: FastMCP):# Load cross-repo enricher (Phase 3 + 4)try:+ from repowise.core.workspace.breaking_change import BREAKING_CHANGES_FILENAMEfrom repowise.core.workspace.config import WORKSPACE_DATA_DIRfrom repowise.core.workspace.contracts import CONTRACTS_FILENAMEfrom repowise.core.workspace.system_graph import SYSTEM_GRAPH_FILENAME@@ -290,10 +291,12 @@ async def _lifespan(server: FastMCP):cross_repo_path = ws_root / WORKSPACE_DATA_DIR / "cross_repo_edges.json"contracts_path = ws_root / WORKSPACE_DATA_DIR / CONTRACTS_FILENAMEsystem_graph_path = ws_root / WORKSPACE_DATA_DIR / SYSTEM_GRAPH_FILENAME+ breaking_changes_path = ws_root / WORKSPACE_DATA_DIR / BREAKING_CHANGES_FILENAMEenricher = CrossRepoEnricher(cross_repo_path,contracts_path=contracts_path,system_graph_path=system_graph_path,+ breaking_changes_path=breaking_changes_path,)if enricher.has_data or enricher.has_system_graph:_state._cross_repo_enricher = enricherdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex 0e22129e0..c015ef89e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -412,6 +412,56 @@ def _as_path(entry: Any) -> str | None:#: glanceable. The full impact set is on get_blast_radius / the REST endpoint._XR_WILL_BREAK_LIMIT = 5_XR_COCHANGE_LIMIT = 3+#: Caps on the breaking-change directive — providers and consumers-per-provider.+#: The full report is on GET /api/workspace/breaking-changes.+_BC_PROVIDER_LIMIT = 5+_BC_CONSUMER_LIMIT = 5+++def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:+ """Breaking-change half of the PR directive: incompatible provider changes.++ Reads the persisted breaking-change report (current HEAD vs the previously+ indexed 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.+ """+ out: list[dict[str, Any]] = []+ try:+ if not _is_workspace_mode():+ return out+ enricher = _state._cross_repo_enricher+ if enricher is None or not getattr(enricher, "has_breaking_changes", False):+ return out+ for change in enricher.get_breaking_changes_for_repo(repo_alias):+ if len(out) >= _BC_PROVIDER_LIMIT:+ break+ consumers = 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+ out.append(+ {+ "contract_id": change.get("contract_id"),+ "type": change.get("contract_type"),+ "kind": change.get("kind"),+ "severity": change.get("severity"),+ "detail": change.get("detail"),+ "impacted_consumers": [+ {+ "repo": c.get("repo"),+ "service": c.get("service"),+ "file": c.get("file"),+ }+ for c in cross[:_BC_CONSUMER_LIMIT]+ ],+ }+ )+ except Exception:+ return []+ return outdef _cross_repo_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:@@ -831,12 +881,25 @@ async def get_risk(f"{len(missing_cross_repo_cochanges)} cross-repo co-changer(s) missing.")+ # 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(ctx.alias)+ bc_suffix = ""+ if breaking_changes:+ bc_consumers = sum(len(b["impacted_consumers"]) for b in breaking_changes)+ bc_suffix = (+ f" Breaking changes: {len(breaking_changes)} provider contract(s) changed "+ f"incompatibly, endangering {bc_consumers} consumer(s)."+ )+response["directive"] = {"will_break": will_break,"missing_cochanges": missing_cochanges,"missing_tests": missing_tests,"will_break_consumers": will_break_consumers,"missing_cross_repo_cochanges": missing_cross_repo_cochanges,+ "breaking_changes": breaking_changes,"governance_risk": governance_risk,"overall_risk_score": trimmed_blast.get("overall_risk_score"),"summary": (@@ -844,7 +907,7 @@ async def get_risk(f"~{len(will_break)} downstream file(s) likely affected, "f"{len(missing_cochanges)} historical co-changer(s) missing, "f"{len(missing_tests)} file(s) without tests."- f"{gov_suffix}{xr_suffix}"+ f"{gov_suffix}{xr_suffix}{bc_suffix}"),}else:diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex b9d39d9d5..d7011f1c4 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -21,6 +21,7 @@ from repowise.server.deps import ()from repowise.server.schemas import (WorkspaceBlastRadiusResponse,+ WorkspaceBreakingChangesResponse,WorkspaceCoChangeEntry,WorkspaceCoChangesResponse,WorkspaceContractEntry,@@ -570,6 +571,61 @@ async def get_blast_radius(return WorkspaceBlastRadiusResponse(**result.to_dict())+# ---------------------------------------------------------------------------+# GET /api/workspace/breaking-changes+# ---------------------------------------------------------------------------++[email protected]("/breaking-changes", response_model=WorkspaceBreakingChangesResponse)+async def get_breaking_changes(+ ws_config=Depends(get_workspace_config),+ enricher=Depends(get_cross_repo_enricher),+ repo: str | None = Query(None, description="Filter to changes whose provider is in this repo."),+ severity: str | None = Query(None, description="Filter: breaking or warning."),+):+ """Provider contract changes that break consumers across repos.++ Computed during the most recent ``repowise update --workspace`` by diffing the+ freshly-extracted contracts against the previously-indexed set, then resolving+ each change's direct consumers from the matched links. Returns an empty report+ (not 404) when no breaking changes were detected or no report exists yet.+ """+ _require_workspace(ws_config)++ report = enricher.get_breaking_changes() if enricher is not None else None+ if not report:+ return WorkspaceBreakingChangesResponse()++ changes = list(report.get("changes", []))+ if repo:+ changes = [c for c in changes if c.get("provider_repo") == repo]+ if severity:+ changes = [c for c in changes if c.get("severity") == severity]++ # Recompute rollups when a filter narrowed the set so the response stays+ # self-consistent; otherwise pass the persisted rollups straight through.+ if repo or severity:+ impacted_repos = sorted(+ {ic.get("repo", "") for c in changes for ic in c.get("impacted_consumers", [])}+ )+ impacted_services = sorted(+ {ic.get("node_id", "") for c in changes for ic in c.get("impacted_consumers", [])}+ )+ return WorkspaceBreakingChangesResponse(+ version=report.get("version", 1),+ generated_at=report.get("generated_at", ""),+ changes=changes,+ total=len(changes),+ breaking_count=sum(1 for c in changes if c.get("severity") == "breaking"),+ warning_count=sum(1 for c in changes if c.get("severity") == "warning"),+ impacted_repos=impacted_repos,+ impacted_services=impacted_services,+ total_impacted_consumers=sum(len(c.get("impacted_consumers", [])) for c in changes),+ )++ return WorkspaceBreakingChangesResponse(**report)++# ---------------------------------------------------------------------------# POST /api/workspace/sync# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex fb528d95e..ee1e2119e 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -156,6 +156,8 @@ from .ui_helpers import ()from .workspace import (WorkspaceBlastRadiusResponse,+ WorkspaceBreakingChange,+ WorkspaceBreakingChangesResponse,WorkspaceCoChangeEntry,WorkspaceCoChangesResponse,WorkspaceContractEntry,@@ -167,6 +169,7 @@ from .workspace import (WorkspaceGraphEdge,WorkspaceGraphNode,WorkspaceGraphResponse,+ WorkspaceImpactedConsumer,WorkspaceImpactedNode,WorkspaceOrphanProvider,WorkspaceRepoDiagnostics,@@ -296,6 +299,9 @@ __all__ = ["WebhookResponse","WorkspaceCoChangeEntry","WorkspaceBlastRadiusResponse",+ "WorkspaceBreakingChange",+ "WorkspaceBreakingChangesResponse",+ "WorkspaceImpactedConsumer","WorkspaceCoChangesResponse","WorkspaceContractEntry","WorkspaceContractLinkEntry",diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 22e5a3267..9f702e9c7 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -242,3 +242,48 @@ class WorkspaceBlastRadiusResponse(BaseModel):max_distance: int = 0total_impacted: int = 0unresolved_targets: list[str] = []+++# ---------------------------------------------------------------------------+# Breaking-change guard — provider changes that break consumers across repos.+# Mirrors repowise.core.workspace.breaking_change.+# ---------------------------------------------------------------------------+++class WorkspaceImpactedConsumer(BaseModel):+ repo: str+ service: str | None = None+ node_id: str+ file: str+ symbol: str+ match_type: str = "exact"+ confidence: float = 0.0+++class WorkspaceBreakingChange(BaseModel):+ kind: str+ severity: str # breaking | warning+ contract_id: str+ contract_type: str+ provider_repo: str+ provider_file: str+ provider_symbol: str+ provider_service: str | None = None+ provider_node_id: str = ""+ detail: str+ field_name: str | None = None+ old_value: str | None = None+ new_value: str | None = None+ impacted_consumers: list[WorkspaceImpactedConsumer] = []+++class WorkspaceBreakingChangesResponse(BaseModel):+ version: int = 1+ generated_at: str = ""+ changes: list[WorkspaceBreakingChange] = []+ total: int = 0+ breaking_count: int = 0+ warning_count: int = 0+ impacted_repos: list[str] = []+ impacted_services: list[str] = []+ total_impacted_consumers: int = 0diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex fbd36d04b..ddf1ee5ed 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -205,3 +205,82 @@ export interface CrossRepoBlastRadius {/** Target strings that matched no node or repo. */unresolved_targets: string[];}++// ---------------------------------------------------------------------------+// Contract schema — the optional request/response field shape a contract+// carries when a parser can recover it (proto message fields today; OpenAPI+// when present). Drives schema-level breaking-change detection.+// Mirrors `repowise.core.workspace.contract_schema`.+// ---------------------------------------------------------------------------++/** One field in a request or response shape. `number` is the proto wire tag. */+export interface SchemaField {+ name: string;+ type: string;+ required?: boolean;+ number?: number | null;+ repeated?: boolean;+}++export interface ContractSchema {+ /** Which parser produced the shape (`"proto"` / `"openapi"`). */+ source: string;+ request_fields: SchemaField[];+ response_fields: SchemaField[];+}++// ---------------------------------------------------------------------------+// Breaking-change guard — provider contract changes that break consumers across+// repos, computed by diffing the current contracts against the previously+// indexed set. Mirrors `repowise.core.workspace.breaking_change`.+// ---------------------------------------------------------------------------++/** How a breaking change ranks. `breaking` = wire-incompatible; `warning` = source risk. */+export type BreakingChangeSeverity = "breaking" | "warning";++/** A consumer endangered by a provider's breaking change (from a matched link). */+export interface BreakingChangeConsumer {+ repo: string;+ service: string | null;+ /** System-graph node id of the consumer (for map badging). */+ node_id: string;+ /** The exact consumer file that calls the changed contract. */+ file: string;+ symbol: string;+ match_type: string;+ confidence: number;+}++export interface BreakingChange {+ /** Rule key: `removed_endpoint` | `removed_field` | `field_type_changed` | ... */+ kind: string;+ severity: BreakingChangeSeverity;+ contract_id: string;+ contract_type: string;+ provider_repo: string;+ provider_file: string;+ provider_symbol: string;+ provider_service: string | null;+ /** System-graph node id of the changed provider. */+ provider_node_id: string;+ /** Human-readable one-liner. */+ detail: string;+ field_name?: string | null;+ old_value?: string | null;+ new_value?: string | null;+ impacted_consumers: BreakingChangeConsumer[];+}++export interface BreakingChangeReport {+ version: number;+ generated_at: string;+ changes: BreakingChange[];+ total: number;+ breaking_count: number;+ warning_count: number;+ /** Distinct repos with an endangered consumer. */+ impacted_repos: string[];+ /** Distinct system-graph node ids with an endangered consumer. */+ impacted_services: string[];+ total_impacted_consumers: number;+}diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.tsindex 362725c92..0fe1d5bce 100644--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts@@ -14,7 +14,8 @@ import {buildBlastRadiusOverlay,impactBadgeTone,} from "../../src/workspace/system-map/blast-radius";-import type { CrossRepoBlastRadius } from "@repowise-dev/types";+import { buildBreakingChangeOverlay } from "../../src/workspace/system-map/breaking-changes";+import type { BreakingChange, BreakingChangeReport, CrossRepoBlastRadius } from "@repowise-dev/types";function node(id: string, repo: string, over: Partial<SystemNode> = {}): SystemNode {return {@@ -273,3 +274,75 @@ describe("buildBlastRadiusOverlay", () => {expect(impactBadgeTone(1, false)).toBe("info");});});++describe("buildBreakingChangeOverlay", () => {+ function change(over: Partial<BreakingChange> = {}): BreakingChange {+ return {+ kind: "removed_endpoint",+ severity: "breaking",+ contract_id: "http::GET::/users",+ contract_type: "http",+ provider_repo: "api",+ provider_file: "routes.py",+ provider_symbol: "h",+ provider_service: null,+ provider_node_id: "api",+ detail: "removed",+ impacted_consumers: [+ {+ repo: "web",+ service: null,+ node_id: "web",+ file: "client.ts",+ symbol: "fetch",+ match_type: "exact",+ confidence: 0.9,+ },+ ],+ ...over,+ };+ }+ function report(changes: BreakingChange[]): BreakingChangeReport {+ return {+ version: 1,+ generated_at: "t",+ changes,+ total: changes.length,+ breaking_count: changes.filter((c) => c.severity === "breaking").length,+ warning_count: changes.filter((c) => c.severity === "warning").length,+ impacted_repos: [],+ impacted_services: [],+ total_impacted_consumers: 0,+ };+ }++ const g = graph(+ [node("api", "api"), node("web", "web"), node("idle", "idle")],+ [edge("web", "api"), edge("idle", "api")],+ );++ it("badges the changed provider and at-risk consumers, highlighting the seam", () => {+ const overlay = buildBreakingChangeOverlay(g, report([change()]));+ expect(overlay.nodeBadges?.api).toEqual({ label: "1 breaking", tone: "danger" });+ expect(overlay.nodeBadges?.web).toEqual({ label: "at risk", tone: "warning" });+ // Only the consumer→provider edge in the report is highlighted.+ expect(overlay.highlightEdgeIds?.has("web->api")).toBe(true);+ expect(overlay.highlightEdgeIds?.has("idle->api")).toBe(false);+ expect(overlay.edgeBadges?.["web->api"]).toEqual({ label: "breaking", tone: "danger" });+ // Additive overlay: nothing is dimmed.+ expect(overlay.dimNodeIds).toBeUndefined();+ });++ it("a warning-only provider reads as a warning badge", () => {+ const overlay = buildBreakingChangeOverlay(+ g,+ report([change({ severity: "warning", kind: "removed_field", impacted_consumers: [] })]),+ );+ expect(overlay.nodeBadges?.api).toEqual({ label: "1 change", tone: "warning" });+ });++ it("returns an empty overlay when there are no changes", () => {+ expect(buildBreakingChangeOverlay(g, report([]))).toEqual({});+ expect(buildBreakingChangeOverlay(g, null)).toEqual({});+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsxindex a44b6828a..17e81bd7b 100644--- a/packages/ui/__tests__/workspace/system-map.test.tsx+++ b/packages/ui/__tests__/workspace/system-map.test.tsx@@ -6,6 +6,8 @@ import { SystemMapFilters } from "../../src/workspace/system-map/system-map-filtimport { SystemMapLegend } from "../../src/workspace/system-map/system-map-legend";import { SystemMapInspector } from "../../src/workspace/system-map/system-map-inspector";import { SystemMapBlastPanel } from "../../src/workspace/system-map/system-map-blast-panel";+import { SystemMapBreakingPanel } from "../../src/workspace/system-map/system-map-breaking-panel";+import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";// jsdom has no layout engine → stub ResizeObserver so React Flow can mount.beforeAll(() => {@@ -240,3 +242,71 @@ describe("SystemMapBlastPanel", () => {expect(screen.getByText(/nothing downstream/i)).toBeInTheDocument();});});++describe("SystemMapBreakingPanel", () => {+ function change(over: Partial<BreakingChange> = {}): BreakingChange {+ return {+ kind: "removed_endpoint",+ severity: "breaking",+ contract_id: "http::GET::/users",+ contract_type: "http",+ provider_repo: "api",+ provider_file: "routes.py",+ provider_symbol: "h",+ provider_service: null,+ provider_node_id: "api",+ detail: "http::GET::/users was removed",+ impacted_consumers: [+ {+ repo: "web",+ service: null,+ node_id: "web",+ file: "client.ts",+ symbol: "fetch",+ match_type: "exact",+ confidence: 0.9,+ },+ ],+ ...over,+ };+ }+ function report(changes: BreakingChange[]): BreakingChangeReport {+ return {+ version: 1,+ generated_at: "t",+ changes,+ total: changes.length,+ breaking_count: changes.filter((c) => c.severity === "breaking").length,+ warning_count: changes.filter((c) => c.severity === "warning").length,+ impacted_repos: ["web"],+ impacted_services: ["web"],+ total_impacted_consumers: 1,+ };+ }++ it("renders nothing without a report", () => {+ const { container } = render(<SystemMapBreakingPanel report={null} onClear={() => {}} />);+ expect(container).toBeEmptyDOMElement();+ });++ it("lists a changed provider with both code sides", () => {+ render(<SystemMapBreakingPanel report={report([change()])} onClear={() => {}} />);+ expect(screen.getByText("http::GET::/users")).toBeInTheDocument();+ expect(screen.getByText(/was removed/i)).toBeInTheDocument();+ expect(screen.getByText(/routes\.py/)).toBeInTheDocument(); // provider side+ expect(screen.getByText(/client\.ts/)).toBeInTheDocument(); // consumer side+ expect(screen.getByText(/1 breaking, 0 warning/i)).toBeInTheDocument();+ });++ it("focuses a node when a consumer is clicked", () => {+ const onSelectNode = vi.fn();+ render(<SystemMapBreakingPanel report={report([change()])} onSelectNode={onSelectNode} onClear={() => {}} />);+ fireEvent.click(screen.getByText(/client\.ts/));+ expect(onSelectNode).toHaveBeenCalledWith("web");+ });++ it("shows the clean state when there are no changes", () => {+ render(<SystemMapBreakingPanel report={report([])} onClear={() => {}} />);+ expect(screen.getByText(/no breaking changes/i)).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/workspace/system-map/breaking-changes.ts b/packages/ui/src/workspace/system-map/breaking-changes.tsnew file mode 100644index 000000000..d6c4af546--- /dev/null+++ b/packages/ui/src/workspace/system-map/breaking-changes.ts@@ -0,0 +1,72 @@+/**+ * Breaking-change overlay — turns a `BreakingChangeReport` (computed by the core+ * / REST layer) into a `SystemMapOverlay` the Live System Map renders without any+ * component change. Changed provider services are badged with their breaking+ * count, the consumers they endanger are badged "at risk", and the edges between+ * them are highlighted. This is additive (no dimming): the whole map stays+ * legible, with the at-risk seams called out. The Phase 4 attach point promised+ * by the Phase 2 overlay API.+ */++import type { BreakingChangeReport, SystemGraph } from "@repowise-dev/types";+import type { BadgeTone, SystemMapBadge, SystemMapOverlay } from "./types";++/** A provider with at least one `breaking` change reads danger; warnings read warning. */+function providerTone(severity: "breaking" | "warning"): BadgeTone {+ return severity === "breaking" ? "danger" : "warning";+}++/**+ * Build the at-risk overlay for a breaking-change report. Returns an empty+ * overlay when there are no changes, so passing it through is always safe.+ */+export function buildBreakingChangeOverlay(+ graph: SystemGraph,+ report: BreakingChangeReport | null | undefined,+): SystemMapOverlay {+ if (!report || report.changes.length === 0) return {};++ const providerCount = new Map<string, number>();+ const providerSeverity = new Map<string, "breaking" | "warning">();+ const consumerNodeIds = new Set<string>();+ const atRiskPairs = new Set<string>(); // `${consumerNode}->${providerNode}`++ for (const change of report.changes) {+ const pid = change.provider_node_id;+ providerCount.set(pid, (providerCount.get(pid) ?? 0) + 1);+ if (change.severity === "breaking") providerSeverity.set(pid, "breaking");+ else if (!providerSeverity.has(pid)) providerSeverity.set(pid, "warning");+ for (const consumer of change.impacted_consumers) {+ consumerNodeIds.add(consumer.node_id);+ atRiskPairs.add(`${consumer.node_id}->${pid}`);+ }+ }++ const nodeBadges: Record<string, SystemMapBadge> = {};+ for (const [nid, count] of providerCount) {+ const severity = providerSeverity.get(nid) ?? "warning";+ nodeBadges[nid] = {+ label: severity === "breaking" ? `${count} breaking` : `${count} change`,+ tone: providerTone(severity),+ };+ }+ for (const nid of consumerNodeIds) {+ if (!nodeBadges[nid]) nodeBadges[nid] = { label: "at risk", tone: "warning" };+ }++ const highlightEdgeIds = new Set<string>();+ const edgeBadges: Record<string, SystemMapBadge> = {};+ for (const edge of graph.edges) {+ if (atRiskPairs.has(`${edge.source}->${edge.target}`)) {+ highlightEdgeIds.add(edge.id);+ edgeBadges[edge.id] = { label: "breaking", tone: "danger" };+ }+ }++ const overlay: SystemMapOverlay = { nodeBadges };+ if (highlightEdgeIds.size > 0) {+ overlay.highlightEdgeIds = highlightEdgeIds;+ overlay.edgeBadges = edgeBadges;+ }+ return overlay;+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex 98924bd98..7b84b6698 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -10,6 +10,11 @@ export { SystemMapFilters, type SystemMapFiltersProps } from "./system-map-filteexport { SystemMapInspector, type SystemMapInspectorProps } from "./system-map-inspector";export { SystemMapBlastPanel, type SystemMapBlastPanelProps } from "./system-map-blast-panel";export { buildBlastRadiusOverlay, impactBadgeTone } from "./blast-radius";+export {+ SystemMapBreakingPanel,+ type SystemMapBreakingPanelProps,+} from "./system-map-breaking-panel";+export { buildBreakingChangeOverlay } from "./breaking-changes";export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";export { applyView, computeSystemMapPositions, SYSTEM_MAP_NODE_SIZE, type SystemMapView } from "./layout";export { collapseToRepos } from "./collapse";diff --git a/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsxnew file mode 100644index 000000000..ec79b5935--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx@@ -0,0 +1,193 @@+"use client";++/**+ * Breaking-changes rail for the Live System Map. Given a `BreakingChangeReport`,+ * it lists each changed provider contract (breaking first) and the consumers it+ * endangers, showing both code sides — the provider file that changed and the+ * consumer file that calls it. Pure presentation: the host owns the fetch and+ * passes the report in; the at-risk badges ride the map's overlay prop.+ */++import { AlertTriangle, X } from "lucide-react";+import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";++export interface SystemMapBreakingPanelProps {+ report: BreakingChangeReport | null;+ loading?: boolean;+ /** Focus a provider/consumer service on the map (optional). */+ onSelectNode?: (nodeId: string) => void;+ onClear: () => void;+}++const panelStyle: React.CSSProperties = {+ position: "absolute",+ top: 12,+ right: 12,+ width: 320,+ maxHeight: "calc(100% - 24px)",+ overflowY: "auto",+ background: "var(--color-bg-elevated)",+ border: "1px solid var(--color-border-default)",+ borderRadius: 10,+ boxShadow: "0 8px 24px rgba(0,0,0,0.28)",+ zIndex: 4,+ fontSize: 12,+ color: "var(--color-text-secondary)",+};++function severityColor(severity: string): string {+ return severity === "breaking" ? "var(--color-risk-high)" : "var(--color-warning)";+}++function ChangeRow({+ change,+ onSelectNode,+}: {+ change: BreakingChange;+ onSelectNode?: (id: string) => void;+}) {+ const color = severityColor(change.severity);+ return (+ <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>+ <div style={{ display: "flex", alignItems: "center", gap: 6 }}>+ <span+ style={{+ flexShrink: 0,+ color,+ border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,+ background: `color-mix(in srgb, ${color} 16%, transparent)`,+ borderRadius: 4,+ fontSize: 9,+ fontWeight: 700,+ textTransform: "uppercase",+ padding: "1px 5px",+ }}+ >+ {change.severity}+ </span>+ <button+ type="button"+ onClick={() => onSelectNode?.(change.provider_node_id)}+ title={`Provider: ${change.provider_repo} · ${change.provider_file}`}+ style={{+ flex: 1,+ minWidth: 0,+ textAlign: "left",+ cursor: onSelectNode ? "pointer" : "default",+ background: "transparent",+ color: "var(--color-text-primary)",+ fontWeight: 600,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {change.contract_id}+ </button>+ </div>+ <div style={{ color: "var(--color-text-secondary)", marginTop: 3 }}>{change.detail}</div>+ <div style={{ color: "var(--color-text-tertiary)", fontSize: 10, marginTop: 2 }}>+ {change.provider_repo} · {change.provider_file}+ </div>+ {change.impacted_consumers.length > 0 && (+ <div style={{ marginTop: 6 }}>+ <div style={{ fontSize: 10, fontWeight: 700, color: "var(--color-text-tertiary)" }}>+ Endangers {change.impacted_consumers.length} consumer(s)+ </div>+ {change.impacted_consumers.map((c) => (+ <button+ key={`${c.node_id}:${c.file}`}+ type="button"+ onClick={() => onSelectNode?.(c.node_id)}+ title={`Consumer: ${c.repo} · ${c.file}`}+ style={{+ display: "block",+ width: "100%",+ textAlign: "left",+ cursor: onSelectNode ? "pointer" : "default",+ background: "transparent",+ color: "var(--color-text-secondary)",+ fontSize: 11,+ padding: "2px 0 2px 8px",+ }}+ >+ <span style={{ color: "var(--color-text-primary)" }}>{c.repo}</span> · {c.file}+ </button>+ ))}+ </div>+ )}+ </div>+ );+}++export function SystemMapBreakingPanel({+ report,+ loading,+ onSelectNode,+ onClear,+}: SystemMapBreakingPanelProps) {+ if (!report) return null;++ const sorted = [...report.changes].sort((a, b) =>+ a.severity === b.severity ? 0 : a.severity === "breaking" ? -1 : 1,+ );++ return (+ <div style={panelStyle}>+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ padding: "10px 12px",+ borderBottom: "1px solid var(--color-border-default)",+ }}+ >+ <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>+ <AlertTriangle size={13} style={{ color: "var(--color-risk-high)" }} />+ <span+ style={{+ fontSize: 10,+ fontWeight: 700,+ letterSpacing: 0.6,+ textTransform: "uppercase",+ color: "var(--color-text-tertiary)",+ }}+ >+ Breaking changes+ </span>+ </span>+ <button+ type="button"+ onClick={onClear}+ aria-label="Clear breaking changes"+ style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}+ >+ <X size={14} />+ </button>+ </div>++ <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-default)" }}>+ <div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>+ {loading+ ? "Checking the latest update…"+ : `${report.breaking_count} breaking, ${report.warning_count} warning across ${report.impacted_repos.length} repo(s)`}+ </div>+ </div>++ {!loading && report.changes.length === 0 && (+ <div style={{ padding: "12px", color: "var(--color-text-tertiary)" }}>+ No breaking changes in the most recent update.+ </div>+ )}++ {sorted.map((change) => (+ <ChangeRow+ key={`${change.contract_id}:${change.kind}:${change.field_name ?? ""}`}+ change={change}+ {...(onSelectNode ? { onSelectNode } : {})}+ />+ ))}+ </div>+ );+}diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex 36bc480e9..f0abd373f 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -2,11 +2,13 @@import { useMemo, useState } from "react";import { useRouter } from "next/navigation";-import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap } from "lucide-react";+import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle } from "lucide-react";import {SystemMap,SystemMapBlastPanel,+ SystemMapBreakingPanel,buildBlastRadiusOverlay,+ buildBreakingChangeOverlay,type RepoHealth,} from "@repowise-dev/ui/workspace/system-map";import { StatCard } from "@repowise-dev/ui/shared/stat-card";@@ -15,6 +17,7 @@ import {useWorkspaceSystemGraph,useWorkspaceGraph,useWorkspaceBlastRadius,+ useWorkspaceBreakingChanges,} from "@/lib/hooks/use-workspace";export default function SystemMapPage() {@@ -31,6 +34,12 @@ export default function SystemMapPage() {includeBehavioral,});+ // Breaking-change guard. Lazy-fetched the first time it's toggled on; its+ // at-risk badges ride the map's overlay prop when no blast target is focused.+ const [showBreaking, setShowBreaking] = useState(false);+ const { data: breaking, isLoading: breakingLoading } =+ useWorkspaceBreakingChanges(showBreaking);+// Join repo health (from the repo-level graph) onto service nodes by alias.// The map keys health by `SystemNode.repo`; the repo graph's node `name` is// the repo alias.@@ -42,10 +51,14 @@ export default function SystemMapPage() {return m;}, [repoGraph]);+ // A blast-radius selection focuses the map (dim + ripple) and takes precedence;+ // otherwise the breaking-change overlay badges the at-risk seams additively.const overlay = useMemo(() => {- if (!graph || !blast) return undefined;- return buildBlastRadiusOverlay(graph, blast);- }, [graph, blast]);+ if (!graph) return undefined;+ if (blast) return buildBlastRadiusOverlay(graph, blast);+ if (showBreaking && breaking) return buildBreakingChangeOverlay(graph, breaking);+ return undefined;+ }, [graph, blast, showBreaking, breaking]);const diag = graph?.diagnostics;const serviceCount = graph?.nodes.length ?? 0;@@ -121,11 +134,27 @@ export default function SystemMapPage() {/>Include co-change</label>+ <button+ type="button"+ onClick={() => setShowBreaking((v) => !v)}+ aria-pressed={showBreaking}+ className={`ml-auto inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${+ showBreaking+ ? "border-[var(--color-risk-high)] text-[var(--color-risk-high)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"+ }`}+ >+ <AlertTriangle className="h-4 w-4" />+ Breaking changes+ {showBreaking && breaking && breaking.breaking_count > 0 && (+ <span className="font-semibold">· {breaking.breaking_count}</span>+ )}+ </button>{blastTarget && (<buttontype="button"onClick={() => setBlastTarget(null)}- className="ml-auto text-sm text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ className="text-sm text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]">Clear</button>@@ -152,6 +181,14 @@ export default function SystemMapPage() {onSelectTarget={setBlastTarget}onClear={() => setBlastTarget(null)}/>+ {showBreaking && (+ <SystemMapBreakingPanel+ report={breaking}+ loading={breakingLoading}+ onSelectNode={setBlastTarget}+ onClear={() => setShowBreaking(false)}+ />+ )}</>)}</div>diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.tsindex bf18f45a3..9a445dd68 100644--- a/packages/web/src/lib/api/types/workspace.ts+++ b/packages/web/src/lib/api/types/workspace.ts@@ -144,12 +144,25 @@ export type {OrphanProvider,ImpactedNode,CrossRepoBlastRadius,+ ContractSchema,+ SchemaField,+ BreakingChange,+ BreakingChangeConsumer,+ BreakingChangeReport,+ BreakingChangeSeverity,} from "@repowise-dev/types";-import type { SystemGraph, CrossRepoBlastRadius } from "@repowise-dev/types";+import type {+ SystemGraph,+ CrossRepoBlastRadius,+ BreakingChangeReport,+} from "@repowise-dev/types";/** `GET /api/workspace/system-graph` — the full service-granular system graph. */export type WorkspaceSystemGraphResponse = SystemGraph;/** `GET /api/workspace/blast-radius` — cross-repo downstream impact set. */export type WorkspaceBlastRadiusResponse = CrossRepoBlastRadius;++/** `GET /api/workspace/breaking-changes` — incompatible provider changes + impact. */+export type WorkspaceBreakingChangesResponse = BreakingChangeReport;diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.tsindex 6721eda98..101334ac9 100644--- a/packages/web/src/lib/api/workspace.ts+++ b/packages/web/src/lib/api/workspace.ts@@ -7,6 +7,7 @@ import type {WorkspaceSyncResponse,WorkspaceSystemGraphResponse,WorkspaceBlastRadiusResponse,+ WorkspaceBreakingChangesResponse,} from "./types";export async function getWorkspace(@@ -78,6 +79,21 @@ export async function getWorkspaceBlastRadius(opts: {return apiGet<WorkspaceBlastRadiusResponse>("/api/workspace/blast-radius", params);}+/**+ * Provider contract changes from the most recent update that break consumers+ * across repos, with the impacted consumer files. Optionally filter by provider+ * repo or severity.+ */+export async function getWorkspaceBreakingChanges(opts?: {+ repo?: string;+ severity?: "breaking" | "warning";+}): Promise<WorkspaceBreakingChangesResponse> {+ const params: Record<string, string> = {};+ if (opts?.repo) params.repo = opts.repo;+ if (opts?.severity) params.severity = opts.severity;+ return apiGet<WorkspaceBreakingChangesResponse>("/api/workspace/breaking-changes", params);+}+/*** Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to* scope to one repo; otherwise the server fans out across every loadeddiff --git a/packages/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.tsindex f0a7906b9..1c6cc7a25 100644--- a/packages/web/src/lib/hooks/use-workspace.ts+++ b/packages/web/src/lib/hooks/use-workspace.ts@@ -8,6 +8,7 @@ import {getWorkspaceSystemGraph,getWorkspaceGraph,getWorkspaceBlastRadius,+ getWorkspaceBreakingChanges,} from "@/lib/api/workspace";import type {WorkspaceResponse,@@ -16,6 +17,7 @@ import type {WorkspaceSystemGraphResponse,WorkspaceGraphResponse,WorkspaceBlastRadiusResponse,+ WorkspaceBreakingChangesResponse,} from "@/lib/api/types";export function useWorkspace() {@@ -93,6 +95,19 @@ export function useWorkspaceBlastRadius(return { data: data ?? null, isLoading, error };}+/**+ * Breaking-change report from the most recent workspace update. Pass+ * ``enabled=false`` to skip the request until the user opens the panel.+ */+export function useWorkspaceBreakingChanges(enabled = true) {+ const { data, error, isLoading } = useSWR<WorkspaceBreakingChangesResponse>(+ enabled ? "workspace:breaking-changes" : null,+ () => getWorkspaceBreakingChanges(),+ { revalidateOnFocus: false },+ );+ return { data: data ?? null, isLoading, error };+}+/** Repo-level graph (carries the per-repo health score used by the map). */export function useWorkspaceGraph() {const { data, error, isLoading } = useSWR<WorkspaceGraphResponse>(diff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pyindex 78457e348..bb634c6ca 100644--- a/tests/unit/server/test_mcp_blast_radius.py+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -17,21 +17,51 @@ from repowise.server.mcp_server.tool_blast_radius import get_blast_radiusdef _enricher_with_graph(tmp_path: Path) -> CrossRepoEnricher:contracts = [- Contract(repo="backend", contract_id="http::GET::/users", contract_type="http",- role="provider", file_path="routes.py", symbol_name="get_users", confidence=0.9),- Contract(repo="frontend", contract_id="http::GET::/users", contract_type="http",- role="consumer", file_path="client.ts", symbol_name="fetchUsers", confidence=0.8),+ Contract(+ repo="backend",+ contract_id="http::GET::/users",+ contract_type="http",+ role="provider",+ file_path="routes.py",+ symbol_name="get_users",+ confidence=0.9,+ ),+ Contract(+ repo="frontend",+ contract_id="http::GET::/users",+ contract_type="http",+ role="consumer",+ file_path="client.ts",+ symbol_name="fetchUsers",+ confidence=0.8,+ ),]links = [- ContractLink(contract_id="http::GET::/users", contract_type="http", match_type="exact",- confidence=0.8, provider_repo="backend", provider_file="routes.py",- provider_symbol="get_users", provider_service=None, consumer_repo="frontend",- consumer_file="client.ts", consumer_symbol="fetchUsers", consumer_service=None),+ ContractLink(+ contract_id="http::GET::/users",+ contract_type="http",+ match_type="exact",+ confidence=0.8,+ provider_repo="backend",+ provider_file="routes.py",+ provider_symbol="get_users",+ provider_service=None,+ consumer_repo="frontend",+ consumer_file="client.ts",+ consumer_symbol="fetchUsers",+ consumer_service=None,+ ),]- overlay = CrossRepoOverlay(package_deps=[- CrossRepoPackageDep(source_repo="frontend", target_repo="backend",- source_manifest="package.json", kind="npm_local_path"),- ])+ overlay = CrossRepoOverlay(+ package_deps=[+ CrossRepoPackageDep(+ source_repo="frontend",+ target_repo="backend",+ source_manifest="package.json",+ kind="npm_local_path",+ ),+ ]+ )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")return CrossRepoEnricher(@@ -117,6 +147,91 @@ def test_cross_repo_directive_empty_outside_workspace():_state._registry = prev+def _enricher_with_breaking(tmp_path: Path) -> CrossRepoEnricher:+ from repowise.core.workspace.breaking_change import detect_breaking_changes+ from repowise.core.workspace.contracts import ContractStore++ prev = ContractStore(+ contracts=[+ Contract(+ repo="backend",+ contract_id="http::GET::/users",+ contract_type="http",+ role="provider",+ file_path="routes.py",+ symbol_name="get_users",+ confidence=0.9,+ ),+ ],+ contract_links=[+ ContractLink(+ contract_id="http::GET::/users",+ contract_type="http",+ match_type="exact",+ confidence=0.8,+ provider_repo="backend",+ provider_file="routes.py",+ provider_symbol="get_users",+ provider_service=None,+ consumer_repo="frontend",+ consumer_file="client.ts",+ consumer_symbol="fetchUsers",+ consumer_service=None,+ ),+ ],+ )+ report = detect_breaking_changes(prev, 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 test_breaking_change_directive_reports_impacted_consumers(tmp_path: Path):+ 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 = _enricher_with_breaking(tmp_path)+ try:+ directive = _breaking_change_directive("backend")+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+ assert len(directive) == 1+ assert directive[0]["kind"] == "removed_endpoint"+ assert directive[0]["severity"] == "breaking"+ assert directive[0]["impacted_consumers"][0]["repo"] == "frontend"+++def test_breaking_change_directive_empty_for_other_repo(tmp_path: Path):+ 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 = _enricher_with_breaking(tmp_path)+ try:+ # 'frontend' is a consumer, not the provider of the change → no directive.+ assert _breaking_change_directive("frontend") == []+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+++def test_breaking_change_directive_empty_outside_workspace():+ from repowise.server.mcp_server.tool_risk import _breaking_change_directive++ prev = _state._registry+ _state._registry = None+ try:+ assert _breaking_change_directive("backend") == []+ finally:+ _state._registry = prev++@pytest.mark.asyncioasync def test_no_system_graph_returns_error(tmp_path: Path):prev_registry = _state._registrydiff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex dc153fe7e..a33c2eb78 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -77,80 +77,86 @@ def _make_ws_config():def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:"""Build a real enricher with sample data."""cross_repo_path = tmp_path / "cross_repo_edges.json"- _write_json(cross_repo_path, {- "version": 1,- "co_changes": [- {- "source_repo": "backend",- "source_file": "api/routes.py",- "target_repo": "frontend",- "target_file": "src/client.ts",- "strength": 0.8,- "frequency": 5,- "last_date": "2026-04-10",- },- ],- "package_deps": [- {- "source_repo": "frontend",- "target_repo": "backend",- "source_manifest": "package.json",- "kind": "npm",- },- ],- })+ _write_json(+ cross_repo_path,+ {+ "version": 1,+ "co_changes": [+ {+ "source_repo": "backend",+ "source_file": "api/routes.py",+ "target_repo": "frontend",+ "target_file": "src/client.ts",+ "strength": 0.8,+ "frequency": 5,+ "last_date": "2026-04-10",+ },+ ],+ "package_deps": [+ {+ "source_repo": "frontend",+ "target_repo": "backend",+ "source_manifest": "package.json",+ "kind": "npm",+ },+ ],+ },+ )contracts_path = tmp_path / "contracts.json"- _write_json(contracts_path, {- "version": 1,- "generated_at": "2026-04-12T12:00:00Z",- "contracts": [- {- "repo": "backend",- "contract_id": "http::GET::/api/users",- "contract_type": "http",- "role": "provider",- "file_path": "routes.py",- "symbol_name": "get_users",- "confidence": 0.85,- "service": None,- },- {- "repo": "frontend",- "contract_id": "http::GET::/api/users",- "contract_type": "http",- "role": "consumer",- "file_path": "client.ts",- "symbol_name": "fetchUsers",- "confidence": 0.75,- "service": None,- },- {- "repo": "backend",- "contract_id": "grpc::Auth/Login",- "contract_type": "grpc",- "role": "provider",- "file_path": "auth.py",- "symbol_name": "Login",- "confidence": 0.85,- "service": None,- },- ],- "contract_links": [- {- "contract_id": "http::GET::/api/users",- "contract_type": "http",- "match_type": "exact",- "confidence": 0.75,- "provider_repo": "backend",- "provider_file": "routes.py",- "provider_symbol": "get_users",- "consumer_repo": "frontend",- "consumer_file": "client.ts",- "consumer_symbol": "fetchUsers",- },- ],- })+ _write_json(+ contracts_path,+ {+ "version": 1,+ "generated_at": "2026-04-12T12:00:00Z",+ "contracts": [+ {+ "repo": "backend",+ "contract_id": "http::GET::/api/users",+ "contract_type": "http",+ "role": "provider",+ "file_path": "routes.py",+ "symbol_name": "get_users",+ "confidence": 0.85,+ "service": None,+ },+ {+ "repo": "frontend",+ "contract_id": "http::GET::/api/users",+ "contract_type": "http",+ "role": "consumer",+ "file_path": "client.ts",+ "symbol_name": "fetchUsers",+ "confidence": 0.75,+ "service": None,+ },+ {+ "repo": "backend",+ "contract_id": "grpc::Auth/Login",+ "contract_type": "grpc",+ "role": "provider",+ "file_path": "auth.py",+ "symbol_name": "Login",+ "confidence": 0.85,+ "service": None,+ },+ ],+ "contract_links": [+ {+ "contract_id": "http::GET::/api/users",+ "contract_type": "http",+ "match_type": "exact",+ "confidence": 0.75,+ "provider_repo": "backend",+ "provider_file": "routes.py",+ "provider_symbol": "get_users",+ "consumer_repo": "frontend",+ "consumer_file": "client.ts",+ "consumer_symbol": "fetchUsers",+ },+ ],+ },+ )return CrossRepoEnricher(cross_repo_path, contracts_path=contracts_path)@@ -534,8 +540,7 @@ class TestQueryRepoStats:)for idx, (is_hotspot, churn) in enumerate(rows):conn.execute(- "INSERT INTO git_metadata (id, is_hotspot, churn_percentile) "- "VALUES (?, ?, ?)",+ "INSERT INTO git_metadata (id, is_hotspot, churn_percentile) VALUES (?, ?, ?)",(f"src/f{idx}.py", is_hotspot, churn),)@@ -578,23 +583,60 @@ def _make_system_graph_enricher(tmp_path: Path) -> CrossRepoEnricher:from repowise.core.workspace.system_graph import build_system_graphcontracts = [- Contract(repo="backend", contract_id="http::GET::/api/users", contract_type="http",- role="provider", file_path="routes.py", symbol_name="get_users", confidence=0.85),- Contract(repo="frontend", contract_id="http::GET::/api/users", contract_type="http",- role="consumer", file_path="client.ts", symbol_name="fetchUsers", confidence=0.75),- Contract(repo="backend", contract_id="http::GET::/orphan", contract_type="http",- role="provider", file_path="routes.py", symbol_name="orphan", confidence=0.85),+ Contract(+ repo="backend",+ contract_id="http::GET::/api/users",+ contract_type="http",+ role="provider",+ file_path="routes.py",+ symbol_name="get_users",+ confidence=0.85,+ ),+ Contract(+ repo="frontend",+ contract_id="http::GET::/api/users",+ contract_type="http",+ role="consumer",+ file_path="client.ts",+ symbol_name="fetchUsers",+ confidence=0.75,+ ),+ Contract(+ repo="backend",+ contract_id="http::GET::/orphan",+ contract_type="http",+ role="provider",+ file_path="routes.py",+ symbol_name="orphan",+ confidence=0.85,+ ),]links = [- ContractLink(contract_id="http::GET::/api/users", contract_type="http", match_type="exact",- confidence=0.75, provider_repo="backend", provider_file="routes.py",- provider_symbol="get_users", provider_service=None, consumer_repo="frontend",- consumer_file="client.ts", consumer_symbol="fetchUsers", consumer_service=None),+ ContractLink(+ contract_id="http::GET::/api/users",+ contract_type="http",+ match_type="exact",+ confidence=0.75,+ provider_repo="backend",+ provider_file="routes.py",+ provider_symbol="get_users",+ provider_service=None,+ consumer_repo="frontend",+ consumer_file="client.ts",+ consumer_symbol="fetchUsers",+ consumer_service=None,+ ),]- overlay = CrossRepoOverlay(package_deps=[- CrossRepoPackageDep(source_repo="frontend", target_repo="backend",- source_manifest="package.json", kind="npm_local_path"),- ])+ overlay = CrossRepoOverlay(+ package_deps=[+ CrossRepoPackageDep(+ source_repo="frontend",+ target_repo="backend",+ source_manifest="package.json",+ kind="npm_local_path",+ ),+ ]+ )graph = build_system_graph(contracts, links, overlay, {}, generated_at="t")_write_json(tmp_path / "system_graph.json", graph.to_dict())@@ -714,3 +756,96 @@ class TestGetDiagnostics:assert data["total_links"] == 1assert len(data["orphan_providers"]) == 1assert data["orphan_providers"][0]["contract_id"] == "http::GET::/orphan"+++# ---------------------------------------------------------------------------+# GET /api/workspace/breaking-changes+# ---------------------------------------------------------------------------+++def _make_breaking_enricher(tmp_path: Path) -> CrossRepoEnricher:+ """Enricher backed by a real, core-built breaking-change report artifact."""+ from repowise.core.workspace.breaking_change import detect_breaking_changes+ from repowise.core.workspace.contracts import Contract, ContractLink, ContractStore++ prev = ContractStore(+ contracts=[+ Contract(+ repo="backend",+ contract_id="http::GET::/api/users",+ contract_type="http",+ role="provider",+ file_path="routes.py",+ symbol_name="get_users",+ confidence=0.85,+ ),+ ],+ contract_links=[+ ContractLink(+ contract_id="http::GET::/api/users",+ contract_type="http",+ match_type="exact",+ confidence=0.75,+ provider_repo="backend",+ provider_file="routes.py",+ provider_symbol="get_users",+ provider_service=None,+ consumer_repo="frontend",+ consumer_file="client.ts",+ consumer_symbol="fetchUsers",+ consumer_service=None,+ ),+ ],+ )+ report = detect_breaking_changes(prev, ContractStore(), generated_at="t")+ _write_json(tmp_path / "breaking_changes.json", report.to_dict())+ return CrossRepoEnricher(+ tmp_path / "cross_repo_edges.json",+ breaking_changes_path=tmp_path / "breaking_changes.json",+ )+++class TestGetBreakingChanges:+ @pytest.mark.asyncio+ async def test_not_workspace_mode(self) -> None:+ app = _make_workspace_app()+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/breaking-changes")+ assert resp.status_code == 404++ @pytest.mark.asyncio+ async def test_empty_when_no_report(self) -> None:+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=None)+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/breaking-changes")+ assert resp.status_code == 200+ assert resp.json()["changes"] == []++ @pytest.mark.asyncio+ async def test_reports_removed_endpoint_with_consumer(self, tmp_path: Path) -> None:+ enricher = _make_breaking_enricher(tmp_path)+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/breaking-changes")+ assert resp.status_code == 200+ data = resp.json()+ assert data["breaking_count"] == 1+ assert data["changes"][0]["kind"] == "removed_endpoint"+ assert data["changes"][0]["impacted_consumers"][0]["repo"] == "frontend"+ assert data["impacted_repos"] == ["frontend"]++ @pytest.mark.asyncio+ async def test_filter_by_repo_recomputes_rollups(self, tmp_path: Path) -> None:+ enricher = _make_breaking_enricher(tmp_path)+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/breaking-changes", params={"repo": "nope"})+ assert resp.status_code == 200+ data = resp.json()+ assert data["changes"] == []+ assert data["total"] == 0+ assert data["impacted_repos"] == []diff --git a/tests/unit/workspace/test_breaking_change.py b/tests/unit/workspace/test_breaking_change.pynew file mode 100644index 000000000..14cf01131--- /dev/null+++ b/tests/unit/workspace/test_breaking_change.py@@ -0,0 +1,289 @@+"""Tests for the breaking-change guard — diff rules, impact, negatives, IO.++The negative cases (added optional field, widened set, brand-new endpoint) are+the load-bearing ones: the guard must stay silent on non-breaking changes.+"""++from __future__ import annotations++from repowise.core.workspace.breaking_change import (+ SEVERITY_BREAKING,+ SEVERITY_WARNING,+ BreakingChangeReport,+ detect_breaking_changes,+ load_breaking_change_report,+ run_breaking_change_detection,+ save_breaking_change_report,+)+from repowise.core.workspace.contract_schema import ContractSchema, SchemaField+from repowise.core.workspace.contracts import Contract, ContractLink, ContractStore++# ---------------------------------------------------------------------------+# Fixture builders+# ---------------------------------------------------------------------------+++def _provider(cid, ctype="http", repo="api", file="src/handler.py", service=None, schema=None):+ return Contract(+ repo=repo,+ contract_id=cid,+ contract_type=ctype,+ role="provider",+ file_path=file,+ symbol_name="handler",+ confidence=0.9,+ service=service,+ schema=schema,+ )+++def _link(cid, ctype="http", c_repo="web", c_file="src/client.ts", c_service=None, match="exact"):+ return ContractLink(+ contract_id=cid,+ contract_type=ctype,+ match_type=match,+ confidence=0.9,+ provider_repo="api",+ provider_file="src/handler.py",+ provider_symbol="handler",+ provider_service=None,+ consumer_repo=c_repo,+ consumer_file=c_file,+ consumer_symbol="call",+ consumer_service=c_service,+ )+++def _store(contracts=None, links=None):+ return ContractStore(contracts=contracts or [], contract_links=links or [])+++def _schema(request=None, response=None):+ return ContractSchema(+ source="proto", request_fields=request or [], response_fields=response or []+ )+++def _kinds(report):+ return sorted(c.kind for c in report.changes)+++# ---------------------------------------------------------------------------+# Contract-level rule: removed endpoint+# ---------------------------------------------------------------------------+++def test_removed_endpoint_with_consumer_is_breaking():+ prev = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ report = detect_breaking_changes(prev, _store())+ assert _kinds(report) == ["removed_endpoint"]+ change = report.changes[0]+ assert change.severity == SEVERITY_BREAKING+ assert change.contract_type == "http"+ assert [c.file for c in change.impacted_consumers] == ["src/client.ts"]+ assert change.impacted_consumers[0].node_id == "web"+++def test_removed_endpoint_without_consumer_still_flags_but_no_impact():+ prev = _store([_provider("http::GET::/internal")]) # no links+ report = detect_breaking_changes(prev, _store())+ assert _kinds(report) == ["removed_endpoint"]+ assert report.changes[0].impacted_consumers == []+++def test_added_endpoint_does_not_flag():+ curr = _store([_provider("http::GET::/new")], [_link("http::GET::/new")])+ report = detect_breaking_changes(_store(), curr)+ assert report.changes == []+++def test_unchanged_endpoint_does_not_flag():+ store = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ # Distinct objects, same content.+ other = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ report = detect_breaking_changes(store, other)+ assert report.changes == []+++def test_grpc_removed_method_is_breaking():+ prev = _store(+ [_provider("grpc::auth.AuthService/Login", ctype="grpc")],+ [_link("grpc::auth.AuthService/Login", ctype="grpc")],+ )+ report = detect_breaking_changes(prev, _store())+ assert _kinds(report) == ["removed_endpoint"]+++# ---------------------------------------------------------------------------+# Field-level rules+# ---------------------------------------------------------------------------+++def test_added_optional_field_does_not_flag():+ prev_s = _schema(request=[SchemaField("a", "string", number=1)])+ curr_s = _schema(+ request=[SchemaField("a", "string", number=1), SchemaField("b", "int32", number=2)]+ )+ prev = _store([_provider("grpc::S/M", "grpc", schema=prev_s)])+ curr = _store([_provider("grpc::S/M", "grpc", schema=curr_s)])+ report = detect_breaking_changes(prev, curr)+ assert report.changes == []+++def test_added_required_field_is_breaking():+ prev_s = _schema(request=[SchemaField("a", "string", number=1)])+ curr_s = _schema(+ request=[+ SchemaField("a", "string", number=1),+ SchemaField("b", "int32", number=2, required=True),+ ]+ )+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ assert _kinds(report) == ["field_required"]+ assert report.changes[0].field_name == "b"+ assert report.changes[0].severity == SEVERITY_BREAKING+++def test_optional_to_required_is_breaking():+ prev_s = _schema(request=[SchemaField("a", "string", number=1)])+ curr_s = _schema(request=[SchemaField("a", "string", number=1, required=True)])+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ assert _kinds(report) == ["field_required"]+++def test_removed_response_field_is_breaking_request_field_is_warning():+ prev_s = _schema(+ request=[SchemaField("a", "string", number=1)],+ response=[SchemaField("r", "string", number=1)],+ )+ curr_s = _schema(request=[], response=[])+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ by_sev = {c.severity for c in report.changes}+ assert _kinds(report) == ["removed_field", "removed_field"]+ assert by_sev == {SEVERITY_BREAKING, SEVERITY_WARNING}+++def test_field_type_change_is_breaking():+ prev_s = _schema(request=[SchemaField("a", "string", number=1)])+ curr_s = _schema(request=[SchemaField("a", "int64", number=1)])+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ assert _kinds(report) == ["field_type_changed"]+ assert report.changes[0].old_value == "string"+ assert report.changes[0].new_value == "int64"+++def test_field_number_change_is_breaking():+ prev_s = _schema(request=[SchemaField("a", "string", number=1)])+ curr_s = _schema(request=[SchemaField("a", "string", number=7)])+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ assert _kinds(report) == ["field_number_changed"]+++def test_no_schema_means_no_field_rules():+ # Both sides present but neither carries a schema → only contract-level rules.+ prev = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ curr = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ report = detect_breaking_changes(prev, curr)+ assert report.changes == []+++# ---------------------------------------------------------------------------+# Impact resolution + rollups+# ---------------------------------------------------------------------------+++def test_impact_resolves_service_node_id_from_consumer_service():+ prev = _store(+ [_provider("http::GET::/users")],+ [+ _link(+ "http::GET::/users", c_repo="web", c_file="apps/store/c.ts", c_service="apps/store"+ )+ ],+ )+ report = detect_breaking_changes(prev, _store())+ consumer = report.changes[0].impacted_consumers[0]+ assert consumer.node_id == "web::apps/store"+ assert consumer.service == "apps/store"+++def test_report_rollups_count_breaking_and_impact():+ prev = _store(+ [_provider("http::GET::/a"), _provider("http::GET::/b")],+ [_link("http::GET::/a", c_repo="web"), _link("http::GET::/b", c_repo="mobile")],+ )+ report = detect_breaking_changes(prev, _store())+ d = report.to_dict()+ assert d["total"] == 2+ assert d["breaking_count"] == 2+ assert d["warning_count"] == 0+ assert d["impacted_repos"] == ["mobile", "web"]+ assert d["total_impacted_consumers"] == 2+++def test_changes_sorted_breaking_before_warning():+ prev_s = _schema(+ request=[SchemaField("req", "string", number=1)],+ response=[SchemaField("res", "string", number=1)],+ )+ curr_s = _schema(request=[], response=[]) # removed both → 1 warning + 1 breaking+ report = detect_breaking_changes(+ _store([_provider("grpc::S/M", "grpc", schema=prev_s)]),+ _store([_provider("grpc::S/M", "grpc", schema=curr_s)]),+ )+ assert report.changes[0].severity == SEVERITY_BREAKING+ assert report.changes[-1].severity == SEVERITY_WARNING+++def test_empty_stores_produce_empty_report():+ report = detect_breaking_changes(_store(), _store())+ assert not report.has_changes+ assert report.to_dict()["total"] == 0+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------+++def test_report_round_trips_through_dict():+ prev = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ report = detect_breaking_changes(prev, _store(), generated_at="2026-06-19T00:00:00Z")+ restored = BreakingChangeReport.from_dict(report.to_dict())+ assert restored.generated_at == "2026-06-19T00:00:00Z"+ assert _kinds(restored) == _kinds(report)+ assert restored.changes[0].impacted_consumers[0].node_id == "web"+ assert restored.changes[0].provider_node_id == "api"+++def test_save_and_load_report(tmp_path):+ prev = _store([_provider("http::GET::/users")], [_link("http::GET::/users")])+ run_breaking_change_detection(tmp_path, prev, _store())+ assert (tmp_path / ".repowise-workspace" / "breaking_changes.json").is_file()+ loaded = load_breaking_change_report(tmp_path)+ assert loaded is not None+ assert _kinds(loaded) == ["removed_endpoint"]+++def test_load_missing_report_returns_none(tmp_path):+ assert load_breaking_change_report(tmp_path) is None+++def test_save_returns_path(tmp_path):+ out = save_breaking_change_report(BreakingChangeReport(), tmp_path)+ assert out.name == "breaking_changes.json"diff --git a/tests/unit/workspace/test_proto_schema.py b/tests/unit/workspace/test_proto_schema.pynew file mode 100644index 000000000..c6f201a89--- /dev/null+++ b/tests/unit/workspace/test_proto_schema.py@@ -0,0 +1,117 @@+"""Tests for proto message-field schema capture and Contract schema round-trip."""++from __future__ import annotations++from repowise.core.workspace.contract_schema import ContractSchema, SchemaField+from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.grpc.proto import ProtoDialect, _parse_proto_file++PROTO = """+syntax = "proto3";+package auth;++message LoginRequest {+ string username = 1;+ int32 attempts = 2;+ repeated string scopes = 3;+ message Nested { string ignore_me = 9; }+ oneof credential { string password = 4; string token = 5; }+}++message LoginResponse {+ string session = 1;+}++service AuthService {+ rpc Login (LoginRequest) returns (auth.LoginResponse);+}+"""+++def test_parse_messages_captures_fields_and_excludes_nested():+ _pkg, _svcs, messages = _parse_proto_file(PROTO)+ req = {f.name: f for f in messages["LoginRequest"]}+ assert set(req) == {"username", "attempts", "scopes", "password", "token"}+ assert req["username"].type == "string"+ assert req["username"].number == 1+ assert req["scopes"].repeated is True+ # The nested message's field must not leak into the parent.+ assert "ignore_me" not in req+ # Nested message is still parsed as its own entry.+ assert [f.name for f in messages["Nested"]] == ["ignore_me"]+++def test_parse_rpc_resolves_request_and_response_types():+ _pkg, svcs, _messages = _parse_proto_file(PROTO)+ method = svcs[0].methods[0]+ assert method.name == "Login"+ assert method.request_type == "LoginRequest"+ # Qualified response type (auth.LoginResponse) is preserved.+ assert method.response_type == "auth.LoginResponse"+++def test_dialect_attaches_schema_to_contract():+ ctx = ScanContext(repo_alias="api", rel_path="proto/auth.proto", suffix=".proto", content=PROTO)+ contracts = ProtoDialect().extract(ctx)+ assert len(contracts) == 1+ contract = contracts[0]+ assert contract.contract_id == "grpc::auth.AuthService/Login"+ assert contract.schema is not None+ assert {f.name for f in contract.schema.request_fields} == {+ "username",+ "attempts",+ "scopes",+ "password",+ "token",+ }+ # Qualified response type resolves to the bare message name's fields.+ assert [f.name for f in contract.schema.response_fields] == ["session"]+++def test_no_message_means_no_schema():+ proto = """+ syntax = "proto3";+ service Bare { rpc Ping (Missing) returns (AlsoMissing); }+ """+ ctx = ScanContext(repo_alias="api", rel_path="bare.proto", suffix=".proto", content=proto)+ contract = ProtoDialect().extract(ctx)[0]+ # Unknown messages → empty schema → not attached.+ assert contract.schema is None+++def test_contract_schema_round_trip():+ schema = ContractSchema(+ source="proto",+ request_fields=[SchemaField("a", "string", required=True, number=1)],+ response_fields=[SchemaField("b", "int32", number=2, repeated=True)],+ )+ contract = Contract(+ repo="api",+ contract_id="grpc::S/M",+ contract_type="grpc",+ role="provider",+ file_path="s.proto",+ symbol_name="S/M",+ confidence=0.85,+ schema=schema,+ )+ restored = Contract.from_dict(contract.to_dict())+ assert restored.schema is not None+ assert restored.schema.request_fields[0].required is True+ assert restored.schema.request_fields[0].number == 1+ assert restored.schema.response_fields[0].repeated is True+++def test_contract_without_schema_omits_key():+ contract = Contract(+ repo="api",+ contract_id="http::GET::/x",+ contract_type="http",+ role="provider",+ file_path="r.py",+ symbol_name="h",+ confidence=0.9,+ )+ assert "schema" not in contract.to_dict()+ assert Contract.from_dict(contract.to_dict()).schema is None