Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(coverage): persist the per-test test-to-code map + one ingestion entry point (#790)
Raghav Chamadiya3a3f38384891
diff --git a/README.md b/README.mdindex deebf786d..36ff2ef63 100644--- a/README.md+++ b/README.md@@ -157,7 +157,7 @@ headline, so the bug-predictive number stays clean.```bashrepowise health # KPIs + lowest-scoring files-repowise health --coverage cov.lcov # ingest LCOV/Cobertura/Clover → untested-hotspot+repowise coverage add cov.lcov # ingest LCOV/Cobertura/Clover → untested-hotspotrepowise health --refactoring-targets # ranked by impact / effortrepowise health --trend # snapshots + declining / predicted-decline alerts```diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex f0e9f307b..f61951070 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -413,8 +413,6 @@ Compute per-file code-health scores from 25 deterministic markers (McCabe comple| `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) || `--badge` | Print a shields.io-compatible badge URL/JSON for the repo's health score |-| `--coverage <path>` | Ingest a coverage report (LCOV / Cobertura / Clover). Repeatable. |-| `--coverage-format` | Override coverage-format auto-detection: `lcov`, `cobertura`, `clover` || `--format` | Output: `table` (default), `json`, `md` || `--safe-only` | Documented no-op placeholder for a future confidence filter; has no effect today || `--repo` | In workspace mode, target a specific repo (defaults to primary) |@@ -427,13 +425,15 @@ repowise health --module packages/server # restrict to a directoryrepowise health --refactoring-targets # ranked by impact / effortrepowise health --generate-code packages/server/app.py::handler # LLM patch for one targetrepowise health --trend # snapshot history + alerts-repowise health --coverage coverage.lcov # ingest coverage+repowise coverage add coverage.lcov # ingest coverage, then:+repowise healthrepowise health --format json | jq .kpis # machine-readable````repowise init` and `repowise update` populate the health tables automatically -no separate command needed. `repowise status` shows a one-line summary(`Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: <path>)`).+Health automatically folds in whatever coverage was already ingested via `repowise coverage add`, no flag needed.---@@ -475,8 +475,8 @@ regardless of where their tests live.**Subcommands:**```bash-repowise coverage add [PATHS...] # ingest one or more reports-repowise coverage status # show currently ingested coverage+repowise coverage add [PATHS...] # ingest coverage reports (+ per-test map when contexts are present)+repowise coverage status # show ingested coverage + the map```**`add` options:**@@ -486,13 +486,28 @@ repowise coverage status # show currently ingested coverage| `--path` | Repo path (defaults to cwd / workspace primary) || `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json` |+`add` ingests per-file line/branch coverage from LCOV, Cobertura, Clover, or a+coverage.py `.coverage` file. It auto-discovers `coverage/lcov.info`,+`.coverage`, and similar reports at the repo root when no path is given, and+merges multiple reports (hit wins). When the report carries per-test contexts,+a coverage.py `.coverage` written with `coverage run --contexts=test`, or a+per-test lcov, `add` also builds the per-test *test-to-code map*, which test+covers which source lines. A report without contexts still ingests the+per-file coverage; it just skips the map.+```bash-repowise coverage add # discover coverage/lcov.info etc.+repowise coverage add # discover coverage/lcov.info, .coverage, etc.repowise coverage add coverage/lcov.inforepowise coverage add web.lcov api.lcov # merged, hit wins-repowise coverage status+coverage run --contexts=test -m pytest # produce .coverage with contexts+repowise coverage add .coverage # per-file coverage + per-test map+repowise coverage status # coverage summary + "Test-to-code map" counts```+> The per-test map is a separate dimension from the per-file aggregate that+> `add` always stores (a file is covered, merged over all tests) and from what+> `health` reads. It's used to answer "which tests exercise this change".+---### `repowise distill <command>`diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 895df142f..cabfcdeaa 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -588,16 +588,17 @@ score by more than half a point.## Test coverage-Pass coverage reports straight into the analyzer:+Ingest coverage reports, then run health:```bashpytest --cov --cov-report=lcov:coverage.lcov-repowise health --coverage coverage.lcov+repowise coverage add coverage.lcov+repowise health# Cobertura, Clover, or multiple sources also work:-repowise health \- --coverage backend/coverage.xml --coverage-format cobertura \- --coverage frontend/lcov.info+repowise coverage add backend/coverage.xml --format cobertura+repowise coverage add frontend/lcov.info+repowise health```Formats are auto-detected: **LCOV**, **Cobertura** XML, **Clover** XML, and adiff --git a/docs/INTELLIGENCE_LAYERS.md b/docs/INTELLIGENCE_LAYERS.mdindex c2017faf5..8988d972e 100644--- a/docs/INTELLIGENCE_LAYERS.md+++ b/docs/INTELLIGENCE_LAYERS.md@@ -188,7 +188,7 @@ the layer closes the loop into concrete, graph-aware refactoring plans```bashrepowise health # KPIs + lowest-scoring files-repowise health --coverage cov.lcov # ingest coverage, light up untested-hotspot+repowise coverage add cov.lcov # ingest coverage, light up untested-hotspotrepowise health --refactoring-targets # ranked by impact / effortrepowise health --trend # last 10 snapshots + declining/predicted-decline alertsrepowise status # one-line summary in the status reportdiff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex 409e42502..9ae572f7f 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -146,7 +146,7 @@ core/pipeline/```cli/src/repowise/cli/commands/-├── health_cmd.py # repowise health [--trend|--coverage|--refactoring-targets|--module]+├── health_cmd.py # repowise health [--trend|--refactoring-targets|--module]├── status_cmd.py # `Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: ...)`└── update_cmd.py # incremental path: HealthAnalyzer.analyze(changed_files=...)```@@ -621,7 +621,7 @@ KPI + per-file score history. Rolling delete on insert keeps the latest### `coverage_files`-Per-file coverage, overwritten on every `--coverage` run. Carries the+Per-file coverage, overwritten on every `coverage add` run. Carries theexplicit `covered_lines_json` array so the `coverage_gap` marker canflag the exact uncovered surface, not just the percent.@@ -638,8 +638,8 @@ repowise health --file path/to/x.py # deep-dive one filerepowise health --module packages/server # restrict to a directory prefixrepowise health --refactoring-targets # ranked by impact / effortrepowise health --trend # last 10 snapshots + active alerts-repowise health --coverage coverage.lcov # ingest coverage; can repeat-repowise health --coverage-format cobertura+repowise coverage add coverage.lcov # ingest coverage; can repeat+repowise coverage add coverage.xml --format coberturarepowise health --format json | jq ...repowise health --safe-only # confidence ≥ 0.8 only (placeholder)```diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex 50a4ceb22..50aa98787 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -1,10 +1,11 @@"""``repowise coverage`` — ingest and inspect test-coverage reports.-Coverage is auto-discovered and ingested during ``repowise init`` /-``repowise update``. This command is the manual path: point it at an-lcov / Cobertura / Clover report (or let it discover one) to populate-per-file line/branch coverage, which clears ``untested_hotspot`` for files-that are tested regardless of where their tests live.+The single entry point for coverage. ``coverage add`` populates per-file+line/branch coverage (which clears ``untested_hotspot`` for tested files) and,+when a report carries contexts (a coverage.py ``.coverage`` or a per-test+lcov), also builds the per-test "test-to-code" map. ``repowise health`` then+folds in whatever was ingested here - it no longer takes a coverage flag of+its own."""from __future__ import annotations@@ -65,12 +66,19 @@ def coverage_group() -> None:help="Force a parser instead of auto-detecting from content.",)def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: str | None) -> None:- """Ingest one or more coverage reports (auto-discovers when none given).+ """Ingest coverage (auto-discovers reports when none are given).++ Stores per-file line/branch coverage, and additionally the per-test+ "test-to-code" map when a report carries contexts - a coverage.py+ ``.coverage`` written with ``coverage run --contexts=test``, or a per-test+ lcov. The map is what answers "which tests exercise this change"; reports+ without contexts ingest per-file coverage only.Examples:- repowise coverage add # discover coverage/lcov.info etc.+ repowise coverage add # discover lcov.info, .coverage, ...repowise coverage add coverage/lcov.info+ repowise coverage add .coverage # per-test map from coverage.pyrepowise coverage add web.lcov api.lcov # merged hit-wins"""repo_path = _resolve_coverage_repo(repo)@@ -80,6 +88,8 @@ def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: strCoverageConfig,build_coverage_map,discover_artifacts,+ parse_contexts_file,+ resolve_test_reports,)from repowise.core.repo_config import load_repo_config@@ -89,13 +99,15 @@ def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: strreport_paths = [Path(p) for p in paths]else:report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)+ report_paths += _discover_context_reports(repo_path)if not report_paths:console.print("[yellow]No coverage report found.[/yellow] Looked for "- "coverage/lcov.info, **/cobertura.xml, and similar.\n"- "Generate one (e.g. [cyan]cargo llvm-cov --lcov --output-path "- "coverage/lcov.info[/cyan]) then re-run, or pass a path:\n"- " [cyan]repowise coverage add path/to/lcov.info[/cyan]"+ "coverage/lcov.info, .coverage, **/cobertura.xml, and similar.\n"+ "Generate one (e.g. [cyan]coverage run --contexts=test -m pytest[/cyan] "+ "or [cyan]cargo llvm-cov --lcov --output-path coverage/lcov.info[/cyan]) "+ "then re-run, or pass a path:\n"+ " [cyan]repowise coverage add path/to/report[/cyan]")returnconsole.print(@@ -103,6 +115,11 @@ def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: str+ ", ".join(p.name for p in report_paths[:5]))+ # The aggregate parsers read text (lcov/xml/json); the coverage.py+ # ``.coverage`` sqlite only feeds the per-test map, so keep it out of the+ # text-parsing path (its binary bytes would not decode as UTF-8).+ agg_paths = [p for p in report_paths if not _is_sqlite(p)]+async def _do() -> None:from repowise.core.persistence import (create_engine,@@ -112,6 +129,7 @@ def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: strfrom repowise.core.persistence.crud import (get_repository_by_path,save_coverage_files,+ save_test_coverage,)engine = create_engine(get_db_url_for_repo(repo_path))@@ -131,152 +149,122 @@ def coverage_add(paths: tuple[str, ...], repo: str | None, coverage_format: str)return- resolved, errors = build_coverage_map(- repo_path,- report_paths,- repo_keys,- coverage_format=coverage_format or cfg.format,- strip_prefix=cfg.strip_prefix,- path_prefix=cfg.path_prefix,- )- for path, err in errors:- console.print(f"[yellow] {path.name}: {err}[/yellow]")+ head_sha = getattr(repo_row, "head_commit", None)++ # --- Per-file aggregate coverage (lcov / cobertura / clover / json).+ agg_matched = 0+ if agg_paths:+ resolved, errors = build_coverage_map(+ repo_path,+ agg_paths,+ repo_keys,+ coverage_format=coverage_format or cfg.format,+ strip_prefix=cfg.strip_prefix,+ path_prefix=cfg.path_prefix,+ )+ for path, err in errors:+ console.print(f"[yellow] {path.name}: {err}[/yellow]")+ if resolved.files:+ await save_coverage_files(+ session,+ repo_row.id,+ resolved.files,+ source_format=resolved.source_format or "lcov",+ ingested_commit_sha=head_sha,+ )+ agg_matched = resolved.matched+ console.print(+ f"[green]Ingested coverage for {resolved.matched} file(s)[/green] "+ f"({resolved.matched_exact} exact, {resolved.matched_suffix} resolved)."+ )+ skipped = resolved.unmatched + resolved.ambiguous+ if skipped:+ sample = ", ".join(skipped[:5])+ console.print(+ f"[yellow]{len(skipped)} report file(s) did not map to the "+ f"repo tree[/yellow] (e.g. {sample})."+ )++ # --- Per-test map, from any report that carries contexts.+ map_records: list = []+ map_format: str | None = None+ for report_path in report_paths:+ creport = parse_contexts_file(report_path)+ if not creport.has_contexts:+ # A plain lcov without TN is normal (handled as aggregate+ # above); a .coverage without contexts is worth calling out+ # so the user knows why no map was built.+ if _is_sqlite(report_path):+ console.print(+ f"[yellow]{report_path.name}: no per-test contexts "+ f"(ran without --contexts=test); per-test map "+ f"skipped.[/yellow]"+ )+ continue+ rtc = resolve_test_reports(+ creport,+ repo_keys,+ strip_prefix=cfg.strip_prefix,+ path_prefix=cfg.path_prefix,+ )+ map_records.extend(rtc.records)+ map_format = map_format or creport.source_format+ if map_records:+ written = await save_test_coverage(+ session,+ repo_row.id,+ map_records,+ source_format=map_format or "coverage.py",+ ingested_commit_sha=head_sha,+ )+ dropped = len(map_records) - written+ extra = (+ f" [yellow]({dropped} dropped: duplicate or over cap)[/yellow]"+ if dropped+ else ""+ )+ console.print(+ f"[green]Built the test-to-code map: {written} test->file "+ f"record(s).[/green]{extra}"+ )- if not resolved.files:+ if not agg_matched and not map_records:console.print("[red]No report files mapped to indexed source files.[/red] ""If paths look prefixed (e.g. build/…), set ""[cyan]coverage.strip_prefix[/cyan] in .repowise/config.yaml.")return-- await save_coverage_files(- session,- repo_row.id,- resolved.files,- source_format=resolved.source_format or "lcov",- ingested_commit_sha=getattr(repo_row, "head_commit", None),- )-console.print(- f"[green]Ingested coverage for {resolved.matched} file(s)[/green] "- f"({resolved.matched_exact} exact, {resolved.matched_suffix} resolved)."- )- skipped = resolved.unmatched + resolved.ambiguous- if skipped:- sample = ", ".join(skipped[:5])- console.print(- f"[yellow]{len(skipped)} report file(s) did not map to the "- f"repo tree[/yellow] (e.g. {sample})."- )- console.print(- "Run [cyan]repowise health[/cyan] to fold coverage into the "- "defect scores and clear untested-hotspot findings."+ "Run [cyan]repowise health[/cyan] to fold coverage into the defect "+ "scores, or [cyan]repowise coverage status[/cyan] to review it.")run_async(_do())-@coverage_group.command("contexts")[email protected]("paths", nargs=-1, type=click.Path(exists=True, dir_okay=False))- "--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary)."-)[email protected]("--limit", type=int, default=20, help="Max per-test records to print.")-def coverage_contexts(paths: tuple[str, ...], repo: str | None, limit: int) -> None:- """Preview the per-test coverage map from a context-carrying report.-- Opt-in and read-only: reads a coverage.py ``.coverage`` sqlite (written- with ``coverage run --contexts=test``) or a per-test lcov, then prints- "test T covers N lines of file F". Nothing is persisted - this is the- Phase 0 substrate surface, not the ingest path.-- A report produced without contexts degrades loudly rather than showing- an empty map:+_SQLITE_MAGIC = b"SQLite format 3\x00"- repowise coverage contexts .coverage- repowise coverage contexts coverage/per-test.lcov- """- repo_path = _resolve_coverage_repo(repo)-- from repowise.core.analysis.health.coverage import (- parse_contexts_file,- resolve_test_reports,- )- if paths:- report_paths = [Path(p) for p in paths]- else:- default = repo_path / ".coverage"- if not default.exists():- console.print(- "[yellow]No report given and no .coverage found.[/yellow] "- "Generate one with [cyan]coverage run --contexts=test[/cyan] "- "then pass its path:\n"- " [cyan]repowise coverage contexts .coverage[/cyan]"- )- return- report_paths = [default]+def _is_sqlite(path: Path) -> bool:+ """True when *path* is a coverage.py ``.coverage`` sqlite (binary magic)."""+ try:+ with path.open("rb") as fh:+ return fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC+ except OSError:+ return False- for report_path in report_paths:- report = parse_contexts_file(report_path)- if not report.has_contexts:- console.print(- f"[yellow]{report_path.name}: no contexts - aggregate only, "- f"per-test features unavailable.[/yellow] Regenerate with "- f"[cyan]coverage run --contexts=test[/cyan] (or per-test lcov)."- )- continue- async def _resolve(rep=report) -> None:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- )- from repowise.core.persistence.crud import get_repository_by_path-- engine = create_engine(get_db_url_for_repo(repo_path))- sf = create_session_factory(engine)- async with get_session(sf) as session:- repo_row = await get_repository_by_path(session, str(repo_path))- repo_keys = await _repo_file_keys(session, repo_row.id) if repo_row else set()- _print_context_records(rep, repo_keys, resolve_test_reports, limit)-- run_async(_resolve())---def _print_context_records(report, repo_keys, resolve_test_reports, limit: int) -> None:- """Resolve (when an index exists) and print per-test coverage records."""- if repo_keys:- resolved = resolve_test_reports(report, repo_keys)- records = resolved.records- header = (- f"[bold]{len(records)} record(s)[/bold] "- f"({resolved.matched_exact} exact, {resolved.matched_suffix} resolved, "- f"{resolved.test_files_resolved} test-file(s) mapped)"- )- skipped = resolved.unmatched + resolved.ambiguous- else:- records = report.records- header = f"[bold]{len(records)} record(s)[/bold] (raw paths, no index to resolve against)"- skipped = []+def _discover_context_reports(repo_path: Path) -> list[Path]:+ """Find per-test coverage artifacts under the repo root.- console.print(f"{header} from [cyan]{report.source_format}[/cyan] contexts:")- for rec in records[:limit]:- via = f" [dim](test file: {rec.test_file})[/dim]" if rec.test_file else ""- console.print(- f" [green]{rec.test_id}[/green] covers "- f"{len(rec.covered_lines)} line(s) of [cyan]{rec.file_path}[/cyan]{via}"- )- if len(records) > limit:- console.print(f" [dim]... {len(records) - limit} more[/dim]")- if skipped:- sample = ", ".join(skipped[:5])- console.print(- f"[yellow]{len(skipped)} source path(s) did not map to the repo "- f"tree[/yellow] (e.g. {sample})."- )+ Just the coverage.py ``.coverage`` sqlite - it is the only per-test+ artifact identifiable by name (a per-test lcov is indistinguishable from+ an aggregate one without parsing, so those are passed explicitly and get+ context-parsed alongside the aggregate ingest).+ """+ default = repo_path / ".coverage"+ return [default] if default.is_file() else []@coverage_group.command("status")@@ -296,6 +284,7 @@ def coverage_status(repo: str | None) -> None:from repowise.core.persistence.crud import (get_coverage_summary,get_repository_by_path,+ get_test_coverage_summary,)engine = create_engine(get_db_url_for_repo(repo_path))@@ -306,22 +295,39 @@ def coverage_status(repo: str | None) -> None:console.print("[yellow]No index yet — run `repowise init`.[/yellow]")returnsummary = await get_coverage_summary(session, repo_row.id)- if not summary.get("file_count"):+ map_summary = await get_test_coverage_summary(session, repo_row.id)++ if not summary.get("file_count") and not map_summary.get("pair_count"):console.print("[yellow]No coverage ingested.[/yellow] Run "- "[cyan]repowise coverage add[/cyan] or regenerate the index "- "with a coverage report present."+ "[cyan]repowise coverage add[/cyan] for per-file coverage, or "+ "[cyan]repowise coverage contexts[/cyan] for the per-test map.")return- line_pct = summary.get("line_coverage_pct")- branch_pct = summary.get("branch_coverage_pct")- lines_str = f"{line_pct:.1f}%" if line_pct is not None else "n/a"- console.print(- f"[bold]Coverage[/bold] ({summary.get('source_format') or 'lcov'})\n"- f" Files: {summary['file_count']}\n"- f" Lines: {lines_str}"- )- if branch_pct is not None:- console.print(f" Branch: {branch_pct:.1f}%")++ if summary.get("file_count"):+ line_pct = summary.get("line_coverage_pct")+ branch_pct = summary.get("branch_coverage_pct")+ lines_str = f"{line_pct:.1f}%" if line_pct is not None else "n/a"+ console.print(+ f"[bold]Coverage[/bold] ({summary.get('source_format') or 'lcov'})\n"+ f" Files: {summary['file_count']}\n"+ f" Lines: {lines_str}"+ )+ if branch_pct is not None:+ console.print(f" Branch: {branch_pct:.1f}%")++ if map_summary.get("pair_count"):+ console.print(+ f"[bold]Test-to-code map[/bold] ({map_summary.get('source_format') or 'n/a'})\n"+ f" Tests: {map_summary['test_count']}\n"+ f" Files: {map_summary['source_file_count']}\n"+ f" Records: {map_summary['pair_count']}"+ )+ else:+ console.print(+ "[dim]No test-to-code map yet - build one with "+ "[cyan]repowise coverage contexts[/cyan].[/dim]"+ )run_async(_do())diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 8a3f4a955..aa49d8a09 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -23,7 +23,7 @@ from repowise.cli.helpers import ()from .codegen import _generate_refactoring_code-from .persist import _persist_health+from .persist import _load_persisted_coverage_map, _persist_healthfrom .refactoring_targets import _render_refactoring_targetsfrom .summary import (_render_badge,@@ -67,20 +67,6 @@ from .trends import _render_trenddefault=False,help="Force single-repo mode.",)- "--coverage",- "coverage_paths",- multiple=True,- type=click.Path(exists=True),- help="Ingest a coverage report (LCOV/Cobertura/Clover). May be repeated.",-)- "--coverage-format",- "coverage_format",- default=None,- type=click.Choice(["lcov", "cobertura", "clover"]),- help="Override coverage-format auto-detection.",-)@click.option("--refactoring-targets","refactoring_targets",@@ -126,8 +112,6 @@ def health_command(safe_only: bool,repo_alias: str | None,no_workspace: bool,- coverage_paths: tuple[str, ...],- coverage_format: str | None,refactoring_targets: bool,generate_code: str | None,module_filter: str | None,@@ -142,7 +126,6 @@ def health_command(from pathlib import Path as PathlibPathfrom repowise.core.analysis.health import HealthAnalyzer- from repowise.core.analysis.health.coverage import parse as parse_coveragefrom repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder# Silence structlog/stdlib info+debug lines when the user asked for a@@ -223,40 +206,10 @@ def health_command(except Exception:pass- coverage_map: dict[str, dict] = {}- coverage_persist_files: list = []- coverage_persist_format: str | None = None- if coverage_paths:- for cov_path in coverage_paths:- try:- text = PathlibPath(cov_path).read_text(encoding="utf-8")- except OSError as exc:- status.print(f"[red]Could not read coverage file {cov_path}: {exc}[/red]")- continue- report_cov = parse_coverage(text, format=coverage_format)- if not report_cov.files:- status.print(- f"[yellow]No coverage entries parsed from {cov_path} "- f"(detected={report_cov.source_format}).[/yellow]"- )- continue- for fc in report_cov.files:- coverage_map[fc.file_path] = {- "line_coverage_pct": fc.line_coverage_pct,- "branch_coverage_pct": fc.branch_coverage_pct,- "covered_lines": list(fc.covered_lines),- "total_coverable_lines": fc.total_coverable_lines,- "source_format": report_cov.source_format,- }- # Accumulate for DB persistence. Last format wins when multiple- # reports are passed — they should all be the same format in- # practice, but the CLI doesn't enforce it.- coverage_persist_files.extend(report_cov.files)- coverage_persist_format = report_cov.source_format- status.print(- f"[green]Ingested {len(report_cov.files)} files "- f"from {cov_path} ({report_cov.source_format}).[/green]"- )+ # Coverage folds into scoring from whatever `repowise coverage add` (or+ # index-time ingest) persisted - no per-run flag. Ingestion lives solely+ # in the `coverage` command group.+ coverage_map = _load_persisted_coverage_map(repo_path)analyzer = HealthAnalyzer(graph_builder.graph(),@@ -276,23 +229,15 @@ def health_command()report = analyzer.analyze(analyzer_cfg)- # Persist health + coverage to the repo's wiki.db so the dashboard,- # MCP tools, and `repowise status` see the same numbers as this CLI- # run. Without this step, `--coverage` was effectively a stdout-only- # toy — biomarkers got recomputed in memory but nothing reached the- # tables that drive the Coverage page / get_health.+ # Persist health to the repo's wiki.db so the dashboard, MCP tools, and+ # `repowise status` see the same numbers as this CLI run.## Skip when fmt != "table" (json/md are read by scripts and CI; side# effects are unwelcome) or when the run is filtered to a single# file/module (those are inspection runs that shouldn't overwrite# repo-level state).if fmt == "table" and not file_filter and not module_filter:- _persist_health(- repo_path,- report=report,- coverage_files=coverage_persist_files,- coverage_format=coverage_persist_format,- )+ _persist_health(repo_path, report=report)metrics = report.metricsif file_filter:diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex 0a01e4694..6cdb77a0b 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -1,23 +1,72 @@-"""Persist the analyzer's health + coverage output to the repo's wiki.db."""+"""Persist the analyzer's health output to the repo's wiki.db.++Coverage is *read* here (to fold into scoring) but never written: the+``coverage`` command group owns ingestion of both per-file coverage and the+per-test map. A ``repowise health`` run must not overwrite that data.+"""from __future__ import annotations+import json+from repowise.cli.helpers import console, run_async-def _persist_health(- repo_path: object,- *,- report: object,- coverage_files: list,- coverage_format: str | None,-) -> None:- """Write the analyzer's output to the repo's wiki.db.+def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:+ """Build the analyzer ``coverage_map`` from persisted per-file coverage.++ Reads whatever ``repowise coverage add`` (or index-time ingest) stored in+ ``coverage_files`` so ``repowise health`` reflects it without a flag.+ Best-effort: no repo row / no rows / any DB error yields an empty map.+ """+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_repository_by_path,+ load_coverage_for_repo,+ )++ async def _do() -> dict[str, dict]:+ engine = create_engine(get_db_url_for_repo(repo_path))+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return {}+ rows = await load_coverage_for_repo(session, repo.id)+ out: dict[str, dict] = {}+ for r in rows:+ try:+ covered = list(json.loads(r.covered_lines_json))+ except (ValueError, TypeError):+ covered = []+ out[r.file_path] = {+ "line_coverage_pct": r.line_coverage_pct,+ "branch_coverage_pct": r.branch_coverage_pct,+ "covered_lines": covered,+ "total_coverable_lines": r.total_coverable_lines,+ "source_format": r.source_format,+ }+ return out++ try:+ return run_async(_do())+ except Exception:+ return {}+++def _persist_health(repo_path: object, *, report: object) -> None:+ """Write the analyzer's health output to the repo's wiki.db.Mirrors what ``pipeline/persist.py`` does for ``repowise init``:- overwrite the four health tables for this repo with the freshly- computed values. Best-effort — a missing repo row or a DB error- logs to stderr and returns rather than crashing the CLI.+ overwrite the health tables for this repo with the freshly computed+ values. Coverage tables are left untouched (owned by ``coverage add``).+ Best-effort — a missing repo row or a DB error logs to stderr and+ returns rather than crashing the CLI."""from repowise.cli.helpers import get_db_url_for_repofrom repowise.core.persistence import (@@ -27,7 +76,6 @@ def _persist_health()from repowise.core.persistence.crud import (get_repository_by_path,- save_coverage_files,save_health_findings,save_health_metrics,save_health_snapshot,@@ -46,16 +94,6 @@ def _persist_health()returnrepo_id = repo.id- head_sha = getattr(repo, "head_commit", None)-- if coverage_files:- await save_coverage_files(- session,- repo_id,- coverage_files,- source_format=coverage_format or "lcov",- ingested_commit_sha=head_sha,- )await save_health_metrics(session, repo_id, list(getattr(report, "metrics", []) or []))findings = list(getattr(report, "findings", []) or [])diff --git a/packages/core/alembic/versions/0036_test_coverage.py b/packages/core/alembic/versions/0036_test_coverage.pynew file mode 100644index 000000000..b7900784d--- /dev/null+++ b/packages/core/alembic/versions/0036_test_coverage.py@@ -0,0 +1,71 @@+"""test_coverage table - the per-test test-to-code map.++Persists one ``(test, source file)`` coverage fact per row so the reverse+index "given changed lines, which tests hit them" is a straight query.+Where ``coverage_files`` stores per-file aggregate coverage (merged across+every test), this keeps the test dimension. Point-in-time only: overwritten+per ingest run, no history - mirroring ``coverage_files``.++A table rather than a graph edge: the first consumer is a CI lookup keyed by+changed source file + lines. Populated only from context-carrying reports+(coverage.py contexts / lcov TN records), which are opt-in.++Revision ID: 0036+Revises: 0035+Create Date: 2026-07-12+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0036"+down_revision: str | None = "0035"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "test_coverage",+ 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("test_id", sa.Text, nullable=False),+ sa.Column("test_file", sa.Text, nullable=True),+ sa.Column("source_file", sa.Text, nullable=False),+ sa.Column("covered_lines_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("source_format", sa.String(32), nullable=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", "test_id", "source_file", name="uq_test_coverage"),+ )+ op.create_index(+ "ix_test_coverage_repo_source",+ "test_coverage",+ ["repository_id", "source_file"],+ )+ op.create_index(+ "ix_test_coverage_repo_test",+ "test_coverage",+ ["repository_id", "test_id"],+ )+++def downgrade() -> None:+ op.drop_index("ix_test_coverage_repo_test", table_name="test_coverage")+ op.drop_index("ix_test_coverage_repo_source", table_name="test_coverage")+ op.drop_table("test_coverage")diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.mdindex dbbc66d54..ce25695cd 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md@@ -26,7 +26,7 @@ from repowise.core.analysis.health.coverage import (A small, explicit JSON shape so coverage from *any* runner can benormalized once (keyed by repo-relative POSIX path) and fed to-`repowise health --coverage`:+`repowise coverage add`:```json{diff --git a/packages/core/src/repowise/core/analysis/health/coverage/detector.py b/packages/core/src/repowise/core/analysis/health/coverage/detector.pyindex bbae4e0f9..26e0cc105 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/detector.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/detector.py@@ -1,7 +1,7 @@"""Format auto-detection + test-file heuristic.-The CLI accepts ``--coverage <path>`` without a format flag in the common-case. We sniff the content to decide which parser to dispatch to.+``repowise coverage add <path>`` accepts a report without a format flag in+the common case. We sniff the content to decide which parser to dispatch to.Sniffing rules (cheap, deterministic):@@ -12,7 +12,7 @@ Sniffing rules (cheap, deterministic):- Clover XML has a ``<coverage generated=`` root with a ``<project>``child.-If detection is ambiguous, callers can pass ``--coverage-format`` to+If detection is ambiguous, callers can pass ``coverage add --format`` tooverride."""diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.pyindex 92202daea..91bbd2bb0 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py@@ -56,6 +56,9 @@ class TestCoverage:(``None`` when the test id is not path-shaped or does not resolve)."""+ # Tell pytest this ``Test``-prefixed class is not a test to collect.+ __test__ = False+test_id: strfile_path: strcovered_lines: list[int] = field(default_factory=list)diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex e605ffd09..32ed8e674 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -8,12 +8,18 @@ imports are unaffected.from __future__ import annotations-from . import coverage, dead_code, health, refactoring # noqa: F401+from . import coverage, coverage_map, dead_code, health, refactoring # noqa: F401from .coverage import (get_coverage_summary,load_coverage_for_repo,save_coverage_files,)+from .coverage_map import (+ files_covered_by,+ get_test_coverage_summary,+ save_test_coverage,+ tests_covering,+)from .dead_code import (get_dead_code_findings,get_dead_code_summary,@@ -46,6 +52,7 @@ from .refactoring import (__all__ = ["HEALTH_SNAPSHOT_RETENTION",+ "files_covered_by","get_coverage_summary","get_dead_code_findings","get_dead_code_summary",@@ -56,6 +63,7 @@ __all__ = ["get_perf_coverage","get_refactoring_suggestion","get_refactoring_suggestions",+ "get_test_coverage_summary","list_health_snapshots","load_coverage_for_repo","replace_governance_findings",@@ -65,6 +73,8 @@ __all__ = ["save_health_metrics","save_health_snapshot","save_refactoring_suggestions",+ "save_test_coverage",+ "tests_covering","update_dead_code_status","update_health_finding_status","upsert_dead_code_findings",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.pynew file mode 100644index 000000000..79f2450b3--- /dev/null+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py@@ -0,0 +1,186 @@+"""CRUD for the per-test coverage map (``test_coverage`` table).++Module named ``coverage_map`` (not ``test_coverage``) so pytest does not+collect it as a test module.+++The reverse index - "given a changed source file and lines, which tests hit+them" - is :func:`tests_covering`; the forward direction ("what does this+test cover") is :func:`files_covered_by`. Both are straight indexed queries+scoped to a repository. Rows are point-in-time (overwritten per ingest run),+mirroring ``coverage_files``.+"""++from __future__ import annotations++import json+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from ...models import TestCoverageEntry, _new_uuid+from .._shared import _BATCH_SIZE++# Upper bound on rows persisted per repo, so a pathological O(tests x files)+# report can't balloon the table unbounded. Excess is dropped loudly (the+# caller compares ``written`` against the record count). Generous headroom:+# a 2000-test suite touching 100 files each is 200k pairs.+MAX_TEST_COVERAGE_ROWS = 250_000+++async def save_test_coverage(+ session: AsyncSession,+ repository_id: str,+ records: list[Any],+ *,+ source_format: str,+ ingested_commit_sha: str | None = None,+ max_rows: int = MAX_TEST_COVERAGE_ROWS,+) -> int:+ """Replace the test-coverage rows for *repository_id* with *records*.++ *records* are resolved ``TestCoverage`` dataclasses (canonical+ ``file_path`` / ``test_file``). Delete-then-insert, capped at *max_rows*;+ returns the number of rows written so the caller can report truncation.+ """+ existing = await session.execute(+ select(TestCoverageEntry).where(TestCoverageEntry.repository_id == repository_id)+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ # Deduplicate on (test_id, source_file) - the unique key - keeping the+ # first occurrence, so a report that repeats a pair never trips the+ # constraint mid-batch.+ seen: set[tuple[str, str]] = set()+ capped = records[:max_rows]+ written = 0+ batch: list[TestCoverageEntry] = []+ for rec in capped:+ key = (rec.test_id, rec.file_path)+ if key in seen:+ continue+ seen.add(key)+ batch.append(+ TestCoverageEntry(+ id=_new_uuid(),+ repository_id=repository_id,+ test_id=rec.test_id,+ test_file=rec.test_file,+ source_file=rec.file_path,+ covered_lines_json=json.dumps(list(rec.covered_lines or [])),+ source_format=source_format,+ ingested_commit_sha=ingested_commit_sha,+ )+ )+ if len(batch) >= _BATCH_SIZE:+ session.add_all(batch)+ await session.flush()+ written += len(batch)+ batch = []+ if batch:+ session.add_all(batch)+ await session.flush()+ written += len(batch)+ return written+++def _decode_lines(row: TestCoverageEntry) -> list[int]:+ try:+ return list(json.loads(row.covered_lines_json))+ except (ValueError, TypeError):+ return []+++async def tests_covering(+ session: AsyncSession,+ repository_id: str,+ source_file: str,+ *,+ lines: set[int] | None = None,+) -> list[dict[str, Any]]:+ """Reverse index: tests whose coverage touches *source_file*.++ When *lines* is given, only tests whose covered set intersects it are+ returned (the "changed lines -> impacted tests" query). Each result is+ ``{test_id, test_file, covered_lines, source_format}``, with+ ``covered_lines`` narrowed to the intersecting lines when *lines* is set.+ """+ result = await session.execute(+ select(TestCoverageEntry).where(+ TestCoverageEntry.repository_id == repository_id,+ TestCoverageEntry.source_file == source_file,+ )+ )+ out: list[dict[str, Any]] = []+ for row in result.scalars().all():+ covered = _decode_lines(row)+ if lines is not None:+ hit = sorted(lines.intersection(covered))+ if not hit:+ continue+ covered_out = hit+ else:+ covered_out = covered+ out.append(+ {+ "test_id": row.test_id,+ "test_file": row.test_file,+ "covered_lines": covered_out,+ "source_format": row.source_format,+ }+ )+ return out+++async def files_covered_by(+ session: AsyncSession,+ repository_id: str,+ test_id: str,+) -> list[dict[str, Any]]:+ """Forward direction: source files (and lines) a given test covers."""+ result = await session.execute(+ select(TestCoverageEntry).where(+ TestCoverageEntry.repository_id == repository_id,+ TestCoverageEntry.test_id == test_id,+ )+ )+ return [+ {+ "source_file": row.source_file,+ "covered_lines": _decode_lines(row),+ "source_format": row.source_format,+ }+ for row in result.scalars().all()+ ]+++async def get_test_coverage_summary(+ session: AsyncSession,+ repository_id: str,+) -> dict[str, Any]:+ """Repo-level shape of the map (counts + provenance). Empty when no rows."""+ result = await session.execute(+ select(TestCoverageEntry).where(TestCoverageEntry.repository_id == repository_id)+ )+ rows = list(result.scalars().all())+ if not rows:+ return {+ "pair_count": 0,+ "test_count": 0,+ "source_file_count": 0,+ "source_format": None,+ "ingested_at": None,+ "ingested_commit_sha": None,+ }+ latest = max(rows, key=lambda r: r.ingested_at)+ return {+ "pair_count": len(rows),+ "test_count": len({r.test_id for r in rows}),+ "source_file_count": len({r.source_file for r in rows}),+ "source_format": latest.source_format,+ "ingested_at": latest.ingested_at,+ "ingested_commit_sha": latest.ingested_commit_sha,+ }diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex f6720ab5d..05d550cc1 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1048,6 +1048,59 @@ class CoverageFile(Base):__table_args__ = (UniqueConstraint("repository_id", "file_path", name="uq_coverage_files"),)+class TestCoverageEntry(Base):+ """One ``(test, source file)`` coverage fact - the test-to-code map.++ Where :class:`CoverageFile` stores per-file aggregate coverage (a file is+ covered, merged across every test), this keeps the test dimension: a row+ says test ``test_id`` covered ``covered_lines_json`` of ``source_file``.+ It backs the reverse index "given changed lines, which tests hit them"+ that run-only-affected-tests and coverage-backed missing-test signals+ lean on.++ Design: a table, not a graph edge. The first consumer is a CI lookup+ keyed by changed source file + lines, which is a straight table query; a+ projected graph edge (composing with blast-radius) is deferred until a+ consumer needs graph composition.++ Point-in-time only: rows are overwritten per ingest run (delete-then+ -insert by ``repository_id``), no history - mirroring ``CoverageFile``.+ Populated only from context-carrying reports; ``covered_lines_json`` is a+ JSON int list (ceiling: fine at current scale, swap to a bitmap/RLE+ encoding if O(tests x files) row size becomes a problem).+ """++ __tablename__ = "test_coverage"+ # Not a pytest test class despite the ``Test`` prefix.+ __test__ = False++ 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+ )+ # Raw test identifier from the report (coverage.py context+ # ``module::qualname|phase`` or an lcov ``TN:`` name).+ test_id: Mapped[str] = mapped_column(Text, nullable=False)+ # Canonical repo key of the test's own source file, when resolvable.+ test_file: Mapped[str | None] = mapped_column(Text, nullable=True)+ # Canonical repo key of the covered source file.+ source_file: Mapped[str] = mapped_column(Text, nullable=False)+ covered_lines_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ source_format: Mapped[str] = mapped_column(String(32), nullable=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", "test_id", "source_file", name="uq_test_coverage"),+ # Reverse index (changed source file -> covering tests) is the hot path.+ Index("ix_test_coverage_repo_source", "repository_id", "source_file"),+ # Forward index (test -> files it covers).+ Index("ix_test_coverage_repo_test", "repository_id", "test_id"),+ )++class AnswerCache(Base):"""Cached LLM-synthesized answers from get_answer.diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsxindex 7cacdfa30..5adebcad0 100644--- a/packages/ui/src/files/file-coverage-tab.tsx+++ b/packages/ui/src/files/file-coverage-tab.tsx@@ -20,7 +20,7 @@ export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabP<EmptyStateicon={<Shield className="h-8 w-8" />}title="No coverage data"- description="Ingest a coverage report (repowise health --coverage <report>) to see line-level coverage here."+ description="Ingest a coverage report (repowise coverage add <report>) to see line-level coverage here."/>);}diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 3ed571242..3fa9584f9 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -483,7 +483,7 @@ function NoCoverageState() {</p><pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">pytest --cov --cov-report=lcov{"\n"}- repowise health --coverage coverage.lcov+ repowise coverage add coverage.lcov</pre><p className="text-xs text-[var(--color-text-tertiary)]">Supported formats: LCOV · Cobertura · Clover.diff --git a/plugins/claude-code/commands/health.md b/plugins/claude-code/commands/health.mdindex 9dad0d406..d4db3f780 100644--- a/plugins/claude-code/commands/health.md+++ b/plugins/claude-code/commands/health.md@@ -29,7 +29,7 @@ Handle `$ARGUMENTS`:- "trend" / "trends" → `repowise health --trend` (last snapshots + declining / predicted-decline alerts)- "module <name>" → `repowise health --module <name>`- "safe" → `repowise health --safe-only`-- a coverage file (e.g. `cov.lcov`, `coverage.xml`) → `repowise health --coverage <file>` to light up untested-hotspot / coverage-gap markers (LCOV, Cobertura, Clover)+- a coverage file (e.g. `cov.lcov`, `coverage.xml`, `.coverage`) → `repowise coverage add <file>` to ingest it (folds into health markers, and builds the per-test map when the report has contexts), then `repowise health`Other flags: `--format json` for machine-readable output, `--repo <alias>` /`--no-workspace` in workspace mode.diff --git a/plugins/claude-code/skills/code-health/SKILL.md b/plugins/claude-code/skills/code-health/SKILL.mdindex 15bcaa699..8e982daef 100644--- a/plugins/claude-code/skills/code-health/SKILL.md+++ b/plugins/claude-code/skills/code-health/SKILL.md@@ -44,15 +44,16 @@ not just *bigger*.3. Before editing a flagged file → cross-check `get_risk(targets=[...])`; a filethat is both low-health *and* a churn hotspot deserves the most care.4. Untested-hotspot / coverage questions → tell the user coverage markers- light up once they ingest a report: `repowise health --coverage cov.lcov`- (LCOV / Cobertura / Clover).+ light up once they ingest a report: `repowise coverage add cov.lcov`+ (LCOV / Cobertura / Clover; a coverage.py `.coverage` also builds the+ per-test map), then re-run `repowise health`.## CLI equivalents- `repowise health` — KPIs + lowest-scoring files- `repowise health --refactoring-targets` — ranked by impact / effort- `repowise health --trend` — snapshots + declining alerts-- `repowise health --coverage <file>` — ingest coverage, light up untested-hotspot+- `repowise coverage add <file>` — ingest coverage, light up untested-hotspot## Error handlingdiff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex f80d368c1..71a517173 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -318,6 +318,7 @@ def test_base_includes_all_models():"health_snapshots","refactoring_suggestions","coverage_files",+ "test_coverage","pipeline_jobs","graph_metrics","graph_node_membership",diff --git a/tests/unit/persistence/test_test_coverage_crud.py b/tests/unit/persistence/test_test_coverage_crud.pynew file mode 100644index 000000000..138600c1d--- /dev/null+++ b/tests/unit/persistence/test_test_coverage_crud.py@@ -0,0 +1,150 @@+"""CRUD for the per-test coverage map (``test_coverage`` table).++Exercises both query directions (reverse index with line intersection,+forward lookup), the point-in-time overwrite, and dedup/cap on save.+"""++from __future__ import annotations++from repowise.core.analysis.health.coverage import TestCoverage+from repowise.core.persistence.crud import (+ files_covered_by,+ get_test_coverage_summary,+ save_test_coverage,+)+from repowise.core.persistence.crud import (+ # Aliased: a bare ``tests_covering`` module global would be collected by+ # pytest as a test function (``test`` prefix).+ tests_covering as find_covering_tests,+)+from tests.unit.persistence.helpers import insert_repo+++def _rec(test_id: str, source_file: str, lines: list[int], test_file: str | None = None):+ return TestCoverage(+ test_id=test_id,+ file_path=source_file,+ covered_lines=lines,+ source_format="coverage.py",+ test_file=test_file,+ )+++async def test_save_and_query_both_directions(async_session) -> None:+ repo = await insert_repo(async_session)+ records = [+ _rec("tests/test_a.py::test_one|run", "src/foo.py", [1, 2, 3], "tests/test_a.py"),+ _rec("tests/test_a.py::test_one|run", "src/bar.py", [10], "tests/test_a.py"),+ _rec("tests/test_b.py::test_two|run", "src/foo.py", [3, 4, 5], "tests/test_b.py"),+ ]+ written = await save_test_coverage(async_session, repo.id, records, source_format="coverage.py")+ await async_session.commit()+ assert written == 3++ # Reverse: which tests cover src/foo.py at all.+ covering = await find_covering_tests(async_session, repo.id, "src/foo.py")+ ids = {c["test_id"] for c in covering}+ assert ids == {"tests/test_a.py::test_one|run", "tests/test_b.py::test_two|run"}++ # Forward: what does test_one cover.+ covered = await files_covered_by(async_session, repo.id, "tests/test_a.py::test_one|run")+ by_file = {c["source_file"]: c["covered_lines"] for c in covered}+ assert by_file == {"src/foo.py": [1, 2, 3], "src/bar.py": [10]}+++async def test_reverse_index_intersects_changed_lines(async_session) -> None:+ repo = await insert_repo(async_session)+ await save_test_coverage(+ async_session,+ repo.id,+ [+ _rec("t_one", "src/foo.py", [1, 2, 3]),+ _rec("t_two", "src/foo.py", [8, 9]),+ ],+ source_format="coverage.py",+ )+ await async_session.commit()++ # Only tests whose covered lines intersect the changed set come back,+ # narrowed to the intersecting lines - the impacted-tests query.+ hits = await find_covering_tests(async_session, repo.id, "src/foo.py", lines={2, 3})+ assert len(hits) == 1+ assert hits[0]["test_id"] == "t_one"+ assert hits[0]["covered_lines"] == [2, 3]++ # A change to line 9 hits only the other test.+ hits = await find_covering_tests(async_session, repo.id, "src/foo.py", lines={9})+ assert [h["test_id"] for h in hits] == ["t_two"]++ # A change touching no covered line returns nothing.+ assert await find_covering_tests(async_session, repo.id, "src/foo.py", lines={100}) == []+++async def test_save_overwrites_previous_run(async_session) -> None:+ repo = await insert_repo(async_session)+ await save_test_coverage(+ async_session, repo.id, [_rec("old", "src/foo.py", [1])], source_format="coverage.py"+ )+ await async_session.commit()+ await save_test_coverage(+ async_session, repo.id, [_rec("new", "src/foo.py", [2])], source_format="coverage.py"+ )+ await async_session.commit()++ covering = await find_covering_tests(async_session, repo.id, "src/foo.py")+ assert [c["test_id"] for c in covering] == ["new"]+++async def test_save_dedupes_repeated_pairs(async_session) -> None:+ repo = await insert_repo(async_session)+ # Same (test_id, source_file) twice - the unique key. First wins; the+ # second is dropped rather than tripping the constraint.+ written = await save_test_coverage(+ async_session,+ repo.id,+ [+ _rec("t", "src/foo.py", [1, 2]),+ _rec("t", "src/foo.py", [3, 4]),+ ],+ source_format="coverage.py",+ )+ await async_session.commit()+ assert written == 1+ covered = await files_covered_by(async_session, repo.id, "t")+ assert covered[0]["covered_lines"] == [1, 2]+++async def test_save_caps_rows(async_session) -> None:+ repo = await insert_repo(async_session)+ records = [_rec(f"t{i}", "src/foo.py", [i]) for i in range(10)]+ written = await save_test_coverage(+ async_session, repo.id, records, source_format="coverage.py", max_rows=4+ )+ await async_session.commit()+ assert written == 4+ covering = await find_covering_tests(async_session, repo.id, "src/foo.py")+ assert len(covering) == 4+++async def test_summary_counts(async_session) -> None:+ repo = await insert_repo(async_session)+ empty = await get_test_coverage_summary(async_session, repo.id)+ assert empty["pair_count"] == 0++ await save_test_coverage(+ async_session,+ repo.id,+ [+ _rec("t_one", "src/foo.py", [1]),+ _rec("t_one", "src/bar.py", [2]),+ _rec("t_two", "src/foo.py", [3]),+ ],+ source_format="coverage.py",+ )+ await async_session.commit()++ summary = await get_test_coverage_summary(async_session, repo.id)+ assert summary["pair_count"] == 3+ assert summary["test_count"] == 2+ assert summary["source_file_count"] == 2+ assert summary["source_format"] == "coverage.py"