Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(coverage): patch coverage on the agent, API and local surfaces (#2634)
Raghav Chamadiya92411fa6abdc
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 2f1c8da9e..9dd3ea050 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -663,6 +663,15 @@ the same distinction in one word: `measured`, `inferred`, or absent. Build themeasured map with `coverage run --contexts=test` followed by`repowise coverage add`.+When the index stores coverage, the response also carries `patch_coverage`:+the share of the change's executable lines the stored coverage ran, the same+computation and JSON shape `repowise coverage check --format json` gates on.+`patch_coverage_pct` is null when no changed line is executable, files the+coverage never names read `not_in_report` rather than 0%, and+`scope.freshness` is `stale` when the coverage was measured at another commit+than the change's head (`unknown` for uncommitted work), so its line numbers+may describe other code. The block is absent when no coverage is stored.+In workspace mode the response also carries `cross_repo`, and every`cross_repo.consumers[]` row gains a `tests` block: a `state` (`measured`,`inferred`, `none` or `unresolved`), up to five `tests_to_run` rows carryingdiff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex 89de01dce..73d7a6540 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -199,7 +199,14 @@ Report paths are resolved against `git ls-files` rather than an index, so a filethe change adds resolves too. Without `REVSPEC` the base comes from the CI'spull-request variables, else the default branch; pass it explicitly in CI so thejob says what it measures. Reports come from `--report`, else `coverage.paths`,-else discovery.+else discovery, else (locally) the coverage an index already stores from+`coverage add`.++The same figure is on every surface, from the same computation over stored+coverage: `get_change_risk`'s `patch_coverage` block, and+`GET /api/repos/{id}/health/coverage/patch?base=&head=` (diffs `base...head`; `null`+when nothing is ingested), which the editor's branch-risk view reads. Stored+coverage measured at another commit than the change's head is marked `stale`.The denominator is changed lines the report marks executable, so a changedcomment or blank line is neither covered nor uncovered. What counts is decided bydiff --git a/packages/api-client/src/risk.ts b/packages/api-client/src/risk.tsindex b39fe9f35..0e1408df7 100644--- a/packages/api-client/src/risk.ts+++ b/packages/api-client/src/risk.ts@@ -1,9 +1,11 @@/*** REST client for the change-risk endpoints.- * Backend: packages/server/src/repowise/server/routers/git.py (risk/range)+ * Backend: packages/server/src/repowise/server/routers/git.py (risk/range) and+ * routers/code_health/coverage_routes.py (health/coverage/patch)*/import { apiGet } from "./client";+import type { PatchCoverageResponse } from "@repowise-dev/types/generated/http";import type { RiskAuthority } from "@repowise-dev/types/risk-semantics";import type { RiskDriverResponse } from "./types/git";@@ -74,3 +76,17 @@ export async function getRiskRange(baseline: params.baseline,});}++/**+ * Patch coverage of `base...head`: the share of the change's executable lines+ * the stored test coverage ran. Null when no coverage report was ingested.+ */+export async function getPatchCoverage(+ repoId: string,+ params: Pick<RiskRangeParams, "base" | "head">,+): Promise<PatchCoverageResponse | null> {+ return apiGet<PatchCoverageResponse | null>(+ `/api/repos/${repoId}/health/coverage/patch`,+ { base: params.base, head: params.head },+ );+}diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex 86e85afe9..a0c31b851 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -2,7 +2,10 @@Needs git and a coverage report, nothing else: no index, no API key. Reportpaths are resolved against ``git ls-files``, so a file added by the change-resolves too (an index cached from the base branch would not know it).+resolves too (an index cached from the base branch would not know it). With no+report on disk it falls back to the coverage an index stores, but gates on it+only when that coverage was measured at the change's head and carries+executable-line data; otherwise it cannot evaluate.Exit codes and output channels are the shared CI ones (:mod:`repowise.cli.ci`):0 when the gate passes or there is nothing to judge, 1 when patch coverage is@@ -24,9 +27,10 @@ from repowise.cli.ci import (cannot_evaluate,ci_notices,)-from repowise.cli.helpers import console+from repowise.cli.helpers import console, repo_index_session, run_asyncfrom repowise.cli.output import emit_json, format_optionfrom repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS+from repowise.core.persistence.database import has_db_storeclass _CannotEvaluateError(Exception):@@ -108,27 +112,89 @@ def _evaluate(revspec, reports, report_format, fail_under, repo, notices):root = _repo_root(repo)cfg = _coverage_config(root, validate_threshold=fail_under is None)+ threshold = fail_under if fail_under is not None else cfg.fail_underreport_paths = [Path(p) for p in reports] or cfg.report_paths(root)+ if not report_paths and not has_db_store(root):+ raise _CannotEvaluateError("no_report", _NO_REPORT)+ changed, label = _changed_lines(str(root), revspec or _default_revspec(str(root)))if not report_paths:- raise _CannotEvaluateError(- "no_report",- "No coverage report found. Pass one with --report (lcov.info, coverage.xml, "- "coverage.out, jacoco.xml, ...) or set coverage.paths in .repowise/config.yaml."- )+ # No report on disk: the index's stored coverage answers, when it can.+ if notices is console:+ notices.print("[dim]Reading the coverage stored in the index[/dim]")+ return _gateable(run_async(_stored(root, changed, label, threshold)))if notices is console:# Machine formats carry the list in ``scope.reports`` instead.notices.print(f"[dim]Reading {', '.join(escape(str(p)) for p in report_paths)}[/dim]")- changed, label = _changed_lines(str(root), revspec or _default_revspec(str(root)))return patch_coverage_from_resolved(changed,_resolve_reports(root, cfg, report_paths, report_format, notices),- threshold=fail_under if fail_under is not None else cfg.fail_under,+ threshold=threshold,label=label,reports=[str(p) for p in report_paths],)+_NO_REPORT = (+ "No coverage report found. Pass one with --report (lcov.info, coverage.xml, "+ "coverage.out, jacoco.xml, ...), set coverage.paths in .repowise/config.yaml, "+ "or ingest one with `repowise coverage add`."+)+++def _gateable(pc):+ """Stored coverage the gate can trust, or why it cannot evaluate.++ Coverage from another commit describes other code, and coverage stored+ before executable lines were kept cannot tell an uncovered line from a+ comment: either would pass a gate that measured nothing.+ """+ if pc is None:+ raise _CannotEvaluateError("no_report", _NO_REPORT)+ if pc.scope.freshness != "current":+ at = f" at {pc.scope.measured_commit[:7]}" if pc.scope.measured_commit else ""+ raise _CannotEvaluateError(+ "coverage_stale",+ f"The stored coverage was measured{at}, not at this change's head. "+ "Pass a fresh report with --report, or re-run `repowise coverage add`.",+ )+ measurable = pc.with_status("measured") + pc.with_status("no_coverable_changes")+ if pc.with_status("no_line_data") and not measurable:+ raise _CannotEvaluateError(+ "no_line_data",+ "The stored coverage predates executable-line data. Re-run "+ "`repowise coverage add` with the report, or pass it with --report.",+ )+ return pc+++async def _stored(root: Path, changed, label: str, threshold: float | None):+ """Patch coverage from the index's stored coverage, or ``None`` without one."""+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.core import git_refs+ from repowise.core.analysis.change_risk.features import revspec_head+ from repowise.core.analysis.patch_coverage import stored_patch_coverage++ async with repo_index_session(root) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ try:+ return await stored_patch_coverage(+ session,+ repo_id,+ changed,+ label=label,+ head_commit=git_refs.resolve(str(root), revspec_head(label)),+ threshold=threshold,+ )+ except SQLAlchemyError as exc:+ raise _CannotEvaluateError(+ "index_unreadable", f"Could not read the index's coverage: {exc}"+ ) from exc++def _resolve_reports(root, cfg, report_paths, report_format, notices):"""Parse the reports against the files git tracks, failing when nothing usable remains."""from repowise.core import git_refsdiff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex 2e478ad22..c81bc92b7 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -20,6 +20,7 @@ from repowise.cli.helpers import (console,ensure_repowise_dir,get_db_url_for_repo,+ reconcile_schema_best_effort,resolve_command_target,run_async,)@@ -165,7 +166,10 @@ def coverage_add(save_test_coverage,)- engine = create_engine(get_db_url_for_repo(repo_path))+ url = get_db_url_for_repo(repo_path)+ # An index from an older repowise lacks newer columns; back-fill them.+ await reconcile_schema_best_effort(url)+ engine = create_engine(url)sf = create_session_factory(engine)async with get_session(sf) as session:repo_row = await get_repository_by_path(session, str(repo_path))@@ -373,7 +377,10 @@ def coverage_status(repo: str | None, fmt: str) -> None:get_test_coverage_summary,)- engine = create_engine(get_db_url_for_repo(repo_path))+ url = get_db_url_for_repo(repo_path)+ # An index from an older repowise lacks newer columns; back-fill them.+ await reconcile_schema_best_effort(url)+ engine = create_engine(url)sf = create_session_factory(engine)async with get_session(sf) as session:repo_row = await get_repository_by_path(session, str(repo_path))diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex f30f57494..56357ce31 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -7,7 +7,6 @@ per-test map. A ``repowise health`` run must not overwrite that data.from __future__ import annotations-import jsonfrom collections.abc import Sequencefrom pathlib import Pathfrom typing import Any@@ -30,7 +29,7 @@ def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:)from repowise.core.persistence.crud import (get_repository_by_path,- load_coverage_for_repo,+ load_coverage_map,)async def _do() -> dict[str, dict]:@@ -44,21 +43,7 @@ def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:repo = await get_repository_by_path(session, str(repo_path))if repo is None:return {}- rows = await load_coverage_for_repo(session, repo.id)- out: dict[str, dict] = {}- for r in rows:- try:- covered = list(json.loads(r.covered_lines_json))- except (ValueError, TypeError):- covered = []- out[r.file_path] = {- "line_coverage_pct": r.line_coverage_pct,- "branch_coverage_pct": r.branch_coverage_pct,- "covered_lines": covered,- "total_coverable_lines": r.total_coverable_lines,- "source_format": r.source_format,- }- return out+ return await load_coverage_map(session, repo.id)try:return run_async(_do())diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 721ef42ae..55039d35a 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -12,6 +12,7 @@ import contextlibimport osimport sysimport time+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any@@ -100,26 +101,35 @@ def _repair_module_attribution(repo_path: Path) -> int:return changed+@dataclass(frozen=True)+class RescoreCoverage:+ """Coverage for a health re-score, and whether it replaces what is stored."""++ coverage_map: dict[str, dict] = field(default_factory=dict)+ files: list[Any] = field(default_factory=list)+ source_format: str | None = None+ # True for a reingestion, including an empty one that must clear stored rows.+ authoritative: bool = False+ mapping_partial: bool = False++async def _coverage_for_rescore(session: Any,repo_id: str,repo_path: Path,parsed_files: list[Any],-) -> tuple[dict[str, dict], list[Any], str | None, bool]:+) -> RescoreCoverage:"""Coverage to feed a health re-score, preserved across updates.Default: reload the rows already persisted (no re-parse). When``coverage.reingest_on_update`` is set, re-discover and re-resolve a- fresh report instead. The final return value marks an authoritative- reingestion, including an empty result that must clear stored rows.+ fresh report instead."""- import json-from repowise.core.analysis.health.coverage import (CoverageConfig,build_coverage_map,)- from repowise.core.persistence.crud import load_coverage_for_repo+ from repowise.core.persistence.crud import load_coverage_mapfrom repowise.core.repo_config import load_repo_configcfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))@@ -139,30 +149,22 @@ async def _coverage_for_rescore(path_prefix=cfg.path_prefix,)if resolved.coverage_map:- return resolved.coverage_map, resolved.files, resolved.source_format, True+ return RescoreCoverage(+ resolved.coverage_map,+ resolved.files,+ resolved.source_format,+ authoritative=True,+ mapping_partial=resolved.mapping_partial,+ )# Reingestion is authoritative. Falling back to old rows when a report# disappeared (or now maps to nothing) makes this config refresh differ# from a clean index and then incorrectly stamps stale data current.- return {}, [], None, True+ return RescoreCoverage(authoritative=True)- rows = await load_coverage_for_repo(session, repo_id)- coverage_map: dict[str, dict] = {}- source_format: str | None = None- for row in rows:- source_format = source_format or getattr(row, "source_format", None)- try:- covered = json.loads(row.covered_lines_json) if row.covered_lines_json else []- except (ValueError, TypeError):- covered = []- coverage_map[row.file_path] = {- "line_coverage_pct": row.line_coverage_pct,- "branch_coverage_pct": row.branch_coverage_pct,- "covered_lines": covered,- "total_coverable_lines": row.total_coverable_lines or 0,- "source_format": source_format,- }- return coverage_map, [], source_format, False+ coverage_map = await load_coverage_map(session, repo_id)+ source_format = next((e["source_format"] for e in coverage_map.values()), None)+ return RescoreCoverage(coverage_map, source_format=source_format)async def _persist_partial_health(@@ -1456,18 +1458,13 @@ async def _rescore_health_from_db(# line/branch coverage even though the coverage_files rows still# existed. Reload them (and optionally re-discover a fresh report)# so coverage survives `repowise update`.- (- coverage_map,- coverage_files,- coverage_format,- coverage_authoritative,- ) = await _coverage_for_rescore(session, repo_id, repo_path, parsed_files)+ coverage = await _coverage_for_rescore(session, repo_id, repo_path, parsed_files)analyzer = HealthAnalyzer(graph_builder.graph(),git_meta_map=git_meta_map,parsed_files=parsed_files,- coverage_map=coverage_map,+ coverage_map=coverage.coverage_map,duplication_cache_dir=Path(repo_path) / ".repowise",repo_root=repo_path,stored_blame_findings=stored_blame_findings,@@ -1493,7 +1490,7 @@ async def _rescore_health_from_db(await save_full_health_report(session, repo_id, report, analyzed_commit=get_head_commit(Path(repo_path)))- if coverage_authoritative:+ if coverage.authoritative:# Stamp the live HEAD from disk, not the stored# ``repo.head_commit`` column. The column names the last# *indexed* commit; the coverage just scored describes the@@ -1504,9 +1501,10 @@ async def _rescore_health_from_db(await save_coverage_files(session,repo_id,- coverage_files,- source_format=coverage_format or "lcov",+ coverage.files,+ source_format=coverage.source_format or "lcov",ingested_commit_sha=live_head,+ mapping_partial=coverage.mapping_partial,)await persist_graph_nodes(session, repo_id, graph_builder)diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex dcb07a25f..1522d58da 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -227,8 +227,10 @@ async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, stfrom repowise.core.persistence import create_engine, create_session_factory, get_sessionfrom repowise.core.persistence.crud import get_repository_by_path+ from repowise.core.persistence.database import has_db_store- if not (root / REPOWISE_DIR / "wiki.db").is_file():+ # The configured store, which may live outside the repo (REPOWISE_DB_URL).+ if not has_db_store(root):yield Nonereturn# The stack keeps the session open across the yield and disposes the engine@@ -236,7 +238,9 @@ async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, stasync with contextlib.AsyncExitStack() as stack:opened: tuple[AsyncSession, str] | None = Nonetry:- engine = create_engine(get_db_url_for_repo(root))+ url = get_db_url_for_repo(root)+ await reconcile_schema_best_effort(url)+ engine = create_engine(url)stack.push_async_callback(engine.dispose)factory = create_session_factory(engine)session = await stack.enter_async_context(get_session(factory))diff --git a/packages/core/alembic/versions/0079_coverage_coverable_lines.py b/packages/core/alembic/versions/0079_coverage_coverable_lines.pynew file mode 100644index 000000000..9a5748e48--- /dev/null+++ b/packages/core/alembic/versions/0079_coverage_coverable_lines.py@@ -0,0 +1,47 @@+"""coverage_files: store the lines each report calls executable.++``coverable_lines_json`` holds the executable-line set, hit or not, so patch+coverage can be computed from stored coverage: without it an uncovered+changed line cannot be told from a changed comment. ``'[]'`` means the report+did not say (or the row predates the column).++Local SQLite stores never run Alembic -- ``init_db``'s reconciler issues+additive DDL for missing columns -- so this migration exists for managed+Postgres.++Revision ID: 0079+Revises: 0078+Create Date: 2026-09-28+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0079"+down_revision: str | None = "0078"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def _columns() -> set[str]:+ inspector = sa.inspect(op.get_bind())+ return {c["name"] for c in inspector.get_columns("coverage_files")}+++def upgrade() -> None:+ # Guarded: ``init_db``'s reconciler may already have added it on Postgres.+ if "coverable_lines_json" not in _columns():+ op.add_column(+ "coverage_files",+ sa.Column("coverable_lines_json", sa.Text(), nullable=False, server_default="[]"),+ )+++def downgrade() -> None:+ if "coverable_lines_json" in _columns():+ op.drop_column("coverage_files", "coverable_lines_json")diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.pyindex 72dbbc986..619682c24 100644--- a/packages/core/src/repowise/core/analysis/change_risk/features.py+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py@@ -76,6 +76,12 @@ def split_revspec(revspec: str) -> tuple[str, str, str] | None:return base or "HEAD", sep, head or "HEAD"+def revspec_head(revspec: str | None) -> str:+ """The revision a change ends at: a range's head, else the revision itself."""+ parts = split_revspec(revspec) if revspec else None+ return parts[2] if parts else revspec or "HEAD"++def _git(args: list[str], cwd: str, *, check: bool = True) -> str:# stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC# pipe handles can wedge the session (same failure mode _meta.py guardsdiff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.pyindex c278d8dde..58d68e51a 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py@@ -28,6 +28,7 @@ from .discovery import (resolve_reports,resolve_test_reports,)+from .freshness import FreshnessStatus, coverage_freshnessfrom .goprofile import parse_go_coverprofilefrom .jacoco import parse_jacocofrom .lcov import parse_lcov@@ -49,10 +50,12 @@ __all__ = ["CoverageDecay","CoverageReport","FileCoverage",+ "FreshnessStatus","ResolvedCoverage","ResolvedTestCoverage","TestCoverage","build_coverage_map",+ "coverage_freshness","decay_for_file","decay_since","detect_format",diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.pyindex e1d8a48a8..c662ef3c5 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py@@ -32,7 +32,13 @@ from pathlib import Pathfrom repowise.core.fs_walk import PRUNED_DIRS, WalkSnapshot, iter_globfrom .detector import parse as parse_coverage-from .model import ContextCoverageReport, CoverageReport, FileCoverage, TestCoverage+from .model import (+ ContextCoverageReport,+ CoverageReport,+ FileCoverage,+ TestCoverage,+ coverage_map_entry,+)# Default glob patterns, relative to the repo root. Ordered roughly by how# canonical/common the location is. Kept curated (not a blind ``**/*.info``)@@ -421,13 +427,7 @@ def resolve_reports(result.mapping_partial = result.matched * 2 < report_file_countfor key, fc in by_key.items():- result.coverage_map[key] = {- "line_coverage_pct": fc.line_coverage_pct,- "branch_coverage_pct": fc.branch_coverage_pct,- "covered_lines": list(fc.covered_lines),- "total_coverable_lines": fc.total_coverable_lines,- "source_format": result.source_format,- }+ result.coverage_map[key] = coverage_map_entry(fc, result.source_format)result.files = list(by_key.values())return resultdiff --git a/packages/core/src/repowise/core/analysis/health/coverage/freshness.py b/packages/core/src/repowise/core/analysis/health/coverage/freshness.pynew file mode 100644index 000000000..52e0bb85f--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/freshness.py@@ -0,0 +1,22 @@+"""Does stored coverage describe the code a reader is asking about?++One rule for every surface: coverage is ``current`` when it was measured at+the commit in question, ``stale`` when at another, ``unknown`` when either+commit is missing. Callers differ only in which commit they ask about (the+indexed tree, a change's head).+"""++from __future__ import annotations++from typing import Literal++FreshnessStatus = Literal["current", "stale", "unknown"]+++def coverage_freshness(+ measured_commit: str | None, reference_commit: str | None+) -> FreshnessStatus:+ """Freshness of coverage measured at *measured_commit* for *reference_commit*."""+ if not measured_commit or not reference_commit:+ return "unknown"+ return "current" if measured_commit == reference_commit else "stale"diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.pyindex 31cc9e040..290f6c37a 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py@@ -76,6 +76,17 @@ def parse_xml(text: str) -> ET.Element | None:return None+def coverage_map_entry(fc: FileCoverage, source_format: str | None) -> dict:+ """The per-file dict ``HealthAnalyzer`` reads from its ``coverage_map``."""+ return {+ "line_coverage_pct": fc.line_coverage_pct,+ "branch_coverage_pct": fc.branch_coverage_pct,+ "covered_lines": list(fc.covered_lines),+ "total_coverable_lines": fc.total_coverable_lines,+ "source_format": source_format,+ }++@dataclassclass CoverageReport:"""Whole-report bundle returned by every parser.diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.pyindex 83709f570..7268ac1d3 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py@@ -22,6 +22,7 @@ from .render import (render_markdown,scope_line,)+from .stored import stored_patch_coverage__all__ = ["RANGE_LIMIT",@@ -40,4 +41,5 @@ __all__ = ["patch_coverage_from_resolved","render_markdown","scope_line",+ "stored_patch_coverage",]diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.pyindex 793438625..1c6d4e0b8 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING, Any, Literal, get_argsfrom ...test_paths import is_test_related_pathfrom ..changed_lines import line_ranges+from ..health.coverage.freshness import FreshnessStatusfrom ..health.coverage.model import FileCoverageif TYPE_CHECKING:@@ -78,9 +79,17 @@ class PatchScope:label: str = "" # the diff, e.g. "origin/main...HEAD"source_formats: tuple[str, ...] = ()reports: tuple[str, ...] = () # report files read, as the caller named them- report_path_count: int = 0 # file entries across those reports- # Report entries that did not map to a file in the repository.- unmatched_report_path_count: int = 0+ # File entries across those reports, and how many did not map to a file in+ # the repository. ``None`` when unknown (stored coverage keeps only matches).+ report_path_count: int | None = None+ unmatched_report_path_count: int | None = None+ # Fewer than half the report's files mapped: the figure covers a fragment.+ mapping_partial: bool = False+ # The commit the coverage was measured at, and whether that is the+ # change's head (``coverage_freshness``). Stale coverage still computes,+ # but its line numbers describe other code, so every renderer says so.+ measured_commit: str | None = None+ freshness: FreshnessStatus = "unknown"def to_dict(self) -> dict[str, Any]:return {@@ -89,6 +98,9 @@ class PatchScope:"reports": list(self.reports),"report_path_count": self.report_path_count,"unmatched_report_path_count": self.unmatched_report_path_count,+ "mapping_partial": self.mapping_partial,+ "measured_commit": self.measured_commit,+ "freshness": self.freshness,}@@ -151,9 +163,15 @@ def compute_patch_coverage(*,threshold: float | None = None,scope: PatchScope | None = None,+ report_paths: Iterable[str] | None = None,) -> PatchCoverage:- """Intersect a change with a coverage report. See the module docstring."""- measured_suffixes = {PurePosixPath(p).suffix for p in coverage}+ """Intersect a change with a coverage report. See the module docstring.++ *report_paths* is every path the report measures, when *coverage* holds+ only the changed files' entries (a stored report read for one change); it+ decides which unlisted files count as ``not_in_report``.+ """+ measured_suffixes = {PurePosixPath(p).suffix for p in report_paths or coverage}files: list[FilePatchCoverage] = []out_of_scope = 0for path in sorted(changed):@@ -195,6 +213,7 @@ def patch_coverage_from_resolved(reports=tuple(reports),report_path_count=resolved.matched + unmatched,unmatched_report_path_count=unmatched,+ mapping_partial=resolved.mapping_partial,),)diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.pyindex 21c59b113..3997270a5 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py@@ -63,7 +63,12 @@ def scope_line(pc: PatchCoverage, *, markdown: bool = True) -> str:if pc.out_of_scope_count:files += f", {pc.out_of_scope_count} out of scope"parts.append(files)- if scope.unmatched_report_path_count:+ if scope.freshness == "stale":+ at = f" at {scope.measured_commit[:7]}" if scope.measured_commit else ""+ parts.append(f"coverage was measured{at}, not at this change's head")+ if scope.mapping_partial:+ parts.append("most report paths did not match this repository, so this covers a fragment")+ elif scope.unmatched_report_path_count:parts.append(f"{scope.unmatched_report_path_count} of {scope.report_path_count} report paths ""did not match a file in this repository"diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.pynew file mode 100644index 000000000..554cc5b02--- /dev/null+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py@@ -0,0 +1,58 @@+"""Patch coverage from the coverage an index already stores.++The CLI gate reads a fresh report; every other surface (agent tools, the+REST API, editors) reads what ``coverage add`` or indexing stored. Both end in+:func:`compute_patch_coverage`, so the number cannot differ by surface.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping++from sqlalchemy.ext.asyncio import AsyncSession++from ..health.coverage.freshness import coverage_freshness+from .compute import PatchCoverage, PatchScope, compute_patch_coverage+++async def stored_patch_coverage(+ session: AsyncSession,+ repository_id: str,+ changed: Mapping[str, Iterable[int]],+ *,+ label: str = "",+ head_commit: str | None = None,+ threshold: float | None = None,+) -> PatchCoverage | None:+ """Patch coverage of *changed* against stored coverage; ``None`` when none is stored.++ *head_commit* is the commit the change ends at; coverage measured anywhere+ else is marked ``stale`` in the scope.+ """+ from repowise.core.persistence.crud import (+ get_coverage_summary,+ load_coverage_for_repo,+ load_file_coverage,+ )++ rows = await load_coverage_for_repo(session, repository_id, include_covered_lines=False)+ if not rows:+ return None+ summary = await get_coverage_summary(session, repository_id, rows=rows)+ measured = {row.file_path for row in rows}+ wanted = sorted(set(changed) & measured)+ coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}+ commit = summary["ingested_commit_sha"]+ return compute_patch_coverage(+ changed,+ coverage,+ threshold=threshold,+ report_paths=measured,+ scope=PatchScope(+ label=label,+ source_formats=(summary["source_format"],) if summary["source_format"] else (),+ mapping_partial=bool(summary["mapping_partial"]),+ measured_commit=commit,+ freshness=coverage_freshness(commit, head_commit),+ ),+ )diff --git a/packages/core/src/repowise/core/analysis/test_impact.py b/packages/core/src/repowise/core/analysis/test_impact.pyindex 727dffd5d..f95a6862e 100644--- a/packages/core/src/repowise/core/analysis/test_impact.py+++ b/packages/core/src/repowise/core/analysis/test_impact.py@@ -15,6 +15,7 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.coverage.freshness import coverage_freshnessfrom repowise.core.exclusion import is_excludedfrom repowise.core.persistence.models import Repository@@ -48,11 +49,10 @@ def _freshness("ingested_commit": ingested_commit,"indexed_commit": indexed_commit,}+ status = coverage_freshness(ingested_commit, indexed_commit)return {- "status": "current" if ingested_commit == indexed_commit else "stale",- "reason": None- if ingested_commit == indexed_commit- else "coverage_commit_differs_from_index",+ "status": status,+ "reason": None if status == "current" else "coverage_commit_differs_from_index","ingested_commit": ingested_commit,"indexed_commit": indexed_commit,}diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 0ec307ac9..6265895f9 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -18,8 +18,11 @@ from . import ( # noqa: F401refactoring,)from .coverage import (+ file_coverage_from_row,get_coverage_summary,load_coverage_for_repo,+ load_coverage_map,+ load_file_coverage,save_coverage_files,)from .coverage_map import (@@ -119,6 +122,7 @@ __all__ = ["covered_source_files","doc_drift_findings_stored","doc_drift_references_stored",+ "file_coverage_from_row","files_covered_by","finalize_performance_opportunities","finalize_refactoring_opportunities",@@ -153,6 +157,8 @@ __all__ = ["list_performance_opportunities","list_refactoring_opportunities","load_coverage_for_repo",+ "load_coverage_map",+ "load_file_coverage","opportunity_details","performance_facet_counts","performance_file_rollups",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.pyindex c4febe316..98be87791 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py@@ -3,12 +3,15 @@from __future__ import annotationsimport json-from typing import Any, Literal, overload+from typing import TYPE_CHECKING, Any, Literal, overloadfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom ...models import CoverageFile, _new_uuid++if TYPE_CHECKING:+ from repowise.core.analysis.health.coverage.model import FileCoveragefrom .._shared import _BATCH_SIZE@@ -37,23 +40,7 @@ async def save_coverage_files(await session.flush()for i in range(0, len(files), _BATCH_SIZE):- batch = files[i : i + _BATCH_SIZE]- for f in batch:- if hasattr(f, "file_path"):- data = {- "file_path": f.file_path,- "line_coverage_pct": float(f.line_coverage_pct),- "branch_coverage_pct": (- float(f.branch_coverage_pct) if f.branch_coverage_pct is not None else None- ),- "covered_lines_json": json.dumps(list(f.covered_lines or [])),- "total_coverable_lines": int(f.total_coverable_lines or 0),- }- else:- data = dict(f)- if "covered_lines" in data:- data["covered_lines_json"] = json.dumps(list(data.pop("covered_lines") or []))-+ for f in files[i : i + _BATCH_SIZE]:session.add(CoverageFile(id=_new_uuid(),@@ -61,28 +48,44 @@ async def save_coverage_files(source_format=source_format,ingested_commit_sha=ingested_commit_sha,mapping_partial=mapping_partial,- **{- k: v- for k, v in data.items()- if k- not in (- "id",- "repository_id",- "source_format",- "ingested_commit_sha",- "mapping_partial",- )- and hasattr(CoverageFile, k)- },+ **_row_columns(f),))await session.flush()-#: Every column of ``CoverageFile`` except ``covered_lines_json``. That blob is-#: the per-file set of covered line numbers, and it dominates the table: 467 KB-#: of the 549 KB stored for this repo's 1,401 rows. Only the single-file detail-#: view reads it, so every repo-wide caller was hydrating it to throw it away.+#: Columns the ingest sets for every row, so a per-file input never overrides them.+_INGEST_COLUMNS = frozenset(+ {"id", "repository_id", "source_format", "ingested_commit_sha", "mapping_partial"}+)+++def _row_columns(f: Any) -> dict[str, Any]:+ """Per-file column values from a ``FileCoverage`` or a dict of the same shape."""+ if hasattr(f, "file_path"):+ return {+ "file_path": f.file_path,+ "line_coverage_pct": float(f.line_coverage_pct),+ "branch_coverage_pct": (+ float(f.branch_coverage_pct) if f.branch_coverage_pct is not None else None+ ),+ "covered_lines_json": json.dumps(list(f.covered_lines or [])),+ "total_coverable_lines": int(f.total_coverable_lines or 0),+ "coverable_lines_json": json.dumps(list(getattr(f, "coverable_lines", None) or [])),+ }+ data = dict(f)+ for key in ("covered_lines", "coverable_lines"):+ if key in data:+ data[f"{key}_json"] = json.dumps(list(data.pop(key) or []))+ return {+ k: v for k, v in data.items() if k not in _INGEST_COLUMNS and hasattr(CoverageFile, k)+ }+++#: Every column of ``CoverageFile`` except the two line-set blobs+#: (``covered_lines_json``, ``coverable_lines_json``). They dominate the table:+#: the covered set alone was 467 KB of the 549 KB stored for this repo's 1,401+#: rows, and only line-level readers need them._COVERAGE_SCALAR_COLUMNS = (CoverageFile.file_path,CoverageFile.source_format,@@ -125,9 +128,10 @@ async def load_coverage_for_repo("""Coverage rows for a repo, optionally scoped to *file_paths*.``include_covered_lines=False`` returns ``Row`` objects carrying every- column except ``covered_lines_json``. They are attribute-accessed exactly+ column except the two line-set blobs. They are attribute-accessed exactlylike the ORM entities, so a caller that reads named fields needs no change- — but a caller that touches ``covered_lines_json`` must ask for it.+ — but a caller that touches ``covered_lines_json`` or+ ``coverable_lines_json`` must ask for them."""q = (select(CoverageFile)@@ -142,6 +146,55 @@ async def load_coverage_for_repo(return list(result.all())+def _line_list(raw: str | None) -> list[int]:+ try:+ return [int(n) for n in json.loads(raw)] if raw else []+ except (ValueError, TypeError):+ return []+++def file_coverage_from_row(row: Any) -> FileCoverage:+ """A stored row as the parsers' ``FileCoverage``, the one row-to-model conversion."""+ from repowise.core.analysis.health.coverage.model import FileCoverage++ return FileCoverage(+ file_path=row.file_path,+ line_coverage_pct=row.line_coverage_pct,+ branch_coverage_pct=row.branch_coverage_pct,+ covered_lines=_line_list(row.covered_lines_json),+ total_coverable_lines=row.total_coverable_lines or 0,+ coverable_lines=_line_list(getattr(row, "coverable_lines_json", None)),+ )+++async def load_file_coverage(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+) -> dict[str, FileCoverage]:+ """Stored coverage as ``{path: FileCoverage}``, line sets included."""+ rows = await load_coverage_for_repo(session, repository_id, file_paths=file_paths)+ return {row.file_path: file_coverage_from_row(row) for row in rows}+++async def load_coverage_map(session: AsyncSession, repository_id: str) -> dict[str, dict]:+ """Stored coverage in the shape ``HealthAnalyzer`` takes as ``coverage_map``."""+ from repowise.core.analysis.health.coverage.model import coverage_map_entry++ # Health scoring never reads the executable-line set, so its blob is not+ # loaded (it is at least as large as the covered set).+ result = await session.execute(+ select(*_COVERAGE_SCALAR_COLUMNS, CoverageFile.covered_lines_json).where(+ CoverageFile.repository_id == repository_id+ )+ )+ return {+ row.file_path: coverage_map_entry(file_coverage_from_row(row), row.source_format)+ for row in result.all()+ }++async def get_coverage_summary(session: AsyncSession,repository_id: str,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex c76a4a2f7..f32e0dff2 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -2203,6 +2203,10 @@ class CoverageFile(Base):branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)covered_lines_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")total_coverable_lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ # Lines the report calls executable, hit or not. Patch coverage needs it to+ # tell an uncovered changed line from a changed comment. "[]" means the+ # report did not say (or the row predates the column), never "none".+ coverable_lines_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")# True when the ingest that wrote these rows mapped fewer than half of the# report's files to the repo tree (severe path-mapping loss). The rows are# still written — a partial report is better than none — but consumersdiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 487bc647f..8df3eb643 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -590,7 +590,6 @@ async def load_stored_coverage_map(repo_path: Any, *, log: LogFn | None = None)established safe default."""log = log or _noop_log- import jsonif not (Path(repo_path) / ".repowise" / "wiki.db").is_file():return {}@@ -602,7 +601,7 @@ async def load_stored_coverage_map(repo_path: Any, *, log: LogFn | None = None))from repowise.core.persistence.crud import (get_repository_by_path,- load_coverage_for_repo,+ load_coverage_map,)from repowise.core.persistence.database import resolve_db_url@@ -612,21 +611,9 @@ async def load_stored_coverage_map(repo_path: Any, *, log: LogFn | None = None)repo = await get_repository_by_path(session, str(repo_path))if repo is None:return {}- rows = await load_coverage_for_repo(session, repo.id)+ coverage_map = await load_coverage_map(session, repo.id)finally:await engine.dispose()- coverage_map: dict[str, dict] = {}- for row in rows:- try:- covered = json.loads(row.covered_lines_json) if row.covered_lines_json else []- except (ValueError, TypeError):- covered = []- coverage_map[row.file_path] = {- "line_coverage_pct": row.line_coverage_pct,- "branch_coverage_pct": row.branch_coverage_pct,- "covered_lines": covered,- "total_coverable_lines": row.total_coverable_lines or 0,- }return coverage_mapexcept Exception as exc:log(f"[yellow]Stored coverage unavailable: {exc}[/yellow]")diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex d83c5288c..7e9c6de81 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -140,6 +140,8 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"fix_history","branch_overlap","cross_repo",+ "patch_coverage.files[]",+ "patch_coverage","impacted_tests","health_delta.limits","health_delta.skipped",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.pyindex bb5407d8f..8a128cd4b 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@@ -148,6 +148,7 @@ async def get_change_risk(change is not cleared.``impacted_tests`` keeps measured coverage and inferred candidates distinct.+ ``patch_coverage`` is the share of changed executable lines stored coverage ran.``fix_history`` is the changed files' bug-fix record, ``overlap`` the pastfixes on these exact lines. ``branch_overlap`` names other branches editingthem. ``diff_shape`` is one line on size, not a danger verdict. An empty@@ -228,6 +229,11 @@ async def get_change_risk(payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error, collector)+ patch = await _patch_coverage_block(+ ctx, changed, changed_error, revspec, result, collector+ )+ if patch is not None:+ payload["patch_coverage"] = patchprior_fixes = await _prior_fixes_block(ctx, changed)if prior_fixes is not None:# One fix record, not two. The blocks answered the same question@@ -1086,6 +1092,59 @@ async def _inferred_impacted(return block+async def _patch_coverage_block(+ ctx: Any,+ changed: dict[str, set[int]],+ changed_error: tuple[str, str] | None,+ revspec: str | None,+ result: Any,+ collector: OmissionCollector,+) -> dict[str, Any] | None:+ """Share of the change's executable lines the stored coverage ran, or ``None``.++ The same computation ``repowise coverage check`` gates on, read from the+ coverage the index stores. ``None`` when there is no index, no stored+ coverage, or no readable change: ``impacted_tests`` already says why.+ ``files`` lists only the files that need attention, capped; the totals and+ ``file_counts`` still count every file.+ """+ from repowise.core import git_refs+ from repowise.core.analysis.change_risk.features import revspec_head+ from repowise.core.analysis.patch_coverage import attention_rows, stored_patch_coverage+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None or changed_error is not None or not changed:+ return None+ # Uncommitted edits were never measured, so no commit can vouch for them.+ head_commit = None+ if not result.working_tree:+ head_commit = git_refs.resolve(str(ctx.path), revspec_head(revspec)) or None+ try:+ async with get_session(session_factory) as session:+ patch = await stored_patch_coverage(+ session,+ (await _get_repo(session)).id,+ changed,+ label=result.features.ref,+ head_commit=head_commit,+ )+ except (LookupError, SQLAlchemyError):+ return None+ if patch is None:+ return None+ block = patch.to_dict()+ rows = [f.to_dict() for f in attention_rows(patch)]+ if len(rows) > _IMPACTED_TESTS_LIMIT:+ collector.add(+ f"patch_coverage.files beyond cap={_IMPACTED_TESTS_LIMIT} "+ f"({len(rows) - _IMPACTED_TESTS_LIMIT} dropped)",+ [row["file_path"] for row in rows[_IMPACTED_TESTS_LIMIT:]],+ )+ block["files"] = rows[:_IMPACTED_TESTS_LIMIT]+ return block++async def _impacted_tests_block(ctx: Any,changed: dict[str, set[int]],diff --git a/packages/server/src/repowise/server/routers/_local_git.py b/packages/server/src/repowise/server/routers/_local_git.pynew file mode 100644index 000000000..e03a4d4a8--- /dev/null+++ b/packages/server/src/repowise/server/routers/_local_git.py@@ -0,0 +1,39 @@+"""A repository's local checkout, for routes that run git against it."""++from __future__ import annotations++import os+import subprocess++from fastapi import Depends, HTTPException+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence import crud+from repowise.core.persistence.models import Repository+from repowise.server.deps import get_db_session+++async def resolve_local_repo(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> Repository:+ """Resolve a repository with a usable local checkout, or raise 404."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None or not repo.local_path or not os.path.isdir(repo.local_path):+ raise HTTPException(status_code=404, detail="Repository not found")+ return repo+++def revision_exists(repo_path: str, rev: str) -> bool:+ # Reject option-shaped input outright; git refuses ref names starting+ # with "-", so this loses no legitimate revision and keeps user input+ # from ever being parsed as a git flag here or downstream.+ if not rev or rev.startswith("-"):+ return False+ result = subprocess.run(+ ["git", "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"],+ cwd=repo_path,+ capture_output=True,+ text=True,+ )+ return result.returncode == 0diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex 4b36209bd..6420fa831 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -14,6 +14,7 @@ any ratio built from it would be a coverage figure the data cannot support.from __future__ import annotations+import asyncioimport jsonfrom typing import Any@@ -27,7 +28,10 @@ from repowise.core.analysis.test_reachability import (tests_reaching_by_tier,)from repowise.core.persistence import crud+from repowise.core.persistence.models import Repositoryfrom repowise.server.deps import get_db_session+from repowise.server.routers._local_git import resolve_local_repo, revision_exists+from repowise.server.schemas.patch_coverage import PatchCoverageResponsefrom ._router import router@@ -373,3 +377,45 @@ async def health_tests_reaching("total": total,"truncated": total > len(reached.tests),}+++def _read_change(local_path: str, base: str, head: str) -> tuple[dict[str, set[int]], str, str]:+ """``(changed lines, label, head sha)`` for ``base...head``; git only, run off the loop."""+ import subprocess++ from repowise.core import git_refs+ from repowise.core.analysis.changed_lines import changed_lines++ if not revision_exists(local_path, base) or not revision_exists(local_path, head):+ raise HTTPException(status_code=400, detail=f"Unknown revision in {base!r}...{head!r}")+ try:+ changed, label = changed_lines(local_path, f"{base}...{head}")+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except subprocess.TimeoutExpired as exc:+ raise HTTPException(status_code=504, detail="git timed out reading the change") from exc+ return changed, label, git_refs.resolve(local_path, head)+++ "/api/repos/{repo_id}/health/coverage/patch",+ response_model=PatchCoverageResponse | None,+)+async def health_coverage_patch(+ base: str = Query(..., description="Base revision; the change is what head did since"),+ head: str = Query("HEAD", description="Head revision"),+ repo: Repository = Depends(resolve_local_repo),+ session: AsyncSession = Depends(get_db_session),+) -> PatchCoverageResponse | None:+ """Patch coverage of ``base...head`` from the coverage the index stores.++ The computation ``repowise coverage check`` gates on. ``null`` when no+ coverage has been ingested, which is not the same as 0%.+ """+ from repowise.core.analysis.patch_coverage import stored_patch_coverage++ changed, label, head_sha = await asyncio.to_thread(_read_change, repo.local_path, base, head)+ patch = await stored_patch_coverage(+ session, repo.id, changed, label=label, head_commit=head_sha or None+ )+ return PatchCoverageResponse.model_validate(patch.to_dict()) if patch is not None else Nonediff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex ee7f73816..82f2f14ee 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -3,8 +3,6 @@from __future__ import annotationsimport json-import os-import subprocessfrom collections import Counterfrom datetime import datetime, timedelta@@ -41,6 +39,7 @@ from repowise.core.persistence.models import GitCommit, GitMetadata, Repositoryfrom repowise.core.persistence.sql import is_missing_tablefrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server.tool_risk import _check_test_gap+from repowise.server.routers._local_git import resolve_local_repo, revision_existsfrom repowise.server.schemas import (AgentTrendBucket,AgentTrendResponse,@@ -728,32 +727,6 @@ async def get_reviewer_suggestions(return ReviewerSuggestionsResponse(paths=paths, suggestions=suggestions)-async def _resolve_local_repo(- repo_id: str,- session: AsyncSession = Depends(get_db_session),-) -> Repository:- """Resolve a repository with a usable local checkout, or raise 404."""- repo = await crud.get_repository(session, repo_id)- if repo is None or not repo.local_path or not os.path.isdir(repo.local_path):- raise HTTPException(status_code=404, detail="Repository not found")- return repo---def _revision_exists(repo_path: str, rev: str) -> bool:- # Reject option-shaped input outright; git refuses ref names starting- # with "-", so this loses no legitimate revision and keeps user input- # from ever being parsed as a git flag here or downstream.- if not rev or rev.startswith("-"):- return False- result = subprocess.run(- ["git", "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"],- cwd=repo_path,- capture_output=True,- text=True,- )- return result.returncode == 0--@router.get("/{repo_id}/risk/range", response_model=RiskRangeResponse)def get_risk_range(repo_id: str,@@ -764,7 +737,7 @@ def get_risk_range(ge=0,description="Recent commits to sample for the repo-relative percentile (0 skips it)",),- repo: Repository = Depends(_resolve_local_repo),+ repo: Repository = Depends(resolve_local_repo),) -> RiskRangeResponse:"""Assess a ``base..head`` range from its live diff shape and history.@@ -775,7 +748,7 @@ def get_risk_range(the threadpool, since it shells out to git."""local_path = repo.local_path- if not _revision_exists(local_path, base) or not _revision_exists(local_path, head):+ if not revision_exists(local_path, base) or not revision_exists(local_path, head):raise HTTPException(status_code=400, detail=f"Unknown revision in range {base!r}..{head!r}")try:diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 5608c9f05..db7a4f3ab 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -217,6 +217,12 @@ if TYPE_CHECKING:PageVersionResponse,)from .pagination import Paginated+ from .patch_coverage import (+ PatchCoverageFile,+ PatchCoverageFileCounts,+ PatchCoverageResponse,+ PatchCoverageScope,+ )from .refactoring import (RefactoringOpportunitiesResponse,RefactoringOpportunityDetailResponse,@@ -488,6 +494,12 @@ _EXPORTS: dict[str, tuple[str, ...]] = {),"pages": ("JobResponse", "PageResponse", "PageSummaryResponse", "PageVersionResponse"),"pagination": ("Paginated",),+ "patch_coverage": (+ "PatchCoverageFile",+ "PatchCoverageFileCounts",+ "PatchCoverageResponse",+ "PatchCoverageScope",+ ),"refactoring": ("RefactoringOpportunitiesResponse","RefactoringOpportunityDetailResponse",@@ -743,6 +755,10 @@ __all__ = ["PageSummaryResponse","PageVersionResponse","Paginated",+ "PatchCoverageFile",+ "PatchCoverageFileCounts",+ "PatchCoverageResponse",+ "PatchCoverageScope","PopulationBreakdown","ProviderEntry","ProviderStatusResponse",diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.pynew file mode 100644index 000000000..f5797c764--- /dev/null+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py@@ -0,0 +1,63 @@+"""Patch coverage over the wire: ``PatchCoverage.to_dict()``, typed.++Mirrors ``repowise coverage check --format json`` field for field, so a client+reading this endpoint and a CI job reading the command see one shape.+"""++from __future__ import annotations++from pydantic import BaseModel, ConfigDict++from repowise.core.analysis.health.coverage.freshness import FreshnessStatus+from repowise.core.analysis.patch_coverage.compute import FileStatus, GateStatus+++class _Strict(BaseModel):+ # A key ``to_dict`` gains must fail validation, not vanish from the API.+ model_config = ConfigDict(extra="forbid")+++class PatchCoverageFile(_Strict):+ file_path: str+ status: FileStatus+ changed_line_count: int+ coverable_line_count: int+ covered_line_count: int+ #: 0-100, floored to two decimals; null when no changed line is executable.+ patch_coverage_pct: float | None+ #: Inclusive ``[start, end]`` runs of changed, executable, unexecuted lines.+ uncovered_ranges: list[list[int]]+++class PatchCoverageFileCounts(_Strict):+ measured: int+ not_in_report: int+ no_line_data: int+ no_coverable_changes: int+ out_of_scope: int+++class PatchCoverageScope(_Strict):+ label: str+ source_formats: list[str]+ reports: list[str]+ #: Null when unknown: stored coverage keeps only the paths that matched.+ report_path_count: int | None+ unmatched_report_path_count: int | None+ #: Fewer than half the report's paths matched this repository.+ mapping_partial: bool+ measured_commit: str | None+ #: ``stale`` when the coverage was measured at another commit than the+ #: change's head: the figure still computes but describes other code.+ freshness: FreshnessStatus+++class PatchCoverageResponse(_Strict):+ patch_coverage_pct: float | None+ covered_line_count: int+ coverable_line_count: int+ threshold: float | None+ gate: GateStatus+ file_counts: PatchCoverageFileCounts+ files: list[PatchCoverageFile]+ scope: PatchCoverageScopediff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 28af11a54..8468a2087 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2138,6 +2138,46 @@ export interface Paginated_SymbolResponse_ {next_offset?: number | null;}+export interface PatchCoverageFile {+ file_path: string;+ status: "measured" | "not_in_report" | "no_line_data" | "no_coverable_changes";+ changed_line_count: number;+ coverable_line_count: number;+ covered_line_count: number;+ patch_coverage_pct: number | null;+ uncovered_ranges: number[][];+}++export interface PatchCoverageFileCounts {+ measured: number;+ not_in_report: number;+ no_line_data: number;+ no_coverable_changes: number;+ out_of_scope: number;+}++export interface PatchCoverageResponse {+ patch_coverage_pct: number | null;+ covered_line_count: number;+ coverable_line_count: number;+ threshold: number | null;+ gate: "pass" | "fail" | "no_data" | "not_set";+ file_counts: PatchCoverageFileCounts;+ files: PatchCoverageFile[];+ scope: PatchCoverageScope;+}++export interface PatchCoverageScope {+ label: string;+ source_formats: string[];+ reports: string[];+ report_path_count: number | null;+ unmatched_report_path_count: number | null;+ mapping_partial: boolean;+ measured_commit: string | null;+ freshness: "current" | "stale" | "unknown";+}+/*** What the map is counting.*diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsxnew file mode 100644index 000000000..76556c704--- /dev/null+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx@@ -0,0 +1,77 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import type { PatchCoverageResponse } from "@repowise-dev/types/generated/http";+import {+ PatchCoverageSummary,+ floorPct,+ formatLineRanges,+} from "../../src/health/patch-coverage-summary.js";++function coverage(fileCount: number): PatchCoverageResponse {+ return {+ patch_coverage_pct: 50,+ covered_line_count: fileCount,+ coverable_line_count: fileCount * 2,+ threshold: null,+ gate: "not_set",+ file_counts: {+ measured: fileCount,+ not_in_report: 0,+ no_line_data: 0,+ no_coverable_changes: 0,+ out_of_scope: 0,+ },+ files: Array.from({ length: fileCount }, (_, i) => ({+ file_path: `src/f${i}.ts`,+ status: "measured" as const,+ changed_line_count: 2,+ coverable_line_count: 2,+ covered_line_count: 1,+ patch_coverage_pct: 50,+ uncovered_ranges: [[i + 1, i + 1]],+ })),+ scope: {+ label: "coverage.xml",+ source_formats: ["cobertura"],+ reports: ["coverage.xml"],+ report_path_count: fileCount,+ unmatched_report_path_count: 0,+ measured_commit: "abcdef1234",+ mapping_partial: false,+ freshness: "current",+ },+ };+}++describe("patch coverage formatting", () => {+ it("floors to one decimal so a near miss never reads as full", () => {+ expect(floorPct(99.99)).toBe("99.9");+ expect(floorPct(66.66)).toBe("66.6");+ expect(floorPct(57.3)).toBe("57.3");+ expect(floorPct(100)).toBe("100.0");+ });++ it("prints single lines bare and runs as a span", () => {+ expect(+ formatLineRanges([+ [3, 3],+ [7, 9],+ ]),+ ).toBe("3, 7-9");+ });+});++describe("PatchCoverageSummary", () => {+ it("lists ten files with gaps and counts the rest", () => {+ render(<PatchCoverageSummary coverage={coverage(12)} />);+ expect(screen.getByText("src/f9.ts")).toBeTruthy();+ expect(screen.queryByText("src/f10.ts")).toBeNull();+ expect(screen.getByText("and 2 more")).toBeTruthy();+ });++ it("stays quiet about freshness when coverage is current", () => {+ render(<PatchCoverageSummary coverage={coverage(1)} />);+ expect(screen.getByText("1 of 2 changed executable lines covered")).toBeTruthy();+ expect(screen.queryByText(/measured at/)).toBeNull();+ });+});diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex 9812ff299..c44947389 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -35,6 +35,7 @@ export * from "./hidden-coupling-list";export * from "./defect-accuracy-card";export * from "./code-health-lede";export * from "./coverage-lede";+export * from "./patch-coverage-summary";export * from "./severity-mark";export * from "./code-health-adapter";export * from "./file-opportunity";diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsxnew file mode 100644index 000000000..41abcfa21--- /dev/null+++ b/packages/ui/src/health/patch-coverage-summary.tsx@@ -0,0 +1,195 @@+/**+ * Patch coverage of one change: how many of the lines it changed that can+ * execute the stored test coverage actually ran, and where the rest are.+ *+ * A verdict sentence, not a figure with a band. There is no threshold here to+ * colour against, and a gate belongs to CI (`repowise coverage check`), so the+ * only marked state is stale evidence: coverage measured at another commit+ * describes other code, and the line numbers below it may not line up.+ */++import type {+ PatchCoverageFile,+ PatchCoverageResponse,+} from "@repowise-dev/types/generated/http";++export interface PatchCoverageSummaryProps {+ coverage: PatchCoverageResponse;+ /** Makes each listed path open its file. */+ onOpenFile?: (path: string) => void;+}++/** Files with uncovered lines listed before the rest collapse into a count. */+const MAX_FILES = 10;++/** Floors to one decimal so 99.99 never reads as 100.0. The epsilon absorbs+ * binary error (57.3 * 10 is 572.99...) that would otherwise floor a step low. */+export function floorPct(pct: number): string {+ return (Math.floor(pct * 10 + 1e-9) / 10).toFixed(1);+}++/** `[[3, 3], [7, 9]]` as `3, 7-9`. */+export function formatLineRanges(ranges: number[][]): string {+ return ranges+ .map(([start, end]) =>+ end == null || end === start ? `${start}` : `${start}-${end}`,+ )+ .join(", ");+}++function plural(n: number, word: string): string {+ return `${n} ${word}${n === 1 ? "" : "s"}`;+}++export function PatchCoverageSummary({+ coverage,+ onOpenFile,+}: PatchCoverageSummaryProps) {+ const pct = coverage.patch_coverage_pct;+ const uncovered = coverage.files.filter(+ (f) => f.status === "measured" && f.uncovered_ranges.length > 0,+ );+ const unmeasured = coverage.files.filter(+ (f) => f.status === "not_in_report" || f.status === "no_line_data",+ );+ const measuredAt = coverage.scope.measured_commit?.slice(0, 7) ?? null;++ return (+ <div className="flex flex-col gap-1.5">+ <p className="text-[15px] text-[var(--color-text-secondary)]">+ {pct == null ? (+ // Unknown is a sentence, never 0%: nothing the report measured changed.+ <>+ <span className="font-semibold text-[var(--color-text-primary)]">+ Patch coverage not measured+ </span>{" "}+ · no changed line is an executable line the coverage report measured+ </>+ ) : (+ <>+ <span className="font-semibold text-[var(--color-text-primary)]">+ Patch coverage{" "}+ <span className="tabular-nums">{floorPct(pct)}%</span>+ </span>{" "}+ ·{" "}+ <span className="tabular-nums">+ {coverage.covered_line_count} of{" "}+ {plural(coverage.coverable_line_count, "changed executable line")}{" "}+ covered+ </span>+ </>+ )}+ </p>++ {coverage.scope.freshness === "stale" && (+ <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <span+ aria-hidden+ className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]"+ />+ <span>+ <span className="sr-only">Stale: </span>+ Coverage was measured at{" "}+ {measuredAt ? (+ <code className="font-mono">{measuredAt}</code>+ ) : (+ "another commit"+ )}+ , not at this change's head+ </span>+ </p>+ )}++ {coverage.scope.mapping_partial && (+ <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <span+ aria-hidden+ className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]"+ />+ <span>+ Most report paths did not match this repository, so this covers a fragment+ </span>+ </p>+ )}++ {uncovered.length > 0 && (+ <ul className="mt-1 flex flex-col gap-0.5">+ {uncovered.slice(0, MAX_FILES).map((f) => (+ <FileRow+ key={f.file_path}+ file={f}+ trailing={`lines ${formatLineRanges(f.uncovered_ranges)}`}+ onOpenFile={onOpenFile}+ />+ ))}+ {uncovered.length > MAX_FILES && (+ <li className="px-1.5 pt-1 text-xs text-[var(--color-text-tertiary)]">+ and {uncovered.length - MAX_FILES} more+ </li>+ )}+ </ul>+ )}++ {unmeasured.length > 0 && (+ <details className="group mt-1">+ <summary className="cursor-pointer text-xs text-[var(--color-text-tertiary)]">+ {plural(unmeasured.length, "changed file")} the coverage report does+ not measure+ </summary>+ <ul className="mt-1 flex flex-col gap-0.5">+ {unmeasured.map((f) => (+ <FileRow+ key={f.file_path}+ file={f}+ trailing={+ f.status === "not_in_report" ? "not in report" : "no line data"+ }+ onOpenFile={onOpenFile}+ />+ ))}+ </ul>+ </details>+ )}+ </div>+ );+}++function FileRow({+ file,+ trailing,+ onOpenFile,+}: {+ file: PatchCoverageFile;+ trailing: string;+ onOpenFile: ((path: string) => void) | undefined;+}) {+ const body = (+ <>+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-[var(--color-text-primary)]">+ {file.file_path}+ </span>+ <span className="shrink-0 font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {trailing}+ </span>+ </>+ );+ const row = "flex w-full items-center gap-2 rounded px-1.5 py-1 text-left";+ return (+ <li>+ {onOpenFile ? (+ <button+ type="button"+ onClick={() => onOpenFile(file.file_path)}+ title={`Open ${file.file_path}`}+ className={`${row} transition-colors hover:bg-[var(--color-bg-surface)]`}+ >+ {body}+ </button>+ ) : (+ <div className={row} title={file.file_path}>+ {body}+ </div>+ )}+ </li>+ );+}diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.tsindex 767fcc99e..145315f11 100644--- a/packages/vscode/src/core/webviewApi.ts+++ b/packages/vscode/src/core/webviewApi.ts@@ -29,7 +29,7 @@ import {} from "@repowise-dev/api-client/refactoring";import { listDecisions } from "@repowise-dev/api-client/decisions";import { getPageById, listAllPages } from "@repowise-dev/api-client/pages";-import { getRiskRange } from "@repowise-dev/api-client/risk";+import { getPatchCoverage, getRiskRange } from "@repowise-dev/api-client/risk";import {buildRefactoringOpportunityPrompt,buildRefactoringPlanPrompt,@@ -347,9 +347,13 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostAp.get<string>("risk.baseBranch", "").trim();const base = configured || ctx.repo?.default_branch || "main";- const result = await getRiskRange(id, { base, head: "HEAD" });+ const range = { base, head: "HEAD" };+ const [result, patchCoverage] = await Promise.all([+ getRiskRange(id, range),+ getPatchCoverage(id, range).catch(() => null),+ ]);const branch = await getCurrentBranchName(ctx.workspace.repoRoot ?? "");- return { base, branch, result };+ return { base, branch, result, patchCoverage };},// Change impact: reads the working tree, so it tracks the live change setdiff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.tsindex 1d702f055..95086ffcb 100644--- a/packages/vscode/src/shared/webviewMessages.ts+++ b/packages/vscode/src/shared/webviewMessages.ts@@ -34,6 +34,7 @@ import type {PageResponse,} from "@repowise-dev/api-client/types";import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";+import type { PatchCoverageResponse } from "@repowise-dev/types/generated/http";import type { ReviewerSuggestion } from "@repowise-dev/api-client/types";import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";import type { ArchitectureView } from "@repowise-dev/ui/c4";@@ -219,6 +220,12 @@ export interface RiskRangeReport {base: string;branch: string | null;result: RiskRangeResponse;+ /**+ * Patch coverage of the same base...HEAD range. Null when no coverage was+ * ingested, or when the fetch failed (an older server has no endpoint): the+ * panel then shows nothing rather than an error.+ */+ patchCoverage: PatchCoverageResponse | null;}/**diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 18f49e977..6f41eb058 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -61,6 +61,55 @@ const REPORT: RiskRangeReport = {},],},+ patchCoverage: null,+};++const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {+ patch_coverage_pct: 66.66,+ covered_line_count: 2,+ coverable_line_count: 3,+ threshold: null,+ gate: "not_set",+ file_counts: {+ measured: 1,+ not_in_report: 1,+ no_line_data: 0,+ no_coverable_changes: 0,+ out_of_scope: 0,+ },+ files: [+ {+ file_path: "src/core.ts",+ status: "measured",+ changed_line_count: 5,+ coverable_line_count: 3,+ covered_line_count: 2,+ patch_coverage_pct: 66.66,+ uncovered_ranges: [+ [3, 3],+ [7, 9],+ ],+ },+ {+ file_path: "src/new.ts",+ status: "not_in_report",+ changed_line_count: 4,+ coverable_line_count: 0,+ covered_line_count: 0,+ patch_coverage_pct: null,+ uncovered_ranges: [],+ },+ ],+ scope: {+ label: "coverage.xml",+ source_formats: ["cobertura"],+ reports: ["coverage.xml"],+ report_path_count: 10,+ unmatched_report_path_count: 0,+ measured_commit: "abcdef1234567890",+ mapping_partial: false,+ freshness: "stale",+ },};const REPO: RepoInit = {@@ -403,6 +452,77 @@ describe("risk App", () => {expect(screen.queryByText(/test recommendation/)).toBeNull();});+ it("reports patch coverage of the range with a denominator and its gaps", async () => {+ const riskRange = vi+ .fn()+ .mockResolvedValue({ ...REPORT, patchCoverage: PATCH_COVERAGE });+ const openFile = vi.fn();+ render(+ <App+ host={makeHost(riskRange, undefined, { openFile })}+ repo={REPO}+ params={{}}+ refreshToken={0}+ />,+ );++ // Floored, never rounded up: 66.66 reads 66.6.+ expect(await screen.findByText("66.6%")).toBeTruthy();+ expect(+ screen.getByText("2 of 3 changed executable lines covered"),+ ).toBeTruthy();+ expect(screen.getByText("abcdef1")).toBeTruthy();+ expect(screen.getByText(/not at this change's head/)).toBeTruthy();+ expect(screen.getByText("lines 3, 7-9")).toBeTruthy();+ expect(screen.getByText("not in report")).toBeTruthy();++ fireEvent.click(screen.getByTitle("Open src/core.ts"));+ expect(openFile).toHaveBeenCalledWith("src/core.ts");+ });++ it("shows no patch coverage when none was ingested", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ render(+ <App+ host={makeHost(riskRange)}+ repo={REPO}+ params={{}}+ refreshToken={0}+ />,+ );++ await screen.findByText("Elevated");+ expect(screen.queryByText(/Patch coverage/)).toBeNull();+ });++ it("says unknown patch coverage in words, never 0%", async () => {+ const riskRange = vi.fn().mockResolvedValue({+ ...REPORT,+ patchCoverage: {+ ...PATCH_COVERAGE,+ patch_coverage_pct: null,+ covered_line_count: 0,+ coverable_line_count: 0,+ files: [PATCH_COVERAGE.files[1]],+ scope: { ...PATCH_COVERAGE.scope, freshness: "current" },+ },+ });+ render(+ <App+ host={makeHost(riskRange)}+ repo={REPO}+ params={{}}+ refreshToken={0}+ />,+ );++ expect(+ await screen.findByText("Patch coverage not measured"),+ ).toBeTruthy();+ expect(screen.queryByText("0.0%")).toBeNull();+ expect(screen.queryByText(/not at this change's head/)).toBeNull();+ });+it("shows a clean-tree empty state when nothing changed", async () => {const riskRange = vi.fn().mockResolvedValue(REPORT);render(diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex f0715197d..93c02325d 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -26,6 +26,7 @@ import { Badge, Button } from "@repowise-dev/ui/ui";import { EmptyState } from "@repowise-dev/ui/shared";import { PageLede } from "@repowise-dev/ui/shared/page-lede";import { OverviewSection } from "@repowise-dev/ui/overview";+import { PatchCoverageSummary } from "@repowise-dev/ui/health/patch-coverage-summary";import type { ViewProps } from "../../runtime/mount";import type { WebviewHost } from "../../runtime/rpc";import type {@@ -181,6 +182,20 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {<><ScoreHero report={report} /><VerdictStrip impact={impact} cochangeFloor={cochangeFloor} />+ {report.patchCoverage && (+ // Absent (no coverage ingested, or an older server) renders+ // nothing: an unmeasured change is not a finding.+ <section className="flex flex-col gap-1 border-t border-[var(--color-border-default)] pt-6 sm:pt-8">+ <PatchCoverageSummary+ coverage={report.patchCoverage}+ onOpenFile={(path) => host.openFile(path)}+ />+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Committed changes against{" "}+ <code>{report.base}</code>; uncommitted edits are not counted.+ </p>+ </section>+ )}<ChangeImpactimpact={impact}loading={impactLoading}diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.pyindex 62e19e0c0..f2cd9a431 100644--- a/tests/unit/cli/test_coverage_check_cmd.py+++ b/tests/unit/cli/test_coverage_check_cmd.py@@ -189,3 +189,26 @@ def test_flag_overrides_a_bad_config_threshold(repo) -> None:)report = _lcov(repo, {2: 1, 3: 1})assert _run(repo, "main...feat", "--report", report, "--fail-under", "50").exit_code == 0+++def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:+ from repowise.cli.commands.coverage_check_cmd import _CannotEvaluateError, _gateable+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.analysis.patch_coverage import PatchScope, compute_patch_coverage++ def _pc(fc, freshness):+ return compute_patch_coverage(+ {"a.py": {1}}, {"a.py": fc}, threshold=80, scope=PatchScope(freshness=freshness)+ )++ fresh = _pc(file_coverage("a.py", [1], [1]), "current")+ assert _gateable(fresh) is fresh+ with pytest.raises(_CannotEvaluateError) as stale:+ _gateable(_pc(file_coverage("a.py", [1], [1]), "stale"))+ assert stale.value.code == "coverage_stale"+ with pytest.raises(_CannotEvaluateError) as legacy:+ _gateable(_pc(file_coverage("a.py", [1], []), "current"))+ assert legacy.value.code == "no_line_data"+ with pytest.raises(_CannotEvaluateError) as missing:+ _gateable(None)+ assert missing.value.code == "no_report"diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.pyindex 90d7a05ad..897cb87ce 100644--- a/tests/unit/cli/test_coverage_cmd.py+++ b/tests/unit/cli/test_coverage_cmd.py@@ -196,6 +196,11 @@ def test_coverage_add_stamps_live_head_not_stored_column(tmp_path, monkeypatch)monkeypatch.setattr(coverage_cmd, "_repo_file_keys", _fake_repo_file_keys)monkeypatch.setattr(coverage_cmd, "get_db_url_for_repo", lambda path: "sqlite:///:memory:")++ async def _no_reconcile(_url):+ return None++ monkeypatch.setattr(coverage_cmd, "reconcile_schema_best_effort", _no_reconcile)monkeypatch.setattr("repowise.core.persistence.create_engine", lambda url: object())monkeypatch.setattr("repowise.core.persistence.create_session_factory", lambda engine: object())monkeypatch.setattr("repowise.core.persistence.get_session", lambda sf: _FakeSession())diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.pyindex 13d72ab15..f44cbd7ac 100644--- a/tests/unit/cli/test_update_persist_reliability.py+++ b/tests/unit/cli/test_update_persist_reliability.py@@ -251,14 +251,12 @@ def test_missing_reingested_coverage_is_authoritative_empty(tmp_path: Path, monklambda *_args, **_kwargs: [],)- coverage_map, files, source_format, authoritative = asyncio.run(- _coverage_for_rescore(object(), "repo", tmp_path, [])- )+ coverage = asyncio.run(_coverage_for_rescore(object(), "repo", tmp_path, []))- assert coverage_map == {}- assert files == []- assert source_format is None- assert authoritative is True+ assert coverage.coverage_map == {}+ assert coverage.files == []+ assert coverage.source_format is None+ assert coverage.authoritative is Truedef test_reingest_with_nothing_to_read_keeps_stored_coverage(tmp_path: Path, monkeypatch) -> None:@@ -271,14 +269,39 @@ def test_reingest_with_nothing_to_read_keeps_stored_coverage(tmp_path: Path, mon)async def _stored(_session, _repo_id):- return []+ return {"a.py": {"source_format": "lcov"}}++ monkeypatch.setattr("repowise.core.persistence.crud.load_coverage_map", _stored)++ coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, []))+ assert coverage.authoritative is False+ assert coverage.source_format == "lcov"- monkeypatch.setattr("repowise.core.persistence.crud.load_coverage_for_repo", _stored)- *_, authoritative = asyncio.run(- persistence._coverage_for_rescore(object(), "repo", tmp_path, [])+def test_reingest_carries_the_partial_mapping_flag(tmp_path: Path, monkeypatch) -> None:+ # A fragment re-ingested on update must be stored as a fragment.+ from repowise.cli.commands.update_cmd import persistence+ from repowise.core.analysis.health.coverage import FileCoverage, ResolvedCoverage++ monkeypatch.setattr(+ "repowise.core.repo_config.load_repo_config",+ lambda _path: {"coverage": {"reingest_on_update": True, "paths": ["c.lcov"]}},+ )+ (tmp_path / "c.lcov").write_text("SF:a.py\nDA:1,1\nend_of_record\n", encoding="utf-8")+ resolved = ResolvedCoverage(+ coverage_map={"a.py": {}},+ files=[FileCoverage("a.py", 100.0, None, [1], 1, [1])],+ source_format="lcov",+ mapping_partial=True,)- assert authoritative is False+ monkeypatch.setattr(+ "repowise.core.analysis.health.coverage.build_coverage_map",+ lambda *_a, **_k: (resolved, []),+ )++ coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, []))+ assert coverage.authoritative is True+ assert coverage.mapping_partial is True# ---------------------------------------------------------------------------diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.pynew file mode 100644index 000000000..4c5c3496b--- /dev/null+++ b/tests/unit/persistence/test_coverage_loaders.py@@ -0,0 +1,110 @@+"""Stored coverage round-trips through the one row-to-model conversion.++``load_file_coverage`` feeds patch coverage, which needs the executable-line+set a report stated; ``load_coverage_map`` feeds health scoring in the shape+the report resolver builds, so stored and freshly parsed coverage score alike.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.coverage import (+ file_coverage,+ parse_lcov,+ resolve_reports,+)+from repowise.core.persistence.crud import (+ load_coverage_map,+ load_file_coverage,+ save_coverage_files,+ upsert_repository,+)++_LCOV = "SF:src/a.py\nDA:1,1\nDA:3,0\nDA:4,2\nBRDA:1,0,0,1\nBRDA:1,0,1,0\nend_of_record\n"+++async def repo(async_session, tmp_path):+ return await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+++async def test_executable_lines_survive_a_round_trip(async_session, repo) -> None:+ fc = file_coverage("src/a.py", [1, 4], [1, 3, 4], branches_found=2, branches_hit=1)+ await save_coverage_files(async_session, repo.id, [fc], source_format="lcov")++ loaded = await load_file_coverage(async_session, repo.id)++ assert loaded == {"src/a.py": fc}+++async def test_stored_map_matches_the_resolved_map(async_session, repo) -> None:+ resolved = resolve_reports([parse_lcov(_LCOV)], {"src/a.py"})+ await save_coverage_files(+ async_session, repo.id, resolved.files, source_format=resolved.source_format+ )++ assert await load_coverage_map(async_session, repo.id) == resolved.coverage_map+++async def test_rows_without_line_sets_load_as_unknown(async_session, repo) -> None:+ # A dict row with no line sets, as written before executable lines were stored.+ await save_coverage_files(+ async_session,+ repo.id,+ [{"file_path": "b.py", "line_coverage_pct": 50.0, "total_coverable_lines": 2}],+ source_format="cobertura",+ )++ (fc,) = (await load_file_coverage(async_session, repo.id)).values()+ assert fc.coverable_lines == []+ assert fc.covered_lines == []+++async def test_stored_patch_coverage_matches_a_fresh_report(async_session, repo) -> None:+ from repowise.core.analysis.patch_coverage import (+ compute_patch_coverage,+ stored_patch_coverage,+ )++ fc = file_coverage("src/a.py", [1, 4], [1, 3, 4])+ other = file_coverage("src/b.py", [1], [1])+ await save_coverage_files(+ async_session, repo.id, [fc, other], source_format="lcov", ingested_commit_sha="abc"+ )+ changed = {"src/a.py": {1, 2, 3}, "src/new.py": {1}, "README.md": {1}}++ stored = await stored_patch_coverage(+ async_session, repo.id, changed, label="main...HEAD", head_commit="abc"+ )+ fresh = compute_patch_coverage(changed, {"src/a.py": fc, "src/b.py": other})++ assert stored is not None+ assert stored.files == fresh.files+ assert stored.out_of_scope_count == fresh.out_of_scope_count == 1+ assert stored.scope.freshness == "current"+ assert stored.scope.source_formats == ("lcov",)+++async def test_stored_patch_coverage_marks_coverage_from_another_commit(+ async_session, repo+) -> None:+ from repowise.core.analysis.patch_coverage import render_markdown, stored_patch_coverage++ fc = file_coverage("src/a.py", [1], [1, 2])+ await save_coverage_files(+ async_session, repo.id, [fc], source_format="lcov", ingested_commit_sha="abcdef0123"+ )+ stored = await stored_patch_coverage(+ async_session, repo.id, {"src/a.py": {2}}, head_commit="fff"+ )++ assert stored is not None+ assert stored.scope.freshness == "stale"+ assert "measured at abcdef0, not at this change's head" in render_markdown(stored)+++async def test_stored_patch_coverage_is_none_without_coverage(async_session, repo) -> None:+ from repowise.core.analysis.patch_coverage import stored_patch_coverage++ assert await stored_patch_coverage(async_session, repo.id, {"a.py": {1}}) is Nonediff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.pyindex ca3d4feec..9e7add53c 100644--- a/tests/unit/server/mcp/test_tool_change_risk.py+++ b/tests/unit/server/mcp/test_tool_change_risk.py@@ -335,3 +335,102 @@ def test_cross_repo_block_never_raises(monkeypatch):_state, "_cross_repo_enricher", _enricher(get_contract_links_as_provider=_boom))assert tool._cross_repo_block("api", ["api/orders.py"]) is None+++# ---------------------------------------------------------------------------+# patch_coverage: the gate's number, read from stored coverage+# ---------------------------------------------------------------------------+++def _collector(tmp_path) -> OmissionCollector:+ return OmissionCollector("get_change_risk", repo_root=tmp_path)+++def _scored(ref: str = "main...HEAD", working_tree: bool = False) -> SimpleNamespace:+ return SimpleNamespace(working_tree=working_tree, features=SimpleNamespace(ref=ref))+++async def test_patch_coverage_is_the_gate_computation_on_stored_coverage(+ monkeypatch, factory, session, tmp_path+):+ from repowise.core import git_refs+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.persistence.crud import save_coverage_files, upsert_repository++ repo = await upsert_repository(session, name="r", local_path=str(tmp_path))+ await save_coverage_files(+ session,+ repo.id,+ [file_coverage("a.py", [1], [1, 2])],+ source_format="lcov",+ ingested_commit_sha="abc",+ )+ await session.commit()++ async def _repo(_session, *_a, **_k):+ return repo++ monkeypatch.setattr(tool, "_get_repo", _repo)+ monkeypatch.setattr(git_refs, "resolve", lambda _p, _rev: "abc")+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)++ block = await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, "main...HEAD", _scored(), _collector(tmp_path)+ )+ assert block["patch_coverage_pct"] == 50.0+ assert block["scope"]["freshness"] == "current"+ assert block["scope"]["label"] == "main...HEAD"++ # Uncommitted edits were never measured: no commit vouches for them.+ dirty = await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, None, _scored(working_tree=True), _collector(tmp_path)+ )+ assert dirty["scope"]["freshness"] == "unknown"+++async def test_patch_coverage_is_absent_without_a_readable_change_or_index(+ monkeypatch, factory, tmp_path+):+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)+ error = ("unknown", "Could not read changed lines from git.")+ c = _collector(tmp_path)+ assert await tool._patch_coverage_block(ctx, {}, error, None, _scored(), c) is None+ no_index = SimpleNamespace(session_factory=None, path=tmp_path)+ assert await tool._patch_coverage_block(no_index, {"a.py": {1}}, None, None, _scored(), c) is None+ _get_repo_raising(monkeypatch, LookupError("no repo"))+ assert await tool._patch_coverage_block(ctx, {"a.py": {1}}, None, None, _scored(), c) is None+++async def test_patch_coverage_files_are_capped_to_what_needs_attention(+ monkeypatch, factory, tmp_path+):+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.analysis.patch_coverage import compute_patch_coverage++ coverage = {f"f{i}.py": file_coverage(f"f{i}.py", [], [1]) for i in range(15)}+ coverage["ok.py"] = file_coverage("ok.py", [1], [1])+ changed = {path: {1} for path in coverage}++ async def _stored(*_a, **_k):+ return compute_patch_coverage(changed, coverage)++ import repowise.core.analysis.patch_coverage as pc_module++ monkeypatch.setattr(pc_module, "stored_patch_coverage", _stored)+ collector = _collector(tmp_path)+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)++ async def _repo(_session, *_a, **_k):+ return SimpleNamespace(id="r")++ monkeypatch.setattr(tool, "_get_repo", _repo)+ block = await tool._patch_coverage_block(ctx, changed, None, "HEAD", _scored(), collector)++ assert len(block["files"]) == 10+ assert all(f["status"] == "measured" and f["uncovered_ranges"] for f in block["files"])+ # Totals still count every file, the fully covered one included.+ assert block["file_counts"]["measured"] == 16+ assert block["coverable_line_count"] == 16diff --git a/tests/unit/server/test_patch_coverage_schema.py b/tests/unit/server/test_patch_coverage_schema.pynew file mode 100644index 000000000..93e08e9f3--- /dev/null+++ b/tests/unit/server/test_patch_coverage_schema.py@@ -0,0 +1,40 @@+"""The REST model is ``PatchCoverage.to_dict()``, key for key, so they cannot drift."""++from __future__ import annotations++from repowise.core.analysis.health.coverage import file_coverage+from repowise.core.analysis.patch_coverage import PatchScope, compute_patch_coverage+from repowise.server.schemas.patch_coverage import PatchCoverageResponse+++def test_every_to_dict_key_round_trips_through_the_response_model() -> None:+ coverage = {+ "a.py": file_coverage("a.py", [1], [1, 2, 3]),+ "b.py": file_coverage("b.py", [1], []),+ "c.py": file_coverage("c.py", [1], [1]),+ }+ changed = {"a.py": {1, 2, 3}, "b.py": {1}, "c.py": {9}, "new.py": {1}, "t/test_x.py": {1}}+ pc = compute_patch_coverage(+ changed,+ coverage,+ threshold=80,+ scope=PatchScope(+ label="main...HEAD",+ source_formats=("lcov",),+ reports=("lcov.info",),+ report_path_count=4,+ unmatched_report_path_count=1,+ mapping_partial=True,+ measured_commit="abc",+ freshness="stale",+ ),+ )+ wire = pc.to_dict()++ assert {f["status"] for f in wire["files"]} == {+ "measured",+ "no_line_data",+ "no_coverable_changes",+ "not_in_report",+ }+ assert PatchCoverageResponse.model_validate(wire).model_dump() == wirediff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 81a618279..134d78c5d 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -225,3 +225,38 @@ async def test_route_scores_through_the_shared_facade(assert body["fix_history"]["density"] == expected.fix_densityassert body["fix_history"]["percentile"] == expected.fix_percentileassert body["fix_history"]["available"] == expected.fix_history_available+++async def test_patch_coverage_reads_stored_coverage(+ client: AsyncClient, session, git_repo: Path, tmp_path: Path+) -> None:+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.persistence.crud import save_coverage_files++ base = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ head = _commit(git_repo, {"src/a.py": "x = 1\ny = 2\nz = 3\n"}, "feat: add a")+ repo = await _register(client, tmp_path)+ url = f"/api/repos/{repo['id']}/health/coverage/patch"++ # Nothing ingested yet: null, not a zero.+ empty = await client.get(url, params={"base": base})+ assert empty.status_code == 200 and empty.json() is None++ await save_coverage_files(+ session,+ repo["id"],+ [file_coverage("src/a.py", [1, 2], [1, 2, 3])],+ source_format="lcov",+ ingested_commit_sha=head,+ )+ await session.commit()+ data = (await client.get(url, params={"base": base})).json()++ assert data["patch_coverage_pct"] == 66.66+ assert data["files"][0]["uncovered_ranges"] == [[3, 3]]+ assert data["scope"]["freshness"] == "current"+ assert data["scope"]["label"] == f"{base}...HEAD"+ assert (await client.get(url, params={"base": "nope"})).status_code == 400