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.

feat(mcp): gate get_risk's unactionable fields, fix its false test gaps (#1883)

Raghav Chamadiya02365f437440
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index c103a02e6..247dd82fb 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -444,11 +444,14 @@ Modification risk assessment for files or a set of changed files.
|-----------|------|----------|-------------|
| `targets` | list[string] | No | File paths to assess |
| `changed_files` | list[string] | No | Files in a PR/changeset for blast radius analysis; passing this switches the response into PR-directive mode |
+| `include` | list[string] | No | Opt-in blocks: `graph` (`impact_surface`, `direct_risks`), `churn` (`change_magnitude`, `risk_type`, `change_pattern`) |
| `repo` | string | No | *(workspace only)* Target repo alias |
**Returns:** Per-file `hotspot_score` (0-1 churn percentile), `health_score` (0-10), hotspot status, dependent count, co-change partners (each with a recency-decayed `weight`, not an integer count), blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.
-> **Scales.** 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.
+> **Opt-in blocks.** `impact_surface` and `direct_risks` are pagerank floats an agent cannot rank; `change_magnitude`, `risk_type` and `change_pattern` restate numbers printed beside them. All five are computed regardless and feed `risk_summary`; `include` only decides whether they ship. `global_hotspots` accompanies a multi-target call only, being ambient orientation that a single named file does not need; it ranks by fix history the same way `defect_profile` does.
+
+> **Scales.** `overall_risk_score` (in `pr_blast_radius`, with an `overall_risk_score_measures` note beside it) reads where the change lands. It is not comparable to `get_change_risk.score`, which is also 0-10 and reads the shape of the diff. Ratios derived from ownership or percentile columns are 0-1 (`hotspot_score`, `owner_pct`, `recent_owner_pct`); coverage and gap fields are 0-100 (`coverage_pct`, `branch_coverage_pct`, `share_of_repo_gap_pct`, `change_entropy_pct`, `churn_percentile`). The `_pct` suffix alone does not tell you which — check this table. Every emitted float is rounded to 4 significant digits.
When `changed_files` is passed, the response leads with a `directive` block. Its core lists are the local blast radius: `will_break` (production files that depend on the diff and are likely to break), `will_break_tests` (test files impacted the same way, kept separate so a burst of broken tests doesn't crowd production impact out of the capped list), `missing_cochanges` (historical co-changers absent from the diff), `missing_tests` (changed files without test coverage), and `tests_to_run` (the positive complement of `missing_tests`: the tests that exercise the changed files, as pytest-runnable arguments). Read `tests_to_run_basis` beside it, because the ids alone do not say where they came from: `measured` means the per-test coverage map proves those tests execute the changed files; `inferred` means the import graph shows those test *files* reaching the change, which is a candidate list rather than proof and needs no coverage ingest; `none` means neither source knows of a test, which is unknown and not "untested". The two are never mixed in one list. In workspace mode that directive also carries the cross-repo fallout of the changed repo:
@@ -465,6 +468,7 @@ When `changed_files` is passed, the response leads with a `directive` block. Its
```
get_risk(targets=["src/auth/middleware.ts"])
get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])
+get_risk(targets=["src/auth/middleware.ts"], include=["graph", "churn"])
```
---
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index c2229c692..b80385990 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -57,7 +57,9 @@ _PRIORITY_LEAD = {
#: ``_base_dep_count`` is bookkeeping the tool uses to rebuild ``risk_summary``
#: after enrichment. ``impact_surface`` is the transitive dependent set, the one
#: genuinely unbounded block, and its own summary counts survive in
-#: ``risk_summary`` and ``dependents_count``.
+#: ``risk_summary`` and ``dependents_count``. It is opt-in on the tool now and
+#: this command does not ask for it; the entry stays so that a caller passing a
+#: hand-built payload gets the same projection.
_DROPPED_TARGET_KEYS = ("_base_dep_count", "impact_surface")
@@ -117,6 +119,8 @@ def _target_risk(
return get_risk(
targets=list(targets),
changed_files=list(changed_files) or None,
+ # _render_target_risk prints risk_type and change_magnitude.
+ include=["churn"],
)
payload = _ta.run(repo, _factory, "get_risk")
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.py
index eba05d40f..42c41f904 100644
--- a/packages/core/src/repowise/core/analysis/pr_blast.py
+++ b/packages/core/src/repowise/core/analysis/pr_blast.py
@@ -40,6 +40,45 @@ def rank_tests_by_reach(by_file: Mapping[str, Iterable[str]]) -> list[str]:
return sorted(reach, key=lambda t: (-reach[t], t))
+#: Prefixes that name a module for its slot in a dispatch table rather than for
+#: its subject, so its tests are named after the subject alone: ``tool_dead_code``
+#: is tested by ``test_dead_code``, not ``test_tool_dead_code``.
+_ROLE_PREFIXES = ("tool_", "get_")
+
+#: Below this, a stripped stem is too generic to be evidence of anything.
+_MIN_STEM_LENGTH = 3
+
+
+def test_name_stems(base: str) -> list[tuple[str, bool]]:
+ """Stems a test file for ``base`` could be named after, each with whether the
+ match has to be exact.
+
+ The full stem keeps the historical substring match, which absorbs suffixes
+ like ``test_parser_edge_cases``. A stripped stem is shorter and so collides
+ far more easily (``tool_repos`` -> ``repos``, a prefix of ``repository``),
+ and clearing a gap on a coincidence is the one error that costs a reader.
+ """
+ stems = [(base, False)]
+ for prefix in _ROLE_PREFIXES:
+ stripped = base[len(prefix) :]
+ if base.startswith(prefix) and len(stripped) >= _MIN_STEM_LENGTH:
+ stems.append((stripped, True))
+ return stems
+
+
+def _names_a_test_for(stem: str, ext: str, test_path: str, exact: bool) -> bool:
+ """Whether ``test_path`` follows a naming convention for ``stem``."""
+ if exact:
+ named = os.path.splitext(os.path.basename(test_path))[0]
+ return named in (f"test_{stem}", f"{stem}_test", f"{stem}.spec")
+ return (
+ f"test_{stem}" in test_path
+ or f"{stem}_test" in test_path
+ or f"{stem}.spec.{ext}" in test_path
+ or f"{stem}.spec." in test_path
+ )
+
+
class PRBlastRadiusAnalyzer:
"""Compute blast radius for a proposed PR given its changed files."""
@@ -294,7 +333,8 @@ class PRBlastRadiusAnalyzer:
Used only as this floor; nothing downstream reads a coverage figure
off it.
3. Otherwise the filename pattern (test_<name>, <name>_test,
- <name>.spec.*) - an honest "unknown", never asserted as untested.
+ <name>.spec.*), tried against every stem in ``test_name_stems`` - an
+ honest "unknown", never asserted as untested.
Test files themselves are excluded; they don't need their own tests.
"""
@@ -346,12 +386,8 @@ class PRBlastRadiusAnalyzer:
base = os.path.splitext(os.path.basename(path))[0]
ext = os.path.splitext(path)[1].lstrip(".")
has_test = any(
- (
- f"test_{base}" in tp
- or f"{base}_test" in tp
- or f"{base}.spec.{ext}" in tp
- or f"{base}.spec." in tp
- )
+ _names_a_test_for(stem, ext, tp, exact)
+ for stem, exact in test_name_stems(base)
for tp in test_paths
)
if not has_test:
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 7df4bb411..ffd794c19 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
@@ -86,10 +86,10 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
"rationale comments. Call before a refactor or a pattern divergence.",
),
"get_risk": (
- "get_risk(targets, changed_files?)",
- "What history says about touching these files. PR mode (`changed_files`) "
- "leads with a `directive`: read `will_break` / `missing_cochanges` / "
- "`missing_tests` / `tests_to_run` first.",
+ "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 `will_break` "
+ "/ `missing_cochanges` / `missing_tests` / `tests_to_run`.",
),
"get_change_risk": (
"get_change_risk(revspec, extensions?, exclude_patterns?)",
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 632faee54..d8a4ef3ac 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
@@ -53,6 +53,13 @@ _WILL_BREAK_TESTS_LIMIT = 3
#: the overflow and the full per-file map live in pr_blast_radius.guarding_tests.
_TESTS_TO_RUN_LIMIT = 10
+#: get_risk and get_change_risk both render 0-10 and measure unrelated things.
+#: Whichever an agent reads first, this says the other is not the same scale.
+_OVERALL_SCORE_MEASURES = (
+ "where the change lands: centrality of the changed files and how far it "
+ "reaches; not comparable to get_change_risk.score, which measures diff shape"
+)
+
def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], int]:
"""Breaking-change half of the PR directive: incompatible provider changes.
@@ -235,6 +242,8 @@ def _trim_blast_lists(
f"pr_blast_radius.{key} beyond cap={cap} ({len(value) - cap} dropped)",
value[cap:],
)
+ if trimmed_blast.get("overall_risk_score") is not None:
+ trimmed_blast["overall_risk_score_measures"] = _OVERALL_SCORE_MEASURES
return trimmed_blast
@@ -374,7 +383,8 @@ def _build_pr_directive(
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]
- if len(all_tests_to_run) > _TESTS_TO_RUN_LIMIT:
+ capped = len(all_tests_to_run) > _TESTS_TO_RUN_LIMIT
+ if 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)",
@@ -391,6 +401,14 @@ def _build_pr_directive(
f" {len(all_tests_to_run)} test file(s) reach the change per the import graph "
f"(inferred, not coverage-proven) - run these first."
)
+ 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.
+ 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."
+ )
gov_count = len(governance_risk)
gov_suffix = f" {gov_count} governance risk(s) detected." if gov_count > 0 else ""
@@ -449,7 +467,6 @@ def _build_pr_directive(
"conformance_violations": conformance_violations,
"dependency_cycles": dependency_cycles,
"governance_risk": governance_risk,
- "overall_risk_score": trimmed_blast.get("overall_risk_score"),
"summary": (
f"PR touches {len(changed_files)} file(s). "
f"~{len(will_break)} downstream file(s) likely affected, "
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 4c3902a24..c393d82bb 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
@@ -21,8 +21,10 @@ from repowise.server.mcp_server._helpers import (
_get_repo,
_resolve_repo_context,
_unsupported_repo_all,
+ attach_ignored_arguments,
filter_path_list,
filter_rows_by_attr,
+ resolve_enum_argument,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
@@ -39,11 +41,36 @@ _SHED_ORDER: tuple[str, ...] = (
)
+#: Fields an agent cannot rank or act on: uncalibrated pagerank floats, and
+#: labels derived from numbers already printed beside them. Computed either way
+#: (``risk_summary`` reads them); ``include`` only decides whether they ship.
+_TARGET_CARD_INCLUDES: dict[str, tuple[str, ...]] = {
+ "graph": ("impact_surface",),
+ "churn": ("change_magnitude", "risk_type", "change_pattern"),
+}
+_BLAST_INCLUDES: dict[str, tuple[str, ...]] = {"graph": ("direct_risks",)}
+_INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | frozenset(_BLAST_INCLUDES)
+
+
+def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:
+ """Strip the opt-in fields no ``include`` key asked for."""
+ cards = list(response.get("targets", {}).values())
+ blast = response.get("pr_blast_radius") or {}
+ for source, keys_by_block in ((cards, _TARGET_CARD_INCLUDES), ([blast], _BLAST_INCLUDES)):
+ for block, keys in keys_by_block.items():
+ if block in include:
+ continue
+ for holder in source:
+ for key in keys:
+ holder.pop(key, None)
+
+
@mcp.tool()
async def get_risk(
targets: list[str],
repo: str | None = None,
changed_files: list[str] | None = None,
+ include: list[str] | None = None,
) -> dict:
"""What history says about touching these files — bug fixes, churn, owners.
@@ -62,7 +89,7 @@ async def get_risk(
for sustained recent fix pressure, and top_symbols. Read top_symbols as
"mostly here" rather than exact — symbol spans are current-tree while each
fix's line ranges are numbered on its own parent commit. Nothing names the
- commit that introduced a bug. global_hotspots ranks the same way.
+ commit that introduced a bug.
episodes counts the dated records bound to a target — what happened here and
why, evidenced by a commit or a filesystem fact. It appears only when there
@@ -73,9 +100,16 @@ async def get_risk(
targets: file paths to assess.
repo: usually omitted.
changed_files: PR-changed files for blast-radius mode.
+ include: opt-in blocks - "graph", "churn".
"""
if repo == "all":
return _unsupported_repo_all("get_risk")
+ ignored: list[dict] = []
+ include_set = {
+ block
+ for block in (include or [])
+ if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)
+ }
ctx = await _resolve_repo_context(repo)
exclude_spec = _get_exclude_spec(ctx.path)
targets = filter_path_list(targets, exclude_spec)
@@ -223,15 +257,17 @@ async def get_risk(
test_paths,
ctx.alias,
)
- else:
- # Standard per-file risk request (no diff) — keep global hotspots as
- # ambient awareness. Cheap (≤5 entries) and useful for orientation.
+ 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.
response["global_hotspots"] = global_hotspots
response["_meta"] = _build_meta(
repository=repository,
targets=[*targets, *(changed_files or [])] if targets or changed_files else None,
)
+ _drop_opt_in_blocks(response, include_set)
+ attach_ignored_arguments(response, ignored)
fit_to_budget(response, _SHED_ORDER, collector)
collector.attach(response)
return response
diff --git a/tests/integration/test_mcp.py b/tests/integration/test_mcp.py
index 397c14107..59b93e1b0 100644
--- a/tests/integration/test_mcp.py
+++ b/tests/integration/test_mcp.py
@@ -392,7 +392,7 @@ async def test_mcp_git_intelligence_flow(mcp_env):
assert t["last_change"]["days_ago"] == 443
# Risk assessment
- risk = await get_risk(["src/auth/login.py"])
+ risk = await get_risk(["src/auth/login.py", "src/auth/jwt.py"])
t = risk["targets"]["src/auth/login.py"]
assert t["hotspot_score"] == 0.95
assert len(t["co_change_partners"]) == 1
diff --git a/tests/unit/persistence/test_test_gap_graph_floor.py b/tests/unit/persistence/test_test_gap_graph_floor.py
index 749675da7..458b2c426 100644
--- a/tests/unit/persistence/test_test_gap_graph_floor.py
+++ b/tests/unit/persistence/test_test_gap_graph_floor.py
@@ -97,3 +97,59 @@ async def test_a_co_change_edge_does_not_clear_a_gap(async_session):
analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
assert await analyzer._find_test_gaps(["src/lonely.py"]) == ["src/lonely.py"]
assert await _check_test_gap(async_session, repo.id, "src/lonely.py") is True
+
+
+async def test_a_dispatch_named_module_is_not_a_gap_when_its_test_drops_the_prefix(
+ async_session,
+):
+ """``tool_dead_code.py`` is tested by ``test_dead_code.py``, and the graph
+ cannot say so: the test imports it through a package re-export and the
+ barrel dispatches on by name. The filename fallback is the only signal left,
+ so it has to try the stem the test is actually named for."""
+ repo = await _seed(
+ async_session,
+ [],
+ [
+ ("tests/test_dead_code.py", True),
+ ("tests/test_risk.py", True),
+ ("src/mcp/tool_dead_code.py", False),
+ ("src/mcp/get_risk.py", False),
+ ],
+ )
+ analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
+ assert await analyzer._find_test_gaps(["src/mcp/tool_dead_code.py", "src/mcp/get_risk.py"]) == []
+
+
+async def test_stripping_the_prefix_does_not_clear_an_unrelated_file(async_session):
+ """Widening the evidence must not lower the bar to "some test exists"."""
+ repo = await _seed(
+ async_session,
+ [],
+ [("tests/test_dead_code.py", True), ("src/mcp/tool_search.py", False)],
+ )
+ analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
+ assert await analyzer._find_test_gaps(["src/mcp/tool_search.py"]) == ["src/mcp/tool_search.py"]
+
+
+def test_a_stripped_stem_too_short_to_mean_anything_is_not_offered():
+ """``get_id.py`` must not be cleared by every ``test_identity.py`` around."""
+ from repowise.core.analysis.pr_blast import test_name_stems
+
+ assert test_name_stems("tool_dead_code") == [("tool_dead_code", False), ("dead_code", True)]
+ assert test_name_stems("get_id") == [("get_id", False)]
+ assert test_name_stems("service") == [("service", False)]
+
+
+async def test_a_stripped_stem_does_not_match_a_longer_word_it_prefixes(async_session):
+ """``tool_repos`` strips to ``repos``, which is a prefix of ``repository``.
+
+ The full stem keeps its substring match; a stripped one has to be named
+ exactly, or widening the evidence would quietly become "some test exists".
+ """
+ repo = await _seed(
+ async_session,
+ [],
+ [("tests/test_repository_head_commit.py", True), ("src/mcp/tool_repos.py", False)],
+ )
+ analyzer = PRBlastRadiusAnalyzer(async_session, repo.id)
+ assert await analyzer._find_test_gaps(["src/mcp/tool_repos.py"]) == ["src/mcp/tool_repos.py"]
diff --git a/tests/unit/server/mcp/test_fix_history_coherence.py b/tests/unit/server/mcp/test_fix_history_coherence.py
index 4bf147386..d535ef55d 100644
--- a/tests/unit/server/mcp/test_fix_history_coherence.py
+++ b/tests/unit/server/mcp/test_fix_history_coherence.py
@@ -55,7 +55,7 @@ async def test_global_hotspots_surfaces_a_bug_magnet_that_is_not_a_churn_hotspot
await _add_bug_magnet(session, repo_id, "src/quiet/breaks_a_lot.py", fixes=6, days=10)
- result = await get_risk(["src/auth/service.py"])
+ result = await get_risk(["src/auth/service.py", "src/db/models.py"])
listed = {h["file_path"]: h for h in result["global_hotspots"]}
assert "src/quiet/breaks_a_lot.py" in listed
@@ -73,7 +73,7 @@ async def test_global_hotspots_ranks_fix_history_ahead_of_churn(setup_mcp, sessi
# models.py is in the fixture with no fix history; target something else so
# both candidates are eligible for the list.
- result = await get_risk(["src/auth/middleware.py"])
+ result = await get_risk(["src/auth/middleware.py", "src/db/models.py"])
paths = [h["file_path"] for h in result["global_hotspots"]]
assert paths, "expected an attention list"
@@ -85,7 +85,7 @@ async def test_global_hotspots_stays_silent_on_files_without_fix_history(setup_m
"""A repo with no fix data pays nothing: no keys, not zeroed keys."""
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/auth/middleware.py"])
+ result = await get_risk(["src/auth/middleware.py", "src/db/models.py"])
for entry in result["global_hotspots"]:
assert "fix_count" not in entry
assert "bug_magnet" not in entry
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 5d0653d8c..a1cd28b14 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -13,7 +13,7 @@ import pytest
async def test_get_risk_single_target(setup_mcp):
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/auth/service.py"])
+ result = await get_risk(["src/auth/service.py"], include=["graph", "churn"])
targets = result["targets"]
assert "src/auth/service.py" in targets
t = targets["src/auth/service.py"]
@@ -45,7 +45,9 @@ 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"])
+ 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
@@ -59,7 +61,7 @@ async def test_get_risk_multiple_targets(setup_mcp):
async def test_get_risk_global_hotspots_exclude_targets(setup_mcp):
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/auth/service.py"])
+ result = await get_risk(["src/auth/service.py", "src/db/models.py"])
# service.py is a hotspot but should NOT appear in global_hotspots
for h in result["global_hotspots"]:
assert h["file_path"] != "src/auth/service.py"
@@ -69,7 +71,7 @@ async def test_get_risk_global_hotspots_exclude_targets(setup_mcp):
async def test_get_risk_no_git_metadata(setup_mcp):
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/auth/middleware.py"])
+ result = await get_risk(["src/auth/middleware.py"], include=["graph", "churn"])
t = result["targets"]["src/auth/middleware.py"]
assert t["hotspot_score"] == 0.0 # No git metadata for this file
assert t["trend"] == "unknown"
@@ -83,7 +85,7 @@ async def test_get_risk_no_git_metadata(setup_mcp):
async def test_get_risk_stable_file(setup_mcp):
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/db/models.py"])
+ result = await get_risk(["src/db/models.py"], include=["churn"])
t = result["targets"]["src/db/models.py"]
# 0 commits in 30d and 90d → stable
assert t["trend"] == "stable"
@@ -339,3 +341,98 @@ async def test_test_gap_uses_health_filename_heuristic(session, repo_id):
)
await session.flush()
assert await _check_test_gap(session, repo_id, "src/my_module.py") is False
+
+
+async def test_get_risk_omits_global_hotspots_for_a_single_target(setup_mcp):
+ """Ambient orientation earns its place across targets, not on one named file."""
+ from repowise.server.mcp_server import get_risk
+
+ assert "global_hotspots" not in await get_risk(["src/auth/service.py"])
+ assert "global_hotspots" in await get_risk(["src/auth/service.py", "src/db/models.py"])
+
+
+async def test_get_risk_gates_the_fields_an_agent_cannot_act_on(setup_mcp):
+ """graph and churn blocks ship only when include asks for them."""
+ from repowise.server.mcp_server import get_risk
+
+ default = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])
+ card = default["targets"]["src/auth/service.py"]
+ for key in ("impact_surface", "change_magnitude", "risk_type", "change_pattern"):
+ assert key not in card
+ assert "direct_risks" not in default["pr_blast_radius"]
+ # The blocks that answer a question stay unconditional.
+ for key in ("co_change_partners", "risk_summary"):
+ assert key in card
+
+ graph = await get_risk(
+ ["src/auth/service.py"], changed_files=["src/auth/service.py"], include=["graph"]
+ )
+ assert "impact_surface" in graph["targets"]["src/auth/service.py"]
+ assert "direct_risks" in graph["pr_blast_radius"]
+ assert "change_magnitude" not in graph["targets"]["src/auth/service.py"]
+
+ churn = await get_risk(["src/auth/service.py"], include=["churn"])
+ churn_card = churn["targets"]["src/auth/service.py"]
+ assert {"change_magnitude", "risk_type", "change_pattern"} <= set(churn_card)
+ assert "impact_surface" not in churn_card
+
+
+async def test_get_risk_names_an_unknown_include_rather_than_applying_it(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"], include=["graph", "nonsense"])
+ assert "impact_surface" in result["targets"]["src/auth/service.py"]
+ assert result["ignored_arguments"] == [
+ {"argument": "include", "values": ["nonsense"], "valid": ["churn", "graph"]}
+ ]
+
+
+async def test_get_risk_directive_does_not_copy_the_analyzer_score(setup_mcp):
+ """overall_risk_score lives in pr_blast_radius, with a note on its scale."""
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])
+
+ assert "overall_risk_score" not in result["directive"]
+ blast = result["pr_blast_radius"]
+ assert "overall_risk_score" in blast
+ assert "get_change_risk.score" in blast["overall_risk_score_measures"]
+
+
+async def test_get_risk_directive_points_at_the_full_run_list_when_capped(setup_mcp, session):
+ """A capped tests_to_run says where the uncapped copy is."""
+ from repowise.core.analysis.health.coverage import TestCoverage
+ from repowise.core.persistence.crud import save_test_coverage
+ from repowise.server.mcp_server import get_risk
+ from repowise.server.mcp_server.tool_risk.directives import _TESTS_TO_RUN_LIMIT
+
+ over_cap = _TESTS_TO_RUN_LIMIT + 3
+ await save_test_coverage(
+ session,
+ "repo1",
+ [
+ TestCoverage(
+ test_id=f"tests/test_{i}.py::test_it",
+ file_path="src/auth/service.py",
+ covered_lines=[1],
+ source_format="coverage.py",
+ test_file=f"tests/test_{i}.py",
+ )
+ for i in range(over_cap)
+ ],
+ source_format="coverage.py",
+ )
+ await session.flush()
+
+ result = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])
+ 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 len(result["pr_blast_radius"]["guarding_tests"]["tests_to_run"]) == over_cap
diff --git a/tests/unit/server/test_mcp_decision_graph.py b/tests/unit/server/test_mcp_decision_graph.py
index 34c3bdef9..346966c82 100644
--- a/tests/unit/server/test_mcp_decision_graph.py
+++ b/tests/unit/server/test_mcp_decision_graph.py
@@ -594,7 +594,7 @@ async def test_get_risk_no_changed_files_no_governance_risk(setup_mcp_decisions)
"""Without changed_files (non-PR mode), directive is absent and no governance_risk."""
from repowise.server.mcp_server import get_risk
- result = await get_risk(["src/auth/service.py"])
+ result = await get_risk(["src/auth/service.py", "src/db/models.py"])
# No directive in standard mode
assert "directive" not in result
assert "global_hotspots" in result