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(risk): say when line coverage is stored without a per-test map, and flag stale measured tests (#4339)

Raghav Chamadiya9179fc646127
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index ce56ab39a..f4a41a823 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -250,7 +250,7 @@ What history says about touching a file: hotspot score, bug-fix record, owners,
| `include` | list[string] | none | `graph` (typed dependents, consumers, cross-repo links), `churn`, `owners` (owner percentages, bus factor, contributor count), `tests` (typed `test_recommendations` in PR mode), `blast` (`pr_blast_radius` in PR mode), `scales` (units and calibration, identical per call), `changes` (each file's newest Change Records) |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
-**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners` (`file_path`, `support`, `conf_ab`, `has_import_link`), `primary_owner` (detailed owner metrics are opt-in under `include=["owners"]`), test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run` (the same selection `repowise impacted-tests` makes), `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_run_all` (with `tests_run_all_reasons` when every test must run), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers`, `next_calls`, and `reach` (`localized`, `moderate` or `broad`; `null` when no structural score was computed). `include=["blast"]` adds `pr_blast_radius`; the raw 0 to 10 `structural_impact_score` and its scale appear there only with `include=["blast", "scales"]`. `missing_tests` appears only when coverage can back it. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.
+**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners` (`file_path`, `support`, `conf_ab`, `has_import_link`), `primary_owner` (detailed owner metrics are opt-in under `include=["owners"]`), test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run` (the same selection `repowise impacted-tests` makes), `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_run_all` (with `tests_run_all_reasons` when every test must run), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers`, `next_calls`, and `reach` (`localized`, `moderate` or `broad`; `null` when no structural score was computed). `include=["blast"]` adds `pr_blast_radius`; the raw 0 to 10 `structural_impact_score` and its scale appear there only with `include=["blast", "scales"]`. `missing_tests` appears only when coverage can back it. With no per-test map but stored line coverage, `coverage.reason` is `no_per_test_map_aggregate_available` and `coverage.aggregate` gives its file count and freshness. With `include=["tests"]`, measured rows match a changed file rather than its changed lines (`evidence[].match: "file"`), and a row whose test file is gone or changed since the coverage was measured carries `stale: true` and `stale_reason`. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.
Dependent counts are a floor over the indexed graph, and structural reach is not proof of runtime breakage. `reach` bands an uncalibrated heuristic that never sees the diff; it is not a probability.
diff --git a/packages/core/src/repowise/core/analysis/test_impact.py b/packages/core/src/repowise/core/analysis/test_impact.py
index ca223f696..4a9b508bf 100644
--- a/packages/core/src/repowise/core/analysis/test_impact.py
+++ b/packages/core/src/repowise/core/analysis/test_impact.py
@@ -8,19 +8,21 @@ from an empty recommendation population.
from __future__ import annotations
+import asyncio
import sys
from collections import defaultdict
from collections.abc import Collection, Iterable, Mapping, Sequence
+from pathlib import Path
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.coverage.freshness import coverage_freshness
from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET, rank_reaching
from repowise.core.analysis.test_selection import expand_test_scopes
from repowise.core.exclusion import is_excluded
-from repowise.core.persistence.models import Repository
+from repowise.core.persistence.models import CoverageFile, Repository
_BASIS_ORDER = {"measured": 0, "inferred": 1}
@@ -87,7 +89,15 @@ async def analyze_test_impact(
return assemble_test_impact([], {}, {}, {}, **fold)
summary, measured, coverage_error = await _read_coverage(session, repository_id, changed)
- indexed_commit, indexed_commit_error = await _read_indexed_commit(session, repository_id)
+ indexed_commit, local_path, indexed_commit_error = await _read_repository(
+ session, repository_id
+ )
+ aggregate = None
+ if not summary.get("pair_count"):
+ aggregate = await _read_aggregate(session, repository_id, indexed_commit)
+ stale_tests = await _stale_measured_tests(
+ measured, summary.get("ingested_commit_sha"), local_path
+ )
inferred, test_files, inference_error = await _read_inferred(session, repository_id, changed)
return assemble_test_impact(
@@ -100,6 +110,8 @@ async def analyze_test_impact(
indexed_commit_error=indexed_commit_error,
coverage_error=coverage_error,
inference_error=inference_error,
+ aggregate_summary=aggregate,
+ stale_tests=stale_tests,
**fold,
)
@@ -129,19 +141,86 @@ async def _read_coverage(
return summary, measured, coverage_error
-async def _read_indexed_commit(
+async def _read_repository(
session: AsyncSession, repository_id: str
-) -> tuple[str | None, str | None]:
- """The repository's indexed head commit, or ``None`` and the read error."""
+) -> tuple[str | None, str | None, str | None]:
+ """The indexed head commit and checkout path, or ``None`` and the read error."""
try:
- indexed_commit = (
+ row = (
await session.execute(
- select(Repository.head_commit).where(Repository.id == repository_id)
+ select(Repository.head_commit, Repository.local_path).where(
+ Repository.id == repository_id
+ )
)
- ).scalar_one_or_none()
+ ).one_or_none()
except Exception as exc:
- return None, type(exc).__name__
- return indexed_commit, None
+ return None, None, type(exc).__name__
+ return (row[0], row[1], None) if row else (None, None, None)
+
+
+async def _read_aggregate(
+ session: AsyncSession, repository_id: str, indexed_commit: str | None
+) -> Mapping[str, Any] | None:
+ """How many files stored line coverage names and where it was measured; ``None`` if none.
+
+ A count and the newest row, not the full summary: this is an aside on
+ every PR-mode call and needs no figures.
+ """
+ scope = CoverageFile.repository_id == repository_id
+ try:
+ count = (
+ await session.execute(select(func.count()).select_from(CoverageFile).where(scope))
+ ).scalar_one()
+ if not count:
+ return None
+ commit = (
+ await session.execute(
+ select(CoverageFile.ingested_commit_sha)
+ .where(scope)
+ .order_by(CoverageFile.ingested_at.desc())
+ .limit(1)
+ )
+ ).scalar_one_or_none()
+ except Exception: # an aside to the per-test answer; never fail it
+ return None
+ return {
+ "file_count": count,
+ "ingested_commit_sha": commit,
+ "freshness": {"status": coverage_freshness(commit, indexed_commit)},
+ }
+
+
+async def _stale_measured_tests(
+ measured: Mapping[str, Sequence[Mapping[str, Any]]],
+ ingested_commit: str | None,
+ local_path: str | None,
+) -> dict[str, str]:
+ """``{test file: reason}`` for measured test files that differ from the measured run.
+
+ Read from git between the measured commit and the checkout's working tree:
+ ``test_file_missing`` when the file is deleted, ``test_file_changed`` when
+ it is edited. Only what git can prove: without a checkout or a measured
+ commit, or when git cannot tell, nothing is flagged. Ceiling: a checkout
+ nested below its git root reports root-relative paths, which match nothing.
+ """
+ from repowise.core.analysis.patch_coverage.stored import _changed_since
+
+ files = {f for rows in measured.values() for row in rows if (f := _runnable_file(row))}
+ if not files or not ingested_commit or not local_path or not Path(local_path).is_dir():
+ return {}
+ since = await asyncio.to_thread(_changed_since, local_path, ingested_commit, None)
+ return {
+ f: "test_file_changed" if (Path(local_path) / f).is_file() else "test_file_missing"
+ for f in sorted(files & (since or set()))
+ }
+
+
+def _runnable_file(row: Mapping[str, Any]) -> str | None:
+ """A measured row's test file: its own, or the path part of a ``path::name`` id."""
+ if row.get("test_file"):
+ return str(row["test_file"])
+ test_id = str(row["test_id"])
+ return test_id.split("::", 1)[0] if "::" in test_id else None
async def _read_inferred(
@@ -212,6 +291,8 @@ def assemble_test_impact(
inference_error: str | None = None,
indexed_commit_error: str | None = None,
repository_test_files: Collection[str] = (),
+ aggregate_summary: Mapping[str, Any] | None = None,
+ stale_tests: Mapping[str, str] | None = None,
) -> dict[str, Any]:
"""Fold coverage and reachability evidence into the test-impact result.
@@ -242,6 +323,17 @@ def assemble_test_impact(
changed file, so ``files[*].inferred_tests`` and the recommendations it
feeds are bounded; ``inferred_tests_total`` and
``inference.candidates_before_dedup`` keep the count before the cap.
+
+ *aggregate_summary* is the stored per-file line coverage summary
+ (``file_count``, ``ingested_commit_sha``, ``freshness``), read when there
+ is no per-test map. It cannot say which test ran a file, so it fills no
+ recommendation; ``coverage.aggregate`` says it exists (``None`` otherwise).
+
+ *stale_tests* maps a measured test file to why the checkout no longer
+ matches it (``test_file_missing``, ``test_file_changed``): every row carries
+ ``stale`` and ``stale_reason``, set only on rows measured coverage alone backs. Measured rows
+ match a changed file, not its changed lines, so measured evidence says
+ ``match: "file"`` (``None`` on inferred evidence).
"""
changed = _changed_paths(changed_files, exclude_spec)
repository = repository or repository_id
@@ -270,6 +362,7 @@ def assemble_test_impact(
"changed_files_without_measured_tests": 0,
"ingested_at": None,
"source_format": None,
+ "aggregate": None,
"freshness": {
"status": "unknown",
"reason": "no_changed_files",
@@ -318,6 +411,7 @@ def assemble_test_impact(
"basis": "measured",
"source_file": path,
"via": "coverage-map",
+ "match": "file",
"source_format": row.get("source_format"),
}
if detail not in evidence[key]:
@@ -361,6 +455,7 @@ def assemble_test_impact(
"basis": "inferred",
"source_file": path,
"via": reached["via"],
+ "match": None,
"source_format": None,
}
if detail not in evidence[key]:
@@ -376,6 +471,8 @@ def assemble_test_impact(
)
)
bases = sorted({row["basis"] for row in details}, key=_BASIS_ORDER.__getitem__)
+ runnable = {*test_files[(repo_id, test_id)], test_id.split("::", 1)[0]}
+ stale_reason = _stale_reason(bases, runnable, stale_tests)
recommendations.append(
{
"test_id": test_id,
@@ -388,6 +485,8 @@ def assemble_test_impact(
"bases": bases,
"source_files": sorted({row["source_file"] for row in details}),
"evidence": details,
+ "stale": stale_reason is not None,
+ "stale_reason": stale_reason,
}
)
recommendations.sort(
@@ -407,7 +506,11 @@ def assemble_test_impact(
coverage_reason = f"{coverage_error}: coverage_query_failed"
elif not map_present:
coverage_status = "unavailable"
- coverage_reason = "no_per_test_coverage_map"
+ coverage_reason = (
+ "no_per_test_map_aggregate_available"
+ if aggregate_summary
+ else "no_per_test_coverage_map"
+ )
elif 0 < matched_files < len(changed):
coverage_status = "partial"
coverage_reason = "coverage_map_matches_only_part_of_change"
@@ -429,6 +532,13 @@ def assemble_test_impact(
"ingested_at": _iso(summary.get("ingested_at")),
"source_format": summary.get("source_format"),
"freshness": freshness,
+ "aggregate": {
+ "file_count": int(aggregate_summary.get("file_count") or 0),
+ "ingested_commit": aggregate_summary.get("ingested_commit_sha"),
+ "freshness": (aggregate_summary.get("freshness") or {}).get("status", "unknown"),
+ }
+ if aggregate_summary
+ else None,
}
inference = {
"status": inference_status,
@@ -520,3 +630,15 @@ def assemble_test_impact(
),
},
}
+
+
+def _stale_reason(
+ bases: Sequence[str], files: Collection[str], stale_tests: Mapping[str, str] | None
+) -> str | None:
+ """Why a measured-only row's test file differs from the measured run, if it does.
+
+ A row the graph also backs keeps its inferred evidence, which is read live.
+ """
+ if not stale_tests or list(bases) != ["measured"]:
+ return None
+ return next((stale_tests[f] for f in sorted(files) if f in stale_tests), None)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py
index 54a04e566..a86065cfd 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py
@@ -66,7 +66,7 @@ def _project_recommendation(row: dict[str, Any]) -> dict[str, Any]:
if out.get("source_files") == sources:
out.pop("source_files", None)
out["evidence"] = [
- {k: v for k, v in e.items() if not (k == "source_format" and v is None)}
+ {k: v for k, v in e.items() if not (k in {"source_format", "match"} and v is None)}
if isinstance(e, dict)
else e
for e in evidence
@@ -75,6 +75,9 @@ def _project_recommendation(row: dict[str, Any]) -> dict[str, Any]:
out.pop("bases", None)
if out.get("test_file") in (out.get("test_id"), None):
out.pop("test_file", None)
+ if not out.get("stale"):
+ out.pop("stale", None)
+ out.pop("stale_reason", None)
return out
@@ -196,6 +199,11 @@ def missing_tests(
}
population = [path for path in changed_files if path in gap_paths]
summary = f"Showing {len(population[:3])} of {len(population)} changed-file test gap(s)."
+ elif coverage.get("reason") == "no_per_test_map_aggregate_available":
+ summary = (
+ "No per-test coverage map; aggregate line coverage is available, but it "
+ "cannot say which test ran a file, so test gaps are not listed."
+ )
else:
summary = (
f"Coverage analysis is {coverage.get('status', 'unavailable')}, so test gaps "
@@ -220,15 +228,18 @@ def coverage_fields(test_impact: dict[str, Any], coverage: dict[str, Any]) -> di
if coverage.get("status", "unavailable") != "unavailable":
return {
"test_analysis": test_impact.get("analysis") or {"status": "unavailable"},
- "coverage_analysis": coverage,
+ "coverage_analysis": {
+ k: v for k, v in coverage.items() if not (k == "aggregate" and v is None)
+ },
"test_inference_analysis": test_impact.get("inference") or {"status": "unavailable"},
}
- return {
- "coverage": {
- "status": coverage.get("status") or "unavailable",
- "reason": coverage.get("reason") or "no_per_test_coverage_map",
- }
+ block = {
+ "status": coverage.get("status") or "unavailable",
+ "reason": coverage.get("reason") or "no_per_test_coverage_map",
}
+ if coverage.get("aggregate"):
+ block["aggregate"] = coverage["aggregate"]
+ return {"coverage": block}
def cross_repo_fields(relationships: dict[str, Any]) -> dict[str, Any]:
diff --git a/packages/server/src/repowise/server/schemas/blast_radius.py b/packages/server/src/repowise/server/schemas/blast_radius.py
index 881622b16..4a78c7e9c 100644
--- a/packages/server/src/repowise/server/schemas/blast_radius.py
+++ b/packages/server/src/repowise/server/schemas/blast_radius.py
@@ -51,6 +51,9 @@ class TestImpactEvidence(BaseModel):
basis: Literal["measured", "inferred"]
source_file: str
via: Literal["coverage-map", "call-graph", "import-graph"]
+ #: ``file`` on measured evidence: a test ran the changed file, not
+ #: necessarily its changed lines.
+ match: Literal["file"] | None = None
source_format: str | None = None
@@ -63,6 +66,9 @@ class TestRecommendation(BaseModel):
bases: list[Literal["measured", "inferred"]]
source_files: list[str]
evidence: list[TestImpactEvidence]
+ #: A measured row whose test file is gone or changed since the coverage run.
+ stale: bool = False
+ stale_reason: Literal["test_file_missing", "test_file_changed"] | None = None
class TestImpactFile(BaseModel):
@@ -85,6 +91,12 @@ class TestImpactFreshness(BaseModel):
indexed_commit: str | None = None
+class TestImpactAggregate(BaseModel):
+ file_count: int
+ ingested_commit: str | None = None
+ freshness: Literal["current", "stale", "unknown"]
+
+
class TestImpactCoverage(BaseModel):
status: Literal["available", "partial", "unavailable", "degraded"]
reason: str | None = None
@@ -98,6 +110,8 @@ class TestImpactCoverage(BaseModel):
ingested_at: str | None = None
source_format: str | None = None
freshness: TestImpactFreshness
+ #: Stored per-file line coverage, when there is no per-test map.
+ aggregate: TestImpactAggregate | None = None
class TestImpactInference(BaseModel):
diff --git a/packages/types/src/blast-radius.ts b/packages/types/src/blast-radius.ts
index 4ab0c0a77..2a6ccecd7 100644
--- a/packages/types/src/blast-radius.ts
+++ b/packages/types/src/blast-radius.ts
@@ -52,6 +52,8 @@ export interface TestImpactEvidence {
basis: TestRecommendationBasis;
source_file: string;
via: "coverage-map" | "call-graph" | "import-graph";
+ /** `file` on measured evidence: a test ran the changed file, not necessarily its changed lines. */
+ match?: "file" | null;
source_format: string | null;
}
@@ -66,6 +68,9 @@ export interface TestRecommendation {
bases: TestRecommendationBasis[];
source_files: string[];
evidence: TestImpactEvidence[];
+ /** A measured row whose test file is gone or changed since the coverage run. */
+ stale?: boolean;
+ stale_reason?: "test_file_missing" | "test_file_changed" | null;
}
export interface TestImpactResponse {
@@ -111,6 +116,12 @@ export interface TestImpactResponse {
ingested_commit: string | null;
indexed_commit: string | null;
};
+ /** Stored per-file line coverage, when there is no per-test map. */
+ aggregate?: {
+ file_count: number;
+ ingested_commit: string | null;
+ freshness: "current" | "stale" | "unknown";
+ } | null;
};
inference: {
status: "available" | "degraded";
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 1dd1d5e32..33c864209 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4204,6 +4204,12 @@ export interface SymbolResponse {
fix_count?: number | null;
}
+export interface TestImpactAggregate {
+ file_count: number;
+ ingested_commit?: string | null;
+ freshness: "current" | "stale" | "unknown";
+}
+
export interface TestImpactAnalysis {
status: "available" | "partial" | "degraded";
stale: boolean;
@@ -4225,12 +4231,14 @@ export interface TestImpactCoverage {
ingested_at?: string | null;
source_format?: string | null;
freshness: TestImpactFreshness;
+ aggregate?: TestImpactAggregate | null;
}
export interface TestImpactEvidence {
basis: "measured" | "inferred";
source_file: string;
via: "coverage-map" | "call-graph" | "import-graph";
+ match?: "file" | null;
source_format?: string | null;
}
@@ -4286,6 +4294,8 @@ export interface TestRecommendation {
bases: ("measured" | "inferred")[];
source_files: string[];
evidence: TestImpactEvidence[];
+ stale?: boolean;
+ stale_reason?: "test_file_missing" | "test_file_changed" | null;
}
export interface TransitiveEntry {
diff --git a/tests/unit/analysis/test_assemble_test_impact.py b/tests/unit/analysis/test_assemble_test_impact.py
index 2e8132018..ab29d8eba 100644
--- a/tests/unit/analysis/test_assemble_test_impact.py
+++ b/tests/unit/analysis/test_assemble_test_impact.py
@@ -167,3 +167,49 @@ def test_an_expanded_scope_ranks_by_the_walk_distance() -> None:
"tests/z/test_near.py",
"tests/a/test_core.py",
]
+
+
+_AGGREGATE = {"file_count": 40, "ingested_commit_sha": "old", "freshness": {"status": "stale"}}
+
+
+def test_stored_line_coverage_without_a_per_test_map_is_named() -> None:
+ impact = assemble_test_impact(
+ ["src/a.py"],
+ {},
+ {},
+ {"pair_count": 0},
+ repository_id="r1",
+ aggregate_summary=_AGGREGATE,
+ )
+ assert impact["coverage"]["status"] == "unavailable"
+ assert impact["coverage"]["reason"] == "no_per_test_map_aggregate_available"
+ assert impact["coverage"]["aggregate"] == {
+ "file_count": 40,
+ "ingested_commit": "old",
+ "freshness": "stale",
+ }
+
+
+def test_measured_rows_match_the_file_and_carry_a_stale_test_file() -> None:
+ impact = _assemble(stale_tests={"tests/test_a.py": "test_file_changed"})
+ measured, inferred = impact["recommendations"]
+ assert measured["evidence"][0]["match"] == "file"
+ assert (measured["stale"], measured["stale_reason"]) == (True, "test_file_changed")
+ # Only a measured row is a claim about a past run; an inferred one is read live.
+ assert (inferred["stale"], inferred["stale_reason"]) == (False, None)
+
+
+def test_a_row_the_graph_also_backs_is_never_stale() -> None:
+ impact = _assemble(stale_tests={"tests/test_b.py": "test_file_missing"})
+ assert not any(row["stale"] for row in impact["recommendations"])
+ both = assemble_test_impact(
+ ["src/a.py"],
+ {"src/a.py": [{"test_id": "tests/test_a.py::t", "test_file": "tests/test_a.py"}]},
+ {"src/a.py": {"tests": ["tests/test_a.py::t"], "via": "call-graph"}},
+ _SUMMARY,
+ repository_id="r1",
+ indexed_commit="head",
+ stale_tests={"tests/test_a.py": "test_file_changed"},
+ )
+ assert both["recommendations"][0]["bases"] == ["measured", "inferred"]
+ assert both["recommendations"][0]["stale"] is False
diff --git a/tests/unit/analysis/test_test_impact_stale_tests.py b/tests/unit/analysis/test_test_impact_stale_tests.py
new file mode 100644
index 000000000..37426437e
--- /dev/null
+++ b/tests/unit/analysis/test_test_impact_stale_tests.py
@@ -0,0 +1,67 @@
+"""Which measured test files differ from the measured run."""
+
+from __future__ import annotations
+
+import subprocess
+
+from repowise.core.analysis.test_impact import _stale_measured_tests
+
+
+def _git(cwd, *args) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+
+def _repo(tmp_path):
+ _git(tmp_path, "init", "-q")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ tests = tmp_path / "tests"
+ tests.mkdir()
+ for name in ("test_kept.py", "test_edited.py", "test_gone.py"):
+ (tests / name).write_text("def test_it(): pass\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-q", "-m", "measured")
+ return _git(tmp_path, "rev-parse", "HEAD")
+
+
+def _rows(*files):
+ return {"src/a.py": [{"test_id": f"{f}::test_it", "test_file": f} for f in files]}
+
+
+async def test_a_gone_and_an_edited_test_file_are_flagged(tmp_path):
+ measured_at = _repo(tmp_path)
+ (tmp_path / "tests" / "test_edited.py").write_text("def test_it(): assert 1\n", "utf-8")
+ _git(tmp_path, "commit", "-qam", "edit")
+ (tmp_path / "tests" / "test_gone.py").unlink()
+
+ stale = await _stale_measured_tests(
+ _rows("tests/test_kept.py", "tests/test_edited.py", "tests/test_gone.py"),
+ measured_at,
+ str(tmp_path),
+ )
+
+ assert stale == {
+ "tests/test_edited.py": "test_file_changed",
+ "tests/test_gone.py": "test_file_missing",
+ }
+
+
+async def test_an_uncommitted_edit_counts_and_a_file_absent_from_git_does_not(tmp_path):
+ head = _repo(tmp_path)
+ (tmp_path / "tests" / "test_edited.py").write_text("changed\n", "utf-8")
+
+ stale = await _stale_measured_tests(
+ _rows("tests/test_kept.py", "tests/test_edited.py", "other/test_never.py"),
+ head,
+ str(tmp_path),
+ )
+
+ # A path git never knew is no proof the run's file is gone (another checkout).
+ assert stale == {"tests/test_edited.py": "test_file_changed"}
+
+
+async def test_without_a_checkout_nothing_is_flagged():
+ assert await _stale_measured_tests(_rows("tests/test_x.py"), "a", None) == {}
+
diff --git a/tests/unit/persistence/golden/test_impact.json b/tests/unit/persistence/golden/test_impact.json
index b4e0af095..8cd256850 100644
--- a/tests/unit/persistence/golden/test_impact.json
+++ b/tests/unit/persistence/golden/test_impact.json
@@ -11,6 +11,7 @@
"status": "partial"
},
"coverage": {
+ "aggregate": null,
"changed_files_total": 7,
"changed_files_with_measured_tests": 4,
"changed_files_without_measured_tests": 3,
@@ -148,6 +149,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/both.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -158,6 +160,8 @@
"source_files": [
"src/both.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_both.py",
"test_id": "tests/test_both.py::test_measured"
},
@@ -169,6 +173,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/measured.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -179,6 +184,8 @@
"source_files": [
"src/measured.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_measured.py",
"test_id": "tests/test_measured.py::test_measured"
},
@@ -190,6 +197,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/seed.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -200,6 +208,8 @@
"source_files": [
"src/seed.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_seed.py",
"test_id": "tests/test_seed.py::test_seed"
},
@@ -211,6 +221,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -221,6 +232,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_00"
},
@@ -232,6 +245,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -242,6 +256,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_01"
},
@@ -253,6 +269,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -263,6 +280,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_02"
},
@@ -274,6 +293,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -284,6 +304,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_03"
},
@@ -295,6 +317,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -305,6 +328,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_04"
},
@@ -316,6 +341,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -326,6 +352,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_05"
},
@@ -337,6 +365,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -347,6 +376,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_06"
},
@@ -358,6 +389,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -368,6 +400,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_07"
},
@@ -379,6 +413,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -389,6 +424,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_08"
},
@@ -400,6 +437,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -410,6 +448,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_09"
},
@@ -421,6 +461,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -431,6 +472,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_10"
},
@@ -442,6 +485,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -452,6 +496,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_11"
},
@@ -463,6 +509,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/both.py",
"source_format": null,
"via": "import-graph"
@@ -473,6 +520,8 @@
"source_files": [
"src/both.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_both_inferred.py",
"test_id": "tests/test_both_inferred.py"
},
@@ -484,6 +533,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/inferred.py",
"source_format": null,
"via": "import-graph"
@@ -494,6 +544,8 @@
"source_files": [
"src/inferred.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_inferred.py",
"test_id": "tests/test_inferred.py"
}
@@ -521,6 +573,7 @@
"status": "partial"
},
"coverage": {
+ "aggregate": null,
"changed_files_total": 8,
"changed_files_with_measured_tests": 0,
"changed_files_without_measured_tests": 8,
@@ -654,6 +707,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/both.py",
"source_format": null,
"via": "import-graph"
@@ -664,6 +718,8 @@
"source_files": [
"src/both.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_both_inferred.py",
"test_id": "tests/test_both_inferred.py"
},
@@ -675,6 +731,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/inferred.py",
"source_format": null,
"via": "import-graph"
@@ -685,6 +742,8 @@
"source_files": [
"src/inferred.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_inferred.py",
"test_id": "tests/test_inferred.py"
},
@@ -696,6 +755,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/inferred.py",
"source_format": null,
"via": "import-graph"
@@ -706,6 +766,8 @@
"source_files": [
"src/inferred.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/excluded/test_hidden.py",
"test_id": "tests/excluded/test_hidden.py"
}
@@ -736,6 +798,7 @@
"status": "partial"
},
"coverage": {
+ "aggregate": null,
"changed_files_total": 0,
"changed_files_with_measured_tests": 0,
"changed_files_without_measured_tests": 0,
@@ -788,6 +851,7 @@
"status": "partial"
},
"coverage": {
+ "aggregate": null,
"changed_files_total": 6,
"changed_files_with_measured_tests": 3,
"changed_files_without_measured_tests": 3,
@@ -913,6 +977,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/both.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -923,6 +988,8 @@
"source_files": [
"src/both.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_both.py",
"test_id": "tests/test_both.py::test_measured"
},
@@ -934,6 +1001,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/measured.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -944,6 +1012,8 @@
"source_files": [
"src/measured.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_measured.py",
"test_id": "tests/test_measured.py::test_measured"
},
@@ -955,6 +1025,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -965,6 +1036,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_00"
},
@@ -976,6 +1049,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -986,6 +1060,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_01"
},
@@ -997,6 +1073,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1007,6 +1084,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_02"
},
@@ -1018,6 +1097,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1028,6 +1108,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_03"
},
@@ -1039,6 +1121,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1049,6 +1132,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_04"
},
@@ -1060,6 +1145,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1070,6 +1156,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_05"
},
@@ -1081,6 +1169,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1091,6 +1180,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_06"
},
@@ -1102,6 +1193,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1112,6 +1204,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_07"
},
@@ -1123,6 +1217,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1133,6 +1228,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_08"
},
@@ -1144,6 +1241,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1154,6 +1252,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_09"
},
@@ -1165,6 +1265,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1175,6 +1276,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_10"
},
@@ -1186,6 +1289,7 @@
"evidence": [
{
"basis": "measured",
+ "match": "file",
"source_file": "src/truncate.py",
"source_format": "coverage.py",
"via": "coverage-map"
@@ -1196,6 +1300,8 @@
"source_files": [
"src/truncate.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_truncate.py",
"test_id": "tests/test_truncate.py::test_11"
},
@@ -1207,6 +1313,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/both.py",
"source_format": null,
"via": "import-graph"
@@ -1217,6 +1324,8 @@
"source_files": [
"src/both.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_both_inferred.py",
"test_id": "tests/test_both_inferred.py"
},
@@ -1228,6 +1337,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/inferred.py",
"source_format": null,
"via": "import-graph"
@@ -1238,6 +1348,8 @@
"source_files": [
"src/inferred.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/test_inferred.py",
"test_id": "tests/test_inferred.py"
},
@@ -1249,6 +1361,7 @@
"evidence": [
{
"basis": "inferred",
+ "match": null,
"source_file": "src/inferred.py",
"source_format": null,
"via": "import-graph"
@@ -1259,6 +1372,8 @@
"source_files": [
"src/inferred.py"
],
+ "stale": false,
+ "stale_reason": null,
"test_file": "tests/excluded/test_hidden.py",
"test_id": "tests/excluded/test_hidden.py"
}
diff --git a/tests/unit/persistence/test_test_impact_aggregate.py b/tests/unit/persistence/test_test_impact_aggregate.py
new file mode 100644
index 000000000..f7587a4a8
--- /dev/null
+++ b/tests/unit/persistence/test_test_impact_aggregate.py
@@ -0,0 +1,37 @@
+"""analyze_test_impact with stored line coverage and no per-test map."""
+
+from __future__ import annotations
+
+
+async def test_analyze_names_stored_line_coverage_when_there_is_no_per_test_map(
+ async_session,
+):
+ from repowise.core.analysis.test_impact import analyze_test_impact
+ from repowise.core.persistence.crud import save_coverage_files
+ from tests.unit.persistence.helpers import insert_repo
+
+ repo = await insert_repo(async_session, name="aggregate", head_commit="head")
+ await save_coverage_files(
+ async_session,
+ repo.id,
+ [
+ {
+ "file_path": "src/a.py",
+ "line_coverage_pct": 50.0,
+ "covered_lines": [1],
+ "total_coverable_lines": 2,
+ "branch_coverage_pct": None,
+ }
+ ],
+ source_format="lcov",
+ ingested_commit_sha="head",
+ )
+
+ impact = await analyze_test_impact(async_session, repo.id, ["src/a.py"])
+
+ assert impact["coverage"]["reason"] == "no_per_test_map_aggregate_available"
+ assert impact["coverage"]["aggregate"] == {
+ "file_count": 1,
+ "ingested_commit": "head",
+ "freshness": "current",
+ }
diff --git a/tests/unit/server/mcp/test_risk_aggregate_coverage.py b/tests/unit/server/mcp/test_risk_aggregate_coverage.py
new file mode 100644
index 000000000..ef0f76cb5
--- /dev/null
+++ b/tests/unit/server/mcp/test_risk_aggregate_coverage.py
@@ -0,0 +1,33 @@
+"""get_risk PR mode with stored line coverage but no per-test map."""
+
+from __future__ import annotations
+
+from repowise.server.mcp_server.tool_risk.directives_pr import coverage_fields, missing_tests
+
+_COVERAGE = {
+ "status": "unavailable",
+ "reason": "no_per_test_map_aggregate_available",
+ "aggregate": {"file_count": 40, "ingested_commit": "old", "freshness": "current"},
+}
+
+
+def test_the_summary_names_the_aggregate_instead_of_unavailable_coverage():
+ gaps = missing_tests({"test_gaps": ["src/a.py"]}, ["src/a.py"], _COVERAGE, None)
+
+ assert gaps.usable is False
+ assert gaps.population == []
+ assert "aggregate line coverage is available" in gaps.summary
+ assert "withheld" not in gaps.summary
+
+
+def test_the_coverage_block_carries_the_aggregate():
+ block = coverage_fields({}, _COVERAGE)["coverage"]
+
+ assert block["reason"] == "no_per_test_map_aggregate_available"
+ assert block["aggregate"]["file_count"] == 40
+
+
+def test_without_stored_coverage_the_block_is_unchanged():
+ block = coverage_fields({}, {"status": "unavailable"})["coverage"]
+
+ assert block == {"status": "unavailable", "reason": "no_per_test_coverage_map"}