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
Cross-repo blast radius and change risk (#513)
Raghav Chamadiya6203a0bfca61
diff --git a/docs/CHANGE_RISK.md b/docs/CHANGE_RISK.mdindex a7328f713..dafec1dbe 100644--- a/docs/CHANGE_RISK.md+++ b/docs/CHANGE_RISK.md@@ -78,3 +78,24 @@ ship; the runtime stays deterministic and zero-LLM.Recalibrate via `repowise-bench/health-defect/jit_calibration.py`; the constantslive in `packages/core/src/repowise/core/analysis/change_risk/model.py`.++## Cross-repo change risk (workspace mode)++In a workspace, a change rarely stops at the repo boundary. When `get_risk` is+called in PR mode (`changed_files`), its `directive` block gains two cross-repo+fields derived from the [system graph](WORKSPACES.md#system-graph):++- `will_break_consumers` — services in *other* repos that structurally depend on+ the changed repo (a contract or package import). These are the consumers most+ likely to break.+- `missing_cross_repo_cochanges` — services in other repos that historically+ co-change with the changed repo but aren't in the diff. Correlation, not a+ call, so they read as "may drift," not "will break."++The same reachability powers the `get_blast_radius` MCP tool, the+`GET /api/workspace/blast-radius` endpoint, and the Live System Map's+blast-radius ripple. Structural edges outweigh behavioral co-change in the+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 full+model.diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex ed1b42481..e2977ba36 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -27,6 +27,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport| `get_why` | Architectural decisions | Before structural changes || `get_dead_code` | Unreachable code | Cleanup tasks || `get_health` | Code-health biomarker scores | Before refactoring — find the worst files |+| `get_blast_radius` | Cross-repo downstream impact (workspace only) | Before changing a service other repos consume |---@@ -211,6 +212,11 @@ Modification risk assessment for files or a set of changed files.**Returns:** Per-file risk score (0–10), hotspot status, dependent count, co-change partners, blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.+When `changed_files` is passed, the response leads with a `directive` block. In workspace mode that directive also carries the cross-repo fallout of the changed repo:++- `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.+**When to use:** Before modifying files — especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.**Example calls:**@@ -222,6 +228,31 @@ get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])---+## `get_blast_radius`++*(Workspace mode only.)* Cross-repo downstream impact: if you change this service, what breaks across the other repos?++**Parameters:**++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `targets` | list[string] | Yes | Node ids (`repo` or `repo::service/path`) or repo aliases |+| `max_depth` | int | No | Reachability depth (1–8, default 3) |+| `include_behavioral` | bool | No | Include co-change (behavioral) edges (default true) |++**Returns:** The impacted services ranked by impact `score`, each with `distance` (hops), `structural` (a real dependency vs co-change only), and the edge kinds that carried the impact; plus `impacted_repos`, `structural_count` / `behavioral_count`, `total_impacted`, and any `unresolved_targets`.++**When to use:** Before changing a high-fan-out provider — see who consumes it across repo boundaries. Structural impact (`will break`) outweighs behavioral co-change (`may drift`). Reads the same system graph the [Live System Map](WORKSPACES.md#live-system-map) renders.++**Example calls:**++```+get_blast_radius(targets=["backend"])+get_blast_radius(targets=["mono::services/auth"], max_depth=2, include_behavioral=false)+```++---+## `get_why`Architectural decision intelligence. Three modes depending on parameters.@@ -323,12 +354,13 @@ The MCP server automatically enriches responses with cross-repo intelligence:- **Co-change partners** from other repos surfaced in `get_context` and `get_risk`- **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---## Proactive Hooks (Complementary)-In addition to the 9 MCP tools, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:+In addition to the MCP tools above, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:- **Claude Code PostToolUse** — broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.- **Codex SessionStart/UserPromptSubmit** — Codex receives concise Repowise MCP workflow guidance when a session or prompt starts.diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.mdindex 958815288..b04db279a 100644--- a/docs/WORKSPACES.md+++ b/docs/WORKSPACES.md@@ -284,12 +284,31 @@ The map appears once the workspace has at least two indexed repositories with de---+## Cross-Repo Blast Radius++Blast radius answers a single question: **if I change this service, what downstream services and repos break?** It walks the [system graph](#system-graph) *against* its edge direction — a `consumer → provider` edge means changing the provider impacts the consumer — and returns every reachable service ranked by an impact score.++Two edge classes are weighted and labelled distinctly:++- **Structural** edges (http / grpc / event / package) assert a real dependency — a contract or an import. They propagate impact at full weight and surface as **will break**.+- **Behavioral** co-change edges only assert that two files historically *changed together*. They are correlation, not a call, so they propagate at half weight (one named constant, `BEHAVIORAL_EDGE_WEIGHT`) and surface as **may drift**.++Each impacted service carries its `distance` (hops from the change) and `score` (0-1, with distance decay and the behavioral weighting baked in). Nearer, structural impact ranks highest.++Use it three ways:++- **REST** — `GET /api/workspace/blast-radius?target=<node-id-or-repo>&max_depth=3&include_behavioral=true`. `target` is a node id (`repo` or `repo::service/path`) or a repo alias (expands to all its services).+- **MCP** — the `get_blast_radius` tool (workspace mode) gives an agent the impacted set before it touches a high-fan-out provider. The `get_risk` PR-mode directive also gains `will_break_consumers` and `missing_cross_repo_cochanges` so a diff in one repo flags its cross-repo fallout.+- **System Map** — pick a service in the **Blast radius** control above the map; the reachable set ripples (highlighted, the rest dimmed, badges grading intensity), and a side panel lists the impacted services. Click any impacted service to walk the impact outward from there.++---+## MCP IntegrationWorkspace init automatically registers MCP servers with Claude Desktop and Claude Code. The MCP server is workspace-aware:- **Default repo context** — queries go to the primary repo unless you specify otherwise-- **Cross-repo tools** — MCP tools can query across repos and return enriched context with co-change and contract data+- **Cross-repo tools** — MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius))- **Repo parameter** — most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace---diff --git a/packages/core/src/repowise/core/workspace/blast_radius.py b/packages/core/src/repowise/core/workspace/blast_radius.pynew file mode 100644index 000000000..2acc47e45--- /dev/null+++ b/packages/core/src/repowise/core/workspace/blast_radius.py@@ -0,0 +1,298 @@+"""Cross-repo blast radius — reachability over the system graph.++Answers "if I change this service, what downstream services and repos are+affected?" by traversing the Phase 1 :class:`SystemGraph` *against* its edge+direction: an edge ``source → target`` means *source depends on / calls+target*, so changing ``target`` puts ``source`` at risk. We follow those+reverse links outward from the changed node(s) to find everything that could+break.++Two edge classes are weighted and labeled distinctly (the D5 honesty rule):++* **Structural** edges (http / grpc / event / package / db) assert a real+ dependency — a contract or an import. Impact propagates at full weight.+* **Behavioral** co-change edges only assert that two files *changed together*+ in history; they are correlation, not a call. They propagate impact at+ :data:`BEHAVIORAL_EDGE_WEIGHT` — the single knob that tunes "change together"+ against "call each other" in the ranking.++The cross-repo vocabulary mirrors the single-repo blast radius+(``packages/core/src/repowise/core/analysis/pr_blast.py`` + ``blast-radius.ts``):+impacted items are ranked by an impact ``score`` and carry a ``distance`` (hops+from the change). This module is pure and I/O-free — callers load the persisted+``system_graph.json`` (via :func:`load_system_graph` or the MCP enricher) and+hand the :class:`SystemGraph` in.+"""++from __future__ import annotations++from collections import defaultdict+from dataclasses import dataclass, field+from typing import Any++from repowise.core.workspace.system_graph import SystemEdge, SystemGraph++# ---------------------------------------------------------------------------+# Constants (single source of truth)+# ---------------------------------------------------------------------------++#: Default reachability depth. Cross-repo systems are shallow (a request rarely+#: crosses more than a handful of service boundaries), so a small default keeps+#: the impact set honest — distant, weakly-connected services are noise.+DEFAULT_MAX_DEPTH = 3++#: Hard ceiling on traversal depth so a pathological graph can't run away.+MAX_DEPTH_LIMIT = 8++#: Behavioral (co-change) edges assert correlation, not a real call, so they+#: propagate impact at a fraction of a structural edge's weight. This is the one+#: knob that separates "these change together" from "these call each other" in+#: the reachability ranking — keep it the only place that distinction is tuned.+BEHAVIORAL_EDGE_WEIGHT = 0.5++#: Each additional hop attenuates the propagated impact: a service two calls away+#: is less likely to actually break than a direct consumer. Applied once per hop,+#: so a node at distance *d* carries roughly ``DISTANCE_DECAY ** d`` of the base.+DISTANCE_DECAY = 0.6++#: Cap on the number of impacted nodes returned. ``total_impacted`` always+#: reflects the true count; this only bounds the returned list (and the artifact)+#: so a high-fan-out hub can't bloat a response. Mirrors the trimming convention+#: in the single-repo risk tool.+MAX_IMPACTED = 100+++# ---------------------------------------------------------------------------+# Data models+# ---------------------------------------------------------------------------+++@dataclass+class ImpactedNode:+ """A service reachable from the change, with its ranked impact."""++ id: str # system-graph node id+ repo: str+ name: str+ kind: str # service | frontend | worker | library | external+ distance: int # hops from the nearest changed node (1 = direct dependent)+ score: float # 0-1 ranked impact (distance decay + behavioral weight baked in)+ structural: bool # reachable via an all-structural path (a real dependency)+ edge_kinds: list[str] = field(default_factory=list) # kinds carrying impact in++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "repo": self.repo,+ "name": self.name,+ "kind": self.kind,+ "distance": self.distance,+ "score": self.score,+ "structural": self.structural,+ "edge_kinds": self.edge_kinds,+ }+++@dataclass+class CrossRepoBlastRadius:+ """The reachable impact set for one or more changed services."""++ targets: list[str] # resolved node ids the traversal started from+ target_repos: list[str] # distinct repos of the targets+ impacted: list[ImpactedNode] # ranked, capped at MAX_IMPACTED+ impacted_repos: list[str] # distinct repos in the impact set (excl. targets)+ structural_count: int # impacted nodes reachable via a real dependency+ behavioral_count: int # impacted nodes reachable only via co-change+ max_distance: int # deepest hop reached+ total_impacted: int # true count before MAX_IMPACTED capping+ unresolved_targets: list[str] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "targets": self.targets,+ "target_repos": self.target_repos,+ "impacted": [n.to_dict() for n in self.impacted],+ "impacted_repos": self.impacted_repos,+ "structural_count": self.structural_count,+ "behavioral_count": self.behavioral_count,+ "max_distance": self.max_distance,+ "total_impacted": self.total_impacted,+ "unresolved_targets": self.unresolved_targets,+ }+++# ---------------------------------------------------------------------------+# Target resolution+# ---------------------------------------------------------------------------+++def resolve_targets(graph: SystemGraph, raw_targets: list[str]) -> tuple[list[str], list[str]]:+ """Map caller-supplied target strings to system-graph node ids.++ Accepts an exact node id (``"repo"`` or ``"repo::service/path"``) or a repo+ alias (expands to every node in that repo). Returns ``(resolved, unresolved)``+ where ``resolved`` is a sorted, de-duplicated list of node ids.+ """+ node_ids = {n.id for n in graph.nodes}+ nodes_by_repo: dict[str, list[str]] = defaultdict(list)+ for n in graph.nodes:+ nodes_by_repo[n.repo].append(n.id)++ resolved: set[str] = set()+ unresolved: list[str] = []+ for raw in raw_targets:+ if raw in node_ids:+ resolved.add(raw)+ elif raw in nodes_by_repo:+ resolved.update(nodes_by_repo[raw])+ else:+ unresolved.append(raw)+ return sorted(resolved), unresolved+++# ---------------------------------------------------------------------------+# Reachability (pure)+# ---------------------------------------------------------------------------+++@dataclass+class _Accum:+ """Per-node accumulator during the outward traversal."""++ distance: int+ score: float+ structural: bool # any all-structural path reaches it+ edge_kinds: set[str]+++def _build_impact_adjacency(+ edges: list[SystemEdge],+) -> dict[str, list[tuple[str, SystemEdge]]]:+ """Adjacency in *impact* direction: changed-node id → (dependent id, edge).++ Structural edge ``source → target`` (source depends on target): changing+ ``target`` impacts ``source``, so we add ``target → source``. Behavioral+ co-change edges are symmetric, so both endpoints impact each other.+ """+ adj: dict[str, list[tuple[str, SystemEdge]]] = defaultdict(list)+ for e in edges:+ if e.structural:+ adj[e.target].append((e.source, e))+ else:+ adj[e.source].append((e.target, e))+ adj[e.target].append((e.source, e))+ return adj+++def cross_repo_blast_radius(+ graph: SystemGraph,+ targets: list[str],+ *,+ max_depth: int = DEFAULT_MAX_DEPTH,+ include_behavioral: bool = True,+) -> CrossRepoBlastRadius:+ """Compute the downstream impact set for *targets* over the system graph.++ Traverses reverse dependency edges outward from the resolved target nodes,+ ranking each reachable service by an impact ``score`` that bakes in distance+ decay and the structural/behavioral weighting. Cycle-safe (bounded by+ ``max_depth`` and convergent score relaxation) and pure.+ """+ depth = max(1, min(max_depth, MAX_DEPTH_LIMIT))+ resolved, unresolved = resolve_targets(graph, targets)++ nodes_by_id = {n.id: n for n in graph.nodes}+ target_set = set(resolved)+ target_repos = sorted({nodes_by_id[t].repo for t in resolved if t in nodes_by_id})++ if not resolved:+ return CrossRepoBlastRadius(+ targets=resolved,+ target_repos=target_repos,+ impacted=[],+ impacted_repos=[],+ structural_count=0,+ behavioral_count=0,+ max_distance=0,+ total_impacted=0,+ unresolved_targets=unresolved,+ )++ edges = graph.edges+ if not include_behavioral:+ edges = [e for e in edges if e.structural]+ adj = _build_impact_adjacency(edges)++ best: dict[str, _Accum] = {}+ # Frontier value per node: (propagated score, path-is-all-structural).+ frontier: dict[str, tuple[float, bool]] = {t: (1.0, True) for t in resolved}++ for hop in range(1, depth + 1):+ next_frontier: dict[str, tuple[float, bool]] = {}+ for src, (src_score, src_structural) in frontier.items():+ for dst, edge in adj.get(src, []):+ if dst in target_set:+ continue # never impact a changed node back onto itself+ factor = 1.0 if edge.structural else BEHAVIORAL_EDGE_WEIGHT+ cand_score = src_score * edge.confidence * factor * DISTANCE_DECAY+ if cand_score <= 0.0:+ continue+ path_structural = src_structural and edge.structural++ acc = best.get(dst)+ if acc is None:+ acc = _Accum(+ distance=hop,+ score=cand_score,+ structural=path_structural,+ edge_kinds={edge.kind},+ )+ best[dst] = acc+ else:+ acc.distance = min(acc.distance, hop)+ acc.score = max(acc.score, cand_score)+ acc.structural = acc.structural or path_structural+ acc.edge_kinds.add(edge.kind)++ # Only keep relaxing while the propagated score improves —+ # convergent, so cycles terminate well before max_depth.+ prev = next_frontier.get(dst)+ if prev is None or cand_score > prev[0]:+ next_frontier[dst] = (cand_score, path_structural)+ if not next_frontier:+ break+ frontier = next_frontier++ impacted = [+ ImpactedNode(+ id=nid,+ repo=nodes_by_id[nid].repo if nid in nodes_by_id else "",+ name=nodes_by_id[nid].name if nid in nodes_by_id else nid,+ kind=nodes_by_id[nid].kind if nid in nodes_by_id else "service",+ distance=acc.distance,+ score=round(acc.score, 4),+ structural=acc.structural,+ edge_kinds=sorted(acc.edge_kinds),+ )+ for nid, acc in best.items()+ ]+ # Rank: strongest impact first, then nearest, then stable by id.+ impacted.sort(key=lambda n: (-n.score, n.distance, n.id))++ total = len(impacted)+ structural_count = sum(1 for n in impacted if n.structural)+ behavioral_count = total - structural_count+ max_distance = max((n.distance for n in impacted), default=0)+ impacted_repos = sorted({n.repo for n in impacted if n.repo not in target_repos})++ return CrossRepoBlastRadius(+ targets=resolved,+ target_repos=target_repos,+ impacted=impacted[:MAX_IMPACTED],+ impacted_repos=impacted_repos,+ structural_count=structural_count,+ behavioral_count=behavioral_count,+ max_distance=max_distance,+ total_impacted=total,+ unresolved_targets=unresolved,+ )diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 304aef841..bf4b936ff 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -1,4 +1,4 @@-"""repowise MCP Server — 17 tools for AI coding assistants.+"""repowise MCP Server — 18 tools for AI coding assistants.Exposes the full repowise wiki as queryable tools via the MCP protocol.Supports stdio transport (Claude Code, Cursor, Cline), streamable HTTP, and@@ -38,6 +38,7 @@ from repowise.server.mcp_server._server import (run_mcp,)from repowise.server.mcp_server.tool_answer import get_answer+from repowise.server.mcp_server.tool_blast_radius import get_blast_radiusfrom repowise.server.mcp_server.tool_context import get_contextfrom repowise.server.mcp_server.tool_dead_code import get_dead_codefrom repowise.server.mcp_server.tool_health import get_health@@ -108,6 +109,7 @@ __all__ = ["_is_path","create_mcp_server","get_answer",+ "get_blast_radius","get_context","get_dead_code","get_health",diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.pynew file mode 100644index 000000000..582f4866b--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py@@ -0,0 +1,99 @@+"""MCP Tool: get_blast_radius — cross-repo downstream impact (workspace only).++Answers "if I change this service, what breaks across the other repos?" by+traversing the workspace system graph. Structural dependencies (contracts,+package deps) are ranked above behavioral co-change. Mirrors the single-repo+change-risk vocabulary (``get_risk`` PR-mode, ``blast-radius.ts``): impacted+services carry an impact ``score`` and a ``distance``.+"""++from __future__ import annotations++from typing import Any++from repowise.core.registry import mcp_tool_registry as mcp+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._helpers import _is_workspace_mode+from repowise.server.mcp_server._meta import build_meta as _build_meta++#: How many impacted services the MCP response carries inline. The full set is+#: available via the REST endpoint / the map; here we keep the agent payload+#: tight and report the true count in ``total_impacted``.+_MCP_IMPACTED_LIMIT = 25+++async def get_blast_radius(+ targets: list[str],+ max_depth: int = 3,+ include_behavioral: bool = True,+) -> dict[str, Any]:+ """Cross-repo blast radius — what downstream services break if you change this.++ Workspace-only. Traverses the system graph from the given service(s) and+ returns the impacted services across every repo, ranked by impact score.+ Structural edges (http / grpc / event / package) outweigh behavioral+ co-change. Call before changing a high-fan-out provider to see who consumes+ it across repo boundaries.++ Args:+ targets: node ids ("repo" or "repo::service/path") or repo aliases.+ max_depth: reachability depth (1-8, default 3).+ include_behavioral: include co-change (behavioral) edges (default true).+ """+ if not _is_workspace_mode():+ return {+ "error": "get_blast_radius is only available in workspace mode.",+ "_meta": _build_meta(),+ }++ enricher = _state._cross_repo_enricher+ raw = enricher.get_system_graph() if enricher is not None else None+ if not raw:+ return {+ "error": (+ "No system graph is available yet. Run `repowise update --workspace` "+ "to build cross-repo relationships."+ ),+ "_meta": _build_meta(),+ }++ from repowise.core.workspace.blast_radius import cross_repo_blast_radius+ from repowise.core.workspace.system_graph import SystemGraph++ graph = SystemGraph.from_dict(raw)+ result = cross_repo_blast_radius(+ graph,+ targets,+ max_depth=max(1, min(max_depth, 8)),+ include_behavioral=include_behavioral,+ )++ impacted = [n.to_dict() for n in result.impacted[:_MCP_IMPACTED_LIMIT]]++ summary = (+ f"Changing {len(result.targets)} service(s) impacts {result.total_impacted} "+ f"downstream service(s) across {len(result.impacted_repos)} other repo(s): "+ f"{result.structural_count} via a real dependency, "+ f"{result.behavioral_count} via co-change only."+ )+ if not result.targets:+ summary = (+ f"None of the requested targets matched a service in the graph: "+ f"{result.unresolved_targets}."+ )++ return {+ "targets": result.targets,+ "target_repos": result.target_repos,+ "impacted": impacted,+ "impacted_truncated": max(0, len(result.impacted) - len(impacted)),+ "impacted_repos": result.impacted_repos,+ "structural_count": result.structural_count,+ "behavioral_count": result.behavioral_count,+ "max_distance": result.max_distance,+ "total_impacted": result.total_impacted,+ "unresolved_targets": result.unresolved_targets,+ "summary": summary,+ "_meta": _build_meta(),+ }diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex e4d07dc73..0e22129e0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -408,6 +408,57 @@ def _as_path(entry: Any) -> str | None:return None+#: Caps on the cross-repo directive lists — kept tight so the PR directive stays+#: glanceable. The full impact set is on get_blast_radius / the REST endpoint.+_XR_WILL_BREAK_LIMIT = 5+_XR_COCHANGE_LIMIT = 3+++def _cross_repo_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Cross-repo half of the PR directive: downstream services in other repos.++ Resolves the changed repo to its system-graph nodes and ranks reachable+ services in OTHER repos by impact, splitting structural (``will_break``) from+ behavioral co-change (``missing_cochanges``). Returns two empty lists when+ not in workspace mode or no system graph is available. Never raises.+ """+ will_break_consumers: list[dict[str, Any]] = []+ missing_cross_repo_cochanges: list[dict[str, Any]] = []+ try:+ if not _is_workspace_mode():+ return will_break_consumers, missing_cross_repo_cochanges+ enricher = _state._cross_repo_enricher+ raw_graph = enricher.get_system_graph() if enricher is not None else None+ if not raw_graph:+ return will_break_consumers, missing_cross_repo_cochanges++ from repowise.core.workspace.blast_radius import cross_repo_blast_radius+ from repowise.core.workspace.system_graph import SystemGraph++ result = cross_repo_blast_radius(SystemGraph.from_dict(raw_graph), [repo_alias])+ for n in result.impacted:+ if n.repo == repo_alias:+ continue # cross-repo only — intra-repo impact is the single-repo blast+ if n.structural:+ if len(will_break_consumers) < _XR_WILL_BREAK_LIMIT:+ will_break_consumers.append(+ {+ "repo": n.repo,+ "service": n.name,+ "distance": n.distance,+ "score": n.score,+ "via": n.edge_kinds,+ }+ )+ elif len(missing_cross_repo_cochanges) < _XR_COCHANGE_LIMIT:+ missing_cross_repo_cochanges.append(+ {"repo": n.repo, "service": n.name, "score": n.score}+ )+ except Exception:+ return [], []+ return will_break_consumers, missing_cross_repo_cochanges++def _trim_blast_lists(pr_blast_radius: dict[str, Any],exclude_spec: Any,@@ -765,10 +816,27 @@ async def get_risk(gov_count = len(governance_risk)gov_suffix = f" {gov_count} governance risk(s) detected." if gov_count > 0 else ""++ # Cross-repo directive (workspace mode only). Resolve the changed repo to+ # its system-graph nodes and walk reachability to find downstream+ # services in OTHER repos — split structural (will break) from behavioral+ # (co-change only). Repo-scoped: it answers "can this PR's repo break+ # something across a repo boundary?" using the same reachability the map+ # and get_blast_radius use.+ will_break_consumers, missing_cross_repo_cochanges = _cross_repo_directive(ctx.alias)+ xr_suffix = ""+ if will_break_consumers or missing_cross_repo_cochanges:+ xr_suffix = (+ f" Cross-repo: {len(will_break_consumers)} consumer service(s) may break, "+ f"{len(missing_cross_repo_cochanges)} cross-repo co-changer(s) missing."+ )+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,"governance_risk": governance_risk,"overall_risk_score": trimmed_blast.get("overall_risk_score"),"summary": (@@ -776,7 +844,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}"+ f"{gov_suffix}{xr_suffix}"),}else:diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex 3dbf2302b..b9d39d9d5 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -20,6 +20,7 @@ from repowise.server.deps import (verify_api_key,)from repowise.server.schemas import (+ WorkspaceBlastRadiusResponse,WorkspaceCoChangeEntry,WorkspaceCoChangesResponse,WorkspaceContractEntry,@@ -527,6 +528,48 @@ async def get_diagnostics(return WorkspaceExtractionDiagnostics(**diagnostics)+# ---------------------------------------------------------------------------+# GET /api/workspace/blast-radius+# ---------------------------------------------------------------------------++[email protected]("/blast-radius", response_model=WorkspaceBlastRadiusResponse)+async def get_blast_radius(+ ws_config=Depends(get_workspace_config),+ enricher=Depends(get_cross_repo_enricher),+ target: list[str] = Query(+ ...,+ description="One or more node ids ('repo' or 'repo::service/path') or repo aliases.",+ ),+ max_depth: int = Query(3, ge=1, le=8, description="Reachability depth."),+ include_behavioral: bool = Query(+ True, description="Include co-change (behavioral) edges in reachability."+ ),+):+ """Cross-repo blast radius — downstream services impacted by a change.++ Traverses the system graph against its edge direction (a consumer→provider+ edge means changing the provider impacts the consumer), ranking impacted+ services by an impact score that weights structural dependencies above+ behavioral co-change. Reads the same ``system_graph.json`` artifact the map+ renders. Returns an empty result (not 404) when no graph is built yet.+ """+ _require_workspace(ws_config)++ from repowise.core.workspace.blast_radius import cross_repo_blast_radius+ from repowise.core.workspace.system_graph import SystemGraph++ raw = enricher.get_system_graph() if enricher is not None else None+ if not raw:+ return WorkspaceBlastRadiusResponse(targets=[], unresolved_targets=list(target))++ graph = SystemGraph.from_dict(raw)+ result = cross_repo_blast_radius(+ graph, target, max_depth=max_depth, include_behavioral=include_behavioral+ )+ return WorkspaceBlastRadiusResponse(**result.to_dict())++# ---------------------------------------------------------------------------# POST /api/workspace/sync# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex cbcc8916c..fb528d95e 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -155,6 +155,7 @@ from .ui_helpers import (WebhookResponse,)from .workspace import (+ WorkspaceBlastRadiusResponse,WorkspaceCoChangeEntry,WorkspaceCoChangesResponse,WorkspaceContractEntry,@@ -166,6 +167,7 @@ from .workspace import (WorkspaceGraphEdge,WorkspaceGraphNode,WorkspaceGraphResponse,+ WorkspaceImpactedNode,WorkspaceOrphanProvider,WorkspaceRepoDiagnostics,WorkspaceRepoEntry,@@ -293,6 +295,7 @@ __all__ = ["TransitiveEntry","WebhookResponse","WorkspaceCoChangeEntry",+ "WorkspaceBlastRadiusResponse","WorkspaceCoChangesResponse","WorkspaceContractEntry","WorkspaceContractLinkEntry",@@ -303,6 +306,7 @@ __all__ = ["WorkspaceGraphEdge","WorkspaceGraphNode","WorkspaceGraphResponse",+ "WorkspaceImpactedNode","WorkspaceOrphanProvider","WorkspaceRepoDiagnostics","WorkspaceRepoEntry",diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 7fed37484..22e5a3267 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -213,3 +213,32 @@ class WorkspaceSystemGraphResponse(BaseModel):nodes: list[WorkspaceSystemNode] = []edges: list[WorkspaceSystemEdge] = []diagnostics: WorkspaceExtractionDiagnostics = WorkspaceExtractionDiagnostics()+++# ---------------------------------------------------------------------------+# Cross-repo blast radius (reachability over the system graph)+# Mirrors repowise.core.workspace.blast_radius.+# ---------------------------------------------------------------------------+++class WorkspaceImpactedNode(BaseModel):+ id: str+ repo: str+ name: str+ kind: str = "service"+ distance: int+ score: float+ structural: bool+ edge_kinds: list[str] = []+++class WorkspaceBlastRadiusResponse(BaseModel):+ targets: list[str] = []+ target_repos: list[str] = []+ impacted: list[WorkspaceImpactedNode] = []+ impacted_repos: list[str] = []+ structural_count: int = 0+ behavioral_count: int = 0+ max_distance: int = 0+ total_impacted: int = 0+ unresolved_targets: list[str] = []diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex 5dfd54d9d..fbd36d04b 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -161,3 +161,47 @@ export interface ExtractionDiagnostics {unmatched_by_reason: Record<string, number>;orphan_providers: OrphanProvider[];}++// ---------------------------------------------------------------------------+// Cross-repo blast radius — reachability over the system graph. "If I change+// this service, what downstream services and repos break?" Mirrors the+// single-repo blast-radius vocabulary (`blast-radius.ts`): impacted items carry+// an impact `score` and a `distance`. Mirrors `repowise.core.workspace.blast_radius`.+// ---------------------------------------------------------------------------++/** A service reachable from the change, with its ranked impact. */+export interface ImpactedNode {+ /** System-graph node id (`"repo"` or `"repo::service/path"`). */+ id: string;+ repo: string;+ name: string;+ kind: "service" | "frontend" | "worker" | "library" | "external";+ /** Hops from the nearest changed node (1 = a direct dependent). */+ distance: number;+ /** 0-1 ranked impact, with distance decay and behavioral weighting baked in. */+ score: number;+ /** Reachable via an all-structural path (a real dependency, not co-change). */+ structural: boolean;+ /** Distinct edge kinds that carried impact into this node. */+ edge_kinds: SystemEdgeKind[];+}++export interface CrossRepoBlastRadius {+ /** Resolved node ids the traversal started from. */+ targets: string[];+ /** Distinct repos of the targets. */+ target_repos: string[];+ /** Ranked impact set (strongest first), capped server-side. */+ impacted: ImpactedNode[];+ /** Distinct repos in the impact set, excluding the target repos. */+ impacted_repos: string[];+ /** Impacted nodes reachable via a real dependency. */+ structural_count: number;+ /** Impacted nodes reachable only via co-change correlation. */+ behavioral_count: number;+ max_distance: number;+ /** True count before the server-side cap. */+ total_impacted: number;+ /** Target strings that matched no node or repo. */+ unresolved_targets: string[];+}diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.tsindex 161b02291..362725c92 100644--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts@@ -10,6 +10,11 @@ import {} from "../../src/workspace/system-map/edge-kinds";import { nodeKindStyle, NODE_KIND_ORDER } from "../../src/workspace/system-map/node-kinds";import { resolveEdgeOverlay, resolveNodeOverlay } from "../../src/workspace/system-map/types";+import {+ buildBlastRadiusOverlay,+ impactBadgeTone,+} from "../../src/workspace/system-map/blast-radius";+import type { CrossRepoBlastRadius } from "@repowise-dev/types";function node(id: string, repo: string, over: Partial<SystemNode> = {}): SystemNode {return {@@ -201,3 +206,70 @@ describe("overlay resolution", () => {expect(resolveEdgeOverlay({ dimEdgeIds: new Set(["e"]) }, "e")).toEqual({ highlighted: false, dimmed: true });});});++describe("buildBlastRadiusOverlay", () => {+ function result(over: Partial<CrossRepoBlastRadius> = {}): CrossRepoBlastRadius {+ return {+ targets: ["db"],+ target_repos: ["db"],+ impacted: [],+ impacted_repos: [],+ structural_count: 0,+ behavioral_count: 0,+ max_distance: 0,+ total_impacted: 0,+ unresolved_targets: [],+ ...over,+ };+ }++ const g = graph(+ [node("db", "db"), node("api", "api"), node("web", "web"), node("idle", "idle")],+ [edge("api", "db"), edge("web", "api"), edge("web", "idle")],+ );++ it("highlights the focus set and dims everything else", () => {+ const overlay = buildBlastRadiusOverlay(+ g,+ result({+ impacted: [+ { id: "api", repo: "api", name: "api", kind: "service", distance: 1, score: 0.5, structural: true, edge_kinds: ["http"] },+ { id: "web", repo: "web", name: "web", kind: "service", distance: 2, score: 0.2, structural: true, edge_kinds: ["http"] },+ ],+ }),+ );+ expect([...(overlay.highlightNodeIds ?? [])].sort()).toEqual(["api", "db", "web"]);+ // The unrelated node is dimmed.+ expect(overlay.dimNodeIds?.has("idle")).toBe(true);+ expect(overlay.dimNodeIds?.has("api")).toBe(false);+ // Edges fully inside focus are highlighted; the rest dimmed.+ expect(overlay.highlightEdgeIds?.has("api->db")).toBe(true);+ expect(overlay.highlightEdgeIds?.has("web->api")).toBe(true);+ expect(overlay.dimEdgeIds?.has("web->idle")).toBe(true);+ });++ it("badges the source and grades impacted nodes by intensity", () => {+ const overlay = buildBlastRadiusOverlay(+ g,+ result({+ impacted: [+ { id: "api", repo: "api", name: "api", kind: "service", distance: 1, score: 0.5, structural: true, edge_kinds: ["http"] },+ ],+ }),+ );+ expect(overlay.nodeBadges?.db).toEqual({ label: "source", tone: "info" });+ expect(overlay.nodeBadges?.api).toEqual({ label: "d1", tone: "danger" });+ });++ it("returns an empty overlay when nothing is in focus", () => {+ const overlay = buildBlastRadiusOverlay(g, result({ targets: [], impacted: [] }));+ expect(overlay).toEqual({});+ });++ it("grades intensity: structural-near danger, structural-far info, behavioral info", () => {+ expect(impactBadgeTone(1, true)).toBe("danger");+ expect(impactBadgeTone(2, true)).toBe("warning");+ expect(impactBadgeTone(3, true)).toBe("info");+ expect(impactBadgeTone(1, false)).toBe("info");+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsxindex f06d899ba..a44b6828a 100644--- a/packages/ui/__tests__/workspace/system-map.test.tsx+++ b/packages/ui/__tests__/workspace/system-map.test.tsx@@ -1,10 +1,11 @@import { describe, it, expect, vi, beforeAll } from "vitest";import { render, screen, fireEvent } from "@testing-library/react";-import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";+import type { CrossRepoBlastRadius, SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";import { SystemMap } from "../../src/workspace/system-map/system-map";import { SystemMapFilters } from "../../src/workspace/system-map/system-map-filters";import { 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";// jsdom has no layout engine → stub ResizeObserver so React Flow can mount.beforeAll(() => {@@ -167,3 +168,75 @@ describe("SystemMapInspector", () => {expect(container).toBeEmptyDOMElement();});});++describe("SystemMapBlastPanel", () => {+ function result(over: Partial<CrossRepoBlastRadius> = {}): CrossRepoBlastRadius {+ return {+ targets: ["db"],+ target_repos: ["db"],+ impacted: [],+ impacted_repos: [],+ structural_count: 0,+ behavioral_count: 0,+ max_distance: 0,+ total_impacted: 0,+ unresolved_targets: [],+ ...over,+ };+ }++ it("renders nothing without a result", () => {+ const { container } = render(+ <SystemMapBlastPanel result={null} onSelectTarget={() => {}} onClear={() => {}} />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("lists impacted services split by structural vs behavioral", () => {+ render(+ <SystemMapBlastPanel+ result={result({+ impacted: [+ { id: "api", repo: "api", name: "api", kind: "service", distance: 1, score: 0.5, structural: true, edge_kinds: ["http"] },+ { id: "ops", repo: "ops", name: "ops", kind: "service", distance: 1, score: 0.2, structural: false, edge_kinds: ["co_change"] },+ ],+ impacted_repos: ["api", "ops"],+ structural_count: 1,+ behavioral_count: 1,+ total_impacted: 2,+ })}+ onSelectTarget={() => {}}+ onClear={() => {}}+ />,+ );+ expect(screen.getByText(/will break/i)).toBeInTheDocument();+ expect(screen.getByText(/may drift/i)).toBeInTheDocument();+ expect(screen.getByText("api")).toBeInTheDocument();+ expect(screen.getByText(/2 impacted across 2 other repo/i)).toBeInTheDocument();+ });++ it("re-targets when an impacted service is clicked", () => {+ const onSelectTarget = vi.fn();+ render(+ <SystemMapBlastPanel+ result={result({+ impacted: [+ { id: "api", repo: "api", name: "api", kind: "service", distance: 1, score: 0.5, structural: true, edge_kinds: ["http"] },+ ],+ total_impacted: 1,+ })}+ onSelectTarget={onSelectTarget}+ onClear={() => {}}+ />,+ );+ fireEvent.click(screen.getByText("api"));+ expect(onSelectTarget).toHaveBeenCalledWith("api");+ });++ it("shows the no-downstream state honestly", () => {+ render(+ <SystemMapBlastPanel result={result()} onSelectTarget={() => {}} onClear={() => {}} />,+ );+ expect(screen.getByText(/nothing downstream/i)).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/workspace/system-map/blast-radius.ts b/packages/ui/src/workspace/system-map/blast-radius.tsnew file mode 100644index 000000000..b7ef5d4cf--- /dev/null+++ b/packages/ui/src/workspace/system-map/blast-radius.ts@@ -0,0 +1,70 @@+/**+ * Blast-radius ripple — turns a `CrossRepoBlastRadius` (computed by the core /+ * REST layer) into a `SystemMapOverlay` the Live System Map renders without any+ * component change. The target service(s) and everything reachable from them are+ * highlighted; the rest of the map is dimmed; impacted nodes carry a small badge+ * whose tone encodes intensity (nearer + structural = stronger). This is the+ * Phase 3 attach point promised by the Phase 2 overlay API.+ */++import type { CrossRepoBlastRadius, SystemGraph } from "@repowise-dev/types";+import type { BadgeTone, SystemMapBadge, SystemMapOverlay } from "./types";++/**+ * Intensity tone for an impacted node. Structural impact (a real dependency)+ * reads stronger than behavioral co-change, and nearer hops stronger than+ * distant ones — a calm gradient rather than a single alarm colour.+ */+export function impactBadgeTone(distance: number, structural: boolean): BadgeTone {+ if (!structural) return "info";+ if (distance <= 1) return "danger";+ if (distance === 2) return "warning";+ return "info";+}++/**+ * Build the ripple overlay for a blast-radius result. Returns an empty overlay+ * (no dimming, no highlight) when nothing is in focus, so passing it through is+ * always safe.+ */+export function buildBlastRadiusOverlay(+ graph: SystemGraph,+ result: CrossRepoBlastRadius,+): SystemMapOverlay {+ const targets = new Set(result.targets);+ const focus = new Set<string>(targets);+ for (const n of result.impacted) focus.add(n.id);++ if (focus.size === 0) return {};++ const dimNodeIds = new Set<string>();+ for (const node of graph.nodes) {+ if (!focus.has(node.id)) dimNodeIds.add(node.id);+ }++ const nodeBadges: Record<string, SystemMapBadge> = {};+ for (const t of targets) nodeBadges[t] = { label: "source", tone: "info" };+ for (const n of result.impacted) {+ nodeBadges[n.id] = {+ label: `d${n.distance}`,+ tone: impactBadgeTone(n.distance, n.structural),+ };+ }++ // Highlight edges fully inside the focus set (the ripple's paths); dim the+ // rest so the impacted subgraph reads cleanly.+ const highlightEdgeIds = new Set<string>();+ const dimEdgeIds = new Set<string>();+ for (const edge of graph.edges) {+ if (focus.has(edge.source) && focus.has(edge.target)) highlightEdgeIds.add(edge.id);+ else dimEdgeIds.add(edge.id);+ }++ return {+ highlightNodeIds: focus,+ dimNodeIds,+ nodeBadges,+ highlightEdgeIds,+ dimEdgeIds,+ };+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex cc3cbf4fe..98924bd98 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -8,6 +8,8 @@ export { SystemMap, type SystemMapProps } from "./system-map";export { SystemMapLegend } from "./system-map-legend";export { SystemMapFilters, type SystemMapFiltersProps } from "./system-map-filters";export { SystemMapInspector, type SystemMapInspectorProps } from "./system-map-inspector";+export { SystemMapBlastPanel, type SystemMapBlastPanelProps } from "./system-map-blast-panel";+export { buildBlastRadiusOverlay, impactBadgeTone } from "./blast-radius";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-blast-panel.tsx b/packages/ui/src/workspace/system-map/system-map-blast-panel.tsxnew file mode 100644index 000000000..f73e6b107--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-blast-panel.tsx@@ -0,0 +1,198 @@+"use client";++/**+ * Blast-radius results rail for the Live System Map. Given a+ * `CrossRepoBlastRadius`, it lists the impacted services (strongest first),+ * split into structural (a real dependency will break) and behavioral (only+ * co-changes historically). Clicking a service re-targets the ripple from it,+ * so you can walk the impact outward. Pure presentation — the host owns the+ * fetch and passes the result in; the ripple itself rides the map's overlay prop.+ */++import { X, Zap } from "lucide-react";+import type { CrossRepoBlastRadius, ImpactedNode } from "@repowise-dev/types";+import { impactBadgeTone } from "./blast-radius";++export interface SystemMapBlastPanelProps {+ result: CrossRepoBlastRadius | null;+ loading?: boolean;+ /** Re-target the ripple from an impacted service (walk the impact outward). */+ onSelectTarget: (nodeId: string) => void;+ onClear: () => void;+}++const panelStyle: React.CSSProperties = {+ position: "absolute",+ top: 12,+ left: 12,+ width: 290,+ 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 toneColor(tone: "danger" | "warning" | "info"): string {+ switch (tone) {+ case "danger":+ return "var(--color-risk-high)";+ case "warning":+ return "var(--color-warning)";+ default:+ return "var(--color-accent-fill)";+ }+}++function ImpactedRow({+ node,+ onSelect,+}: {+ node: ImpactedNode;+ onSelect: (id: string) => void;+}) {+ const tone = impactBadgeTone(node.distance, node.structural);+ const color = toneColor(tone);+ return (+ <button+ type="button"+ onClick={() => onSelect(node.id)}+ title={`Re-target the ripple from ${node.name}`}+ style={{+ display: "flex",+ alignItems: "center",+ gap: 8,+ width: "100%",+ textAlign: "left",+ padding: "6px 12px",+ cursor: "pointer",+ background: "transparent",+ borderBottom: "1px solid var(--color-border-subtle)",+ }}+ >+ <span+ title={`distance ${node.distance}`}+ style={{+ flexShrink: 0,+ width: 22,+ textAlign: "center",+ 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,+ padding: "1px 0",+ }}+ >+ d{node.distance}+ </span>+ <span style={{ flex: 1, minWidth: 0 }}>+ <span style={{ color: "var(--color-text-primary)", display: "block", fontWeight: 600 }}>+ {node.name}+ </span>+ <span style={{ color: "var(--color-text-tertiary)", fontSize: 10 }}>+ {node.repo} · {node.edge_kinds.join(", ")}+ </span>+ </span>+ <span style={{ flexShrink: 0, color: "var(--color-text-tertiary)", fontVariantNumeric: "tabular-nums" }}>+ {node.score.toFixed(2)}+ </span>+ </button>+ );+}++function Section({+ title,+ nodes,+ onSelect,+}: {+ title: string;+ nodes: ImpactedNode[];+ onSelect: (id: string) => void;+}) {+ if (nodes.length === 0) return null;+ return (+ <div>+ <div+ style={{+ padding: "6px 12px",+ fontSize: 10,+ fontWeight: 700,+ letterSpacing: 0.5,+ textTransform: "uppercase",+ color: "var(--color-text-tertiary)",+ background: "var(--color-bg-surface)",+ }}+ >+ {title} · {nodes.length}+ </div>+ {nodes.map((n) => (+ <ImpactedRow key={n.id} node={n} onSelect={onSelect} />+ ))}+ </div>+ );+}++export function SystemMapBlastPanel({+ result,+ loading,+ onSelectTarget,+ onClear,+}: SystemMapBlastPanelProps) {+ if (!result) return null;++ const structural = result.impacted.filter((n) => n.structural);+ const behavioral = result.impacted.filter((n) => !n.structural);+ const sourceLabel = result.targets.join(", ") || result.unresolved_targets.join(", ");++ 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 }}>+ <Zap size={13} style={{ color: "var(--color-accent-primary)" }} />+ <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--color-text-tertiary)" }}>+ Blast radius+ </span>+ </span>+ <button type="button" onClick={onClear} aria-label="Clear blast radius" 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-primary)", fontWeight: 600, wordBreak: "break-word" }}>+ {sourceLabel || "—"}+ </div>+ <div style={{ color: "var(--color-text-tertiary)", fontSize: 11, marginTop: 2 }}>+ {loading+ ? "Computing impact…"+ : `${result.total_impacted} impacted across ${result.impacted_repos.length} other repo(s)`}+ </div>+ </div>++ {!loading && result.impacted.length === 0 && (+ <div style={{ padding: "12px", color: "var(--color-text-tertiary)" }}>+ {result.targets.length === 0+ ? "No matching service in the graph."+ : "Nothing downstream — no other service depends on this one."}+ </div>+ )}++ <Section title="Will break (dependency)" nodes={structural} onSelect={onSelectTarget} />+ <Section title="May drift (co-change)" nodes={behavioral} onSelect={onSelectTarget} />+ </div>+ );+}diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex bc77bd45d..36bc480e9 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -1,14 +1,20 @@"use client";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { useRouter } from "next/navigation";-import { Waypoints, Boxes, ArrowLeftRight, Share2 } from "lucide-react";-import { SystemMap, type RepoHealth } from "@repowise-dev/ui/workspace/system-map";+import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap } from "lucide-react";+import {+ SystemMap,+ SystemMapBlastPanel,+ buildBlastRadiusOverlay,+ type RepoHealth,+} from "@repowise-dev/ui/workspace/system-map";import { StatCard } from "@repowise-dev/ui/shared/stat-card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import {useWorkspaceSystemGraph,useWorkspaceGraph,+ useWorkspaceBlastRadius,} from "@/lib/hooks/use-workspace";export default function SystemMapPage() {@@ -16,6 +22,15 @@ export default function SystemMapPage() {const { data: graph, isLoading, error } = useWorkspaceSystemGraph();const { data: repoGraph } = useWorkspaceGraph();+ // Blast-radius target. Driven by a page-level picker (and re-targetable from+ // the impacted panel) so the map component stays unchanged — the ripple rides+ // its existing `overlay` prop.+ const [blastTarget, setBlastTarget] = useState<string | null>(null);+ const [includeBehavioral, setIncludeBehavioral] = useState(true);+ const { data: blast, isLoading: blastLoading } = useWorkspaceBlastRadius(blastTarget, {+ includeBehavioral,+ });+// 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.@@ -27,6 +42,11 @@ export default function SystemMapPage() {return m;}, [repoGraph]);+ const overlay = useMemo(() => {+ if (!graph || !blast) return undefined;+ return buildBlastRadiusOverlay(graph, blast);+ }, [graph, blast]);+const diag = graph?.diagnostics;const serviceCount = graph?.nodes.length ?? 0;const edgeCount = graph?.edges.length ?? 0;@@ -70,18 +90,69 @@ export default function SystemMapPage() {/></div>- <div className="rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-300px)] min-h-[560px]">+ {/* Blast-radius controls: pick a service to see what breaks downstream. */}+ <div className="flex flex-wrap items-center gap-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-2.5">+ <span className="inline-flex items-center gap-1.5 text-sm font-medium text-[var(--color-text-primary)]">+ <Zap className="h-4 w-4 text-[var(--color-accent-primary)]" />+ Blast radius+ </span>+ <select+ aria-label="Blast-radius source service"+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2 py-1 text-sm text-[var(--color-text-primary)]"+ value={blastTarget ?? ""}+ onChange={(e) => setBlastTarget(e.target.value || null)}+ disabled={!graph || serviceCount === 0}+ >+ <option value="">Select a service…</option>+ {(graph?.nodes ?? [])+ .slice()+ .sort((a, b) => a.id.localeCompare(b.id))+ .map((n) => (+ <option key={n.id} value={n.id}>+ {n.service_path ? `${n.repo} · ${n.name}` : n.name}+ </option>+ ))}+ </select>+ <label className="inline-flex items-center gap-1.5 text-sm text-[var(--color-text-secondary)]">+ <input+ type="checkbox"+ checked={includeBehavioral}+ onChange={(e) => setIncludeBehavioral(e.target.checked)}+ />+ Include co-change+ </label>+ {blastTarget && (+ <button+ type="button"+ onClick={() => setBlastTarget(null)}+ className="ml-auto text-sm text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ Clear+ </button>+ )}+ </div>++ <div className="relative rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-360px)] min-h-[560px]">{isLoading ? (<div className="p-4 h-full"><Skeleton className="h-full w-full" /></div>) : (- <SystemMap- graph={graph}- error={error ?? null}- healthByRepo={healthByRepo}- onOpenContract={() => router.push("/workspace/contracts")}- />+ <>+ <SystemMap+ graph={graph}+ error={error ?? null}+ healthByRepo={healthByRepo}+ {...(overlay ? { overlay } : {})}+ onOpenContract={() => router.push("/workspace/contracts")}+ />+ <SystemMapBlastPanel+ result={blast}+ loading={blastLoading}+ onSelectTarget={setBlastTarget}+ onClear={() => setBlastTarget(null)}+ />+ </>)}</div></div>diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.tsindex f89b2d912..bf18f45a3 100644--- a/packages/web/src/lib/api/types/workspace.ts+++ b/packages/web/src/lib/api/types/workspace.ts@@ -142,12 +142,14 @@ export type {UnmatchedConsumer,UnmatchedReason,OrphanProvider,+ ImpactedNode,+ CrossRepoBlastRadius,} from "@repowise-dev/types";-import type { SystemGraph, ExtractionDiagnostics } from "@repowise-dev/types";+import type { SystemGraph, CrossRepoBlastRadius } from "@repowise-dev/types";/** `GET /api/workspace/system-graph` — the full service-granular system graph. */export type WorkspaceSystemGraphResponse = SystemGraph;-/** `GET /api/workspace/diagnostics` — extraction diagnostics standalone. */-export type WorkspaceDiagnosticsResponse = ExtractionDiagnostics;+/** `GET /api/workspace/blast-radius` — cross-repo downstream impact set. */+export type WorkspaceBlastRadiusResponse = CrossRepoBlastRadius;diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.tsindex 1d5ed77fe..6721eda98 100644--- a/packages/web/src/lib/api/workspace.ts+++ b/packages/web/src/lib/api/workspace.ts@@ -6,7 +6,7 @@ import type {WorkspaceGraphResponse,WorkspaceSyncResponse,WorkspaceSystemGraphResponse,- WorkspaceDiagnosticsResponse,+ WorkspaceBlastRadiusResponse,} from "./types";export async function getWorkspace(@@ -62,15 +62,20 @@ export async function getWorkspaceSystemGraph();}-/** Extraction diagnostics (providers/consumers, unmatched-by-reason, orphans). */-export async function getWorkspaceDiagnostics(- fetchOptions?: RequestInit,-): Promise<WorkspaceDiagnosticsResponse> {- return apiGet<WorkspaceDiagnosticsResponse>(- "/api/workspace/diagnostics",- undefined,- fetchOptions,- );+/**+ * Cross-repo blast radius from a service node (or repo alias): the downstream+ * services impacted if it changes, ranked by impact. Reads the same system+ * graph the map renders.+ */+export async function getWorkspaceBlastRadius(opts: {+ target: string;+ maxDepth?: number;+ includeBehavioral?: boolean;+}): Promise<WorkspaceBlastRadiusResponse> {+ const params: Record<string, string | number | boolean> = { target: opts.target };+ if (opts.maxDepth != null) params.max_depth = opts.maxDepth;+ if (opts.includeBehavioral != null) params.include_behavioral = opts.includeBehavioral;+ return apiGet<WorkspaceBlastRadiusResponse>("/api/workspace/blast-radius", params);}/**diff --git a/packages/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.tsindex e8eade8a6..f0a7906b9 100644--- a/packages/web/src/lib/hooks/use-workspace.ts+++ b/packages/web/src/lib/hooks/use-workspace.ts@@ -6,16 +6,16 @@ import {getWorkspaceContracts,getWorkspaceCoChanges,getWorkspaceSystemGraph,- getWorkspaceDiagnostics,getWorkspaceGraph,+ getWorkspaceBlastRadius,} from "@/lib/api/workspace";import type {WorkspaceResponse,WorkspaceContractsResponse,WorkspaceCoChangesResponse,WorkspaceSystemGraphResponse,- WorkspaceDiagnosticsResponse,WorkspaceGraphResponse,+ WorkspaceBlastRadiusResponse,} from "@/lib/api/types";export function useWorkspace() {@@ -69,10 +69,25 @@ export function useWorkspaceSystemGraph() {return { data: data ?? null, isLoading, error };}-export function useWorkspaceDiagnostics() {- const { data, error, isLoading } = useSWR<WorkspaceDiagnosticsResponse>(- "workspace:diagnostics",- () => getWorkspaceDiagnostics(),+/**+ * Cross-repo blast radius for a selected target service. Pass ``null`` to skip+ * the request (no target selected).+ */+export function useWorkspaceBlastRadius(+ target: string | null,+ opts?: { maxDepth?: number; includeBehavioral?: boolean },+) {+ const key = target+ ? `workspace:blast-radius:${target}:${opts?.maxDepth ?? ""}:${opts?.includeBehavioral ?? ""}`+ : null;+ const { data, error, isLoading } = useSWR<WorkspaceBlastRadiusResponse>(+ key,+ () =>+ getWorkspaceBlastRadius({+ target: target as string,+ ...(opts?.maxDepth != null ? { maxDepth: opts.maxDepth } : {}),+ ...(opts?.includeBehavioral != null ? { includeBehavioral: opts.includeBehavioral } : {}),+ }),{ revalidateOnFocus: false },);return { data: data ?? null, isLoading, error };diff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pynew file mode 100644index 000000000..78457e348--- /dev/null+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -0,0 +1,132 @@+"""Tests for the get_blast_radius MCP tool (workspace-only cross-repo impact)."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from repowise.core.workspace.contracts import Contract, ContractLink+from repowise.core.workspace.cross_repo import CrossRepoOverlay, CrossRepoPackageDep+from repowise.core.workspace.system_graph import build_system_graph+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._enrichment import CrossRepoEnricher+from repowise.server.mcp_server.tool_blast_radius import get_blast_radius+++def _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),+ ]+ 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),+ ]+ 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(+ tmp_path / "cross_repo_edges.json",+ system_graph_path=tmp_path / "system_graph.json",+ )+++def workspace_state(tmp_path: Path):+ """Enable workspace mode with a real system-graph-backed enricher."""+ prev_registry = _state._registry+ prev_enricher = _state._cross_repo_enricher+ _state._registry = object() # _is_workspace_mode() only checks for non-None+ _state._cross_repo_enricher = _enricher_with_graph(tmp_path)+ try:+ yield+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+++async def test_requires_workspace_mode():+ prev = _state._registry+ _state._registry = None+ try:+ result = await get_blast_radius(["backend"])+ finally:+ _state._registry = prev+ assert "error" in result+ assert "workspace mode" in result["error"]+++async def test_changing_provider_impacts_consumer(workspace_state):+ result = await get_blast_radius(["backend"])+ ids = {n["id"] for n in result["impacted"]}+ assert "frontend" in ids+ assert result["structural_count"] >= 1+ assert "frontend" in result["impacted_repos"]+ assert "backend" in result["targets"]+ assert "downstream service" in result["summary"]+++async def test_unresolved_target(workspace_state):+ result = await get_blast_radius(["ghost"])+ assert result["unresolved_targets"] == ["ghost"]+ assert result["impacted"] == []+ assert result["targets"] == []+++async def test_leaf_consumer_has_no_downstream(workspace_state):+ result = await get_blast_radius(["frontend"])+ # frontend only consumes / depends; nothing downstream of it.+ assert result["impacted"] == []+ assert result["total_impacted"] == 0+++def test_cross_repo_directive_splits_structural_and_behavioral(workspace_state):+ """The get_risk PR-mode cross-repo helper reports other-repo consumers."""+ from repowise.server.mcp_server.tool_risk import _cross_repo_directive++ will_break, missing_cochanges = _cross_repo_directive("backend")+ # frontend consumes backend (http) and package-depends on it → structural.+ assert any(e["repo"] == "frontend" for e in will_break)+ assert all("service" in e and "score" in e for e in will_break)+ # No cross-repo co-change edges in this fixture.+ assert missing_cochanges == []+++def test_cross_repo_directive_empty_outside_workspace():+ from repowise.server.mcp_server import _state+ from repowise.server.mcp_server.tool_risk import _cross_repo_directive++ prev = _state._registry+ _state._registry = None+ try:+ assert _cross_repo_directive("backend") == ([], [])+ finally:+ _state._registry = prev+++async def test_no_system_graph_returns_error(tmp_path: Path):+ prev_registry = _state._registry+ prev_enricher = _state._cross_repo_enricher+ _state._registry = object()+ _state._cross_repo_enricher = CrossRepoEnricher(tmp_path / "cross_repo_edges.json")+ try:+ result = await get_blast_radius(["backend"])+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher+ assert "error" in result+ assert "system graph" in result["error"]diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex 059fe8a05..dc153fe7e 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -637,6 +637,60 @@ class TestGetSystemGraph:assert ("frontend", "backend", "package") in kinds # dependent -> dependency+class TestGetBlastRadius:+ @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/blast-radius", params={"target": "backend"})+ assert resp.status_code == 404++ @pytest.mark.asyncio+ async def test_empty_when_no_graph(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/blast-radius", params={"target": "backend"})+ assert resp.status_code == 200+ data = resp.json()+ assert data["impacted"] == []+ assert data["unresolved_targets"] == ["backend"]++ @pytest.mark.asyncio+ async def test_changing_provider_impacts_consumer(self, tmp_path: Path) -> None:+ enricher = _make_system_graph_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/blast-radius", params={"target": "backend"})+ assert resp.status_code == 200+ data = resp.json()+ # frontend consumes backend's http contract AND package-depends on it.+ assert "frontend" in {n["id"] for n in data["impacted"]}+ assert data["structural_count"] >= 1+ assert "frontend" in data["impacted_repos"]++ @pytest.mark.asyncio+ async def test_unresolved_target_reported(self, tmp_path: Path) -> None:+ enricher = _make_system_graph_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/blast-radius", params={"target": "ghost"})+ data = resp.json()+ assert data["unresolved_targets"] == ["ghost"]+ assert data["impacted"] == []++ @pytest.mark.asyncio+ async def test_target_is_required(self) -> None:+ app = _make_workspace_app(ws_config=_make_ws_config())+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/blast-radius")+ assert resp.status_code == 422 # missing required query param++class TestGetDiagnostics:@pytest.mark.asyncioasync def test_not_workspace_mode(self) -> None:diff --git a/tests/unit/workspace/test_blast_radius.py b/tests/unit/workspace/test_blast_radius.pynew file mode 100644index 000000000..60885fcdc--- /dev/null+++ b/tests/unit/workspace/test_blast_radius.py@@ -0,0 +1,347 @@+"""Tests for cross-repo blast radius — reachability, weighting, ranking, cycles."""++from __future__ import annotations++from repowise.core.workspace.blast_radius import (+ BEHAVIORAL_EDGE_WEIGHT,+ MAX_IMPACTED,+ CrossRepoBlastRadius,+ cross_repo_blast_radius,+ resolve_targets,+)+from repowise.core.workspace.contracts import Contract, ContractLink+from repowise.core.workspace.cross_repo import (+ CrossRepoCoChange,+ CrossRepoOverlay,+ CrossRepoPackageDep,+)+from repowise.core.workspace.extractors.service_boundary import ServiceBoundary+from repowise.core.workspace.system_graph import build_system_graph+++# ---------------------------------------------------------------------------+# Fixture builders (mirror test_system_graph.py)+# ---------------------------------------------------------------------------+++def _provider(repo, cid, ctype="http", file="src/handler.py") -> Contract:+ return Contract(+ repo=repo,+ contract_id=cid,+ contract_type=ctype,+ role="provider",+ file_path=file,+ symbol_name="handler",+ confidence=0.9,+ )+++def _consumer(repo, cid, ctype="http", file="src/client.py") -> Contract:+ return Contract(+ repo=repo,+ contract_id=cid,+ contract_type=ctype,+ role="consumer",+ file_path=file,+ symbol_name="call",+ confidence=0.8,+ )+++def _link(cid, p_repo, p_file, c_repo, c_file, ctype="http", match="exact", conf=0.9) -> ContractLink:+ return ContractLink(+ contract_id=cid,+ contract_type=ctype,+ match_type=match,+ confidence=conf,+ provider_repo=p_repo,+ provider_file=p_file,+ provider_symbol="handler",+ provider_service=None,+ consumer_repo=c_repo,+ consumer_file=c_file,+ consumer_symbol="call",+ consumer_service=None,+ )+++def _cochange(s_repo, s_file, t_repo, t_file, strength=0.7) -> CrossRepoCoChange:+ return CrossRepoCoChange(+ source_repo=s_repo,+ source_file=s_file,+ target_repo=t_repo,+ target_file=t_file,+ strength=strength,+ frequency=4,+ last_date="2026-06-01",+ )+++def _chain_graph():+ """web --http--> api --http--> db (each consumer calls the next provider).++ Edge direction is consumer→provider, so changing ``db`` impacts ``api`` then+ ``web`` walking the reverse links.+ """+ contracts = [+ _provider("db", "http::GET::/rows", file="db/h.py"),+ _consumer("api", "http::GET::/rows", file="api/c.py"),+ _provider("api", "http::GET::/users", file="api/h.py"),+ _consumer("web", "http::GET::/users", file="web/c.py"),+ ]+ links = [+ _link("http::GET::/rows", "db", "db/h.py", "api", "api/c.py"),+ _link("http::GET::/users", "api", "api/h.py", "web", "web/c.py"),+ ]+ return build_system_graph(contracts, links, CrossRepoOverlay(), {})+++# ---------------------------------------------------------------------------+# Target resolution+# ---------------------------------------------------------------------------+++def test_resolve_target_by_node_id():+ graph = _chain_graph()+ resolved, unresolved = resolve_targets(graph, ["api"])+ assert resolved == ["api"]+ assert unresolved == []+++def test_resolve_target_by_repo_alias_expands_to_all_nodes():+ boundaries = {+ "mono": [+ ServiceBoundary(service_path="services/auth", service_name="auth"),+ ServiceBoundary(service_path="services/billing", service_name="billing"),+ ]+ }+ contracts = [+ _provider("mono", "http::a", file="services/auth/h.py"),+ _provider("mono", "http::b", file="services/billing/h.py"),+ ]+ graph = build_system_graph(contracts, [], CrossRepoOverlay(), boundaries)+ resolved, unresolved = resolve_targets(graph, ["mono"])+ assert set(resolved) == {"mono::services/auth", "mono::services/billing"}+ assert unresolved == []+++def test_resolve_unknown_target():+ graph = _chain_graph()+ resolved, unresolved = resolve_targets(graph, ["ghost"])+ assert resolved == []+ assert unresolved == ["ghost"]+++# ---------------------------------------------------------------------------+# Reachability + direction+# ---------------------------------------------------------------------------+++def test_changing_provider_reaches_transitive_consumers():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["db"])+ impacted = {n.id: n for n in result.impacted}+ # db's direct dependent is api (distance 1); web is transitive (distance 2).+ assert set(impacted) == {"api", "web"}+ assert impacted["api"].distance == 1+ assert impacted["web"].distance == 2+ assert result.max_distance == 2+++def test_leaf_consumer_has_no_downstream():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["web"])+ # Nothing depends on web (it only consumes), so nothing is impacted.+ assert result.impacted == []+ assert result.total_impacted == 0+++def test_distance_decay_ranks_nearer_higher():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["db"])+ api = next(n for n in result.impacted if n.id == "api")+ web = next(n for n in result.impacted if n.id == "web")+ assert api.score > web.score+ # impacted list is sorted by score desc → api first.+ assert result.impacted[0].id == "api"+++def test_max_depth_bounds_traversal():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["db"], max_depth=1)+ assert {n.id for n in result.impacted} == {"api"}+ assert result.max_distance == 1+++# ---------------------------------------------------------------------------+# Structural vs behavioral weighting + labeling+# ---------------------------------------------------------------------------+++def test_structural_and_behavioral_are_labeled_distinctly():+ contracts = [+ _provider("api", "http::GET::/users", file="api/h.py"),+ _consumer("web", "http::GET::/users", file="web/c.py"),+ ]+ links = [_link("http::GET::/users", "api", "api/h.py", "web", "web/c.py")]+ overlay = CrossRepoOverlay(+ co_changes=[_cochange("api", "api/h.py", "infra", "infra/deploy.yaml", strength=0.7)]+ )+ graph = build_system_graph(contracts, links, overlay, {})+ result = cross_repo_blast_radius(graph, ["api"])+ by_id = {n.id: n for n in result.impacted}+ # web depends on api via http (structural); infra only co-changes (behavioral).+ assert by_id["web"].structural is True+ assert by_id["infra"].structural is False+ assert result.structural_count == 1+ assert result.behavioral_count == 1+++def test_behavioral_edge_scores_lower_than_structural_at_same_distance():+ # api has one structural dependent (web) and one co-change partner (infra),+ # both at distance 1, both with the same edge confidence — the behavioral+ # one must rank lower purely from BEHAVIORAL_EDGE_WEIGHT.+ contracts = [+ _provider("api", "http::GET::/u", file="api/h.py"),+ _consumer("web", "http::GET::/u", file="web/c.py", ),+ ]+ links = [_link("http::GET::/u", "api", "api/h.py", "web", "web/c.py", conf=0.7)]+ overlay = CrossRepoOverlay(+ co_changes=[_cochange("api", "api/h.py", "infra", "infra/x.yaml", strength=0.7)]+ )+ graph = build_system_graph(contracts, links, overlay, {})+ result = cross_repo_blast_radius(graph, ["api"])+ by_id = {n.id: n for n in result.impacted}+ assert by_id["web"].score > by_id["infra"].score+ # The behavioral score is exactly the structural one scaled by the weight.+ assert by_id["infra"].score == round(by_id["web"].score * BEHAVIORAL_EDGE_WEIGHT, 4)+++def test_include_behavioral_false_drops_co_change_edges():+ contracts = [+ _provider("api", "http::GET::/u", file="api/h.py"),+ _consumer("web", "http::GET::/u", file="web/c.py"),+ ]+ links = [_link("http::GET::/u", "api", "api/h.py", "web", "web/c.py")]+ overlay = CrossRepoOverlay(+ co_changes=[_cochange("api", "api/h.py", "infra", "infra/x.yaml")]+ )+ graph = build_system_graph(contracts, links, overlay, {})+ result = cross_repo_blast_radius(graph, ["api"], include_behavioral=False)+ assert {n.id for n in result.impacted} == {"web"}+ assert result.behavioral_count == 0+++def test_co_change_propagates_both_directions():+ overlay = CrossRepoOverlay(+ co_changes=[_cochange("a", "a/x.py", "b", "b/y.py", strength=0.8)]+ )+ graph = build_system_graph([], [], overlay, {})+ # Changing either side impacts the other (undirected behavioral edge).+ assert {n.id for n in cross_repo_blast_radius(graph, ["a"]).impacted} == {"b"}+ assert {n.id for n in cross_repo_blast_radius(graph, ["b"]).impacted} == {"a"}+++def test_package_dep_impact_points_to_dependents():+ overlay = CrossRepoOverlay(+ package_deps=[+ CrossRepoPackageDep(+ source_repo="web",+ target_repo="shared",+ source_manifest="package.json",+ kind="npm_local_path",+ )+ ]+ )+ graph = build_system_graph([], [], overlay, {})+ # web depends on shared → changing shared impacts web.+ result = cross_repo_blast_radius(graph, ["shared"])+ assert {n.id for n in result.impacted} == {"web"}+ assert result.impacted[0].structural is True+ assert result.impacted[0].edge_kinds == ["package"]+++# ---------------------------------------------------------------------------+# Edge cases+# ---------------------------------------------------------------------------+++def test_unknown_target_yields_empty_with_unresolved():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["ghost"])+ assert result.impacted == []+ assert result.unresolved_targets == ["ghost"]+ assert result.targets == []+++def test_cycle_is_traversed_safely():+ # a ↔ b structural cycle: a depends on b AND b depends on a.+ contracts = [+ _provider("a", "http::pa", file="a/h.py"),+ _consumer("b", "http::pa", file="b/c.py"),+ _provider("b", "http::pb", file="b/h.py"),+ _consumer("a", "http::pb", file="a/c.py"),+ ]+ links = [+ _link("http::pa", "a", "a/h.py", "b", "b/c.py"),+ _link("http::pb", "b", "b/h.py", "a", "a/c.py"),+ ]+ graph = build_system_graph(contracts, links, CrossRepoOverlay(), {})+ result = cross_repo_blast_radius(graph, ["a"])+ # b is impacted; a (the target) is never re-impacted onto itself.+ assert {n.id for n in result.impacted} == {"b"}+++def test_impacted_repos_excludes_target_repo():+ graph = _chain_graph()+ result = cross_repo_blast_radius(graph, ["db"])+ assert "db" not in result.impacted_repos+ assert set(result.impacted_repos) == {"api", "web"}+++def test_result_is_capped_but_total_is_honest():+ # One provider with many distinct consumers → many distance-1 impacted nodes.+ contracts = [_provider("hub", "http::GET::/x", file="hub/h.py")]+ links = []+ for i in range(MAX_IMPACTED + 20):+ repo = f"c{i}"+ contracts.append(_consumer(repo, "http::GET::/x", file=f"{repo}/c.py"))+ links.append(_link("http::GET::/x", "hub", "hub/h.py", repo, f"{repo}/c.py"))+ graph = build_system_graph(contracts, links, CrossRepoOverlay(), {})+ result = cross_repo_blast_radius(graph, ["hub"])+ assert len(result.impacted) == MAX_IMPACTED+ assert result.total_impacted == MAX_IMPACTED + 20+++def test_to_dict_shape_is_locked():+ graph = _chain_graph()+ data = cross_repo_blast_radius(graph, ["db"]).to_dict()+ assert set(data) == {+ "targets",+ "target_repos",+ "impacted",+ "impacted_repos",+ "structural_count",+ "behavioral_count",+ "max_distance",+ "total_impacted",+ "unresolved_targets",+ }+ assert set(data["impacted"][0]) == {+ "id",+ "repo",+ "name",+ "kind",+ "distance",+ "score",+ "structural",+ "edge_kinds",+ }+++def test_empty_graph_is_safe():+ graph = build_system_graph([], [], CrossRepoOverlay(), {})+ result = cross_repo_blast_radius(graph, ["anything"])+ assert isinstance(result, CrossRepoBlastRadius)+ assert result.impacted == []+ assert result.total_impacted == 0