Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): surface cross-repo test impact on get_change_risk, get_blast_radius, the API and the contract page (#2123)
Raghav Chamadiya06c0ba8cb5ff
diff --git a/README.md b/README.mdindex 967f24bc6..87e2821bf 100644--- a/README.md+++ b/README.md@@ -398,6 +398,7 @@ change, and the architecture rule the new dependency violates before it ships.| **Contract map** | Which services provide and consume each HTTP, gRPC, event, socket, and data contract? Links retain exact/candidate confidence and the source evidence. || **Cross-repo blast radius** | If this provider changes, which downstream services **will break** through structural dependencies, and which ones **may drift** through historical co-change? || **Breaking-change guard** | Was an endpoint removed or a typed contract changed incompatibly, and which exact consumer files call it? |+| **Test impact** | Which tests in the consumer repos should run for this provider change, measured from coverage or inferred from the call graph, and which links could not be determined? || **Architecture as code** | Does the live system graph violate declared dependency rules or contain cycles? `repowise workspace check` gates CI. || **Architecture health** | How coupled is the estate? Track propagation cost, the cyclic core, service roles, and a deterministic 1–10 architecture score. || **Federated context** | One dashboard and one MCP server answer across every repository while preserving repo-level evidence. |diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex da1c4240e..186fc9218 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -591,6 +591,18 @@ the same distinction in one word: `measured`, `inferred`, or absent. Build themeasured map with `coverage run --contexts=test` followed by`repowise coverage add`.+In workspace mode the response also carries `cross_repo`, and every+`cross_repo.consumers[]` row gains a `tests` block: a `state` (`measured`,+`inferred`, `none` or `unresolved`), up to five `tests_to_run` rows carrying+`test_file`, `test_id`, `basis`, `via` and `confidence`, `total` and+`truncated` for the overflow (the tail goes to the omission store), and+`unresolved_reason` / `unresolved_detail` when the join could not be followed.+Only `tests_to_run` is capped at five; `total` is the true number of tests+found for that consumer, so `truncated: true` means `total` minus five went to+the omission store. `unresolved_reason: "lookup_failed"` is the state every row+lands in when the join itself failed, as opposed to one link that could not be+followed, and `unresolved_detail` names what failed.+> **Output-schema change.** `impacted_tests.tests` is now> `impacted_tests.tests_to_run`, matching `get_risk`'s directive.@@ -1064,6 +1076,11 @@ path weight, not a breakage probability), each with `distance` (hops),carried the impact; plus `impact_score_semantics`, `impacted_repos`,`structural_count` / `behavioral_count`, `total_impacted`, and unresolved targets.+Each `symbol_targets[].consumers[]` row also carries a `tests` block of the same+shape as `get_change_risk`'s: which tests in that consumer repo guard the+symbol's contracts, capped at five with the tail in the omission store, and a+named reason when a link could not be followed.+**When to use:** Before changing a high-fan-out provider, see who structurallyconsumes it across repo boundaries. Structural reach outweighs historicalco-change in ranking, but neither is a runtime-breakage claim. Reads the samediff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 7ce03d4bb..a93dffe5a 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -433,6 +433,12 @@ An empty answer always says which of these produced it, so "no tests" is never aResults are capped per consumer and provider pair so one widely-called helper cannot flood the list; when the cap bites, the command prints how many it dropped and `--format json` carries the exact counts.+Use it three ways:++- **CLI**, `repowise workspace impacted-tests <repo:path>...`, the command above.+- **REST**, `GET /api/workspace/test-impact?repo=<alias>&file=<path>`. Repeat `file` for several changed files in the same repo. The response carries the same fields the `--format json` output has: `recommendations` (each with its consumer repo, the `consumer_files` and bound `consumer_symbol_ids` that reached the test, `basis`, `via`, `confidence` and the contract ids that produced it), `unresolved` with a reason per link, `files_analyzed` with the state each landed on, and the `summary` counts. Over the API an empty answer's `summary.reason` is `no_contract_data`, `no_matching_links` or `lookup_failed`.+- **Web UI**, a provider contract's page (`/workspace/contracts/detail`) ends in a **Tests to run** section: the tests grouped by consumer repo, each marked measured or inferred and saying whether the coverage map, the call graph or the import graph found it, and a **Could not determine** list naming the consumer file and the reason. A consumer contract has no such section, since tests are found on the consumer side.+---## Architecture Conformancediff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.tsindex 865f59baa..5c0e9dd8c 100644--- a/packages/api-client/src/types/workspace.ts+++ b/packages/api-client/src/types/workspace.ts@@ -226,6 +226,13 @@ export type {NodeArchitectureRole,NodeRole,ArchitectureType,+ WorkspaceTestRecommendation,+ WorkspaceUnresolvedLink,+ WorkspaceTestImpactFile,+ WorkspaceTestImpactResponse,+ TestImpactBasis,+ TestImpactState,+ TestImpactUnresolvedReason,} from "@repowise-dev/types";import type {diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.tsindex d936a05dd..dd48437d2 100644--- a/packages/api-client/src/workspace.ts+++ b/packages/api-client/src/workspace.ts@@ -11,6 +11,7 @@ import type {WorkspaceBreakingChangesResponse,WorkspaceConformanceResponse,WorkspaceArchitectureResponse,+ WorkspaceTestImpactResponse,ExtractionDiagnostics,} from "./types";@@ -170,3 +171,27 @@ export async function syncWorkspace(opts?: {params,);}++/**+ * Which tests in the consumer repos guard a change to these provider files.+ *+ * Rows carry the basis they came from: `measured` when a coverage map recorded+ * the test against the consumer call site, `inferred` when the consumer call or+ * import graph reaches it. Links the join could not follow come back in+ * `unresolved` with a reason, so an empty answer always names its state.+ */+export async function getWorkspaceTestImpact(+ repo: string,+ files: string[],+ fetchOptions?: RequestInit,+): Promise<WorkspaceTestImpactResponse> {+ // `file` repeats once per changed path, so the query is built here: the+ // shared param helper sets each key once.+ const query = new URLSearchParams({ repo });+ for (const file of files) query.append("file", file);+ return apiGet<WorkspaceTestImpactResponse>(+ `/api/workspace/test-impact?${query.toString()}`,+ undefined,+ fetchOptions,+ );+}diff --git a/packages/core/src/repowise/core/workspace/test_impact.py b/packages/core/src/repowise/core/workspace/test_impact.pyindex 79f096b65..3a5da034a 100644--- a/packages/core/src/repowise/core/workspace/test_impact.py+++ b/packages/core/src/repowise/core/workspace/test_impact.py@@ -60,8 +60,10 @@ class WorkspaceTestRecommendation:test_id: strtest_file: strconsumer_repo: str- consumer_file: str- consumer_symbol_id: str | None+ # Plural: merging folds every call site the one test guards into this row,+ # and only bound links reach a row, so no symbol id here is ever None.+ consumer_files: list[str]+ consumer_symbol_ids: list[str]provider_repo: strcontract_ids: list[str]contract_types: list[str]@@ -154,10 +156,9 @@ def _merge_recommendations()return replace(strongest,- consumer_file=min(first.consumer_file, second.consumer_file),- consumer_symbol_id=min(- (s for s in (first.consumer_symbol_id, second.consumer_symbol_id) if s),- default=None,+ consumer_files=sorted(set(first.consumer_files) | set(second.consumer_files)),+ consumer_symbol_ids=sorted(+ set(first.consumer_symbol_ids) | set(second.consumer_symbol_ids)),contract_ids=sorted(set(first.contract_ids) | set(second.contract_ids)),contract_types=sorted(set(first.contract_types) | set(second.contract_types)),@@ -317,8 +318,8 @@ async def _analyze_consumer(test_id=entry["test_id"],test_file=entry["test_file"],consumer_repo=alias,- consumer_file=path,- consumer_symbol_id=link.consumer_symbol_id,+ consumer_files=[path],+ consumer_symbol_ids=[link.consumer_symbol_id],provider_repo=link.provider_repo,contract_ids=[link.contract_id],contract_types=[link.contract_type],@@ -360,8 +361,8 @@ async def _analyze_consumer(test_id=test_id,test_file=test_id.split("::", 1)[0],consumer_repo=alias,- consumer_file=path,- consumer_symbol_id=link.consumer_symbol_id,+ consumer_files=[path],+ consumer_symbol_ids=[link.consumer_symbol_id],provider_repo=link.provider_repo,contract_ids=[link.contract_id],contract_types=[link.contract_type],@@ -414,11 +415,13 @@ async def analyze_workspace_test_impact(include_inferred: bool = True,min_confidence: float = 0.0,target_repos: Collection[str] | None = None,+ max_tests_per_pair: int | None = MAX_TESTS_PER_TARGET,) -> WorkspaceTestImpactResult:"""Tests in consumer repos that guard *changed_files* in provider repos.*index* and *links* are supplied by the caller, so a request handler that- already holds both opens nothing here.+ already holds both opens nothing here. ``max_tests_per_pair=None`` turns+ the per-pair cap off, for a caller that caps and banks the tail itself."""changed_by_provider: dict[str, set[str]] = defaultdict(set)for entry in changed_files:@@ -505,13 +508,16 @@ async def analyze_workspace_test_impact(deduplicated = sorted(seen.values(), key=_recommendation_sort_key)- capped: list[WorkspaceTestRecommendation] = []- counts: dict[tuple[str, str], int] = defaultdict(int)- for rec in deduplicated:- pair = (rec.consumer_repo, rec.provider_repo)- if counts[pair] < MAX_TESTS_PER_TARGET:- capped.append(rec)- counts[pair] += 1+ if max_tests_per_pair is None:+ capped = deduplicated+ else:+ capped = []+ counts: dict[tuple[str, str], int] = defaultdict(int)+ for rec in deduplicated:+ pair = (rec.consumer_repo, rec.provider_repo)+ if counts[pair] < max_tests_per_pair:+ capped.append(rec)+ counts[pair] += 1by_basis: dict[str, int] = {"measured": 0, "inferred": 0}by_repo: dict[str, int] = defaultdict(int)@@ -584,8 +590,8 @@ def workspace_test_impact_to_dict(result: WorkspaceTestImpactResult) -> dict[str"test_id": r.test_id,"test_file": r.test_file,"consumer_repo": r.consumer_repo,- "consumer_file": r.consumer_file,- "consumer_symbol_id": r.consumer_symbol_id,+ "consumer_files": r.consumer_files,+ "consumer_symbol_ids": r.consumer_symbol_ids,"provider_repo": r.provider_repo,"contract_ids": r.contract_ids,"contract_types": r.contract_types,diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex e01f8ca92..cc802fb03 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -448,6 +448,11 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:await _repo_registry.close()# The enricher is only ever published alongside the registry.set_tool_workspace(registry=None, workspace_root=None, cross_repo_enricher=None)+ # The test-impact join holds its own session per consumer repo.+ from repowise.server.mcp_server._test_impact import close_test_impact_indexes++ with suppress(Exception):+ await close_test_impact_indexes()# Dispose workspace repo engines firstfor ws_engine in getattr(app.state, "workspace_engines", []):with suppress(Exception):diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 06b866eff..a277e70f6 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -619,6 +619,14 @@ async def execute_job(enricher = getattr(app_state, "cross_repo_enricher", None)if enricher is not None and hasattr(enricher, "reload"):enricher.reload()+ # Imported here because a single-repo server never gets this+ # far: the contract map and the consumer indexes the join+ # reads change together, so a reload of one invalidates both.+ from repowise.server.mcp_server._test_impact import (+ close_test_impact_indexes,+ )++ await close_test_impact_indexes()except Exception:logger.debug("enricher_reload_failed", job_id=job_id, exc_info=True)diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 9531cef86..2c3497ee9 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -461,6 +461,10 @@ async def _lifespan(server: FastMCP):await _cancel_task(_warm_task)_state._lancedb_ready = None_state._cross_repo_enricher = None+ # The test-impact join holds its own session per consumer repo.+ from repowise.server.mcp_server._test_impact import close_test_impact_indexes++ await close_test_impact_indexes()await registry.close()_state._registry = None_state._workspace_root = Nonediff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.pyindex afdea6f8f..117de3ef7 100644--- a/packages/server/src/repowise/server/mcp_server/_state.py+++ b/packages/server/src/repowise/server/mcp_server/_state.py@@ -35,6 +35,17 @@ _registry: Any = None # RepoRegistry | None_workspace_root: str | None = None_cross_repo_enricher: Any = None # CrossRepoEnricher | None+# Consumer repo indexes held open for the cross-repo test-impact join, keyed by+# alias. Opening one costs a full symbol-table load, so a repo is opened once+# and reused across tool calls; ``None`` records a repo that has no index. Each+# holds one database session, and a session is not concurrent-safe, so the lock+# below serializes the joins that read them. Both are cleared by+# ``_test_impact.close_test_impact_indexes()`` where the enricher is dropped.+_test_impact_indexes: dict[str, Any] = {}+# The loop the lock was created on, paired with the lock: an asyncio.Lock is+# bound to one event loop, and a test or an embedded server can run a second.+_test_impact_lock: tuple[Any, asyncio.Lock] | None = None+# Embedder health — set by _resolve_embedder() in _server.py. ``None`` until an# embedder is resolved. When an explicitly-configured embedder fails to# initialise we still fall back to MockEmbedder (so non-RAG tools stay up) butdiff --git a/packages/server/src/repowise/server/mcp_server/_test_impact.py b/packages/server/src/repowise/server/mcp_server/_test_impact.pynew file mode 100644index 000000000..6fb98b298--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_test_impact.py@@ -0,0 +1,280 @@+"""Cross-repo test impact for the MCP tools that already name consumers.++``get_change_risk`` and ``get_blast_radius`` both hand an agent a list of+consumer call sites in other repos. The question that follows is always "so+what do I run?", and the workspace already holds the answer: the contract links+say which consumer symbol sits on the far side, and each consumer repo's index+says which of its tests reach that symbol. This module joins the two and shapes+one small block per consumer row.++Both tools stay usable outside workspace mode: every entry point returns+``None`` or an empty block instead of raising, so a caller omits the block+instead of reporting a failure.+"""++from __future__ import annotations++import asyncio+import logging+from typing import TYPE_CHECKING, Any++from repowise.server.mcp_server import _state++if TYPE_CHECKING:+ from collections.abc import Mapping, Sequence++ from repowise.core.workspace.test_impact import WorkspaceTestImpactResult+ from repowise.server.mcp_server._budget import OmissionCollector++_log = logging.getLogger("repowise.mcp.test_impact")++#: Tests named inline per consumer row. The rows are numerous and the tail is+#: recoverable through the omission store, so the inline list stays short.+_TESTS_PER_CONSUMER_LIMIT = 5++_BASIS_ORDER = {"measured": 0, "inferred": 1}++__all__ = [+ "close_test_impact_indexes",+ "cross_repo_tests",+ "cross_repo_tests_for",+ "tests_block_for",+]+++def _norm(path: str) -> str:+ """The same one comparable spelling ``core.workspace.test_impact`` uses."""+ cleaned = (path or "").replace("\\", "/")+ while cleaned.startswith("./"):+ cleaned = cleaned[2:]+ return cleaned+++def _lock() -> asyncio.Lock:+ """The one lock guarding the process-held indexes.++ Each cached index holds a single database session, and a session is not+ concurrent-safe, so two overlapping tool calls must not share one. The lock+ is stored with the loop it was made on, because a lock bound to a loop that+ has gone away can never be acquired again.+ """+ loop = asyncio.get_running_loop()+ held = _state._test_impact_lock+ if held is None or held[0] is not loop:+ held = (loop, asyncio.Lock())+ _state._test_impact_lock = held+ return held[1]+++def _empty_result(reason: str, detail: str | None = None) -> WorkspaceTestImpactResult:+ """An answer that says why it is empty, so silence is never unexplained."""+ from repowise.core.workspace.test_impact import WorkspaceTestImpactResult++ summary: dict[str, Any] = {"reason": reason}+ if detail is not None:+ summary["detail"] = detail+ return WorkspaceTestImpactResult(summary=summary)+++async def _consumer_index(alias: str) -> Any:+ """The open index for consumer *alias*, opening it on first use.++ The primary repo is never a consumer of itself here and holds the largest+ symbol table in the workspace, so only the consumer repos the links name+ are ever opened.+ """+ cache = _state._test_impact_indexes+ if alias in cache:+ return cache[alias]+ registry = _state._registry+ ws_config = getattr(registry, "ws_config", None)+ root = getattr(registry, "workspace_root", None)+ if ws_config is None or root is None:+ return None+ entry = next((e for e in ws_config.repos if e.alias == alias), None)+ if entry is None:+ return None++ from repowise.core.workspace.repo_index import open_repo_index++ try:+ index = await open_repo_index(alias, (root / entry.path).resolve())+ except Exception:+ _log.debug("Could not open the index for '%s'", alias, exc_info=True)+ index = None+ # Only a real index is cached. Re-checking a repo without one costs a+ # single stat, and it lets a repo indexed later start answering without a+ # restart of this process.+ if index is not None:+ cache[alias] = index+ return index+++async def cross_repo_tests_for(+ changed_by_repo: Mapping[str, Sequence[str]],+) -> WorkspaceTestImpactResult | None:+ """One join over every provider repo and file a tool call touches.++ ``None`` only outside workspace mode or without contract data, so a caller+ can omit its block entirely. Every other empty answer names its reason in+ ``summary``: ``no_matching_links`` when the contract map knows no consumer+ of those files, ``lookup_failed`` when the join itself broke. Never raises.+ """+ if _state._registry is None:+ return None+ enricher = _state._cross_repo_enricher+ if enricher is None or not getattr(enricher, "has_contract_data", False):+ return None+ try:+ from repowise.core.workspace.contracts import ContractLink+ from repowise.core.workspace.repo_index import WorkspaceIndex+ from repowise.core.workspace.test_impact import analyze_workspace_test_impact++ # Straight off the loaded artifact; contracts.json is never re-read.+ seen: set[int] = set()+ links = []+ changed: list[dict[str, str]] = []+ for alias, paths in sorted(changed_by_repo.items()):+ for path in sorted(set(paths)):+ changed.append({"repo": alias, "path": path})+ for raw in enricher.get_contract_links_as_provider(alias, path):+ if id(raw) in seen:+ continue+ seen.add(id(raw))+ links.append(ContractLink.from_dict(raw))++ consumers = sorted(+ {lk.consumer_repo for lk in links if lk.consumer_repo != lk.provider_repo}+ )+ if not changed or not consumers:+ return _empty_result("no_matching_links")++ async with _lock():+ opened = {}+ for consumer in consumers:+ index = await _consumer_index(consumer)+ if index is not None:+ opened[consumer] = index+ # A copy, so WorkspaceIndex.close() can never empty the cache. The+ # per-pair cap is off because this caller caps its own inline list+ # and banks the tail, so it needs the true total.+ return await analyze_workspace_test_impact(+ WorkspaceIndex(dict(opened)),+ links,+ changed,+ target_repos=set(consumers),+ max_tests_per_pair=None,+ )+ except Exception as exc:+ _log.debug("Cross-repo test impact unavailable", exc_info=True)+ return _empty_result("lookup_failed", type(exc).__name__)+++async def cross_repo_tests(+ alias: str, changed_files: list[str]+) -> WorkspaceTestImpactResult | None:+ """Tests in other repos that guard *changed_files* in repo *alias*."""+ if not changed_files:+ return None+ return await cross_repo_tests_for({alias: changed_files})+++def tests_block_for(+ result: WorkspaceTestImpactResult | None,+ consumer_repo: str,+ consumer_file: str,+ contract_id: str,+ collector: OmissionCollector | None,+ label: str,+) -> dict[str, Any]:+ """The ``tests`` block for one consumer row of a tool payload.++ The rows are read as the join produced them: the state is whichever signal+ the join actually reached, and a link it could not follow keeps its reason+ instead of being reported as "no tests".+ """+ block: dict[str, Any] = {+ "state": "none",+ "tests_to_run": [],+ "total": 0,+ "truncated": False,+ "unresolved_reason": None,+ "unresolved_detail": None,+ }+ if result is None:+ return block+ # A join that broke says so on every row it would have answered, so no row+ # reads as "nothing guards this".+ if result.summary.get("reason") == "lookup_failed":+ block["state"] = "unresolved"+ block["unresolved_reason"] = "lookup_failed"+ block["unresolved_detail"] = result.summary.get("detail")+ return block+ path = _norm(consumer_file)+ rows = [+ rec+ for rec in result.recommendations+ if rec.consumer_repo == consumer_repo+ and path in rec.consumer_files+ and contract_id in rec.contract_ids+ ]+ unresolved = next(+ (+ u+ for u in result.unresolved+ if u.consumer_repo == consumer_repo+ and u.consumer_file == path+ and u.contract_id == contract_id+ ),+ None,+ )+ if rows:+ rows.sort(key=lambda r: _BASIS_ORDER.get(r.basis, 99))+ block["state"] = rows[0].basis+ elif unresolved is not None:+ # The reason belongs to the unresolved state alone: a row that did find+ # tests through some other link is answered, not undetermined.+ block["state"] = "unresolved"+ block["unresolved_reason"] = unresolved.reason+ block["unresolved_detail"] = unresolved.detail++ tests = [+ {+ "test_file": rec.test_file,+ "test_id": rec.test_id,+ "basis": rec.basis,+ "via": rec.via,+ "confidence": rec.confidence,+ }+ for rec in rows+ ]+ block["total"] = len(tests)+ block["truncated"] = len(tests) > _TESTS_PER_CONSUMER_LIMIT+ if block["truncated"] and collector is not None:+ dropped = len(tests) - _TESTS_PER_CONSUMER_LIMIT+ collector.add(+ f"{label} beyond cap={_TESTS_PER_CONSUMER_LIMIT} ({dropped} dropped)",+ tests[_TESTS_PER_CONSUMER_LIMIT:],+ )+ block["tests_to_run"] = tests[:_TESTS_PER_CONSUMER_LIMIT]+ return block+++async def close_test_impact_indexes() -> None:+ """Release every consumer index this process opened. Never raises.++ Closing runs under the lock so no join is mid-query on a session being torn+ down, and the lock is dropped with the indexes it guarded so the next call+ binds a fresh one to whatever loop is running then.+ """+ async with _lock():+ cache = _state._test_impact_indexes+ for alias, index in list(cache.items()):+ if index is None:+ continue+ try:+ await index.close()+ except Exception:+ _log.debug("Error closing the index for '%s'", alias, exc_info=True)+ cache.clear()+ _state._test_impact_lock = Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.pyindex 76308de31..e2211b5d3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py@@ -14,9 +14,11 @@ from typing import Anyfrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import _is_workspace_modefrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import persisted_analysis_meta as _analysis_meta+from repowise.server.mcp_server._test_impact import cross_repo_tests_for, tests_block_for#: How many impacted services the MCP response carries inline. The full set is#: available via the REST endpoint / the map; here we keep the agent payload@@ -88,7 +90,10 @@ async def get_blast_radius(# Only targets the node/alias resolver rejected are tried as symbol ids, so# a string that already names a node keeps its existing meaning._, unresolved = resolve_targets(graph, targets)- symbol_targets, effective = _resolve_symbol_targets(enricher, graph, targets, unresolved)+ collector = OmissionCollector("get_blast_radius", repo_root=_state._repo_path)+ symbol_targets, effective = await _resolve_symbol_targets(+ enricher, graph, targets, unresolved, collector+ )result = cross_repo_blast_radius(graph,effective,@@ -144,6 +149,7 @@ async def get_blast_radius(}if symbol_targets:payload["symbol_targets"] = symbol_targets+ collector.attach(payload)return payload@@ -167,11 +173,12 @@ def _graph_node_for(nodes_by_repo: dict[str, list[Any]], contract: dict[str, Anyreturn best-def _resolve_symbol_targets(+async def _resolve_symbol_targets(enricher: Any,graph: Any,targets: list[str],unresolved: list[str],+ collector: OmissionCollector | None = None,) -> tuple[list[dict[str, Any]], list[str]]:"""Expand symbol-id targets into graph nodes plus their symbol-level consumers.@@ -185,6 +192,11 @@ def _resolve_symbol_targets(nodes_by_repo: dict[str, list[Any]] = defaultdict(list)for node in graph.nodes:nodes_by_repo[node.repo].append(node)++ pending: list[dict[str, Any]] = []+ # Every symbol target's provider files, collected before any lookup runs,+ # so one join answers the whole call over one set of opened indexes.+ changed_by_repo: dict[str, set[str]] = defaultdict(set)for raw in dict.fromkeys(unresolved):# Providers only: a consumer contract's symbol calls a surface rather# than publishing one, so it has no downstream to traverse.@@ -216,19 +228,70 @@ def _resolve_symbol_targets(}for link in links[:_SYMBOL_CONSUMER_LIMIT]]+ # A symbol with no consumers has nothing to join, so nothing opens.+ if links:+ for c in contracts:+ if c.get("repo") and c.get("file_path"):+ changed_by_repo[c["repo"]].add(c["file_path"])+ pending.append(+ {+ "symbol_id": raw,+ "nodes": nodes,+ "contracts": contracts,+ "repos": repos,+ "links": links,+ "consumers": consumers,+ }+ )++ impact = (+ await cross_repo_tests_for(+ {repo: sorted(files) for repo, files in sorted(changed_by_repo.items())}+ )+ if changed_by_repo+ else None+ )++ for item in pending:+ contracts = item["contracts"]+ links = item["links"]+ consumers = item["consumers"]+ tests_total = 0+ unresolved_total = 0+ for j, (row, link) in enumerate(zip(consumers, links, strict=False)):+ # A consumer in the provider's own repo is one program calling+ # itself. The join drops those links, so the row gets no tests key+ # instead of a block that would read as "no tests guard this".+ if impact is None or link.get("consumer_repo") == link.get("provider_repo"):+ continue+ row["tests"] = tests_block_for(+ impact,+ row.get("repo") or "",+ row.get("file") or "",+ row.get("contract_id") or "",+ collector,+ f"symbol_targets[{len(blocks)}].consumers[{j}].tests.tests_to_run",+ )+ tests_total += row["tests"]["total"]+ unresolved_total += 1 if row["tests"]["state"] == "unresolved" else 0block: dict[str, Any] = {- "symbol_id": raw,- "nodes": nodes,+ "symbol_id": item["symbol_id"],+ "nodes": item["nodes"],"contract_ids": sorted({c["contract_id"] for c in contracts if c.get("contract_id")}),"consumers": consumers,"consumer_count": len(links),"consumers_truncated": max(0, len(links) - len(consumers)),}+ if any("tests" in row for row in consumers):+ block["tests_summary"] = (+ f"tests to run: {tests_total} across {len(consumers)} consumer(s), "+ f"{unresolved_total} unresolved"+ )# Symbol ids are repo-relative, so one id can name two symbols.- if len(repos) > 1:- block["ambiguous_in_repos"] = repos+ if len(item["repos"]) > 1:+ block["ambiguous_in_repos"] = item["repos"]blocks.append(block)- replacements[raw] = nodes+ replacements[item["symbol_id"]] = item["nodes"]if not replacements:return [], targetsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 15bcd1415..d9f7c8366 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -48,6 +48,11 @@ from repowise.server.mcp_server._helpers import (resolve_enum_argument,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._test_impact import (+ _norm,+ cross_repo_tests,+ tests_block_for,+)log = structlog.get_logger(__name__)@@ -210,7 +215,11 @@ async def get_change_risk(prior_fixes = await _prior_fixes_block(ctx, changed)if prior_fixes is not None:payload["prior_fixes"] = prior_fixes- cross_repo = _cross_repo_block(getattr(ctx, "alias", ""), sorted(changed))+ alias = getattr(ctx, "alias", "")+ # The join needs an open index per consumer repo, so it runs once for+ # the whole change and the block distributes its rows.+ impact = await cross_repo_tests(alias, sorted(changed))+ cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)if cross_repo is not None:payload["cross_repo"] = cross_repoexcept BaseException:@@ -472,7 +481,12 @@ def _has_contract_data() -> bool:return bool(enricher is not None and getattr(enricher, "has_contract_data", False))-def _cross_repo_block(alias: str, changed_files: list[str]) -> dict[str, Any] | None:+def _cross_repo_block(+ alias: str,+ changed_files: list[str],+ impact: Any = None,+ collector: OmissionCollector | None = None,+) -> dict[str, Any] | None:"""What this commit does to consumers in other repos, or ``None``.A commit that changes a published signature is the same class of fact as@@ -575,8 +589,41 @@ def _cross_repo_block(alias: str, changed_files: list[str]) -> dict[str, Any] |summary += "; the last workspace update found no break in them."else:summary += "; no breaking-change report has been built for them."+ shown = consumers[:_CROSS_REPO_CONSUMER_LIMIT]+ if impact is not None:+ for i, row in enumerate(shown):+ row["tests"] = tests_block_for(+ impact,+ row.get("repo") or "",+ row.get("file") or "",+ row.get("contract_id") or "",+ collector,+ f"cross_repo.consumers[{i}].tests.tests_to_run",+ )+ # Counted over the rows this payload actually carries, so the+ # sentence never promises tests for a consumer the cap dropped.+ keys = {+ (+ row.get("repo") or "",+ _norm(row.get("file") or ""),+ row.get("contract_id") or "",+ )+ for row in shown+ }+ test_files = {+ rec.test_file+ for rec in impact.recommendations+ for path in rec.consumer_files+ for cid in rec.contract_ids+ if (rec.consumer_repo, path, cid) in keys+ }+ undetermined = sum(1 for row in shown if row["tests"]["state"] == "unresolved")+ summary += (+ f" {len(test_files)} consumer test file(s) to run, "+ f"{undetermined} link(s) could not be determined."+ )return {- "consumers": consumers[:_CROSS_REPO_CONSUMER_LIMIT],+ "consumers": shown,"consumers_truncated": max(0, len(consumers) - _CROSS_REPO_CONSUMER_LIMIT),"consumer_repos": repos,"breaking_changes": breaking,diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex edc6b445c..28203fc9b 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -41,6 +41,7 @@ from repowise.server.schemas import (WorkspaceResponse,WorkspaceSyncResponse,WorkspaceSystemGraphResponse,+ WorkspaceTestImpactResponse,)from repowise.server.services.module_health import read_repo_health_score@@ -686,6 +687,50 @@ async def get_blast_radius(return WorkspaceBlastRadiusResponse(**result.to_dict())+# ---------------------------------------------------------------------------+# GET /api/workspace/test-impact+# ---------------------------------------------------------------------------++[email protected]("/test-impact", response_model=WorkspaceTestImpactResponse)+async def get_test_impact(+ ws_config=Depends(get_workspace_config),+ enricher=Depends(get_cross_repo_enricher),+ repo: str = Query(..., description="Provider repo alias the changed files belong to."),+ file: list[str] = Query(+ ..., description="Changed file path, relative to that repo's root. Repeatable."+ ),+):+ """Which tests in the consumer repos guard a change to these provider files.++ Rows carry the basis they came from: ``measured`` when a coverage map+ recorded the test against the consumer call site, ``inferred`` when the+ consumer's call or import graph reaches it. A link the join could not+ follow is reported in ``unresolved`` with its reason, never dropped, so an+ empty answer always names the state that produced it.++ Shares :func:`cross_repo_tests` with the MCP tools, so the REST answer and+ the agent answer cannot drift apart.+ """+ _require_workspace(ws_config)++ if enricher is None:+ return WorkspaceTestImpactResponse(summary={"reason": "no_contract_data"})++ # Imported here, not at module scope: the helper pulls in the cross-repo+ # join and holds consumer indexes open, and a single-repo server never+ # reaches this route.+ from repowise.server.mcp_server._test_impact import cross_repo_tests++ result = await cross_repo_tests(repo, list(file))+ if result is None:+ return WorkspaceTestImpactResponse(summary={"reason": "no_contract_data"})++ from repowise.core.workspace.test_impact import workspace_test_impact_to_dict++ return WorkspaceTestImpactResponse(**workspace_test_impact_to_dict(result))++# ---------------------------------------------------------------------------# GET /api/workspace/breaking-changes# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex d7033786a..c00b313a5 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -270,7 +270,11 @@ from .workspace import (WorkspaceSystemEdge,WorkspaceSystemGraphResponse,WorkspaceSystemNode,+ WorkspaceTestImpactFile,+ WorkspaceTestImpactResponse,+ WorkspaceTestRecommendation,WorkspaceUnmatchedConsumer,+ WorkspaceUnresolvedLink,)from .zoom import (ZoomMapResponse,@@ -497,7 +501,11 @@ __all__ = ["WorkspaceSystemEdge","WorkspaceSystemGraphResponse","WorkspaceSystemNode",+ "WorkspaceTestImpactFile",+ "WorkspaceTestImpactResponse",+ "WorkspaceTestRecommendation","WorkspaceUnmatchedConsumer",+ "WorkspaceUnresolvedLink","ZoomMapResponse","ZoomMetricsResponse","ZoomNodeResponse",diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 68cd3eee4..1303668c0 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -2,7 +2,7 @@from __future__ import annotations-from pydantic import BaseModel+from pydantic import BaseModel, Fieldclass WorkspaceRepoEntry(BaseModel):@@ -423,3 +423,80 @@ class WorkspaceArchitectureResponse(BaseModel):role_breakdown: dict[str, int] = {}roles: list[WorkspaceNodeArchitectureRole] = []generated_at: str = ""+++# ---------------------------------------------------------------------------+# Cross-repo test impact: which consumer tests guard a provider change.+# Mirrors repowise.core.workspace.test_impact.workspace_test_impact_to_dict.+# ---------------------------------------------------------------------------+++class WorkspaceTestRecommendation(BaseModel):+ """A test in a consumer repo that guards a changed provider file."""++ test_id: str = ""+ test_file: str = ""+ consumer_repo: str = ""+ #: Every consumer file that reached this test. One test can guard several+ #: call sites, and merging rows on the test would otherwise drop all but+ #: one of the files that led to it.+ consumer_files: list[str] = []+ #: The symbols the contracts bound to in the consumer. Carried through the+ #: boundary so a caller can look the call sites up instead of guessing them+ #: from the files.+ consumer_symbol_ids: list[str] = []+ provider_repo: str = ""+ contract_ids: list[str] = []+ contract_types: list[str] = []+ basis: str = "inferred" # measured | inferred+ via: str = "" # coverage-map | call-graph | import-graph+ confidence: float = 0.0+ source_files: list[str] = []+ evidence: list[dict] = []+++class WorkspaceUnresolvedLink(BaseModel):+ """A contract link the join could not follow, and why."""++ consumer_repo: str = ""+ consumer_file: str = ""+ consumer_symbol_id: str | None = None+ provider_repo: str = ""+ provider_file: str = ""+ contract_id: str = ""+ contract_type: str = ""+ reason: str = "" # no_index | unbound | symbol_missing | lookup_failed+ detail: str | None = None+++class WorkspaceTestImpactFile(BaseModel):+ """One consumer file the join looked at, and the state it ended in."""++ consumer_repo: str = ""+ consumer_file: str = ""+ state: str = "none" # measured | inferred | none | unresolved+ measured_tests_count: int = 0+ inferred_tests_count: int = 0+ via: str | None = None+ provider_repos: list[str] = []+ contract_ids: list[str] = []+ consumer_symbol_ids: list[str] = []+++class WorkspaceTestImpactResponse(BaseModel):+ """``GET /api/workspace/test-impact``: consumer tests for a provider change."""++ workspace: bool = True+ recommendations: list[WorkspaceTestRecommendation] = []+ recommendations_total: int = 0+ recommendations_emitted: int = 0+ recommendations_truncated: bool = False+ recommendations_omitted: int = 0+ recommendations_by_basis: dict[str, int] = {}+ recommendations_by_repo: dict[str, int] = {}+ recommendations_by_consumer_repo: dict[str, int] = {}+ unresolved: list[WorkspaceUnresolvedLink] = []+ files_analyzed: list[WorkspaceTestImpactFile] = []+ #: Free-form counters and the state that produced an empty answer, so an+ #: empty response always names its reason.+ summary: dict = Field(default_factory=dict)diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 541a40dd8..a75ed634e 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2974,6 +2974,52 @@ export interface WorkspaceSystemNode {is_isolated?: boolean;}+/** One consumer file the join looked at, and the state it ended in. */+export interface WorkspaceTestImpactFile {+ consumer_repo?: string;+ consumer_file?: string;+ state?: string;+ measured_tests_count?: number;+ inferred_tests_count?: number;+ via?: string | null;+ provider_repos?: string[];+ contract_ids?: string[];+ consumer_symbol_ids?: string[];+}++/** ``GET /api/workspace/test-impact``: consumer tests for a provider change. */+export interface WorkspaceTestImpactResponse {+ workspace?: boolean;+ recommendations?: WorkspaceTestRecommendation[];+ recommendations_total?: number;+ recommendations_emitted?: number;+ recommendations_truncated?: boolean;+ recommendations_omitted?: number;+ recommendations_by_basis?: Record<string, number>;+ recommendations_by_repo?: Record<string, number>;+ recommendations_by_consumer_repo?: Record<string, number>;+ unresolved?: WorkspaceUnresolvedLink[];+ files_analyzed?: WorkspaceTestImpactFile[];+ summary?: Record<string, unknown>;+}++/** A test in a consumer repo that guards a changed provider file. */+export interface WorkspaceTestRecommendation {+ test_id?: string;+ test_file?: string;+ consumer_repo?: string;+ consumer_files?: string[];+ consumer_symbol_ids?: string[];+ provider_repo?: string;+ contract_ids?: string[];+ contract_types?: string[];+ basis?: string;+ via?: string;+ confidence?: number;+ source_files?: string[];+ evidence?: Record<string, unknown>[];+}+export interface WorkspaceUnmatchedConsumer {repo: string;file_path: string;@@ -2982,6 +3028,19 @@ export interface WorkspaceUnmatchedConsumer {reason: string;}+/** A contract link the join could not follow, and why. */+export interface WorkspaceUnresolvedLink {+ consumer_repo?: string;+ consumer_file?: string;+ consumer_symbol_id?: string | null;+ provider_repo?: string;+ provider_file?: string;+ contract_id?: string;+ contract_type?: string;+ reason?: string;+ detail?: string | null;+}+export interface ZoomMapResponse {root_id: string;project_name: string;diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex 2dae11469..bd286a7da 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -487,3 +487,93 @@ export interface ArchitectureMetrics {roles: NodeArchitectureRole[];generated_at: string;}++// ---------------------------------------------------------------------------+// Cross-repo test impact: which consumer tests guard a provider change.+// Mirror of `core/workspace/test_impact.py` and+// `server/schemas/workspace.py::WorkspaceTestImpactResponse`.+// ---------------------------------------------------------------------------++/** How a recommendation was arrived at. */+export type TestImpactBasis = "measured" | "inferred";++/** The state one consumer file ended the join in. */+export type TestImpactState = "measured" | "inferred" | "none" | "unresolved";++/** Why a contract link could not be followed into the consumer's tests. */+export type TestImpactUnresolvedReason =+ | "no_index"+ | "unbound"+ | "symbol_missing"+ | "lookup_failed";++/** A test in a consumer repo that guards a changed provider file. */+export interface WorkspaceTestRecommendation {+ test_id: string;+ test_file: string;+ consumer_repo: string;+ /** Every consumer file that reached this test, sorted. */+ consumer_files: string[];+ /** The symbols the contracts bound to in the consumer, sorted. */+ consumer_symbol_ids: string[];+ provider_repo: string;+ contract_ids: string[];+ contract_types: string[];+ basis: TestImpactBasis;+ /** "coverage-map" | "call-graph" | "import-graph". */+ via: string;+ /** The link's confidence as a plain number, not a percentage. */+ confidence: number;+ /** Provider files this test guards. */+ source_files: string[];+ evidence: Record<string, unknown>[];+}++/** A contract link the join could not follow, and why. */+export interface WorkspaceUnresolvedLink {+ consumer_repo: string;+ consumer_file: string;+ consumer_symbol_id: string | null;+ provider_repo: string;+ provider_file: string;+ contract_id: string;+ contract_type: string;+ reason: TestImpactUnresolvedReason | string;+ detail: string | null;+}++/** One consumer file the join looked at, and the state it ended in. */+export interface WorkspaceTestImpactFile {+ consumer_repo: string;+ consumer_file: string;+ state: TestImpactState;+ measured_tests_count: number;+ inferred_tests_count: number;+ /** The tier that answered, or null when nothing did. */+ via: string | null;+ provider_repos: string[];+ contract_ids: string[];+ consumer_symbol_ids: string[];+}++/** `GET /api/workspace/test-impact`: consumer tests for a provider change. */+export interface WorkspaceTestImpactResponse {+ workspace: boolean;+ recommendations: WorkspaceTestRecommendation[];+ recommendations_total: number;+ recommendations_emitted: number;+ recommendations_truncated: boolean;+ recommendations_omitted: number;+ recommendations_by_basis: Record<string, number>;+ recommendations_by_repo: Record<string, number>;+ recommendations_by_consumer_repo: Record<string, number>;+ unresolved: WorkspaceUnresolvedLink[];+ files_analyzed: WorkspaceTestImpactFile[];+ /**+ * Counters plus, when the answer is empty, the `reason` that produced it+ * ("no_contract_data" | "no_changed_files" | "no_matching_links" |+ * "no_contract_store" | "lookup_failed"), and for "lookup_failed" a+ * `detail` naming what failed.+ */+ summary: Record<string, unknown>;+}diff --git a/packages/ui/__tests__/workspace/contract-tests-section.test.tsx b/packages/ui/__tests__/workspace/contract-tests-section.test.tsxnew file mode 100644index 000000000..826392584--- /dev/null+++ b/packages/ui/__tests__/workspace/contract-tests-section.test.tsx@@ -0,0 +1,177 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import type {+ WorkspaceTestImpactResponse,+ WorkspaceTestRecommendation,+ WorkspaceUnresolvedLink,+} from "@repowise-dev/types/workspace";+import { ContractTestsSection } from "../../src/workspace/contract-tests-section.js";++const CONTRACT = "http::GET::/users";++function rec(over: Partial<WorkspaceTestRecommendation> = {}): WorkspaceTestRecommendation {+ return {+ test_id: "web::tests/users.test.ts::loads",+ test_file: "tests/users.test.ts",+ consumer_repo: "web",+ consumer_files: ["src/client.ts"],+ consumer_symbol_ids: ["src/client.ts::fetchUsers"],+ provider_repo: "api",+ contract_ids: [CONTRACT],+ contract_types: ["http"],+ basis: "measured",+ via: "coverage-map",+ confidence: 0.9,+ source_files: ["src/client.ts"],+ evidence: [],+ ...over,+ };+}++function unresolved(over: Partial<WorkspaceUnresolvedLink> = {}): WorkspaceUnresolvedLink {+ return {+ consumer_repo: "web",+ consumer_file: "src/client.ts",+ consumer_symbol_id: null,+ provider_repo: "api",+ provider_file: "app/routers/users.py",+ contract_id: CONTRACT,+ contract_type: "http",+ reason: "unbound",+ detail: null,+ ...over,+ };+}++function response(over: Partial<WorkspaceTestImpactResponse> = {}): WorkspaceTestImpactResponse {+ return {+ workspace: true,+ recommendations: [],+ recommendations_total: 0,+ recommendations_emitted: 0,+ recommendations_truncated: false,+ recommendations_omitted: 0,+ recommendations_by_basis: {},+ recommendations_by_repo: {},+ recommendations_by_consumer_repo: {},+ unresolved: [],+ files_analyzed: [],+ summary: {},+ ...over,+ };+}++describe("ContractTestsSection", () => {+ it("renders nothing for a null result", () => {+ const { container } = render(<ContractTestsSection result={null} contractId={CONTRACT} />);+ expect(container).toBeEmptyDOMElement();+ });++ it("lists a measured row under its consumer repo", () => {+ render(+ <ContractTestsSection+ result={response({ recommendations: [rec()] })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.getByRole("heading", { name: "Tests to run" })).toBeTruthy();+ expect(screen.getByText("web")).toBeTruthy();+ expect(screen.getByText("tests/users.test.ts")).toBeTruthy();+ expect(screen.getByText("measured")).toBeTruthy();+ expect(screen.getByText("via the coverage map")).toBeTruthy();+ });++ it("writes an inferred row without a percentage anywhere", () => {+ const { container } = render(+ <ContractTestsSection+ result={response({+ recommendations: [rec({ basis: "inferred", via: "call-graph", confidence: 0.6 })],+ })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.getByText("inferred")).toBeTruthy();+ expect(screen.getByText("via the call graph")).toBeTruthy();+ expect(container.textContent).not.toContain("%");+ });++ it("names the consumer file and the reason for a link it could not follow", () => {+ render(+ <ContractTestsSection+ result={response({ unresolved: [unresolved()] })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.getByRole("heading", { name: "Could not determine" })).toBeTruthy();+ expect(screen.getByText("web / src/client.ts")).toBeTruthy();+ expect(screen.getByText("contract never bound to a symbol")).toBeTruthy();+ });++ it("says the consumers were analyzed when nothing reaches the contract", () => {+ render(<ContractTestsSection result={response()} contractId={CONTRACT} />);+ expect(screen.getByText(/nothing reaches the call sites/)).toBeTruthy();+ });++ it("names each summary reason in words", () => {+ const cases: [string, RegExp][] = [+ ["no_contract_store", /no extracted contracts/],+ ["no_matching_links", /No contract link joins this file/],+ ["no_changed_files", /No provider file was submitted/],+ ["no_contract_data", /carries no contract data/],+ ["lookup_failed", /lookup failed before it could answer/],+ ];+ for (const [reason, words] of cases) {+ const { unmount } = render(+ <ContractTestsSection result={response({ summary: { reason } })} contractId={CONTRACT} />,+ );+ expect(screen.getByText(words)).toBeTruthy();+ unmount();+ }+ });++ it("appends the detail a failed lookup carries", () => {+ render(+ <ContractTestsSection+ result={response({ summary: { reason: "lookup_failed", detail: "TimeoutError" } })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.getByText(/\(TimeoutError\)/)).toBeTruthy();+ });++ it("keys two rows sharing a test id across provider repos apart", () => {+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ render(+ <ContractTestsSection+ result={response({+ recommendations: [+ rec({ source_files: ["app/routers/users.py"] }),+ rec({ provider_repo: "billing", source_files: ["app/routers/plans.py"] }),+ ],+ })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.getAllByText("tests/users.test.ts")).toHaveLength(2);+ expect(errors.mock.calls.flat().join(" ")).not.toContain("same key");+ errors.mockRestore();+ });++ it("drops rows belonging to another contract", () => {+ render(+ <ContractTestsSection+ result={response({ recommendations: [rec({ contract_ids: ["http::GET::/orders"] })] })}+ contractId={CONTRACT}+ />,+ );+ expect(screen.queryByText("tests/users.test.ts")).toBeNull();+ expect(screen.getByText(/nothing reaches the call sites/)).toBeTruthy();+ });++ it("renders the host's error wording", () => {+ render(+ <ContractTestsSection result={null} contractId={CONTRACT} error="Test impact is unavailable." />,+ );+ expect(screen.getByText("Test impact is unavailable.")).toBeTruthy();+ });+});diff --git a/packages/ui/src/workspace/contract-tests-section.tsx b/packages/ui/src/workspace/contract-tests-section.tsxnew file mode 100644index 000000000..dd2479cb5--- /dev/null+++ b/packages/ui/src/workspace/contract-tests-section.tsx@@ -0,0 +1,204 @@+/**+ * The tests in other repositories that guard one provider contract.+ *+ * The join starts from the contract links, so the rows here are already scoped+ * to the consumers that call this contract; the only narrowing left is to this+ * contract in particular, which is why `contractId` is a prop and not the+ * caller filtering before it hands the result over.+ *+ * Two rules run through the whole section. Every empty block names the state+ * that produced it, because "no tests" between "nothing guards this" and "we+ * could not look" is the one ambiguity this view exists to remove. And the+ * evidence is written in words: a measured row is a coverage map saying the+ * test ran the code, an inferred row is a graph walk saying it could, and a+ * bar or a percentage would put those two on one scale they do not share.+ */++import type { ReactNode } from "react";+import type {+ WorkspaceTestImpactResponse,+ WorkspaceTestRecommendation,+ WorkspaceUnresolvedLink,+} from "@repowise-dev/types/workspace";+import { Badge } from "../ui/badge";++export interface ContractTestsSectionProps {+ /** The test-impact answer for this contract's provider file, or null. */+ result: WorkspaceTestImpactResponse | null;+ /** Only rows naming this contract belong on this page. */+ contractId: string;+ /** A failed lookup, worded by the host. */+ error?: string | null;+}++const VIA_WORDS: Record<string, string> = {+ "coverage-map": "coverage map",+ "call-graph": "call graph",+ "import-graph": "import graph",+};++const REASON_WORDS: Record<string, string> = {+ unbound: "contract never bound to a symbol",+ no_index: "consumer has no index",+ symbol_missing: "bound symbol is not in the index",+ lookup_failed: "lookup failed",+};++const SUMMARY_REASON_WORDS: Record<string, string> = {+ // Only the CLI reports this one: it reads the contract store from disk and+ // finds none. The route answers from an enricher that is already loaded, so+ // it cannot produce it. Worded here anyway so a CLI-shaped payload rendered+ // in the UI still reads.+ no_contract_store:+ "This workspace has no extracted contracts to join tests to. Run a workspace update to build the contract store.",+ no_contract_data:+ "This workspace carries no contract data, so there is no link from this file to a consumer to follow.",+ no_matching_links:+ "No contract link joins this file to a consumer repository, so no test in another repository can be traced back to it.",+ no_changed_files:+ "No provider file was submitted for analysis, so nothing was traced.",+ lookup_failed:+ "The lookup failed before it could answer, so treat these consumers as unknown.",+};++const NONE_WORDS =+ "The consumer repositories were analyzed and nothing reaches the call sites for this contract. That is an answer, not a failure: no test in another repository guards it.";++export function ContractTestsSection({ result, contractId, error }: ContractTestsSectionProps) {+ // Null is "the host did not ask", which is a different fact from "the answer+ // was empty" and gets no section at all.+ if (!result && !error) return null;++ return (+ <section className="mt-10 flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-6 sm:mt-12 sm:pt-8">+ <h2 className="text-xl font-semibold tracking-tight text-[var(--color-text-primary)]">+ Tests to run+ </h2>+ <Body result={result} contractId={contractId} error={error ?? null} />+ </section>+ );+}++function Body({+ result,+ contractId,+ error,+}: {+ result: WorkspaceTestImpactResponse | null;+ contractId: string;+ error: string | null;+}) {+ if (error) return <Prose>{error}</Prose>;+ if (!result) return null;++ const rows = result.recommendations.filter((r) => r.contract_ids.includes(contractId));+ const unresolved = result.unresolved.filter((u) => u.contract_id === contractId);++ if (rows.length === 0 && unresolved.length === 0) {+ const reason = summaryReason(result);+ // An empty-string reason is still a miss, so index with "" and let the+ // lookup fall through to the analyzed-and-found-nothing wording.+ const words = SUMMARY_REASON_WORDS[reason ?? ""] ?? NONE_WORDS;+ const detail = reason === "lookup_failed" ? summaryDetail(result) : null;+ return <Prose>{detail ? `${words} (${detail})` : words}</Prose>;+ }++ return (+ <>+ <Prose>+ Tests in the repositories that call this contract, found by walking each consumer's+ own index from the call site. A measured row is a coverage map recording that the test ran+ the code; an inferred row is a graph reaching it.+ </Prose>+ {groupByRepo(rows).map(([repo, repoRows]) => (+ <div key={repo} className="flex flex-col gap-2">+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {repo}+ </h3>+ <ul className="m-0 flex list-none flex-col gap-2 p-0">+ {repoRows.map((row) => (+ // One test id can appear once per provider repo it guards, so+ // the provider files are part of what makes the row unique.+ <li+ key={`${row.consumer_repo}|${row.test_id}|${row.source_files.join(",")}`}+ className="flex flex-col gap-1"+ >+ <span className="font-mono text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {row.test_file}+ </span>+ <span className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-text-tertiary)]">+ <Badge variant={row.basis === "measured" ? "accent" : "outline"}>+ {row.basis}+ </Badge>+ <span>via the {VIA_WORDS[row.via] ?? row.via}</span>+ {/* A plain number: confidence here is a rank among rows, and+ a percentage would read as a chance the test catches it. */}+ <span className="tabular-nums">confidence {row.confidence.toFixed(2)}</span>+ </span>+ </li>+ ))}+ </ul>+ </div>+ ))}+ {unresolved.length > 0 && <UnresolvedList rows={unresolved} />}+ </>+ );+}++function UnresolvedList({ rows }: { rows: WorkspaceUnresolvedLink[] }) {+ return (+ <div className="flex flex-col gap-2">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Could not determine+ </h3>+ <Prose>+ These call sites were not answered either way, so treat them as unknown and not as+ untested.+ </Prose>+ <ul className="m-0 flex list-none flex-col gap-2 p-0">+ {rows.map((row, index) => (+ <li+ key={`${row.consumer_repo}|${row.consumer_file}|${row.contract_id}|${+ row.consumer_symbol_id ?? index+ }`}+ >+ <span className="font-mono text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {row.consumer_repo} / {row.consumer_file}+ </span>+ <span className="ml-2 text-xs text-[var(--color-text-tertiary)]">+ {REASON_WORDS[row.reason] ?? row.reason}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}++function Prose({ children }: { children: ReactNode }) {+ return (+ <p className="max-w-[68ch] text-base leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {children}+ </p>+ );+}++function summaryReason(result: WorkspaceTestImpactResponse): string | null {+ const reason = result.summary?.reason;+ return typeof reason === "string" ? reason : null;+}++function summaryDetail(result: WorkspaceTestImpactResponse): string | null {+ const detail = result.summary?.detail;+ return typeof detail === "string" && detail ? detail : null;+}++function groupByRepo(rows: WorkspaceTestRecommendation[]): [string, WorkspaceTestRecommendation[]][] {+ const byRepo = new Map<string, WorkspaceTestRecommendation[]>();+ for (const row of rows) {+ const bucket = byRepo.get(row.consumer_repo);+ if (bucket) bucket.push(row);+ else byRepo.set(row.consumer_repo, [row]);+ }+ return [...byRepo.entries()].sort(([a], [b]) => a.localeCompare(b));+}diff --git a/packages/ui/src/workspace/index.ts b/packages/ui/src/workspace/index.tsindex e246b93f2..d4992b291 100644--- a/packages/ui/src/workspace/index.ts+++ b/packages/ui/src/workspace/index.ts@@ -4,6 +4,7 @@ export * from "./co-change-table";export * from "./contract-drawer";export * from "./contract-facts";export * from "./contract-links-table";+export * from "./contract-tests-section";export * from "./contract-type-badge";export * from "./cross-repo-summary";export * from "./package-deps-table";diff --git a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx b/packages/web/src/app/workspace/contracts/detail/contract-body.tsxindex 3eeb1358e..343ff52db 100644--- a/packages/web/src/app/workspace/contracts/detail/contract-body.tsx+++ b/packages/web/src/app/workspace/contracts/detail/contract-body.tsx@@ -5,8 +5,13 @@ import type {WorkspaceContractEntry,WorkspaceContractLinkEntry,} from "@/lib/api/types";-import type { ContractSchema, SchemaField } from "@repowise-dev/types/workspace";+import type {+ ContractSchema,+ SchemaField,+ WorkspaceTestImpactResponse,+} from "@repowise-dev/types/workspace";import { contractTypeLabel } from "@repowise-dev/ui/workspace/contract-type-label";+import { ContractTestsSection } from "@repowise-dev/ui/workspace/contract-tests-section";import {asContractSchema,contractHeading,@@ -36,9 +41,12 @@ interface Props {detail: WorkspaceContractDetail;/** Repo alias to indexed repo id. A never-indexed repo has no entry. */repoIds: Record<string, string>;+ /** Consumer tests guarding this contract. Providers only; null otherwise. */+ testImpact?: WorkspaceTestImpactResponse | null;+ testImpactError?: string | null;}-export function ContractBody({ detail, repoIds }: Props) {+export function ContractBody({ detail, repoIds, testImpact, testImpactError }: Props) {const { contract, links, unmatched_reason: unmatchedReason } = detail;const isProvider = contract.role === "provider";const schema = asContractSchema(detail.contract_schema);@@ -111,6 +119,12 @@ export function ContractBody({ detail, repoIds }: Props) {repoIds={repoIds}/>+ <ContractTestsSection+ result={testImpact ?? null}+ contractId={contract.contract_id}+ error={testImpactError ?? null}+ />+<SchemaSection contract={contract} schema={schema} /><Sectiondiff --git a/packages/web/src/app/workspace/contracts/detail/page.tsx b/packages/web/src/app/workspace/contracts/detail/page.tsxindex 5eb5b7993..155feafd0 100644--- a/packages/web/src/app/workspace/contracts/detail/page.tsx+++ b/packages/web/src/app/workspace/contracts/detail/page.tsx@@ -1,7 +1,12 @@import type { Metadata } from "next";import { notFound } from "next/navigation";import { ApiClientError } from "@/lib/api/client";-import { getWorkspace, getWorkspaceContractDetail } from "@/lib/api/workspace";+import {+ getWorkspace,+ getWorkspaceContractDetail,+ getWorkspaceTestImpact,+} from "@/lib/api/workspace";+import type { WorkspaceTestImpactResponse } from "@repowise-dev/types/workspace";import { contractHeading } from "@repowise-dev/ui/workspace/contract-facts";import { ContractBody } from "./contract-body";@@ -59,5 +64,27 @@ export default async function ContractDetailPage({ searchParams }: Props) {}}- return <ContractBody detail={detailResult.value} repoIds={repoIds} />;+ const { contract } = detailResult.value;+ let testImpact: WorkspaceTestImpactResponse | null = null;+ let testImpactError: string | null = null;+ // Only a provider has consumers to find tests in, and the lookup opens the+ // consumer indexes, so a consumer contract never pays for it. It runs after+ // the detail because the role and the file path are what it takes.+ if (contract.role === "provider") {+ try {+ testImpact = await getWorkspaceTestImpact(contract.repo, [contract.file_path]);+ } catch {+ testImpactError =+ "Test impact could not be read. It is answered from the consumer repositories' own indexes, and that lookup failed.";+ }+ }++ return (+ <ContractBody+ detail={detailResult.value}+ repoIds={repoIds}+ testImpact={testImpact}+ testImpactError={testImpactError}+ />+ );}diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.pyindex 1b0d76bd5..8f455d784 100644--- a/tests/unit/cli/test_workspace_cmd.py+++ b/tests/unit/cli/test_workspace_cmd.py@@ -874,8 +874,8 @@ class TestWorkspaceImpactedTests:test_id="tests/api.test.ts::it_getUser",test_file="tests/api.test.ts",consumer_repo="frontend",- consumer_file="src/api.ts",- consumer_symbol_id="src/api.ts::getUser",+ consumer_files=["src/api.ts"],+ consumer_symbol_ids=["src/api.ts::getUser"],provider_repo="backend",contract_ids=["http::GET::/users"],contract_types=["http"],diff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pyindex 729e82e45..e928dd9f4 100644--- a/tests/unit/server/test_mcp_blast_radius.py+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -310,6 +310,15 @@ async def test_symbol_target_names_the_consuming_symbol(workspace_state):"match_type": "exact","confidence": 0.8,"symbol_id": "client.ts::fetchUsers",+ # No consumer index is open here, so the link is reported unfollowed.+ "tests": {+ "state": "unresolved",+ "tests_to_run": [],+ "total": 0,+ "truncated": False,+ "unresolved_reason": "no_index",+ "unresolved_detail": None,+ },}]assert blocks[0]["consumers_truncated"] == 0diff --git a/tests/unit/server/test_mcp_blast_radius_symbols.py b/tests/unit/server/test_mcp_blast_radius_symbols.pyindex e2297a7a8..09d63499b 100644--- a/tests/unit/server/test_mcp_blast_radius_symbols.py+++ b/tests/unit/server/test_mcp_blast_radius_symbols.py@@ -235,3 +235,29 @@ def test_enricher_symbol_indexes_survive_a_reload(tmp_path: Path):assert len(enricher.get_contracts_for_symbol("src/types.ts::Order")) == 1assert len(enricher.get_contract_links_by_provider_symbol("src/types.ts::Order")) == 1assert enricher.get_contracts_for_symbol("nope.ts::Nope") == []+++async def test_a_consumer_row_names_the_tests_that_guard_it(tmp_path: Path):+ """Without an open consumer index the link is reported, never dropped."""+ provider = _provider()+ consumer = _consumer()+ with _in_workspace(_enricher(tmp_path, [provider, consumer], [_link(provider, consumer)])):+ result = await get_blast_radius(["src/types.ts::Order"])+ block = result["symbol_targets"][0]+ tests = block["consumers"][0]["tests"]+ assert tests["state"] == "unresolved"+ assert tests["unresolved_reason"] == "no_index"+ assert tests["tests_to_run"] == []+ assert block["tests_summary"] == "tests to run: 0 across 1 consumer(s), 1 unresolved"+++async def test_no_tests_block_when_the_symbol_has_no_consumers(tmp_path: Path):+ """No link means no join to run, so the row carries no empty promise."""+ provider = _provider(file_path="src/types.ts", service="packages/gone")+ with _in_workspace(_enricher(tmp_path, [provider], [])):+ result = await get_blast_radius(["src/types.ts::Order"])+ block = result["symbol_targets"][0]+ assert block["consumers"] == []+ assert "tests_summary" not in blockdiff --git a/tests/unit/server/test_mcp_change_risk_cross_repo.py b/tests/unit/server/test_mcp_change_risk_cross_repo.pyindex 81ebd4bf5..ce04fee75 100644--- a/tests/unit/server/test_mcp_change_risk_cross_repo.py+++ b/tests/unit/server/test_mcp_change_risk_cross_repo.py@@ -321,3 +321,69 @@ def test_cross_repo_participates_in_the_response_ceiling(tmp_path: Path):# The tests to run outlive both the consumer list and the fix record.assert payload["impacted_tests"]["tests_to_run"] == ["t.py"]assert "fix_history" not in payload+++def test_no_tests_block_without_a_test_impact_result(tmp_path: Path):+ """The helper declining is the block being absent, not an empty list."""+ block = _block(_enricher(tmp_path, [_link()]), [PROVIDER_FILE])+ assert "tests" not in block["consumers"][0]+ assert "consumer test file(s) to run" not in block["summary"]+++def test_each_consumer_row_carries_the_tests_that_guard_it(tmp_path: Path):+ from repowise.core.workspace.test_impact import (+ UnresolvedLink,+ WorkspaceTestImpactResult,+ WorkspaceTestRecommendation,+ )+ from repowise.server.mcp_server.tool_change_risk import _cross_repo_block++ impact = WorkspaceTestImpactResult(+ recommendations=[+ WorkspaceTestRecommendation(+ test_id="tests/api.test.ts::it",+ test_file="tests/api.test.ts",+ consumer_repo="frontend",+ consumer_files=["src/api.ts"],+ consumer_symbol_ids=["src/api.ts::getOrder"],+ provider_repo="api",+ contract_ids=["code::@acme/types::Order"],+ contract_types=["code"],+ basis="inferred",+ via="call-graph",+ confidence=0.9,+ source_files=[PROVIDER_FILE],+ evidence=[],+ )+ ],+ unresolved=[+ UnresolvedLink(+ consumer_repo="frontend",+ consumer_file="src/other.ts",+ consumer_symbol_id=None,+ provider_repo="api",+ provider_file=PROVIDER_FILE,+ contract_id="code::@acme/types::Order",+ contract_type="code",+ reason="unbound",+ )+ ],+ )+ enricher = _enricher(tmp_path, [_link(), _link(consumer_file="src/other.ts")])+ prev_registry = _state._registry+ prev_enricher = _state._cross_repo_enricher+ _state._registry = object()+ _state._cross_repo_enricher = enricher+ try:+ block = _cross_repo_block("api", [PROVIDER_FILE], impact, None)+ finally:+ _state._registry = prev_registry+ _state._cross_repo_enricher = prev_enricher++ assert block["consumers"][0]["tests"]["state"] == "inferred"+ assert block["consumers"][0]["tests"]["tests_to_run"][0]["via"] == "call-graph"+ assert block["consumers"][1]["tests"]["state"] == "unresolved"+ assert block["consumers"][1]["tests"]["unresolved_reason"] == "unbound"+ assert block["summary"].endswith(+ " 1 consumer test file(s) to run, 1 link(s) could not be determined."+ )diff --git a/tests/unit/server/test_mcp_test_impact.py b/tests/unit/server/test_mcp_test_impact.pynew file mode 100644index 000000000..cfe897792--- /dev/null+++ b/tests/unit/server/test_mcp_test_impact.py@@ -0,0 +1,412 @@+"""The cross-repo ``tests`` block the MCP tools attach to a consumer row.++The helper is exercised against a real consumer index, because the two things+it has to get right are query-path facts: the repo is opened from the workspace+config by alias, and the block is keyed by the consumer file the link names.+The four states each have to reach the block intact, and a link the join could+not follow has to arrive as its reason, not as an empty list.+"""++from __future__ import annotations++import contextlib+from pathlib import Path+from typing import Any++import pytest++from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET+from repowise.core.ingestion.models import Symbol+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig+from repowise.core.workspace.contracts import ContractLink+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._test_impact import (+ _TESTS_PER_CONSUMER_LIMIT,+ close_test_impact_indexes,+ cross_repo_tests,+)+from repowise.server.mcp_server._test_impact import (+ tests_block_for as _tests_block_for,+)++from ...unit.workspace._repo_index import make_repo_index++PROVIDER_FILE = "app/routers/users.py"+CONTRACT_ID = "http::GET::/users/{param}"+++def _symbol(symbol_id: str) -> Symbol:+ name = symbol_id.split("::", 1)[1]+ return Symbol(+ id=symbol_id,+ name=name,+ qualified_name=name,+ kind="function",+ signature=f"function {name}()",+ start_line=1,+ end_line=5,+ docstring=None,+ visibility="public",+ )+++def _link(+ *,+ consumer_file: str,+ consumer_symbol_id: str | None,+ consumer_repo: str = "frontend",+ contract_id: str = CONTRACT_ID,+) -> ContractLink:+ return ContractLink(+ contract_id=contract_id,+ contract_type="http",+ match_type="exact",+ confidence=0.9,+ provider_repo="backend",+ provider_file=PROVIDER_FILE,+ provider_symbol="get_user",+ provider_service=None,+ consumer_repo=consumer_repo,+ consumer_file=consumer_file,+ consumer_symbol="getUser",+ consumer_service=None,+ consumer_symbol_id=consumer_symbol_id,+ )+++BOUND = _link(consumer_file="src/api.ts", consumer_symbol_id="src/api.ts::getUser")+UNBOUND = _link(consumer_file="src/legacy.ts", consumer_symbol_id=None)+NOTHING_REACHES = _link(+ consumer_file="src/other.ts", consumer_symbol_id="src/other.ts::helper"+)+ONLY_IMPORTED = _link(+ consumer_file="src/imported.ts", consumer_symbol_id="src/imported.ts::thing"+)+WIDE = _link(consumer_file="src/wide.ts", consumer_symbol_id="src/wide.ts::wide")+HUGE = _link(consumer_file="src/huge.ts", consumer_symbol_id="src/huge.ts::huge")++_WIDE_TESTS = _TESTS_PER_CONSUMER_LIMIT + 3++#: Above the per-pair cap the core join applies by default, so a total of+#: exactly this many proves the helper turned that cap off.+_HUGE_TESTS = MAX_TESTS_PER_TARGET + 10+++class _FakeEnricher:+ """Stands in for the loaded contract artifact, indexed the same way."""++ has_contract_data = True++ def __init__(self, links: list[ContractLink]) -> None:+ # One dict per link, built once: the helper deduplicates by identity.+ self._by_provider: dict[tuple[str, str], list[dict[str, Any]]] = {}+ for link in links:+ key = (link.provider_repo, link.provider_file)+ self._by_provider.setdefault(key, []).append(link.to_dict())++ def get_contract_links_as_provider(self, alias: str, path: str) -> list[dict[str, Any]]:+ return self._by_provider.get((alias, path), [])+++class _FakeCollector:+ """Records what would have gone to the omission store."""++ def __init__(self) -> None:+ self.chunks: list[tuple[str, Any]] = []++ def add(self, label: str, value: Any) -> None:+ self.chunks.append((label, value))+++async def _make_frontend(repo: Path) -> None:+ """A consumer repo with one file per state the block can report."""+ wide_tests = [f"tests/wide{i}.test.ts" for i in range(_WIDE_TESTS)]+ index = await make_repo_index(+ repo,+ {+ "src/api.ts": [_symbol("src/api.ts::getUser")],+ "src/other.ts": [_symbol("src/other.ts::helper")],+ "src/imported.ts": [_symbol("src/imported.ts::thing")],+ "src/wide.ts": [_symbol("src/wide.ts::wide")],+ },+ alias="frontend",+ graph_nodes=(+ ("src/api.ts", False),+ ("src/other.ts", False),+ ("src/imported.ts", False),+ ("src/wide.ts", False),+ ("tests/api.test.ts", True),+ ("tests/imports.test.ts", True),+ *((path, True) for path in wide_tests),+ ),+ graph_edges=(+ ("src/api.ts", "src/api.ts::getUser", "defines"),+ ("src/other.ts", "src/other.ts::helper", "defines"),+ ("src/imported.ts", "src/imported.ts::thing", "defines"),+ ("src/wide.ts", "src/wide.ts::wide", "defines"),+ ("tests/api.test.ts", "tests/api.test.ts::it_getUser", "defines"),+ ("tests/api.test.ts::it_getUser", "src/api.ts::getUser", "calls"),+ ("tests/imports.test.ts", "src/imported.ts", "imports"),+ *((path, f"{path}::it", "defines") for path in wide_tests),+ *((f"{path}::it", "src/wide.ts::wide", "calls") for path in wide_tests),+ ),+ coverage=(("tests/cov.test.ts::covers", "tests/cov.test.ts", "src/api.ts"),),+ )+ # The helper opens the repo itself; only the database on disk is wanted.+ await index.close()+++class _FakeRegistry:+ def __init__(self, root: Path) -> None:+ self.workspace_root = root+ self.ws_config = WorkspaceConfig(+ repos=[RepoEntry(path="frontend", alias="frontend")]+ )+++def _in_workspace(root: Path | None, enricher: Any):+ prev = (_state._registry, _state._cross_repo_enricher)+ _state._registry = _FakeRegistry(root) if root is not None else None+ _state._cross_repo_enricher = enricher+ try:+ yield+ finally:+ _state._registry, _state._cross_repo_enricher = prev+++async def _make_huge_frontend(repo: Path) -> None:+ """A consumer repo whose one call site is reached by more tests than the cap."""+ tests = [f"tests/huge{i}.test.ts" for i in range(_HUGE_TESTS)]+ index = await make_repo_index(+ repo,+ {"src/huge.ts": [_symbol("src/huge.ts::huge")]},+ alias="frontend",+ graph_nodes=(+ ("src/huge.ts", False),+ *((path, True) for path in tests),+ ),+ graph_edges=(+ ("src/huge.ts", "src/huge.ts::huge", "defines"),+ *((path, f"{path}::it", "defines") for path in tests),+ *((f"{path}::it", "src/huge.ts::huge", "calls") for path in tests),+ ),+ )+ await index.close()+++async def workspace(tmp_path: Path):+ """A workspace whose one consumer repo is indexed on disk."""+ await _make_frontend(tmp_path / "frontend")+ try:+ yield tmp_path+ finally:+ await close_test_impact_indexes()+++async def huge_workspace(tmp_path: Path):+ """The same workspace, with one call site far more tests reach."""+ await _make_huge_frontend(tmp_path / "frontend")+ try:+ yield tmp_path+ finally:+ await close_test_impact_indexes()+++def _block(result: Any, link: ContractLink, collector: Any = None) -> dict[str, Any]:+ return _tests_block_for(+ result,+ link.consumer_repo,+ link.consumer_file,+ link.contract_id,+ collector,+ "cross_repo.consumers[0].tests.tests_to_run",+ )+++# ---------------------------------------------------------------------------+# The four states+# ---------------------------------------------------------------------------+++async def test_a_covered_call_site_is_measured(workspace: Path) -> None:+ with _in_workspace(workspace, _FakeEnricher([BOUND])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, BOUND)+ assert block["state"] == "measured"+ assert block["tests_to_run"][0]["test_file"] == "tests/cov.test.ts"+ assert block["tests_to_run"][0]["via"] == "coverage-map"+ assert block["unresolved_reason"] is None+ # A plain number, never a percentage.+ assert block["tests_to_run"][0]["confidence"] == 0.9+++async def test_an_uncovered_call_site_falls_back_to_inferred(workspace: Path) -> None:+ with _in_workspace(workspace, _FakeEnricher([ONLY_IMPORTED])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, ONLY_IMPORTED)+ assert block["state"] == "inferred"+ assert [t["test_file"] for t in block["tests_to_run"]] == ["tests/imports.test.ts"]+ assert block["tests_to_run"][0]["via"] == "import-graph"+++async def test_a_call_site_nothing_reaches_says_none(workspace: Path) -> None:+ """The walk ran and came back empty; that is a state, not a silence."""+ with _in_workspace(workspace, _FakeEnricher([NOTHING_REACHES])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, NOTHING_REACHES)+ assert block["state"] == "none"+ assert block["tests_to_run"] == []+ assert block["total"] == 0+ assert block["unresolved_reason"] is None+++async def test_a_link_that_never_bound_carries_its_reason(workspace: Path) -> None:+ with _in_workspace(workspace, _FakeEnricher([UNBOUND])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, UNBOUND)+ assert block["state"] == "unresolved"+ assert block["unresolved_reason"] == "unbound"+ assert block["tests_to_run"] == []+++async def test_a_consumer_repo_without_an_index_says_so(workspace: Path) -> None:+ absent = _link(+ consumer_file="src/client.ts",+ consumer_symbol_id="src/client.ts::call",+ consumer_repo="mobile",+ )+ with _in_workspace(workspace, _FakeEnricher([absent])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, absent)+ assert block["state"] == "unresolved"+ assert block["unresolved_reason"] == "no_index"+++# ---------------------------------------------------------------------------+# The cap+# ---------------------------------------------------------------------------+++async def test_the_inline_list_is_capped_and_the_tail_is_recoverable(+ workspace: Path,+) -> None:+ collector = _FakeCollector()+ with _in_workspace(workspace, _FakeEnricher([WIDE])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, WIDE, collector)+ assert block["state"] == "inferred"+ assert len(block["tests_to_run"]) == _TESTS_PER_CONSUMER_LIMIT+ assert block["total"] == _WIDE_TESTS+ assert block["truncated"] is True+ label, tail = collector.chunks[0]+ assert label == (+ f"cross_repo.consumers[0].tests.tests_to_run beyond "+ f"cap={_TESTS_PER_CONSUMER_LIMIT} ({_WIDE_TESTS - _TESTS_PER_CONSUMER_LIMIT} dropped)"+ )+ assert len(tail) == _WIDE_TESTS - _TESTS_PER_CONSUMER_LIMIT+++async def test_the_total_counts_every_test_not_the_join_cap(+ huge_workspace: Path,+) -> None:+ """The helper caps its own inline list, so the join must not cap first."""+ collector = _FakeCollector()+ with _in_workspace(huge_workspace, _FakeEnricher([HUGE])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ block = _block(result, HUGE, collector)+ assert block["total"] == _HUGE_TESTS+ assert block["truncated"] is True+ assert len(block["tests_to_run"]) == _TESTS_PER_CONSUMER_LIMIT+ assert len(collector.chunks[0][1]) == _HUGE_TESTS - _TESTS_PER_CONSUMER_LIMIT+++# ---------------------------------------------------------------------------+# When the helper declines+# ---------------------------------------------------------------------------+++async def test_absent_outside_workspace_mode(workspace: Path) -> None:+ with _in_workspace(None, _FakeEnricher([BOUND])):+ assert await cross_repo_tests("backend", [PROVIDER_FILE]) is None+++async def test_absent_without_contract_data(workspace: Path) -> None:+ enricher = _FakeEnricher([BOUND])+ enricher.has_contract_data = False+ with _in_workspace(workspace, enricher):+ assert await cross_repo_tests("backend", [PROVIDER_FILE]) is None+++async def test_no_link_for_the_changed_file_is_named_not_silent(workspace: Path) -> None:+ """Contract data but no link is an answer with a reason, not a None."""+ with _in_workspace(workspace, _FakeEnricher([BOUND])):+ result = await cross_repo_tests("backend", ["app/untouched.py"])+ assert result is not None+ assert result.summary["reason"] == "no_matching_links"+ assert result.recommendations == []+++async def test_a_failed_join_names_itself_on_every_row(+ workspace: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A break in the lookup must not read as "no tests guard this"."""+ import repowise.core.workspace.test_impact as core_test_impact++ def _boom(*args: Any, **kwargs: Any) -> Any:+ raise RuntimeError("index gone")++ monkeypatch.setattr(core_test_impact, "analyze_workspace_test_impact", _boom)+ with _in_workspace(workspace, _FakeEnricher([BOUND])):+ result = await cross_repo_tests("backend", [PROVIDER_FILE])+ assert result is not None+ assert result.summary == {"reason": "lookup_failed", "detail": "RuntimeError"}+ block = _block(result, BOUND)+ assert block["state"] == "unresolved"+ assert block["unresolved_reason"] == "lookup_failed"+ assert block["unresolved_detail"] == "RuntimeError"+++async def test_a_none_result_still_yields_a_block_naming_its_state() -> None:+ block = _block(None, BOUND)+ assert block["state"] == "none"+ assert block == {+ "state": "none",+ "tests_to_run": [],+ "total": 0,+ "truncated": False,+ "unresolved_reason": None,+ "unresolved_detail": None,+ }+++# ---------------------------------------------------------------------------+# The process-held indexes+# ---------------------------------------------------------------------------+++async def test_the_consumer_index_is_opened_once_and_released(workspace: Path) -> None:+ """Opening a repo loads its whole symbol table, so it is held across calls."""+ with _in_workspace(workspace, _FakeEnricher([BOUND])):+ await cross_repo_tests("backend", [PROVIDER_FILE])+ first = _state._test_impact_indexes["frontend"]+ await cross_repo_tests("backend", [PROVIDER_FILE])+ assert _state._test_impact_indexes["frontend"] is first+ await close_test_impact_indexes()+ assert _state._test_impact_indexes == {}+++async def test_a_closed_cache_answers_again_on_the_next_call(workspace: Path) -> None:+ """Closing releases the sessions and the lock; the next call rebuilds both."""+ with _in_workspace(workspace, _FakeEnricher([BOUND])):+ first = await cross_repo_tests("backend", [PROVIDER_FILE])+ await close_test_impact_indexes()+ assert _state._test_impact_lock is None+ again = await cross_repo_tests("backend", [PROVIDER_FILE])+ assert first is not None and again is not None+ assert [r.test_id for r in again.recommendations] == [+ r.test_id for r in first.recommendations+ ]+ assert _state._test_impact_indexes["frontend"] is not Nonediff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex 927a441d5..b6d50a8f8 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -4,8 +4,10 @@ from __future__ import annotationsimport jsonimport sqlite3+import sysfrom contextlib import asynccontextmanagerfrom pathlib import Path+from types import ModuleTypefrom unittest.mock import MagicMock, patchimport pytest@@ -13,6 +15,11 @@ from fastapi import FastAPIfrom fastapi.responses import JSONResponsefrom httpx import ASGITransport, AsyncClient+from repowise.core.workspace.test_impact import (+ UnresolvedLink,+ WorkspaceTestImpactResult,+ WorkspaceTestRecommendation,+)from repowise.server.mcp_server._enrichment import CrossRepoEnricherfrom repowise.server.routers import workspace@@ -1390,3 +1397,180 @@ class TestRepoQueryBudget:statements, connections = await self._measure(tmp_path, 3)assert statements == self.QUERIES_PER_REPO * 3assert connections == self.CONNECTIONS_PER_REPO * 3+++class TestGetTestImpact:+ """`/api/workspace/test-impact`: consumer tests for a provider change."""++ @staticmethod+ def _install_helper(monkeypatch: pytest.MonkeyPatch, fn) -> None:+ """Point the route's ``cross_repo_tests`` import at *fn*.++ The module is created when it is absent, so this test pins the route's+ own behaviour without depending on the helper's implementation.+ """+ name = "repowise.server.mcp_server._test_impact"+ module = sys.modules.get(name) or ModuleType(name)+ monkeypatch.setitem(sys.modules, name, module)+ monkeypatch.setattr(module, "cross_repo_tests", fn, raising=False)++ @pytest.mark.asyncio+ async def test_not_workspace_mode(self) -> None:+ app = _make_workspace_app()+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get(+ "/api/workspace/test-impact",+ params={"repo": "backend", "file": "api/routes.py"},+ )+ assert resp.status_code == 404++ @pytest.mark.asyncio+ async def test_file_is_required(self) -> None:+ app = _make_workspace_app(ws_config=_make_ws_config())+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/test-impact", params={"repo": "backend"})+ assert resp.status_code == 422++ @pytest.mark.asyncio+ async def test_no_contract_data_names_its_reason(self) -> None:+ """Without an enricher the answer is empty but says why, not a 404."""+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=None)+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get(+ "/api/workspace/test-impact",+ params={"repo": "backend", "file": "api/routes.py"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["recommendations"] == []+ assert data["summary"]["reason"] == "no_contract_data"++ @pytest.mark.asyncio+ async def test_helper_returning_none_is_an_empty_answer(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ async def _none(alias: str, changed_files: list[str]):+ return None++ self._install_helper(monkeypatch, _none)+ app = _make_workspace_app(+ ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path)+ )+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get(+ "/api/workspace/test-impact",+ params={"repo": "backend", "file": "api/routes.py"},+ )+ assert resp.status_code == 200+ assert resp.json()["summary"]["reason"] == "no_contract_data"++ @pytest.mark.asyncio+ async def test_repeated_file_params_reach_the_helper(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ seen: dict[str, object] = {}++ async def _capture(alias: str, changed_files: list[str]):+ seen["alias"] = alias+ seen["files"] = list(changed_files)+ return WorkspaceTestImpactResult()++ self._install_helper(monkeypatch, _capture)+ app = _make_workspace_app(+ ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path)+ )+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get(+ "/api/workspace/test-impact",+ params=[+ ("repo", "backend"),+ ("file", "api/routes.py"),+ ("file", "api/models.py"),+ ],+ )+ assert resp.status_code == 200+ assert seen["alias"] == "backend"+ assert seen["files"] == ["api/routes.py", "api/models.py"]++ @pytest.mark.asyncio+ async def test_rows_keep_symbol_ids_and_unresolved_reasons(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """The boundary carries the symbol id, the basis, and the reason."""+ result = WorkspaceTestImpactResult(+ recommendations=[+ WorkspaceTestRecommendation(+ test_id="tests/test_client.py::test_users",+ test_file="tests/test_client.py",+ consumer_repo="frontend",+ consumer_files=["src/client.ts"],+ consumer_symbol_ids=["src/client.ts::fetchUsers"],+ provider_repo="backend",+ contract_ids=["http::GET::/api/users"],+ contract_types=["http"],+ basis="measured",+ via="coverage-map",+ confidence=0.9,+ source_files=["api/routes.py"],+ evidence=[{"basis": "measured", "via": "coverage-map"}],+ )+ ],+ recommendations_total=1,+ recommendations_emitted=1,+ unresolved=[+ UnresolvedLink(+ consumer_repo="frontend",+ consumer_file="src/orders.ts",+ consumer_symbol_id=None,+ provider_repo="backend",+ provider_file="api/routes.py",+ contract_id="http::GET::/api/orders",+ contract_type="http",+ reason="unbound",+ detail=None,+ )+ ],+ files_analyzed=[+ {+ "consumer_repo": "frontend",+ "consumer_file": "src/client.ts",+ "state": "measured",+ "measured_tests_count": 1,+ "inferred_tests_count": 0,+ "via": "coverage-map",+ "provider_repos": ["backend"],+ "contract_ids": ["http::GET::/api/users"],+ "consumer_symbol_ids": ["src/client.ts::fetchUsers"],+ }+ ],+ summary={"states": {"measured": 1, "inferred": 0, "none": 0, "unresolved": 0}},+ )++ async def _result(alias: str, changed_files: list[str]):+ return result++ self._install_helper(monkeypatch, _result)+ app = _make_workspace_app(+ ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path)+ )+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get(+ "/api/workspace/test-impact",+ params={"repo": "backend", "file": "api/routes.py"},+ )+ assert resp.status_code == 200+ data = resp.json()+ row = data["recommendations"][0]+ assert row["consumer_symbol_ids"] == ["src/client.ts::fetchUsers"]+ assert row["basis"] == "measured"+ assert row["confidence"] == 0.9+ assert data["unresolved"][0]["reason"] == "unbound"+ assert data["unresolved"][0]["consumer_symbol_id"] is None+ assert data["files_analyzed"][0]["state"] == "measured"+ assert data["summary"]["states"]["measured"] == 1diff --git a/tests/unit/workspace/test_test_impact.py b/tests/unit/workspace/test_test_impact.pyindex 697345437..cf1bd354c 100644--- a/tests/unit/workspace/test_test_impact.py+++ b/tests/unit/workspace/test_test_impact.py@@ -166,7 +166,8 @@ class TestStates:assert by_basis["measured"].via == "coverage-map"assert by_basis["inferred"].test_file == "tests/api.test.ts"assert by_basis["inferred"].via == "call-graph"- assert by_basis["inferred"].consumer_symbol_id == "src/api.ts::getUser"+ assert by_basis["inferred"].consumer_symbol_ids == ["src/api.ts::getUser"]+ assert by_basis["inferred"].consumer_files == ["src/api.ts"]assert by_basis["inferred"].contract_ids == [BOUND.contract_id]assert by_basis["inferred"].contract_types == ["http"]assert by_basis["inferred"].source_files == [PROVIDER_FILE]