Skip to content

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

feat(coverage): record each ingest and report its freshness and path matches (#2636)

Raghav Chamadiya4f37f5f3b07e
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 9dd3ea050..fea1fcbf4 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -1199,6 +1199,26 @@ get_health(only=["top_findings"]) # + top_findings_total, au
get_health(only=["kpis"], limit=0) # headline numbers, no rows at all
```
+### Coverage: the stored report and how far to trust it
+
+`include=["coverage"]` returns the stored per-file rows and a repo-wide
+`summary`. Every row carries `covered_line_count` beside
+`total_coverable_lines`; targeted mode adds the `covered_lines` array. The
+summary's `freshness.status` is `current` when the report was measured at the
+indexed commit, `stale` when at another one (its line numbers may describe
+code that has moved), and `unknown` when either commit is missing.
+`report_paths` says how the report's own file entries mapped at ingest
+(`total`, `matched`, `unmatched`, `ambiguous`, and a short `unmatched_sample`);
+it is null for coverage stored before that record existed. `source_formats`
+lists every report format merged.
+
+In targeted mode each row also carries a `decay` block: how many of the
+report's covered lines are unchanged since it ran (`confirmed_lines`) and how
+many have moved since (`invalidated_lines`, now unknown rather than uncovered).
+`decay.drifted` is true once a fifth of a file's measurement has moved. It is a
+per-file statement about lines, separate from the summary's commit-level
+`freshness`.
+
### Performance: one lead, then drill down
A bare `get_health()` carries `performance_directive`: one bounded lead with
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 73d7a6540..add844721 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -115,6 +115,14 @@ the longest trailing-path overlap. A tie refuses to guess and is reported as
ambiguous rather than mapped to the wrong file. If a whole report comes back
unmatched, set `coverage.strip_prefix` in `.repowise/config.yaml`.
+Each ingest records how the report mapped: every format merged, how many of
+its paths matched, did not match or tied, a short sample of the misses, and
+the commit it was measured at. The coverage summary (REST `/health/coverage`,
+MCP `get_health`) reports it as `report_paths`, and its `freshness` says
+whether the measurement matches the indexed commit. Stored patch coverage
+reads the same record, so its report path counts are real numbers rather than
+null.
+
## Building a per-test map
The map needs a report that records *which test* covered each line. Two paths
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index c81bc92b7..72b74484d 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -228,7 +228,7 @@ def coverage_add(
resolved.files,
source_format=resolved.source_format or "lcov",
ingested_commit_sha=head_sha,
- mapping_partial=mapping_partial,
+ provenance=resolved.provenance,
)
agg_matched = resolved.matched
console.print(
@@ -389,7 +389,9 @@ def coverage_status(repo: str | None, fmt: str) -> None:
if fmt == "json":
emit_json({"repo": str(repo_path), "indexed": False})
return
- summary = await get_coverage_summary(session, repo_row.id)
+ summary = await get_coverage_summary(
+ session, repo_row.id, reference_commit=repo_row.head_commit
+ )
map_summary = await get_test_coverage_summary(session, repo_row.id)
if fmt == "json":
@@ -430,6 +432,16 @@ def coverage_status(repo: str | None, fmt: str) -> None:
)
if branch_pct is not None:
console.print(f" Branch: {branch_pct:.1f}%")
+ paths = summary.get("report_paths")
+ if paths:
+ console.print(
+ f" Report paths matched: {paths['matched']} of {paths['total']}"
+ )
+ if (summary.get("freshness") or {}).get("status") == "stale":
+ console.print(
+ f" [yellow]Measured at {(summary['ingested_commit_sha'] or '')[:8]}, "
+ "not the indexed commit; re-run the tests and ingest again.[/yellow]"
+ )
if map_summary.get("pair_count"):
console.print(
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 55039d35a..82b076472 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -110,7 +110,8 @@ class RescoreCoverage:
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
+ # How the reingested report mapped (``CoverageProvenance``); None when reused.
+ provenance: Any = None
async def _coverage_for_rescore(
@@ -154,7 +155,7 @@ async def _coverage_for_rescore(
resolved.files,
resolved.source_format,
authoritative=True,
- mapping_partial=resolved.mapping_partial,
+ provenance=resolved.provenance,
)
# Reingestion is authoritative. Falling back to old rows when a report
@@ -1504,7 +1505,7 @@ async def _rescore_health_from_db(
coverage.files,
source_format=coverage.source_format or "lcov",
ingested_commit_sha=live_head,
- mapping_partial=coverage.mapping_partial,
+ provenance=coverage.provenance,
)
await persist_graph_nodes(session, repo_id, graph_builder)
diff --git a/packages/core/alembic/versions/0080_coverage_ingest_provenance.py b/packages/core/alembic/versions/0080_coverage_ingest_provenance.py
new file mode 100644
index 000000000..1f992c652
--- /dev/null
+++ b/packages/core/alembic/versions/0080_coverage_ingest_provenance.py
@@ -0,0 +1,80 @@
+"""Coverage provenance: an exact covered count, and a record of each ingest.
+
+``coverage_files.covered_line_count`` is the size of the covered-line set, so
+repo and module aggregates count covered lines without reading the blob or
+deriving them back from a rounded percentage. NULL on older rows.
+
+``coverage_ingests`` holds one row per repository describing the ingest that
+wrote its coverage rows: every report format merged, how many of the report's
+paths matched, did not match or tied, a capped sample of the misses, whether
+the mapping was partial, and the commit. The coverage rows keep only matches,
+so these counts exist nowhere else.
+
+Local SQLite stores never run Alembic -- ``init_db``'s reconciler creates new
+tables and adds missing columns -- so this migration exists for managed
+Postgres. Both steps are guarded because the reconciler may have run first.
+
+Revision ID: 0080
+Revises: 0079
+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 = "0080"
+down_revision: str | None = "0079"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def _inspector() -> sa.engine.reflection.Inspector:
+ return sa.inspect(op.get_bind())
+
+
+def upgrade() -> None:
+ columns = {c["name"] for c in _inspector().get_columns("coverage_files")}
+ if "covered_line_count" not in columns:
+ op.add_column(
+ "coverage_files",
+ sa.Column("covered_line_count", sa.Integer(), nullable=True),
+ )
+ if not _inspector().has_table("coverage_ingests"):
+ op.create_table(
+ "coverage_ingests",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("source_formats_json", sa.Text(), nullable=False, server_default="[]"),
+ sa.Column("report_path_count", sa.Integer(), nullable=True),
+ sa.Column("matched_path_count", sa.Integer(), nullable=True),
+ sa.Column("unmatched_path_count", sa.Integer(), nullable=True),
+ sa.Column("ambiguous_path_count", sa.Integer(), nullable=True),
+ sa.Column("unmatched_sample_json", sa.Text(), nullable=False, server_default="[]"),
+ sa.Column("mapping_partial", sa.Boolean(), nullable=False, server_default=sa.false()),
+ sa.Column(
+ "ingested_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ sa.Column("ingested_commit_sha", sa.String(40), nullable=True),
+ sa.UniqueConstraint("repository_id", name="uq_coverage_ingests"),
+ )
+
+
+def downgrade() -> None:
+ if _inspector().has_table("coverage_ingests"):
+ op.drop_table("coverage_ingests")
+ columns = {c["name"] for c in _inspector().get_columns("coverage_files")}
+ if "covered_line_count" in columns:
+ op.drop_column("coverage_files", "covered_line_count")
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index 58d68e51a..b423370ce 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -10,8 +10,8 @@ from .contexts import (
parse_lcov_contexts,
)
from .decay import (
- STALE_DRIFT_PCT,
- STALE_MIN_MEASURED,
+ DRIFT_MIN_MEASURED,
+ DRIFT_PCT,
CoverageDecay,
decay_for_file,
decay_since,
@@ -20,6 +20,7 @@ from .decay import (
from .detector import PARSERS, detect_format, is_test_file, paired_test_file, parse
from .discovery import (
CoverageConfig,
+ CoverageProvenance,
ResolvedCoverage,
ResolvedTestCoverage,
build_coverage_map,
@@ -42,12 +43,13 @@ from .model import (
from .repowise_json import parse_repowise_json
__all__ = [
+ "DRIFT_MIN_MEASURED",
+ "DRIFT_PCT",
"PARSERS",
- "STALE_DRIFT_PCT",
- "STALE_MIN_MEASURED",
"ContextCoverageReport",
"CoverageConfig",
"CoverageDecay",
+ "CoverageProvenance",
"CoverageReport",
"FileCoverage",
"FreshnessStatus",
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/decay.py b/packages/core/src/repowise/core/analysis/health/coverage/decay.py
index f396d1651..74d78d2b1 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/decay.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/decay.py
@@ -59,27 +59,29 @@ class CoverageDecay:
drift_pct: float
@property
- def is_stale(self) -> bool:
+ def is_drifted(self) -> bool:
"""Whether enough of the measurement went unknown to stop quoting it.
The threshold is a display convention, not a scoring input. Nothing in
this module deducts health points; consumers use it to decide whether
- to caveat the figure they render.
+ to caveat the figure they render. Not "stale": that word means coverage
+ measured at another commit (``coverage_freshness``), which a file can
+ be without drifting and drift without being.
"""
- return self.measured >= STALE_MIN_MEASURED and self.drift_pct >= STALE_DRIFT_PCT
+ return self.measured >= DRIFT_MIN_MEASURED and self.drift_pct >= DRIFT_PCT
#: Share of a measurement that must have gone unknown before a consumer should
#: caveat the figure. A fifth is enough that "91% covered" has stopped being a
#: fair summary of the file in front of the reader.
-STALE_DRIFT_PCT = 20.0
+DRIFT_PCT = 20.0
#: Covered lines a file must have before the ratio means anything. Measured on
#: this repo's own index: without a floor the drift ranking is led by package
#: ``__init__.py`` files carrying a single covered line, where one version bump
#: is 100% drift and says nothing about the file. Ten lines puts the trigger at
#: two changed lines, which is the smallest move worth caveating a figure over.
-STALE_MIN_MEASURED = 10
+DRIFT_MIN_MEASURED = 10
def measurement_ref(
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index c662ef3c5..3826ed1d8 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -177,6 +177,39 @@ class ResolvedCoverage:
def total(self) -> int:
return self.matched + len(self.unmatched) + len(self.ambiguous)
+ @property
+ def provenance(self) -> CoverageProvenance:
+ return CoverageProvenance(
+ source_formats=tuple(self.source_formats),
+ report_path_count=self.total,
+ matched_path_count=self.matched,
+ unmatched_path_count=len(self.unmatched),
+ ambiguous_path_count=len(self.ambiguous),
+ unmatched_sample=tuple((self.unmatched + self.ambiguous)[:UNMATCHED_SAMPLE_CAP]),
+ mapping_partial=self.mapping_partial,
+ )
+
+
+#: Unmatched report paths kept for the diagnostic; the counts stay exact.
+UNMATCHED_SAMPLE_CAP = 10
+
+
+@dataclass(frozen=True)
+class CoverageProvenance:
+ """Where an ingest's coverage came from, stored beside its rows.
+
+ Counts are over the report's file entries. ``None`` means the writer did
+ not know them, which is not zero.
+ """
+
+ source_formats: tuple[str, ...] = ()
+ report_path_count: int | None = None
+ matched_path_count: int | None = None
+ unmatched_path_count: int | None = None
+ ambiguous_path_count: int | None = None
+ unmatched_sample: tuple[str, ...] = ()
+ mapping_partial: bool = False
+
def discover_artifacts(
repo_root: Path,
@@ -356,6 +389,7 @@ def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:
dst.covered_lines = sorted(covered)
dst.coverable_lines = sorted(coverable)
dst.total_coverable_lines = total
+ dst.covered_line_count = len(covered)
dst.line_coverage_pct = round(len(covered) / total * 100.0, 2) if total else 0.0
if src.branch_coverage_pct is not None:
dst.branch_coverage_pct = (
@@ -411,6 +445,7 @@ def resolve_reports(
covered_lines=list(fc.covered_lines),
total_coverable_lines=fc.total_coverable_lines,
coverable_lines=list(fc.coverable_lines),
+ covered_line_count=fc.covered_line_count,
)
if key in by_key:
_merge_into(by_key[key], resolved_fc)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.py
index 290f6c37a..16f146d13 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py
@@ -22,6 +22,10 @@ class FileCoverage:
(hit or not). It is what tells an uncovered changed line apart from a
changed comment or blank line, so patch coverage needs it. Empty means
the report did not say which lines are executable, not that none are.
+
+ ``covered_line_count`` is the numerator of ``line_coverage_pct``, kept so
+ aggregates never derive it back from the rounded percentage. ``None``
+ when the source stated a percentage rather than a count.
"""
file_path: str
@@ -30,6 +34,7 @@ class FileCoverage:
covered_lines: list[int] = field(default_factory=list)
total_coverable_lines: int = 0
coverable_lines: list[int] = field(default_factory=list)
+ covered_line_count: int | None = None
def file_coverage(
@@ -61,6 +66,7 @@ def file_coverage(
covered_lines=sorted(covered_set),
total_coverable_lines=n_total,
coverable_lines=sorted(coverable_set),
+ covered_line_count=n_hit,
)
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index 97c769daf..a60561775 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -175,9 +175,9 @@ class HealthReport:
# to the ``coverage_files`` table. Empty when no coverage was ingested.
coverage_files: list[Any] = field(default_factory=list)
coverage_format: str | None = None
- # True when the ingested coverage report mapped fewer than half its files
- # to the repo tree (#1746); carried so the persister can stamp the rows.
- coverage_mapping_partial: bool = False
+ # How the ingested report mapped to the repo tree (``CoverageProvenance``:
+ # formats, path counts, partial mapping #1746), for the persister to record.
+ coverage_provenance: Any = None
# Incremental writers replace all dimensions only for ``authoritative_paths``.
# ``performance_authoritative_paths`` may be wider: the bounded execution
# closure whose performance rows/plans were recomputed for full parity.
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
index 1c6d4e0b8..0395d9f1f 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
@@ -80,7 +80,7 @@ class PatchScope:
source_formats: tuple[str, ...] = ()
reports: tuple[str, ...] = () # report files read, as the caller named them
# 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).
+ # the repository. ``None`` when unknown (an ingest that did not record them).
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.
@@ -211,7 +211,7 @@ def patch_coverage_from_resolved(
label=label,
source_formats=tuple(resolved.source_formats),
reports=tuple(reports),
- report_path_count=resolved.matched + unmatched,
+ report_path_count=resolved.total,
unmatched_report_path_count=unmatched,
mapping_partial=resolved.mapping_partial,
),
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
index 554cc5b02..11f270396 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
@@ -43,6 +43,7 @@ async def stored_patch_coverage(
wanted = sorted(set(changed) & measured)
coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}
commit = summary["ingested_commit_sha"]
+ paths = summary["report_paths"]
return compute_patch_coverage(
changed,
coverage,
@@ -50,7 +51,9 @@ async def stored_patch_coverage(
report_paths=measured,
scope=PatchScope(
label=label,
- source_formats=(summary["source_format"],) if summary["source_format"] else (),
+ source_formats=tuple(summary["source_formats"]),
+ report_path_count=paths["total"] if paths else None,
+ unmatched_report_path_count=paths["unmatched"] + paths["ambiguous"] if paths else None,
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.py
index f95a6862e..2a6d34981 100644
--- a/packages/core/src/repowise/core/analysis/test_impact.py
+++ b/packages/core/src/repowise/core/analysis/test_impact.py
@@ -42,22 +42,22 @@ def _freshness(
"ingested_commit": ingested_commit,
"indexed_commit": None,
}
- if not ingested_commit or not indexed_commit:
- return {
- "status": "unknown",
- "reason": "coverage_or_index_commit_unavailable",
- "ingested_commit": ingested_commit,
- "indexed_commit": indexed_commit,
- }
status = coverage_freshness(ingested_commit, indexed_commit)
return {
"status": status,
- "reason": None if status == "current" else "coverage_commit_differs_from_index",
+ "reason": _FRESHNESS_REASONS[status],
"ingested_commit": ingested_commit,
"indexed_commit": indexed_commit,
}
+_FRESHNESS_REASONS: dict[str, str | None] = {
+ "current": None,
+ "stale": "coverage_commit_differs_from_index",
+ "unknown": "coverage_or_index_commit_unavailable",
+}
+
+
def _recommendation_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]:
return (
-len(row["source_files"]),
diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
index 5627d7534..257d279db 100644
--- a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
+++ b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
@@ -12,7 +12,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from datetime import datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any
from ..models import (
CoverageFile,
@@ -24,6 +24,9 @@ from ..models import (
HealthSnapshot,
)
+if TYPE_CHECKING:
+ from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
+
class AnalysisIndexStore(ABC):
"""GitMetadata, DeadCode, Decision, Health, Coverage CRUD."""
@@ -246,7 +249,7 @@ class AnalysisIndexStore(ABC):
*,
source_format: str,
ingested_commit_sha: str | None = None,
- mapping_partial: bool = False,
+ provenance: CoverageProvenance | None = None,
) -> None: ...
@abstractmethod
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index 6265895f9..6bae3b3db 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -18,6 +18,9 @@ from . import ( # noqa: F401
refactoring,
)
from .coverage import (
+ coverage_by_module,
+ coverage_row_dict,
+ empty_coverage_summary,
file_coverage_from_row,
get_coverage_summary,
load_coverage_for_repo,
@@ -119,9 +122,12 @@ __all__ = [
"backfill_is_test",
"backfill_module_attribution",
"count_refactoring_suggestions",
+ "coverage_by_module",
+ "coverage_row_dict",
"covered_source_files",
"doc_drift_findings_stored",
"doc_drift_references_stored",
+ "empty_coverage_summary",
"file_coverage_from_row",
"files_covered_by",
"finalize_performance_opportunities",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
index 98be87791..081a8e984 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
@@ -8,9 +8,11 @@ from typing import TYPE_CHECKING, Any, Literal, overload
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from ...models import CoverageFile, _new_uuid
+from ...models import CoverageFile, CoverageIngest, _new_uuid
if TYPE_CHECKING:
+ from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
+ from repowise.core.analysis.health.coverage.freshness import FreshnessStatus
from repowise.core.analysis.health.coverage.model import FileCoverage
from .._shared import _BATCH_SIZE
@@ -22,23 +24,42 @@ async def save_coverage_files(
*,
source_format: str,
ingested_commit_sha: str | None = None,
- mapping_partial: bool = False,
+ provenance: CoverageProvenance | None = None,
) -> None:
- """Replace coverage rows for *repository_id* with *files*.
+ """Replace coverage rows for *repository_id* with *files*, and record the ingest.
Mirrors the delete-then-insert pattern used by the health writers.
*files* is a list of ``FileCoverage`` dataclasses (or dicts with the
- same shape). ``mapping_partial`` marks the whole ingest as a fragment
- (fewer than half the report's files mapped to the repo tree, #1746);
- it is a property of the ingest, not of any one row.
+ same shape). *provenance*, from a writer that resolved the report
+ itself, supplies the formats, the path counts and ``mapping_partial``
+ (fewer than half the report's files mapped to the repo tree, #1746: a
+ property of the ingest, stamped on every row). Without it the ingest
+ records ``source_format`` alone and its path counts stay unknown.
"""
- existing = await session.execute(
- select(CoverageFile).where(CoverageFile.repository_id == repository_id)
- )
- for row in existing.scalars().all():
- await session.delete(row)
+ from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
+
+ p = provenance or CoverageProvenance()
+ for model in (CoverageFile, CoverageIngest):
+ existing = await session.execute(select(model).where(model.repository_id == repository_id))
+ for row in existing.scalars().all():
+ await session.delete(row)
await session.flush()
+ session.add(
+ CoverageIngest(
+ id=_new_uuid(),
+ repository_id=repository_id,
+ source_formats_json=json.dumps(list(p.source_formats) or [source_format]),
+ report_path_count=p.report_path_count,
+ matched_path_count=p.matched_path_count,
+ unmatched_path_count=p.unmatched_path_count,
+ ambiguous_path_count=p.ambiguous_path_count,
+ unmatched_sample_json=json.dumps(list(p.unmatched_sample)),
+ mapping_partial=p.mapping_partial,
+ ingested_commit_sha=ingested_commit_sha,
+ )
+ )
+
for i in range(0, len(files), _BATCH_SIZE):
for f in files[i : i + _BATCH_SIZE]:
session.add(
@@ -47,7 +68,7 @@ async def save_coverage_files(
repository_id=repository_id,
source_format=source_format,
ingested_commit_sha=ingested_commit_sha,
- mapping_partial=mapping_partial,
+ mapping_partial=p.mapping_partial,
**_row_columns(f),
)
)
@@ -71,15 +92,21 @@ def _row_columns(f: Any) -> dict[str, Any]:
),
"covered_lines_json": json.dumps(list(f.covered_lines or [])),
"total_coverable_lines": int(f.total_coverable_lines or 0),
+ "covered_line_count": _covered_count(f),
"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 {
+ columns = {
k: v for k, v in data.items() if k not in _INGEST_COLUMNS and hasattr(CoverageFile, k)
}
+ if columns.get("covered_line_count") is None:
+ columns["covered_line_count"] = _derived_count(
+ columns.get("line_coverage_pct"), columns.get("total_coverable_lines")
+ )
+ return columns
#: Every column of ``CoverageFile`` except the two line-set blobs
@@ -92,6 +119,7 @@ _COVERAGE_SCALAR_COLUMNS = (
CoverageFile.line_coverage_pct,
CoverageFile.branch_coverage_pct,
CoverageFile.total_coverable_lines,
+ CoverageFile.covered_line_count,
CoverageFile.mapping_partial,
CoverageFile.ingested_at,
CoverageFile.ingested_commit_sha,
@@ -153,6 +181,73 @@ def _line_list(raw: str | None) -> list[int]:
return []
+def _covered_count(row: Any) -> int:
+ """Covered lines in a row or ``FileCoverage``: its count, else derived.
+
+ Parsed reports carry the count. Derivation from the rounded percentage is
+ left for rows written before the column and for sources that state only a
+ percentage; it is exact below 10,000 coverable lines, where two-decimal
+ rounding cannot move the product by half a line.
+ """
+ count = getattr(row, "covered_line_count", None)
+ if count is not None:
+ return int(count)
+ return _derived_count(row.line_coverage_pct, row.total_coverable_lines)
+
+
+def _derived_count(pct: float | None, total: int | None) -> int:
+ return round(float(pct or 0.0) / 100.0 * int(total or 0))
+
+
+def coverage_row_dict(row: Any, *, include_covered_lines: bool) -> dict[str, Any]:
+ """A stored coverage row as every surface sends it.
+
+ ``include_covered_lines=False`` omits the per-line array, and is required
+ for a row read with ``include_covered_lines=False``: that row carries no
+ ``covered_lines_json`` at all. ``covered_line_count`` is sent either way.
+ """
+ out: dict[str, Any] = {
+ "file_path": row.file_path,
+ "source_format": row.source_format,
+ "line_coverage_pct": row.line_coverage_pct,
+ "branch_coverage_pct": row.branch_coverage_pct,
+ }
+ if include_covered_lines:
+ out["covered_lines"] = _line_list(row.covered_lines_json)
+ out["total_coverable_lines"] = row.total_coverable_lines
+ out["covered_line_count"] = _covered_count(row)
+ out["ingested_at"] = row.ingested_at.isoformat() if row.ingested_at else None
+ out["ingested_commit_sha"] = row.ingested_commit_sha
+ return out
+
+
+def coverage_by_module(rows: list[Any]) -> list[dict[str, Any]]:
+ """Stored rows rolled up by directory, worst covered first.
+
+ *rows* must be every row for the repo, for the same reason as
+ :func:`get_coverage_summary`.
+ """
+ modules: dict[str, dict[str, int]] = {}
+ for r in rows:
+ mod = r.file_path.rsplit("/", 1)[0] if "/" in r.file_path else "(root)"
+ bucket = modules.setdefault(mod, {"covered": 0, "total": 0, "files": 0})
+ bucket["files"] += 1
+ bucket["total"] += r.total_coverable_lines
+ bucket["covered"] += _covered_count(r)
+ out = [
+ {
+ "module": name,
+ "files": v["files"],
+ "covered_lines": v["covered"],
+ "total_lines": v["total"],
+ "line_coverage_pct": round(v["covered"] / v["total"] * 100.0, 2) if v["total"] else 0.0,
+ }
+ for name, v in modules.items()
+ ]
+ out.sort(key=lambda x: x["line_coverage_pct"])
+ return out
+
+
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
@@ -164,6 +259,7 @@ def file_coverage_from_row(row: Any) -> FileCoverage:
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)),
+ covered_line_count=getattr(row, "covered_line_count", None),
)
@@ -195,11 +291,58 @@ async def load_coverage_map(session: AsyncSession, repository_id: str) -> dict[s
}
+def empty_coverage_summary() -> dict[str, Any]:
+ """The summary's shape when nothing is stored: no measurement, not zero percent."""
+ return {
+ "file_count": 0,
+ "covered_lines": 0,
+ "total_lines": 0,
+ "line_coverage_pct": None,
+ "branch_coverage_pct": None,
+ "source_format": None,
+ "source_formats": [],
+ "mapping_partial": None,
+ "ingested_at": None,
+ "ingested_commit_sha": None,
+ "report_paths": None,
+ "freshness": None,
+ }
+
+
+def _report_paths(ingest: CoverageIngest | None) -> dict[str, Any] | None:
+ """How the report's own file entries mapped; ``None`` when the ingest did not record it."""
+ if ingest is None or ingest.report_path_count is None:
+ return None
+ try:
+ sample = [str(p) for p in json.loads(ingest.unmatched_sample_json or "[]")]
+ except (ValueError, TypeError):
+ sample = []
+ return {
+ "total": ingest.report_path_count,
+ "matched": ingest.matched_path_count or 0,
+ "unmatched": ingest.unmatched_path_count or 0,
+ "ambiguous": ingest.ambiguous_path_count or 0,
+ "unmatched_sample": sample,
+ }
+
+
+def _source_formats(ingest: CoverageIngest | None, fallback: str | None) -> list[str]:
+ if ingest is not None:
+ try:
+ formats = [str(f) for f in json.loads(ingest.source_formats_json or "[]")]
+ except (ValueError, TypeError):
+ formats = []
+ if formats:
+ return formats
+ return [fallback] if fallback else []
+
+
async def get_coverage_summary(
session: AsyncSession,
repository_id: str,
*,
rows: list[Any] | None = None,
+ reference_commit: str | None = None,
) -> dict[str, Any]:
"""Repo-level coverage aggregate. Returns an empty shape when no rows.
@@ -208,29 +351,31 @@ async def get_coverage_summary(
function would have read itself — ``load_coverage_for_repo(repository_id)``,
i.e. **every** row for the repo. Handing over a subset (a ``file_paths=``
read, say) would silently report that subset's coverage as the repo's.
+
+ *reference_commit* is the commit the caller is describing (the indexed
+ tree, usually); ``freshness`` says whether the coverage was measured there
+ (``coverage_freshness``). ``report_paths`` is how the report's own entries
+ mapped to the repository, ``None`` for an ingest that did not record it.
"""
+ from repowise.core.analysis.health.coverage.freshness import coverage_freshness
+
if rows is None:
rows = await load_coverage_for_repo(
session, repository_id, include_covered_lines=False
)
if not rows:
- return {
- "file_count": 0,
- "covered_lines": 0,
- "total_lines": 0,
- "line_coverage_pct": None,
- "branch_coverage_pct": None,
- "source_format": None,
- "mapping_partial": None,
- "ingested_at": None,
- "ingested_commit_sha": None,
- }
+ return empty_coverage_summary()
+ ingest = (
+ await session.execute(
+ select(CoverageIngest).where(CoverageIngest.repository_id == repository_id)
+ )
+ ).scalar_one_or_none()
covered = 0
total = 0
branch_pcts: list[float] = []
branch_weights: list[int] = []
for r in rows:
- covered += round(r.line_coverage_pct / 100.0 * r.total_coverable_lines)
+ covered += _covered_count(r)
total += r.total_coverable_lines
if r.branch_coverage_pct is not None:
branch_pcts.append(r.branch_coverage_pct)
@@ -248,6 +393,7 @@ async def get_coverage_summary(
# table's. Rows written before the flag existed read False (column
# default), which is correct for complete legacy ingests.
mapping_partial = bool(getattr(latest, "mapping_partial", False))
+ status: FreshnessStatus = coverage_freshness(latest.ingested_commit_sha, reference_commit)
return {
"file_count": len(rows),
"covered_lines": covered,
@@ -255,7 +401,10 @@ async def get_coverage_summary(
"line_coverage_pct": round(line_pct, 2),
"branch_coverage_pct": round(branch_pct, 2) if branch_pct is not None else None,
"source_format": latest.source_format,
+ "source_formats": _source_formats(ingest, latest.source_format),
"mapping_partial": mapping_partial,
"ingested_at": latest.ingested_at,
"ingested_commit_sha": latest.ingested_commit_sha,
+ "report_paths": _report_paths(ingest),
+ "freshness": {"status": status, "indexed_commit": reference_commit},
}
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index f32e0dff2..bf60ab8f0 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2203,6 +2203,9 @@ 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)
+ # How many lines ``covered_lines_json`` names, so aggregates count covered
+ # lines without reading the blob. NULL on rows written before the column.
+ covered_line_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 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".
@@ -2220,6 +2223,39 @@ class CoverageFile(Base):
__table_args__ = (UniqueConstraint("repository_id", "file_path", name="uq_coverage_files"),)
+class CoverageIngest(Base):
+ """Where the stored ``coverage_files`` rows came from: one row per ingest.
+
+ Replaced together with the rows it describes, so a repository has at most
+ one. Ceiling: no history; a per-ingest trend drops the unique constraint.
+ The path counts are over the report's own file entries, matched or not,
+ which the coverage rows cannot say (they keep only matches). NULL counts
+ mean the writer did not know them.
+ """
+
+ __tablename__ = "coverage_ingests"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ # Every distinct report format merged, in report order.
+ source_formats_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ report_path_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ matched_path_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ unmatched_path_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ ambiguous_path_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # A capped sample of the report paths that did not map, for the diagnostic.
+ unmatched_sample_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ mapping_partial: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ ingested_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+ ingested_commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)
+
+ __table_args__ = (UniqueConstraint("repository_id", name="uq_coverage_ingests"),)
+
+
class TestCoverageEntry(Base):
"""One ``(test, source file)`` coverage fact - the test-to-code map.
diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
index d25997dd9..f6254d7e5 100644
--- a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
+++ b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
@@ -7,7 +7,7 @@ delegates to :mod:`crud`. Split out to keep store files under 400 lines.
from __future__ import annotations
from datetime import datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any
from sqlalchemy.ext.asyncio import AsyncSession
@@ -23,6 +23,9 @@ from ..models import (
HealthSnapshot,
)
+if TYPE_CHECKING:
+ from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
+
class _SqlAnalysisMixin(AnalysisIndexStore):
"""Concrete delegations for the analysis IndexStore surface."""
@@ -295,7 +298,7 @@ class _SqlAnalysisMixin(AnalysisIndexStore):
*,
source_format: str,
ingested_commit_sha: str | None = None,
- mapping_partial: bool = False,
+ provenance: CoverageProvenance | None = None,
) -> None:
await crud.save_coverage_files(
self._session,
@@ -303,7 +306,7 @@ class _SqlAnalysisMixin(AnalysisIndexStore):
files,
source_format=source_format,
ingested_commit_sha=ingested_commit_sha,
- mapping_partial=mapping_partial,
+ provenance=provenance,
)
async def load_coverage_for_repo(
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 2102fb73d..09c185b9d 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1958,7 +1958,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
coverage_files,
source_format=getattr(hr, "coverage_format", None) or "lcov",
ingested_commit_sha=head_sha,
- mapping_partial=bool(getattr(hr, "coverage_mapping_partial", False)),
+ provenance=getattr(hr, "coverage_provenance", None),
)
# Per-function blame rollup (FULL tier only; empty otherwise).
fn_blame_rows = getattr(hr, "function_blame_rows", None)
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 24eb0c690..698d0ccb8 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -172,10 +172,11 @@ def _build_pipeline_coverage(
explicit_paths: list[Path] | None,
*,
progress: ProgressCallback | None,
-) -> tuple[dict[str, dict], list[Any], str | None, bool]:
+) -> tuple[dict[str, dict], list[Any], str | None, Any]:
"""Discover/parse/resolve coverage reports for an indexing run.
- Returns ``(coverage_map, resolved_files, source_format, mapping_partial)``.
+ Returns ``(coverage_map, resolved_files, source_format, provenance)``, the
+ last a ``CoverageProvenance`` or ``None`` when no report was read.
Best-effort: any failure logs and yields an empty map so health analysis
proceeds without coverage. Unmatched report files are surfaced via
*progress* so "coverage didn't show up" is never silent.
@@ -191,7 +192,7 @@ def _build_pipeline_coverage(
report_paths = list(explicit_paths) if explicit_paths else cfg.report_paths(repo_path)
if not report_paths:
- return {}, [], None, False
+ return {}, [], None, None
repo_keys = {pf.file_info.path for pf in parsed_files}
resolved, errors = build_coverage_map(
@@ -232,13 +233,13 @@ def _build_pipeline_coverage(
resolved.coverage_map,
resolved.files,
resolved.source_format,
- resolved.mapping_partial,
+ resolved.provenance,
)
except Exception as exc:
if progress:
progress.on_message("warning", f"Coverage ingestion skipped: {exc}")
logger.debug("pipeline_coverage_failed", error=str(exc))
- return {}, [], None, False
+ return {}, [], None, None
async def _run_health_analysis(
@@ -283,13 +284,13 @@ async def _run_health_analysis(
coverage_map: dict[str, dict] = {}
coverage_files: list[Any] = []
coverage_format: str | None = None
- coverage_mapping_partial = False
+ coverage_provenance: Any = None
if repo_path is not None:
(
coverage_map,
coverage_files,
coverage_format,
- coverage_mapping_partial,
+ coverage_provenance,
) = _build_pipeline_coverage(
repo_path, parsed_files, coverage_report_paths, progress=progress
)
@@ -331,7 +332,7 @@ async def _run_health_analysis(
if coverage_files:
report.coverage_files = coverage_files
report.coverage_format = coverage_format
- report.coverage_mapping_partial = coverage_mapping_partial
+ report.coverage_provenance = coverage_provenance
if progress:
findings_count = len(report.findings)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 49196350a..49c9e7a5a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -33,6 +33,7 @@ from repowise.core.ingestion.models import (
SYMBOL_USE_EDGE_TYPES,
)
from repowise.core.persistence.crud import (
+ coverage_row_dict,
doc_drift_references_stored,
get_all_file_metrics,
get_community_members,
@@ -44,10 +45,10 @@ from repowise.core.persistence.crud import (
get_graph_node,
get_graph_nodes_by_ids,
get_node_degree_counts,
+ load_coverage_for_repo,
serialize_doc_drift_reference_row,
)
from repowise.core.persistence.models import (
- CoverageFile,
GraphEdge,
GraphNode,
HealthFileMetric,
@@ -713,14 +714,9 @@ async def _resolve_health(
for f in findings_res.scalars().all()
]
- coverage_row = (
- await session.execute(
- select(CoverageFile).where(
- CoverageFile.repository_id == repo_id,
- CoverageFile.file_path == file_path,
- )
- )
- ).scalar_one_or_none()
+ coverage_rows = await load_coverage_for_repo(
+ session, repo_id, file_paths=[file_path], include_covered_lines=False
+ )
health: dict[str, Any] = {
"score": round(metric.score, 2),
@@ -732,13 +728,8 @@ async def _resolve_health(
"duplication_pct": metric.duplication_pct,
"top_biomarkers": top_biomarkers,
}
- if coverage_row is not None:
- health["coverage"] = {
- "source_format": coverage_row.source_format,
- "line_coverage_pct": coverage_row.line_coverage_pct,
- "branch_coverage_pct": coverage_row.branch_coverage_pct,
- "total_coverable_lines": coverage_row.total_coverable_lines,
- }
+ if coverage_rows:
+ health["coverage"] = coverage_row_dict(coverage_rows[0], include_covered_lines=False)
elif metric.line_coverage_pct is not None:
health["coverage"] = {
"line_coverage_pct": metric.line_coverage_pct,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py
index c681bd449..e643908e9 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py
@@ -8,10 +8,7 @@ tests import them from ``tool_health`` directly.
from __future__ import annotations
from repowise.core.analysis.health.aggregation import module_rollups as _module_rollups
-from repowise.server.mcp_server.tool_health.coverage import (
- _attach_coverage_decay,
- _serialize_coverage_row,
-)
+from repowise.server.mcp_server.tool_health.coverage import _attach_coverage_decay
from repowise.server.mcp_server.tool_health.plans import _validation_profile
from repowise.server.mcp_server.tool_health.serialize import (
_health_finding_id,
@@ -30,7 +27,6 @@ __all__ = [
"_perf_rank",
"_rank_emitted",
"_refactoring_plan_id",
- "_serialize_coverage_row",
"_serialize_refactoring",
"_validation_profile",
"get_health",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py b/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
index 742071571..c4d8b3bda 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
@@ -2,10 +2,10 @@
from __future__ import annotations
-import json
from typing import Any
from repowise.core.analysis.health.coverage import decay_since, measurement_ref
+from repowise.core.persistence.crud import coverage_row_dict
from repowise.server.mcp_server.tool_health.paging import Pager
@@ -24,11 +24,13 @@ def _coverage_block(
"""
if scoped:
selected_coverage = pager.bound(rows, "coverage.files")
- coverage_payload = [_serialize_coverage_row(r) for r in selected_coverage]
+ coverage_payload = [
+ coverage_row_dict(r, include_covered_lines=True) for r in selected_coverage
+ ]
_attach_coverage_decay(coverage_payload, selected_coverage, repo_path)
else:
# Built narrow: these rows were read without the column (see ``loading``).
- full_coverage_payload = [_serialize_coverage_row(r, covered_lines=False) for r in rows]
+ full_coverage_payload = [coverage_row_dict(r, include_covered_lines=False) for r in rows]
coverage_payload = pager.bound(full_coverage_payload, "coverage.files")
# ``ingested_at`` is a datetime on the summary too — coerce.
if summary.get("ingested_at") is not None:
@@ -86,33 +88,6 @@ def _attach_coverage_decay(payload: list[dict[str, Any]], rows: list[Any], repo_
"confirmed_lines": d.confirmed,
"invalidated_lines": d.invalidated,
"drift_pct": d.drift_pct,
- "stale": d.is_stale,
+ "drifted": d.is_drifted,
"measured_at_commit": ref[:12],
}
-
-
-def _serialize_coverage_row(row: Any, *, covered_lines: bool = True) -> dict[str, Any]:
- """One coverage row. ``covered_lines=False`` omits the per-line array.
-
- The narrow form is not the wide form minus a key: a row read with
- ``include_covered_lines=False`` carries no ``covered_lines_json`` at all, so
- touching it would raise rather than merely waste the parse.
- """
- out: dict[str, Any] = {
- "file_path": row.file_path,
- "source_format": row.source_format,
- "line_coverage_pct": row.line_coverage_pct,
- "branch_coverage_pct": row.branch_coverage_pct,
- }
- # Inserted here, not appended, so the wide form's key order is unchanged.
- if covered_lines:
- try:
- out["covered_lines"] = (
- json.loads(row.covered_lines_json) if row.covered_lines_json else []
- )
- except Exception:
- out["covered_lines"] = []
- out["total_coverable_lines"] = row.total_coverable_lines
- out["ingested_at"] = row.ingested_at.isoformat() if row.ingested_at else None
- out["ingested_commit_sha"] = row.ingested_commit_sha
- return out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index 2a7248635..a70698b0a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -281,11 +281,14 @@ async def _read_coverage(
"file_path",
)
# A stored repo-wide aggregate cannot describe a narrowed population, so
- # it is omitted there; the rows stay.
+ # it is omitted there; the rows stay. Freshness is against the indexed
+ # commit, the tree every other figure in the response describes.
summary = (
{}
if pop.reported_scope == "production"
- else await get_coverage_summary(session, repository.id)
+ else await get_coverage_summary(
+ session, repository.id, reference_commit=getattr(repository, "head_commit", None)
+ )
)
return rows, summary
diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
index 6420fa831..5bdc6d8c0 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
@@ -15,7 +15,6 @@ any ratio built from it would be a coverage figure the data cannot support.
from __future__ import annotations
import asyncio
-import json
from typing import Any
from fastapi import Depends, HTTPException, Query
@@ -31,30 +30,17 @@ from repowise.core.persistence import crud
from repowise.core.persistence.models import Repository
from repowise.server.deps import get_db_session
from repowise.server.routers._local_git import resolve_local_repo, revision_exists
+from repowise.server.schemas.coverage import CoverageResponse
from repowise.server.schemas.patch_coverage import PatchCoverageResponse
from ._router import router
-def _coverage_row_to_dict(row: Any, *, include_covered_lines: bool = False) -> dict:
- out: dict[str, Any] = {
- "file_path": row.file_path,
- "source_format": row.source_format,
- "line_coverage_pct": row.line_coverage_pct,
- "branch_coverage_pct": row.branch_coverage_pct,
- "total_coverable_lines": row.total_coverable_lines,
- "ingested_at": row.ingested_at.isoformat() if row.ingested_at else None,
- "ingested_commit_sha": row.ingested_commit_sha,
- }
- if include_covered_lines:
- try:
- out["covered_lines"] = json.loads(row.covered_lines_json or "[]")
- except Exception:
- out["covered_lines"] = []
- return out
-
-
[email protected]("/api/repos/{repo_id}/health/coverage")
+ "/api/repos/{repo_id}/health/coverage",
+ response_model=CoverageResponse,
+ response_model_exclude_unset=True,
+)
async def health_coverage(
repo_id: str,
file_path: str | None = Query(None),
@@ -86,6 +72,9 @@ async def health_coverage(
and no modules. A declined response omits ``basis`` rather than reporting
``"none"`` - the graph was not consulted, which is not the same as the graph
having nothing to say.
+
+ ``summary.freshness`` compares the measurement's commit with the indexed
+ one, the tree every other figure on the page describes.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
@@ -103,13 +92,15 @@ async def health_coverage(
# reach this", so answer that instead of an empty measured shape.
if not include_inferred:
return {
- "summary": _empty_summary(),
+ "summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
"modules_total": 0,
}
return await _inferred_coverage(session, repo_id, limit)
- summary = await crud.get_coverage_summary(session, repo_id, rows=all_rows)
+ summary = await crud.get_coverage_summary(
+ session, repo_id, rows=all_rows, reference_commit=repo.head_commit
+ )
if summary.get("ingested_at") is not None:
summary = {**summary, "ingested_at": summary["ingested_at"].isoformat()}
@@ -118,10 +109,12 @@ async def health_coverage(
detail = await crud.load_coverage_for_repo(
session, repo_id, file_paths=[file_path], include_covered_lines=True
)
- files = [_coverage_row_to_dict(r, include_covered_lines=True) for r in detail]
+ files = [crud.coverage_row_dict(r, include_covered_lines=True) for r in detail]
else:
rows_sorted = sorted(all_rows, key=lambda r: r.line_coverage_pct)
- files = [_coverage_row_to_dict(r) for r in rows_sorted[:limit]]
+ files = [
+ crud.coverage_row_dict(r, include_covered_lines=False) for r in rows_sorted[:limit]
+ ]
# Attach per-file health score so the UI can render a coverage
# x score matrix without a second request. Scoped to the rows we are
# actually returning: a repo-wide read hydrates every metric row and
@@ -137,29 +130,9 @@ async def health_coverage(
f["health_score"] = round(m.score, 2)
f["nloc"] = m.nloc
- # Aggregate by directory for module-level bars (cheap; one pass).
# Always over the repo-wide read, never over ``files``: this is what the
# repo's coverage looks like by directory, not what this page of it does.
- modules: dict[str, dict[str, Any]] = {}
- for r in all_rows:
- mod = r.file_path.rsplit("/", 1)[0] if "/" in r.file_path else "(root)"
- bucket = modules.setdefault(mod, {"covered": 0, "total": 0, "files": 0})
- bucket["files"] += 1
- bucket["total"] += r.total_coverable_lines
- bucket["covered"] += round(r.line_coverage_pct / 100.0 * r.total_coverable_lines)
- module_rows = [
- {
- "module": name,
- "files": v["files"],
- "covered_lines": v["covered"],
- "total_lines": v["total"],
- "line_coverage_pct": (
- round(v["covered"] / v["total"] * 100.0, 2) if v["total"] else 0.0
- ),
- }
- for name, v in modules.items()
- ]
- module_rows.sort(key=lambda x: x["line_coverage_pct"])
+ module_rows = crud.coverage_by_module(all_rows)
# The hybrid gap. A single stored row is enough to select the measured
# basis for the whole repository, but most files in most repos have no
@@ -196,26 +169,6 @@ async def health_coverage(
}
-def _empty_summary() -> dict[str, Any]:
- """The measured summary's zero shape.
-
- Sent on the inferred basis so the field keeps one type. It is empty because
- nothing measured this repo, which is a different statement from "measured at
- zero percent" - and the only field that distinguishes them is ``basis``.
- """
- return {
- "file_count": 0,
- "covered_lines": 0,
- "total_lines": 0,
- "line_coverage_pct": None,
- "branch_coverage_pct": None,
- "source_format": None,
- "mapping_partial": None,
- "ingested_at": None,
- "ingested_commit_sha": None,
- }
-
-
async def _inferred_coverage(
session: AsyncSession,
repo_id: str,
@@ -249,7 +202,7 @@ async def _inferred_coverage(
if not test_files:
return {
"basis": "none",
- "summary": _empty_summary(),
+ "summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
"modules_total": 0,
@@ -273,7 +226,7 @@ async def _inferred_coverage(
# just to learn there is nothing to add.
return {
"basis": "inferred",
- "summary": _empty_summary(),
+ "summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
"modules_total": 0,
@@ -290,7 +243,7 @@ async def _inferred_coverage(
except Exception:
return {
"basis": "none",
- "summary": _empty_summary(),
+ "summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
"modules_total": 0,
@@ -308,7 +261,7 @@ async def _inferred_coverage(
]
return {
"basis": "inferred",
- "summary": _empty_summary(),
+ "summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
"modules_total": 0,
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 0f1b6a91f..7afe09d10 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -321,23 +321,15 @@ async def file_detail(
)
# --- Coverage (incl. line-level set for the heatmap) --------------------
- coverage_rows = await crud.load_coverage_for_repo(session, repo_id, file_paths=[file_path])
+ # ``covered_line_count`` is sent in both modes so "N of M lines hit" never
+ # has to count the array client-side, which is what forced it to travel.
+ coverage_rows = await crud.load_coverage_for_repo(
+ session, repo_id, file_paths=[file_path], include_covered_lines=not slim
+ )
coverage: dict | None = None
if coverage_rows:
- c = coverage_rows[0]
- covered_lines = _json_or(c.covered_lines_json, [])
- coverage = {
- "line_coverage_pct": c.line_coverage_pct,
- "branch_coverage_pct": c.branch_coverage_pct,
- "total_coverable_lines": c.total_coverable_lines,
- # Sent in both modes so "N of M lines hit" never has to count the
- # array client-side, which is what forced the array to travel.
- "covered_line_count": len(covered_lines),
- "covered_lines": [] if slim else covered_lines,
- "source_format": c.source_format,
- "ingested_at": c.ingested_at.isoformat() if c.ingested_at else None,
- "ingested_commit_sha": c.ingested_commit_sha,
- }
+ coverage = crud.coverage_row_dict(coverage_rows[0], include_covered_lines=not slim)
+ coverage.setdefault("covered_lines", [])
# --- Graph context ------------------------------------------------------
graph: dict | None = None
diff --git a/packages/server/src/repowise/server/schemas/coverage.py b/packages/server/src/repowise/server/schemas/coverage.py
new file mode 100644
index 000000000..8a9c196e5
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/coverage.py
@@ -0,0 +1,72 @@
+"""The coverage map over the wire, with its summary typed.
+
+The summary mirrors ``crud.get_coverage_summary`` field for field, strict so a
+key the aggregate gains fails here instead of vanishing from the API. The
+per-file, per-module and inferred blocks stay loosely typed: their TypeScript
+is hand-written beside the UI that reads them.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, ConfigDict
+
+from repowise.core.analysis.health.coverage.freshness import FreshnessStatus
+
+
+class _Strict(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+
+class CoverageReportPaths(_Strict):
+ """How the report's own file entries mapped to the repository at ingest."""
+
+ total: int
+ matched: int
+ #: Named no file in the repository.
+ unmatched: int
+ #: Tied between several files, so none was chosen.
+ ambiguous: int
+ #: A capped sample of the unmatched, then ambiguous, paths as the report wrote them.
+ unmatched_sample: list[str]
+
+
+class CoverageSummaryFreshness(_Strict):
+ """Whether the coverage was measured at the commit the index describes."""
+
+ status: FreshnessStatus
+ #: The indexed commit the measurement is compared against.
+ indexed_commit: str | None
+
+
+class CoverageSummary(_Strict):
+ """The repository's stored coverage, aggregated. Zero counts and nulls when none is stored."""
+
+ file_count: int
+ covered_lines: int
+ total_lines: int
+ line_coverage_pct: float | None
+ branch_coverage_pct: float | None
+ source_format: str | None
+ #: Every report format the ingest merged, in report order.
+ source_formats: list[str]
+ #: Fewer than half the report's paths matched: the figures cover a fragment.
+ mapping_partial: bool | None
+ ingested_at: str | None
+ ingested_commit_sha: str | None
+ #: Null when nothing is stored or the ingest predates the record.
+ report_paths: CoverageReportPaths | None
+ #: Null when nothing is stored.
+ freshness: CoverageSummaryFreshness | None
+
+
+class CoverageResponse(BaseModel):
+ """``GET /health/coverage``. ``basis`` is absent when the graph was not consulted."""
+
+ summary: CoverageSummary
+ files: list[dict[str, Any]]
+ modules: list[dict[str, Any]]
+ modules_total: int
+ basis: Literal["measured", "inferred", "none"] | None = None
+ inferred: dict[str, Any] | None = None
diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.py
index f5797c764..661cfc903 100644
--- a/packages/server/src/repowise/server/schemas/patch_coverage.py
+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py
@@ -41,7 +41,7 @@ class PatchCoverageScope(_Strict):
label: str
source_formats: list[str]
reports: list[str]
- #: Null when unknown: stored coverage keeps only the paths that matched.
+ #: Null when unknown: stored by an ingest that did not record its path counts.
report_path_count: int | None
unmatched_report_path_count: int | None
#: Fewer than half the report's paths matched this repository.
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 8468a2087..369cec624 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -708,6 +708,47 @@ export interface CouplingNodeResponse {
nloc?: number;
}
+/** How the report's own file entries mapped to the repository at ingest. */
+export interface CoverageReportPaths {
+ total: number;
+ matched: number;
+ unmatched: number;
+ ambiguous: number;
+ unmatched_sample: string[];
+}
+
+/** ``GET /health/coverage``. ``basis`` is absent when the graph was not consulted. */
+export interface CoverageResponse {
+ summary: CoverageSummary;
+ files: Record<string, unknown>[];
+ modules: Record<string, unknown>[];
+ modules_total: number;
+ basis?: "measured" | "inferred" | "none" | null;
+ inferred?: Record<string, unknown> | null;
+}
+
+/** The repository's stored coverage, aggregated. Zero counts and nulls when none is stored. */
+export interface CoverageSummary {
+ file_count: number;
+ covered_lines: number;
+ total_lines: number;
+ line_coverage_pct: number | null;
+ branch_coverage_pct: number | null;
+ source_format: string | null;
+ source_formats: string[];
+ mapping_partial: boolean | null;
+ ingested_at: string | null;
+ ingested_commit_sha: string | null;
+ report_paths: CoverageReportPaths | null;
+ freshness: CoverageSummaryFreshness | null;
+}
+
+/** Whether the coverage was measured at the commit the index describes. */
+export interface CoverageSummaryFreshness {
+ status: "current" | "stale" | "unknown";
+ indexed_commit: string | null;
+}
+
/** 202 launch payload for a re-analysis (an index-only job, no LLM work). */
export interface DeadCodeAnalyzeResponse {
job_id: string;
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 48bd192e6..b2f4ce926 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -16,6 +16,7 @@
*/
import type { C4IoKind } from "./external-systems.js";
+import type { CoverageSummary } from "./generated/http.js";
import type { Paginated } from "./pagination.js";
import type { StepClassification, ValidationBasis, ValidationVia } from "./refactoring.js";
@@ -1034,16 +1035,17 @@ export interface ModuleCoverageRow {
line_coverage_pct: number;
}
-export interface CoverageSummary {
- file_count: number;
- covered_lines: number;
- total_lines: number;
- line_coverage_pct: number | null;
- branch_coverage_pct: number | null;
- source_format: string | null;
- ingested_at: string | null;
- ingested_commit_sha: string | null;
-}
+/**
+ * The summary is generated from the server's response model. `freshness` is
+ * `stale` when the report was measured at another commit than the indexed
+ * one; `report_paths` is how the report's own entries mapped, `null` for an
+ * ingest that did not record it.
+ */
+export type {
+ CoverageReportPaths,
+ CoverageSummary,
+ CoverageSummaryFreshness,
+} from "./generated/http.js";
/**
* Which signal answered "is this tested". `measured` is a coverage report: it
diff --git a/packages/ui/__tests__/health/coverage-provenance.test.tsx b/packages/ui/__tests__/health/coverage-provenance.test.tsx
new file mode 100644
index 000000000..2ac9ef772
--- /dev/null
+++ b/packages/ui/__tests__/health/coverage-provenance.test.tsx
@@ -0,0 +1,86 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import type { CoverageSummary, HealthCoverageResponse } from "@repowise-dev/types/health";
+import { CoverageLede } from "../../src/health/coverage-lede.js";
+import { CoverageView } from "../../src/health/coverage-view.js";
+import type { CodeHealthAdapter } from "../../src/health/code-health-adapter.js";
+
+const SUMMARY: CoverageSummary = {
+ file_count: 2,
+ covered_lines: 30,
+ total_lines: 40,
+ line_coverage_pct: 75,
+ branch_coverage_pct: null,
+ source_format: "lcov",
+ source_formats: ["lcov"],
+ mapping_partial: false,
+ ingested_at: "2026-09-28T10:00:00Z",
+ ingested_commit_sha: "aaaaaaaa11",
+ report_paths: {
+ total: 5,
+ matched: 2,
+ unmatched: 3,
+ ambiguous: 0,
+ unmatched_sample: ["/ci/build/src/gone.py"],
+ },
+ freshness: { status: "current", indexed_commit: "aaaaaaaa11" },
+};
+
+describe("CoverageLede freshness", () => {
+ it("stays quiet when the report was measured at the indexed commit", () => {
+ render(<CoverageLede summary={SUMMARY} files={[]} moduleCount={0} />);
+ expect(screen.queryByText("Measured at another commit.")).not.toBeInTheDocument();
+ });
+
+ it("says so when the report came from another commit", () => {
+ render(
+ <CoverageLede
+ summary={{
+ ...SUMMARY,
+ freshness: { status: "stale", indexed_commit: "bbbbbbbb22" },
+ }}
+ files={[]}
+ moduleCount={0}
+ />,
+ );
+ expect(screen.getByText("Measured at another commit.")).toBeInTheDocument();
+ expect(screen.getByText("bbbbbbbb")).toBeInTheDocument();
+ });
+});
+
+describe("CoverageGap report-path diagnostic", () => {
+ it("states how many report paths matched, with an example miss", async () => {
+ const response: HealthCoverageResponse = {
+ basis: "measured",
+ summary: SUMMARY,
+ files: [],
+ modules: [],
+ modules_total: 0,
+ inferred: {
+ files: [],
+ files_total: 1,
+ files_reached: 1,
+ files_not_reached: 0,
+ test_file_count: 1,
+ measured_file_count: 2,
+ },
+ };
+ const adapter = {
+ cacheKey: "provenance-test",
+ getCoverage: vi.fn().mockResolvedValue(response),
+ listFindings: vi.fn().mockResolvedValue([]),
+ navigate: vi.fn(),
+ fileHref: (p: string) => `/files/${p}`,
+ } as unknown as CodeHealthAdapter;
+
+ render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <CoverageView adapter={adapter} />
+ </SWRConfig>,
+ );
+
+ expect(await screen.findByText("2 of 5")).toBeInTheDocument();
+ expect(screen.getByText("/ci/build/src/gone.py")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/health/inferred-tests.test.tsx b/packages/ui/__tests__/health/inferred-tests.test.tsx
index b0e339ccf..b955bb390 100644
--- a/packages/ui/__tests__/health/inferred-tests.test.tsx
+++ b/packages/ui/__tests__/health/inferred-tests.test.tsx
@@ -42,8 +42,12 @@ function response(map: Partial<InferredTestMap> = {}): HealthCoverageResponse {
line_coverage_pct: null,
branch_coverage_pct: null,
source_format: null,
+ source_formats: [],
+ mapping_partial: null,
ingested_at: null,
ingested_commit_sha: null,
+ report_paths: null,
+ freshness: null,
},
files: [],
modules: [],
diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsx
index 080aa6ecb..a94f4ef9f 100644
--- a/packages/ui/src/health/coverage-lede.tsx
+++ b/packages/ui/src/health/coverage-lede.tsx
@@ -155,6 +155,8 @@ export function CoverageLede({
: "branch coverage rides on the same report."}
</p>
)}
+
+ <StaleNotice summary={summary} />
</PageLede>
<StatRibbon stats={stats} />
@@ -162,6 +164,32 @@ export function CoverageLede({
);
}
+/** Current is the quiet default; only a report from another commit is marked. */
+function StaleNotice({ summary }: { summary: CoverageSummary }) {
+ if (summary.freshness?.status !== "stale") return null;
+ return (
+ <p className="mt-2.5">
+ <strong className="font-semibold text-[var(--color-warning)]">
+ Measured at another commit.
+ </strong>{" "}
+ The report ran at{" "}
+ <span className="font-mono text-[var(--color-text-primary)]">
+ {summary.ingested_commit_sha?.slice(0, 8)}
+ </span>
+ {summary.freshness.indexed_commit ? (
+ <>
+ {" "}and the index is at{" "}
+ <span className="font-mono text-[var(--color-text-primary)]">
+ {summary.freshness.indexed_commit.slice(0, 8)}
+ </span>
+ </>
+ ) : null}
+ , so its line numbers may describe code that has since moved. Run the
+ tests and ingest again to bring it level.
+ </p>
+ );
+}
+
/** The one second read that belongs to the percentage itself. */
function BandSplit({
split,
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index af32bb691..27bbb0ae6 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -492,6 +492,8 @@ function CoverageGap({
const map = data.inferred as InferredTestMap;
const measured = map.measured_file_count ?? 0;
const unreached = map.files.filter((f) => !f.reached);
+ const paths = data.summary.report_paths;
+ const missed = paths ? paths.unmatched + paths.ambiguous : 0;
return (
<OverviewSection
@@ -502,6 +504,31 @@ function CoverageGap({
: "The dependency graph could not answer for the files the coverage report left out."
}
>
+ {/* Why a file can be missing here: the report named it under a path
+ that did not map to this repository. */}
+ {paths && paths.total > 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ <span className="tabular-nums">
+ {paths.matched.toLocaleString()} of {paths.total.toLocaleString()}
+ </span>{" "}
+ report paths matched a file in this repository
+ {missed > 0 ? (
+ <>
+ ; {missed.toLocaleString()} did not
+ {paths.unmatched_sample[0] ? (
+ <>
+ {" "}(for example{" "}
+ <span className="font-mono">{paths.unmatched_sample[0]}</span>). Set{" "}
+ <span className="font-mono">coverage.strip_prefix</span> or{" "}
+ <span className="font-mono">coverage.path_prefix</span> if the
+ paths are off
+ </>
+ ) : null}
+ </>
+ ) : null}
+ .
+ </p>
+ ) : null}
<div className="border-t border-[var(--color-border-default)]">
<ResponsiveTable
columns={gapColumns}
diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.py
index f44cbd7ac..9e4524daf 100644
--- a/tests/unit/cli/test_update_persist_reliability.py
+++ b/tests/unit/cli/test_update_persist_reliability.py
@@ -278,8 +278,8 @@ def test_reingest_with_nothing_to_read_keeps_stored_coverage(tmp_path: Path, mon
assert coverage.source_format == "lcov"
-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.
+def test_reingest_carries_the_ingest_provenance(tmp_path: Path, monkeypatch) -> None:
+ # A fragment re-ingested on update must be stored as a fragment, with its counts.
from repowise.cli.commands.update_cmd import persistence
from repowise.core.analysis.health.coverage import FileCoverage, ResolvedCoverage
@@ -292,6 +292,9 @@ def test_reingest_carries_the_partial_mapping_flag(tmp_path: Path, monkeypatch)
coverage_map={"a.py": {}},
files=[FileCoverage("a.py", 100.0, None, [1], 1, [1])],
source_format="lcov",
+ source_formats=["lcov"],
+ matched_exact=1,
+ unmatched=["x/b.py", "x/c.py"],
mapping_partial=True,
)
monkeypatch.setattr(
@@ -301,7 +304,9 @@ def test_reingest_carries_the_partial_mapping_flag(tmp_path: Path, monkeypatch)
coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, []))
assert coverage.authoritative is True
- assert coverage.mapping_partial is True
+ assert coverage.provenance.mapping_partial is True
+ assert coverage.provenance.report_path_count == 3
+ assert coverage.provenance.unmatched_sample == ("x/b.py", "x/c.py")
# ---------------------------------------------------------------------------
diff --git a/tests/unit/health/test_coverage_decay.py b/tests/unit/health/test_coverage_decay.py
index 95d69a1ab..32cf2ccfd 100644
--- a/tests/unit/health/test_coverage_decay.py
+++ b/tests/unit/health/test_coverage_decay.py
@@ -9,8 +9,8 @@ from datetime import UTC, datetime, timedelta
import pytest
from repowise.core.analysis.health.coverage import (
- STALE_DRIFT_PCT,
- STALE_MIN_MEASURED,
+ DRIFT_MIN_MEASURED,
+ DRIFT_PCT,
decay_for_file,
decay_since,
measurement_ref,
@@ -46,7 +46,7 @@ def test_no_covered_lines_does_not_divide_by_zero() -> None:
d = decay_for_file(set(), {1, 2, 3})
assert (d.measured, d.confirmed, d.invalidated) == (0, 0, 0)
assert d.drift_pct == 0.0
- assert d.is_stale is False
+ assert d.is_drifted is False
def test_confirmed_and_invalidated_always_sum_to_measured() -> None:
@@ -66,22 +66,22 @@ def test_small_file_is_never_stale_on_ratio_alone() -> None:
"""
d = decay_for_file({1}, {1})
assert d.drift_pct == 100.0
- assert d.is_stale is False
+ assert d.is_drifted is False
def test_stale_once_the_file_is_big_enough_and_drift_clears_the_bar() -> None:
- covered = set(range(1, STALE_MIN_MEASURED + 1))
+ covered = set(range(1, DRIFT_MIN_MEASURED + 1))
changed = set(list(covered)[:3]) # 30% of 10
d = decay_for_file(covered, changed)
- assert d.measured >= STALE_MIN_MEASURED
- assert d.drift_pct > STALE_DRIFT_PCT
- assert d.is_stale is True
+ assert d.measured >= DRIFT_MIN_MEASURED
+ assert d.drift_pct > DRIFT_PCT
+ assert d.is_drifted is True
def test_big_file_under_the_bar_is_not_stale() -> None:
covered = set(range(1, 101))
d = decay_for_file(covered, {1, 2}) # 2%
- assert d.is_stale is False
+ assert d.is_drifted is False
# --- end-to-end against a real git repo ------------------------------------
diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.py
index 4c5c3496b..c6709b84c 100644
--- a/tests/unit/persistence/test_coverage_loaders.py
+++ b/tests/unit/persistence/test_coverage_loaders.py
@@ -108,3 +108,84 @@ async def test_stored_patch_coverage_is_none_without_coverage(async_session, rep
from repowise.core.analysis.patch_coverage import stored_patch_coverage
assert await stored_patch_coverage(async_session, repo.id, {"a.py": {1}}) is None
+
+
+async def test_ingest_provenance_reaches_the_summary_and_stored_patch_scope(
+ async_session, repo
+) -> None:
+ from repowise.core.analysis.patch_coverage import stored_patch_coverage
+ from repowise.core.persistence.crud import get_coverage_summary
+
+ lcov = _LCOV + "SF:/elsewhere/gone.py\nDA:1,1\nend_of_record\n"
+ resolved = resolve_reports([parse_lcov(lcov)], {"src/a.py"})
+ await save_coverage_files(
+ async_session,
+ repo.id,
+ resolved.files,
+ source_format="lcov",
+ ingested_commit_sha="abc",
+ provenance=resolved.provenance,
+ )
+
+ summary = await get_coverage_summary(async_session, repo.id, reference_commit="def")
+ assert summary["source_formats"] == ["lcov"]
+ assert summary["report_paths"] == {
+ "total": 2,
+ "matched": 1,
+ "unmatched": 1,
+ "ambiguous": 0,
+ "unmatched_sample": ["/elsewhere/gone.py"],
+ }
+ assert summary["freshness"] == {"status": "stale", "indexed_commit": "def"}
+
+ stored = await stored_patch_coverage(async_session, repo.id, {"src/a.py": {1}})
+ assert stored is not None
+ assert stored.scope.report_path_count == 2
+ assert stored.scope.unmatched_report_path_count == 1
+
+
+async def test_an_ingest_without_provenance_leaves_path_counts_unknown(
+ async_session, repo
+) -> None:
+ from repowise.core.persistence.crud import get_coverage_summary
+
+ await save_coverage_files(
+ async_session, repo.id, [file_coverage("a.py", [1], [1])], source_format="cobertura"
+ )
+ summary = await get_coverage_summary(async_session, repo.id)
+
+ assert summary["report_paths"] is None
+ assert summary["source_formats"] == ["cobertura"]
+ assert summary["freshness"] == {"status": "unknown", "indexed_commit": None}
+
+
+async def test_a_reingest_replaces_the_previous_provenance(async_session, repo) -> None:
+ from repowise.core.persistence.crud import get_coverage_summary
+
+ resolved = resolve_reports([parse_lcov(_LCOV)], {"src/a.py"})
+ for commit in ("one", "two"):
+ await save_coverage_files(
+ async_session,
+ repo.id,
+ resolved.files,
+ source_format="lcov",
+ ingested_commit_sha=commit,
+ provenance=resolved.provenance,
+ )
+
+ summary = await get_coverage_summary(async_session, repo.id, reference_commit="two")
+ assert summary["freshness"]["status"] == "current"
+ assert summary["report_paths"]["total"] == 1
+
+
+async def test_summary_counts_covered_lines_exactly(async_session, repo) -> None:
+ # 10,001 of 20,001 is 50.0025%, stored as 50.0; deriving the count back
+ # from the percentage would say 10,000.
+ from repowise.core.persistence.crud import get_coverage_summary
+
+ fc = file_coverage("big.py", range(1, 10_002), range(1, 20_002))
+ await save_coverage_files(async_session, repo.id, [fc], source_format="lcov")
+
+ summary = await get_coverage_summary(async_session, repo.id)
+ assert fc.line_coverage_pct == 50.0
+ assert summary["covered_lines"] == 10_001
diff --git a/tests/unit/persistence/test_coverage_narrow_read.py b/tests/unit/persistence/test_coverage_narrow_read.py
index 1f01f7da9..99d66fb5c 100644
--- a/tests/unit/persistence/test_coverage_narrow_read.py
+++ b/tests/unit/persistence/test_coverage_narrow_read.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import pytest
+from repowise.core.analysis.health.coverage import CoverageProvenance
from repowise.core.persistence.crud import (
get_coverage_summary,
load_coverage_for_repo,
@@ -137,7 +138,7 @@ async def test_summary_reports_mapping_partial_when_ingest_was_fragment(
r.id,
_FILES,
source_format="lcov",
- mapping_partial=True,
+ provenance=CoverageProvenance(mapping_partial=True),
)
summary = await get_coverage_summary(async_session, r.id)
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 4dc155fc7..b9291290c 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -332,6 +332,7 @@ def test_base_includes_all_models():
"performance_opportunities",
"performance_summaries",
"coverage_files",
+ "coverage_ingests",
"test_coverage",
"pipeline_jobs",
"graph_metrics",
diff --git a/tests/unit/pipeline/test_coverage_ingestion.py b/tests/unit/pipeline/test_coverage_ingestion.py
index 248b075cc..579daf5f2 100644
--- a/tests/unit/pipeline/test_coverage_ingestion.py
+++ b/tests/unit/pipeline/test_coverage_ingestion.py
@@ -44,7 +44,7 @@ def test_explicit_paths_take_priority(tmp_path: Path) -> None:
report.write_text("SF:src/a.ts\nDA:1,1\nend_of_record\n")
parsed = [_parsed("src/a.ts")]
- coverage_map, _files, _fmt, _partial = _build_pipeline_coverage(
+ coverage_map, _files, _fmt, _provenance = _build_pipeline_coverage(
tmp_path, parsed, [report], progress=None
)
assert "src/a.ts" in coverage_map
@@ -52,13 +52,13 @@ def test_explicit_paths_take_priority(tmp_path: Path) -> None:
def test_no_report_yields_empty_map(tmp_path: Path) -> None:
parsed = [_parsed("src/a.ts")]
- coverage_map, files, fmt, partial = _build_pipeline_coverage(
+ coverage_map, files, fmt, provenance = _build_pipeline_coverage(
tmp_path, parsed, None, progress=None
)
assert coverage_map == {}
assert files == []
assert fmt is None
- assert partial is False
+ assert provenance is None
def test_auto_discover_disabled_via_config(tmp_path: Path) -> None:
@@ -70,7 +70,7 @@ def test_auto_discover_disabled_via_config(tmp_path: Path) -> None:
)
parsed = [_parsed("src/a.ts")]
- coverage_map, _files, _fmt, _partial = _build_pipeline_coverage(
+ coverage_map, _files, _fmt, _provenance = _build_pipeline_coverage(
tmp_path, parsed, None, progress=None
)
assert coverage_map == {}
@@ -88,7 +88,7 @@ def test_strip_prefix_from_config(tmp_path: Path) -> None:
)
parsed = [_parsed("web/index.ts"), _parsed("api/index.ts")]
- coverage_map, _files, _fmt, _partial = _build_pipeline_coverage(
+ coverage_map, _files, _fmt, _provenance = _build_pipeline_coverage(
tmp_path, parsed, None, progress=None
)
assert "web/index.ts" in coverage_map
diff --git a/tests/unit/server/mcp/test_context_enrichment.py b/tests/unit/server/mcp/test_context_enrichment.py
index 6808c3299..1c02bcfd9 100644
--- a/tests/unit/server/mcp/test_context_enrichment.py
+++ b/tests/unit/server/mcp/test_context_enrichment.py
@@ -408,11 +408,19 @@ async def test_health_for_a_symbol_target_reads_its_file_with_stored_coverage_an
assert health["max_ccn"] == 15
assert health["has_test_file"] is False
assert health["module"] == "auth"
- assert health["coverage"] == {
+ coverage = health["coverage"]
+ assert "covered_lines" not in coverage
+ assert {k: coverage[k] for k in (
+ "file_path", "source_format", "line_coverage_pct", "branch_coverage_pct",
+ "total_coverable_lines", "covered_line_count",
+ )} == {
+ "file_path": "src/auth/service.py",
"source_format": "lcov",
"line_coverage_pct": 61.5,
"branch_coverage_pct": 40.0,
"total_coverable_lines": 200,
+ # No stored count on this row, so derived from 61.5% of 200.
+ "covered_line_count": 123,
}
assert len(health["top_biomarkers"]) == 2
top = health["top_biomarkers"][0]
diff --git a/tests/unit/server/mcp/test_health_coverage_decay.py b/tests/unit/server/mcp/test_health_coverage_decay.py
index 4bafa5dbb..b92d62a03 100644
--- a/tests/unit/server/mcp/test_health_coverage_decay.py
+++ b/tests/unit/server/mcp/test_health_coverage_decay.py
@@ -9,10 +9,8 @@ from datetime import UTC, datetime
import pytest
-from repowise.server.mcp_server.tool_health import (
- _attach_coverage_decay,
- _serialize_coverage_row,
-)
+from repowise.core.persistence.crud import coverage_row_dict
+from repowise.server.mcp_server.tool_health import _attach_coverage_decay
def _git(cwd, *args: str) -> str:
@@ -52,7 +50,7 @@ def test_decay_marks_the_lines_that_moved_since_the_report(repo) -> None:
_git(repo, "commit", "-qm", "edit")
rows = [_row("mod.py", [1, 2, 3], sha=base)]
- payload = [_serialize_coverage_row(r) for r in rows]
+ payload = [coverage_row_dict(r, include_covered_lines=True) for r in rows]
_attach_coverage_decay(payload, rows, str(repo))
decay = payload[0]["decay"]
@@ -75,7 +73,7 @@ def test_the_stored_percentage_is_never_rewritten(repo) -> None:
_git(repo, "commit", "-qm", "edit")
rows = [_row("mod.py", [1, 2, 3], sha=base, pct=75.0)]
- payload = [_serialize_coverage_row(r) for r in rows]
+ payload = [coverage_row_dict(r, include_covered_lines=True) for r in rows]
_attach_coverage_decay(payload, rows, str(repo))
assert payload[0]["line_coverage_pct"] == 75.0
@@ -86,7 +84,7 @@ def test_no_decay_block_when_the_measurement_cannot_be_placed(repo) -> None:
"""Absent, not zero. A zero drift block would read as a freshness claim."""
rows = [_row("mod.py", [1, 2, 3], sha=None)]
rows[0].ingested_at = None
- payload = [_serialize_coverage_row(r) for r in rows]
+ payload = [coverage_row_dict(r, include_covered_lines=True) for r in rows]
_attach_coverage_decay(payload, rows, str(repo))
assert "decay" not in payload[0]
@@ -95,7 +93,7 @@ def test_no_decay_block_when_the_measurement_cannot_be_placed(repo) -> None:
def test_a_row_with_no_covered_lines_gets_no_decay_block(repo) -> None:
head = _git(repo, "rev-parse", "HEAD").strip()
rows = [_row("mod.py", [], sha=head)]
- payload = [_serialize_coverage_row(r) for r in rows]
+ payload = [coverage_row_dict(r, include_covered_lines=True) for r in rows]
_attach_coverage_decay(payload, rows, str(repo))
assert "decay" not in payload[0]
@@ -104,11 +102,11 @@ def test_a_row_with_no_covered_lines_gets_no_decay_block(repo) -> None:
def test_untouched_file_reports_a_confirmed_measurement(repo) -> None:
head = _git(repo, "rev-parse", "HEAD").strip()
rows = [_row("mod.py", [1, 2, 3], sha=head)]
- payload = [_serialize_coverage_row(r) for r in rows]
+ payload = [coverage_row_dict(r, include_covered_lines=True) for r in rows]
_attach_coverage_decay(payload, rows, str(repo))
assert payload[0]["decay"]["invalidated_lines"] == 0
- assert payload[0]["decay"]["stale"] is False
+ assert payload[0]["decay"]["drifted"] is False
def test_empty_row_list_is_a_no_op(repo) -> None:
diff --git a/tests/unit/server/test_health_coverage_route.py b/tests/unit/server/test_health_coverage_route.py
index 0ead72a9d..12e104c71 100644
--- a/tests/unit/server/test_health_coverage_route.py
+++ b/tests/unit/server/test_health_coverage_route.py
@@ -196,3 +196,24 @@ async def test_covered_lines_are_withheld_from_the_list_response(
assert all("covered_lines" not in f for f in listed["files"])
assert detail["files"][0]["covered_lines"] == [1, 2, 3]
+
+
+async def test_summary_says_whether_coverage_was_measured_at_the_indexed_commit(
+ client, session, tmp_path
+) -> None:
+ from repowise.core.persistence.models import Repository
+
+ repo = await create_test_repo(client, tmp_path)
+ await save_coverage_files(
+ session, repo["id"], _FILES, source_format="lcov", ingested_commit_sha="aaa"
+ )
+ row = await session.get(Repository, repo["id"])
+ row.head_commit = "bbb"
+ await session.commit()
+
+ summary = (await _get(client, repo["id"], include_inferred="false"))["summary"]
+
+ assert summary["freshness"] == {"status": "stale", "indexed_commit": "bbb"}
+ # Written without provenance: the counts are unknown, not zero.
+ assert summary["report_paths"] is None
+ assert summary["source_formats"] == ["lcov"]
diff --git a/tests/unit/server/test_response_contract.py b/tests/unit/server/test_response_contract.py
index 1d7b11ce7..f0ed2cad6 100644
--- a/tests/unit/server/test_response_contract.py
+++ b/tests/unit/server/test_response_contract.py
@@ -44,7 +44,6 @@ UNMODELLED: frozenset[tuple[str, str]] = frozenset(
("GET", "/api/repos/{repo_id}/files"),
("GET", "/api/repos/{repo_id}/files/{file_path}"),
("POST", "/api/repos/{repo_id}/generate/estimate"),
- ("GET", "/api/repos/{repo_id}/health/coverage"),
("GET", "/api/repos/{repo_id}/health/files"),
("GET", "/api/repos/{repo_id}/health/files/breakdown"),
("GET", "/api/repos/{repo_id}/health/map"),