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(change-risk): line-level impacted tests in get_change_risk (#903)

Raghav Chamadiyaf43b37bab3c7
diff --git a/README.md b/README.md
index 4e5340862..955f474b3 100644
--- a/README.md
+++ b/README.md
@@ -487,7 +487,7 @@ diverges from live `.git/HEAD`.
| `get_symbol("file.py::Name")` | Raw source bytes for one indexed symbol with exact line bounds, cheaper and safer than `Read` + offset math. |
| `search_codebase(query, kind?)` | Semantic search over the wiki, filterable by `kind` (implementation / test / config / doc), tagging each result's `search_method`. |
| `get_risk(targets, changed_files?)` | Hotspot scores, dependents, co-change partners, ownership, test gaps, security signals. Pass `changed_files` for PR mode → a `directive` block (`will_break`, `missing_cochanges`, `missing_tests`, `tests_to_run`, `governance_risk`). |
-| `get_change_risk(revspec, extensions?)` | Pre-merge defect score for a whole commit or `base..head` range from the shape of the diff (Kamei-style JIT metrics), ranked as a `risk_percentile` against recent commits. Scores the change; `get_risk` scores the indexed files it touches. |
+| `get_change_risk(revspec, extensions?)` | Pre-merge defect score for a whole commit or `base..head` range from the shape of the diff (Kamei-style JIT metrics), ranked as a `risk_percentile` against recent commits. Also returns `impacted_tests`: the tests the per-test coverage map proves execute the change's changed *lines*, plus honest missing-test buckets. Scores the change; `get_risk` scores the indexed files it touches. |
| `get_why(query?, targets?)` | Architectural decision records, status, evidence spans, and the supersession **lineage chain**. Falls back to git archaeology when no ADRs exist. |
| `get_dead_code(...)` | Unreachable code by confidence tier with cleanup-impact estimates; cross-repo consumer detection in workspace mode. |
| `get_health(targets?, include?)` | Marker scores per file across three signals (defect · maintainability · performance). Dashboard mode → KPIs + lowest-scoring files + module rollup; targeted mode → per-file findings. Self-check before a PR via `include`: `accuracy` (does the score find the bugs), `signals` (per-file churn / owners / prior defects), `churn_complexity`, a dimension name to filter findings, plus `coverage`, `trend`, and `refactoring` → **structured, graph-aware refactoring plans** (split groups, move target, cut edges + blast radius), not template strings. |
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index d0c24fc30..3e484d8ad 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -356,6 +356,17 @@ repo-relative `risk_percentile`, `review_priority`, and `classification`.
Use the percentile and review priority for triage; the raw score is secondary
context when no repository baseline is available.
+It also returns `impacted_tests`: the tests the per-test coverage map proves
+execute the change's changed *lines* (line-precise, so a narrower set than
+`get_risk`'s file-level `tests_to_run`), capped at ten with `total` and
+`truncated` reporting any overflow. Its `missing_tests` buckets flag
+`untested_changes` (covered file, uncovered change), `stale_test_candidates`
+(covered lines whose guarding test file is absent from the diff), `covered`, and
+`no_coverage_data` (files absent from the map). When no map is ingested,
+`status` is `no_map` and the change is reported as unknown ("run the full
+suite"), never as untested. Build the map with `coverage run --contexts=test`
+followed by `repowise coverage add`.
+
**When to use:** Before merging a commit or PR range, especially when you need
to assess the diff itself rather than the risk of an already-indexed file.
diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
index 6a2830092..2ac407aee 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
@@ -12,9 +12,36 @@ import subprocess
import pathspec
-from .features import GIT_TIMEOUT_SECONDS, features_from_file_changes
+from .features import GIT_TIMEOUT_SECONDS, _git, features_from_file_changes
from .model import score_change
+# Process-wide memo for the 200-commit baseline walk, which is the dominant cost
+# of a default get_change_risk call and is identical for every change scored
+# against the same repo state. Keyed on the *resolved anchor sha* (not the ref
+# name) so a new commit on HEAD busts the entry, plus every other input that
+# changes the sample (sample size, filters, the self-excluded ref).
+_BASELINE_CACHE: dict[tuple, list[float]] = {}
+# Crude bound so a long-lived MCP server that scores many distinct changes does
+# not grow the memo without limit. On overflow the whole cache is dropped
+# (correctness is unaffected; the next call just recomputes). Upgrade to an LRU
+# only if profiling shows the drop-all churn matters.
+_BASELINE_CACHE_MAX = 256
+
+
+def clear_baseline_cache() -> None:
+ """Drop all memoized baseline samples (test isolation / manual reset)."""
+ _BASELINE_CACHE.clear()
+
+
+def _resolve_anchor_sha(repo_path: str, anchor: str) -> str | None:
+ """Resolve *anchor* to a full sha for cache keying, or None if it cannot be.
+
+ check=False: a bad anchor is not fatal here - it just means we skip caching
+ and let :func:`baseline_scores` compute (and degrade) as it normally would.
+ """
+ sha = _git(["rev-parse", "--verify", "--quiet", anchor], repo_path, check=False).strip()
+ return sha or None
+
def baseline_scores(
repo_path: str,
@@ -78,3 +105,34 @@ def baseline_scores(
feats = features_from_file_changes(changes, exp=None)
scores.append(score_change(feats).score)
return scores
+
+
+def baseline_scores_cached(
+ repo_path: str,
+ anchor: str,
+ limit: int,
+ extensions: tuple[str, ...],
+ excluded_ref: str,
+ exclude_patterns: tuple[str, ...] = (),
+) -> list[float]:
+ """Memoized :func:`baseline_scores`, keyed on the resolved anchor sha.
+
+ Same result as :func:`baseline_scores` for the same inputs; it just skips the
+ 200-commit git walk when an identical sample was already computed this
+ process. The anchor is resolved to a sha so ``HEAD`` (or a branch ref) busts
+ the entry as soon as a new commit lands. When the anchor cannot be resolved
+ the call falls through to an uncached computation.
+ """
+ sha = _resolve_anchor_sha(repo_path, anchor)
+ if sha is None:
+ return baseline_scores(
+ repo_path, anchor, limit, extensions, excluded_ref, exclude_patterns
+ )
+ key = (repo_path, sha, limit, extensions, excluded_ref, exclude_patterns)
+ if key in _BASELINE_CACHE:
+ return _BASELINE_CACHE[key]
+ scores = baseline_scores(repo_path, anchor, limit, extensions, excluded_ref, exclude_patterns)
+ if len(_BASELINE_CACHE) >= _BASELINE_CACHE_MAX:
+ _BASELINE_CACHE.clear()
+ _BASELINE_CACHE[key] = scores
+ return scores
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index 3d9e4a4cc..ad248a05a 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -6,7 +6,7 @@ import subprocess
from dataclasses import dataclass, replace
from pathlib import Path
-from .baseline import baseline_scores
+from .baseline import baseline_scores_cached
from .features import (
GIT_TIMEOUT_SECONDS,
ChangeFeatures,
@@ -93,7 +93,7 @@ def score_live_change(
priority: str | None = None
baseline_sample_size = 0
if baseline:
- scores = baseline_scores(
+ scores = baseline_scores_cached(
repo_path,
anchor,
baseline,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 50b7d58de..da8bc2af4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -5,12 +5,28 @@ from __future__ import annotations
import asyncio
import subprocess
import time
+from typing import Any
-from repowise.core.analysis.change_risk import change_risk_payload, score_live_change
+import pathspec
+
+from repowise.core.analysis.change_risk import (
+ change_risk_payload,
+ normalize_extensions,
+ score_live_change,
+)
from repowise.core.registry import mcp_tool_registry as mcp
-from repowise.server.mcp_server._helpers import _resolve_repo_context, _unsupported_repo_all
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._meta import build_meta as _build_meta
+#: Cap on the line-precise impacted-test list, matching the get_risk directive's
+#: ``tests_to_run`` cap so both surfaces stay glanceable. ``total`` and
+#: ``truncated`` report the overflow rather than silently dropping it.
+_IMPACTED_TESTS_LIMIT = 10
+
@mcp.tool()
async def get_change_risk(
@@ -30,11 +46,14 @@ async def get_change_risk(
Prefer ``risk_percentile`` as the indicator of change risk: it ranks this
change against sampled recent commits in the same repository. Summarize it
with ``review_priority`` and ``classification``. ``score``, ``probability``,
- and ``level`` are secondary corpus-calibrated context; use them as the
- fallback only when ``risk_percentile`` is unavailable.
- ``baseline_sample_size`` is the number of filtered recent commits used to
- calculate ``risk_percentile`` (normally 200); a smaller sample makes the
- percentile less representative of the repository's usual change risk.
+ and ``level`` are secondary corpus-calibrated context, the fallback only
+ when ``risk_percentile`` is unavailable.
+
+ ``impacted_tests`` names the tests the per-test coverage map proves execute
+ the change's changed *lines* (line-precise, narrower than get_risk's
+ file-level ``tests_to_run``), with ``missing_tests`` buckets for changed
+ lines no test covers. Its ``status`` is ``no_map`` (unknown, run the full
+ suite), never "untested", when no map is ingested.
Args:
revspec: Commit or ``base..head`` range to score. Defaults to ``HEAD``.
@@ -69,6 +88,16 @@ async def get_change_risk(
f"No counted file changes in {revspec!r} "
"(check the revspec, extensions, or exclusion filters)."
)
+ # Line-precise impacted tests over the SAME file universe the score counted
+ # (its extensions + riskignore + request excludes), so the two never
+ # disagree about which files the change touches.
+ payload["impacted_tests"] = await _impacted_tests_block(
+ ctx,
+ str(ctx.path),
+ revspec,
+ normalize_extensions(tuple(extensions or ())),
+ result.riskignore_excludes + result.request_excludes,
+ )
# source: live_git marks that this response is computed from the working
# checkout's git, not the index, so index freshness does not apply to it.
payload["_meta"] = _build_meta(
@@ -76,3 +105,162 @@ async def get_change_risk(
extra={"source": "live_git"},
)
return payload
+
+
+def _normalize_revspec(revspec: str) -> str:
+ """Mirror ``score_live_change``'s three-dot handling for ``changed_lines``.
+
+ ``changed_lines`` verifies each side of a ``base..head`` range as a ref, so a
+ three-dot ``base...head`` (whose head parses as ``.head``) would fail its
+ ref check. Strip the extra dot to the two-dot form the scorer already uses.
+ """
+ if ".." in revspec:
+ base, _, head = revspec.partition("..")
+ head = head.lstrip(".") or "HEAD"
+ return f"{base}..{head}"
+ return revspec
+
+
+def _filter_changed(
+ changed: dict[str, set[int]],
+ extensions: tuple[str, ...],
+ exclude_patterns: tuple[str, ...],
+) -> dict[str, set[int]]:
+ """Restrict changed-line files to the score's counted universe.
+
+ ``changed_lines`` applies no suffix/exclude filtering, so without this a
+ change scored ``nf == 0`` under an extension filter could still surface
+ impacted tests for the filtered-out files. Uses the same ``endswith`` +
+ gitwildmatch rules as the numstat accumulator.
+ """
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
+ out: dict[str, set[int]] = {}
+ for path, lines in changed.items():
+ if extensions and not path.endswith(extensions):
+ continue
+ if spec.match_file(path):
+ continue
+ out[path] = lines
+ return out
+
+
+def _empty_impacted(status: str, summary: str) -> dict[str, Any]:
+ """Uniform impacted-tests block for the degraded (no tests to name) paths."""
+ return {
+ "status": status,
+ "map_present": False,
+ "tests": [],
+ "total": 0,
+ "truncated": False,
+ "missing_tests": {
+ "untested_changes": [],
+ "stale_test_candidates": [],
+ "covered": [],
+ "no_coverage_data": [],
+ },
+ "summary": summary,
+ }
+
+
+def _serialize_missing(report: Any) -> dict[str, Any]:
+ """Render the detect_missing_tests dataclass buckets as JSON-ready dicts."""
+ return {
+ "untested_changes": [
+ {
+ "source_file": u.source_file,
+ "uncovered_lines": u.uncovered_lines,
+ "changed_line_count": u.changed_line_count,
+ }
+ for u in report.untested_changes
+ ],
+ "stale_test_candidates": [
+ {
+ "source_file": s.source_file,
+ "covering_test_files": s.covering_test_files,
+ "covering_test_ids_without_file": s.covering_test_ids_without_file,
+ }
+ for s in report.stale_test_candidates
+ ],
+ "covered": list(report.covered),
+ # ``no_data`` is "file not in the map" = unknown, never "untested".
+ "no_coverage_data": list(report.no_data),
+ }
+
+
+async def _impacted_tests_block(
+ ctx: Any,
+ repo_path: str,
+ revspec: str,
+ extensions: tuple[str, ...],
+ exclude_patterns: tuple[str, ...],
+) -> dict[str, Any]:
+ """Line-precise impacted tests + honest missing-test buckets for the change.
+
+ Built on the same core functions the CLI (``repowise impacted-tests``) and
+ get_risk's guarding-tests path use - ``changed_lines`` -> ``tests_covering``
+ / ``detect_missing_tests`` - so the answer is coverage-grounded. The CLI's
+ filename-pattern guess is deliberately omitted: an agent cannot tell a guess
+ from real coverage, and ``no_coverage_data`` already reports those files
+ honestly as "unknown, run the suite". Degrades to a ``status`` string rather
+ than raising, so it never fails the surrounding score.
+ """
+ from repowise.core.analysis.changed_lines import changed_lines
+ from repowise.core.analysis.missing_test_signal import detect_missing_tests
+ from repowise.core.persistence.crud import tests_covering
+ from repowise.core.persistence.database import get_session
+
+ session_factory = getattr(ctx, "session_factory", None)
+ if session_factory is None:
+ return _empty_impacted("no_index", "No index; run `repowise init` to enable impacted tests.")
+
+ try:
+ changed, _label = await asyncio.to_thread(
+ changed_lines, repo_path, _normalize_revspec(revspec)
+ )
+ except ValueError as exc:
+ return _empty_impacted("unknown", f"Could not read changed lines: {exc}")
+ except (subprocess.SubprocessError, OSError):
+ return _empty_impacted("unknown", "Could not read changed lines from git.")
+
+ changed = _filter_changed(changed, extensions, exclude_patterns)
+ if not changed:
+ return _empty_impacted(
+ "no_source_line_changes", "No changed source lines to map to tests."
+ )
+
+ try:
+ async with get_session(session_factory) as session:
+ repo_id = (await _get_repo(session)).id
+ report = await detect_missing_tests(session, repo_id, changed)
+ if report.map_empty:
+ return _empty_impacted(
+ "no_map",
+ "No per-test coverage map ingested; run the full suite. Build the map "
+ "with `coverage run --contexts=test` then `repowise coverage add`.",
+ )
+ all_ids: set[str] = set()
+ for source_file, lines in changed.items():
+ for row in await tests_covering(session, repo_id, source_file, lines=lines):
+ all_ids.add(row["test_id"])
+ except LookupError:
+ return _empty_impacted("no_index", "No indexed repository; run `repowise init`.")
+
+ tests = sorted(all_ids)
+ total = len(tests)
+ return {
+ "status": "map_present",
+ "map_present": True,
+ "tests": tests[:_IMPACTED_TESTS_LIMIT],
+ "total": total,
+ "truncated": total > _IMPACTED_TESTS_LIMIT,
+ "missing_tests": _serialize_missing(report),
+ "summary": (
+ f"{total} test(s) cover the changed lines"
+ + (
+ f"; showing first {_IMPACTED_TESTS_LIMIT}"
+ if total > _IMPACTED_TESTS_LIMIT
+ else ""
+ )
+ + "."
+ ),
+ }
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
index 24166087b..8d40703ca 100644
--- a/tests/unit/analysis/test_change_risk.py
+++ b/tests/unit/analysis/test_change_risk.py
@@ -318,3 +318,70 @@ def test_score_live_change_below_min_baseline_yields_no_percentile(git_repo: Pat
assert result.baseline_sample_size < 8
assert result.percentile is None
assert result.priority is None
+
+
+def test_baseline_cache_hits_on_second_call_and_busts_on_new_commit(
+ git_repo: Path, monkeypatch
+) -> None:
+ # The 200-commit baseline walk is the dominant cost of a default call and is
+ # identical for the same repo state, so it is memoized on the resolved anchor
+ # sha. Give the repo enough history to actually build a percentile.
+ from repowise.core.analysis.change_risk import baseline
+
+ for i in range(10):
+ _commit(git_repo, {f"src/f{i}.py": f"x = {i}\n"}, f"feat: file {i}", author="Dev")
+
+ baseline.clear_baseline_cache()
+ calls = {"n": 0}
+ real = baseline.baseline_scores
+
+ def _counting(*args, **kwargs):
+ calls["n"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(baseline, "baseline_scores", _counting)
+
+ first = score_live_change(str(git_repo), "HEAD", baseline=200)
+ second = score_live_change(str(git_repo), "HEAD", baseline=200)
+ # Second identical call reuses the memo: no extra baseline walk.
+ assert calls["n"] == 1
+ assert first.percentile == second.percentile
+ assert first.baseline_sample_size == second.baseline_sample_size
+
+ # A new commit moves HEAD's sha, so the memo key changes and the walk reruns.
+ _commit(git_repo, {"src/new.py": "y = 1\n"}, "feat: bust", author="Dev")
+ score_live_change(str(git_repo), "HEAD", baseline=200)
+ assert calls["n"] == 2
+
+ baseline.clear_baseline_cache()
+
+
+def test_baseline_cache_isolated_by_filters(git_repo: Path, monkeypatch) -> None:
+ # Different filters produce different samples, so they must not share a memo
+ # entry even at the same anchor sha.
+ from repowise.core.analysis.change_risk import baseline
+
+ for i in range(10):
+ _commit(
+ git_repo,
+ {f"src/f{i}.py": f"x = {i}\n", f"docs/d{i}.md": f"# {i}\n"},
+ f"feat: file {i}",
+ author="Dev",
+ )
+
+ baseline.clear_baseline_cache()
+ calls = {"n": 0}
+ real = baseline.baseline_scores
+
+ def _counting(*args, **kwargs):
+ calls["n"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(baseline, "baseline_scores", _counting)
+
+ score_live_change(str(git_repo), "HEAD", baseline=200)
+ score_live_change(str(git_repo), "HEAD", baseline=200, extensions=("py",))
+ # Distinct extension filters key separately, so both walked.
+ assert calls["n"] == 2
+
+ baseline.clear_baseline_cache()
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index ffda42c71..ea78a54d0 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -119,3 +119,186 @@ async def test_get_change_risk_rejects_repo_all() -> None:
assert "error" in result
assert "get_change_risk" in result["error"]
+
+
+# ---------------------------------------------------------------------------
+# Line-level impacted tests (Phase 4B fold-in)
+# ---------------------------------------------------------------------------
+
+
+async def _factory_with_repo(coverage_records: list | None):
+ """Build an in-memory session factory seeded with one repo + coverage map."""
+ from datetime import UTC, datetime
+
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+ from sqlalchemy.pool import StaticPool
+
+ from repowise.core.persistence.crud import save_test_coverage
+ from repowise.core.persistence.database import init_db
+ from repowise.core.persistence.models import Repository
+
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ now = datetime(2026, 7, 18, tzinfo=UTC)
+ async with factory() as s:
+ s.add(
+ Repository(
+ id="repo1",
+ name="repo",
+ url="https://example.com/repo",
+ local_path="/tmp/repo",
+ default_branch="main",
+ settings_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ await s.flush()
+ if coverage_records:
+ await save_test_coverage(s, "repo1", coverage_records, source_format="coverage.py")
+ await s.commit()
+ return factory
+
+
+def _tc(test_id: str, source_file: str, covered_lines: list[int], test_file: str):
+ from repowise.core.analysis.health.coverage import TestCoverage
+
+ return TestCoverage(
+ test_id=test_id,
+ file_path=source_file,
+ covered_lines=covered_lines,
+ source_format="coverage.py",
+ test_file=test_file,
+ )
+
+
+async def test_impacted_tests_line_precise_hit_and_miss(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a\nb\nc\nd\ne\n"}, "chore: seed app")
+ # The change: edit app.py line 3, add other.py and new.py.
+ _commit(
+ repo,
+ {
+ "src/app.py": "a\nb\nc2\nd\ne\n",
+ "src/other.py": "o1\no2\no3\n",
+ "src/new.py": "n1\n",
+ },
+ "feat: change",
+ )
+
+ factory = await _factory_with_repo(
+ [
+ _tc("tests/test_app.py::test_app", "src/app.py", [3], "tests/test_app.py"),
+ _tc("tests/test_other.py::test_other", "src/other.py", [9], "tests/test_other.py"),
+ ]
+ )
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo), session_factory=factory)
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0)
+
+ it = result["impacted_tests"]
+ assert it["status"] == "map_present"
+ assert it["map_present"] is True
+ # app.py line 3 is covered -> its test is named; other/new are not covering.
+ assert it["tests"] == ["tests/test_app.py::test_app"]
+ assert it["total"] == 1
+ assert it["truncated"] is False
+
+ mt = it["missing_tests"]
+ # other.py is in the map but its changed lines (1,2,3) are uncovered.
+ assert mt["untested_changes"] == [
+ {"source_file": "src/other.py", "uncovered_lines": [1, 2, 3], "changed_line_count": 3}
+ ]
+ # new.py has no coverage rows -> unknown, never "untested".
+ assert mt["no_coverage_data"] == ["src/new.py"]
+ # app.py is covered but its test file is absent from the diff -> stale candidate.
+ assert [s["source_file"] for s in mt["stale_test_candidates"]] == ["src/app.py"]
+
+
+async def test_impacted_tests_no_map_is_unknown_not_untested(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a\nb\n"}, "chore: seed")
+ _commit(repo, {"src/app.py": "a\nb\nc\n"}, "feat: add line")
+
+ factory = await _factory_with_repo(None) # repo present, no coverage rows
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo), session_factory=factory)
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0)
+
+ it = result["impacted_tests"]
+ assert it["status"] == "no_map"
+ assert it["map_present"] is False
+ assert it["tests"] == []
+ # Honest degradation: no untested claim, a "run the suite" summary instead.
+ assert it["missing_tests"]["untested_changes"] == []
+ assert "run the full suite" in it["summary"]
+
+
+async def test_impacted_tests_overflow_cap_is_honest(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/hot.py": "seed\n"}, "chore: seed")
+ _commit(repo, {"src/hot.py": "changed\n"}, "feat: touch line 1")
+
+ # 12 distinct tests all cover the changed line 1 -> over the cap of 10.
+ records = [
+ _tc(f"tests/test_{i}.py::test_{i}", "src/hot.py", [1], f"tests/test_{i}.py")
+ for i in range(12)
+ ]
+ factory = await _factory_with_repo(records)
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo), session_factory=factory)
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0)
+
+ it = result["impacted_tests"]
+ assert it["total"] == 12
+ assert len(it["tests"]) == 10
+ assert it["truncated"] is True
+
+
+async def test_impacted_tests_no_session_factory_degrades_to_no_index(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a\n"}, "chore: seed")
+ _commit(repo, {"src/app.py": "a\nb\n"}, "feat: add")
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo)) # no session_factory
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0)
+
+ assert result["impacted_tests"]["status"] == "no_index"
+ assert result["impacted_tests"]["map_present"] is False