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): keep a coverage history and show its trend (#2642)

Raghav Chamadiyad9cbf2de5a5b
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index d1f2cac81..9138cf073 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -123,6 +123,15 @@ 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.
+Ingest records are kept as history, not replaced: each one also stores the
+repo-wide line and branch coverage it measured, and the newest 50 are
+retained. REST `/health/coverage` returns them oldest first as `history`, and
+the Coverage tab draws a trend under the headline figure once there are three
+reports. Partial ingests are left out of the trend, since their figure covers
+a fragment of the repository. A local index created before this change keeps
+a single record per repository (its table still carries the old uniqueness
+rule) until it is rebuilt.
+
A few rules keep that matching honest in monorepos and mixed layouts:
- A match needs more than the basename when the report names a directory:
diff --git a/packages/core/alembic/versions/0081_coverage_ingest_history.py b/packages/core/alembic/versions/0081_coverage_ingest_history.py
new file mode 100644
index 000000000..93d1c341e
--- /dev/null
+++ b/packages/core/alembic/versions/0081_coverage_ingest_history.py
@@ -0,0 +1,79 @@
+"""coverage_ingests: keep one row per ingest, with its repo-wide figures.
+
+The one-row-per-repository unique constraint is dropped so each ingest adds a
+row, and an index on ``(repository_id, ingested_at)`` serves the newest-first
+read. ``line_coverage_pct``, ``branch_coverage_pct``, ``covered_lines`` and
+``total_lines`` hold what that ingest measured, so the coverage trend reads
+one row per report. NULL on rows written before them.
+
+Local SQLite stores never run Alembic: ``init_db``'s reconciler adds the
+columns and the index but never drops a constraint, so ``save_coverage_files``
+keeps the single-row behaviour on a store that still carries it. Every step is
+guarded because the reconciler may have run first.
+
+Revision ID: 0081
+Revises: 0080
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0081"
+down_revision: str | None = "0080"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_TABLE = "coverage_ingests"
+_UNIQUE = "uq_coverage_ingests"
+_INDEX = "ix_coverage_ingests_repo_ingested"
+_FIGURES = (
+ ("line_coverage_pct", sa.Float()),
+ ("branch_coverage_pct", sa.Float()),
+ ("covered_lines", sa.Integer()),
+ ("total_lines", sa.Integer()),
+)
+
+
+def _inspector() -> sa.engine.reflection.Inspector:
+ return sa.inspect(op.get_bind())
+
+
+def upgrade() -> None:
+ columns = {c["name"] for c in _inspector().get_columns(_TABLE)}
+ for name, type_ in _FIGURES:
+ if name not in columns:
+ op.add_column(_TABLE, sa.Column(name, type_, nullable=True))
+ uniques = {u["name"] for u in _inspector().get_unique_constraints(_TABLE)}
+ if _UNIQUE in uniques:
+ # Batch mode rebuilds the table on SQLite, which cannot drop a constraint.
+ with op.batch_alter_table(_TABLE) as batch:
+ batch.drop_constraint(_UNIQUE, type_="unique")
+ if _INDEX not in {i["name"] for i in _inspector().get_indexes(_TABLE)}:
+ op.create_index(_INDEX, _TABLE, ["repository_id", "ingested_at"])
+
+
+def downgrade() -> None:
+ if _INDEX in {i["name"] for i in _inspector().get_indexes(_TABLE)}:
+ op.drop_index(_INDEX, table_name=_TABLE)
+ # Restoring the constraint needs one row per repository: keep the newest.
+ op.execute(
+ sa.text(
+ f"DELETE FROM {_TABLE} WHERE id NOT IN ("
+ f"SELECT id FROM (SELECT id, ROW_NUMBER() OVER ("
+ f"PARTITION BY repository_id ORDER BY ingested_at DESC, id DESC) AS rn "
+ f"FROM {_TABLE}) ranked WHERE rn = 1)"
+ )
+ )
+ with op.batch_alter_table(_TABLE) as batch:
+ if _UNIQUE not in {u["name"] for u in _inspector().get_unique_constraints(_TABLE)}:
+ batch.create_unique_constraint(_UNIQUE, ["repository_id"])
+ columns = {c["name"] for c in _inspector().get_columns(_TABLE)}
+ for name, _ in _FIGURES:
+ if name in columns:
+ batch.drop_column(name)
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 6bae3b3db..28ae23679 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -24,6 +24,7 @@ from .coverage import (
file_coverage_from_row,
get_coverage_summary,
load_coverage_for_repo,
+ load_coverage_history,
load_coverage_map,
load_file_coverage,
save_coverage_files,
@@ -163,6 +164,7 @@ __all__ = [
"list_performance_opportunities",
"list_refactoring_opportunities",
"load_coverage_for_repo",
+ "load_coverage_history",
"load_coverage_map",
"load_file_coverage",
"opportunity_details",
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 081a8e984..3cb2fca66 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,14 @@
from __future__ import annotations
import json
+from collections.abc import Iterable
+from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal, overload
-from sqlalchemy import select
+from sqlalchemy import delete, inspect, select
from sqlalchemy.ext.asyncio import AsyncSession
-from ...models import CoverageFile, CoverageIngest, _new_uuid
+from ...models import CoverageFile, CoverageIngest, _new_uuid, _now_utc
if TYPE_CHECKING:
from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
@@ -16,6 +18,9 @@ if TYPE_CHECKING:
from repowise.core.analysis.health.coverage.model import FileCoverage
from .._shared import _BATCH_SIZE
+#: Ingest rows kept per repo for the coverage trend; older ones are pruned on write.
+COVERAGE_HISTORY_RETENTION: int = 50
+
async def save_coverage_files(
session: AsyncSession,
@@ -25,59 +30,173 @@ async def save_coverage_files(
source_format: str,
ingested_commit_sha: str | None = None,
provenance: CoverageProvenance | None = None,
+ ingested_at: datetime | None = None,
) -> None:
"""Replace coverage rows for *repository_id* with *files*, and record the ingest.
- Mirrors the delete-then-insert pattern used by the health writers.
+ Mirrors the delete-then-insert pattern used by the health writers for the
+ per-file rows; the ingest row is appended, with the repo-wide figures of
+ *files*, unless the newest one already says exactly that (then it is
+ restamped), and ingests past ``COVERAGE_HISTORY_RETENTION`` are pruned.
*files* is a list of ``FileCoverage`` dataclasses (or dicts with the
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.
+ *ingested_at* defaults to now.
"""
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)
+ at = ingested_at or _now_utc()
+ existing = await session.execute(
+ select(CoverageFile).where(CoverageFile.repository_id == repository_id)
+ )
+ for row in existing.scalars().all():
+ await session.delete(row)
+ if await _ingest_is_single_row(session):
+ await session.execute(
+ delete(CoverageIngest).where(CoverageIngest.repository_id == repository_id)
+ )
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,
- )
+ columns = [_row_columns(f) for f in files]
+ await _record_ingest(
+ session,
+ repository_id,
+ _ingest_figures(columns, p, source_format),
+ at=at,
+ commit=ingested_commit_sha,
)
- for i in range(0, len(files), _BATCH_SIZE):
- for f in files[i : i + _BATCH_SIZE]:
+ for i in range(0, len(columns), _BATCH_SIZE):
+ for c in columns[i : i + _BATCH_SIZE]:
session.add(
CoverageFile(
id=_new_uuid(),
repository_id=repository_id,
source_format=source_format,
+ ingested_at=at,
ingested_commit_sha=ingested_commit_sha,
mapping_partial=p.mapping_partial,
- **_row_columns(f),
+ **c,
)
)
await session.flush()
+ await session.flush() # the ingest row, when *files* is empty
+ await _prune_history(session, repository_id)
+
+
+def _ingest_figures(
+ columns: list[dict[str, Any]], p: CoverageProvenance, source_format: str
+) -> dict[str, Any]:
+ """The ingest row's measured columns: its provenance and repo-wide figures."""
+ covered, total, line_pct, branch_pct = _aggregate(
+ (
+ c["covered_line_count"],
+ int(c.get("total_coverable_lines") or 0),
+ c.get("branch_coverage_pct"),
+ )
+ for c in columns
+ )
+ return {
+ "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,
+ # No coverable lines is no measurement, which keeps it off the trend.
+ "line_coverage_pct": line_pct if total else None,
+ "branch_coverage_pct": branch_pct,
+ "covered_lines": covered,
+ "total_lines": total,
+ }
+
+
+async def _newest_ingest(session: AsyncSession, repository_id: str) -> CoverageIngest | None:
+ return (
+ await session.execute(
+ select(CoverageIngest)
+ .where(CoverageIngest.repository_id == repository_id)
+ .order_by(CoverageIngest.ingested_at.desc(), CoverageIngest.id.desc())
+ .limit(1)
+ )
+ ).scalar_one_or_none()
+
+
+async def _record_ingest(
+ session: AsyncSession,
+ repository_id: str,
+ measured: dict[str, Any],
+ *,
+ at: datetime,
+ commit: str | None,
+) -> None:
+ """Append the ingest, or restamp the newest when it measured exactly this.
+
+ The same report ingested again (an update that re-ingests, a full
+ re-index) is one measurement, not a new trend point.
+ """
+ newest = await _newest_ingest(session, repository_id)
+ if newest is not None and all(getattr(newest, k) == v for k, v in measured.items()):
+ newest.ingested_at = at
+ newest.ingested_commit_sha = commit
+ return
+ session.add(
+ CoverageIngest(
+ id=_new_uuid(),
+ repository_id=repository_id,
+ ingested_at=at,
+ ingested_commit_sha=commit,
+ **measured,
+ )
+ )
+
+
+async def _prune_history(session: AsyncSession, repository_id: str) -> None:
+ """Drop ingests past ``COVERAGE_HISTORY_RETENTION``, oldest first."""
+ history = await session.execute(
+ select(CoverageIngest.id)
+ .where(CoverageIngest.repository_id == repository_id)
+ .order_by(CoverageIngest.ingested_at.desc(), CoverageIngest.id.desc())
+ .offset(COVERAGE_HISTORY_RETENTION)
+ )
+ stale = list(history.scalars().all())
+ if stale:
+ await session.execute(delete(CoverageIngest).where(CoverageIngest.id.in_(stale)))
+
+
+async def _ingest_is_single_row(session: AsyncSession) -> bool:
+ """Whether the live ``coverage_ingests`` still allows one row per repository.
+
+ Local SQLite stores never run Alembic, and the reconciler that upgrades
+ them adds columns and indexes but never drops a constraint, so a store
+ created before migration 0081 keeps the unique ``repository_id``. There
+ the ingest row is replaced rather than appended: the store keeps working
+ with a one-point history. Ceiling: such a store gains history only once
+ the table is rebuilt (deleting ``.repowise`` and re-indexing does it).
+ """
+
+ def _check(sync_session: Any) -> bool:
+ uniques = inspect(sync_session.connection()).get_unique_constraints("coverage_ingests")
+ return any(u["column_names"] == ["repository_id"] for u in uniques)
+
+ return await session.run_sync(_check)
#: 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"}
+ {
+ "id",
+ "repository_id",
+ "source_format",
+ "ingested_at",
+ "ingested_commit_sha",
+ "mapping_partial",
+ }
)
@@ -337,6 +456,67 @@ def _source_formats(ingest: CoverageIngest | None, fallback: str | None) -> list
return [fallback] if fallback else []
+def _aggregate(
+ parts: Iterable[tuple[int, int, float | None]],
+) -> tuple[int, int, float, float | None]:
+ """Repo-wide ``(covered, total, line %, branch %)`` from per-file figures.
+
+ *parts* is ``(covered lines, coverable lines, branch %)`` per file. Branch
+ coverage is weighted by coverable lines, over the files that report it.
+ """
+ covered = 0
+ total = 0
+ branch_sum = 0.0
+ branch_weight = 0
+ for file_covered, file_total, branch in parts:
+ covered += file_covered
+ total += file_total
+ if branch is not None:
+ weight = max(file_total, 1)
+ branch_sum += branch * weight
+ branch_weight += weight
+ line_pct = round(covered / total * 100.0, 2) if total else 0.0
+ branch_pct = round(branch_sum / branch_weight, 2) if branch_weight else None
+ return covered, total, line_pct, branch_pct
+
+
+async def load_coverage_history(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ limit: int = COVERAGE_HISTORY_RETENTION,
+) -> list[dict[str, Any]]:
+ """The newest *limit* ingests' repo-wide figures, oldest first, for a trend.
+
+ Rows written before the figures existed are skipped, and so are partial
+ ingests: their figure is a subset's coverage, not the repository's.
+ """
+ result = await session.execute(
+ select(
+ CoverageIngest.ingested_at,
+ CoverageIngest.ingested_commit_sha,
+ CoverageIngest.line_coverage_pct,
+ CoverageIngest.branch_coverage_pct,
+ )
+ .where(
+ CoverageIngest.repository_id == repository_id,
+ CoverageIngest.line_coverage_pct.is_not(None),
+ CoverageIngest.mapping_partial.is_(False),
+ )
+ .order_by(CoverageIngest.ingested_at.desc(), CoverageIngest.id.desc())
+ .limit(limit)
+ )
+ return [
+ {
+ "ingested_at": row.ingested_at.isoformat(),
+ "ingested_commit_sha": row.ingested_commit_sha,
+ "line_coverage_pct": row.line_coverage_pct,
+ "branch_coverage_pct": row.branch_coverage_pct,
+ }
+ for row in reversed(result.all())
+ ]
+
+
async def get_coverage_summary(
session: AsyncSession,
repository_id: str,
@@ -365,28 +545,10 @@ async def get_coverage_summary(
)
if not rows:
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 += _covered_count(r)
- total += r.total_coverable_lines
- if r.branch_coverage_pct is not None:
- branch_pcts.append(r.branch_coverage_pct)
- branch_weights.append(max(r.total_coverable_lines, 1))
- line_pct = (covered / total * 100.0) if total else 0.0
- branch_pct: float | None
- if branch_pcts:
- wsum = sum(branch_weights)
- branch_pct = sum(p * w for p, w in zip(branch_pcts, branch_weights, strict=True)) / wsum
- else:
- branch_pct = None
+ ingest = await _newest_ingest(session, repository_id)
+ covered, total, line_pct, branch_pct = _aggregate(
+ (_covered_count(r), r.total_coverable_lines, r.branch_coverage_pct) for r in rows
+ )
latest = max(rows, key=lambda r: r.ingested_at)
# A partial ingest is a whole-table property: every row of the latest
# delete-then-insert batch carries the same flag, so any row reports the
@@ -398,8 +560,8 @@ async def get_coverage_summary(
"file_count": len(rows),
"covered_lines": covered,
"total_lines": total,
- "line_coverage_pct": round(line_pct, 2),
- "branch_coverage_pct": round(branch_pct, 2) if branch_pct is not None else None,
+ "line_coverage_pct": line_pct,
+ "branch_coverage_pct": branch_pct,
"source_format": latest.source_format,
"source_formats": _source_formats(ingest, latest.source_format),
"mapping_partial": mapping_partial,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index bf60ab8f0..6216abb4b 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2226,11 +2226,12 @@ class CoverageFile(Base):
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.
+ Kept as history: the newest row describes the stored coverage rows, and
+ older ones (pruned past ``COVERAGE_HISTORY_RETENTION``) keep the repo-wide
+ figures of earlier reports for the trend. 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; NULL figures mean the row predates them.
"""
__tablename__ = "coverage_ingests"
@@ -2252,8 +2253,16 @@ class CoverageIngest(Base):
DateTime(timezone=True), nullable=False, default=_now_utc
)
ingested_commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)
+ # The repo-wide figures this ingest wrote, aggregated the way the summary
+ # aggregates the stored rows, so the trend reads one row per report.
+ line_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
+ branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
+ covered_lines: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ total_lines: Mapped[int | None] = mapped_column(Integer, nullable=True)
- __table_args__ = (UniqueConstraint("repository_id", name="uq_coverage_ingests"),)
+ __table_args__ = (
+ Index("ix_coverage_ingests_repo_ingested", "repository_id", "ingested_at"),
+ )
class TestCoverageEntry(Base):
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 5bdc6d8c0..005cd5683 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
@@ -103,6 +103,7 @@ async def health_coverage(
)
if summary.get("ingested_at") is not None:
summary = {**summary, "ingested_at": summary["ingested_at"].isoformat()}
+ history = await _history_block(session, repo_id, badge=bool(file_path) or module_limit == 0)
if file_path:
# The one caller that wants the covered-line set, for one file.
@@ -158,6 +159,7 @@ async def health_coverage(
"modules": module_rows[:module_limit] if module_limit else [],
"modules_total": len(module_rows),
"inferred": inferred["inferred"],
+ **history,
}
return {
@@ -166,9 +168,21 @@ async def health_coverage(
"files": files,
"modules": module_rows[:module_limit] if module_limit else [],
"modules_total": len(module_rows),
+ **history,
}
+async def _history_block(session: AsyncSession, repo_id: str, *, badge: bool) -> dict[str, Any]:
+ """One point per ingested report, oldest first; measured basis only.
+
+ Left off the one-file and no-module reads (the tab badge), which never
+ draw it.
+ """
+ if badge:
+ return {}
+ return {"history": await crud.load_coverage_history(session, repo_id)}
+
+
async def _inferred_coverage(
session: AsyncSession,
repo_id: str,
diff --git a/packages/server/src/repowise/server/schemas/coverage.py b/packages/server/src/repowise/server/schemas/coverage.py
index 8a9c196e5..7c14e9681 100644
--- a/packages/server/src/repowise/server/schemas/coverage.py
+++ b/packages/server/src/repowise/server/schemas/coverage.py
@@ -61,6 +61,15 @@ class CoverageSummary(_Strict):
freshness: CoverageSummaryFreshness | None
+class CoverageHistoryPoint(_Strict):
+ """One ingested report's repo-wide figures, as ``crud.load_coverage_history`` reads them."""
+
+ ingested_at: str
+ ingested_commit_sha: str | None
+ line_coverage_pct: float
+ branch_coverage_pct: float | None
+
+
class CoverageResponse(BaseModel):
"""``GET /health/coverage``. ``basis`` is absent when the graph was not consulted."""
@@ -70,3 +79,5 @@ class CoverageResponse(BaseModel):
modules_total: int
basis: Literal["measured", "inferred", "none"] | None = None
inferred: dict[str, Any] | None = None
+ #: Retained reports, oldest first, partial ones left out. Measured basis only.
+ history: list[CoverageHistoryPoint] | None = None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 369cec624..07a0355cd 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -708,6 +708,14 @@ export interface CouplingNodeResponse {
nloc?: number;
}
+/** One ingested report's repo-wide figures, as ``crud.load_coverage_history`` reads them. */
+export interface CoverageHistoryPoint {
+ ingested_at: string;
+ ingested_commit_sha: string | null;
+ line_coverage_pct: number;
+ branch_coverage_pct: number | null;
+}
+
/** How the report's own file entries mapped to the repository at ingest. */
export interface CoverageReportPaths {
total: number;
@@ -725,6 +733,7 @@ export interface CoverageResponse {
modules_total: number;
basis?: "measured" | "inferred" | "none" | null;
inferred?: Record<string, unknown> | null;
+ history?: CoverageHistoryPoint[] | null;
}
/** The repository's stored coverage, aggregated. Zero counts and nulls when none is stored. */
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index b2f4ce926..881af651e 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -16,7 +16,7 @@
*/
import type { C4IoKind } from "./external-systems.js";
-import type { CoverageSummary } from "./generated/http.js";
+import type { CoverageHistoryPoint, CoverageSummary } from "./generated/http.js";
import type { Paginated } from "./pagination.js";
import type { StepClassification, ValidationBasis, ValidationVia } from "./refactoring.js";
@@ -1042,6 +1042,7 @@ export interface ModuleCoverageRow {
* ingest that did not record it.
*/
export type {
+ CoverageHistoryPoint,
CoverageReportPaths,
CoverageSummary,
CoverageSummaryFreshness,
@@ -1153,6 +1154,11 @@ export interface HealthCoverageResponse {
* the inferred map carries counts only — never a percentage.
*/
inferred?: InferredTestMap;
+ /**
+ * One point per retained report, oldest first, partial reports left out.
+ * Present on the measured basis only; absent from an older backend.
+ */
+ history?: CoverageHistoryPoint[];
}
/* ------------------------------------------------------------------ *
diff --git a/packages/ui/__tests__/health/coverage-trend.test.tsx b/packages/ui/__tests__/health/coverage-trend.test.tsx
new file mode 100644
index 000000000..9e5c4b978
--- /dev/null
+++ b/packages/ui/__tests__/health/coverage-trend.test.tsx
@@ -0,0 +1,93 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import type { CoverageHistoryPoint, CoverageSummary } from "@repowise-dev/types/health";
+import { CoverageLede } from "../../src/health/coverage-lede.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: null,
+ freshness: { status: "current", indexed_commit: "aaaaaaaa11" },
+};
+
+function points(...pcts: number[]): CoverageHistoryPoint[] {
+ return pcts.map((pct, i) => ({
+ ingested_at: `2026-09-2${i}T10:00:00Z`,
+ ingested_commit_sha: `c${i}`,
+ line_coverage_pct: pct,
+ branch_coverage_pct: null,
+ }));
+}
+
+function renderLede(history?: CoverageHistoryPoint[]) {
+ return render(
+ <CoverageLede summary={SUMMARY} files={[]} moduleCount={0} history={history} />,
+ );
+}
+
+describe("CoverageLede trend", () => {
+ it("draws nothing for fewer than three reports", () => {
+ const { container } = renderLede(points(70, 75));
+ expect(container.querySelector("svg path")).toBeNull();
+ expect(screen.queryByText(/across the last/)).not.toBeInTheDocument();
+ });
+
+ it("draws nothing without a history", () => {
+ const { container } = renderLede();
+ expect(container.querySelector("svg path")).toBeNull();
+ });
+
+ it("draws the line and says which way it moved from three reports", () => {
+ const { container } = renderLede(points(71.8, 73, 75));
+ expect(container.querySelector("svg path")).not.toBeNull();
+ expect(
+ screen.getByText("Up 3.2 points across the last 3 reports, from 71.8% to 75.0%."),
+ ).toBeInTheDocument();
+ });
+
+ it("names a fall in words", () => {
+ renderLede(points(80, 78, 75));
+ expect(
+ screen.getByText("Down 5.0 points across the last 3 reports, from 80.0% to 75.0%."),
+ ).toBeInTheDocument();
+ });
+
+ it("measures the move between the figures it prints", () => {
+ // 71.84 and 75.06 print as 71.8 and 75.1: the gap is 3.3, not 3.22.
+ renderLede(points(71.84, 73, 75.06));
+ expect(
+ screen.getByText("Up 3.3 points across the last 3 reports, from 71.8% to 75.1%."),
+ ).toBeInTheDocument();
+ });
+
+ it("calls a flat series unchanged", () => {
+ renderLede(points(75, 75.01, 75));
+ expect(screen.getByText("Unchanged at 75.0% across the last 3 reports.")).toBeInTheDocument();
+ });
+
+ it("says back at when the series moved and returned", () => {
+ renderLede(points(75, 74, 75));
+ expect(screen.getByText("Back at 75.0% across the last 3 reports.")).toBeInTheDocument();
+ });
+
+ it("hides the trend under a partial headline", () => {
+ const { container } = render(
+ <CoverageLede
+ summary={{ ...SUMMARY, mapping_partial: true }}
+ files={[]}
+ moduleCount={0}
+ history={points(70, 72, 75)}
+ />,
+ );
+ expect(container.querySelector("svg path")).toBeNull();
+ expect(screen.queryByText(/across the last/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsx
index a94f4ef9f..fc36ae8c2 100644
--- a/packages/ui/src/health/coverage-lede.tsx
+++ b/packages/ui/src/health/coverage-lede.tsx
@@ -14,9 +14,14 @@
import { useMemo } from "react";
import type { ReactNode } from "react";
-import type { CoverageFileRow, CoverageSummary } from "@repowise-dev/types/health";
+import type {
+ CoverageFileRow,
+ CoverageHistoryPoint,
+ CoverageSummary,
+} from "@repowise-dev/types/health";
import { PageLede } from "../shared/page-lede";
+import { Sparkline } from "./sparkline";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { formatDate, formatDateTime, formatNumber } from "../lib/format";
import { coverageBand } from "./tokens";
@@ -29,8 +34,12 @@ export interface CoverageLedeProps {
moduleCount: number;
/** Rendered under the prose. */
action?: ReactNode;
+ /** One point per ingested report, oldest first, for the trend under the figure. */
+ history?: CoverageHistoryPoint[] | undefined;
}
+const MIN_TREND_POINTS = 3;
+
/** Band order for the split bar: worst first, matching how the tables list. */
const BANDS = [
{ key: "thin", label: "Thin", max: 30, bar: "bg-[var(--color-error)]" },
@@ -44,62 +53,15 @@ export function CoverageLede({
files,
moduleCount,
action,
+ history,
}: CoverageLedeProps) {
const pct = summary.line_coverage_pct;
const band = pct == null ? null : coverageBand(pct);
const uncovered = Math.max(0, summary.total_lines - summary.covered_lines);
- // Weighted by coverable lines rather than by file count, for the same reason
- // the health distribution weights by NLOC: one large untested module must not
- // hide behind a hundred fully covered one-line shims.
- const split = useMemo(() => {
- const lines = BANDS.map(() => 0);
- let total = 0;
- for (const f of files) {
- // A file with no coverable lines has no percentage to band. Counting it
- // as 0% would invent a thin slice out of empty `__init__` files.
- if (f.total_coverable_lines <= 0 || f.line_coverage_pct == null) continue;
- const i = BANDS.findIndex((b) => f.line_coverage_pct! < b.max);
- const at = i === -1 ? BANDS.length - 1 : i;
- lines[at] = (lines[at] ?? 0) + f.total_coverable_lines;
- total += f.total_coverable_lines;
- }
- if (total === 0) return null;
- return BANDS.map((b, i) => ({
- ...b,
- pct: Math.round(((lines[i] ?? 0) / total) * 1000) / 10,
- })).filter((b) => b.pct > 0);
- }, [files]);
-
- const stats: RibbonStat[] = [
- {
- label: "Files instrumented",
- value: formatNumber(summary.file_count),
- ...(moduleCount > 0
- ? { sub: `across ${formatNumber(moduleCount)} directories` }
- : {}),
- },
- {
- label: "Uncovered lines",
- value: formatNumber(uncovered),
- sub: `of ${formatNumber(summary.total_lines)} coverable`,
- },
- {
- label: "Branch coverage",
- value:
- summary.branch_coverage_pct == null
- ? ""
- : `${summary.branch_coverage_pct.toFixed(1)}%`,
- hint: "Share of conditional branches a test takes both ways. Many runners emit no branch data at all, in which case this cell is absent rather than zero.",
- },
- {
- label: "Report format",
- value: (summary.source_format ?? "").toUpperCase(),
- ...(summary.ingested_at
- ? { sub: `ingested ${formatDate(summary.ingested_at)}` }
- : {}),
- },
- ];
+ const split = useMemo(() => bandSplit(files), [files]);
+ const trend = trendValues(summary, history);
+ const stats = ledeStats(summary, moduleCount, uncovered);
return (
<div className="flex flex-col gap-6">
@@ -110,7 +72,14 @@ export function CoverageLede({
unit="of coverable lines"
layout="beside"
{...(action ? { action } : {})}
- figureFooter={split ? <BandSplit split={split} /> : undefined}
+ figureFooter={
+ split || trend ? (
+ <div className="space-y-3">
+ {split ? <BandSplit split={split} /> : null}
+ {trend ? <CoverageTrend values={trend} /> : null}
+ </div>
+ ) : undefined
+ }
>
<p>
Tests reach{" "}
@@ -136,25 +105,7 @@ export function CoverageLede({
weekly is where defects arrive.
</p>
- {summary.source_format && (
- <p className="mt-2.5">
- Read from{" "}
- <span className="font-mono text-[var(--color-text-primary)]">
- {summary.source_format}
- </span>{" "}
- output
- {summary.ingested_at
- ? `, ingested ${formatDateTime(summary.ingested_at)}`
- : ""}
- {summary.ingested_commit_sha
- ? ` at ${summary.ingested_commit_sha.slice(0, 8)}`
- : ""}
- . Re-ingest after a test run to move these figures;{" "}
- {summary.branch_coverage_pct == null
- ? "this report carries no branch data, so branch coverage is absent rather than zero."
- : "branch coverage rides on the same report."}
- </p>
- )}
+ <SourceNote summary={summary} />
<StaleNotice summary={summary} />
</PageLede>
@@ -164,6 +115,89 @@ export function CoverageLede({
);
}
+/** Weighted by coverable lines rather than by file count, for the same reason
+ * the health distribution weights by NLOC: one large untested module must not
+ * hide behind a hundred fully covered one-line shims. */
+function bandSplit(files: CoverageFileRow[]) {
+ const lines = BANDS.map(() => 0);
+ let total = 0;
+ for (const f of files) {
+ // A file with no coverable lines has no percentage to band. Counting it
+ // as 0% would invent a thin slice out of empty `__init__` files.
+ if (f.total_coverable_lines <= 0 || f.line_coverage_pct == null) continue;
+ const i = BANDS.findIndex((b) => f.line_coverage_pct! < b.max);
+ const at = i === -1 ? BANDS.length - 1 : i;
+ lines[at] = (lines[at] ?? 0) + f.total_coverable_lines;
+ total += f.total_coverable_lines;
+ }
+ if (total === 0) return null;
+ return BANDS.map((b, i) => ({
+ ...b,
+ pct: Math.round(((lines[i] ?? 0) / total) * 1000) / 10,
+ })).filter((b) => b.pct > 0);
+}
+
+/** Two reports are a comparison, not a trend; the line starts at three. The
+ * history leaves partial reports out, so beside a partial headline it would
+ * end on a different figure than the one it sits under. */
+function trendValues(
+ summary: CoverageSummary,
+ history: CoverageLedeProps["history"],
+): number[] | null {
+ if (summary.mapping_partial || !history || history.length < MIN_TREND_POINTS) return null;
+ return history.map((p) => p.line_coverage_pct);
+}
+
+function ledeStats(
+ summary: CoverageSummary,
+ moduleCount: number,
+ uncovered: number,
+): RibbonStat[] {
+ return [
+ {
+ label: "Files instrumented",
+ value: formatNumber(summary.file_count),
+ ...(moduleCount > 0 ? { sub: `across ${formatNumber(moduleCount)} directories` } : {}),
+ },
+ {
+ label: "Uncovered lines",
+ value: formatNumber(uncovered),
+ sub: `of ${formatNumber(summary.total_lines)} coverable`,
+ },
+ {
+ label: "Branch coverage",
+ value:
+ summary.branch_coverage_pct == null ? "" : `${summary.branch_coverage_pct.toFixed(1)}%`,
+ hint: "Share of conditional branches a test takes both ways. Many runners emit no branch data at all, in which case this cell is absent rather than zero.",
+ },
+ {
+ label: "Report format",
+ value: (summary.source_format ?? "").toUpperCase(),
+ ...(summary.ingested_at ? { sub: `ingested ${formatDate(summary.ingested_at)}` } : {}),
+ },
+ ];
+}
+
+/** Where the figures came from, and how to move them. */
+function SourceNote({ summary }: { summary: CoverageSummary }) {
+ if (!summary.source_format) return null;
+ return (
+ <p className="mt-2.5">
+ Read from{" "}
+ <span className="font-mono text-[var(--color-text-primary)]">
+ {summary.source_format}
+ </span>{" "}
+ output
+ {summary.ingested_at ? `, ingested ${formatDateTime(summary.ingested_at)}` : ""}
+ {summary.ingested_commit_sha ? ` at ${summary.ingested_commit_sha.slice(0, 8)}` : ""}
+ . Re-ingest after a test run to move these figures;{" "}
+ {summary.branch_coverage_pct == null
+ ? "this report carries no branch data, so branch coverage is absent rather than zero."
+ : "branch coverage rides on the same report."}
+ </p>
+ );
+}
+
/** 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;
@@ -190,6 +224,33 @@ function StaleNotice({ summary }: { summary: CoverageSummary }) {
);
}
+/**
+ * Line coverage across the retained reports, on the full 0 to 100 scale so a
+ * small move reads as small. Neutral ink: a direction is not a verdict, and
+ * the sentence says which way it went.
+ */
+function CoverageTrend({ values }: { values: number[] }) {
+ // Rounded before subtracting, so the delta is the gap between the two
+ // figures the sentence prints.
+ const round = (v: number) => Math.round(v * 10) / 10;
+ const first = round(values[0]!);
+ const last = round(values[values.length - 1]!);
+ const delta = round(last - first);
+ const span = `across the last ${values.length} reports`;
+ const sentence =
+ delta !== 0
+ ? `${delta > 0 ? "Up" : "Down"} ${Math.abs(delta).toFixed(1)} points ${span}, from ${first.toFixed(1)}% to ${last.toFixed(1)}%.`
+ : values.every((v) => round(v) === last)
+ ? `Unchanged at ${last.toFixed(1)}% ${span}.`
+ : `Back at ${last.toFixed(1)}% ${span}.`;
+ return (
+ <div className="flex items-center gap-3 text-[var(--color-text-tertiary)]">
+ <Sparkline values={values} width={96} height={24} domain={[0, 100]} />
+ <p className="text-xs tabular-nums">{sentence}</p>
+ </div>
+ );
+}
+
/** 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 7013f279c..9a9fcde67 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -383,7 +383,12 @@ function CoverageBody({
return (
<div className="flex flex-col gap-6 sm:gap-8">
- <CoverageLede summary={summary} files={files} moduleCount={moduleCount} />
+ <CoverageLede
+ summary={summary}
+ files={files}
+ moduleCount={moduleCount}
+ history={data.history}
+ />
<OverviewSection
title="Health against coverage"
diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.py
index c6709b84c..a9a5f0d29 100644
--- a/tests/unit/persistence/test_coverage_loaders.py
+++ b/tests/unit/persistence/test_coverage_loaders.py
@@ -7,7 +7,10 @@ the report resolver builds, so stored and freshly parsed coverage score alike.
from __future__ import annotations
+from datetime import UTC, datetime
+
import pytest
+from sqlalchemy import select, text
from repowise.core.analysis.health.coverage import (
file_coverage,
@@ -15,11 +18,15 @@ from repowise.core.analysis.health.coverage import (
resolve_reports,
)
from repowise.core.persistence.crud import (
+ get_coverage_summary,
+ load_coverage_for_repo,
+ load_coverage_history,
load_coverage_map,
load_file_coverage,
save_coverage_files,
upsert_repository,
)
+from repowise.core.persistence.models import CoverageIngest
_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"
@@ -189,3 +196,178 @@ async def test_summary_counts_covered_lines_exactly(async_session, repo) -> None
summary = await get_coverage_summary(async_session, repo.id)
assert fc.line_coverage_pct == 50.0
assert summary["covered_lines"] == 10_001
+
+
+def _at(minute: int) -> datetime:
+ return datetime(2026, 9, 1, 12, minute, tzinfo=UTC)
+
+
+async def _ingest(session, repo_id: str, covered: int, minute: int, **kwargs) -> None:
+ """One report of ten coverable lines with *covered* of them hit."""
+ fc = file_coverage("a.py", range(1, covered + 1), range(1, 11))
+ await save_coverage_files(
+ session, repo_id, [fc], source_format="lcov", ingested_at=_at(minute), **kwargs
+ )
+
+
+async def test_every_ingest_is_kept_with_its_figures(async_session, repo) -> None:
+ for minute, covered in enumerate((5, 7, 6)):
+ await _ingest(async_session, repo.id, covered, minute, ingested_commit_sha=f"c{minute}")
+
+ history = await load_coverage_history(async_session, repo.id)
+
+ assert [(p["ingested_commit_sha"], p["line_coverage_pct"]) for p in history] == [
+ ("c0", 50.0),
+ ("c1", 70.0),
+ ("c2", 60.0),
+ ]
+ # SQLite drops the offset, as it does for every stored coverage timestamp.
+ assert history[0]["ingested_at"].startswith("2026-09-01T12:00:00")
+ # The per-file rows are still replaced: only the latest report is stored.
+ assert len(await load_coverage_for_repo(async_session, repo.id)) == 1
+
+
+async def test_ingests_past_the_retention_are_pruned(async_session, repo, monkeypatch) -> None:
+ from repowise.core.persistence.crud.analysis import coverage as coverage_crud
+
+ monkeypatch.setattr(coverage_crud, "COVERAGE_HISTORY_RETENTION", 3)
+ for minute in range(5):
+ await _ingest(async_session, repo.id, minute + 1, minute)
+
+ rows = (await async_session.execute(select(CoverageIngest))).scalars().all()
+ assert sorted(r.line_coverage_pct for r in rows) == [30.0, 40.0, 50.0]
+
+
+async def test_the_summary_reads_the_latest_ingest(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="lcov",
+ provenance=resolved.provenance,
+ ingested_at=_at(0),
+ )
+ # The newer ingest carries no provenance, so the summary must say unknown.
+ await _ingest(async_session, repo.id, 4, 1)
+
+ summary = await get_coverage_summary(async_session, repo.id)
+
+ assert summary["report_paths"] is None
+ assert summary["line_coverage_pct"] == 40.0
+
+
+async def test_the_stored_figures_match_the_summary(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="lcov", ingested_at=_at(0)
+ )
+
+ summary = await get_coverage_summary(async_session, repo.id)
+ ingest = (await async_session.execute(select(CoverageIngest))).scalar_one()
+
+ assert (ingest.line_coverage_pct, ingest.branch_coverage_pct) == (
+ summary["line_coverage_pct"],
+ summary["branch_coverage_pct"],
+ )
+ assert (ingest.covered_lines, ingest.total_lines) == (
+ summary["covered_lines"],
+ summary["total_lines"],
+ )
+
+
+async def test_partial_ingests_stay_out_of_the_history(async_session, repo) -> None:
+ from repowise.core.analysis.health.coverage.discovery import CoverageProvenance
+
+ await _ingest(async_session, repo.id, 5, 0)
+ await _ingest(async_session, repo.id, 9, 1, provenance=CoverageProvenance(mapping_partial=True))
+
+ history = await load_coverage_history(async_session, repo.id)
+
+ assert [p["line_coverage_pct"] for p in history] == [50.0]
+
+
+async def test_reingesting_the_same_report_restamps_rather_than_appends(
+ async_session, repo
+) -> None:
+ await _ingest(async_session, repo.id, 5, 0, ingested_commit_sha="one")
+ await _ingest(async_session, repo.id, 6, 1, ingested_commit_sha="two")
+ # An update that re-ingests, or a full re-index: the same figures again.
+ await _ingest(async_session, repo.id, 6, 2, ingested_commit_sha="three")
+
+ history = await load_coverage_history(async_session, repo.id)
+
+ assert [(p["ingested_commit_sha"], p["line_coverage_pct"]) for p in history] == [
+ ("one", 50.0),
+ ("three", 60.0),
+ ]
+ assert history[-1]["ingested_at"].startswith("2026-09-01T12:02:00")
+
+
+async def test_an_ingest_with_no_coverable_lines_stays_off_the_trend(
+ async_session, repo
+) -> None:
+ await _ingest(async_session, repo.id, 5, 0)
+ await save_coverage_files(
+ async_session,
+ repo.id,
+ [file_coverage("empty.py", [], [])],
+ source_format="lcov",
+ ingested_at=_at(1),
+ )
+
+ ingests = (
+ await async_session.execute(select(CoverageIngest).order_by(CoverageIngest.ingested_at))
+ ).scalars()
+ history = await load_coverage_history(async_session, repo.id)
+
+ assert [i.line_coverage_pct for i in ingests] == [50.0, None]
+ assert [p["line_coverage_pct"] for p in history] == [50.0]
+
+
+# The table as migration 0080 created it, with one row allowed per repository.
+_OLD_INGESTS_DDL = """
+CREATE TABLE coverage_ingests (
+ id VARCHAR(32) NOT NULL PRIMARY KEY,
+ repository_id VARCHAR(32) NOT NULL REFERENCES repositories (id) ON DELETE CASCADE,
+ source_formats_json TEXT NOT NULL DEFAULT '[]',
+ report_path_count INTEGER,
+ matched_path_count INTEGER,
+ unmatched_path_count INTEGER,
+ ambiguous_path_count INTEGER,
+ unmatched_sample_json TEXT NOT NULL DEFAULT '[]',
+ mapping_partial BOOLEAN NOT NULL DEFAULT 0,
+ ingested_at DATETIME NOT NULL,
+ ingested_commit_sha VARCHAR(40),
+ CONSTRAINT uq_coverage_ingests UNIQUE (repository_id)
+)
+"""
+
+
+async def test_a_store_that_still_has_the_one_row_constraint_keeps_working(
+ async_engine, tmp_path
+) -> None:
+ """Local stores never run Alembic, and the reconciler never drops a constraint."""
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+ from repowise.core.persistence.database import init_db
+
+ async with async_engine.begin() as conn:
+ await conn.execute(text("DROP TABLE coverage_ingests"))
+ await conn.execute(text(_OLD_INGESTS_DDL))
+ await init_db(async_engine) # the reconciler adds the new columns
+
+ factory = async_sessionmaker(async_engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as session:
+ repo = await upsert_repository(session, name="old", local_path=str(tmp_path))
+ await _ingest(session, repo.id, 5, 0, ingested_commit_sha="one")
+ await _ingest(session, repo.id, 8, 1, ingested_commit_sha="two")
+ await session.commit()
+
+ summary = await get_coverage_summary(session, repo.id, reference_commit="two")
+ history = await load_coverage_history(session, repo.id)
+
+ assert summary["freshness"]["status"] == "current"
+ assert [(p["ingested_commit_sha"], p["line_coverage_pct"]) for p in history] == [
+ ("two", 80.0)
+ ]
diff --git a/tests/unit/server/test_health_coverage_basis.py b/tests/unit/server/test_health_coverage_basis.py
index decb0b7b3..f5378f089 100644
--- a/tests/unit/server/test_health_coverage_basis.py
+++ b/tests/unit/server/test_health_coverage_basis.py
@@ -252,6 +252,8 @@ async def test_no_report_falls_back_to_the_graph(client, session, tmp_path):
body = await _get(client, repo["id"])
assert body["basis"] == "inferred"
+ # A report trend is a measured fact; the inferred shape never carries one.
+ assert "history" not in body
reached = {f["file_path"]: f["reached"] for f in body["inferred"]["files"]}
assert reached == {"src/a.py": True, "src/b.py": False}
assert body["inferred"]["files_reached"] == 1
diff --git a/tests/unit/server/test_health_coverage_route.py b/tests/unit/server/test_health_coverage_route.py
index 12e104c71..35767fc2c 100644
--- a/tests/unit/server/test_health_coverage_route.py
+++ b/tests/unit/server/test_health_coverage_route.py
@@ -217,3 +217,52 @@ async def test_summary_says_whether_coverage_was_measured_at_the_indexed_commit(
# Written without provenance: the counts are unknown, not zero.
assert summary["report_paths"] is None
assert summary["source_formats"] == ["lcov"]
+
+
+async def test_history_carries_one_point_per_report_oldest_first(
+ client, session, tmp_path
+) -> None:
+ from datetime import UTC, datetime
+
+ repo = await create_test_repo(client, tmp_path)
+ for minute, commit in enumerate(("aaa", "bbb")):
+ files = _FILES if commit == "aaa" else _FILES[1:]
+ await save_coverage_files(
+ session,
+ repo["id"],
+ files,
+ source_format="lcov",
+ ingested_commit_sha=commit,
+ ingested_at=datetime(2026, 9, 1, 12, minute, tzinfo=UTC),
+ )
+ await session.commit()
+
+ body = await _get(client, repo["id"], include_inferred="false")
+
+ # SQLite drops the offset, as it does for ``summary.ingested_at``.
+ assert body["history"] == [
+ {
+ "ingested_at": "2026-09-01T12:00:00",
+ "ingested_commit_sha": "aaa",
+ "line_coverage_pct": 63.33,
+ "branch_coverage_pct": 54.17,
+ },
+ {
+ "ingested_at": "2026-09-01T12:01:00",
+ "ingested_commit_sha": "bbb",
+ "line_coverage_pct": 74.0,
+ "branch_coverage_pct": 64.0,
+ },
+ ]
+ assert body["history"][-1]["line_coverage_pct"] == body["summary"]["line_coverage_pct"]
+
+
+ "params", [{"file_path": "src/a.py"}, {"limit": 1, "module_limit": 0}]
+)
+async def test_the_badge_reads_carry_no_history(client, seeded, params) -> None:
+ """The one-file and no-module reads never draw a trend, so they skip its read."""
+ body = await _get(client, seeded["id"], include_inferred="false", **params)
+
+ assert body["basis"] == "measured"
+ assert "history" not in body