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
fix(mcp): separate risk relationship semantics (#1905)
Raghav Chamadiya47714d684c95
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex c4dc01eb3..5df9fd864 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -444,18 +444,18 @@ Modification risk assessment for files or a set of changed files.|-----------|------|----------|-------------|| `targets` | list[string] | No | File paths to assess || `changed_files` | list[string] | No | Files in a PR/changeset for blast radius analysis; passing this switches the response into PR-directive mode |-| `include` | list[string] | No | Opt-in blocks: `graph` (`impact_surface`, `direct_risks`), `churn` (`change_magnitude`, `risk_type`, `change_pattern`) |+| `include` | list[string] | No | Opt-in blocks: `graph` (typed `dependents`, `consumers`, `cross_repo_links`, structural `impact_surface`, `direct_risks`), `churn` (`change_magnitude`, `risk_type`, `change_pattern`) || `repo` | string | No | *(workspace only)* Target repo alias |-**Returns:** Per-file `hotspot_score` (0-1 churn percentile), `health_score` (0-10), hotspot status, dependent count, co-change partners (each with a recency-decayed `weight`, not an integer count), blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.+**Returns:** Per-file `hotspot_score` (0-1 churn percentile), `health_score` (0-10), hotspot status, direct directed `dependents_count`, historical `co_change_partners` (each with a recency-decayed `weight`, not an integer count), blast radius, recommended reviewers, test gap analysis, and security signals. With `include=["graph"]`, `dependents` preserves direct versus transitive structural reach, `consumers` contains typed contract consumers only, and `cross_repo_links` retains both repository identities, direction, relationship type, evidence kind, and file- or repository-level granularity. Package-manifest links are repository-level and never invent a target file. Every typed relationship collection carries matching total/emitted/truncated fields. `relationship_analysis` distinguishes available-empty analysis from unavailable, degraded, partial, and source-truncated artifacts and retains artifact generation/provenance fields. Structural reach is not proof of runtime breakage.> **Opt-in blocks.** `impact_surface` and `direct_risks` are pagerank floats an agent cannot rank; `change_magnitude`, `risk_type` and `change_pattern` restate numbers printed beside them. All five are computed regardless and feed `risk_summary`; `include` only decides whether they ship. `global_hotspots` accompanies a multi-target call only, being ambient orientation that a single named file does not need; it ranks by fix history the same way `defect_profile` does.> **Scales.** `overall_risk_score` (in `pr_blast_radius`, with an `overall_risk_score_measures` note beside it) reads where the change lands. It is not comparable to `get_change_risk.score`, which is also 0-10 and reads the shape of the diff. Ratios derived from ownership or percentile columns are 0-1 (`hotspot_score`, `owner_pct`, `recent_owner_pct`); coverage and gap fields are 0-100 (`coverage_pct`, `branch_coverage_pct`, `share_of_repo_gap_pct`, `change_entropy_pct`, `churn_percentile`). The `_pct` suffix alone does not tell you which — check this table. Every emitted float is rounded to 4 significant digits.-When `changed_files` is passed, the response leads with a `directive` block. Its core lists are the local blast radius: `may_break` (production files that reach the diff through the import graph and so may break), `may_break_tests` (test files impacted the same way, kept separate so a burst of broken tests doesn't crowd production impact out of the capped list), `missing_cochanges` (historical co-changers absent from the diff), `missing_tests` (changed files without test coverage), and `tests_to_run` (the positive complement of `missing_tests`: the tests that exercise the changed files, as pytest-runnable arguments). Read `tests_to_run_basis` beside it, because the ids alone do not say where they came from: `measured` means the per-test coverage map proves those tests execute the changed files; `inferred` means the import graph shows those test *files* reaching the change, which is a candidate list rather than proof and needs no coverage ingest; `none` means neither source knows of a test, which is unknown and not "untested". The two are never mixed in one list. In workspace mode that directive also carries the cross-repo fallout of the changed repo:+When `changed_files` is passed, the response leads with a `directive` block. Its core lists are the local blast radius: `may_break` (production files in structural reverse-import reach of the diff, candidates for review rather than proven breakage), `may_break_tests` (test files reached the same way, kept separate so a burst of tests doesn't crowd production impact out of the capped list), `missing_cochanges` (historical co-changers absent from the diff), `missing_tests` (changed files without test coverage), and `tests_to_run` (the positive complement of `missing_tests`: the tests that exercise the changed files, as pytest-runnable arguments). Read `tests_to_run_basis` beside it, because the ids alone do not say where they came from: `measured` means the per-test coverage map proves those tests execute the changed files; `inferred` means the import graph shows those test *files* reaching the change, which is a candidate list rather than proof and needs no coverage ingest; `none` means neither source knows of a test, which is unknown and not "untested". The two are never mixed in one list. 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.+- `will_break_consumers`: deprecated compatibility name for services in *other* repos that structurally depend on this one. Rows carry `claim: structural_reach`, `runtime_breakage_claim: false`, both repository roles, direction, distance, and aggregated edge kinds; the sibling `will_break_consumers_semantics` is `structural_reach_only`. Matching total/emitted/truncated fields describe the exact pre-cap structural population, while `cross_repo_relationship_analysis` labels unavailable or partial edge provenance.- `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](../scale/WORKSPACES.md#breaking-change-guard).- `conformance_violations`: declared dependency-rule breaches the diff's repo participates in, each with the offending `source`/`target` services, the `rule` (e.g. `frontend !-> db`), and `edge_kind`. See [Architecture Conformance](../scale/WORKSPACES.md#architecture-conformance).@@ -466,8 +466,9 @@ When `changed_files` is passed, the response leads with a `directive` block. Its> a reverse-import reachability walk: `get_risk` is given a file list, never a> diff, so it cannot know whether the symbol an importer actually uses changed.> The old name promised a precision the analyzer does not have.-> `will_break_consumers` and `breaking_changes` keep "will" — those come from-> real contract diffing.+> `will_break_consumers` temporarily keeps its old key for compatibility, but+> it is structural reach only and is explicitly marked deprecated. Only+> `breaking_changes` comes from incompatible contract diffing.**When to use:** Before modifying files, especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.mdindex 67759c15f..f52abd4e7 100644--- a/docs/reference/COMPUTED_GLOSSARY.md+++ b/docs/reference/COMPUTED_GLOSSARY.md@@ -241,8 +241,8 @@ workspace overlays, MCP responses, and CLI output.| Risk trend | Velocity from 30-day vs prior 60-day commit rates. | `tool_risk._compute_trend()` | `increasing`, `stable`, `decreasing` || Risk type | Human bucket for the kind of risk. | `tool_risk._classify_risk_type()` | `bug-prone`, `churn-heavy`, `bus-factor-risk`, `high-coupling`, `stable` || Change pattern | Human label from dominant commit category. | `tool_risk._derive_change_pattern()` | `feature-active`, `fix-heavy`, `dependency-churn`, `mixed-activity` |-| Impact surface | Top critical reverse dependencies within two hops. | `tool_risk._compute_impact_surface()` | `[{file_path: "src/api.py", pagerank: 0.05}]` |-| Risk summary | One-line synthesized risk sentence for MCP. | `tool_risk._assess_one_target()` | `src/auth.py - hotspot score 88% (increasing), 6 dependents...` |+| Impact surface | PageRank-ranked structural reverse-dependency reach within two hops. It preserves distance and does not claim runtime breakage. | `tool_risk._compute_impact_surface()` | `[{file_path: "src/api.py", distance: 2, claim: "structural_reach"}]` |+| Risk summary | One-line synthesized risk sentence for MCP; its dependency count is direct-only. | `tool_risk._assess_one_target()` | `src/auth.py - hotspot score 88% (increasing), 6 direct dependents...` || Top hotspots | Highest churn/hotspot files returned for context. | `get_risk()` | `[{file_path: "src/db.py", hotspot_score: 0.94}]` |## Code Health And Defect-Score Benchmark Metricsdiff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex d102bf143..be7e8400f 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -213,7 +213,7 @@ def _render_card(name: str, card: dict) -> None:trend = card.get("trend") or "unknown"console.print(f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "- f"{card.get('dependents_count', 0)} dependents · "+ f"{card.get('dependents_count', 0)} direct dependents · "f"{card.get('risk_type', 'unknown')} · owned "f"{_ta.owner_share(card.get('owner_pct'))} by "f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"@@ -262,11 +262,17 @@ def _render_card(name: str, card: dict) -> None:cross = card.get("cross_repo_impact") or {}if cross:repos = cross.get("affected_repos") or []- consumers = cross.get("cross_repo_consumers") or []+ historical = cross.get("cross_repo_consumers") or []contracts = cross.get("contract_consumers") or []console.print(- f" [bold]Crosses repo boundaries[/bold] [dim]{len(consumers)} consumer(s)"- + (f", {len(contracts)} contract link(s)" if contracts else "")+ " [bold]Crosses repo boundaries[/bold] [dim]"+ f"{cross.get('cross_repo_consumers_total', len(historical))} historical co-change(s)"+ + (+ f", {cross.get('contract_consumers_total', len(contracts))} "+ "typed contract consumer(s)"+ if contracts+ else ""+ )+ (f" in {', '.join(str(r) for r in repos)}" if repos else "")+ "[/dim]")@@ -297,13 +303,13 @@ def _render_card(name: str, card: dict) -> None:if partners:console.print(" [bold]Co-changes with[/bold]")for p in partners[:8]:- link = " [dim](imports)[/dim]" if p.get("has_import_link") else ""+ link = " [dim](also imports)[/dim]" if p.get("has_import_link") else ""# A recency-decayed weight rather than a raw tally, so it is not an# integer; ``:g`` keeps a whole number whole and trims the rest.weight = p.get("weight", 0)- shown = f"{float(weight):.1f}".rstrip("0").rstrip(".") if weight else "0"+ weight_text = f"{float(weight):.1f}".rstrip("0").rstrip(".") if weight else "0"console.print(- f" {escape(str(p.get('file_path', '')))} [dim]x{shown}[/dim]{link}"+ f" {escape(str(p.get('file_path', '')))} [dim]x{weight_text}[/dim]{link}")if len(partners) > 8:console.print(f" [dim]… and {len(partners) - 8} more (--format json).[/dim]")@@ -328,7 +334,7 @@ def _print_list(label: str, values: list[str], *, indent: str = " ") -> None:#: four printed as raw Python dict reprs. Each formatter is written against#: that module's construction site._DIRECTIVE_RECORD_BLOCKS = (- ("Consumers that may break", "will_break_consumers"),+ ("Consumer structural reach", "will_break_consumers"),("Missing cross-repo co-changes", "missing_cross_repo_cochanges"),("Breaking contract changes", "breaking_changes"),("Conformance violations", "conformance_violations"),diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.pyindex 1d0d4c405..169abddb0 100644--- a/packages/core/src/repowise/core/analysis/pr_blast.py+++ b/packages/core/src/repowise/core/analysis/pr_blast.py@@ -24,7 +24,8 @@ from typing import Anyfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.ingestion.models import NON_DEPENDENCY_EDGE_TYPES+from repowise.core.exclusion import is_excluded+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.models import GitMetadata, GraphNode@@ -90,6 +91,7 @@ class PRBlastRadiusAnalyzer:self,changed_files: list[str],max_depth: int = 3,+ exclude_spec: Any = None,) -> dict:"""Return full blast-radius analysis for the given changed files.@@ -106,7 +108,9 @@ class PRBlastRadiusAnalyzer:direct_risks = await self._score_files(changed_files)# 2. Transitive affected files- transitive_affected = await self._transitive_affected(changed_files, max_depth)+ transitive_affected = await self._transitive_affected(+ changed_files, max_depth, exclude_spec+ )# Sorted, because this list is cut before it is shown. ``test_gaps``# preserves this order and ``get_risk``'s PR directive renders three of# it as ``missing_tests``, the third line an agent is told to read.@@ -169,7 +173,7 @@ class PRBlastRadiusAnalyzer:)node_by_path: dict[str, Any] = {n.node_id: n for n in node_res.scalars().all()}- results = []+ results: list[dict[str, Any]] = []for path in paths:meta = meta_by_path.get(path)node = node_by_path.get(path)@@ -185,7 +189,7 @@ class PRBlastRadiusAnalyzer:})- results.sort(key=lambda x: -x["risk_score"])+ results.sort(key=lambda x: -float(x["risk_score"]))return results@staticmethod@@ -193,7 +197,9 @@ class PRBlastRadiusAnalyzer:"""Compute file-level risk: centrality * (1 + temporal_hotspot_score)."""return centrality * (1.0 + temporal_hotspot_score)- async def _transitive_affected(self, changed_files: list[str], max_depth: int) -> list[dict]:+ async def _transitive_affected(+ self, changed_files: list[str], max_depth: int, exclude_spec: Any = None+ ) -> list[dict]:"""BFS over reverse graph edges (source_node_id -> target_node_id direction).We want files that *import* the changed files (i.e. are affected when a@@ -227,22 +233,30 @@ class PRBlastRadiusAnalyzer:break# SQLite / SQLAlchemy compatible IN query via text()placeholders = ",".join(f":p{i}" for i in range(len(frontier)))- excluded = ",".join(f":e{i}" for i in range(len(NON_DEPENDENCY_EDGE_TYPES)))+ allowed = ",".join(f":e{i}" for i in range(len(FILE_DEPENDENCY_EDGE_TYPES)))params: dict[str, Any] = {"repo_id": self._repo_id}params.update({f"p{i}": v for i, v in enumerate(frontier)})- params.update({f"e{i}": v for i, v in enumerate(sorted(NON_DEPENDENCY_EDGE_TYPES))})+ params.update({f"e{i}": v for i, v in enumerate(sorted(FILE_DEPENDENCY_EDGE_TYPES))})rows = await self._session.execute(text(- f"SELECT DISTINCT source_node_id FROM graph_edges "- f"WHERE repository_id = :repo_id "- f"AND target_node_id IN ({placeholders}) "- f"AND edge_type NOT IN ({excluded})"+ f"SELECT DISTINCT e.source_node_id FROM graph_edges e "+ f"JOIN graph_nodes source ON source.repository_id = e.repository_id "+ f"AND source.node_id = e.source_node_id AND source.node_type = 'file' "+ f"JOIN graph_nodes target ON target.repository_id = e.repository_id "+ f"AND target.node_id = e.target_node_id AND target.node_type = 'file' "+ f"WHERE e.repository_id = :repo_id "+ f"AND e.target_node_id IN ({placeholders}) "+ f"AND e.edge_type IN ({allowed})"),params,)next_frontier = []for (src,) in rows:- if src not in visited and src not in set(changed_files):+ if (+ src not in visited+ and src not in set(changed_files)+ and not is_excluded(src, exclude_spec)+ ):visited[src] = depthnext_frontier.append(src)frontier = next_frontier@@ -250,7 +264,16 @@ class PRBlastRadiusAnalyzer:# Depth first, then path: a sort on depth alone is stable, so files# sharing a depth kept the row order the query happened to return.return [- {"path": p, "depth": d}+ {+ "path": p,+ "depth": d,+ "distance": d,+ "direct": d == 1,+ "direction": "dependent_to_dependency",+ "evidence_kind": "structural",+ "claim": "structural_reach",+ "runtime_breakage_claim": False,+ }for p, d in sorted(visited.items(), key=lambda item: (item[1], item[0]))]@@ -280,6 +303,15 @@ class PRBlastRadiusAnalyzer:"changed": meta.file_path,"missing_partner": partner_path,"score": score,+ "relationship_type": "co_change",+ "direction": "undirected",+ "evidence_kind": "historical",+ "provenance": "git_history",+ **(+ {"support": partner["frequency"]}+ if partner.get("frequency") is not None+ else {}+ ),})@@ -305,7 +337,7 @@ class PRBlastRadiusAnalyzer:if email:owner_files[email].append(pct)- reviewers = [+ reviewers: list[dict[str, Any]] = [{"email": email,"files": len(pcts),@@ -313,7 +345,7 @@ class PRBlastRadiusAnalyzer:}for email, pcts in owner_files.items()]- reviewers.sort(key=lambda x: (-x["files"], -x["ownership_pct"]))+ reviewers.sort(key=lambda x: (-int(x["files"]), -float(x["ownership_pct"])))return reviewers[:5]async def _find_test_gaps(self, affected_files: list[str]) -> list[str]:diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex 9ac0c7eb3..520002903 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -10,6 +10,7 @@ import jsonimport loggingfrom collections import defaultdictfrom pathlib import Path+from typing import Any_log = logging.getLogger("repowise.mcp.enrichment")@@ -29,12 +30,21 @@ class CrossRepoEnricher:self._total_co_changes: int = 0self._package_deps: list[dict] = []self._repo_summaries: dict[str, dict] = {}+ self._cross_repo_analysis: dict = {+ "status": "unavailable",+ "reason": "artifact_missing",+ }+ self._contract_analysis: dict = {+ "status": "unavailable",+ "reason": "artifact_missing",+ }# Pre-built indexesself._co_change_index: dict[tuple[str, str], list[dict]] = defaultdict(list)self._consumer_index: dict[tuple[str, str], list[dict]] = defaultdict(list)self._package_dep_index: dict[str, list[dict]] = defaultdict(list)self._package_dep_reverse: dict[str, list[str]] = defaultdict(list)+ self._package_dep_reverse_links: dict[str, list[dict]] = defaultdict(list)# Contract indexes (Phase 4)self._contracts: list[dict] = []@@ -84,6 +94,10 @@ class CrossRepoEnricher:try:data = json.loads(data_path.read_text(encoding="utf-8"))except Exception:+ self._cross_repo_analysis = {+ "status": "degraded",+ "reason": "artifact_parse_failed",+ }_log.warning("Failed to parse cross-repo data at %s", data_path, exc_info=True)return@@ -96,6 +110,11 @@ class CrossRepoEnricher:data_path,data.get("version", 1),)+ self._cross_repo_analysis = {+ "status": "degraded",+ "reason": "unsupported_contract_version",+ "contract_version": data.get("version", 1),+ }returnself._co_changes = data.get("co_changes", [])@@ -104,13 +123,30 @@ class CrossRepoEnricher:self._total_co_changes = data.get("total_co_changes", len(self._co_changes))self._package_deps = data.get("package_deps", [])self._repo_summaries = data.get("repo_summaries", {})+ self._cross_repo_analysis = {+ "status": (+ "partial" if self._total_co_changes > len(self._co_changes) else "available"+ ),+ "contract_version": data.get("version", 1),+ "generated_at": data.get("generated_at"),+ "repo_provenance": data.get("repo_provenance", {}),+ "freshness": {+ "status": "unavailable",+ "reason": "live_repository_heads_not_compared",+ },+ "source_co_changes_total": self._total_co_changes,+ "source_co_changes_emitted": len(self._co_changes),+ "source_truncated": self._total_co_changes > len(self._co_changes),+ }# Build co-change index: (repo, file) -> list of partner dicts+ malformed_co_changes = 0for cc in self._co_changes:try:src_key = (cc["source_repo"], cc["source_file"])tgt_key = (cc["target_repo"], cc["target_file"])except KeyError:+ malformed_co_changes += 1_log.debug("Skipping malformed co-change entry: %s", cc)continue@@ -143,11 +179,13 @@ class CrossRepoEnricher:self._consumer_index[key].sort(key=lambda x: -x["strength"])# Build package dep indexes+ malformed_package_deps = 0for pd in self._package_deps:try:src_repo = pd["source_repo"]tgt_repo = pd["target_repo"]except KeyError:+ malformed_package_deps += 1_log.debug("Skipping malformed package dep entry: %s", pd)continueself._package_dep_index[src_repo].append(@@ -159,6 +197,22 @@ class CrossRepoEnricher:)# Reverse: who depends on target_repoself._package_dep_reverse[tgt_repo].append(src_repo)+ self._package_dep_reverse_links[tgt_repo].append(+ {+ "source_repo": src_repo,+ "target_repo": tgt_repo,+ "source_manifest": pd.get("source_manifest", ""),+ "kind": pd.get("kind", ""),+ }+ )+ if malformed_co_changes or malformed_package_deps:+ self._cross_repo_analysis.update(+ {+ "status": "partial",+ "malformed_co_changes_skipped": malformed_co_changes,+ "malformed_package_deps_skipped": malformed_package_deps,+ }+ )_log.debug("Cross-repo enricher loaded: %d co-change edges, %d package deps",@@ -175,17 +229,33 @@ class CrossRepoEnricher:try:data = json.loads(contracts_path.read_text(encoding="utf-8"))except Exception:+ self._contract_analysis = {+ "status": "degraded",+ "reason": "artifact_parse_failed",+ }_log.warning("Failed to parse contract data at %s", contracts_path, exc_info=True)returnself._contracts = data.get("contracts", [])self._contract_links = data.get("contract_links", [])+ self._contract_analysis = {+ "status": "available",+ "contract_version": data.get("version", 1),+ "generated_at": data.get("generated_at"),+ "repo_provenance": data.get("repo_provenance", {}),+ "freshness": {+ "status": "unavailable",+ "reason": "live_repository_heads_not_compared",+ },+ }+ malformed_contract_links = 0for link in self._contract_links:try:provider_key = (link["provider_repo"], link["provider_file"])consumer_key = (link["consumer_repo"], link["consumer_file"])except KeyError:+ malformed_contract_links += 1_log.debug("Skipping malformed contract link: %s", link)continueself._contract_provider_index[provider_key].append(link)@@ -194,6 +264,14 @@ class CrossRepoEnricher:if provider_symbol:self._link_provider_symbol_index[provider_symbol].append(link)+ if malformed_contract_links:+ self._contract_analysis.update(+ {+ "status": "partial",+ "malformed_contract_links_skipped": malformed_contract_links,+ }+ )+for contract in self._contracts:symbol_id = contract.get("symbol_id")if symbol_id:@@ -211,14 +289,15 @@ class CrossRepoEnricher:_log.debug("No system graph at %s", system_graph_path)returntry:- self._system_graph = json.loads(system_graph_path.read_text(encoding="utf-8"))+ graph = json.loads(system_graph_path.read_text(encoding="utf-8"))+ self._system_graph = graphexcept Exception:_log.warning("Failed to parse system graph at %s", system_graph_path, exc_info=True)return_log.debug("System graph loaded: %d nodes, %d edges",- len(self._system_graph.get("nodes", [])),- len(self._system_graph.get("edges", [])),+ len(graph.get("nodes", [])),+ len(graph.get("edges", [])),)def _load_breaking_changes(self, breaking_changes_path: Path) -> None:@@ -227,19 +306,20 @@ class CrossRepoEnricher:_log.debug("No breaking-change report at %s", breaking_changes_path)returntry:- self._breaking_changes = json.loads(breaking_changes_path.read_text(encoding="utf-8"))+ report = json.loads(breaking_changes_path.read_text(encoding="utf-8"))+ self._breaking_changes = reportexcept 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", []):+ for change in report.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", [])),+ len(report.get("changes", [])),)def _load_conformance(self, conformance_path: Path) -> None:@@ -248,14 +328,15 @@ class CrossRepoEnricher:_log.debug("No conformance report at %s", conformance_path)returntry:- self._conformance = json.loads(conformance_path.read_text(encoding="utf-8"))+ report = json.loads(conformance_path.read_text(encoding="utf-8"))+ self._conformance = reportexcept Exception:_log.warning("Failed to parse conformance at %s", conformance_path, exc_info=True)return_log.debug("Conformance report loaded: %d violation(s), %d cycle(s)",- len(self._conformance.get("violations", [])),- len(self._conformance.get("cycles", [])),+ len(report.get("violations", [])),+ len(report.get("cycles", [])),)def reload(self) -> None:@@ -269,10 +350,19 @@ class CrossRepoEnricher:self._total_co_changes = 0self._package_deps = []self._repo_summaries = {}+ self._cross_repo_analysis = {+ "status": "unavailable",+ "reason": "artifact_missing",+ }+ self._contract_analysis = {+ "status": "unavailable",+ "reason": "artifact_missing",+ }self._co_change_index = defaultdict(list)self._consumer_index = defaultdict(list)self._package_dep_index = defaultdict(list)self._package_dep_reverse = defaultdict(list)+ self._package_dep_reverse_links = defaultdict(list)self._contracts = []self._contract_links = []self._contract_provider_index = defaultdict(list)@@ -311,6 +401,16 @@ class CrossRepoEnricher:"""True if contracts or contract links are available."""return bool(self._contracts or self._contract_links)+ @property+ def cross_repo_analysis(self) -> dict:+ """Availability, provenance, and source truncation for the overlay."""+ return dict(self._cross_repo_analysis)++ @property+ def contract_analysis(self) -> dict:+ """Availability and provenance for the contract artifact."""+ return dict(self._contract_analysis)+@propertydef has_system_graph(self) -> bool:"""True if a system graph artifact has been loaded."""@@ -328,7 +428,7 @@ class CrossRepoEnricher:empty change list is silence rather than an all-clear. Callers thatreport findings must not present it as one."""- return bool(self._breaking_changes) and bool(self._breaking_changes.get("generated_at"))+ return bool(self._breaking_changes and self._breaking_changes.get("generated_at"))def get_breaking_changes(self) -> dict | None:"""Return the raw breaking-change report (changes + rollups)."""@@ -345,7 +445,7 @@ class CrossRepoEnricher:See :attr:`has_breaking_changes`: an unstamped report's zero findingsmean nothing looked, not that nothing was found."""- return bool(self._conformance) and bool(self._conformance.get("generated_at"))+ return bool(self._conformance and self._conformance.get("generated_at"))def get_conformance(self) -> dict | None:"""Return the raw conformance report (violations + cycles + rollups)."""@@ -430,6 +530,10 @@ class CrossRepoEnricher:"""Return repo aliases that depend on *repo_alias* via package manifests."""return self._package_dep_reverse.get(repo_alias, [])+ def get_package_consumers(self, repo_alias: str) -> list[dict]:+ """Typed package links whose source repository depends on *repo_alias*."""+ return self._package_dep_reverse_links.get(repo_alias, [])+def get_cross_repo_summary(self) -> dict:"""High-level cross-repo stats for the overview footer."""# Count repo-to-repo connections@@ -441,8 +545,11 @@ class CrossRepoEnricher:pair = tuple(sorted([pd["source_repo"], pd["target_repo"]]))repo_pairs[pair] += 1 # type: ignore[index]+ connections: list[dict[str, Any]] = [+ {"repos": list(pair), "edge_count": count} for pair, count in repo_pairs.items()+ ]top_connections = sorted(- [{"repos": list(pair), "edge_count": count} for pair, count in repo_pairs.items()],+ connections,key=lambda x: -x["edge_count"],)[:5]diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.pyindex eeb84d985..57669cb16 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py@@ -18,6 +18,7 @@ from repowise.core.persistence.models import ()from repowise.server.mcp_server._helpers import (filter_dicts_by_key,+ is_excluded,)#: A file carrying this many counted bug fixes reads as bug-prone. Same trigger@@ -28,6 +29,10 @@ _BUG_PRONE_FIXES = 3#: these", short enough to keep the block inside the per-file token budget._TOP_FIX_SYMBOLS = 3+# Relationship rows are deliberately bounded independently. Their totals are+# computed after repository exclusions and before this presentation cap.+_RELATIONSHIP_LIMIT = 5+def _derive_change_pattern(categories: dict[str, int]) -> str:"""Derive a human-readable change pattern from commit category counts."""@@ -133,39 +138,90 @@ async def _get_active_contributor_count(session: AsyncSession, repo_id: str) ->return None-def _compute_impact_surface(+def _reverse_neighbors(reverse_deps: dict[str, Any], node: str) -> dict[str, set[str]]:+ """Normalize one reverse-adjacency entry to ``dependent -> edge types``.++ The set-shaped fallback keeps the small pure helper tests and older callers+ compatible. Production passes the typed mapping built by ``get_risk``.+ """+ raw = reverse_deps.get(node, {})+ if isinstance(raw, dict):+ return {+ str(dependent): {str(edge_type) for edge_type in edge_types}+ for dependent, edge_types in raw.items()+ }+ return {str(dependent): {"dependency"} for dependent in raw}+++def _dependency_population(target: str,- reverse_deps: dict[str, set[str]],+ reverse_deps: dict[str, Any],node_meta: dict[str, Any],exclude_spec: Any = None,) -> list[dict]:- """Find the top 3 most critical modules that depend on this file."""- # BFS up to 2 hops through reverse dependencies- visited: set[str] = set()+ """Directed structural dependents within two hops, one row per node.++ Graph edges are stored ``source depends on target``. Walking the reverse+ adjacency therefore discovers only nodes that depend on *target*. Each row+ retains direct/transitive distance and the typed structural path; it makes+ no runtime-breakage claim.+ """+ discovered: dict[str, dict] = {}frontier = {target}- for _ in range(2):+ paths: dict[str, list[dict]] = {target: []}+ for distance in (1, 2):next_frontier: set[str] = set()- for node in frontier:- for dep in reverse_deps.get(node, set()):- if dep != target and dep not in visited:- visited.add(dep)- next_frontier.add(dep)+ for node in sorted(frontier):+ for dependent, edge_types in sorted(_reverse_neighbors(reverse_deps, node).items()):+ if (+ dependent == target+ or dependent in discovered+ or is_excluded(dependent, exclude_spec)+ ):+ continue+ edge = {+ "source": dependent,+ "target": node,+ "relationship_types": sorted(edge_types),+ }+ path = [edge, *paths.get(node, [])]+ meta = node_meta.get(dependent)+ row = {+ "node_id": dependent,+ "file_path": dependent,+ "target": target,+ "direction": "dependent_to_dependency",+ "evidence_kind": "structural",+ "claim": "structural_reach",+ "distance": distance,+ "direct": distance == 1,+ "relationship_types": sorted(edge_types)+ if distance == 1+ else ["transitive_dependency"],+ "path": path,+ "pagerank": meta.pagerank if meta else 0.0,+ "is_entry_point": meta.is_entry_point if meta else False,+ }+ if distance > 1:+ row["via"] = node+ discovered[dependent] = row+ paths[dependent] = path+ next_frontier.add(dependent)frontier = next_frontier- if not visited:- return []+ population = filter_dicts_by_key(list(discovered.values()), "file_path", exclude_spec)+ population.sort(key=lambda row: (row["distance"], row["file_path"]))+ return population- # Rank by pagerank (most critical first)- ranked = []- for dep in visited:- meta = node_meta.get(dep)- ranked.append(- {- "file_path": dep,- "pagerank": meta.pagerank if meta else 0.0,- "is_entry_point": meta.is_entry_point if meta else False,- }- )++def _compute_impact_surface(+ target: str,+ reverse_deps: dict[str, Any],+ node_meta: dict[str, Any],+ exclude_spec: Any = None,+) -> list[dict]:+ """Legacy top-three structural reach view, derived from typed dependents."""+ ranked = _dependency_population(target, reverse_deps, node_meta, exclude_spec)# Path breaks the tie, or the answer is not the same twice. ``visited`` is# a set, so ``ranked`` starts in hash order, and a stable sort keeps that# order wherever pagerank ties — which it does constantly, since most@@ -173,7 +229,6 @@ def _compute_impact_surface(# different "top 3 most critical modules" (measured: tests/test_progress.py# vs examples/fullscreen.py in the same slot, same tree, minutes apart).ranked.sort(key=lambda x: (-x["pagerank"], x["file_path"]))- ranked = filter_dicts_by_key(ranked, "file_path", exclude_spec)return ranked[:3]@@ -250,8 +305,10 @@ async def _get_security_signals(session: AsyncSession, repo_id: str, target: strreturn []-def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) -> list[dict]:- """Top-5 co-change partners for *meta*, by frequency, with import-link flags.+def _build_co_changes(+ meta: Any, structural_related: Any, exclude_spec: Any+) -> tuple[list[dict], int]:+ """Historical co-change partners and their exact post-filter population.Larger lists make MCP responses verbose without adding signal: top-5 capturesthe bulk of the temporal-coupling mass and keeps tool output tight for agents.@@ -265,20 +322,34 @@ def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) ->partners,key=lambda p: p.get("co_change_count", p.get("count", 0)) or 0,reverse=True,- )[:5]- return filter_dicts_by_key(- [- {- "file_path": p.get("file_path", p.get("path", "")),- "weight": p.get("co_change_count", p.get("count", 0)),- "last_co_change": p.get("last_co_change"),- "has_import_link": p.get("file_path", p.get("path", "")) in import_related,- }- for p in partners_sorted- ],- "file_path",- exclude_spec,)+ relation_types = structural_related if isinstance(structural_related, dict) else {}+ related_paths = set(structural_related)+ rows = []+ for partner in partners_sorted:+ path = partner.get("file_path", partner.get("path", ""))+ types = sorted(relation_types.get(path, ()))+ row = {+ "file_path": path,+ "weight": partner.get("co_change_count", partner.get("count", 0)),+ "last_co_change": partner.get("last_co_change"),+ "relationship_type": "co_change",+ "direction": "undirected",+ "evidence_kind": "historical",+ "provenance": "git_history",+ "has_structural_link": path in related_paths,+ # Compatibility field: unlike the broader structural flag, this is+ # true only for an actual imports edge.+ "has_import_link": "imports" in types if types else path in related_paths,+ }+ if types:+ row["structural_relationship_types"] = types+ support = partner.get("frequency", partner.get("shared_commit_count"))+ if support is not None:+ row["support"] = support+ rows.append(row)+ population = filter_dicts_by_key(rows, "file_path", exclude_spec)+ return population[:_RELATIONSHIP_LIMIT], len(population)def fix_annotation(meta: Any) -> dict | None:@@ -385,8 +456,8 @@ async def _assess_one_target(repository: Repository,target: str,all_edge_map: dict[str, int],- import_links: dict[str, set[str]],- reverse_deps: dict[str, set[str]],+ import_links: dict[str, dict[str, set[str]]],+ reverse_deps: dict[str, dict[str, set[str]]],node_meta: dict[str, Any],exclude_spec: Any = None,team_size: int | None = None,@@ -400,7 +471,75 @@ async def _assess_one_target(repo_id = repository.idresult_data: dict[str, Any] = {"target": target}- dep_count = all_edge_map.get(target, 0)+ dependency_population = _dependency_population(target, reverse_deps, node_meta, exclude_spec)+ dependents = dependency_population[:_RELATIONSHIP_LIMIT]+ # If both distances exist, protect one transitive row from a large direct+ # fan-in. Otherwise the totals would say transitive reach exists while the+ # bounded typed field silently showed only direct rows.+ first_transitive = next((row for row in dependency_population if not row["direct"]), None)+ if (+ first_transitive is not None+ and dependents+ and all(row["direct"] for row in dependents)+ and len(dependency_population) > len(dependents)+ ):+ dependents[-1] = first_transitive+ impact_surface = sorted(+ dependency_population,+ key=lambda row: (-row["pagerank"], row["file_path"]),+ )[:3]+ direct_dependents_total = sum(row["direct"] for row in dependency_population)+ transitive_dependents_total = len(dependency_population) - direct_dependents_total+ # The compatibility count uses the same post-exclusion population as the+ # typed rows. ``all_edge_map`` remains in the signature for callers that+ # predate the typed adjacency, but no longer drives the public total.+ dep_count = direct_dependents_total++ result_data.update(+ {+ # ``dependents_count`` is the compatibility field: direct, directed+ # graph dependents only. It no longer absorbs co-change or contract+ # rows. The typed collection includes both direct and two-hop rows.+ "dependents_count": dep_count,+ "dependents": dependents,+ "dependents_total": len(dependency_population),+ "dependents_emitted": len(dependents),+ "dependents_truncated": len(dependents) < len(dependency_population),+ "direct_dependents_total": direct_dependents_total,+ "transitive_dependents_total": transitive_dependents_total,+ "impact_surface": impact_surface,+ "impact_surface_total": len(dependency_population),+ "impact_surface_emitted": len(impact_surface),+ "impact_surface_truncated": len(impact_surface) < len(dependency_population),+ "consumers": [],+ "consumers_total": 0,+ "consumers_emitted": 0,+ "consumers_truncated": False,+ "cross_repo_links": [],+ "cross_repo_links_total": 0,+ "cross_repo_links_emitted": 0,+ "cross_repo_links_truncated": False,+ "relationship_analysis": {+ "dependencies": {+ "status": "available",+ "scope": "repository_graph",+ "evidence_kind": "structural",+ "max_depth": 2,+ "runtime_breakage_claim": False,+ },+ "consumers": {+ "status": "unavailable",+ "scope": "workspace_contract_links",+ "reason": "workspace contract analysis is unavailable",+ },+ "cross_repo": {+ "status": "unavailable",+ "scope": "workspace_file_relationships",+ "reason": "workspace relationship analysis is unavailable",+ },+ },+ }+ )# Git metadatares = await session.execute(@@ -414,18 +553,19 @@ async def _assess_one_target(if meta is None:result_data["hotspot_score"] = 0.0result_data["is_hotspot"] = False- result_data["dependents_count"] = dep_countresult_data["co_change_partners"] = []+ result_data["co_change_partners_total"] = 0+ result_data["co_change_partners_emitted"] = 0+ result_data["co_change_partners_truncated"] = False+ result_data["relationship_analysis"]["co_change"] = {+ "status": "unavailable",+ "scope": "git_history",+ "reason": "no git metadata is available for the target",+ }result_data["primary_owner"] = Noneresult_data["owner_pct"] = Noneresult_data["trend"] = "unknown"result_data["risk_type"] = "high-coupling" if dep_count >= 5 else "unknown"- result_data["impact_surface"] = _compute_impact_surface(- target,- reverse_deps,- node_meta,- exclude_spec,- )result_data["test_gap"] = await _check_test_gap(session, repo_id, target)result_data["security_signals"] = await _get_security_signals(session, repo_id, target)result_data["risk_summary"] = f"{target} — no git metadata available"@@ -433,7 +573,9 @@ async def _assess_one_target(hotspot_score = meta.churn_percentile or 0.0- co_changes = _build_co_changes(meta, import_links.get(target, set()), exclude_spec)+ co_changes, co_changes_total = _build_co_changes(+ meta, import_links.get(target, {}), exclude_spec+ )owner = meta.primary_owner_name or "unknown"pct = meta.primary_owner_commit_pct or 0.0@@ -444,9 +586,6 @@ async def _assess_one_target(# --- Risk type classification ---risk_type = _classify_risk_type(meta, dep_count, team_size)- # --- Impact surface ---- impact_surface = _compute_impact_surface(target, reverse_deps, node_meta, exclude_spec)-# Phase 2: commit classification → change_patternchange_pattern = _derive_change_pattern(_load_commit_categories(meta))@@ -460,8 +599,15 @@ async def _assess_one_target(# score alone can reproduce the churn half but not the floors, so on a# quiet repo it would badge files the backend does not consider hotspots.result_data["is_hotspot"] = bool(getattr(meta, "is_hotspot", False))- result_data["dependents_count"] = dep_countresult_data["co_change_partners"] = co_changes+ result_data["co_change_partners_total"] = co_changes_total+ result_data["co_change_partners_emitted"] = len(co_changes)+ result_data["co_change_partners_truncated"] = len(co_changes) < co_changes_total+ result_data["relationship_analysis"]["co_change"] = {+ "status": "available",+ "scope": "git_history",+ "evidence_kind": "historical",+ }result_data["primary_owner"] = ownerresult_data["owner_pct"] = pctresult_data["recent_owner"] = getattr(meta, "recent_owner_name", None)@@ -476,7 +622,6 @@ async def _assess_one_target("lines_deleted_90d": getattr(meta, "lines_deleted_90d", 0) or 0,"avg_commit_size": round(getattr(meta, "avg_commit_size", 0.0) or 0.0, 1),}- result_data["impact_surface"] = impact_surface# Phase 3: rename tracking & merge commit proxyoriginal_path = getattr(meta, "original_path", None)if original_path:@@ -501,10 +646,6 @@ async def _assess_one_target(if bus_factor == 1 and (meta.commit_count_total or 0) > 20:bus_note = f", bus factor risk (sole maintainer: {owner})"- # NOTE: risk_summary is built here but dependents_count may be updated- # later by cross-repo enrichment. We store dep_count now and let the- # outer function rebuild the summary after enrichment if needed.- result_data["_base_dep_count"] = dep_count# Lead with the bug-fix history when there is any. The summary used to open# on a churn percentile even where risk_type said "bug-prone", so the first# thing an agent read disagreed with the classification beside it. Counted@@ -513,8 +654,8 @@ async def _assess_one_target(result_data["risk_summary"] = (f"{target} — {_fix_clause(defect_profile)}"f"hotspot score {hotspot_score:.0%} ({trend}), "- f"{dep_count} dependents, {risk_type}, {change_pattern}, "- f"{len(co_changes)} co-change partners, owned {pct:.0%} by {owner}"+ f"{dep_count} direct dependents, {risk_type}, {change_pattern}, "+ f"{co_changes_total} co-change partners, owned {pct:.0%} by {owner}"f"{bus_note}{capped_note}")diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex 49877c4ee..8de100f4f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -162,50 +162,102 @@ def _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[return violations, cycles-def _cross_repo_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+def _cross_repo_relationships(repo_alias: str) -> 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_consumers``) from behavioral co-change (``missing_cochanges``).+ services in OTHER repos by impact, splitting structural reach (the legacy+ ``will_break_consumers`` field) from behavioral co-change+ (``missing_cochanges``). Structural reach is not runtime-breakage proof.Returns two empty lists when not in workspace mode or no system graph isavailable. Never raises."""- will_break_consumers: list[dict[str, Any]] = []- missing_cross_repo_cochanges: list[dict[str, Any]] = []+ unavailable = {+ "structural": [],+ "structural_total": 0,+ "historical": [],+ "historical_total": 0,+ "analysis": {"status": "unavailable", "reason": "system_graph_unavailable"},+ }try:if not _is_workspace_mode():- return will_break_consumers, missing_cross_repo_cochanges+ return unavailableenricher = _state._cross_repo_enricherraw_graph = enricher.get_system_graph() if enricher is not None else Noneif not raw_graph:- return will_break_consumers, missing_cross_repo_cochanges+ return unavailablefrom repowise.core.workspace.blast_radius import cross_repo_blast_radiusfrom repowise.core.workspace.system_graph import SystemGraph+ structural: list[dict[str, Any]] = []+ historical: list[dict[str, Any]] = []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 blastif 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}+ structural.append(+ {+ "repo": n.repo,+ "service": n.name,+ "consumer_repository": n.repo,+ "dependency_repository": repo_alias,+ "distance": n.distance,+ "direct": n.distance == 1,+ "score": n.score,+ "via": n.edge_kinds,+ "relationship_type": "structural_dependency",+ "direction": "consumer_to_dependency",+ "evidence_kind": "structural",+ "claim": "structural_reach",+ "runtime_breakage_claim": False,+ }+ )+ else:+ historical.append(+ {+ "repo": n.repo,+ "service": n.name,+ "source_repository": repo_alias,+ "target_repository": n.repo,+ "score": n.score,+ "relationship_type": "co_change",+ "direction": "undirected",+ "evidence_kind": "historical",+ "provenance": "workspace_system_graph",+ })+ return {+ "structural": structural[:_XR_WILL_BREAK_LIMIT],+ "structural_total": len(structural),+ "historical": historical[:_XR_COCHANGE_LIMIT],+ "historical_total": len(historical),+ "analysis": {+ "status": "partial" if structural else "available",+ "scope": "workspace_system_graph",+ "evidence_resolution": "aggregated_path_edge_kinds",+ "inference_detail": "unavailable",+ "generated_at": raw_graph.get("generated_at"),+ "repo_provenance": raw_graph.get("repo_provenance", {}),+ "freshness": {+ "status": "unavailable",+ "reason": "live_repository_heads_not_compared",+ },+ **({"reason": "per_edge_match_provenance_not_retained"} if structural else {}),+ },+ }except Exception:- return [], []- return will_break_consumers, missing_cross_repo_cochanges+ return {+ **unavailable,+ "analysis": {"status": "degraded", "reason": "analysis_failed"},+ }+++def _cross_repo_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Compatibility wrapper returning the two legacy directive lists."""+ relationships = _cross_repo_relationships(repo_alias)+ return relationships["structural"], relationships["historical"]def _trim_blast_lists(@@ -235,6 +287,7 @@ def _trim_blast_lists(if exclude_spec:value = [e for e in value if not is_excluded(_as_path(e), exclude_spec)]trimmed_blast[key] = value+ total = len(value)if len(value) > cap:trimmed_blast[key] = value[:cap]trimmed_blast[f"{key}_truncated_total"] = len(value)@@ -243,6 +296,9 @@ def _trim_blast_lists(f"pr_blast_radius.{key} beyond cap={cap} ({len(value) - cap} dropped)",value[cap:],)+ trimmed_blast[f"{key}_total"] = total+ trimmed_blast[f"{key}_emitted"] = len(trimmed_blast.get(key, []))+ trimmed_blast[f"{key}_truncated"] = total > len(trimmed_blast.get(key, []))if trimmed_blast.get("overall_risk_score") is not None:trimmed_blast["overall_risk_score_measures"] = _OVERALL_SCORE_MEASURESreturn trimmed_blast@@ -327,6 +383,10 @@ def _build_pr_directive(f"{r.get('target')} :: co_change_partners beyond 3",partners[3:],)+ emitted = len(r.get("co_change_partners") or [])+ total = r.get("co_change_partners_total", emitted)+ r["co_change_partners_emitted"] = emitted+ r["co_change_partners_truncated"] = emitted < totaltrimmed_blast = _trim_blast_lists(pr_blast_radius, exclude_spec, collector)response["pr_blast_radius"] = trimmed_blast@@ -424,12 +484,18 @@ def _build_pr_directive(# (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(alias)+ cross_repo_relationships = _cross_repo_relationships(alias)+ will_break_consumers = cross_repo_relationships["structural"]+ missing_cross_repo_cochanges = cross_repo_relationships["historical"]+ will_break_total = cross_repo_relationships["structural_total"]+ missing_cross_repo_total = cross_repo_relationships["historical_total"]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."+ f" Cross-repo: showing {len(will_break_consumers)} of {will_break_total} "+ f"consumer service(s) in structural reach, showing "+ f"{len(missing_cross_repo_cochanges)} of {missing_cross_repo_total} "+ f"cross-repo co-changer(s) missing.")# Breaking-change guard — incompatible provider changes (removed route /@@ -466,7 +532,18 @@ def _build_pr_directive("tests_to_run": tests_to_run,"tests_to_run_basis": tests_to_run_basis,"will_break_consumers": will_break_consumers,+ "will_break_consumers_semantics": "structural_reach_only",+ "will_break_consumers_deprecated": True,+ "will_break_consumers_total": will_break_total,+ "will_break_consumers_emitted": len(will_break_consumers),+ "will_break_consumers_truncated": len(will_break_consumers) < will_break_total,"missing_cross_repo_cochanges": missing_cross_repo_cochanges,+ "missing_cross_repo_cochanges_total": missing_cross_repo_total,+ "missing_cross_repo_cochanges_emitted": len(missing_cross_repo_cochanges),+ "missing_cross_repo_cochanges_truncated": (+ len(missing_cross_repo_cochanges) < missing_cross_repo_total+ ),+ "cross_repo_relationship_analysis": cross_repo_relationships["analysis"],"breaking_changes": breaking_changes,"breaking_changes_truncated": breaking_changes_dropped,"conformance_violations": conformance_violations,diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.pyindex 7370a5032..40a192441 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py@@ -12,76 +12,257 @@ from repowise.server.mcp_server._helpers import (_is_workspace_mode,)+_RELATIONSHIP_LIMIT = 5+++def _contract_consumer(link: dict, provider_repo: str, provider_file: str) -> dict:+ row = {+ "source_repository": provider_repo,+ "source_file": provider_file,+ "target_repository": link["consumer_repo"],+ "target_file": link["consumer_file"],+ "provider_repository": provider_repo,+ "provider_file": provider_file,+ "consumer_repository": link["consumer_repo"],+ "consumer_file": link["consumer_file"],+ "contract_id": link["contract_id"],+ "contract_type": link["contract_type"],+ "relationship_type": "contract_consumer",+ "direction": "provider_to_consumer",+ "evidence_kind": "contract",+ }+ for key in ("match_type", "confidence"):+ if link.get(key) is not None:+ row[key] = link[key]+ return row+++def _contract_provider(link: dict, consumer_repo: str, consumer_file: str) -> dict:+ row = {+ "source_repository": link["provider_repo"],+ "source_file": link["provider_file"],+ "target_repository": consumer_repo,+ "target_file": consumer_file,+ "provider_repository": link["provider_repo"],+ "provider_file": link["provider_file"],+ "consumer_repository": consumer_repo,+ "consumer_file": consumer_file,+ "contract_id": link["contract_id"],+ "contract_type": link["contract_type"],+ "relationship_type": "contract_provider",+ "direction": "provider_to_consumer",+ "evidence_kind": "contract",+ }+ for key in ("match_type", "confidence"):+ if link.get(key) is not None:+ row[key] = link[key]+ return row+++def _cross_repo_co_change(alias: str, target: str, partner: dict) -> dict:+ row = {+ "source_repository": alias,+ "source_file": target,+ "target_repository": partner["repo"],+ "target_file": partner["file"],+ "relationship_type": "co_change",+ "direction": "undirected",+ "evidence_kind": "historical",+ "provenance": "workspace_git_history",+ "strength": partner.get("strength", 0),+ }+ if partner.get("frequency") is not None:+ row["support"] = partner["frequency"]+ if partner.get("last_date"):+ row["last_observed_at"] = partner["last_date"]+ return row+++def _package_consumer(link: dict, target: str) -> dict:+ """Normalize a repository-level package consumer without inventing a file edge."""+ return {+ "source_repository": link["source_repo"],+ "source_file": link.get("source_manifest") or None,+ "target_repository": link["target_repo"],+ "target_file": None,+ "queried_file": target,+ "relationship_type": "package_dependency",+ "dependency_kind": link.get("kind") or "unknown",+ "direction": "consumer_to_dependency",+ "evidence_kind": "structural",+ "claim": "repository_structural_reach",+ "runtime_breakage_claim": False,+ "granularity": "repository",+ "provenance": "package_manifest",+ }+++def _combined_analysis(cross_state: dict, contract_state: dict, rows: list[dict]) -> dict:+ statuses = {cross_state.get("status"), contract_state.get("status")}+ if statuses == {"unavailable"}:+ status = "unavailable"+ elif statuses & {"partial", "degraded"} or statuses == {"available", "unavailable"}:+ status = "partial"+ else:+ status = "available"+ return {+ "status": status,+ "scope": "workspace_file_and_repository_relationships",+ "evidence_kinds": sorted({row["evidence_kind"] for row in rows}),+ "sources": {+ "cross_repo_overlay": cross_state,+ "contracts": contract_state,+ },+ }+async def _enrich_cross_repo(results: list[dict], alias: str) -> None:- """Annotate per-target results with cross-repo partners, affected repos and- contract links (workspace mode only). Mutates *results* in place; no-op when- no enricher data is available. Behavior preserved verbatim from inline form.+ """Add typed workspace relationships without changing dependency counts.++ Co-change is historical and undirected. Consumers exist only when a typed+ provider-to-consumer contract link exists. Every normalized cross-repo row+ retains both repository identities, direction, type, and evidence kind."""enricher = _state._cross_repo_enricher- if enricher is None or not enricher.has_data or not _is_workspace_mode():+ if enricher is None or not _is_workspace_mode():return+ cross_state = enricher.cross_repo_analysis+ contract_state = enricher.contract_analysisfor r in results:target = r["target"]cross_partners = enricher.get_cross_repo_partners(alias, target)- affected_repos = enricher.get_affected_repos(alias, target)- if cross_partners or affected_repos:- r["cross_repo_impact"] = {- "cross_repo_consumers": [- {"repo": p["repo"], "file": p["file"], "strength": p["strength"]}- for p in cross_partners[:5]- ],- "affected_repos": affected_repos,- }- r["dependents_count"] = r.get("dependents_count", 0) + len(cross_partners)- # Rebuild risk_summary with updated dependents count- if "_base_dep_count" in r:- r["risk_summary"] = r["risk_summary"].replace(- f"{r['_base_dep_count']} dependents",- f"{r['dependents_count']} dependents",- )-- # Contract links (Phase 4)- if not enricher.has_contract_data:- continueprovider_links = enricher.get_contract_links_as_provider(alias, target)consumer_links = enricher.get_contract_links_as_consumer(alias, target)- if not (provider_links or consumer_links):+ package_consumers = enricher.get_package_consumers(alias)++ consumers = [_contract_consumer(link, alias, target) for link in provider_links]+ r["consumers"] = consumers[:_RELATIONSHIP_LIMIT]+ r["consumers_total"] = len(consumers)+ r["consumers_emitted"] = len(r["consumers"])+ r["consumers_truncated"] = len(r["consumers"]) < len(consumers)+ r["relationship_analysis"]["consumers"] = {+ **contract_state,+ "scope": "workspace_contract_links",+ "evidence_kind": "contract",+ }++ co_change_links = [+ _cross_repo_co_change(alias, target, partner) for partner in cross_partners+ ]+ provider_rows = [+ _contract_consumer(link, alias, target)+ for link in provider_links+ if link.get("consumer_repo") != alias+ ]+ consumer_rows = [+ _contract_provider(link, alias, target)+ for link in consumer_links+ if link.get("provider_repo") != alias+ ]+ package_rows = [_package_consumer(link, target) for link in package_consumers]+ cross_repo_links = [*provider_rows, *consumer_rows, *package_rows, *co_change_links]+ priority = {"contract": 0, "structural": 1, "historical": 2}+ cross_repo_links.sort(+ key=lambda row: (+ priority.get(row["evidence_kind"], 9),+ row.get("target_repository", row.get("consumer_repository", "")),+ row.get("target_file", row.get("consumer_file", "")),+ row.get("source_repository", row.get("provider_repository", "")),+ )+ )+ r["cross_repo_links"] = cross_repo_links[:_RELATIONSHIP_LIMIT]+ r["cross_repo_links_total"] = len(cross_repo_links)+ r["cross_repo_links_emitted"] = len(r["cross_repo_links"])+ r["cross_repo_links_truncated"] = len(r["cross_repo_links"]) < len(cross_repo_links)+ r["relationship_analysis"]["cross_repo"] = _combined_analysis(+ cross_state, contract_state, cross_repo_links+ )++ if not cross_repo_links:continue++ affected_repos = sorted(+ {+ repo+ for row in cross_repo_links+ for repo in (+ row.get("source_repository"),+ row.get("target_repository"),+ row.get("provider_repository"),+ row.get("consumer_repository"),+ )+ if repo and repo != alias+ }+ )impact = r.setdefault("cross_repo_impact", {})- if provider_links:+ legacy_co_changes = [+ {+ "repo": p["repo"],+ "file": p["file"],+ "strength": p["strength"],+ "relationship_type": "co_change",+ "direction": "undirected",+ "evidence_kind": "historical",+ "provenance": "workspace_git_history",+ }+ for p in cross_partners+ ]+ # Compatibility window: the old name remains, but every row and the+ # sibling marker state precisely that it is historical co-change.+ impact["cross_repo_consumers"] = legacy_co_changes[:_RELATIONSHIP_LIMIT]+ impact["cross_repo_consumers_semantics"] = "historical_co_change_partners"+ impact["cross_repo_consumers_deprecated"] = True+ impact["cross_repo_consumers_total"] = len(legacy_co_changes)+ impact["cross_repo_consumers_emitted"] = len(impact["cross_repo_consumers"])+ impact["cross_repo_consumers_truncated"] = len(impact["cross_repo_consumers"]) < len(+ legacy_co_changes+ )+ impact["cross_repo_consumers_analysis"] = cross_state+ impact["affected_repos"] = affected_repos+ impact["affected_repos_total"] = len(affected_repos)+ impact["affected_repos_emitted"] = len(affected_repos)+ impact["affected_repos_truncated"] = False+ cross_provider_links = [+ link for link in provider_links if link.get("consumer_repo") != alias+ ]+ cross_consumer_links = [+ link for link in consumer_links if link.get("provider_repo") != alias+ ]+ if cross_provider_links:impact["contract_consumers"] = [{"consumer_repo": lk["consumer_repo"],"consumer_file": lk["consumer_file"],"contract_id": lk["contract_id"],"type": lk["contract_type"],+ "relationship_type": "contract_consumer",+ "direction": "provider_to_consumer",+ "evidence_kind": "contract",}- for lk in provider_links[:5]+ for lk in cross_provider_links[:_RELATIONSHIP_LIMIT]]- r["dependents_count"] = r.get("dependents_count", 0) + len(provider_links)- if consumer_links:+ impact["contract_consumers_total"] = len(cross_provider_links)+ impact["contract_consumers_emitted"] = len(impact["contract_consumers"])+ impact["contract_consumers_truncated"] = len(impact["contract_consumers"]) < len(+ cross_provider_links+ )+ if cross_consumer_links:impact["contract_providers"] = [{"provider_repo": lk["provider_repo"],"provider_file": lk["provider_file"],"contract_id": lk["contract_id"],"type": lk["contract_type"],+ "relationship_type": "contract_provider",+ "direction": "provider_to_consumer",+ "evidence_kind": "contract",}- for lk in consumer_links[:5]+ for lk in cross_consumer_links[:_RELATIONSHIP_LIMIT]]---def _finalize_dep_summaries(results: list[dict]) -> None:- """Rebuild risk_summary for any post-enrichment dependents_count change and- drop the internal ``_base_dep_count`` key. Mutates *results* in place.- """- for r in results:- base = r.pop("_base_dep_count", None)- if base is not None and r.get("dependents_count", base) != base:- r["risk_summary"] = r["risk_summary"].replace(- f"{base} dependents",- f"{r['dependents_count']} dependents",+ impact["contract_providers_total"] = len(cross_consumer_links)+ impact["contract_providers_emitted"] = len(impact["contract_providers"])+ impact["contract_providers_truncated"] = len(impact["contract_providers"]) < len(+ cross_consumer_links)diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 4c994d2da..0afb112e7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -6,7 +6,7 @@ import asynciofrom sqlalchemy import select-from repowise.core.ingestion.models import NON_DEPENDENCY_EDGE_TYPES+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -30,7 +30,7 @@ from repowise.server.mcp_server._meta import build_meta as _build_metafrom .assessment import _assess_one_target, _get_active_contributor_count, fix_annotationfrom .directives import _build_pr_directive, _governance_directive-from .enrichment import _enrich_cross_repo, _enrich_health, _finalize_dep_summaries+from .enrichment import _enrich_cross_repo, _enrich_health# Cheapest loss first; the target cards and the directive are never shed.# ``guarding_tests`` leads the dossier: _trim_blast_lists leaves it uncapped.@@ -45,7 +45,27 @@ _SHED_ORDER: tuple[str, ...] = (#: labels derived from numbers already printed beside them. Computed either way#: (``risk_summary`` reads them); ``include`` only decides whether they ship._TARGET_CARD_INCLUDES: dict[str, tuple[str, ...]] = {- "graph": ("impact_surface",),+ "graph": (+ "impact_surface",+ "impact_surface_total",+ "impact_surface_emitted",+ "impact_surface_truncated",+ "dependents",+ "dependents_total",+ "dependents_emitted",+ "dependents_truncated",+ "direct_dependents_total",+ "transitive_dependents_total",+ "consumers",+ "consumers_total",+ "consumers_emitted",+ "consumers_truncated",+ "cross_repo_links",+ "cross_repo_links_total",+ "cross_repo_links_emitted",+ "cross_repo_links_truncated",+ "relationship_analysis",+ ),"churn": ("change_magnitude", "risk_type", "change_pattern"),}_BLAST_INCLUDES: dict[str, tuple[str, ...]] = {"graph": ("direct_risks",)}@@ -75,8 +95,11 @@ async def get_risk("""What history says about touching these files — bug fixes, churn, owners.Fuses git temporal signals (``hotspot_score``/``owner_pct`` are 0-1; trend;- bus factor) with graph topology (dependents, co-changes, impact surface)- and security findings. Consult before editing a bug-fixed or busy file. Pass+ bus factor) with graph topology. ``dependents`` are directed structural+ reach (source depends on target), ``consumers`` require typed contract links,+ and ``co_change_partners`` are historical correlation only. Structural reach+ is not proof of runtime breakage. The response also includes security+ findings. Consult before editing a bug-fixed or busy file. Passchanged_files for PR mode: the response leads with a directive block(may_break, missing_cochanges, missing_tests, tests_to_run) — read itfirst. tests_to_run_basis backs the run-list: measured (a coverage map@@ -84,12 +107,8 @@ async def get_risk(graph shows reaching them; candidates, no ingest needed). To score a commitor ``base..head`` range instead, use ``get_change_risk``.- defect_profile appears only on files with counted bug fixes: how many landed- in the trailing 6 months, how long ago the last one was, a bug_magnet flag- for sustained recent fix pressure, and top_symbols. Read top_symbols as- "mostly here" rather than exact — symbol spans are current-tree while each- fix's line ranges are numbered on its own parent commit. Nothing names the- commit that introduced a bug.+ defect_profile appears only with counted fixes; top_symbols is approximate+ attribution, and nothing names a bug-inducing commit.episodes counts the dated records bound to a target — what happened here andwhy, evidenced by a commit or a filesystem fact. It appears only when there@@ -119,6 +138,14 @@ async def get_risk(repository = await _get_repo(session)repo_id = repository.id+ # File-node endpoints and the positive dependency vocabulary are both+ # required: an untyped or symbol edge must not become a file dependent.+ node_res = await session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo_id)+ )+ node_meta = {n.node_id: n for n in node_res.scalars().all()}+ file_node_ids = {node_id for node_id, node in node_meta.items() if node.node_type == "file"}+# Pre-load edges. Dependency edges only: everything below reads these as# "X depends on Y", and the graph also carries containment and co-change# edges. Leaving co_changes in made the relation circular: a co-change@@ -128,24 +155,29 @@ async def get_risk(res = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id,- GraphEdge.edge_type.notin_(NON_DEPENDENCY_EDGE_TYPES),+ GraphEdge.edge_type.in_(FILE_DEPENDENCY_EDGE_TYPES),+ GraphEdge.source_node_id.in_(file_node_ids),+ GraphEdge.target_node_id.in_(file_node_ids),))all_edges = res.scalars().all()- dep_counts: dict[str, int] = {}- import_links: dict[str, set[str]] = {}- reverse_deps: dict[str, set[str]] = {} # target -> set of importers+ import_links: dict[str, dict[str, set[str]]] = {}+ reverse_deps: dict[str, dict[str, set[str]]] = {}for e in all_edges:- dep_counts[e.target_node_id] = dep_counts.get(e.target_node_id, 0) + 1- import_links.setdefault(e.source_node_id, set()).add(e.target_node_id)- import_links.setdefault(e.target_node_id, set()).add(e.source_node_id)- reverse_deps.setdefault(e.target_node_id, set()).add(e.source_node_id)+ edge_type = str(e.edge_type)+ import_links.setdefault(e.source_node_id, {}).setdefault(e.target_node_id, set()).add(+ edge_type+ )+ import_links.setdefault(e.target_node_id, {}).setdefault(e.source_node_id, set()).add(+ edge_type+ )+ reverse_deps.setdefault(e.target_node_id, {}).setdefault(e.source_node_id, set()).add(+ edge_type+ )+ # Count unique incoming dependent nodes, not parallel edge rows. A file+ # with both an import and a type-use edge is still one direct dependent.+ dep_counts = {target: len(sources) for target, sources in reverse_deps.items()}- # Pre-load graph nodes for pagerank / impact surface- node_res = await session.execute(- select(GraphNode).where(GraphNode.repository_id == repo_id)- )- node_meta = {n.node_id: n for n in node_res.scalars().all()}test_paths = {nid for nid, n in node_meta.items() if n.is_test}# Team size is repo-wide — compute once, share across targets@@ -220,15 +252,11 @@ async def get_risk(from repowise.core.analysis.pr_blast import PRBlastRadiusAnalyzeranalyzer = PRBlastRadiusAnalyzer(session, repo_id)- pr_blast_radius = await analyzer.analyze_files(changed_files)+ pr_blast_radius = await analyzer.analyze_files(changed_files, exclude_spec=exclude_spec)# Cross-repo blast radius enrichment (Phase 3 + 4)await _enrich_cross_repo(results, ctx.alias)- # Final risk_summary rebuild for any remaining dependents_count updates- # (e.g. contract provider links) and cleanup of internal keys.- _finalize_dep_summaries(results)-# ---- Code-health enrichment --------------------------------------------# Attach per-file health_score + top_biomarkers (up to 3) drawn from the# health tables. Conservative: missing data → no field, never invented.@@ -246,6 +274,7 @@ async def get_risk(collector = OmissionCollector("get_risk", repo_root=ctx.path)if pr_blast_radius is not None:+ assert changed_files is not None# Governance risk — bounded query over changed_files (small set).governance_risk = await _governance_directive(ctx, changed_files)_build_pr_directive(diff --git a/tests/fixtures/mcp/risk_relationships.json b/tests/fixtures/mcp/risk_relationships.jsonnew file mode 100644index 000000000..ddd95aa95--- /dev/null+++ b/tests/fixtures/mcp/risk_relationships.json@@ -0,0 +1,71 @@+{+ "target": "src/auth/service.py",+ "excluded_path": "src/excluded.py",+ "nodes": [+ "src/auth/service.py",+ "src/db/models.py",+ "src/direct_0.py",+ "src/direct_1.py",+ "src/direct_2.py",+ "src/direct_3.py",+ "src/direct_4.py",+ "src/direct_5.py",+ "src/transitive.py",+ "src/excluded.py",+ "src/excluded_child.py",+ "docs/cochange-only.md",+ "src/unknown.py"+ ],+ "edges": [+ {"source": "src/direct_0.py", "target": "src/auth/service.py", "type": "imports"},+ {"source": "src/direct_1.py", "target": "src/auth/service.py", "type": "type_use"},+ {"source": "src/direct_2.py", "target": "src/auth/service.py", "type": "framework"},+ {"source": "src/direct_3.py", "target": "src/auth/service.py", "type": "imports"},+ {"source": "src/direct_4.py", "target": "src/auth/service.py", "type": "imports"},+ {"source": "src/direct_5.py", "target": "src/auth/service.py", "type": "imports"},+ {"source": "src/transitive.py", "target": "src/direct_0.py", "type": "imports"},+ {"source": "src/auth/service.py", "target": "src/db/models.py", "type": "imports"},+ {"source": "src/excluded.py", "target": "src/auth/service.py", "type": "imports"},+ {"source": "src/excluded_child.py", "target": "src/excluded.py", "type": "imports"},+ {"source": "docs/cochange-only.md", "target": "src/auth/service.py", "type": "co_changes"},+ {"source": "src/unknown.py", "target": "src/auth/service.py", "type": "mystery_edge"}+ ],+ "co_changes": [+ {"file_path": "docs/cochange-only.md", "co_change_count": 9.5, "frequency": 7, "last_co_change": "2026-08-20"},+ {"file_path": "src/direct_0.py", "co_change_count": 8.5, "frequency": 6, "last_co_change": "2026-08-19"},+ {"file_path": "src/history_1.py", "co_change_count": 7.5, "frequency": 5, "last_co_change": "2026-08-18"},+ {"file_path": "src/history_2.py", "co_change_count": 6.5, "frequency": 4, "last_co_change": "2026-08-17"},+ {"file_path": "src/history_3.py", "co_change_count": 5.5, "frequency": 3, "last_co_change": "2026-08-16"},+ {"file_path": "src/history_4.py", "co_change_count": 4.5, "frequency": 2, "last_co_change": "2026-08-15"},+ {"file_path": "src/excluded.py", "co_change_count": 99.0, "frequency": 99, "last_co_change": "2026-08-21"}+ ],+ "cross_repo": {+ "version": 2,+ "generated_at": "2026-08-21T00:00:00Z",+ "repo_provenance": {"alpha": {"indexed_commit": "alpha-indexed"}, "beta": {"indexed_commit": "beta-indexed"}},+ "total_co_changes": 8,+ "co_changes": [+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "beta", "target_file": "src/auth/service.py", "strength": 0.9, "frequency": 9, "last_date": "2026-08-20"},+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "beta", "target_file": "src/client_1.ts", "strength": 0.8, "frequency": 8, "last_date": "2026-08-19"},+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "beta", "target_file": "src/client_2.ts", "strength": 0.7, "frequency": 7, "last_date": "2026-08-18"},+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "gamma", "target_file": "src/client_3.ts", "strength": 0.6, "frequency": 6, "last_date": "2026-08-17"},+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "gamma", "target_file": "src/client_4.ts", "strength": 0.5, "frequency": 5, "last_date": "2026-08-16"},+ {"source_repo": "alpha", "source_file": "src/auth/service.py", "target_repo": "gamma", "target_file": "src/client_5.ts", "strength": 0.4, "frequency": 4, "last_date": "2026-08-15"}+ ],+ "package_deps": [+ {"source_repo": "delta", "target_repo": "alpha", "source_manifest": "package.json", "kind": "npm_workspace"}+ ],+ "repo_summaries": {}+ },+ "contracts": {+ "version": 2,+ "generated_at": "2026-08-21T01:00:00Z",+ "repo_provenance": {"alpha": {"indexed_commit": "alpha-contract"}, "gamma": {"indexed_commit": "gamma-contract"}},+ "contracts": [],+ "contract_links": [+ {"contract_id": "http::GET::/service", "contract_type": "http", "match_type": "exact", "confidence": 0.9, "provider_repo": "alpha", "provider_file": "src/auth/service.py", "consumer_repo": "beta", "consumer_file": "src/auth/service.py"},+ {"contract_id": "topic::auth-events", "contract_type": "topic", "match_type": "exact", "confidence": 0.8, "provider_repo": "gamma", "provider_file": "src/provider.py", "consumer_repo": "alpha", "consumer_file": "src/auth/service.py"},+ {"contract_id": "code::local", "contract_type": "code", "match_type": "exact", "confidence": 1.0, "provider_repo": "alpha", "provider_file": "src/auth/service.py", "consumer_repo": "alpha", "consumer_file": "src/local_consumer.py"}+ ]+ }+}diff --git a/tests/unit/server/mcp/test_risk_dependency_edges.py b/tests/unit/server/mcp/test_risk_dependency_edges.pyindex fa778312f..dce9ab268 100644--- a/tests/unit/server/mcp/test_risk_dependency_edges.py+++ b/tests/unit/server/mcp/test_risk_dependency_edges.py@@ -89,6 +89,35 @@ async def test_co_change_partner_is_not_blast_radius(setup_mcp, factory):assert _TARGET not in affected+async def test_pr_relationship_rows_are_typed_and_totals_match(setup_mcp, factory):+ from repowise.server.mcp_server import get_risk++ await _add_doc_co_change(factory, setup_mcp)+ result = await get_risk([_TARGET], changed_files=[_TARGET])+ blast = result["pr_blast_radius"]++ assert blast["transitive_affected_total"] >= len(blast["transitive_affected"])+ assert blast["transitive_affected_emitted"] == len(blast["transitive_affected"])+ assert blast["transitive_affected_truncated"] is (+ blast["transitive_affected_total"] > blast["transitive_affected_emitted"]+ )+ assert all(+ row["evidence_kind"] == "structural"+ and row["claim"] == "structural_reach"+ and row["runtime_breakage_claim"] is False+ for row in blast["transitive_affected"]+ )++ warning = next(row for row in blast["cochange_warnings"] if row["missing_partner"] == _DOC)+ assert warning["relationship_type"] == "co_change"+ assert warning["evidence_kind"] == "historical"+ assert warning["direction"] == "undirected"+ assert warning["provenance"] == "git_history"+ assert blast["cochange_warnings_total"] >= blast["cochange_warnings_emitted"]+ assert blast["cochange_warnings_emitted"] == len(blast["cochange_warnings"])++@pytest.mark.asyncioasync def test_containment_edges_are_not_dependents(setup_mcp, factory):from repowise.server.mcp_server import get_riskdiff --git a/tests/unit/server/mcp/test_risk_relationship_semantics.py b/tests/unit/server/mcp/test_risk_relationship_semantics.pynew file mode 100644index 000000000..bd0141eec--- /dev/null+++ b/tests/unit/server/mcp/test_risk_relationship_semantics.py@@ -0,0 +1,347 @@+"""Sealed contract tests for get_risk relationship meanings."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path++import pytest++from repowise.core.persistence.models import GitMetadata, GraphEdge, GraphNode+from repowise.core.workspace.registry import RepoContext+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._enrichment import CrossRepoEnricher++_FIXTURE = Path(__file__).parents[3] / "fixtures" / "mcp" / "risk_relationships.json"+++class _SealedRegistry:+ def __init__(self, context: RepoContext) -> None:+ self._context = context++ def resolve_repo_param(self, repo: str | None = None) -> str:+ return repo or self._context.alias++ async def get(self, alias: str) -> RepoContext:+ assert alias == self._context.alias+ return self._context+++async def relationship_payload(setup_mcp, factory, tmp_path):+ """Exact external payload from the sealed local + workspace relationship graph."""+ from sqlalchemy import delete, select++ from repowise.server.mcp_server import get_risk++ fixture = json.loads(_FIXTURE.read_text(encoding="utf-8"))+ target = fixture["target"]+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "config.yaml").write_text(+ f"exclude_patterns:\n - {fixture['excluded_path']}\n", encoding="utf-8"+ )++ async with factory() as session:+ await session.execute(delete(GraphEdge).where(GraphEdge.repository_id == setup_mcp))+ await session.execute(delete(GraphNode).where(GraphNode.repository_id == setup_mcp))+ for index, node_id in enumerate(fixture["nodes"]):+ session.add(+ GraphNode(+ id=f"sealed-node-{index}",+ repository_id=setup_mcp,+ node_id=node_id,+ node_type="file",+ language="python",+ pagerank=0.01 + index / 1000,+ )+ )+ for index, edge in enumerate(fixture["edges"]):+ session.add(+ GraphEdge(+ id=f"sealed-edge-{index}",+ repository_id=setup_mcp,+ source_node_id=edge["source"],+ target_node_id=edge["target"],+ edge_type=edge["type"],+ imported_names_json="[]",+ )+ )+ meta = (+ await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == setup_mcp,+ GitMetadata.file_path == target,+ )+ )+ ).scalar_one()+ meta.co_change_partners_json = json.dumps(fixture["co_changes"])+ await session.commit()++ cross_path = tmp_path / "cross_repo_edges.json"+ contracts_path = tmp_path / "contracts.json"+ cross_path.write_text(json.dumps(fixture["cross_repo"]), encoding="utf-8")+ contracts_path.write_text(json.dumps(fixture["contracts"]), encoding="utf-8")+ context = RepoContext(+ alias="alpha",+ path=tmp_path,+ session_factory=_state._session_factory,+ fts=_state._fts,+ vector_store=_state._vector_store,+ decision_store=_state._decision_store,+ vector_store_ready=_state._vector_store_ready or asyncio.Event(),+ _engine=None,+ )+ previous = (_state._registry, _state._cross_repo_enricher)+ _state._registry = _SealedRegistry(context)+ _state._cross_repo_enricher = CrossRepoEnricher(cross_path, contracts_path)+ try:+ yield {+ "normal": await get_risk([target], repo="alpha", include=["graph"]),+ "pr": await get_risk([target], repo="alpha", changed_files=[target], include=["graph"]),+ }+ finally:+ _state._registry, _state._cross_repo_enricher = previous+++def _card(payload: dict) -> dict:+ external = payload.get("normal", payload)+ return external["targets"]["src/auth/service.py"]+++async def test_directed_dependents_preserve_direction_distance_and_structural_claim(+ relationship_payload,+):+ card = _card(relationship_payload)+ rows = {row["file_path"]: row for row in card["dependents"]}++ assert "src/direct_0.py" in rows+ assert rows["src/direct_0.py"]["direct"] is True+ assert rows["src/direct_0.py"]["distance"] == 1+ assert rows["src/direct_0.py"]["evidence_kind"] == "structural"+ assert rows["src/direct_0.py"]["claim"] == "structural_reach"+ assert card["relationship_analysis"]["dependencies"]["runtime_breakage_claim"] is False+ assert "src/db/models.py" not in rows # target depends on it: reverse direction+ assert "docs/cochange-only.md" not in rows # temporal graph edge is not structural+ assert "src/unknown.py" not in rows # untyped graph edge is not structural+ assert card["direct_dependents_total"] == 6+ assert card["transitive_dependents_total"] == 1+ assert "6 direct dependents" in card["risk_summary"]+++async def test_transitive_dependency_and_totals_are_exact_after_exclusion(+ relationship_payload,+):+ card = _card(relationship_payload)+ transitive = next(row for row in card["dependents"] if row["file_path"] == "src/transitive.py")++ assert transitive["direct"] is False+ assert transitive["distance"] == 2+ assert transitive["relationship_types"] == ["transitive_dependency"]+ assert transitive["via"] == "src/direct_0.py"+ assert card["dependents_count"] == 6+ assert card["dependents_total"] == 7+ assert card["dependents_emitted"] == len(card["dependents"]) == 5+ assert card["dependents_truncated"] is True+ assert all(row["file_path"] != "src/excluded.py" for row in card["dependents"])+ assert "src/excluded_child.py" not in {row["file_path"] for row in card["dependents"]}+ assert all(+ edge["source"] != "src/excluded.py" and edge["target"] != "src/excluded.py"+ for row in card["dependents"]+ for edge in row["path"]+ )+ assert card["impact_surface_total"] == 7+ assert card["impact_surface_emitted"] == len(card["impact_surface"]) == 3+ assert card["impact_surface_truncated"] is True+++async def test_co_change_is_historical_only_and_mixed_evidence_stays_separate(+ relationship_payload,+):+ card = _card(relationship_payload)+ partners = {row["file_path"]: row for row in card["co_change_partners"]}+ dependent_paths = {row["file_path"] for row in card["dependents"]}+ consumer_paths = {row["consumer_file"] for row in card["consumers"]}++ only = partners["docs/cochange-only.md"]+ assert only["relationship_type"] == "co_change"+ assert only["evidence_kind"] == "historical"+ assert only["provenance"] == "git_history"+ assert only["support"] == 7+ assert only["has_structural_link"] is False+ assert only["file_path"] not in dependent_paths | consumer_paths++ mixed = partners["src/direct_0.py"]+ assert mixed["has_structural_link"] is True+ assert mixed["structural_relationship_types"] == ["imports"]+ assert card["co_change_partners_total"] == 6+ assert card["co_change_partners_emitted"] == len(card["co_change_partners"]) == 5+ assert card["co_change_partners_truncated"] is True+ assert "src/excluded.py" not in partners+++async def test_typed_consumers_do_not_absorb_dependents_or_co_changes(relationship_payload):+ card = _card(relationship_payload)++ assert card["consumers_total"] == 2+ assert card["consumers_emitted"] == len(card["consumers"]) == 2+ assert card["consumers_truncated"] is False+ consumer = next(row for row in card["consumers"] if row["consumer_repository"] == "beta")+ assert consumer["provider_repository"] == "alpha"+ assert consumer["consumer_repository"] == "beta"+ assert consumer["direction"] == "provider_to_consumer"+ assert consumer["contract_type"] == "http"+ assert consumer["evidence_kind"] == "contract"+ assert {row["consumer_file"] for row in card["consumers"]} == {+ "src/auth/service.py",+ "src/local_consumer.py",+ }+ assert card["dependents_count"] == card["direct_dependents_total"] == 6+++async def test_cross_repo_links_keep_identity_direction_type_and_exact_totals(+ relationship_payload,+):+ card = _card(relationship_payload)+ links = card["cross_repo_links"]++ assert card["cross_repo_links_total"] == 9+ assert card["cross_repo_links_emitted"] == len(links) == 5+ assert card["cross_repo_links_truncated"] is True+ assert all(+ not (row.get("source_repository") == "alpha" and row.get("target_repository") == "alpha")+ for row in links+ )+ provider = next(row for row in links if row["relationship_type"] == "contract_consumer")+ assert (provider["provider_repository"], provider["consumer_repository"]) == (+ "alpha",+ "beta",+ )+ assert (provider["provider_file"], provider["consumer_file"]) == (+ "src/auth/service.py",+ "src/auth/service.py",+ )+ reverse = next(row for row in links if row["relationship_type"] == "contract_provider")+ assert (reverse["provider_repository"], reverse["consumer_repository"]) == (+ "gamma",+ "alpha",+ )+ co_change = next(row for row in links if row["relationship_type"] == "co_change")+ assert co_change["direction"] == "undirected"+ assert co_change["evidence_kind"] == "historical"+ assert co_change["source_repository"] != co_change["target_repository"]+ package = next(row for row in links if row["relationship_type"] == "package_dependency")+ assert (package["source_repository"], package["target_repository"]) == ("delta", "alpha")+ assert package["direction"] == "consumer_to_dependency"+ assert package["granularity"] == "repository"+ assert package["target_file"] is None+ assert card["relationship_analysis"]["cross_repo"]["status"] == "partial"+ assert (+ card["relationship_analysis"]["cross_repo"]["sources"]["cross_repo_overlay"][+ "source_truncated"+ ]+ is True+ )+++async def test_legacy_fields_are_labeled_and_do_not_contradict_typed_fields(+ relationship_payload,+):+ card = _card(relationship_payload)+ legacy = card["cross_repo_impact"]++ assert legacy["cross_repo_consumers_semantics"] == "historical_co_change_partners"+ assert legacy["cross_repo_consumers_deprecated"] is True+ assert legacy["cross_repo_consumers_total"] == 6+ assert legacy["cross_repo_consumers_emitted"] == len(legacy["cross_repo_consumers"]) == 5+ assert legacy["cross_repo_consumers_truncated"] is True+ assert all(+ row["relationship_type"] == "co_change" and row["evidence_kind"] == "historical"+ for row in legacy["cross_repo_consumers"]+ )+ assert legacy["contract_consumers_total"] == 1+ assert card["consumers_total"] == 2+ assert all(row["relationship_type"] == "contract_consumer" for row in card["consumers"])+ assert card["dependents_count"] == 6+++async def test_pr_exclusion_stops_traversal_before_nonexcluded_child(relationship_payload):+ blast = relationship_payload["pr"]["pr_blast_radius"]+ paths = {row["path"] for row in blast["transitive_affected"]}++ assert "src/excluded.py" not in paths+ assert "src/excluded_child.py" not in paths+ assert blast["transitive_affected_total"] == len(blast["transitive_affected"])+++async def test_pr_mode_updates_co_change_emitted_count_after_its_second_cap(setup_mcp, factory):+ from sqlalchemy import select++ from repowise.server.mcp_server import get_risk++ async with factory() as session:+ meta = (+ await session.execute(+ select(GitMetadata).where(GitMetadata.file_path == "src/auth/service.py")+ )+ ).scalar_one()+ partners = json.loads(meta.co_change_partners_json)+ partners.extend(+ {"file_path": f"src/history_{index}.py", "count": 10 - index} for index in range(4)+ )+ meta.co_change_partners_json = json.dumps(partners)+ await session.commit()++ payload = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])+ card = _card(payload)+ assert card["co_change_partners_total"] == 6+ assert card["co_change_partners_emitted"] == len(card["co_change_partners"]) == 3+ assert card["co_change_partners_truncated"] is True+++async def test_valid_empty_workspace_analysis_is_not_reported_as_unknown(setup_mcp, tmp_path):+ from repowise.server.mcp_server import get_risk++ cross_path = tmp_path / "cross_repo_edges.json"+ contracts_path = tmp_path / "contracts.json"+ cross_path.write_text(+ json.dumps({"version": 2, "co_changes": [], "package_deps": []}),+ encoding="utf-8",+ )+ contracts_path.write_text(+ json.dumps({"version": 2, "contracts": [], "contract_links": []}),+ encoding="utf-8",+ )+ context = RepoContext(+ alias="alpha",+ path=tmp_path,+ session_factory=_state._session_factory,+ fts=_state._fts,+ vector_store=_state._vector_store,+ decision_store=_state._decision_store,+ vector_store_ready=_state._vector_store_ready or asyncio.Event(),+ _engine=None,+ )+ previous = (_state._registry, _state._cross_repo_enricher)+ _state._registry = _SealedRegistry(context)+ _state._cross_repo_enricher = CrossRepoEnricher(cross_path, contracts_path)+ try:+ card = _card(await get_risk(["src/auth/service.py"], repo="alpha", include=["graph"]))+ finally:+ _state._registry, _state._cross_repo_enricher = previous++ assert card["consumers"] == []+ assert card["consumers_total"] == card["consumers_emitted"] == 0+ assert card["relationship_analysis"]["consumers"]["status"] == "available"+ assert card["cross_repo_links"] == []+ assert card["cross_repo_links_total"] == card["cross_repo_links_emitted"] == 0+ assert card["relationship_analysis"]["cross_repo"]["status"] == "available"diff --git a/tests/unit/server/test_enrichment_contracts.py b/tests/unit/server/test_enrichment_contracts.pyindex 0d0ee4292..9e418e348 100644--- a/tests/unit/server/test_enrichment_contracts.py+++ b/tests/unit/server/test_enrichment_contracts.py@@ -8,6 +8,7 @@ from pathlib import Pathimport pytestfrom repowise.server.mcp_server._enrichment import CrossRepoEnricher+from repowise.server.mcp_server.tool_risk.enrichment import _combined_analysisdef _write_json(path: Path, data: dict) -> None:@@ -72,6 +73,8 @@ class TestEnricherContractLoading:def test_no_contracts_path(self, empty_cross_repo: Path) -> None:enricher = CrossRepoEnricher(empty_cross_repo)assert enricher.has_contract_data is False+ assert enricher.cross_repo_analysis["status"] == "available"+ assert enricher.contract_analysis["status"] == "unavailable"def test_missing_contracts_file(self, empty_cross_repo: Path, tmp_path: Path) -> None:enricher = CrossRepoEnricher(@@ -79,6 +82,64 @@ class TestEnricherContractLoading:contracts_path=tmp_path / "nonexistent.json",)assert enricher.has_contract_data is False+ assert enricher.contract_analysis == {+ "status": "unavailable",+ "reason": "artifact_missing",+ }++ def test_valid_empty_contract_artifact_is_available(+ self, empty_cross_repo: Path, tmp_path: Path+ ) -> None:+ contracts = tmp_path / "contracts.json"+ _write_json(contracts, {"version": 2, "contracts": [], "contract_links": []})+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts)++ assert enricher.has_contract_data is False+ assert enricher.contract_analysis["status"] == "available"++ def test_malformed_artifacts_are_degraded(self, tmp_path: Path) -> None:+ cross_repo = tmp_path / "cross_repo_edges.json"+ contracts = tmp_path / "contracts.json"+ cross_repo.write_text("{", encoding="utf-8")+ contracts.write_text("{", encoding="utf-8")+ enricher = CrossRepoEnricher(cross_repo, contracts_path=contracts)++ assert enricher.cross_repo_analysis["status"] == "degraded"+ assert enricher.contract_analysis["status"] == "degraded"++ def test_malformed_rows_make_otherwise_valid_artifacts_partial(self, tmp_path: Path) -> None:+ cross_repo = tmp_path / "cross_repo_edges.json"+ contracts = tmp_path / "contracts.json"+ _write_json(+ cross_repo,+ {"version": 2, "co_changes": [{"source_repo": "alpha"}], "package_deps": []},+ )+ _write_json(+ contracts,+ {"version": 2, "contracts": [], "contract_links": [{"provider_repo": "alpha"}]},+ )+ enricher = CrossRepoEnricher(cross_repo, contracts_path=contracts)++ assert enricher.cross_repo_analysis["status"] == "partial"+ assert enricher.cross_repo_analysis["malformed_co_changes_skipped"] == 1+ assert enricher.contract_analysis["status"] == "partial"+ assert enricher.contract_analysis["malformed_contract_links_skipped"] == 1++ @pytest.mark.parametrize(+ ("cross_state", "contract_state"),+ [+ ({"status": "available"}, {"status": "unavailable"}),+ ({"status": "unavailable"}, {"status": "available"}),+ ],+ )+ def test_mixed_source_availability_is_partial(+ self, cross_state: dict, contract_state: dict+ ) -> None:+ analysis = _combined_analysis(cross_state, contract_state, [])++ assert analysis["status"] == "partial"+ assert analysis["sources"]["cross_repo_overlay"] == cross_state+ assert analysis["sources"]["contracts"] == contract_statedef test_loads_contract_links(self, empty_cross_repo: Path, contracts_json: Pathdiff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pyindex 537414501..a14bb558a 100644--- a/tests/unit/server/test_mcp_blast_radius.py+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -145,9 +145,24 @@ def test_cross_repo_directive_splits_structural_and_behavioral(workspace_state):# 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)+ assert all(e["relationship_type"] == "structural_dependency" for e in will_break)+ assert all(e["direction"] == "consumer_to_dependency" for e in will_break)+ assert all(e["claim"] == "structural_reach" for e in will_break)+ assert all(e["runtime_breakage_claim"] is False for e in will_break)+ assert all(e["consumer_repository"] != e["dependency_repository"] for e in will_break)# No cross-repo co-change edges in this fixture.assert missing_cochanges == []+ from repowise.server.mcp_server.tool_risk.directives import _cross_repo_relationships++ relationships = _cross_repo_relationships("backend")+ assert relationships["structural_total"] == len(will_break)+ assert len(relationships["structural"]) <= relationships["structural_total"]+ assert relationships["analysis"]["status"] == "partial"+ assert relationships["analysis"]["evidence_resolution"] == "aggregated_path_edge_kinds"+ assert relationships["analysis"]["generated_at"] == "t"+ assert relationships["analysis"]["freshness"]["status"] == "unavailable"+def test_cross_repo_directive_empty_outside_workspace():from repowise.server.mcp_server import _state