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(health): ingest coverage reports during indexing (#604)

Raghav Chamadiya956e5417ef19
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
new file mode 100644
index 000000000..fab110b8c
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -0,0 +1,222 @@
+"""``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.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+
+from repowise.cli.helpers import (
+ console,
+ ensure_repowise_dir,
+ get_db_url_for_repo,
+ resolve_command_target,
+ run_async,
+)
+
+
+def _resolve_coverage_repo(path: str | None) -> Path:
+ """Resolve the repo path for coverage subcommands (workspace-aware)."""
+ target = resolve_command_target(path=path)
+ target.notice(console, command="coverage")
+ if target.is_workspace:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ return primary
+ assert target.repo_path is not None
+ return target.repo_path
+
+
+async def _repo_file_keys(session, repo_id: str) -> set[str]:
+ """Canonical repo file keys to resolve report paths against.
+
+ Sourced from the persisted health metrics (one row per indexed file);
+ these already carry the repo-relative POSIX key the resolver needs.
+ """
+ from repowise.core.persistence.crud import get_health_metrics
+
+ metrics = await get_health_metrics(session, repo_id)
+ return {m.file_path for m in metrics}
+
+
[email protected]("coverage")
+def coverage_group() -> None:
+ """Ingest and inspect test-coverage reports."""
+
+
+@coverage_group.command("add")
[email protected]("paths", nargs=-1, type=click.Path(exists=True, dir_okay=False))
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary).")
+ "--format",
+ "coverage_format",
+ type=click.Choice(["lcov", "cobertura", "clover", "repowise-json"]),
+ default=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).
+
+ Examples:
+
+ repowise coverage add # discover coverage/lcov.info etc.
+ repowise coverage add coverage/lcov.info
+ repowise coverage add web.lcov api.lcov # merged hit-wins
+ """
+ repo_path = _resolve_coverage_repo(repo)
+ ensure_repowise_dir(repo_path)
+
+ from repowise.core.analysis.health.coverage import (
+ CoverageConfig,
+ build_coverage_map,
+ discover_artifacts,
+ )
+ from repowise.core.repo_config import load_repo_config
+
+ cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
+
+ if paths:
+ report_paths = [Path(p) for p in paths]
+ else:
+ report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)
+ 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]"
+ )
+ return
+ console.print(
+ f"Discovered {len(report_paths)} report(s): "
+ + ", ".join(p.name for p in report_paths[:5])
+ )
+
+ async def _do() -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import (
+ get_repository_by_path,
+ save_coverage_files,
+ )
+
+ 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))
+ if repo_row is None:
+ console.print(
+ "[yellow]No index yet — run `repowise init` once before "
+ "adding coverage.[/yellow]"
+ )
+ return
+ repo_keys = await _repo_file_keys(session, repo_row.id)
+ if not repo_keys:
+ console.print(
+ "[yellow]No indexed files found — run `repowise init` "
+ "first.[/yellow]"
+ )
+ 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]")
+
+ if not resolved.files:
+ 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_async(_do())
+
+
+@coverage_group.command("status")
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary).")
+def coverage_status(repo: str | None) -> None:
+ """Show the coverage currently ingested for this repo."""
+ repo_path = _resolve_coverage_repo(repo)
+
+ async def _do() -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import (
+ get_coverage_summary,
+ 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))
+ if repo_row is None:
+ console.print("[yellow]No index yet — run `repowise init`.[/yellow]")
+ return
+ summary = await get_coverage_summary(session, repo_row.id)
+ if not summary.get("file_count"):
+ console.print(
+ "[yellow]No coverage ingested.[/yellow] Run "
+ "[cyan]repowise coverage add[/cyan] or regenerate the index "
+ "with a coverage report present."
+ )
+ 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}%")
+
+ run_async(_do())
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 8aa0d4457..035776979 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -362,6 +362,19 @@ def _run_generation_phase(
"interactive: prompt; otherwise 0.20."
),
)
+ "--coverage-report",
+ "coverage_report",
+ type=click.Path(exists=True, dir_okay=False),
+ multiple=True,
+ metavar="PATH",
+ help=(
+ "Test-coverage report(s) to ingest (lcov / Cobertura / Clover). "
+ "Repeatable. When omitted, common locations (coverage/lcov.info, "
+ "**/cobertura.xml, ...) are auto-discovered. Distinct from --coverage, "
+ "which controls documentation breadth."
+ ),
+)
@click.option(
"--harvest-decisions/--no-harvest-decisions",
"harvest_decisions",
@@ -413,6 +426,7 @@ def init_command(
init_all: bool,
onboarding: bool,
coverage_pct: float | None,
+ coverage_report: tuple[str, ...],
harvest_decisions: bool,
wiki_style: str | None,
) -> None:
@@ -782,6 +796,9 @@ def init_command(
progress=callback,
existing_kg_fingerprint=_prev_kg_fp,
resume_controller=controller,
+ coverage_report_paths=(
+ [Path(p) for p in coverage_report] if coverage_report else None
+ ),
)
finally:
if engine is not None:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index acef25d5e..86a43e7fa 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -17,6 +17,66 @@ from repowise.cli.helpers import console, run_async, save_state
from .incremental import _build_repo_graph
+async def _coverage_for_rescore(
+ session: Any,
+ repo_id: str,
+ repo_path: Path,
+ parsed_files: list[Any],
+) -> tuple[dict[str, dict], list[Any], str | None]:
+ """Coverage to feed a health re-score, preserved across updates.
+
+ Default: reload the rows already persisted (no re-parse). When
+ ``coverage.reingest_on_update`` is set, re-discover and re-resolve a
+ fresh report instead. Returns ``(coverage_map, files_to_persist,
+ source_format)`` — ``files_to_persist`` is empty on the reload path
+ (rows are unchanged) and populated when re-ingested.
+ """
+ import json
+
+ from repowise.core.analysis.health.coverage import (
+ CoverageConfig,
+ build_coverage_map,
+ discover_artifacts,
+ )
+ from repowise.core.persistence.crud import load_coverage_for_repo
+ from repowise.core.repo_config import load_repo_config
+
+ cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
+
+ if cfg.reingest_on_update and cfg.auto_discover:
+ report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)
+ if report_paths:
+ repo_keys = {pf.file_info.path for pf in parsed_files}
+ resolved, _errors = build_coverage_map(
+ repo_path,
+ report_paths,
+ repo_keys,
+ coverage_format=cfg.format,
+ strip_prefix=cfg.strip_prefix,
+ path_prefix=cfg.path_prefix,
+ )
+ if resolved.coverage_map:
+ return resolved.coverage_map, resolved.files, resolved.source_format
+
+ rows = await load_coverage_for_repo(session, repo_id)
+ coverage_map: dict[str, dict] = {}
+ source_format: str | None = None
+ for row in rows:
+ source_format = source_format or getattr(row, "source_format", None)
+ try:
+ covered = json.loads(row.covered_lines_json) if row.covered_lines_json else []
+ except (ValueError, TypeError):
+ covered = []
+ coverage_map[row.file_path] = {
+ "line_coverage_pct": row.line_coverage_pct,
+ "branch_coverage_pct": row.branch_coverage_pct,
+ "covered_lines": covered,
+ "total_coverable_lines": row.total_coverable_lines or 0,
+ "source_format": source_format,
+ }
+ return coverage_map, [], source_format
+
+
async def _persist_partial_health(session: Any, repo_id: str, report: Any) -> None:
"""Upsert health findings + metrics for the changed-files subset.
@@ -178,7 +238,11 @@ def _run_full_health_rescore(
init_db,
upsert_repository,
)
- from repowise.core.persistence.crud import save_health_findings, save_health_metrics
+ from repowise.core.persistence.crud import (
+ save_coverage_files,
+ save_health_findings,
+ save_health_metrics,
+ )
from repowise.core.persistence.models import GitMetadata
from repowise.core.pipeline.persist import persist_graph_nodes
@@ -215,10 +279,20 @@ def _run_full_health_rescore(
if exclude_spec is None or not exclude_spec.match_file(gm.file_path)
}
+ # Preserve coverage across a re-score. The previous behaviour
+ # rebuilt the analyzer with no coverage_map, nulling every file's
+ # line/branch coverage even though the coverage_files rows still
+ # existed. Reload them (and optionally re-discover a fresh report)
+ # so coverage survives `repowise update`.
+ coverage_map, coverage_files, coverage_format = await _coverage_for_rescore(
+ session, repo_id, repo_path, parsed_files
+ )
+
analyzer = HealthAnalyzer(
graph_builder.graph(),
git_meta_map=git_meta_map,
parsed_files=parsed_files,
+ coverage_map=coverage_map,
duplication_cache_dir=Path(repo_path) / ".repowise",
)
hcfg = HealthConfig.load(repo_path)
@@ -236,6 +310,14 @@ def _run_full_health_rescore(
await save_health_metrics(session, repo_id, report.metrics or [])
await save_health_findings(session, repo_id, list(report.findings or []))
+ if coverage_files:
+ await save_coverage_files(
+ session,
+ repo_id,
+ coverage_files,
+ source_format=coverage_format or "lcov",
+ ingested_commit_sha=getattr(repo, "head_commit", None),
+ )
await persist_graph_nodes(session, repo_id, graph_builder)
try:
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 736095057..4168b6fed 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -10,6 +10,7 @@ from repowise.cli.commands.augment_cmd import augment_command
from repowise.cli.commands.claude_md_cmd import claude_md_command
from repowise.cli.commands.corrections_cmd import corrections_command
from repowise.cli.commands.costs_cmd import costs_command
+from repowise.cli.commands.coverage_cmd import coverage_group
from repowise.cli.commands.dead_code_cmd import dead_code_command
from repowise.cli.commands.decision_cmd import decision_group
from repowise.cli.commands.delete_cmd import delete_command
@@ -68,6 +69,7 @@ register_command(dead_code_command)
register_command(health_command)
register_command(risk_command)
register_command(decision_group)
+register_command(coverage_group)
register_command(search_command)
register_command(distill_command)
register_command(expand_command)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index 0b4acdcae..e944f1926 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -277,3 +277,10 @@ class FileComplexity:
# function holds a bare (non-loop) I/O sink. Empty when the language opts
# out of the perf pass. Consumed by ``perf.crossfn``, not by a biomarker.
perf_fn_facts: list[PerfFnFacts] = field(default_factory=list)
+ # True when the file carries co-located tests that the filename/dir
+ # heuristic cannot see — e.g. Rust ``#[cfg(test)] mod tests`` blocks,
+ # which live inside the source file itself. OR'd into ``has_test_file``
+ # so well-tested inline-test files aren't flagged as untested. Only ever
+ # flips a file from "untested" to "tested", so it can silence a finding
+ # but never invent one.
+ has_inline_tests: bool = False
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 208f7cb42..cb408fb5e 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -152,6 +152,7 @@ def walk_file(
perf_hits=perf_hits,
io_boundary_names=io_boundary_names,
perf_fn_facts=perf_fn_facts,
+ has_inline_tests=_detect_inline_tests(source, language),
)
@@ -165,3 +166,22 @@ def walk_file_complexity(
Prefer ``walk_file`` when class-level metrics are also needed.
"""
return walk_file(abs_path, language, source).functions
+
+
+# Idiomatic Rust unit tests live in a ``#[cfg(test)] mod tests`` block inside
+# the source file itself, so there is no separate test file to pair against.
+# A cheap substring scan over the file head is enough to recognize them —
+# ``#[cfg(test)]`` gates the test module; ``#[test]`` marks each test fn.
+_RUST_INLINE_TEST_MARKERS = (b"#[cfg(test)]", b"#[test]")
+
+
+def _detect_inline_tests(source: bytes, language: str) -> bool:
+ """True when *source* carries co-located tests the filename can't reveal.
+
+ Currently Rust-only. Pure substring scan (no extra parse); returns False
+ for every other language, so it can only ever clear a false ``untested``
+ flag, never create a finding.
+ """
+ if language != "rust":
+ return False
+ return any(marker in source for marker in _RUST_INLINE_TEST_MARKERS)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.md
index baa462581..dbbc66d54 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md
+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md
@@ -9,6 +9,9 @@ from repowise.core.analysis.health.coverage import (
CoverageReport, FileCoverage,
parse, detect_format,
is_test_file, paired_test_file,
+ # discovery + resolution
+ CoverageConfig, ResolvedCoverage,
+ discover_artifacts, resolve_reports, build_coverage_map,
)
```
@@ -49,6 +52,47 @@ skipped (absent ≠ zero).
- `paired_test_file(path, all_paths)` — find the conventional test
partner for a source path.
+## Discovery + path resolution (`discovery.py`)
+
+Ingested coverage only helps if its file paths line up with the indexed
+tree. repowise's canonical file key is **repo-relative, forward-slash
+POSIX** (set in `ingestion/traverser.py`). Almost no coverage tool emits
+that key — lcov / nyc / c8 / cargo-llvm-cov write absolute paths, Cobertura
+writes paths relative to its own `<source>` root — so we reconcile them.
+
+- `discover_artifacts(repo_root, globs=None)` — glob the filesystem for
+ report files (`coverage/lcov.info`, `**/cobertura.xml`, ...). The report
+ dirs are excluded from the indexed file set, so discovery hits the FS
+ directly; results are pruned of vendored dirs and capped.
+- `resolve_reports(reports, repo_keys, ...)` — map each report path to a
+ canonical key by **longest trailing-segment overlap**, refusing to guess
+ on a true tie. Merges multiple reports hit-wins. Returns a
+ `ResolvedCoverage` with the engine `coverage_map`, rewritten
+ `FileCoverage` rows, and `matched` / `unmatched` / `ambiguous`
+ diagnostics (surfaced so coverage never silently shows 0%).
+- `build_coverage_map(repo_root, report_paths, repo_keys, ...)` — read +
+ parse + resolve end-to-end.
+
+### Config (`.repowise/config.yaml`)
+
+All keys optional; the defaults give zero-config auto-discovery during
+`repowise init` / `repowise update`.
+
+```yaml
+coverage:
+ auto_discover: true # discover reports during indexing
+ artifacts: # override the default discovery globs
+ - coverage/lcov.info
+ paths: # explicit report paths (skip discovery)
+ - build/coverage/lcov.info
+ format: lcov # force a parser (else content-sniffed)
+ strip_prefix: build # drop a leading prefix from report paths
+ path_prefix: packages/web # prepend a prefix to report paths
+ reingest_on_update: false # re-parse on every update (else reuse DB rows)
+```
+
+`CoverageConfig.from_repo_config(load_repo_config(repo_path))` parses it.
+
## Inputs
- A raw coverage report (the contents of `coverage.lcov`, a Cobertura
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index 69ffcc5ed..aa0efd08f 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -5,19 +5,33 @@ from __future__ import annotations
from .clover import parse_clover
from .cobertura import parse_cobertura
from .detector import detect_format, is_test_file, paired_test_file, parse
+from .discovery import (
+ CoverageConfig,
+ ResolvedCoverage,
+ build_coverage_map,
+ discover_artifacts,
+ normalize_report_path,
+ resolve_reports,
+)
from .lcov import parse_lcov
from .model import CoverageReport, FileCoverage
from .repowise_json import parse_repowise_json
__all__ = [
+ "CoverageConfig",
"CoverageReport",
"FileCoverage",
+ "ResolvedCoverage",
+ "build_coverage_map",
"detect_format",
+ "discover_artifacts",
"is_test_file",
+ "normalize_report_path",
"paired_test_file",
"parse",
"parse_clover",
"parse_cobertura",
"parse_lcov",
"parse_repowise_json",
+ "resolve_reports",
]
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
new file mode 100644
index 000000000..f8ab92900
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -0,0 +1,379 @@
+"""Coverage artifact discovery + report-path resolution.
+
+Two jobs that make ingested coverage *actually line up* with the repo:
+
+1. **Discovery** — find coverage report files on disk. The file traverser
+ blocks ``coverage/``, ``htmlcov/``, ``target/`` and friends, so report
+ artifacts never appear in the indexed file set; we glob the filesystem
+ directly with a curated, bounded set of patterns.
+
+2. **Resolution** — reconcile the file paths *inside* a report (lcov ``SF:``
+ records, Cobertura ``filename`` attrs, ...) to repowise's canonical file
+ key, which is **repo-relative, forward-slash POSIX** (set in
+ ``ingestion/traverser.py`` via ``abs_path.relative_to(repo_root).as_posix()``).
+
+ Almost no coverage tool emits that key: lcov / nyc / c8 / cargo-llvm-cov
+ write absolute paths; Cobertura writes paths relative to its own
+ ``<source>`` root. Mapping them back is the most common reason coverage
+ appears to "silently show 0%". We resolve by **longest trailing-segment
+ overlap** against the indexed tree, so no per-report path-rewrite config
+ is needed, and we report unmatched files **loudly** rather than rendering
+ a silent 0%.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from .detector import parse as parse_coverage
+from .model import CoverageReport, FileCoverage
+
+# Default glob patterns, relative to the repo root. Ordered roughly by how
+# canonical/common the location is. Kept curated (not a blind ``**/*.info``)
+# so discovery stays fast and doesn't wander into ``node_modules``.
+DEFAULT_DISCOVERY_GLOBS: tuple[str, ...] = (
+ "coverage/lcov.info",
+ "coverage/**/lcov.info",
+ "lcov.info",
+ "coverage.lcov",
+ "coverage/cobertura.xml",
+ "coverage/cobertura-coverage.xml",
+ "**/cobertura.xml",
+ "**/cobertura-coverage.xml",
+ "coverage.xml",
+ "coverage/coverage.xml",
+ "coverage/clover.xml",
+ "**/clover.xml",
+ "target/llvm-cov/**/*.lcov",
+ "target/nextest/**/*.xml",
+)
+
+# Directories we never descend into when expanding ``**`` patterns — heavy,
+# vendored, or irrelevant. Keeps discovery bounded on large repos.
+_PRUNE_DIRS = frozenset(
+ {
+ ".git",
+ "node_modules",
+ ".venv",
+ "venv",
+ "dist",
+ "build",
+ "__pycache__",
+ ".next",
+ ".mypy_cache",
+ ".pytest_cache",
+ ".tox",
+ }
+)
+
+# Hard cap on discovered artifacts — a sane upper bound that still covers
+# polyglot monorepos with several per-package reports.
+_MAX_ARTIFACTS = 50
+
+
+@dataclass
+class CoverageConfig:
+ """The ``coverage:`` block of ``.repowise/config.yaml``.
+
+ All fields are optional; the defaults give zero-config auto-discovery.
+ """
+
+ auto_discover: bool = True
+ # Override the default discovery globs entirely.
+ artifacts: tuple[str, ...] = ()
+ # Explicit report paths (relative to repo root) — bypass discovery.
+ paths: tuple[str, ...] = ()
+ # Force a parser instead of content-sniffing.
+ format: str | None = None
+ # Remove this leading prefix from report paths before matching.
+ strip_prefix: str | None = None
+ # Prepend this prefix to report paths before matching.
+ path_prefix: str | None = None
+ # Re-discover + re-parse reports on every ``repowise update`` (default:
+ # reuse the rows already in the DB; only re-ingest if a report is found).
+ reingest_on_update: bool = False
+
+ @classmethod
+ def from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:
+ block = (repo_config or {}).get("coverage")
+ if not isinstance(block, dict):
+ return cls()
+
+ def _strs(val: object) -> tuple[str, ...]:
+ if isinstance(val, str):
+ return (val,)
+ if isinstance(val, (list, tuple)):
+ return tuple(str(v) for v in val if v)
+ return ()
+
+ return cls(
+ auto_discover=bool(block.get("auto_discover", True)),
+ artifacts=_strs(block.get("artifacts")),
+ paths=_strs(block.get("paths")),
+ format=block.get("format") or None,
+ strip_prefix=block.get("strip_prefix") or None,
+ path_prefix=block.get("path_prefix") or None,
+ reingest_on_update=bool(block.get("reingest_on_update", False)),
+ )
+
+
+@dataclass
+class ResolvedCoverage:
+ """Outcome of resolving a parsed report against the indexed tree."""
+
+ # Canonical repo key -> engine coverage dict (the shape ``HealthAnalyzer``
+ # consumes via ``coverage_map``).
+ coverage_map: dict[str, dict] = field(default_factory=dict)
+ # ``FileCoverage`` rows with ``file_path`` rewritten to canonical keys,
+ # for DB persistence (``save_coverage_files``).
+ files: list[FileCoverage] = field(default_factory=list)
+ source_format: str | None = None
+ # Diagnostics — surfaced to the user so "coverage didn't show up" is
+ # never silent.
+ matched_exact: int = 0
+ matched_suffix: int = 0
+ unmatched: list[str] = field(default_factory=list)
+ ambiguous: list[str] = field(default_factory=list)
+
+ @property
+ def matched(self) -> int:
+ return self.matched_exact + self.matched_suffix
+
+ @property
+ def total(self) -> int:
+ return self.matched + len(self.unmatched) + len(self.ambiguous)
+
+
+def discover_artifacts(
+ repo_root: Path,
+ *,
+ globs: tuple[str, ...] | list[str] | None = None,
+) -> list[Path]:
+ """Return coverage report files under *repo_root*, de-duplicated.
+
+ Globs the filesystem directly (the report dirs are excluded from the
+ indexed file set). Results are pruned of vendored dirs, de-duplicated
+ by resolved path, and capped at :data:`_MAX_ARTIFACTS`.
+ """
+ patterns = tuple(globs) if globs else DEFAULT_DISCOVERY_GLOBS
+ seen: set[Path] = set()
+ out: list[Path] = []
+ for pattern in patterns:
+ for match in repo_root.glob(pattern):
+ if not match.is_file():
+ continue
+ try:
+ rel_parts = match.relative_to(repo_root).parts
+ except ValueError:
+ rel_parts = match.parts
+ if any(part in _PRUNE_DIRS for part in rel_parts[:-1]):
+ continue
+ resolved = match.resolve()
+ if resolved in seen:
+ continue
+ seen.add(resolved)
+ out.append(match)
+ if len(out) >= _MAX_ARTIFACTS:
+ return out
+ return out
+
+
+def normalize_report_path(
+ raw: str,
+ *,
+ strip_prefix: str | None = None,
+ path_prefix: str | None = None,
+) -> str:
+ """Normalize a report file path toward the canonical key shape.
+
+ POSIX separators, no leading ``./`` or ``/``, optional drive letter
+ dropped, then an optional configured *strip_prefix* removed and
+ *path_prefix* prepended. The result is still not guaranteed to be a
+ real repo key — that is what :func:`_match_key` is for — but it is the
+ best deterministic starting point.
+ """
+ p = raw.strip().replace("\\", "/")
+ # Drop a Windows drive letter (``C:/...``).
+ if len(p) >= 2 and p[1] == ":":
+ p = p[2:]
+ while p.startswith("./"):
+ p = p[2:]
+ p = p.lstrip("/")
+ if strip_prefix:
+ sp = strip_prefix.replace("\\", "/").strip("/")
+ if sp and p.startswith(sp + "/"):
+ p = p[len(sp) + 1 :]
+ if path_prefix:
+ pp = path_prefix.replace("\\", "/").strip("/")
+ if pp:
+ p = f"{pp}/{p}"
+ return p
+
+
+def _build_suffix_index(repo_keys: set[str]) -> dict[str, list[str]]:
+ """Map each basename -> repo keys ending in that basename.
+
+ Basename is the cheap first filter; trailing-segment overlap then
+ disambiguates among same-named files (``mod.rs`` is everywhere in Rust).
+ """
+ index: dict[str, list[str]] = defaultdict(list)
+ for key in repo_keys:
+ base = key.rsplit("/", 1)[-1]
+ index[base].append(key)
+ return index
+
+
+def _match_key(
+ norm_path: str,
+ repo_keys: set[str],
+ suffix_index: dict[str, list[str]],
+) -> tuple[str | None, bool]:
+ """Resolve a normalized report path to a canonical key.
+
+ Returns ``(key, ambiguous)``. ``key`` is None when nothing matched;
+ ``ambiguous`` is True when several repo files tie on the longest
+ trailing-segment overlap (we refuse to guess).
+ """
+ if norm_path in repo_keys:
+ return norm_path, False
+
+ base = norm_path.rsplit("/", 1)[-1]
+ candidates = suffix_index.get(base)
+ if not candidates:
+ return None, False
+ if len(candidates) == 1:
+ return candidates[0], False
+
+ report_segs = norm_path.split("/")
+ best_overlap = 0
+ winners: list[str] = []
+ for cand in candidates:
+ cand_segs = cand.split("/")
+ overlap = 0
+ for a, b in zip(reversed(report_segs), reversed(cand_segs), strict=False):
+ if a != b:
+ break
+ overlap += 1
+ if overlap > best_overlap:
+ best_overlap = overlap
+ winners = [cand]
+ elif overlap == best_overlap:
+ winners.append(cand)
+
+ if len(winners) == 1:
+ return winners[0], False
+ return None, True
+
+
+def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:
+ """Hit-wins merge of *src* into *dst* (same canonical key).
+
+ A line covered by any report counts as covered; this enables
+ multi-suite / multi-language ingestion with no config.
+ """
+ covered = set(dst.covered_lines) | set(src.covered_lines)
+ total = max(dst.total_coverable_lines, src.total_coverable_lines, len(covered))
+ dst.covered_lines = sorted(covered)
+ dst.total_coverable_lines = total
+ dst.line_coverage_pct = round(len(covered) / total * 100.0, 2) if total else 0.0
+ if src.branch_coverage_pct is not None:
+ dst.branch_coverage_pct = (
+ src.branch_coverage_pct
+ if dst.branch_coverage_pct is None
+ else max(dst.branch_coverage_pct, src.branch_coverage_pct)
+ )
+
+
+def resolve_reports(
+ reports: list[CoverageReport],
+ repo_keys: set[str],
+ *,
+ strip_prefix: str | None = None,
+ path_prefix: str | None = None,
+) -> ResolvedCoverage:
+ """Resolve one or more parsed reports against the indexed tree.
+
+ Reports are merged hit-wins by canonical key. Returns the engine
+ ``coverage_map``, rewritten ``FileCoverage`` rows for persistence, and
+ diagnostics (matched/unmatched/ambiguous) for loud reporting.
+ """
+ suffix_index = _build_suffix_index(repo_keys)
+ result = ResolvedCoverage()
+ by_key: dict[str, FileCoverage] = {}
+
+ for report in reports:
+ if result.source_format is None and report.source_format not in (None, "unknown"):
+ result.source_format = report.source_format
+ for fc in report.files:
+ norm = normalize_report_path(
+ fc.file_path, strip_prefix=strip_prefix, path_prefix=path_prefix
+ )
+ key, ambiguous = _match_key(norm, repo_keys, suffix_index)
+ if key is None:
+ if ambiguous:
+ result.ambiguous.append(fc.file_path)
+ else:
+ result.unmatched.append(fc.file_path)
+ continue
+ if norm == key:
+ result.matched_exact += 1
+ else:
+ result.matched_suffix += 1
+ resolved_fc = FileCoverage(
+ file_path=key,
+ line_coverage_pct=fc.line_coverage_pct,
+ branch_coverage_pct=fc.branch_coverage_pct,
+ covered_lines=list(fc.covered_lines),
+ total_coverable_lines=fc.total_coverable_lines,
+ )
+ if key in by_key:
+ _merge_into(by_key[key], resolved_fc)
+ else:
+ by_key[key] = resolved_fc
+
+ for key, fc in by_key.items():
+ result.coverage_map[key] = {
+ "line_coverage_pct": fc.line_coverage_pct,
+ "branch_coverage_pct": fc.branch_coverage_pct,
+ "covered_lines": list(fc.covered_lines),
+ "total_coverable_lines": fc.total_coverable_lines,
+ "source_format": result.source_format,
+ }
+ result.files = list(by_key.values())
+ return result
+
+
+def build_coverage_map(
+ repo_root: Path,
+ report_paths: list[Path],
+ repo_keys: set[str],
+ *,
+ coverage_format: str | None = None,
+ strip_prefix: str | None = None,
+ path_prefix: str | None = None,
+) -> tuple[ResolvedCoverage, list[tuple[Path, str]]]:
+ """Read + parse + resolve coverage reports end-to-end.
+
+ Returns the :class:`ResolvedCoverage` and a list of ``(path, error)``
+ for reports that could not be read or parsed (caller decides how loud
+ to be). Unreadable/empty reports are skipped, never fatal.
+ """
+ parsed: list[CoverageReport] = []
+ errors: list[tuple[Path, str]] = []
+ for path in report_paths:
+ try:
+ text = path.read_text(encoding="utf-8")
+ except OSError as exc:
+ errors.append((path, f"could not read: {exc}"))
+ continue
+ report = parse_coverage(text, format=coverage_format)
+ if not report.files:
+ errors.append((path, f"no coverage entries (detected={report.source_format})"))
+ continue
+ parsed.append(report)
+ resolved = resolve_reports(
+ parsed, repo_keys, strip_prefix=strip_prefix, path_prefix=path_prefix
+ )
+ return resolved, errors
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 792da4417..14dd17e87 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -762,7 +762,8 @@ class HealthAnalyzer:
nloc=nloc,
has_test_file=_has_paired_test_file(file_path, path_basenames)
or _is_test_file(file_path)
- or _coverage_is_test_file(file_path),
+ or _coverage_is_test_file(file_path)
+ or fcx.has_inline_tests,
module=module,
function_metrics=fn_metrics,
class_metrics=fcx.classes,
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index b987847f5..59d50d462 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -80,3 +80,9 @@ class HealthReport:
# or no opportunity is found. Typed ``Any`` to avoid importing the
# refactoring package here (it imports this module).
refactoring_suggestions: list[Any] = field(default_factory=list)
+ # Resolved coverage rows ingested for this run (``FileCoverage`` with
+ # canonical repo keys), plus the source format. Populated by the pipeline
+ # when a coverage report is discovered/passed; the persister writes these
+ # to the ``coverage_files`` table. Empty when no coverage was ingested.
+ coverage_files: list[Any] = field(default_factory=list)
+ coverage_format: str | None = None
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 27fd4f433..6cfb40c69 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -178,6 +178,7 @@ async def run_pipeline(
existing_kg_fingerprint: str | None = None,
on_page_ready: Any | None = None,
resume_controller: ResumeController | None = None,
+ coverage_report_paths: list[Path] | None = None,
) -> PipelineResult:
"""Run the repowise indexing/analysis/generation pipeline.
@@ -463,7 +464,12 @@ async def run_pipeline(
)
health_report = await _run_health_analysis(
- graph_builder, git_meta_map, parsed_files, repo_path=repo_path, progress=progress
+ graph_builder,
+ git_meta_map,
+ parsed_files,
+ repo_path=repo_path,
+ coverage_report_paths=coverage_report_paths,
+ progress=progress,
)
# Drop the in-memory-only ``BlameIndex`` now that the health biomarkers
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 6599cbe88..fe3c8cb1a 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -518,6 +518,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
from repowise.core.persistence.crud import (
bulk_upsert_decisions,
recompute_decision_staleness,
+ save_coverage_files,
save_dead_code_findings,
save_health_findings,
save_health_metrics,
@@ -536,6 +537,19 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
await save_health_metrics(session, repo_id, hr.metrics or [])
if hr.findings:
await save_health_findings(session, repo_id, hr.findings)
+ # Resolved coverage rows, when a report was ingested this run.
+ coverage_files = getattr(hr, "coverage_files", None)
+ if coverage_files:
+ head_sha = getattr(result, "head_commit", None) or getattr(
+ result, "commit_sha", None
+ )
+ await save_coverage_files(
+ session,
+ repo_id,
+ coverage_files,
+ source_format=getattr(hr, "coverage_format", None) or "lcov",
+ ingested_commit_sha=head_sha,
+ )
# Structured refactoring suggestions (Extract Class, ...). Repo-wide
# delete-then-insert like findings; empty list clears prior rows.
await save_refactoring_suggestions(
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 1fcbfa4d2..f6b25654b 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -68,12 +68,88 @@ async def _run_dead_code_analysis(
return None
+def _build_pipeline_coverage(
+ repo_path: Path,
+ parsed_files: list[Any],
+ explicit_paths: list[Path] | None,
+ *,
+ progress: ProgressCallback | None,
+) -> tuple[dict[str, dict], list[Any], str | None]:
+ """Discover/parse/resolve coverage reports for an indexing run.
+
+ Returns ``(coverage_map, resolved_files, source_format)``. Best-effort:
+ any failure logs and yields an empty map so health analysis proceeds
+ without coverage. Unmatched report files are surfaced via *progress* so
+ "coverage didn't show up" is never silent.
+ """
+ try:
+ from repowise.core.analysis.health.coverage import (
+ CoverageConfig,
+ build_coverage_map,
+ discover_artifacts,
+ )
+ from repowise.core.repo_config import load_repo_config
+
+ cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
+
+ if explicit_paths:
+ report_paths = list(explicit_paths)
+ elif cfg.paths:
+ report_paths = [repo_path / p for p in cfg.paths if (repo_path / p).is_file()]
+ elif cfg.auto_discover:
+ report_paths = discover_artifacts(
+ repo_path, globs=cfg.artifacts or None
+ )
+ else:
+ return {}, [], None
+
+ if not report_paths:
+ return {}, [], None
+
+ repo_keys = {pf.file_info.path for pf in parsed_files}
+ resolved, errors = build_coverage_map(
+ repo_path,
+ report_paths,
+ repo_keys,
+ coverage_format=cfg.format,
+ strip_prefix=cfg.strip_prefix,
+ path_prefix=cfg.path_prefix,
+ )
+
+ if progress:
+ names = ", ".join(p.name for p in report_paths[:3])
+ more = f" (+{len(report_paths) - 3} more)" if len(report_paths) > 3 else ""
+ progress.on_message(
+ "info",
+ f"→ coverage: {resolved.matched} files matched from {names}{more}",
+ )
+ skipped = len(resolved.unmatched) + len(resolved.ambiguous)
+ if skipped:
+ sample = ", ".join((resolved.unmatched + resolved.ambiguous)[:3])
+ progress.on_message(
+ "warning",
+ f" ↳ {skipped} report file(s) did not map to the repo tree "
+ f"(e.g. {sample}). Set coverage.strip_prefix in "
+ f".repowise/config.yaml if paths are off.",
+ )
+ for path, err in errors:
+ progress.on_message("warning", f" ↳ coverage {path.name}: {err}")
+
+ return resolved.coverage_map, resolved.files, resolved.source_format
+ except Exception as exc:
+ if progress:
+ progress.on_message("warning", f"Coverage ingestion skipped: {exc}")
+ logger.debug("pipeline_coverage_failed", error=str(exc))
+ return {}, [], None
+
+
async def _run_health_analysis(
graph_builder: Any,
git_meta_map: dict[str, dict],
parsed_files: list[Any],
*,
repo_path: Path | None = None,
+ coverage_report_paths: list[Path] | None = None,
progress: ProgressCallback | None,
) -> Any | None:
"""Run code-health analysis (complexity + biomarkers + scoring)."""
@@ -104,11 +180,22 @@ async def _run_health_analysis(
except Exception as exc:
logger.debug("health_module_map_failed", error=str(exc))
+ # Ingest coverage (auto-discovered or explicitly passed) so biomarkers
+ # see real line/branch coverage instead of the has_test_file fallback.
+ coverage_map: dict[str, dict] = {}
+ coverage_files: list[Any] = []
+ coverage_format: str | None = None
+ if repo_path is not None:
+ coverage_map, coverage_files, coverage_format = _build_pipeline_coverage(
+ repo_path, parsed_files, coverage_report_paths, progress=progress
+ )
+
analyzer = HealthAnalyzer(
graph_builder.graph(),
git_meta_map=git_meta_map,
parsed_files=parsed_files,
module_map=module_map,
+ coverage_map=coverage_map,
duplication_cache_dir=(repo_path / ".repowise") if repo_path is not None else None,
)
@@ -134,6 +221,12 @@ async def _run_health_analysis(
else:
report = await asyncio.to_thread(analyzer.analyze, analyzer_config, on_step=_step)
+ # Carry resolved coverage onto the report so the persister can write
+ # the coverage_files table alongside the health metrics.
+ if coverage_files:
+ report.coverage_files = coverage_files
+ report.coverage_format = coverage_format
+
if progress:
findings_count = len(report.findings)
avg = report.kpis.get("average_health", 10.0)
diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.py
new file mode 100644
index 000000000..a97f0068c
--- /dev/null
+++ b/tests/unit/health/test_coverage_discovery.py
@@ -0,0 +1,188 @@
+"""Tests for coverage artifact discovery + report-path resolution.
+
+The resolver is the make-or-break piece: real reports almost never store
+repowise's canonical repo-relative POSIX key, so we must reconcile absolute
+/ build-relative paths back to the indexed tree without per-report config.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.health.coverage import (
+ CoverageConfig,
+ build_coverage_map,
+ discover_artifacts,
+ normalize_report_path,
+ resolve_reports,
+)
+from repowise.core.analysis.health.coverage.model import CoverageReport, FileCoverage
+
+
+def _fc(path: str, pct: float = 50.0, covered: list[int] | None = None) -> FileCoverage:
+ covered = covered if covered is not None else [1, 2]
+ return FileCoverage(
+ file_path=path,
+ line_coverage_pct=pct,
+ branch_coverage_pct=None,
+ covered_lines=covered,
+ total_coverable_lines=4,
+ )
+
+
+def _report(files: list[FileCoverage], fmt: str = "lcov") -> CoverageReport:
+ return CoverageReport(source_format=fmt, files=files)
+
+
+# ---------------------------------------------------------------------------
+# normalize_report_path
+# ---------------------------------------------------------------------------
+
+
+def test_normalize_strips_drive_and_leading_dot_slash() -> None:
+ assert normalize_report_path("C:\\repo\\src\\a.rs") == "repo/src/a.rs"
+ assert normalize_report_path("./src/a.ts") == "src/a.ts"
+ assert normalize_report_path("/abs/src/a.py") == "abs/src/a.py"
+
+
+def test_normalize_applies_strip_and_path_prefix() -> None:
+ assert normalize_report_path("build/src/a.ts", strip_prefix="build") == "src/a.ts"
+ assert normalize_report_path("a.ts", path_prefix="packages/web") == "packages/web/a.ts"
+
+
+# ---------------------------------------------------------------------------
+# resolve_reports — the core matching logic
+# ---------------------------------------------------------------------------
+
+
+def test_exact_match() -> None:
+ keys = {"rust/src/tts/voices.rs", "rust/src/lib.rs"}
+ res = resolve_reports([_report([_fc("rust/src/tts/voices.rs")])], keys)
+ assert res.matched_exact == 1
+ assert res.matched_suffix == 0
+ assert "rust/src/tts/voices.rs" in res.coverage_map
+ assert not res.unmatched
+
+
+def test_absolute_path_resolves_via_suffix() -> None:
+ # cargo-llvm-cov emits absolute build paths; we must map them home.
+ keys = {"rust/src/tts/voices.rs", "rust/src/lib.rs"}
+ report = _report([_fc("/home/ci/work/myproj/rust/src/tts/voices.rs")])
+ res = resolve_reports([report], keys)
+ assert res.matched_suffix == 1
+ assert "rust/src/tts/voices.rs" in res.coverage_map
+ assert not res.unmatched
+
+
+def test_ambiguous_basename_disambiguated_by_overlap() -> None:
+ keys = {"rust/src/tts/mod.rs", "rust/src/transcribe/mod.rs"}
+ report = _report([_fc("/abs/rust/src/transcribe/mod.rs")])
+ res = resolve_reports([report], keys)
+ assert res.matched_suffix == 1
+ assert "rust/src/transcribe/mod.rs" in res.coverage_map
+ assert "rust/src/tts/mod.rs" not in res.coverage_map
+
+
+def test_truly_ambiguous_is_refused_not_guessed() -> None:
+ # Same basename, identical trailing overlap depth -> we refuse to guess.
+ keys = {"a/mod.rs", "b/mod.rs"}
+ report = _report([_fc("mod.rs")])
+ res = resolve_reports([report], keys)
+ assert res.coverage_map == {}
+ assert res.ambiguous == ["mod.rs"]
+
+
+def test_unmatched_reported_not_silently_dropped() -> None:
+ keys = {"src/a.ts"}
+ report = _report([_fc("src/gone.ts")])
+ res = resolve_reports([report], keys)
+ assert res.unmatched == ["src/gone.ts"]
+ assert res.matched == 0
+
+
+def test_hit_wins_merge_across_reports() -> None:
+ keys = {"src/a.ts"}
+ r1 = _report([_fc("src/a.ts", covered=[1, 2])])
+ r2 = _report([_fc("src/a.ts", covered=[2, 3])])
+ res = resolve_reports([r1, r2], keys)
+ entry = res.coverage_map["src/a.ts"]
+ assert entry["covered_lines"] == [1, 2, 3]
+
+
+def test_strip_prefix_upgrades_suffix_to_exact() -> None:
+ keys = {"src/a.ts"}
+ report = _report([_fc("build/src/a.ts")])
+ bare = resolve_reports([report], keys)
+ assert bare.matched_suffix == 1 # resolves, but only by suffix
+ fixed = resolve_reports([report], keys, strip_prefix="build")
+ assert fixed.matched_exact == 1 # now an exact key match
+
+
+def test_path_prefix_resolves_bare_basename_ambiguity() -> None:
+ # A bare basename ties across packages; path_prefix pins the package.
+ keys = {"web/a.ts", "api/a.ts"}
+ report = _report([_fc("a.ts")])
+ bare = resolve_reports([report], keys)
+ assert bare.ambiguous == ["a.ts"]
+ fixed = resolve_reports([report], keys, path_prefix="web")
+ assert fixed.matched_exact == 1
+ assert "web/a.ts" in fixed.coverage_map
+
+
+# ---------------------------------------------------------------------------
+# discover_artifacts
+# ---------------------------------------------------------------------------
+
+
+def test_discover_finds_common_locations(tmp_path: Path) -> None:
+ (tmp_path / "coverage").mkdir()
+ (tmp_path / "coverage" / "lcov.info").write_text("SF:a\nend_of_record\n")
+ (tmp_path / "node_modules" / "pkg").mkdir(parents=True)
+ (tmp_path / "node_modules" / "pkg" / "clover.xml").write_text("<coverage/>")
+
+ found = discover_artifacts(tmp_path)
+ names = {p.name for p in found}
+ assert "lcov.info" in names
+ # node_modules is pruned.
+ assert all("node_modules" not in p.parts for p in found)
+
+
+def test_build_coverage_map_end_to_end(tmp_path: Path) -> None:
+ lcov = "SF:/ci/build/src/a.ts\nDA:1,1\nDA:2,0\nend_of_record\n"
+ report_path = tmp_path / "coverage" / "lcov.info"
+ report_path.parent.mkdir()
+ report_path.write_text(lcov)
+
+ keys = {"src/a.ts"}
+ resolved, errors = build_coverage_map(tmp_path, [report_path], keys)
+ assert not errors
+ assert "src/a.ts" in resolved.coverage_map
+ assert resolved.coverage_map["src/a.ts"]["line_coverage_pct"] == 50.0
+
+
+# ---------------------------------------------------------------------------
+# CoverageConfig
+# ---------------------------------------------------------------------------
+
+
+def test_coverage_config_defaults() -> None:
+ cfg = CoverageConfig.from_repo_config(None)
+ assert cfg.auto_discover is True
+ assert cfg.paths == ()
+
+
+def test_coverage_config_parses_block() -> None:
+ cfg = CoverageConfig.from_repo_config(
+ {
+ "coverage": {
+ "auto_discover": False,
+ "paths": "coverage/lcov.info",
+ "strip_prefix": "build",
+ "reingest_on_update": True,
+ }
+ }
+ )
+ assert cfg.auto_discover is False
+ assert cfg.paths == ("coverage/lcov.info",)
+ assert cfg.strip_prefix == "build"
+ assert cfg.reingest_on_update is True
diff --git a/tests/unit/health/test_rust_inline_tests.py b/tests/unit/health/test_rust_inline_tests.py
new file mode 100644
index 000000000..1a2ed4569
--- /dev/null
+++ b/tests/unit/health/test_rust_inline_tests.py
@@ -0,0 +1,53 @@
+"""Rust inline ``#[cfg(test)]`` detection feeds ``has_test_file``.
+
+Idiomatic Rust unit tests live in a ``#[cfg(test)] mod tests`` block inside
+the source file, invisible to the filename/dir test-pairing heuristic. The
+walker flags these so well-tested Rust files aren't reported as untested.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.complexity.walker import _detect_inline_tests, walk_file
+
+RUST_WITH_INLINE_TESTS = b"""
+pub fn add(a: i32, b: i32) -> i32 {
+ a + b
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn it_adds() {
+ assert_eq!(add(2, 2), 4);
+ }
+}
+"""
+
+RUST_NO_TESTS = b"""
+pub fn add(a: i32, b: i32) -> i32 {
+ a + b
+}
+"""
+
+
+def test_detect_inline_tests_true_for_rust_with_cfg_test() -> None:
+ assert _detect_inline_tests(RUST_WITH_INLINE_TESTS, "rust") is True
+
+
+def test_detect_inline_tests_false_for_rust_without_tests() -> None:
+ assert _detect_inline_tests(RUST_NO_TESTS, "rust") is False
+
+
+def test_detect_inline_tests_false_for_non_rust() -> None:
+ # The same bytes in another language must not trip the Rust-only scan.
+ assert _detect_inline_tests(RUST_WITH_INLINE_TESTS, "python") is False
+
+
+def test_walk_file_sets_has_inline_tests() -> None:
+ fcx = walk_file("src/lib.rs", "rust", RUST_WITH_INLINE_TESTS)
+ assert fcx.has_inline_tests is True
+
+ fcx_no = walk_file("src/lib.rs", "rust", RUST_NO_TESTS)
+ assert fcx_no.has_inline_tests is False
diff --git a/tests/unit/pipeline/test_coverage_ingestion.py b/tests/unit/pipeline/test_coverage_ingestion.py
new file mode 100644
index 000000000..5c9a0428a
--- /dev/null
+++ b/tests/unit/pipeline/test_coverage_ingestion.py
@@ -0,0 +1,94 @@
+"""Pipeline-side coverage ingestion: discovery + resolution into coverage_map.
+
+Covers ``_build_pipeline_coverage``, the bridge that makes ``repowise init``
+auto-pick-up a coverage report and resolve its paths to canonical repo keys
+so health biomarkers see real coverage.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from repowise.core.pipeline.phases.analysis import _build_pipeline_coverage
+
+
+def _parsed(path: str) -> SimpleNamespace:
+ """Minimal stand-in for a ParsedFile (only file_info.path is read)."""
+ return SimpleNamespace(file_info=SimpleNamespace(path=path))
+
+
+def test_autodiscovers_and_resolves_absolute_lcov(tmp_path: Path) -> None:
+ # cargo-llvm-cov-style absolute SF paths under a build dir.
+ lcov = (
+ "SF:/ci/build/rust/src/tts/voices.rs\n"
+ "DA:1,1\nDA:2,1\nDA:3,0\nend_of_record\n"
+ )
+ (tmp_path / "coverage").mkdir()
+ (tmp_path / "coverage" / "lcov.info").write_text(lcov)
+
+ parsed = [_parsed("rust/src/tts/voices.rs"), _parsed("rust/src/lib.rs")]
+ coverage_map, files, fmt = _build_pipeline_coverage(
+ tmp_path, parsed, None, progress=None
+ )
+
+ assert fmt == "lcov"
+ assert "rust/src/tts/voices.rs" in coverage_map
+ assert coverage_map["rust/src/tts/voices.rs"]["line_coverage_pct"] > 0
+ # Persisted rows carry the canonical key, not the absolute report path.
+ assert {f.file_path for f in files} == {"rust/src/tts/voices.rs"}
+
+
+def test_explicit_paths_take_priority(tmp_path: Path) -> None:
+ report = tmp_path / "custom.lcov"
+ report.write_text("SF:src/a.ts\nDA:1,1\nend_of_record\n")
+ parsed = [_parsed("src/a.ts")]
+
+ coverage_map, _files, _fmt = _build_pipeline_coverage(
+ tmp_path, parsed, [report], progress=None
+ )
+ assert "src/a.ts" in coverage_map
+
+
+def test_no_report_yields_empty_map(tmp_path: Path) -> None:
+ parsed = [_parsed("src/a.ts")]
+ coverage_map, files, fmt = _build_pipeline_coverage(
+ tmp_path, parsed, None, progress=None
+ )
+ assert coverage_map == {}
+ assert files == []
+ assert fmt is None
+
+
+def test_auto_discover_disabled_via_config(tmp_path: Path) -> None:
+ (tmp_path / "coverage").mkdir()
+ (tmp_path / "coverage" / "lcov.info").write_text("SF:src/a.ts\nDA:1,1\nend_of_record\n")
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "coverage:\n auto_discover: false\n"
+ )
+ parsed = [_parsed("src/a.ts")]
+
+ coverage_map, _files, _fmt = _build_pipeline_coverage(
+ tmp_path, parsed, None, progress=None
+ )
+ assert coverage_map == {}
+
+
+def test_strip_prefix_from_config(tmp_path: Path) -> None:
+ # Two same-named files force ambiguity that strip_prefix resolves.
+ (tmp_path / "coverage").mkdir()
+ (tmp_path / "coverage" / "lcov.info").write_text(
+ "SF:dist/web/index.ts\nDA:1,1\nend_of_record\n"
+ )
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "coverage:\n strip_prefix: dist\n"
+ )
+ parsed = [_parsed("web/index.ts"), _parsed("api/index.ts")]
+
+ coverage_map, _files, _fmt = _build_pipeline_coverage(
+ tmp_path, parsed, None, progress=None
+ )
+ assert "web/index.ts" in coverage_map
+ assert "api/index.ts" not in coverage_map