Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix: preserve PR test impact semantics (#1912)

Raghav Chamadiyaba9607e01fbe
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 5df9fd864..4ad85e21b 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -453,7 +453,7 @@ Modification risk assessment for files or a set of changed files.
> **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 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:
+When `changed_files` is passed, the exact serialized response starts 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), compatibility `missing_tests`, and additive typed `test_recommendations`. Every recommendation retains `basis`, all retained `bases`, repository identity, source files, and evidence: `measured` means the per-test coverage map found the test; `inferred` means structural reachability found a candidate and is not coverage proof. `tests_to_run` preserves the older measured-first/fallback id projection and `tests_to_run_basis` remains `measured`, `inferred`, or `none`; `files_without_measured_tests` carries the narrower typed coverage claim. Matching total/emitted/truncated/omitted fields describe each exact pre-cap population. `coverage_analysis`, `test_inference_analysis`, and `test_analysis` distinguish available-empty evidence from unavailable, stale, partial, or degraded analysis; unavailable coverage with `tests_to_run: []` never means that no tests are needed. The full typed population is shared with the REST blast-radius response, while any budget-omitted directive rows are recoverable through the response omission marker. In workspace mode the directive also carries the cross-repo fallout of the changed repo:
- `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.
diff --git a/docs/agent/VSCODE.md b/docs/agent/VSCODE.md
index e331d815b..fa0c36f89 100644
--- a/docs/agent/VSCODE.md
+++ b/docs/agent/VSCODE.md
@@ -29,16 +29,16 @@ your uncommitted work against its base branch and opens a panel with the whole
story of the change:
- A summary strip up top: how many files are affected downstream, how many
- usual companion files you have not touched, and how many changed files have
- no associated test. Each chip jumps to its section.
+ usual companion files you have not touched, and the test recommendations or
+ unavailable/partial/stale analysis state. Each chip jumps to its section.
- **Riskiest files in this change**: your changed files ranked by how risky
history and structure say they are, so you review in the right order. Files
that change unusually often are marked as hotspots.
- **Downstream of your changes**: the files that depend on what you edited.
- **Usually changes together**: companion files your history says belong to
this change but are untouched. Advisory, not a rule.
-- **Changed without a test**, and **suggested reviewers** with one-click copy
- for the PR description.
+- **Test impact** with measured coverage evidence kept separate from inferred
+ candidates, and **suggested reviewers** with one-click copy for the PR description.
While you edit, a quiet co-change hint can appear in the status bar when the
files you are touching have a strong history of changing together with a file
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index c0603974e..54f08f722 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -189,19 +189,25 @@ proportion to how much of it is untested rather than only at a cliff.
Two MCP tools carry test information, at two different granularities.
**`get_risk(changed_files=[...])`** leads with a `directive` block whose
-`tests_to_run` names the tests that exercise the changed *files*. It is
-file-level and scoped to the diff itself, and capped at ten.
+`test_recommendations` names tests for the changed *files*. It is file-level,
+scoped to the diff, and capped at ten. Each row keeps its machine-readable
+`basis`, repository identity, source files, and evidence:
-Read `tests_to_run_basis` beside it. The two sources are not interchangeable
-and the ids alone will not tell them apart:
-
-| `tests_to_run_basis` | `tests_to_run` holds | Means |
+| Row `basis` | Recommendation holds | Means |
|---|---|---|
-| `measured` | test node ids | the map proves these execute the changed files |
-| `inferred` | test *file* paths | the graph shows these reaching the change; candidates, run them first |
-| `none` | `[]` | neither source knows of a test. Unknown, not "untested" |
+| `measured` | test node id | the available per-test map found the test covering a changed file |
+| `inferred` | test file path | the graph shows the test reaching the change; a candidate, not coverage proof |
+
+`tests_to_run` is the compatibility id projection. It preserves the historical
+measured-first fallback and its `measured` / `inferred` / `none` scalar domain;
+new consumers use the adjacent typed rows for the additive evidence union.
+Total/emitted/truncated/omitted fields cover each exact population before its
+cap. `coverage_analysis` separately reports
+available, unavailable, partial, degraded, and stale states; an empty list under
+unavailable analysis is unknown and never means "no tests are needed".
-Both forms are runnable arguments to pytest. They are never mixed in one list.
+Both forms are runnable arguments to pytest. The typed list may contain both,
+but every row keeps its own basis; the legacy id list remains measured-first.
**`get_change_risk(revspec=...)`** returns `impacted_tests`, computed from the
changed *lines*, so it is a strictly narrower and more useful set:
@@ -277,11 +283,12 @@ no setup at all.
| May produce a percentage | yes | **never** |
| Labelled | `basis: "measured"` | `basis: "inferred"` |
-The two are shown side by side and are never averaged into one number. Where both
-can answer, the measured one wins outright and the graph is not consulted; the
-inferred tier only fills silence. Its error is one-sided and known, so it is sound
-as a floor ("something reaches this, do not call it untested") and unsound as a
-quantity.
+The two are shown side by side and are never averaged into one number. The
+canonical PR test-impact population evaluates both and retains their separate
+evidence; compatibility surfaces remain measured-first. Other test-intelligence
+surfaces may use inference only to fill measured silence. Inference's error is
+one-sided and known, so it is sound as a floor ("something reaches this, do not
+call it untested") and unsound as a quantity.
### The call graph leads, the import graph fills silence
@@ -380,11 +387,12 @@ Both tools carry an explicit discriminator alongside the list:
summary that says "run the full suite" when it cannot. Other degraded statuses
are `no_index` (nothing indexed yet), `unknown` (the git read failed), and
`no_source_line_changes`. `basis` carries the same distinction in one word.
-- `get_risk` produces `tests_to_run` from a `guarding_tests` block, and the
- `directive` lifts `tests_to_run_basis` beside it, so the two cases are
- distinguishable without reaching into `pr_blast_radius`. `map_present` remains
- the measured-map flag and is still available at
- `pr_blast_radius.guarding_tests.map_present`.
+- `get_risk` and the REST blast-radius route consume one canonical
+ `test_impact` population. The directive lifts capped typed recommendations and
+ keeps `tests_to_run` as a non-contradictory compatibility projection. Coverage
+ availability, freshness, and measured-map presence remain explicit at
+ `pr_blast_radius.test_impact.coverage`; the legacy `guarding_tests` block is a
+ projection of the same rows rather than a separate derivation.
Only `status: "map_present"` with an empty `tests` list means "the map exists and
nothing in it covers this change". That is a real finding. `status: "inferred"`
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index be7e8400f..7f9fed8f2 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -82,12 +82,13 @@ def project_risk(payload: dict) -> dict:
(15/10/10/5) before it gets here — so the block a caller would most want is
the one an allowlist would silently discard, at almost no size.
"""
- out: dict = {
- "targets": {
- name: _project_target(card) for name, card in (payload.get("targets") or {}).items()
- }
+ out: dict = {}
+ if payload.get("directive"):
+ out["directive"] = payload["directive"]
+ out["targets"] = {
+ name: _project_target(card) for name, card in (payload.get("targets") or {}).items()
}
- for key in ("directive", "pr_blast_radius", "global_hotspots", "omission_marker"):
+ for key in ("pr_blast_radius", "global_hotspots", "omission_marker"):
if payload.get(key):
out[key] = payload[key]
note = _ta.index_note(payload)
@@ -511,8 +512,7 @@ def risk_command(
)
elif result.hot_files:
where = (
- f" · {_ordinal(round(result.fix_percentile))} percentile of this repo's "
- "recent commits"
+ f" · {_ordinal(round(result.fix_percentile))} percentile of this repo's recent commits"
if result.fix_percentile is not None
else ""
)
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.py
index 169abddb0..75adac5b6 100644
--- a/packages/core/src/repowise/core/analysis/pr_blast.py
+++ b/packages/core/src/repowise/core/analysis/pr_blast.py
@@ -24,9 +24,9 @@ from typing import Any
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.exclusion import is_excluded
+from repowise.core.exclusion import build_exclude_spec, is_excluded
from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
-from repowise.core.persistence.models import GitMetadata, GraphNode
+from repowise.core.persistence.models import GitMetadata, GraphNode, Repository
def rank_tests_by_reach(by_file: Mapping[str, Iterable[str]]) -> list[str]:
@@ -83,9 +83,15 @@ def _names_a_test_for(stem: str, ext: str, test_path: str, exact: bool) -> bool:
class PRBlastRadiusAnalyzer:
"""Compute blast radius for a proposed PR given its changed files."""
- def __init__(self, session: AsyncSession, repo_id: str) -> None:
+ def __init__(
+ self,
+ session: AsyncSession,
+ repo_id: str,
+ repository_alias: str | None = None,
+ ) -> None:
self._session = session
self._repo_id = repo_id
+ self._repository_alias = repository_alias
async def analyze_files(
self,
@@ -102,6 +108,17 @@ class PRBlastRadiusAnalyzer:
max_depth:
Maximum BFS depth for transitive ancestor lookup.
"""
+ if exclude_spec is None:
+ repo_path = (
+ await self._session.execute(
+ select(Repository.local_path).where(Repository.id == self._repo_id)
+ )
+ ).scalar_one_or_none()
+ if repo_path:
+ exclude_spec = build_exclude_spec(repo_path)
+ changed_files = [
+ path for path in changed_files if not (exclude_spec and is_excluded(path, exclude_spec))
+ ]
changed_set = set(changed_files)
# 1. Per-file direct risk
@@ -129,9 +146,12 @@ class PRBlastRadiusAnalyzer:
# 5. Test gaps
test_gaps = await self._find_test_gaps(all_affected_paths)
- # 6. Guarding tests — the tests the per-test coverage map proves execute
- # the changed files (the "run these to validate" answer).
- guarding_tests = await self._guarding_tests(changed_files)
+ # 6. Canonical test impact. MCP and REST consume this same typed
+ # population; ``guarding_tests`` is its compatibility projection.
+ test_impact = await self._test_impact(changed_files, exclude_spec=exclude_spec)
+ from repowise.core.analysis.test_impact import legacy_guarding_tests
+
+ guarding_tests = legacy_guarding_tests(test_impact)
# 7. Overall risk score (0-10)
overall_risk_score = self._compute_overall_risk(direct_risks, transitive_affected)
@@ -142,6 +162,7 @@ class PRBlastRadiusAnalyzer:
"cochange_warnings": cochange_warnings,
"recommended_reviewers": recommended_reviewers,
"test_gaps": test_gaps,
+ "test_impact": test_impact,
"guarding_tests": guarding_tests,
"overall_risk_score": overall_risk_score,
}
@@ -427,96 +448,50 @@ class PRBlastRadiusAnalyzer:
return gaps
- async def _guarding_tests(self, changed_files: list[str]) -> dict:
- """Tests the per-test coverage map proves execute the *changed* files.
-
- The inverse of ``test_gaps``: instead of "which changed file lacks a
- test", this answers "which recorded tests actually exercise this
- change" - the coverage-backed "run these to validate" list, keyed by
- test id (a pytest-runnable node id when the report carried node-id
- contexts). Reuses the Phase 1 reverse index ``tests_covering``.
-
- Scoped to the changed files, NOT the transitively-affected set: the
- Phase 3 gate showed that affected (importing) files are covered
- overwhelmingly by the same mega parametrized suites, so an
- affected-file run-list is near-useless noise. The actionable set is the
- tests that execute the code you actually edited. Line precision is not
- available here (get_risk takes file paths, not a diff), so this is
- file-level; ``repowise impacted-tests`` gives the line-level answer from
- a real diff.
-
- Falls back to the graph when no coverage report has been ingested, which
- is most repositories: a test file that reaches a changed file is a
- candidate worth running. ``basis`` says which of the two answered, and
- the two are never merged. A run-list the coverage map proved and one the
- graph suggests are different claims, and averaging them would leave the
- reader unable to tell a measured test from a guessed one. The
- inferred list names test *files* rather than test ids, because reaching
- is a file-level fact; both forms are runnable arguments to pytest.
-
- Returns ``{map_present, basis, tests_to_run, by_file}``.
- ``map_present`` stays the measured-map flag it always was.
- ``basis`` is ``"measured"``, ``"inferred"``, or ``"none"`` - and
- ``"none"`` is the honest "unknown", distinct from "this change has no
- guarding tests".
- """
- empty = {"map_present": False, "basis": "none", "tests_to_run": [], "by_file": {}}
- if not changed_files:
- return empty
+ async def _test_impact(self, changed_files: list[str], exclude_spec: Any = None) -> dict:
+ """Canonical measured + inferred test-impact population."""
+ from repowise.core.analysis.test_impact import analyze_test_impact
- from repowise.core.persistence.crud import get_test_coverage_summary, tests_covering
+ return await analyze_test_impact(
+ self._session,
+ self._repo_id,
+ changed_files,
+ repository_alias=self._repository_alias,
+ exclude_spec=exclude_spec,
+ )
- summary = await get_test_coverage_summary(self._session, self._repo_id)
- if summary.get("pair_count", 0) == 0:
- return await self._inferred_guarding_tests(changed_files, empty)
+ async def _guarding_tests(self, changed_files: list[str]) -> dict:
+ """Compatibility projection of :meth:`_test_impact`.
- by_file: dict[str, list[str]] = {}
- all_ids: set[str] = set()
- for path in changed_files:
- rows = await tests_covering(self._session, self._repo_id, path, lines=None)
- if not rows:
- continue
- ids = sorted({r["test_id"] for r in rows})
- by_file[path] = ids
- all_ids.update(ids)
+ ``basis`` retains its historical measured/inferred/none domain and
+ measured-first fallback. The canonical ``test_impact`` block contains
+ the additive union and per-recommendation truth.
+ """
+ from repowise.core.analysis.test_impact import legacy_guarding_tests
- if not all_ids:
- # The map exists but says nothing about these files. The graph may
- # still know something, and saying so beats an empty list that
- # reads as "nothing guards this change".
- blank = {"map_present": True, "basis": "none", "tests_to_run": [], "by_file": {}}
- return await self._inferred_guarding_tests(changed_files, blank)
-
- return {
- "map_present": True,
- "basis": "measured",
- "tests_to_run": rank_tests_by_reach(by_file),
- "by_file": by_file,
- }
+ return legacy_guarding_tests(await self._test_impact(changed_files))
async def _inferred_guarding_tests(self, changed_files: list[str], empty: dict) -> dict:
- """Graph-inferred run-list: test files that reach the changed files.
-
- Never execution-proven. Isolated behind its own method and its own
- ``basis`` value so no caller can pick it up while believing it read the
- measured map. Degrades to *empty* rather than raising: a run-list is an
- aid, and failing the whole risk assessment to withhold one is the wrong
- trade.
- """
- from repowise.core.analysis.test_reachability import tests_reaching
-
- try:
- reaching = await tests_reaching(self._session, self._repo_id, changed_files)
- except Exception:
- return empty
- if not reaching:
- return empty
- by_file = {path: sorted(tests) for path, tests in reaching.items() if tests}
+ """Compatibility wrapper returning only structurally inferred rows."""
+ impact = await self._test_impact(changed_files)
+ inferred = [row for row in impact["recommendations"] if row["basis"] == "inferred"]
+ by_file = {
+ item["source_file"]: item["inferred_tests"]
+ for item in impact["files"]
+ if item["inferred_tests"]
+ }
return {
- "map_present": empty["map_present"],
- "basis": "inferred",
- "tests_to_run": rank_tests_by_reach(by_file),
+ "map_present": empty.get("map_present", impact["coverage"]["map_present"]),
+ "basis": "inferred" if inferred else "none",
+ "tests_to_run": [row["test_id"] for row in inferred],
+ "tests_to_run_with_basis": inferred,
+ "tests_to_run_total": len(inferred),
+ "tests_to_run_emitted": len(inferred),
+ "tests_to_run_truncated": False,
"by_file": by_file,
+ "analysis": impact["analysis"],
+ "coverage": impact["coverage"],
+ "inference": impact["inference"],
}
@staticmethod
diff --git a/packages/core/src/repowise/core/analysis/test_impact.py b/packages/core/src/repowise/core/analysis/test_impact.py
new file mode 100644
index 000000000..555d27474
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/test_impact.py
@@ -0,0 +1,359 @@
+"""Canonical file-level test-impact analysis for PR blast-radius consumers.
+
+The measured per-test coverage map and structural test reachability answer
+different questions. This module keeps both evidence sets, attaches their
+basis to every recommendation, and exposes coverage availability separately
+from an empty recommendation population.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.exclusion import is_excluded
+from repowise.core.persistence.models import Repository
+
+_BASIS_ORDER = {"measured": 0, "inferred": 1}
+
+
+def _iso(value: Any) -> str | None:
+ if value is None:
+ return None
+ isoformat = getattr(value, "isoformat", None)
+ return isoformat() if callable(isoformat) else str(value)
+
+
+def _freshness(ingested_commit: str | None, indexed_commit: str | None) -> dict[str, Any]:
+ if not ingested_commit or not indexed_commit:
+ return {
+ "status": "unknown",
+ "reason": "coverage_or_index_commit_unavailable",
+ "ingested_commit": ingested_commit,
+ "indexed_commit": indexed_commit,
+ }
+ return {
+ "status": "current" if ingested_commit == indexed_commit else "stale",
+ "reason": None
+ if ingested_commit == indexed_commit
+ else "coverage_commit_differs_from_index",
+ "ingested_commit": ingested_commit,
+ "indexed_commit": indexed_commit,
+ }
+
+
+def _recommendation_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]:
+ return (
+ -len(row["source_files"]),
+ _BASIS_ORDER[row["basis"]],
+ row["repository"],
+ row["test_id"],
+ )
+
+
+def legacy_guarding_tests(test_impact: dict[str, Any]) -> dict[str, Any]:
+ """Compatibility projection for the historical ``guarding_tests`` block.
+
+ Compatibility preserves the historical measured-first contract: measured
+ rows win when any exist, otherwise inferred rows are the fallback. Consumers
+ that need the additive union and per-row truth read ``recommendations``.
+ """
+ recommendations = test_impact["recommendations"]
+ measured = [row for row in recommendations if row["basis"] == "measured"]
+ selected = measured or [row for row in recommendations if row["basis"] == "inferred"]
+ basis = selected[0]["basis"] if selected else "none"
+ by_file = {
+ row["source_file"]: row[f"{basis}_tests"]
+ for row in test_impact["files"]
+ if basis != "none" and row[f"{basis}_tests"]
+ }
+ return {
+ "map_present": test_impact["coverage"]["map_present"],
+ "basis": basis,
+ "tests_to_run": [row["test_id"] for row in selected],
+ "tests_to_run_with_basis": selected,
+ "tests_to_run_total": len(selected),
+ "tests_to_run_emitted": len(selected),
+ "tests_to_run_truncated": False,
+ "by_file": by_file,
+ "analysis": test_impact["analysis"],
+ "coverage": test_impact["coverage"],
+ "inference": test_impact["inference"],
+ }
+
+
+async def analyze_test_impact(
+ session: AsyncSession,
+ repository_id: str,
+ changed_files: list[str],
+ *,
+ repository_alias: str | None = None,
+ exclude_spec: Any = None,
+) -> dict[str, Any]:
+ """Return one typed, untruncated recommendation population.
+
+ The same result is consumed by MCP PR mode and the REST blast-radius route.
+ Coverage and graph inference are both evaluated; de-duplication keeps every
+ evidence basis on the surviving recommendation.
+ """
+ from repowise.core.analysis.test_reachability import tests_reaching_by_tier
+ from repowise.core.persistence.crud import get_test_coverage_summary, tests_covering
+
+ changed = sorted(
+ {
+ path
+ for path in changed_files
+ if path and not (exclude_spec and is_excluded(path, exclude_spec))
+ }
+ )
+ repository = repository_alias or repository_id
+ if not changed:
+ return {
+ "recommendations": [],
+ "recommendations_total": 0,
+ "recommendations_emitted": 0,
+ "recommendations_truncated": False,
+ "recommendations_omitted": 0,
+ "recommendations_by_primary_basis": {"measured": 0, "inferred": 0},
+ "files": [],
+ "files_total": 0,
+ "files_without_measured_tests": [],
+ "unknown_files": [],
+ "coverage": {
+ "status": "unavailable",
+ "reason": "no_changed_files",
+ "map_present": False,
+ "pair_count": 0,
+ "test_count": 0,
+ "source_file_count": 0,
+ "changed_files_total": 0,
+ "changed_files_with_measured_tests": 0,
+ "changed_files_without_measured_tests": 0,
+ "ingested_at": None,
+ "source_format": None,
+ "freshness": {
+ "status": "unknown",
+ "reason": "no_changed_files",
+ "ingested_commit": None,
+ "indexed_commit": None,
+ },
+ },
+ "inference": {
+ "status": "available",
+ "reason": None,
+ "changed_files_total": 0,
+ "changed_files_with_candidates": 0,
+ "candidates_before_dedup": 0,
+ },
+ "analysis": {
+ "status": "partial",
+ "stale": False,
+ "partial": True,
+ "degraded": False,
+ "basis_categories": [],
+ },
+ }
+ measured_by_file: dict[str, list[str]] = {path: [] for path in changed}
+ inferred_by_file: dict[str, list[str]] = {path: [] for path in changed}
+ evidence: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
+ test_files: dict[tuple[str, str], set[str]] = defaultdict(set)
+
+ try:
+ summary = await get_test_coverage_summary(session, repository_id)
+ map_present = summary.get("pair_count", 0) > 0
+ coverage_error: str | None = None
+ except Exception as exc: # analysis must degrade without losing graph candidates
+ summary = {}
+ map_present = False
+ coverage_error = type(exc).__name__
+
+ try:
+ indexed_commit = (
+ await session.execute(
+ select(Repository.head_commit).where(Repository.id == repository_id)
+ )
+ ).scalar_one_or_none()
+ except Exception:
+ indexed_commit = None
+
+ if map_present:
+ for path in changed:
+ try:
+ rows = await tests_covering(session, repository_id, path, lines=None)
+ except Exception as exc:
+ coverage_error = type(exc).__name__
+ rows = []
+ for row in rows:
+ test_id = str(row["test_id"])
+ test_file = row.get("test_file")
+ runnable_file = str(test_file or test_id.split("::", 1)[0])
+ if exclude_spec and is_excluded(runnable_file, exclude_spec):
+ continue
+ measured_by_file[path].append(test_id)
+ key = (repository_id, test_id)
+ if test_file:
+ test_files[key].add(str(test_file))
+ detail = {
+ "basis": "measured",
+ "source_file": path,
+ "via": "coverage-map",
+ "source_format": row.get("source_format"),
+ }
+ if detail not in evidence[key]:
+ evidence[key].append(detail)
+
+ try:
+ inferred = await tests_reaching_by_tier(session, repository_id, changed)
+ inference_status = "available"
+ inference_reason = None
+ except Exception as exc:
+ inferred = {}
+ inference_status = "degraded"
+ inference_reason = f"{type(exc).__name__}: test_reachability_failed"
+
+ inferred_totals_by_file: dict[str, int] = {}
+ for path, reached in inferred.items():
+ all_tests = list(reached.all_tests or tuple(reached.tests))
+ kept_tests = [
+ test_id
+ for test_id in all_tests
+ if not (exclude_spec and is_excluded(test_id, exclude_spec))
+ ]
+ inferred_totals_by_file[path] = len(kept_tests)
+ for test_id in kept_tests:
+ inferred_by_file[path].append(test_id)
+ key = (repository_id, test_id)
+ test_files[key].add(test_id)
+ detail = {
+ "basis": "inferred",
+ "source_file": path,
+ "via": reached.via,
+ "source_format": None,
+ }
+ if detail not in evidence[key]:
+ evidence[key].append(detail)
+
+ recommendations: list[dict[str, Any]] = []
+ for (repo_id, test_id), details in evidence.items():
+ details.sort(
+ key=lambda row: (
+ _BASIS_ORDER[row["basis"]],
+ row["source_file"],
+ row["via"],
+ )
+ )
+ bases = sorted({row["basis"] for row in details}, key=_BASIS_ORDER.__getitem__)
+ recommendations.append(
+ {
+ "test_id": test_id,
+ "test_file": sorted(test_files[(repo_id, test_id)])[0]
+ if test_files[(repo_id, test_id)]
+ else None,
+ "repository_id": repo_id,
+ "repository": repository,
+ "basis": bases[0],
+ "bases": bases,
+ "source_files": sorted({row["source_file"] for row in details}),
+ "evidence": details,
+ }
+ )
+ recommendations.sort(key=_recommendation_sort_key)
+
+ matched_files = sum(bool(tests) for tests in measured_by_file.values())
+ coverage_reason: str | None
+ if coverage_error:
+ coverage_status = "degraded"
+ coverage_reason = f"{coverage_error}: coverage_query_failed"
+ elif not map_present:
+ coverage_status = "unavailable"
+ coverage_reason = "no_per_test_coverage_map"
+ elif 0 < matched_files < len(changed):
+ coverage_status = "partial"
+ coverage_reason = "coverage_map_matches_only_part_of_change"
+ else:
+ coverage_status = "available"
+ coverage_reason = "no_matching_changed_files" if changed and matched_files == 0 else None
+
+ freshness = _freshness(summary.get("ingested_commit_sha"), indexed_commit)
+ coverage = {
+ "status": coverage_status,
+ "reason": coverage_reason,
+ "map_present": map_present,
+ "pair_count": int(summary.get("pair_count", 0) or 0),
+ "test_count": int(summary.get("test_count", 0) or 0),
+ "source_file_count": int(summary.get("source_file_count", 0) or 0),
+ "changed_files_total": len(changed),
+ "changed_files_with_measured_tests": matched_files,
+ "changed_files_without_measured_tests": len(changed) - matched_files,
+ "ingested_at": _iso(summary.get("ingested_at")),
+ "source_format": summary.get("source_format"),
+ "freshness": freshness,
+ }
+ inference = {
+ "status": inference_status,
+ "reason": inference_reason,
+ "changed_files_total": len(changed),
+ "changed_files_with_candidates": sum(bool(tests) for tests in inferred_by_file.values()),
+ "candidates_before_dedup": sum(inferred_totals_by_file.values()),
+ }
+
+ files = []
+ for path in changed:
+ measured_tests = sorted(set(measured_by_file[path]))
+ inferred_tests = sorted(set(inferred_by_file[path]))
+ status = "measured" if measured_tests else "inferred" if inferred_tests else "unknown"
+ files.append(
+ {
+ "source_file": path,
+ "status": status,
+ "measured_tests": measured_tests,
+ "measured_tests_total": len(measured_tests),
+ "inferred_tests": inferred_tests,
+ "inferred_tests_total": len(inferred_tests),
+ }
+ )
+
+ stale = freshness["status"] == "stale"
+ degraded = coverage_status == "degraded" or inference_status == "degraded"
+ partial = coverage_status != "available" or inference_status != "available" or stale
+ if degraded:
+ analysis_status = "degraded"
+ elif partial:
+ analysis_status = "partial"
+ else:
+ analysis_status = "available"
+
+ no_measured = [row["source_file"] for row in files if not row["measured_tests"]]
+ unknown = [row["source_file"] for row in files if row["status"] == "unknown"]
+ total = len(recommendations)
+ basis_totals = {
+ basis: sum(row["basis"] == basis for row in recommendations)
+ for basis in ("measured", "inferred")
+ }
+ return {
+ "recommendations": recommendations,
+ "recommendations_total": total,
+ "recommendations_emitted": total,
+ "recommendations_truncated": False,
+ "recommendations_omitted": 0,
+ "recommendations_by_primary_basis": basis_totals,
+ "files": files,
+ "files_total": len(files),
+ "files_without_measured_tests": no_measured,
+ "unknown_files": unknown,
+ "coverage": coverage,
+ "inference": inference,
+ "analysis": {
+ "status": analysis_status,
+ "stale": stale,
+ "partial": partial,
+ "degraded": degraded,
+ "basis_categories": sorted(
+ {basis for row in recommendations for basis in row["bases"]},
+ key=_BASIS_ORDER.__getitem__,
+ ),
+ },
+ }
diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
index 1ebf65d1d..d6fbced7f 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
@@ -87,9 +87,9 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
),
"get_risk": (
"get_risk(targets, changed_files?, include?)",
- "Call before editing: what history says about touching these files. "
- "PR mode (`changed_files`) leads with a `directive`: read `may_break` "
- "/ `missing_cochanges` / `missing_tests` / `tests_to_run`.",
+ "Call before editing for file history and blast radius. PR mode "
+ "(`changed_files`) leads with `directive`; read typed "
+ "`test_recommendations` and coverage state first.",
),
"get_change_risk": (
"get_change_risk(revspec?, extensions?, exclude_patterns?)",
@@ -109,8 +109,7 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
),
"get_overview": (
"get_overview()",
- "Architecture map. Call once, first, in an unfamiliar repo; skip it after "
- "that.",
+ "Architecture map. Call once, first, in an unfamiliar repo; skip it after that.",
),
}
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.py
index 8de100f4f..90cada489 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
@@ -50,7 +50,7 @@ _MAY_BREAK_LIMIT = 5
_MAY_BREAK_TESTS_LIMIT = 3
#: Cap on the coverage-backed run-list. A validate-this-change set can be longer
#: than the may-break lists (it is what you actually run), but stays glanceable;
-#: the overflow and the full per-file map live in pr_blast_radius.guarding_tests.
+#: the overflow and full typed rows live in pr_blast_radius.test_impact.
_TESTS_TO_RUN_LIMIT = 10
#: get_risk and get_change_risk both render 0-10 and measure unrelated things.
@@ -410,69 +410,84 @@ def _build_pr_directive(
[p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", [])) if p],
exclude_spec,
)[:3]
- # Scope to the PR: the directive answers "what should I do about
- # THIS diff", so only changed files belong here. Repo-wide test
- # gaps stay available in pr_blast_radius.test_gaps for deeper
- # review — surfacing them in the directive made unrelated files
- # ("alembic/env.py has no tests") read as failings of the PR.
- # Read from the untrimmed analyzer payload: the trimmed list is
- # capped at 10 repo-wide entries and may have already dropped the
- # changed files we're looking for.
- changed_set = set(changed_files)
- missing_tests = filter_path_list(
- [
- p
- for p in (_as_path(e) for e in pr_blast_radius.get("test_gaps", []))
- if p and p in changed_set
- ],
- exclude_spec,
- )[:3]
+ # Run-list: consume the analyzer's canonical typed population instead of
+ # independently deriving test ids. Every row retains its basis through
+ # de-duplication, sorting, exclusions, and the directive cap.
+ test_impact = pr_blast_radius.get("test_impact") or {}
+ all_recommendations = list(test_impact.get("recommendations") or [])
+ test_recommendations = all_recommendations[:_TESTS_TO_RUN_LIMIT]
+ test_recommendations_total = len(all_recommendations)
+ recommendations_capped = test_recommendations_total > _TESTS_TO_RUN_LIMIT
+ if recommendations_capped:
+ collector.add(
+ f"directive.test_recommendations beyond cap={_TESTS_TO_RUN_LIMIT} "
+ f"({test_recommendations_total - _TESTS_TO_RUN_LIMIT} dropped)",
+ all_recommendations[_TESTS_TO_RUN_LIMIT:],
+ )
- # Run-list: the tests that exercise the changed files (the positive
- # complement of missing_tests). Read from the untrimmed analyzer payload;
- # _trim_blast_lists passes guarding_tests through, but reading it here keeps
- # the source explicit.
+ # Preserve the measured-first legacy projection and its existing scalar
+ # domain. The additive typed rows above are the union of evidence kinds.
guarding = pr_blast_radius.get("guarding_tests") or {}
- all_tests_to_run = list(guarding.get("tests_to_run", []))
- # One word saying where the list came from, because the two sources carry
- # different weight and an agent cannot tell them apart from the ids alone.
- # "measured" is coverage-proven execution; "inferred" is a test file the
- # import graph shows reaching the change, which over-claims and is a
- # candidate list, not a proof. Kept as a sibling field rather than mixed
- # into the ids so no caller can read one as the other.
+ all_tests_to_run = list(guarding.get("tests_to_run") or [])
tests_to_run_basis = guarding.get("basis") or "none"
- # Only the inferred list is exclude-filtered. Its entries are repo file
- # paths, so a user who excluded a tree must not be handed paths out of it;
- # measured entries are test node ids ("path::name"), which are not paths and
- # would not survive a path filter intact.
- if tests_to_run_basis == "inferred":
- all_tests_to_run = filter_path_list(all_tests_to_run, exclude_spec)
tests_to_run = all_tests_to_run[:_TESTS_TO_RUN_LIMIT]
- capped = len(all_tests_to_run) > _TESTS_TO_RUN_LIMIT
- if capped:
+ tests_to_run_total = len(all_tests_to_run)
+ tests_capped = tests_to_run_total > _TESTS_TO_RUN_LIMIT
+ if tests_capped:
collector.add(
f"directive.tests_to_run beyond cap={_TESTS_TO_RUN_LIMIT} "
- f"({len(all_tests_to_run) - _TESTS_TO_RUN_LIMIT} dropped)",
+ f"({tests_to_run_total - _TESTS_TO_RUN_LIMIT} dropped)",
all_tests_to_run[_TESTS_TO_RUN_LIMIT:],
)
- if not all_tests_to_run:
+ if not all_recommendations:
tests_to_run_suffix = ""
- elif tests_to_run_basis == "measured":
- tests_to_run_suffix = (
- f" {len(all_tests_to_run)} coverage-backed test(s) guard the change - run these."
- )
else:
+ basis_totals = test_impact.get("recommendations_by_primary_basis") or {}
+ measured_total = int(basis_totals.get("measured", 0))
+ inferred_total = int(basis_totals.get("inferred", 0))
tests_to_run_suffix = (
- f" {len(all_tests_to_run)} test file(s) reach the change per the import graph "
- f"(inferred, not coverage-proven) - run these first."
+ f" {test_recommendations_total} test recommendation(s): {measured_total} measured "
+ f"and {inferred_total} inferred, not coverage-proven candidate(s); "
+ f"each row carries its basis."
)
- if capped:
- # The cap is fine; nothing told the reader the full list is in the same
- # response. guarding_tests is uncapped and carries the per-file map.
+ if recommendations_capped:
tests_to_run_suffix += (
- f" Showing {_TESTS_TO_RUN_LIMIT} of {len(all_tests_to_run)}; "
- f"all of them, and which file each guards, are in "
- f"pr_blast_radius.guarding_tests."
+ f" Showing {_TESTS_TO_RUN_LIMIT} of {test_recommendations_total}; omitted "
+ "typed rows are captured by the response omission marker."
+ )
+
+ # Keep legacy ``missing_tests`` as changed-file test gaps when analysis is
+ # usable. The additive ``files_without_measured_tests`` field carries the
+ # narrower coverage claim without making older clients misread inferred rows.
+ coverage = test_impact.get("coverage") or {}
+ coverage_freshness = coverage.get("freshness") or {}
+ coverage_usable = coverage.get("status") in {"available", "partial"} and (
+ coverage_freshness.get("status") != "stale"
+ )
+ if coverage_usable:
+ full_gap_paths = {
+ path
+ for path in (_as_path(entry) for entry in pr_blast_radius.get("test_gaps") or [])
+ if path and not (exclude_spec and is_excluded(path, exclude_spec))
+ }
+ all_missing_tests = [path for path in changed_files if path in full_gap_paths]
+ missing_tests = all_missing_tests[:3]
+ missing_tests_total = len(all_missing_tests)
+ if missing_tests_total > len(missing_tests):
+ collector.add(
+ f"directive.missing_tests beyond cap=3 "
+ f"({missing_tests_total - len(missing_tests)} dropped)",
+ all_missing_tests[3:],
+ )
+ missing_tests_summary = (
+ f"Showing {len(missing_tests)} of {missing_tests_total} changed-file test gap(s)."
+ )
+ else:
+ missing_tests = []
+ missing_tests_total = 0
+ missing_tests_summary = (
+ f"Coverage analysis is {coverage.get('status', 'unavailable')}; "
+ "missing_tests is withheld rather than treated as empty evidence."
)
gov_count = len(governance_risk)
@@ -529,8 +544,29 @@ def _build_pr_directive(
"may_break_tests": may_break_tests,
"missing_cochanges": missing_cochanges,
"missing_tests": missing_tests,
+ "missing_tests_semantics": "changed_file_test_gap_compatibility_projection",
+ "missing_tests_total": missing_tests_total,
+ "missing_tests_emitted": len(missing_tests),
+ "missing_tests_truncated": len(missing_tests) < missing_tests_total,
+ "missing_tests_omitted": missing_tests_total - len(missing_tests),
+ "files_without_measured_tests": list(test_impact.get("files_without_measured_tests") or []),
"tests_to_run": tests_to_run,
"tests_to_run_basis": tests_to_run_basis,
+ "tests_to_run_total": tests_to_run_total,
+ "tests_to_run_emitted": len(tests_to_run),
+ "tests_to_run_truncated": tests_capped,
+ "tests_to_run_omitted": tests_to_run_total - len(tests_to_run),
+ "test_recommendations": test_recommendations,
+ "test_recommendations_total": test_recommendations_total,
+ "test_recommendations_emitted": len(test_recommendations),
+ "test_recommendations_truncated": recommendations_capped,
+ "test_recommendations_omitted": max(
+ 0, test_recommendations_total - len(test_recommendations)
+ ),
+ "test_analysis": test_impact.get("analysis") or {"status": "unavailable"},
+ "coverage_analysis": coverage,
+ "test_inference_analysis": test_impact.get("inference") or {"status": "unavailable"},
+ "test_unknown_files": list(test_impact.get("unknown_files") or []),
"will_break_consumers": will_break_consumers,
"will_break_consumers_semantics": "structural_reach_only",
"will_break_consumers_deprecated": True,
@@ -554,7 +590,7 @@ def _build_pr_directive(
f"~{len(may_break)} downstream file(s) may be affected, "
f"{len(may_break_tests)} test(s) may break, "
f"{len(missing_cochanges)} historical co-changer(s) missing, "
- f"{len(missing_tests)} file(s) without tests."
+ f"{missing_tests_summary}"
f"{tests_to_run_suffix}{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"
),
}
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.py
index 0afb112e7..95cd2ff85 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
@@ -33,7 +33,8 @@ from .directives import _build_pr_directive, _governance_directive
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.
+# The directive retains its capped typed run list even if the larger blast
+# dossier is shed to fit the transport budget.
_SHED_ORDER: tuple[str, ...] = (
"global_hotspots",
"pr_blast_radius.guarding_tests",
@@ -102,9 +103,9 @@ async def get_risk(
findings. Consult before editing a bug-fixed or busy file. Pass
changed_files for PR mode: the response leads with a directive block
(may_break, missing_cochanges, missing_tests, tests_to_run) — read it
- first. tests_to_run_basis backs the run-list: measured (a coverage map
- proves those tests run the changed files) or inferred (test files the import
- graph shows reaching them; candidates, no ingest needed). To score a commit
+ first. Each test_recommendations row carries a measured or inferred basis;
+ tests_to_run keeps its measured-first compatibility projection. Coverage
+ availability and freshness are explicit. To score a commit
or ``base..head`` range instead, use ``get_change_risk``.
defect_profile appears only with counted fixes; top_symbols is approximate
@@ -251,7 +252,7 @@ async def get_risk(
if changed_files:
from repowise.core.analysis.pr_blast import PRBlastRadiusAnalyzer
- analyzer = PRBlastRadiusAnalyzer(session, repo_id)
+ analyzer = PRBlastRadiusAnalyzer(session, repo_id, repository_alias=ctx.alias)
pr_blast_radius = await analyzer.analyze_files(changed_files, exclude_spec=exclude_spec)
# Cross-repo blast radius enrichment (Phase 3 + 4)
@@ -287,6 +288,10 @@ async def get_risk(
test_paths,
ctx.alias,
)
+ # Dict insertion order is the serialized external order. PR mode is
+ # action-first by contract, so the directive must precede dossiers,
+ # targets, metadata, and omission details in the exact payload.
+ response = {"directive": response.pop("directive"), **response}
elif len(targets) > 1:
# Standard per-file risk request (no diff) — ambient orientation across
# a set of targets. On one file the caller already named, it is noise.
diff --git a/packages/server/src/repowise/server/routers/blast_radius.py b/packages/server/src/repowise/server/routers/blast_radius.py
index f88bf9dda..49c1b5697 100644
--- a/packages/server/src/repowise/server/routers/blast_radius.py
+++ b/packages/server/src/repowise/server/routers/blast_radius.py
@@ -24,9 +24,9 @@ async def analyze_blast_radius(
) -> BlastRadiusResponse:
"""Compute blast radius for a proposed PR given its changed files.
- Returns direct risk scores per file, transitively affected files (BFS up to
- max_depth), historical co-change warnings, recommended reviewers, test gaps,
- and an overall risk score (0–10).
+ Returns direct risk scores, transitive structural reach, historical
+ co-change warnings, reviewers, compatibility test gaps, a canonical typed
+ test-impact population with evidence/availability state, and a 0–10 score.
"""
analyzer = PRBlastRadiusAnalyzer(session=session, repo_id=repo_id)
result = await analyzer.analyze_files(
diff --git a/packages/server/src/repowise/server/schemas/blast_radius.py b/packages/server/src/repowise/server/schemas/blast_radius.py
index 80c6cc5fd..330907143 100644
--- a/packages/server/src/repowise/server/schemas/blast_radius.py
+++ b/packages/server/src/repowise/server/schemas/blast_radius.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from typing import Literal
+
from pydantic import BaseModel, Field
@@ -34,10 +36,92 @@ class ReviewerEntry(BaseModel):
ownership_pct: float
+class TestImpactEvidence(BaseModel):
+ basis: Literal["measured", "inferred"]
+ source_file: str
+ via: Literal["coverage-map", "call-graph", "import-graph"]
+ source_format: str | None = None
+
+
+class TestRecommendation(BaseModel):
+ test_id: str
+ test_file: str | None = None
+ repository_id: str
+ repository: str
+ basis: Literal["measured", "inferred"]
+ bases: list[Literal["measured", "inferred"]]
+ source_files: list[str]
+ evidence: list[TestImpactEvidence]
+
+
+class TestImpactFile(BaseModel):
+ source_file: str
+ status: Literal["measured", "inferred", "unknown"]
+ measured_tests: list[str]
+ measured_tests_total: int
+ inferred_tests: list[str]
+ inferred_tests_total: int
+
+
+class TestImpactFreshness(BaseModel):
+ status: Literal["current", "stale", "unknown"]
+ reason: str | None = None
+ ingested_commit: str | None = None
+ indexed_commit: str | None = None
+
+
+class TestImpactCoverage(BaseModel):
+ status: Literal["available", "partial", "unavailable", "degraded"]
+ reason: str | None = None
+ map_present: bool
+ pair_count: int
+ test_count: int
+ source_file_count: int
+ changed_files_total: int
+ changed_files_with_measured_tests: int
+ changed_files_without_measured_tests: int
+ ingested_at: str | None = None
+ source_format: str | None = None
+ freshness: TestImpactFreshness
+
+
+class TestImpactInference(BaseModel):
+ status: Literal["available", "degraded"]
+ reason: str | None = None
+ changed_files_total: int
+ changed_files_with_candidates: int
+ candidates_before_dedup: int
+
+
+class TestImpactAnalysis(BaseModel):
+ status: Literal["available", "partial", "degraded"]
+ stale: bool
+ partial: bool
+ degraded: bool
+ basis_categories: list[Literal["measured", "inferred"]]
+
+
+class TestImpactResponse(BaseModel):
+ recommendations: list[TestRecommendation]
+ recommendations_total: int
+ recommendations_emitted: int
+ recommendations_truncated: bool
+ recommendations_omitted: int
+ recommendations_by_primary_basis: dict[Literal["measured", "inferred"], int]
+ files: list[TestImpactFile]
+ files_total: int
+ files_without_measured_tests: list[str]
+ unknown_files: list[str]
+ coverage: TestImpactCoverage
+ inference: TestImpactInference
+ analysis: TestImpactAnalysis
+
+
class BlastRadiusResponse(BaseModel):
direct_risks: list[DirectRiskEntry]
transitive_affected: list[TransitiveEntry]
cochange_warnings: list[CochangeWarning]
recommended_reviewers: list[ReviewerEntry]
test_gaps: list[str]
+ test_impact: TestImpactResponse
overall_risk_score: float
diff --git a/packages/types/src/blast-radius.ts b/packages/types/src/blast-radius.ts
index ae6b8bae9..28809145e 100644
--- a/packages/types/src/blast-radius.ts
+++ b/packages/types/src/blast-radius.ts
@@ -35,12 +35,90 @@ export interface ReviewerEntry {
ownership_pct: number;
}
+export type TestRecommendationBasis = "measured" | "inferred";
+
+export interface TestImpactEvidence {
+ basis: TestRecommendationBasis;
+ source_file: string;
+ via: "coverage-map" | "call-graph" | "import-graph";
+ source_format: string | null;
+}
+
+export interface TestRecommendation {
+ test_id: string;
+ test_file: string | null;
+ repository_id: string;
+ repository: string;
+ /** Strongest evidence on this de-duplicated recommendation. */
+ basis: TestRecommendationBasis;
+ /** Every retained evidence category; measured and inferred may both occur. */
+ bases: TestRecommendationBasis[];
+ source_files: string[];
+ evidence: TestImpactEvidence[];
+}
+
+export interface TestImpactResponse {
+ recommendations: TestRecommendation[];
+ recommendations_total: number;
+ recommendations_emitted: number;
+ recommendations_truncated: boolean;
+ recommendations_omitted: number;
+ /** Exact, mutually exclusive totals over the full recommendation population. */
+ recommendations_by_primary_basis: Record<TestRecommendationBasis, number>;
+ files: Array<{
+ source_file: string;
+ status: "measured" | "inferred" | "unknown";
+ measured_tests: string[];
+ measured_tests_total: number;
+ inferred_tests: string[];
+ inferred_tests_total: number;
+ }>;
+ files_total: number;
+ files_without_measured_tests: string[];
+ unknown_files: string[];
+ coverage: {
+ status: "available" | "partial" | "unavailable" | "degraded";
+ reason: string | null;
+ map_present: boolean;
+ pair_count: number;
+ test_count: number;
+ source_file_count: number;
+ changed_files_total: number;
+ changed_files_with_measured_tests: number;
+ changed_files_without_measured_tests: number;
+ ingested_at: string | null;
+ source_format: string | null;
+ freshness: {
+ status: "current" | "stale" | "unknown";
+ reason: string | null;
+ ingested_commit: string | null;
+ indexed_commit: string | null;
+ };
+ };
+ inference: {
+ status: "available" | "degraded";
+ reason: string | null;
+ changed_files_total: number;
+ changed_files_with_candidates: number;
+ candidates_before_dedup: number;
+ };
+ analysis: {
+ status: "available" | "partial" | "degraded";
+ stale: boolean;
+ partial: boolean;
+ degraded: boolean;
+ basis_categories: TestRecommendationBasis[];
+ };
+}
+
export interface BlastRadiusResponse {
direct_risks: DirectRiskEntry[];
transitive_affected: TransitiveEntry[];
cochange_warnings: CochangeWarning[];
recommended_reviewers: ReviewerEntry[];
test_gaps: string[];
+ /** Canonical typed test-impact population. Optional for older servers. */
+ test_impact?: TestImpactResponse;
/** 0–10. */
overall_risk_score: number;
}
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.md
index d7cecaf42..fb295dbeb 100644
--- a/packages/ui/COMPONENT_CONTRACTS.md
+++ b/packages/ui/COMPONENT_CONTRACTS.md
@@ -1207,7 +1207,9 @@ Email + files-owned + percent ownership. `ownership_pct` is 0–1.
### `blast-radius/test-gaps-list` — `TestGapsList`
-Bullet list of files lacking adjacent test coverage.
+Compatibility list of file-level test gaps. It is not a measured-coverage
+claim; consumers use `result.test_impact` for typed recommendations, evidence
+basis, and coverage availability.
| Prop | Type | Required |
|------|------|----------|
@@ -1224,7 +1226,10 @@ Transitive Files / Co-change Warnings / Test Gaps).
### `blast-radius/blast-radius-results` — `BlastRadiusResults`
-Composes the full results stack: gauge + summary + the five tables.
+Composes the full results stack: gauge, summary, impact map, typed test
+recommendations with measured/inferred basis, explicit unavailable-analysis
+copy, and the compatibility tables. `test_impact` is optional in the shared
+TypeScript contract so the component remains compatible with older servers.
| Prop | Type | Required |
|------|------|----------|
diff --git a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx b/packages/ui/__tests__/blast-radius/blast-radius.test.tsx
index b178e6e35..379857dfe 100644
--- a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx
+++ b/packages/ui/__tests__/blast-radius/blast-radius.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { RiskScoreCard } from "../../src/blast-radius/risk-score-card";
import { TableSection } from "../../src/blast-radius/table-section";
import { DirectRisksTable } from "../../src/blast-radius/direct-risks-table";
@@ -13,14 +13,95 @@ import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
const fixture: BlastRadiusResponse = {
direct_risks: [
- { path: "src/auth/login.py", risk_score: 0.82, temporal_hotspot: 0.74, centrality: 0.045 },
+ {
+ path: "src/auth/login.py",
+ risk_score: 0.82,
+ temporal_hotspot: 0.74,
+ centrality: 0.045,
+ },
],
transitive_affected: [{ path: "src/api/handlers.py", depth: 2 }],
cochange_warnings: [
- { changed: "src/auth/login.py", missing_partner: "tests/test_login.py", score: 7 },
+ {
+ changed: "src/auth/login.py",
+ missing_partner: "tests/test_login.py",
+ score: 7,
+ },
],
recommended_reviewers: [{ email: "[email protected]", files: 12, ownership_pct: 0.42 }],
test_gaps: ["src/auth/login.py"],
+ test_impact: {
+ recommendations: [
+ {
+ test_id: "tests/test_login.py::test_login",
+ test_file: "tests/test_login.py",
+ repository_id: "repo-1",
+ repository: "app",
+ basis: "measured",
+ bases: ["measured"],
+ source_files: ["src/auth/login.py"],
+ evidence: [
+ {
+ basis: "measured",
+ source_file: "src/auth/login.py",
+ via: "coverage-map",
+ source_format: "coverage.py",
+ },
+ ],
+ },
+ ],
+ recommendations_total: 1,
+ recommendations_emitted: 1,
+ recommendations_truncated: false,
+ recommendations_omitted: 0,
+ recommendations_by_primary_basis: { measured: 1, inferred: 0 },
+ files: [
+ {
+ source_file: "src/auth/login.py",
+ status: "measured",
+ measured_tests: ["tests/test_login.py::test_login"],
+ measured_tests_total: 1,
+ inferred_tests: [],
+ inferred_tests_total: 0,
+ },
+ ],
+ files_total: 1,
+ files_without_measured_tests: [],
+ unknown_files: [],
+ coverage: {
+ status: "available",
+ reason: null,
+ map_present: true,
+ pair_count: 1,
+ test_count: 1,
+ source_file_count: 1,
+ changed_files_total: 1,
+ changed_files_with_measured_tests: 1,
+ changed_files_without_measured_tests: 0,
+ ingested_at: "2026-08-24T00:00:00Z",
+ source_format: "coverage.py",
+ freshness: {
+ status: "current",
+ reason: null,
+ ingested_commit: "abc",
+ indexed_commit: "abc",
+ },
+ },
+ inference: {
+ status: "available",
+ reason: null,
+ changed_files_total: 1,
+ changed_files_with_candidates: 0,
+ candidates_before_dedup: 0,
+ },
+ analysis: {
+ status: "available",
+ stale: false,
+ partial: false,
+ degraded: false,
+ basis_categories: ["measured"],
+ },
+ },
overall_risk_score: 7.6,
};
@@ -107,18 +188,27 @@ describe("BlastRadiusSummary", () => {
describe("BlastRadiusResults", () => {
it("composes the risk header, impact map, and collapsible sections", () => {
- render(<BlastRadiusResults result={fixture} changedFiles={["src/auth/login.py"]} />);
+ render(
+ <BlastRadiusResults
+ result={fixture}
+ changedFiles={["src/auth/login.py"]}
+ />,
+ );
// Header band label + gauge score.
expect(screen.getByText("High risk")).toBeTruthy();
expect(screen.getByText("7.6")).toBeTruthy();
// The header tile and the collapsible toggle share the "Direct risks" /
// "Test gaps" copy, so each appears more than once.
- expect(screen.getAllByText("Direct risks").length).toBeGreaterThanOrEqual(1);
+ expect(screen.getAllByText("Direct risks").length).toBeGreaterThanOrEqual(
+ 1,
+ );
expect(screen.getByText("Transitive affected files")).toBeTruthy();
expect(screen.getByText("Co-change warnings")).toBeTruthy();
expect(screen.getByText("Recommended reviewers")).toBeTruthy();
expect(screen.getAllByText("Test gaps").length).toBeGreaterThanOrEqual(1);
expect(screen.getByText("Impact map")).toBeTruthy();
+ expect(screen.getByText("tests/test_login.py::test_login")).toBeTruthy();
+ expect(screen.getByText(/coverage-backed/)).toBeTruthy();
});
it("shows an empty impact map when nothing is affected", () => {
@@ -134,4 +224,79 @@ describe("BlastRadiusResults", () => {
expect(screen.getByText("No downstream impact found")).toBeTruthy();
expect(screen.getByText("Low risk")).toBeTruthy();
});
+
+ it("keeps older server payloads compatible without assuming test availability", () => {
+ const { test_impact: _testImpact, ...legacy } = fixture;
+
+ render(
+ <BlastRadiusResults
+ result={legacy as BlastRadiusResponse}
+ changedFiles={["src/auth/login.py"]}
+ />,
+ );
+ expect(
+ screen.getByText(/did not provide typed test-analysis state/),
+ ).toBeTruthy();
+ });
+
+ it("labels partial test analysis even when recommendations are present", () => {
+ const partial: BlastRadiusResponse = {
+ ...fixture,
+ test_impact: {
+ ...fixture.test_impact!,
+ coverage: {
+ ...fixture.test_impact!.coverage,
+ status: "partial",
+ reason: "coverage_map_matches_only_part_of_change",
+ },
+ analysis: {
+ ...fixture.test_impact!.analysis,
+ status: "partial",
+ partial: true,
+ },
+ },
+ };
+
+ render(
+ <BlastRadiusResults
+ result={partial}
+ changedFiles={["src/auth/login.py"]}
+ />,
+ );
+ expect(
+ screen.getAllByText(/Test analysis is partial/).length,
+ ).toBeGreaterThan(0);
+ });
+
+ it("does not interpret unavailable coverage as no tests needed", () => {
+ const unavailable: BlastRadiusResponse = {
+ ...fixture,
+ test_gaps: [],
+ test_impact: {
+ ...fixture.test_impact!,
+ recommendations: [],
+ recommendations_total: 0,
+ recommendations_emitted: 0,
+ recommendations_by_primary_basis: { measured: 0, inferred: 0 },
+ coverage: {
+ ...fixture.test_impact!.coverage,
+ status: "unavailable",
+ reason: "no_per_test_coverage_map",
+ map_present: false,
+ },
+ analysis: {
+ ...fixture.test_impact!.analysis,
+ status: "partial",
+ partial: true,
+ basis_categories: [],
+ },
+ },
+ };
+
+ render(<BlastRadiusResults result={unavailable} />);
+ expect(screen.getByText("Test analysis limited")).toBeTruthy();
+ expect(
+ screen.getAllByText(/does not mean no tests are needed/).length,
+ ).toBeGreaterThan(0);
+ });
});
diff --git a/packages/ui/src/blast-radius/blast-radius-header.tsx b/packages/ui/src/blast-radius/blast-radius-header.tsx
index 56c8baecf..80ae191bd 100644
--- a/packages/ui/src/blast-radius/blast-radius-header.tsx
+++ b/packages/ui/src/blast-radius/blast-radius-header.tsx
@@ -76,7 +76,11 @@ function RiskGauge({ score }: { score: number }) {
const valueEnd = 180 + frac * 180;
return (
<div className="relative shrink-0" style={{ width: GW, height: GH }}>
- <svg viewBox={`0 0 ${GW} ${GH}`} className="h-auto w-full" aria-hidden="true">
+ <svg
+ viewBox={`0 0 ${GW} ${GH}`}
+ className="h-auto w-full"
+ aria-hidden="true"
+ >
<path
d={arcPath(GCX, GCY, GR, 180, 360)}
fill="none"
@@ -95,7 +99,9 @@ function RiskGauge({ score }: { score: number }) {
)}
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-end pb-1">
- <span className={cn("text-4xl font-bold leading-none tabular-nums", b.text)}>
+ <span
+ className={cn("text-4xl font-bold leading-none tabular-nums", b.text)}
+ >
{score.toFixed(1)}
</span>
<span className="mt-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
@@ -122,7 +128,12 @@ function StatTile({ tile }: { tile: Tile }) {
tile.active ? "" : "opacity-60",
)}
>
- <span className={cn("shrink-0", tile.value > 0 ? tile.tone : "text-[var(--color-text-tertiary)]")}>
+ <span
+ className={cn(
+ "shrink-0",
+ tile.value > 0 ? tile.tone : "text-[var(--color-text-tertiary)]",
+ )}
+ >
{tile.icon}
</span>
<div className="min-w-0">
@@ -147,10 +158,29 @@ function verdict(result: BlastRadiusResponse, changedCount: number): string {
if (reach === 0) {
return `Changing ${changedCount} ${filesWord} looks self-contained — nothing downstream depends on it within this depth.`;
}
- const gapClause =
- gaps > 0
- ? ` ${gaps} affected ${gaps === 1 ? "file lacks" : "files lack"} tests.`
- : " Affected files have tests.";
+ const testImpact = result.test_impact;
+ let gapClause: string;
+ if (!testImpact) {
+ gapClause =
+ " Test analysis state was not provided by this server; no conclusion about needed tests is possible.";
+ } else if (["unavailable", "degraded"].includes(testImpact.coverage.status)) {
+ gapClause =
+ " Test analysis is unavailable; no conclusion about needed tests is possible.";
+ } else if (testImpact.recommendations_total > 0) {
+ const measured = testImpact.recommendations_by_primary_basis.measured;
+ const inferred = testImpact.recommendations_by_primary_basis.inferred;
+ const state = testImpact.analysis.stale
+ ? " Coverage evidence is stale."
+ : testImpact.analysis.partial
+ ? " Test analysis is partial."
+ : "";
+ gapClause = ` ${testImpact.recommendations_total} test recommendation${testImpact.recommendations_total === 1 ? "" : "s"} (${measured} measured, ${inferred} inferred).${state}`;
+ } else if (gaps > 0) {
+ gapClause = ` No test evidence was found for ${gaps} affected ${gaps === 1 ? "file" : "files"}.`;
+ } else {
+ gapClause =
+ " The available coverage map found no measured tests for this change.";
+ }
return `Changing ${changedCount} ${filesWord} puts ${reach} downstream ${
reach === 1 ? "file" : "files"
} in scope (${direct} direct, ${transitive} transitive).${gapClause}`;
@@ -161,7 +191,10 @@ function verdict(result: BlastRadiusResponse, changedCount: number): string {
* plain-English verdict — replacing the old centred-number card + flat stat
* grid so the result reads as a conclusion, not a row of figures.
*/
-export function BlastRadiusHeader({ result, changedFiles = [] }: BlastRadiusHeaderProps) {
+export function BlastRadiusHeader({
+ result,
+ changedFiles = [],
+}: BlastRadiusHeaderProps) {
const b = band(result.overall_risk_score);
const tiles: Tile[] = [
{
@@ -201,7 +234,9 @@ export function BlastRadiusHeader({ result, changedFiles = [] }: BlastRadiusHead
<div className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-2">
- <span className={cn("text-sm font-semibold", b.text)}>{b.label}</span>
+ <span className={cn("text-sm font-semibold", b.text)}>
+ {b.label}
+ </span>
<span className="text-xs text-[var(--color-text-tertiary)]">
· blast radius of this change
</span>
diff --git a/packages/ui/src/blast-radius/blast-radius-results.tsx b/packages/ui/src/blast-radius/blast-radius-results.tsx
index 6da0778c1..85ca1eab9 100644
--- a/packages/ui/src/blast-radius/blast-radius-results.tsx
+++ b/packages/ui/src/blast-radius/blast-radius-results.tsx
@@ -29,6 +29,24 @@ export function BlastRadiusResults({
changedFiles = [],
reviewersSlot,
}: BlastRadiusResultsProps) {
+ const testImpact = result.test_impact;
+ const recommendations = testImpact?.recommendations ?? [];
+ const testAnalysisUnavailable =
+ !testImpact ||
+ ["unavailable", "degraded"].includes(testImpact.coverage.status);
+ const testAnalysisLimited =
+ testAnalysisUnavailable ||
+ Boolean(testImpact?.analysis.partial || testImpact?.analysis.stale);
+ const testAnalysisNote = !testImpact
+ ? "This older server did not provide typed test-analysis state."
+ : testImpact.analysis.stale
+ ? "Coverage evidence is stale; measured recommendations may not describe the indexed commit."
+ : testImpact.analysis.degraded
+ ? "Test analysis is degraded; available recommendations are incomplete."
+ : testImpact.analysis.partial
+ ? "Test analysis is partial; available recommendations do not cover every evidence input."
+ : null;
+
return (
<div className="space-y-6">
<BlastRadiusHeader result={result} changedFiles={changedFiles} />
@@ -57,7 +75,10 @@ export function BlastRadiusResults({
{result.direct_risks.length > 0 ? (
<DirectRisksTable rows={result.direct_risks} />
) : (
- <EmptyState title="No direct risks" description="Nothing depends directly on the changed files." />
+ <EmptyState
+ title="No direct risks"
+ description="Nothing depends directly on the changed files."
+ />
)}
</CollapsibleSection>
@@ -68,7 +89,10 @@ export function BlastRadiusResults({
{result.transitive_affected.length > 0 ? (
<TransitiveTable rows={result.transitive_affected} />
) : (
- <EmptyState title="No transitive impact" description="No deeper dependents within the selected depth." />
+ <EmptyState
+ title="No transitive impact"
+ description="No deeper dependents within the selected depth."
+ />
)}
</CollapsibleSection>
@@ -79,7 +103,10 @@ export function BlastRadiusResults({
{result.cochange_warnings.length > 0 ? (
<CochangeTable rows={result.cochange_warnings} />
) : (
- <EmptyState title="No co-change warnings" description="No historical co-change partners are missing from this change." />
+ <EmptyState
+ title="No co-change warnings"
+ description="No historical co-change partners are missing from this change."
+ />
)}
</CollapsibleSection>
@@ -91,16 +118,81 @@ export function BlastRadiusResults({
{result.recommended_reviewers.length > 0 ? (
<ReviewersTable rows={result.recommended_reviewers} />
) : (
- <EmptyState title="No reviewer suggestions" description="No owners matched the changed files." />
+ <EmptyState
+ title="No reviewer suggestions"
+ description="No owners matched the changed files."
+ />
)}
</CollapsibleSection>
)}
- <CollapsibleSection title="Test gaps" hint={result.test_gaps.length || undefined}>
+ <CollapsibleSection
+ title="Tests to run"
+ hint={testImpact?.recommendations_total || undefined}
+ defaultOpen={recommendations.length > 0 || testAnalysisLimited}
+ >
+ {recommendations.length > 0 ? (
+ <div className="space-y-1">
+ {testAnalysisNote && (
+ <p className="px-2 text-xs text-[var(--color-text-tertiary)]">
+ {testAnalysisNote}
+ </p>
+ )}
+ {recommendations.map((recommendation) => (
+ <div
+ key={`${recommendation.repository_id}:${recommendation.test_id}`}
+ className="flex items-start justify-between gap-3 rounded px-2 py-1.5 text-sm"
+ >
+ <span className="min-w-0 break-all font-mono text-[var(--color-text-primary)]">
+ {recommendation.test_id}
+ </span>
+ <span className="shrink-0 text-xs text-[var(--color-text-tertiary)]">
+ {recommendation.basis === "measured"
+ ? "coverage-backed"
+ : "inferred"}
+ {` · ${recommendation.repository}`}
+ </span>
+ </div>
+ ))}
+ {testImpact?.recommendations_truncated && (
+ <p className="px-2 text-xs text-[var(--color-text-tertiary)]">
+ Showing {testImpact.recommendations_emitted} of{" "}
+ {testImpact.recommendations_total};{" "}
+ {testImpact.recommendations_omitted} omitted.
+ </p>
+ )}
+ </div>
+ ) : (
+ <EmptyState
+ title={
+ testAnalysisLimited
+ ? "Test analysis limited"
+ : "No measured tests found"
+ }
+ description={
+ testAnalysisLimited
+ ? `${testAnalysisNote ?? "Test analysis is incomplete."} An empty recommendation list does not mean no tests are needed.`
+ : "The available coverage map found no measured tests for this change. This is not proof that no relevant tests exist."
+ }
+ />
+ )}
+ </CollapsibleSection>
+
+ <CollapsibleSection
+ title="Test gaps"
+ hint={result.test_gaps.length || undefined}
+ >
{result.test_gaps.length > 0 ? (
<TestGapsList gaps={result.test_gaps} />
) : (
- <EmptyState title="No test gaps" description="Affected files have associated tests." />
+ <EmptyState
+ title="No file-level gaps identified"
+ description={
+ testAnalysisLimited
+ ? "Test analysis is limited; this empty list is not evidence that no tests are needed."
+ : "No additional file-level gap was identified. Use the typed recommendations and their basis above."
+ }
+ />
)}
</CollapsibleSection>
</div>
diff --git a/packages/vscode/README.md b/packages/vscode/README.md
index 4729d7e71..d8ecc883a 100644
--- a/packages/vscode/README.md
+++ b/packages/vscode/README.md
@@ -19,7 +19,7 @@ Click **Analyze Change Risk** in the Source Control view and get the full pictur
- A risk score for the change, with the exact factors that move it.
- **The riskiest files in your change**, ranked, so you know where to focus your own review first.
- **What is downstream**: the files that depend on what you touched.
-- **What you might have forgotten**: files that historically change together with yours but are untouched, and changed files with no associated test.
+- **What you might have forgotten**: files that historically change together with yours but are untouched, plus measured and inferred test recommendations with explicit analysis state.
- **Who should review it**, from ownership and history, with one-click copy for your PR.
While you edit, a quiet status-bar hint appears if you are missing a file that usually travels with your change. It never pops up, never interrupts, and is one click to dismiss or turn off.
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index bc03b84dd..25e487b4b 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -1,5 +1,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+} from "@testing-library/react";
import { App } from "./App";
import type { WebviewHost } from "../../runtime/rpc";
import type {
@@ -28,15 +34,33 @@ const REPORT: RiskRangeReport = {
classification: "Elevated",
fallback_band: null,
is_fix: false,
- features: { la: 120, ld: 30, nf: 6, nd: 2, ns: 1, entropy: 2.31, exp: null },
+ features: {
+ la: 120,
+ ld: 30,
+ nf: 6,
+ nd: 2,
+ ns: 1,
+ entropy: 2.31,
+ exp: null,
+ },
drivers: [
{ feature: "la", value: 120, contribution: 1.8, label: "Lines added" },
- { feature: "exp", value: null, contribution: -0.5, label: "Author experience" },
+ {
+ feature: "exp",
+ value: null,
+ contribution: -0.5,
+ label: "Author experience",
+ },
],
},
};
-const REPO: RepoInit = { id: "r1", name: "repo", headCommit: null, defaultBranch: "main" };
+const REPO: RepoInit = {
+ id: "r1",
+ name: "repo",
+ headCommit: null,
+ defaultBranch: "main",
+};
/** A clean tree: nothing changed, so no impact sections render. */
const CLEAN_IMPACT: ChangeImpactReport = {
@@ -56,8 +80,18 @@ const IMPACT: ChangeImpactReport = {
scope: "branch",
blast: {
direct_risks: [
- { path: "src/a.ts", risk_score: 0.3, temporal_hotspot: 0.1, centrality: 0.8 },
- { path: "src/b.ts", risk_score: 0.82, temporal_hotspot: 0.9, centrality: 0.1 },
+ {
+ path: "src/a.ts",
+ risk_score: 0.3,
+ temporal_hotspot: 0.1,
+ centrality: 0.8,
+ },
+ {
+ path: "src/b.ts",
+ risk_score: 0.82,
+ temporal_hotspot: 0.9,
+ centrality: 0.1,
+ },
],
transitive_affected: [{ path: "src/consumer.ts", depth: 1 }],
cochange_warnings: [
@@ -65,6 +99,69 @@ const IMPACT: ChangeImpactReport = {
],
recommended_reviewers: [],
test_gaps: ["src/b.ts"],
+ test_impact: {
+ recommendations: [
+ {
+ test_id: "src/a.test.ts::covers_a",
+ test_file: "src/a.test.ts",
+ repository_id: "r1",
+ repository: "repo",
+ basis: "measured",
+ bases: ["measured"],
+ source_files: ["src/a.ts"],
+ evidence: [
+ {
+ basis: "measured",
+ source_file: "src/a.ts",
+ via: "coverage-map",
+ source_format: "istanbul",
+ },
+ ],
+ },
+ ],
+ recommendations_total: 1,
+ recommendations_emitted: 1,
+ recommendations_truncated: false,
+ recommendations_omitted: 0,
+ recommendations_by_primary_basis: { measured: 1, inferred: 0 },
+ files: [],
+ files_total: 2,
+ files_without_measured_tests: ["src/b.ts"],
+ unknown_files: ["src/b.ts"],
+ coverage: {
+ status: "partial",
+ reason: "coverage_map_matches_only_part_of_change",
+ map_present: true,
+ pair_count: 1,
+ test_count: 1,
+ source_file_count: 1,
+ changed_files_total: 2,
+ changed_files_with_measured_tests: 1,
+ changed_files_without_measured_tests: 1,
+ ingested_at: null,
+ source_format: "istanbul",
+ freshness: {
+ status: "unknown",
+ reason: "coverage_or_index_commit_unavailable",
+ ingested_commit: null,
+ indexed_commit: null,
+ },
+ },
+ inference: {
+ status: "available",
+ reason: null,
+ changed_files_total: 2,
+ changed_files_with_candidates: 0,
+ candidates_before_dedup: 0,
+ },
+ analysis: {
+ status: "partial",
+ stale: false,
+ partial: true,
+ degraded: false,
+ basis_categories: ["measured"],
+ },
+ },
overall_risk_score: 5.6,
},
reviewers: [
@@ -92,7 +189,9 @@ function makeHost(
api: {
riskRange,
changeImpact,
- getSettings: vi.fn().mockResolvedValue({ "changeIntel.cochangeMinScore": 4 }),
+ getSettings: vi
+ .fn()
+ .mockResolvedValue({ "changeIntel.cochangeMinScore": 4 }),
} as unknown as WebviewHost["api"],
onInit: () => () => {},
onRefresh: () => () => {},
@@ -117,7 +216,14 @@ describe("risk App", () => {
it("leads with the repo-relative ranking and keeps the raw score secondary", async () => {
const riskRange = vi.fn().mockResolvedValue(REPORT);
- render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);
+ render(
+ <App
+ host={makeHost(riskRange)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
+ );
expect(await screen.findByText("Elevated")).toBeTruthy();
expect(screen.getByText("88th percentile")).toBeTruthy();
@@ -131,7 +237,14 @@ describe("risk App", () => {
it("refetches when Run again is clicked", async () => {
const riskRange = vi.fn().mockResolvedValue(REPORT);
- render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);
+ render(
+ <App
+ host={makeHost(riskRange)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
+ );
await screen.findByText("Elevated");
expect(riskRange).toHaveBeenCalledTimes(1);
@@ -144,15 +257,22 @@ describe("risk App", () => {
const riskRange = vi.fn().mockResolvedValue(REPORT);
const changeImpact = vi.fn().mockResolvedValue(IMPACT);
render(
- <App host={makeHost(riskRange, changeImpact)} repo={REPO} params={{}} refreshToken={0} />,
+ <App
+ host={makeHost(riskRange, changeImpact)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
);
expect(await screen.findByText("Downstream of your changes")).toBeTruthy();
// Paths render as split dir/name spans, so match on the file name.
expect(screen.getByText("consumer.ts")).toBeTruthy();
expect(screen.getByText("Usually changes together")).toBeTruthy();
- expect(screen.getByText("a.test.ts")).toBeTruthy();
- expect(screen.getByText("Changed without a test")).toBeTruthy();
+ expect(screen.getAllByText("a.test.ts").length).toBeGreaterThanOrEqual(1);
+ expect(screen.getByText("Test impact")).toBeTruthy();
+ expect(screen.getByText("measured · repo")).toBeTruthy();
+ expect(screen.getByText("no test evidence")).toBeTruthy();
expect(screen.getByText("Ada Lovelace")).toBeTruthy();
});
@@ -190,12 +310,18 @@ describe("risk App", () => {
/>,
);
- expect(await screen.findByText("Riskiest files in this change")).toBeTruthy();
+ expect(
+ await screen.findByText("Riskiest files in this change"),
+ ).toBeTruthy();
expect(screen.getByText("hotspot")).toBeTruthy();
- const bars = screen.getAllByTitle("Risk relative to the riskiest file in this change");
+ const bars = screen.getAllByTitle(
+ "Risk relative to the riskiest file in this change",
+ );
expect(bars).toHaveLength(2);
// Sorted riskiest first: b.ts (0.82) gets the full bar, a.ts a partial one.
- expect((bars[0]!.firstElementChild as HTMLElement).style.width).toBe("100%");
+ expect((bars[0]!.firstElementChild as HTMLElement).style.width).toBe(
+ "100%",
+ );
// b.ts also appears in the test-gap card; the riskiest row renders first.
fireEvent.click(screen.getAllByTitle("Open src/b.ts")[0]!);
@@ -208,12 +334,20 @@ describe("risk App", () => {
const scrollIntoView = vi.fn();
Element.prototype.scrollIntoView = scrollIntoView;
render(
- <App host={makeHost(riskRange, changeImpact)} repo={REPO} params={{}} refreshToken={0} />,
+ <App
+ host={makeHost(riskRange, changeImpact)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
);
- expect(await screen.findByText("may affect 1 downstream file")).toBeTruthy();
+ expect(
+ await screen.findByText("may affect 1 downstream file"),
+ ).toBeTruthy();
expect(screen.getByText("1 co-change partner untouched")).toBeTruthy();
- expect(screen.getByText("1 changed file has no associated test")).toBeTruthy();
+ expect(screen.getByText("test analysis partial")).toBeTruthy();
+ expect(screen.getByText("1 test recommendation")).toBeTruthy();
fireEvent.click(screen.getByText("may affect 1 downstream file"));
expect(scrollIntoView).toHaveBeenCalled();
@@ -221,17 +355,31 @@ describe("risk App", () => {
it("renders no verdict chips on a clean tree", async () => {
const riskRange = vi.fn().mockResolvedValue(REPORT);
- render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);
+ render(
+ <App
+ host={makeHost(riskRange)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
+ );
await screen.findByText("Elevated");
expect(screen.queryByText(/downstream file/)).toBeNull();
expect(screen.queryByText(/untouched/)).toBeNull();
- expect(screen.queryByText(/associated test/)).toBeNull();
+ expect(screen.queryByText(/test recommendation/)).toBeNull();
});
it("shows a clean-tree empty state when nothing changed", async () => {
const riskRange = vi.fn().mockResolvedValue(REPORT);
- render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);
+ render(
+ <App
+ host={makeHost(riskRange)}
+ repo={REPO}
+ params={{}}
+ refreshToken={0}
+ />,
+ );
expect(await screen.findByText("No pending changes")).toBeTruthy();
});
diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsx
index a2296cbd7..e044ce21f 100644
--- a/packages/vscode/webview/src/views/risk/App.tsx
+++ b/packages/vscode/webview/src/views/risk/App.tsx
@@ -74,7 +74,9 @@ const SECTION_IDS = {
} as const;
function scrollToSection(id: string) {
- document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
+ document
+ .getElementById(id)
+ ?.scrollIntoView({ behavior: "smooth", block: "start" });
}
/** Formats a contribution with an explicit sign (positive raises risk). */
@@ -118,7 +120,9 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {
.riskRange()
.then((r) => setReport(r))
.catch((err: unknown) =>
- setError(err instanceof Error ? err.message : "Could not score change risk."),
+ setError(
+ err instanceof Error ? err.message : "Could not score change risk.",
+ ),
)
.finally(() => setLoading(false));
// Impact is independent: a git-less workspace still shows the risk score.
@@ -149,8 +153,12 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {
<GitCompare className="h-4 w-4 shrink-0" />
<span className="truncate">
<code className="text-[var(--color-text-primary)]">{branch}</code>
- <span className="mx-1.5 text-[var(--color-text-tertiary)]">vs</span>
- <code className="text-[var(--color-text-primary)]">{base || "base"}</code>
+ <span className="mx-1.5 text-[var(--color-text-tertiary)]">
+ vs
+ </span>
+ <code className="text-[var(--color-text-primary)]">
+ {base || "base"}
+ </code>
</span>
</p>
</div>
@@ -283,9 +291,11 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {
<FixHistoryNote history={r.fix_history} />
<p className="mt-2.5 text-[var(--color-text-tertiary)]">
Diff-size score{" "}
- <strong className="font-semibold tabular-nums">{r.score.toFixed(1)}/10</strong> — how big
- and spread out the change is, not where it lands. Anchored to a corpus of single commits,
- so a range reads high by construction.
+ <strong className="font-semibold tabular-nums">
+ {r.score.toFixed(1)}/10
+ </strong>{" "}
+ — how big and spread out the change is, not where it lands. Anchored to
+ a corpus of single commits, so a range reads high by construction.
</p>
</PageLede>
);
@@ -296,23 +306,39 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {
* score cannot see. Renders nothing when no touched file has fix history, which
* is itself worth not padding out.
*/
-function FixHistoryNote({ history }: { history: RiskRangeReport["result"]["fix_history"] }) {
+function FixHistoryNote({
+ history,
+}: {
+ history: RiskRangeReport["result"]["fix_history"];
+}) {
if (!history.available) {
- return <p className="mt-2.5">Fix history unavailable — the git history walk failed.</p>;
+ return (
+ <p className="mt-2.5">
+ Fix history unavailable — the git history walk failed.
+ </p>
+ );
}
if (!history.files.length) return null;
const [worst] = history.files;
return (
<p className="mt-2.5">
These files have broken before:{" "}
- <strong className="font-semibold text-[var(--color-text-primary)]">{worst.path}</strong> has{" "}
- <strong className="font-semibold tabular-nums">{worst.fix_pressure.toFixed(1)}</strong>{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {worst.path}
+ </strong>{" "}
+ has{" "}
+ <strong className="font-semibold tabular-nums">
+ {worst.fix_pressure.toFixed(1)}
+ </strong>{" "}
recency-weighted prior fixes
- {history.files.length > 1 ? `, and ${history.files.length - 1} more do too` : ""}
+ {history.files.length > 1
+ ? `, and ${history.files.length - 1} more do too`
+ : ""}
{history.percentile != null ? (
<>
{" "}
- — {ordinal(history.percentile)} percentile of this repo&apos;s recent commits
+ — {ordinal(history.percentile)} percentile of this repo&apos;s recent
+ commits
</>
) : null}
.
@@ -333,11 +359,19 @@ function VerdictStrip({
// `changed.length === 0` matters as well as `blast`: the impact block below
// renders an empty state in that case, so a chip would scroll to an anchor
// that is not on the page. The two must bail on the same condition.
- if (!impact || !blast || impact.gitUnavailable || impact.changed.length === 0) return null;
+ if (!impact || !blast || impact.gitUnavailable || impact.changed.length === 0)
+ return null;
const downstream = blast.transitive_affected.length;
const cochanges = selectMissingCochanges(impact, cochangeFloor).length;
const gaps = blast.test_gaps.length;
+ const testImpact = blast.test_impact;
+ const testAnalysisUnavailable =
+ !testImpact ||
+ ["unavailable", "degraded"].includes(testImpact.coverage.status);
+ const testAnalysisLimited =
+ testAnalysisUnavailable ||
+ Boolean(testImpact?.analysis.partial || testImpact?.analysis.stale);
const chips: Array<{ id: string; label: string }> = [];
if (downstream > 0) {
@@ -352,13 +386,31 @@ function VerdictStrip({
label: `${cochanges} co-change partner${cochanges === 1 ? "" : "s"} untouched`,
});
}
- if (gaps > 0) {
+ if (testAnalysisUnavailable) {
+ chips.push({
+ id: SECTION_IDS.testGaps,
+ label: "test analysis unavailable",
+ });
+ } else if (testImpact.analysis.stale || testImpact.analysis.partial) {
+ chips.push({
+ id: SECTION_IDS.testGaps,
+ label: testImpact.analysis.stale
+ ? "test evidence stale"
+ : "test analysis partial",
+ });
+ }
+ if (testImpact && testImpact.recommendations_total > 0) {
+ chips.push({
+ id: SECTION_IDS.testGaps,
+ label: `${testImpact.recommendations_total} test recommendation${testImpact.recommendations_total === 1 ? "" : "s"}`,
+ });
+ } else if (!testAnalysisLimited && gaps > 0) {
chips.push({
id: SECTION_IDS.testGaps,
label:
gaps === 1
- ? "1 changed file has no associated test"
- : `${gaps} changed files have no associated test`,
+ ? "no test evidence found for 1 changed file"
+ : `no test evidence found for ${gaps} changed files`,
});
}
if (chips.length === 0) return null;
@@ -367,7 +419,7 @@ function VerdictStrip({
<div className="flex flex-wrap gap-2">
{chips.map((c) => (
<button
- key={c.id}
+ key={`${c.id}:${c.label}`}
type="button"
onClick={() => scrollToSection(c.id)}
className="inline-flex items-center rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-surface)]"
@@ -385,7 +437,10 @@ function RiskBreakdown({ report }: { report: RiskRangeReport }) {
const drivers = [...r.drivers].sort(
(a, b) => Math.abs(b.contribution) - Math.abs(a.contribution),
);
- const maxDriver = drivers.reduce((m, d) => Math.max(m, Math.abs(d.contribution)), 0);
+ const maxDriver = drivers.reduce(
+ (m, d) => Math.max(m, Math.abs(d.contribution)),
+ 0,
+ );
const featureRows = FEATURE_LABELS.filter(
([key]) => r.features[key] != null,
) as ReadonlyArray<readonly [string, string]>;
@@ -400,10 +455,18 @@ function RiskBreakdown({ report }: { report: RiskRangeReport }) {
<div className="flex flex-col gap-3">
{drivers.map((d) => {
const raises = d.contribution >= 0;
- const barColor = raises ? "var(--color-error)" : "var(--color-success)";
- const pct = maxDriver > 0 ? (Math.abs(d.contribution) / maxDriver) * 100 : 0;
+ const barColor = raises
+ ? "var(--color-error)"
+ : "var(--color-success)";
+ const pct =
+ maxDriver > 0
+ ? (Math.abs(d.contribution) / maxDriver) * 100
+ : 0;
return (
- <div key={d.feature} className="flex items-center gap-3 text-[15px]">
+ <div
+ key={d.feature}
+ className="flex items-center gap-3 text-[15px]"
+ >
<span className="w-40 shrink-0 truncate text-[var(--color-text-secondary)]">
{d.label}
</span>
@@ -437,7 +500,9 @@ function RiskBreakdown({ report }: { report: RiskRangeReport }) {
key={key}
className="flex items-baseline justify-between gap-3 border-b border-[var(--color-border-default)] py-2 last:border-b-0"
>
- <dt className="text-[15px] text-[var(--color-text-secondary)]">{label}</dt>
+ <dt className="text-[15px] text-[var(--color-text-secondary)]">
+ {label}
+ </dt>
<dd className="text-[15px] font-medium tabular-nums text-[var(--color-text-primary)]">
{formatFeatureValue(r.features[key] as number)}
</dd>
@@ -507,6 +572,23 @@ function ChangeImpact({
const downstream = blast?.transitive_affected ?? [];
const cochanges = selectMissingCochanges(impact, cochangeFloor);
const testGaps = blast?.test_gaps ?? [];
+ const testImpact = blast?.test_impact;
+ const testRecommendations = testImpact?.recommendations ?? [];
+ const testAnalysisUnavailable =
+ !testImpact ||
+ ["unavailable", "degraded"].includes(testImpact.coverage.status);
+ const testAnalysisLimited =
+ testAnalysisUnavailable ||
+ Boolean(testImpact?.analysis.partial || testImpact?.analysis.stale);
+ const testAnalysisHint = !testImpact
+ ? "This older server did not provide typed test-analysis state; an empty list does not mean no tests are needed."
+ : testImpact.analysis.stale
+ ? "Coverage evidence is stale; measured recommendations may not describe the indexed commit."
+ : testImpact.analysis.degraded
+ ? "Test analysis is degraded; an empty list does not mean no tests are needed."
+ : testImpact.analysis.partial
+ ? "Test analysis is partial; recommendations may not cover every evidence input."
+ : "Recommendations keep measured coverage evidence separate from structural inference.";
const reviewers = impact.reviewers;
const overall = blast?.overall_risk_score ?? null;
@@ -518,7 +600,8 @@ function ChangeImpact({
title="What this change touches"
action={
<span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {impact.changed.length} {scopeLabel} file{impact.changed.length === 1 ? "" : "s"}
+ {impact.changed.length} {scopeLabel} file
+ {impact.changed.length === 1 ? "" : "s"}
{overall != null && (
<>
{" · "}
@@ -539,7 +622,11 @@ function ChangeImpact({
hint="Per-file risk from history and structure. Start your review here."
>
{directRisks.slice(0, 10).map((f) => (
- <DirectRiskRow key={f.path} risk={f} onOpen={() => host.openFile(f.path)} />
+ <DirectRiskRow
+ key={f.path}
+ risk={f}
+ onOpen={() => host.openFile(f.path)}
+ />
))}
<MoreRow count={directRisks.length - 10} />
</ImpactBlock>
@@ -583,15 +670,41 @@ function ChangeImpact({
</ImpactBlock>
)}
- {testGaps.length > 0 && (
+ {(testGaps.length > 0 ||
+ testRecommendations.length > 0 ||
+ testAnalysisLimited) && (
<ImpactBlock
id={SECTION_IDS.testGaps}
icon={<TestTube className="h-4 w-4" />}
- title="Changed without a test"
- hint="These changed files have no associated test file."
+ title="Test impact"
+ hint={testAnalysisHint}
>
+ {testRecommendations.slice(0, 10).map((recommendation) => {
+ const path =
+ recommendation.test_file ?? recommendation.test_id.split("::")[0];
+ return (
+ <PathRow
+ key={`${recommendation.repository_id}:${recommendation.test_id}`}
+ path={path}
+ trailing={`${recommendation.basis} · ${recommendation.repository}`}
+ onOpen={() => host.openFile(path)}
+ />
+ );
+ })}
+ <MoreRow
+ count={
+ (testImpact?.recommendations_total ??
+ testRecommendations.length) -
+ Math.min(testRecommendations.length, 10)
+ }
+ />
{testGaps.slice(0, 8).map((p) => (
- <PathRow key={p} path={p} onOpen={() => host.openFile(p)} />
+ <PathRow
+ key={p}
+ path={p}
+ trailing="no test evidence"
+ onOpen={() => host.openFile(p)}
+ />
))}
<MoreRow count={testGaps.length - 8} />
</ImpactBlock>
@@ -653,7 +766,9 @@ function PathRow({
className="flex w-full items-center gap-2 rounded px-1.5 py-1 text-left text-[15px] transition-colors hover:bg-[var(--color-bg-surface)]"
>
<span className="min-w-0 flex-1 truncate">
- {dir && <span className="text-[var(--color-text-tertiary)]">{dir}</span>}
+ {dir && (
+ <span className="text-[var(--color-text-tertiary)]">{dir}</span>
+ )}
<span className="text-[var(--color-text-primary)]">{name}</span>
</span>
{trailing && (
@@ -666,7 +781,13 @@ function PathRow({
}
/** A clickable file row with a quiet relative risk bar and a hotspot marker. */
-function DirectRiskRow({ risk, onOpen }: { risk: RankedDirectRisk; onOpen: () => void }) {
+function DirectRiskRow({
+ risk,
+ onOpen,
+}: {
+ risk: RankedDirectRisk;
+ onOpen: () => void;
+}) {
const name = risk.path.split("/").pop() || risk.path;
const dir = risk.path.slice(0, risk.path.length - name.length);
const pct = Math.min(100, Math.max(0, risk.share * 100));
@@ -678,7 +799,9 @@ function DirectRiskRow({ risk, onOpen }: { risk: RankedDirectRisk; onOpen: () =>
className="flex w-full items-center gap-2 rounded px-1.5 py-1 text-left text-[15px] transition-colors hover:bg-[var(--color-bg-surface)]"
>
<span className="min-w-0 flex-1 truncate">
- {dir && <span className="text-[var(--color-text-tertiary)]">{dir}</span>}
+ {dir && (
+ <span className="text-[var(--color-text-tertiary)]">{dir}</span>
+ )}
<span className="text-[var(--color-text-primary)]">{name}</span>
</span>
{risk.hotspot && (
@@ -709,7 +832,9 @@ function DirectRiskRow({ risk, onOpen }: { risk: RankedDirectRisk; onOpen: () =>
function MoreRow({ count }: { count: number }) {
if (count <= 0) return null;
return (
- <p className="px-1.5 pt-1 text-xs text-[var(--color-text-tertiary)]">+{count} more</p>
+ <p className="px-1.5 pt-1 text-xs text-[var(--color-text-tertiary)]">
+ +{count} more
+ </p>
);
}
@@ -725,7 +850,10 @@ function Reviewers({
const text = top
.map((r) => (r.email ? `${r.name} <${r.email}>` : r.name))
.join(", ");
- host.copyText(`Suggested reviewers: ${text}`, "Reviewers copied to clipboard.");
+ host.copyText(
+ `Suggested reviewers: ${text}`,
+ "Reviewers copied to clipboard.",
+ );
};
const maxScore = top.reduce((m, r) => Math.max(m, r.score), 0);
@@ -758,7 +886,8 @@ function Reviewers({
{r.name}
</span>
<span className="shrink-0 text-xs text-[var(--color-text-tertiary)]">
- {r.recent_commits} recent commit{r.recent_commits === 1 ? "" : "s"}
+ {r.recent_commits} recent commit
+ {r.recent_commits === 1 ? "" : "s"}
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">
diff --git a/tests/fixtures/mcp/pr_test_impact.json b/tests/fixtures/mcp/pr_test_impact.json
new file mode 100644
index 000000000..d94565f08
--- /dev/null
+++ b/tests/fixtures/mcp/pr_test_impact.json
@@ -0,0 +1,45 @@
+{
+ "repositories": ["alpha", "beta"],
+ "changed_files": [
+ "src/measured.py",
+ "src/inferred.py",
+ "src/both.py",
+ "src/no_match.py",
+ "src/truncate.py",
+ "src/excluded.py"
+ ],
+ "unavailable_changed_files": ["src/unavailable.py"],
+ "excluded_paths": ["src/excluded.py", "tests/excluded/**"],
+ "coverage": [
+ {"test_id": "tests/test_measured.py::test_measured", "test_file": "tests/test_measured.py", "source_file": "src/measured.py"},
+ {"test_id": "tests/test_both.py::test_measured", "test_file": "tests/test_both.py", "source_file": "src/both.py"},
+ {"test_id": "tests/test_seed.py::test_seed", "test_file": "tests/test_seed.py", "source_file": "src/seed.py"},
+ {"test_id": "tests/test_truncate.py::test_00", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_01", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_02", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_03", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_04", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_05", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_06", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_07", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_08", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_09", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_10", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"},
+ {"test_id": "tests/test_truncate.py::test_11", "test_file": "tests/test_truncate.py", "source_file": "src/truncate.py"}
+ ],
+ "inferred": [
+ {"test_file": "tests/test_inferred.py", "source_file": "src/inferred.py"},
+ {"test_file": "tests/test_both_inferred.py", "source_file": "src/both.py"},
+ {"test_file": "tests/excluded/test_hidden.py", "source_file": "src/inferred.py"}
+ ],
+ "same_named": {
+ "test_id": "tests/test_shared.py::test_same_name",
+ "source_file": "src/shared.py"
+ },
+ "relationship_semantics": {
+ "dependency": {"source": "src/dependent.py", "target": "src/measured.py", "type": "imports"},
+ "co_change": {"source": "docs/history-only.md", "target": "src/measured.py", "type": "co_changes"},
+ "contract": {"provider_repo": "alpha", "consumer_repo": "beta", "type": "http"},
+ "structural_runtime_breakage_claim": false
+ }
+}
diff --git a/tests/unit/persistence/test_pr_blast_guarding_tests.py b/tests/unit/persistence/test_pr_blast_guarding_tests.py
index d6f147554..826a0dc2b 100644
--- a/tests/unit/persistence/test_pr_blast_guarding_tests.py
+++ b/tests/unit/persistence/test_pr_blast_guarding_tests.py
@@ -106,7 +106,12 @@ async def test_guarding_tests_map_empty_is_honest_unknown(async_session):
result = await analyzer._guarding_tests(["src/math.py"])
# No map -> "unknown", never an empty-because-untested claim.
- assert result == {"map_present": False, "basis": "none", "tests_to_run": [], "by_file": {}}
+ assert result["map_present"] is False
+ assert result["basis"] == "none"
+ assert result["tests_to_run"] == []
+ assert result["by_file"] == {}
+ assert result["coverage"]["status"] == "unavailable"
+ assert result["analysis"]["partial"] is True
async def test_guarding_tests_file_with_no_rows_omitted_but_map_present(async_session):
@@ -134,7 +139,11 @@ async def test_guarding_tests_empty_changed_set(async_session):
analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
result = await analyzer._guarding_tests([])
- assert result == {"map_present": False, "basis": "none", "tests_to_run": [], "by_file": {}}
+ assert result["map_present"] is False
+ assert result["basis"] == "none"
+ assert result["tests_to_run"] == []
+ assert result["by_file"] == {}
+ assert result["coverage"]["reason"] == "no_changed_files"
# ---------------------------------------------------------------------------
@@ -180,8 +189,8 @@ async def test_no_map_falls_back_to_the_graph_and_says_so(async_session):
assert result["by_file"] == {"src/math.py": ["tests/test_math.py"]}
-async def test_a_measured_map_is_never_diluted_by_the_graph(async_session):
- """Coverage answered, so the graph is not consulted at all."""
+async def test_measured_and_inferred_rows_remain_distinguishable(async_session):
+ """Both sources may answer, but the inferred row is never called measured."""
repo = await insert_repo(async_session)
await _seed_map(async_session, repo.id)
_graph(
@@ -192,10 +201,18 @@ async def test_a_measured_map_is_never_diluted_by_the_graph(async_session):
)
await async_session.commit()
- result = await PRBlastRadiusAnalyzer(async_session, repo.id)._guarding_tests(["src/math.py"])
+ analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
+ result = await analyzer._guarding_tests(["src/math.py"])
+ typed = await analyzer._test_impact(["src/math.py"])
assert result["basis"] == "measured"
- assert "tests/test_unrelated.py" not in result["tests_to_run"]
+ rows = {row["test_id"]: row for row in result["tests_to_run_with_basis"]}
+ assert rows["tests/test_math.py::test_add"]["basis"] == "measured"
+ assert rows["tests/test_math.py::test_sub"]["basis"] == "measured"
+ assert "tests/test_unrelated.py" not in rows
+ typed_rows = {row["test_id"]: row for row in typed["recommendations"]}
+ assert typed_rows["tests/test_unrelated.py"]["basis"] == "inferred"
+ assert typed_rows["tests/test_unrelated.py"]["bases"] == ["inferred"]
async def test_a_map_that_is_silent_about_this_file_still_asks_the_graph(async_session):
diff --git a/tests/unit/persistence/test_pr_test_impact_semantics.py b/tests/unit/persistence/test_pr_test_impact_semantics.py
new file mode 100644
index 000000000..cf91fa896
--- /dev/null
+++ b/tests/unit/persistence/test_pr_test_impact_semantics.py
@@ -0,0 +1,335 @@
+"""Sealed contract for PR test-impact evidence, availability, and identity."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.analysis.health.coverage import TestCoverage
+from repowise.core.analysis.test_impact import analyze_test_impact
+from repowise.core.exclusion import build_exclude_spec
+from repowise.core.persistence.crud import save_test_coverage
+from repowise.core.persistence.models import GraphEdge, GraphNode
+from tests.unit.persistence.helpers import insert_repo
+
+_FIXTURE = Path(__file__).parents[2] / "fixtures" / "mcp" / "pr_test_impact.json"
+
+
+def _fixture() -> dict:
+ return json.loads(_FIXTURE.read_text(encoding="utf-8"))
+
+
+async def _seed(session, repo_id: str, fixture: dict, *, with_coverage: bool = True) -> None:
+ if with_coverage:
+ await save_test_coverage(
+ session,
+ repo_id,
+ [
+ TestCoverage(
+ test_id=row["test_id"],
+ file_path=row["source_file"],
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file=row["test_file"],
+ )
+ for row in fixture["coverage"]
+ ],
+ source_format="coverage.py",
+ ingested_commit_sha="fixture-head",
+ )
+
+ paths = set(fixture["changed_files"] + fixture["unavailable_changed_files"])
+ paths.update(row["source_file"] for row in fixture["coverage"])
+ paths.update(row["test_file"] for row in fixture["coverage"])
+ paths.update(row["source_file"] for row in fixture["inferred"])
+ paths.update(row["test_file"] for row in fixture["inferred"])
+ relationship = fixture["relationship_semantics"]
+ paths.update(
+ [
+ relationship["dependency"]["source"],
+ relationship["dependency"]["target"],
+ relationship["co_change"]["source"],
+ ]
+ )
+ test_paths = {
+ *(row["test_file"] for row in fixture["coverage"]),
+ *(row["test_file"] for row in fixture["inferred"]),
+ }
+ for index, path in enumerate(sorted(paths)):
+ session.add(
+ GraphNode(
+ id=f"{repo_id}-node-{index}",
+ repository_id=repo_id,
+ node_id=path,
+ node_type="file",
+ is_test=path in test_paths,
+ )
+ )
+ for index, row in enumerate(fixture["inferred"]):
+ session.add(
+ GraphEdge(
+ id=f"{repo_id}-inferred-{index}",
+ repository_id=repo_id,
+ source_node_id=row["test_file"],
+ target_node_id=row["source_file"],
+ edge_type="imports",
+ )
+ )
+ session.add(
+ GraphEdge(
+ id=f"{repo_id}-structural",
+ repository_id=repo_id,
+ source_node_id=relationship["dependency"]["source"],
+ target_node_id=relationship["dependency"]["target"],
+ edge_type=relationship["dependency"]["type"],
+ )
+ )
+ session.add(
+ GraphEdge(
+ id=f"{repo_id}-historical",
+ repository_id=repo_id,
+ source_node_id=relationship["co_change"]["source"],
+ target_node_id=relationship["co_change"]["target"],
+ edge_type=relationship["co_change"]["type"],
+ )
+ )
+ await session.commit()
+
+
+async def test_sealed_population_retains_basis_availability_exclusions_and_totals(
+ async_session, tmp_path
+):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="alpha", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "exclude_patterns:\n - src/excluded.py\n - tests/excluded/**\n",
+ encoding="utf-8",
+ )
+
+ impact = await analyze_test_impact(
+ async_session,
+ repo.id,
+ fixture["changed_files"],
+ repository_alias="alpha",
+ exclude_spec=build_exclude_spec(tmp_path),
+ )
+
+ assert impact["files_total"] == 5
+ assert impact["recommendations_total"] == len(impact["recommendations"]) == 16
+ assert impact["recommendations_emitted"] == 16
+ assert impact["recommendations_truncated"] is False
+ assert impact["recommendations_omitted"] == 0
+ assert impact["recommendations_by_primary_basis"] == {"measured": 14, "inferred": 2}
+ assert {row["basis"] for row in impact["recommendations"]} == {"measured", "inferred"}
+ assert all(
+ row["repository"] == "alpha" and row["repository_id"] == repo.id
+ for row in impact["recommendations"]
+ )
+ assert all(row["basis"] in row["bases"] for row in impact["recommendations"])
+ assert all(
+ row["evidence"] and all("basis" in item for item in row["evidence"])
+ for row in impact["recommendations"]
+ )
+ assert all("excluded" not in row["test_id"] for row in impact["recommendations"])
+ assert "src/excluded.py" not in {row["source_file"] for row in impact["files"]}
+
+ both = next(row for row in impact["files"] if row["source_file"] == "src/both.py")
+ assert both["measured_tests"] == ["tests/test_both.py::test_measured"]
+ assert both["inferred_tests"] == ["tests/test_both_inferred.py"]
+ assert "src/no_match.py" in impact["files_without_measured_tests"]
+ assert "src/no_match.py" in impact["unknown_files"]
+ assert impact["coverage"]["status"] == "partial"
+ assert impact["coverage"]["freshness"]["status"] == "current"
+ assert impact["analysis"]["partial"] is True
+
+
+async def test_stale_coverage_is_explicit_even_when_it_has_matches(async_session):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="stale", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+ repo.head_commit = "newer-index-head"
+ await async_session.commit()
+
+ impact = await analyze_test_impact(
+ async_session,
+ repo.id,
+ ["src/measured.py"],
+ repository_alias="stale",
+ )
+
+ assert impact["coverage"]["status"] == "available"
+ assert impact["coverage"]["freshness"]["status"] == "stale"
+ assert impact["analysis"]["stale"] is True
+ assert impact["analysis"]["partial"] is True
+ assert impact["recommendations"][0]["basis"] == "measured"
+
+
+async def test_unavailable_coverage_is_not_an_empty_no_tests_claim(async_session):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="unavailable")
+ await _seed(async_session, repo.id, fixture, with_coverage=False)
+
+ impact = await analyze_test_impact(
+ async_session,
+ repo.id,
+ fixture["unavailable_changed_files"],
+ repository_alias="unavailable",
+ )
+
+ assert impact["recommendations"] == []
+ assert impact["recommendations_total"] == 0
+ assert impact["recommendations_by_primary_basis"] == {"measured": 0, "inferred": 0}
+ assert impact["coverage"]["status"] == "unavailable"
+ assert impact["coverage"]["reason"] == "no_per_test_coverage_map"
+ assert impact["unknown_files"] == fixture["unavailable_changed_files"]
+ assert impact["analysis"]["status"] == "partial"
+
+
+async def test_coverage_query_failure_is_explicitly_degraded(async_session, monkeypatch):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="degraded")
+ await _seed(async_session, repo.id, fixture, with_coverage=False)
+
+ async def _boom(*args, **kwargs):
+ raise RuntimeError("sealed coverage failure")
+
+ monkeypatch.setattr(
+ "repowise.core.persistence.crud.get_test_coverage_summary",
+ _boom,
+ )
+ impact = await analyze_test_impact(
+ async_session,
+ repo.id,
+ ["src/inferred.py"],
+ repository_alias="degraded",
+ )
+
+ assert impact["coverage"]["status"] == "degraded"
+ assert impact["analysis"]["status"] == "degraded"
+ assert impact["analysis"]["partial"] is True
+ assert impact["analysis"]["degraded"] is True
+ assert impact["recommendations"][0]["basis"] == "inferred"
+
+
+async def test_dedup_retains_measured_and_inferred_basis(async_session):
+ repo = await insert_repo(async_session, name="dual-basis")
+ await save_test_coverage(
+ async_session,
+ repo.id,
+ [
+ TestCoverage(
+ test_id="tests/test_same.py",
+ file_path="src/same.py",
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file="tests/test_same.py",
+ )
+ ],
+ source_format="coverage.py",
+ )
+ for index, (path, is_test) in enumerate((("src/same.py", False), ("tests/test_same.py", True))):
+ async_session.add(
+ GraphNode(
+ id=f"dual-basis-node-{index}",
+ repository_id=repo.id,
+ node_id=path,
+ node_type="file",
+ is_test=is_test,
+ )
+ )
+ async_session.add(
+ GraphEdge(
+ id="dual-basis-edge",
+ repository_id=repo.id,
+ source_node_id="tests/test_same.py",
+ target_node_id="src/same.py",
+ edge_type="imports",
+ )
+ )
+ await async_session.commit()
+
+ impact = await analyze_test_impact(async_session, repo.id, ["src/same.py"])
+
+ assert impact["recommendations_total"] == 1
+ assert impact["recommendations"][0]["basis"] == "measured"
+ assert impact["recommendations"][0]["bases"] == ["measured", "inferred"]
+ assert {row["basis"] for row in impact["recommendations"][0]["evidence"]} == {
+ "measured",
+ "inferred",
+ }
+ assert impact["analysis"]["basis_categories"] == ["measured", "inferred"]
+ assert impact["files"][0]["inferred_tests_total"] == len(impact["files"][0]["inferred_tests"])
+
+
+async def test_exclusion_uses_test_id_path_when_test_file_is_missing(async_session, tmp_path):
+ repo = await insert_repo(async_session, name="excluded-node-id")
+ await save_test_coverage(
+ async_session,
+ repo.id,
+ [
+ TestCoverage(
+ test_id="tests/excluded/test_hidden.py::test_hidden",
+ file_path="src/visible.py",
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file=None,
+ )
+ ],
+ source_format="coverage.py",
+ )
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "exclude_patterns:\n - tests/excluded/**\n",
+ encoding="utf-8",
+ )
+
+ impact = await analyze_test_impact(
+ async_session,
+ repo.id,
+ ["src/visible.py"],
+ exclude_spec=build_exclude_spec(tmp_path),
+ )
+
+ assert impact["recommendations"] == []
+ assert impact["recommendations_total"] == 0
+
+
+async def test_same_named_tests_keep_repository_identity(async_session):
+ fixture = _fixture()
+ alpha = await insert_repo(async_session, name="alpha-same", local_path="/tmp/alpha")
+ beta = await insert_repo(async_session, name="beta-same", local_path="/tmp/beta")
+ row = fixture["same_named"]
+ for repo in (alpha, beta):
+ await save_test_coverage(
+ async_session,
+ repo.id,
+ [
+ TestCoverage(
+ test_id=row["test_id"],
+ file_path=row["source_file"],
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file="tests/test_shared.py",
+ )
+ ],
+ source_format="coverage.py",
+ )
+ await async_session.commit()
+
+ alpha_impact = await analyze_test_impact(
+ async_session, alpha.id, [row["source_file"]], repository_alias="alpha"
+ )
+ beta_impact = await analyze_test_impact(
+ async_session, beta.id, [row["source_file"]], repository_alias="beta"
+ )
+
+ assert alpha_impact["recommendations"][0]["test_id"] == row["test_id"]
+ assert beta_impact["recommendations"][0]["test_id"] == row["test_id"]
+ assert alpha_impact["recommendations"][0]["repository"] == "alpha"
+ assert beta_impact["recommendations"][0]["repository"] == "beta"
+ assert (
+ alpha_impact["recommendations"][0]["repository_id"]
+ != beta_impact["recommendations"][0]["repository_id"]
+ )
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index ce8c2e70b..cfe1ad890 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -28,6 +28,7 @@ def _create_test_app():
from fastapi.responses import JSONResponse
from repowise.server.routers import (
+ blast_radius,
c4,
code_health,
costs,
@@ -82,6 +83,7 @@ def _create_test_app():
app.include_router(jobs.router)
app.include_router(symbols.router)
app.include_router(graph.router)
+ app.include_router(blast_radius.router)
app.include_router(c4.router)
app.include_router(meta.router)
app.include_router(webhooks.router)
diff --git a/tests/unit/server/mcp/test_pr_test_impact_semantics.py b/tests/unit/server/mcp/test_pr_test_impact_semantics.py
new file mode 100644
index 000000000..8a62dd84d
--- /dev/null
+++ b/tests/unit/server/mcp/test_pr_test_impact_semantics.py
@@ -0,0 +1,121 @@
+"""Exact external PR payload over the sealed test-impact fixture."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+_FIXTURE = Path(__file__).parents[3] / "fixtures" / "mcp" / "pr_test_impact.json"
+
+
+async def test_sealed_pr_payload_is_directive_first_typed_and_count_exact(setup_mcp, session):
+ from repowise.core.analysis.health.coverage import TestCoverage
+ from repowise.core.persistence.crud import save_test_coverage
+ from repowise.core.persistence.models import GraphEdge, GraphNode
+ from repowise.server.mcp_server import get_risk
+
+ fixture = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ changed = [path for path in fixture["changed_files"] if path != "src/excluded.py"]
+ paths = set(changed)
+ paths.update(row["source_file"] for row in fixture["coverage"])
+ paths.update(row["test_file"] for row in fixture["coverage"])
+ paths.update(
+ row["source_file"] for row in fixture["inferred"] if "excluded" not in row["test_file"]
+ )
+ paths.update(
+ row["test_file"] for row in fixture["inferred"] if "excluded" not in row["test_file"]
+ )
+ relation = fixture["relationship_semantics"]
+ paths.update([relation["dependency"]["source"], relation["co_change"]["source"]])
+ test_paths = {path for path in paths if path.startswith("tests/")}
+ for index, path in enumerate(sorted(paths)):
+ session.add(
+ GraphNode(
+ id=f"sealed-impact-node-{index}",
+ repository_id=setup_mcp,
+ node_id=path,
+ node_type="file",
+ is_test=path in test_paths,
+ )
+ )
+ for index, row in enumerate(
+ item for item in fixture["inferred"] if "excluded" not in item["test_file"]
+ ):
+ session.add(
+ GraphEdge(
+ id=f"sealed-impact-inferred-{index}",
+ repository_id=setup_mcp,
+ source_node_id=row["test_file"],
+ target_node_id=row["source_file"],
+ edge_type="imports",
+ )
+ )
+ session.add(
+ GraphEdge(
+ id="sealed-impact-structural",
+ repository_id=setup_mcp,
+ source_node_id=relation["dependency"]["source"],
+ target_node_id=relation["dependency"]["target"],
+ edge_type=relation["dependency"]["type"],
+ )
+ )
+ session.add(
+ GraphEdge(
+ id="sealed-impact-historical",
+ repository_id=setup_mcp,
+ source_node_id=relation["co_change"]["source"],
+ target_node_id=relation["co_change"]["target"],
+ edge_type=relation["co_change"]["type"],
+ )
+ )
+ await save_test_coverage(
+ session,
+ setup_mcp,
+ [
+ TestCoverage(
+ test_id=row["test_id"],
+ file_path=row["source_file"],
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file=row["test_file"],
+ )
+ for row in fixture["coverage"]
+ ],
+ source_format="coverage.py",
+ )
+ await session.flush()
+
+ payload = await get_risk(["src/measured.py"], changed_files=changed, include=["graph"])
+ external = json.loads(json.dumps(payload))
+ directive = external["directive"]
+ full = external["pr_blast_radius"]["test_impact"]
+
+ assert next(iter(external)) == "directive"
+ assert full["recommendations_total"] == len(full["recommendations"]) == 16
+ assert full["recommendations_by_primary_basis"] == {"measured": 14, "inferred": 2}
+ assert full["recommendations_truncated"] is False
+ assert directive["test_recommendations_total"] == 16
+ assert directive["test_recommendations_emitted"] == len(directive["test_recommendations"]) == 10
+ assert directive["test_recommendations_truncated"] is True
+ assert directive["test_recommendations_omitted"] == 6
+ assert directive["tests_to_run"] == [
+ row["test_id"] for row in directive["test_recommendations"]
+ ]
+ assert directive["tests_to_run_total"] == 14
+ assert directive["tests_to_run_basis"] == "measured"
+ assert directive["missing_tests"] == ["src/no_match.py"]
+ assert directive["missing_tests_total"] == directive["missing_tests_emitted"] == 1
+ assert directive["missing_tests_truncated"] is False
+ assert directive["missing_tests_omitted"] == 0
+ assert directive["files_without_measured_tests"] == ["src/inferred.py", "src/no_match.py"]
+ assert all(
+ row["basis"] in {"measured", "inferred"} for row in directive["test_recommendations"]
+ )
+ assert all(row["evidence"] for row in directive["test_recommendations"])
+ assert all(row["repository_id"] == setup_mcp for row in full["recommendations"])
+ assert relation["dependency"]["source"] in directive["may_break"]
+ assert relation["co_change"]["source"] not in directive["may_break"]
+ assert external["_meta"]["contract_version"]
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 4dfc655a4..187419f44 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -45,9 +45,7 @@ async def test_get_risk_single_target(setup_mcp):
async def test_get_risk_multiple_targets(setup_mcp):
from repowise.server.mcp_server import get_risk
- result = await get_risk(
- ["src/auth/service.py", "src/db/models.py"], include=["churn"]
- )
+ result = await get_risk(["src/auth/service.py", "src/db/models.py"], include=["churn"])
targets = result["targets"]
assert len(targets) == 2
assert "global_hotspots" in result
@@ -160,7 +158,16 @@ async def test_get_risk_pr_directive_surfaces_coverage_backed_tests_to_run(setup
]
# The graph also reaches this file, and must not dilute a measured answer.
assert directive["tests_to_run_basis"] == "measured"
- assert "coverage-backed test(s) guard the change" in directive["summary"]
+ assert "2 measured" in directive["summary"]
+ assert {row["basis"] for row in directive["test_recommendations"]} == {
+ "measured",
+ "inferred",
+ }
+ assert all(
+ "basis" in evidence
+ for row in directive["test_recommendations"]
+ for evidence in row["evidence"]
+ )
@pytest.mark.asyncio
@@ -202,6 +209,9 @@ async def test_get_risk_tests_to_run_ranks_by_files_reached(setup_mcp, session):
"tests/test_zeta.py::test_both",
"tests/test_alpha.py::test_one",
]
+ assert "tests/test_service.py" in {
+ row["test_id"] for row in result["directive"]["test_recommendations"]
+ }
class TestRankTestsByReach:
@@ -254,6 +264,42 @@ async def test_get_risk_pr_directive_names_no_tests_when_nothing_reaches(setup_m
assert directive["tests_to_run"] == []
assert directive["tests_to_run_basis"] == "none"
+ assert directive["missing_tests"] == []
+ assert directive["coverage_analysis"]["status"] == "unavailable"
+ assert "missing_tests is withheld" in directive["summary"]
+
+
+async def test_get_risk_pr_payload_serializes_directive_first(setup_mcp):
+ """The exact external JSON order is actionable before any dossier."""
+ import json
+
+ from repowise.server.mcp_server import get_risk
+
+ payload = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])
+ external = json.loads(json.dumps(payload))
+
+ assert next(iter(payload)) == "directive"
+ assert next(iter(external)) == "directive"
+ assert list(external).index("directive") < list(external).index("targets")
+
+
+async def test_get_risk_test_compatibility_projection_cannot_contradict_typed_rows(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ directive = (await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"]))[
+ "directive"
+ ]
+ recommendations = directive["test_recommendations"]
+
+ assert directive["tests_to_run"] == [row["test_id"] for row in recommendations]
+ assert directive["tests_to_run_total"] == directive["test_recommendations_total"]
+ assert directive["tests_to_run_emitted"] == len(recommendations)
+ assert directive["test_recommendations_emitted"] == len(recommendations)
+ assert all(row["basis"] in {"measured", "inferred"} for row in recommendations)
+ assert all(row["basis"] in row["bases"] for row in recommendations)
+ assert all(row["repository_id"] == "repo1" for row in recommendations)
# ---- _classify_risk_type small-team calibration (issue #361) ---------------
@@ -439,6 +485,54 @@ async def test_get_risk_directive_points_at_the_full_run_list_when_capped(setup_
directive = result["directive"]
assert len(directive["tests_to_run"]) == _TESTS_TO_RUN_LIMIT
- assert f"Showing {_TESTS_TO_RUN_LIMIT} of {over_cap}" in directive["summary"]
- assert "pr_blast_radius.guarding_tests" in directive["summary"]
+ assert f"Showing {_TESTS_TO_RUN_LIMIT} of {over_cap + 1}" in directive["summary"]
+ assert directive["tests_to_run_total"] == over_cap
+ assert directive["tests_to_run_emitted"] == _TESTS_TO_RUN_LIMIT
+ assert directive["tests_to_run_truncated"] is True
+ assert directive["test_recommendations_total"] == over_cap + 1
+ assert "response omission marker" in directive["summary"]
assert len(result["pr_blast_radius"]["guarding_tests"]["tests_to_run"]) == over_cap
+
+
+async def test_missing_tests_totals_use_full_precap_changed_file_population(setup_mcp, session):
+ from repowise.core.analysis.health.coverage import TestCoverage
+ from repowise.core.persistence.crud import save_test_coverage
+ from repowise.core.persistence.models import GraphNode
+ from repowise.server.mcp_server import get_risk
+
+ changed = [f"src/sealed_gap_{index}.py" for index in range(5)]
+ for index, path in enumerate(changed):
+ session.add(
+ GraphNode(
+ id=f"sealed-gap-{index}",
+ repository_id=setup_mcp,
+ node_id=path,
+ node_type="file",
+ is_test=False,
+ )
+ )
+ await save_test_coverage(
+ session,
+ setup_mcp,
+ [
+ TestCoverage(
+ test_id="tests/test_seed.py::test_seed",
+ file_path="src/coverage_seed.py",
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file="tests/test_seed.py",
+ )
+ ],
+ source_format="coverage.py",
+ )
+ await session.flush()
+
+ result = await get_risk(["src/auth/service.py"], changed_files=changed)
+ directive = result["directive"]
+
+ assert directive["missing_tests"] == changed[:3]
+ assert directive["missing_tests_total"] == 5
+ assert directive["missing_tests_emitted"] == 3
+ assert directive["missing_tests_truncated"] is True
+ assert directive["missing_tests_omitted"] == 2
diff --git a/tests/unit/server/mcp/test_risk_relationship_semantics.py b/tests/unit/server/mcp/test_risk_relationship_semantics.py
index bd0141eec..062214ffa 100644
--- a/tests/unit/server/mcp/test_risk_relationship_semantics.py
+++ b/tests/unit/server/mcp/test_risk_relationship_semantics.py
@@ -14,6 +14,7 @@ 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"
+_TEST_IMPACT_FIXTURE = Path(__file__).parents[3] / "fixtures" / "mcp" / "pr_test_impact.json"
class _SealedRegistry:
@@ -186,6 +187,9 @@ async def test_co_change_is_historical_only_and_mixed_evidence_stays_separate(
@pytest.mark.asyncio
async def test_typed_consumers_do_not_absorb_dependents_or_co_changes(relationship_payload):
card = _card(relationship_payload)
+ test_impact_contract = json.loads(_TEST_IMPACT_FIXTURE.read_text(encoding="utf-8"))[
+ "relationship_semantics"
+ ]["contract"]
assert card["consumers_total"] == 2
assert card["consumers_emitted"] == len(card["consumers"]) == 2
@@ -195,6 +199,9 @@ async def test_typed_consumers_do_not_absorb_dependents_or_co_changes(relationsh
assert consumer["consumer_repository"] == "beta"
assert consumer["direction"] == "provider_to_consumer"
assert consumer["contract_type"] == "http"
+ assert consumer["provider_repository"] == test_impact_contract["provider_repo"]
+ assert consumer["consumer_repository"] == test_impact_contract["consumer_repo"]
+ assert consumer["contract_type"] == test_impact_contract["type"]
assert consumer["evidence_kind"] == "contract"
assert {row["consumer_file"] for row in card["consumers"]} == {
"src/auth/service.py",
diff --git a/tests/unit/server/test_pr_test_impact_rest.py b/tests/unit/server/test_pr_test_impact_rest.py
new file mode 100644
index 000000000..64b5bb9d1
--- /dev/null
+++ b/tests/unit/server/test_pr_test_impact_rest.py
@@ -0,0 +1,107 @@
+"""REST blast-radius exposes the canonical test-impact population unchanged."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.analysis.health.coverage import TestCoverage
+from repowise.core.analysis.pr_blast import PRBlastRadiusAnalyzer
+from repowise.core.persistence.crud import save_test_coverage
+from repowise.core.persistence.models import GraphEdge, GraphNode
+from tests.unit.server.conftest import create_test_repo
+
+_FIXTURE = Path(__file__).parents[2] / "fixtures" / "mcp" / "pr_test_impact.json"
+
+
+async def test_rest_and_shared_analyzer_return_identical_test_impact(client, session, tmp_path):
+ fixture = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ repo = await create_test_repo(client, tmp_path)
+ repo_id = repo["id"]
+ changed = fixture["changed_files"]
+ config_dir = Path(repo["local_path"]) / ".repowise"
+ config_dir.mkdir()
+ (config_dir / "config.yaml").write_text(
+ "exclude_patterns:\n - src/excluded.py\n - tests/excluded/**\n",
+ encoding="utf-8",
+ )
+
+ paths = set(changed)
+ paths.update(row["source_file"] for row in fixture["coverage"])
+ paths.update(row["test_file"] for row in fixture["coverage"])
+ paths.update(row["source_file"] for row in fixture["inferred"])
+ paths.update(row["test_file"] for row in fixture["inferred"])
+ test_paths = {path for path in paths if path.startswith("tests/")}
+ for index, path in enumerate(sorted(paths)):
+ session.add(
+ GraphNode(
+ id=f"rest-impact-node-{index}",
+ repository_id=repo_id,
+ node_id=path,
+ node_type="file",
+ is_test=path in test_paths,
+ )
+ )
+ for index, row in enumerate(fixture["inferred"]):
+ session.add(
+ GraphEdge(
+ id=f"rest-impact-edge-{index}",
+ repository_id=repo_id,
+ source_node_id=row["test_file"],
+ target_node_id=row["source_file"],
+ edge_type="imports",
+ )
+ )
+ await save_test_coverage(
+ session,
+ repo_id,
+ [
+ TestCoverage(
+ test_id=row["test_id"],
+ file_path=row["source_file"],
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file=row["test_file"],
+ )
+ for row in fixture["coverage"]
+ ],
+ source_format="coverage.py",
+ )
+ await session.commit()
+
+ internal = await PRBlastRadiusAnalyzer(session, repo_id).analyze_files(changed)
+ response = await client.post(
+ f"/api/repos/{repo_id}/blast-radius",
+ json={"changed_files": changed, "max_depth": 3},
+ )
+
+ assert response.status_code == 200
+ external = response.json()
+ assert external["test_impact"] == internal["test_impact"]
+ assert external["test_impact"]["recommendations_total"] == 16
+ assert external["test_impact"]["recommendations_emitted"] == len(
+ external["test_impact"]["recommendations"]
+ )
+ assert "src/excluded.py" not in {row["source_file"] for row in external["test_impact"]["files"]}
+ assert all(
+ "excluded" not in row["test_id"] for row in external["test_impact"]["recommendations"]
+ )
+ assert all("basis" in row for row in external["test_impact"]["recommendations"])
+
+
+async def test_openapi_exposes_typed_test_impact_contract(client):
+ schema = (await client.get("/openapi.json")).json()["components"]["schemas"]
+
+ blast = schema["BlastRadiusResponse"]
+ assert blast["properties"]["test_impact"]["$ref"].endswith("/TestImpactResponse")
+ recommendation = schema["TestRecommendation"]
+ assert recommendation["required"] == [
+ "test_id",
+ "repository_id",
+ "repository",
+ "basis",
+ "bases",
+ "source_files",
+ "evidence",
+ ]
+ assert recommendation["properties"]["basis"]["enum"] == ["measured", "inferred"]