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
fix(coverage): store nothing from a mostly unmapped report unless --allow-partial, and suggest the prefix (#4323)
Raghav Chamadiyade2d73f57ebc
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 62e550428..5bd6ecad6 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1408,8 +1408,15 @@ repowise coverage suggest-gates # propose path-scoped gates for coverage| `--path` | Repo path (defaults to cwd / workspace primary) || `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` || `--strict` | Also exit non-zero when some report files did not map to the repo tree |+| `--allow-partial` | Store the coverage even when more than half the report did not map to the repo tree; the rows are flagged partial || `--verbose` / `-v` | Show debug logs while discovering and ingesting coverage |+When more than half the report did not map to the repo tree, `add` stores+nothing, exits `1`, and suggests the `coverage.strip_prefix` or+`coverage.path_prefix` that would map it. `init` and `update` keep no coverage+from such a report either, so an `update` that re-reads it clears a fragment+stored with `--allow-partial`.+Each `PATH` is a report path or a quoted glob, relative to cwd, as in`coverage check --report`; only when it matches nothing is it read as`PATH=PREFIX`, prepending `PREFIX` to the paths inside the report (likediff --git a/docs/start/CI.md b/docs/start/CI.mdindex 643ebc721..2b4e61fce 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -390,7 +390,9 @@ Several reports merge: a line any of them ran counts as run. A coverage.pydo not line up with the repository (a build directory, a container path), set`coverage.strip_prefix` or `coverage.path_prefix` in `.repowise/config.yaml`.The gate reports how many report paths matched the repository, and exits `2`-when none did, so a wrong prefix never passes as zero.+when none did, so a wrong prefix never passes as zero. When more than half did+not match, it suggests the prefix to set; `repowise coverage add` then stores+nothing unless `--allow-partial` is passed.The threshold can live in config instead of the workflow:diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex 2e985a547..b40d1c7eb 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -504,6 +504,8 @@ class _Reports:path_prefix=self.cfg.path_prefix,report_prefixes=self.prefixes,ignore=self.cfg.ignore,+ # The check stores nothing, so a fragment is judged, flagged partial.+ allow_partial=True,)@@ -537,9 +539,12 @@ def _resolve_reports(reports: _Reports, notices, keys=None, side: str = ""):"carry a build prefix, set coverage.strip_prefix in .repowise/config.yaml.")if resolved.mapping_partial:+ from repowise.core.analysis.health.coverage import prefix_hint++ hint = prefix_hint(resolved.suggested_prefixes)notices.print("[yellow]More than half the report paths did not match a file in this "- "repository; check coverage.strip_prefix / coverage.path_prefix.[/yellow]"+ f"repository; {escape(hint)}.[/yellow]")return resolveddiff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex d0770f99f..9610014c6 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -13,6 +13,7 @@ from __future__ import annotationsfrom pathlib import Pathimport click+from rich.markup import escapefrom repowise.cli._setup import configure_cli_loggingfrom repowise.cli.commands.coverage_check_cmd import coverage_check@@ -86,6 +87,13 @@ coverage_group.add_command(coverage_suggest_gates)default=False,help="Also fail when some report files did not map to the repo tree.",)+ "--allow-partial",+ is_flag=True,+ default=False,+ help="Store the coverage even when more than half the report did not map to the "+ "repo tree (flagged partial).",+)@click.option("--verbose","-v",@@ -98,6 +106,7 @@ def coverage_add(repo: str | None,coverage_format: str | None,strict: bool,+ allow_partial: bool,verbose: bool,) -> None:"""Ingest coverage (auto-discovers reports when none are given).@@ -129,8 +138,10 @@ def coverage_add(repowise coverage add web/coverage/lcov.info=webExits non-zero when nothing was stored, so `coverage add ... || exit 1`- tells a complete ingest from a no-op. With --strict it also exits- non-zero when some report files did not map to the repo tree.+ tells a complete ingest from a no-op. When more than half the report did+ not map to the repo tree it stores nothing and suggests a strip_prefix /+ path_prefix, unless --allow-partial. With --strict it also exits non-zero+ when some report files did not map to the repo tree."""configure_cli_logging(verbose=verbose)@@ -143,7 +154,9 @@ def coverage_add(discover_artifacts,expand_report_args,parse_contexts_file,+ prefix_hint,resolve_test_reports,+ suggest_prefixes,)from repowise.core.repo_config import load_repo_config@@ -219,9 +232,6 @@ def coverage_add()# --- Per-file aggregate coverage (any format in COVERAGE_PARSERS).- agg_matched = 0- unmapped = 0- mapping_partial = False# The same read init runs; a ``.coverage`` comes back in *errors*# with why it has no per-file coverage, then feeds the map below.resolved, errors = build_coverage_map(@@ -233,6 +243,7 @@ def coverage_add(path_prefix=cfg.path_prefix,report_prefixes=report_prefixes,ignore=cfg.ignore,+ allow_partial=allow_partial,)for path, err in errors:console.print(f"[yellow] {path.name}: {err}[/yellow]")@@ -242,40 +253,12 @@ def coverage_add(# for the one run where every single one of them was.skipped = resolved.unmatched + resolved.ambiguousunmapped = len(skipped)- mapping_partial = resolved.mapping_partial- 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,- provenance=resolved.provenance,- )- 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)."- )- 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})."- )- if mapping_partial:- console.print(- "[red]More than half the report did not map to the repo "- "tree.[/red] The stored coverage describes only a fragment "- "of the repository. Fix [cyan]coverage.strip_prefix[/cyan] "- "or [cyan]coverage.path_prefix[/cyan] in "- ".repowise/config.yaml and re-run."- )# --- Per-test map, from any report that carries contexts.map_records: list = []map_format: str | None = Nonemap_readable = False+ map_skipped: list[str] = []for report_path in report_paths:creport = parse_contexts_file(report_path)if not creport.has_contexts:@@ -297,8 +280,52 @@ def coverage_add(path_prefix=report_prefixes.get(report_path) or cfg.path_prefix,ignore=cfg.ignore,)+ if rtc.mapping_partial:+ map_skipped.extend(rtc.unmatched + rtc.ambiguous)map_records.extend(rtc.records)map_format = map_format or creport.source_format++ # A fragment is stored only with --allow-partial: of the per-file+ # coverage or of the map, either one withholds both.+ partial = resolved.mapping_partial or bool(map_skipped)+ if partial and not allow_partial:+ suggested = (+ resolved.suggested_prefixes+ if resolved.mapping_partial+ else suggest_prefixes(+ map_skipped, repo_keys, mapped={r.file_path for r in map_records}+ )+ )+ hint = prefix_hint(suggested)+ part = "report" if resolved.mapping_partial else "per-test map"+ console.print(+ f"[red]More than half the {part} did not map to the repo tree, so "+ f"nothing was stored.[/red] To fix it, {escape(hint)} and re-run, "+ "or pass [cyan]--allow-partial[/cyan] to store the fragment."+ )+ return False++ agg_matched = 0+ 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,+ provenance=resolved.provenance,+ )+ 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)."+ )+ 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. {escape(sample)})."+ )if map_records:written = await save_test_coverage(session,@@ -317,6 +344,12 @@ def coverage_add(f"[green]Built the test-to-code map: {written} test->file "f"record(s).[/green]{extra}")+ if partial:+ console.print(+ "[yellow]Stored a fragment (--allow-partial): more than half the "+ "report did not map to the repo tree, and the stored coverage is "+ "flagged partial.[/yellow]"+ )if not agg_matched and not map_records:if len(errors) == len(report_paths) and not map_readable:@@ -334,16 +367,6 @@ def coverage_add(f"[red]--strict: {unmapped} report file(s) did not map to the repo tree.[/red]")return False- if mapping_partial:- console.print(- "[red]Coverage ingest was partial: more than half the report did "- "not map to the repo tree.[/red] The stored numbers describe only "- "the mapped fragment, not the repository. Fix "- "[cyan]coverage.strip_prefix[/cyan] / [cyan]coverage.path_prefix[/cyan] "- "in .repowise/config.yaml and re-run. This run exits non-zero so "- "scripts cannot mistake a fragment for complete coverage."- )- return Falseconsole.print("Run [cyan]repowise health --recompute[/cyan] to fold coverage into the defect ""scores, or [cyan]repowise coverage status[/cyan] to review it."diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.pyindex 12d28f047..e06e6a62c 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py@@ -31,8 +31,10 @@ from .discovery import (expand_report_args,expand_report_patterns,normalize_report_path,+ prefix_hint,resolve_reports,resolve_test_reports,+ suggest_prefixes,)from .freshness import FreshnessStatus, coverage_freshnessfrom .goprofile import parse_go_coverprofile@@ -86,6 +88,8 @@ __all__ = ["parse_lcov","parse_lcov_contexts","parse_repowise_json",+ "prefix_hint","resolve_reports","resolve_test_reports",+ "suggest_prefixes",]diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.pyindex 0c54310e9..44fabc709 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py@@ -23,7 +23,7 @@ Two jobs that make ingested coverage *actually line up* with the repo:from __future__ import annotations-from collections import defaultdict+from collections import Counter, defaultdictfrom collections.abc import Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom itertools import chain@@ -420,6 +420,11 @@ class ResolvedCoverage:# applied: with ``mapping_partial``, what makes two measurements comparable.report_formats: list[str] = field(default_factory=list)ignore: tuple[str, ...] = ()+ # A partial mapping :func:`build_coverage_map` was not allowed to keep:+ # ``files`` and ``coverage_map`` are empty, the diagnostics stay.+ withheld: bool = False+ # With ``mapping_partial``, the :func:`suggest_prefixes` answer (``None``: abstained).+ suggested_prefixes: tuple[str, str] | None = None@propertydef matched(self) -> int:@@ -998,9 +1003,11 @@ def resolve_reports(# (issue #1746), and it deliberately avoids a hard ratio on the matched# side so monorepos ingesting one package's report stay unflagged.# Ignored entries were dropped on purpose, so they count on neither side.- measured_count = report_file_count - result.ignored- if measured_count:- result.mapping_partial = result.matched * 2 < measured_count+ result.mapping_partial = mostly_unmapped(result.matched, report_file_count - result.ignored)+ if result.mapping_partial:+ result.suggested_prefixes = suggest_prefixes(+ result.unmatched + result.ambiguous, repo_keys, mapped=by_key+ )for key, fc in by_key.items():result.coverage_map[key] = coverage_map_entry(fc, result.source_format)@@ -1008,6 +1015,71 @@ def resolve_reports(return result+def mostly_unmapped(matched: int, measured: int) -> bool:+ """Whether fewer than half of *measured* report files mapped: the ingest is a fragment.++ A fragment is stored or scored only when the caller allows it+ (``coverage add --allow-partial``); every other reader drops it.+ """+ return bool(measured) and matched * 2 < measured+++#: Unmapped report paths :func:`suggest_prefixes` looks at; enough to vote, cheap to scan.+_SUGGEST_SAMPLE = 200+++def suggest_prefixes(+ unmapped: Sequence[str], repo_keys: set[str], mapped: Iterable[str] = ()+) -> tuple[str, str] | None:+ """The ``(strip_prefix, path_prefix)`` that maps most *unmapped* report paths onto *repo_keys*.++ Each path votes for every rewrite that turns it into an indexed key: drop+ the leading segments before its longest shared tail with a key, prepend+ that key's own leading segments. Either side may be ``""`` (nothing to+ set). A tie in votes goes to the rewrite whose ``path_prefix`` holds more+ of the *mapped* keys, the files the same report did resolve (a monorepo+ package's report whose shared file names tie between packages).+ ``None`` (abstain) unless one rewrite explains more than half the paths+ and no other ranks as high.+ """+ sample = list(dict.fromkeys(normalize_report_path(p) for p in unmapped[:_SUGGEST_SAMPLE]))+ suffix_index = _build_suffix_index(repo_keys)+ votes: Counter[tuple[str, str]] = Counter()+ for norm in sample:+ segs = norm.split("/")+ rewrites: set[tuple[str, str]] = set()+ for key in suffix_index.get(segs[-1], ()):+ key_segs = key.split("/")+ tail = _common_run(reversed(segs), reversed(key_segs))+ rewrites.add(("/".join(segs[:-tail]), "/".join(key_segs[:-tail])))+ rewrites.discard(("", ""))+ votes.update(rewrites)+ mapped = list(mapped)++ def rank(rewrite: tuple[str, str]) -> tuple[int, int]:+ prefix = rewrite[1] + "/"+ return votes[rewrite], sum(k.startswith(prefix) for k in mapped) if rewrite[1] else 0++ ranked = sorted(votes, key=rank, reverse=True)+ if not ranked or votes[ranked[0]] * 2 <= len(sample):+ return None+ if len(ranked) > 1 and rank(ranked[0]) == rank(ranked[1]):+ return None+ return ranked[0]+++def prefix_hint(suggested: tuple[str, str] | None) -> str:+ """What to change so a partial mapping maps, worded for every surface alike."""+ if suggested is None:+ return "fix coverage.strip_prefix or coverage.path_prefix in .repowise/config.yaml"+ named = [+ f"{name}: {value}"+ for name, value in zip(("coverage.strip_prefix", "coverage.path_prefix"), suggested, strict=True)+ if value+ ]+ return f"set {' and '.join(named)} in .repowise/config.yaml"++@dataclassclass ResolvedTestCoverage:"""Outcome of resolving a :class:`ContextCoverageReport` against the tree.@@ -1035,6 +1107,13 @@ class ResolvedTestCoverage:def matched(self) -> int:return self.matched_exact + self.matched_suffix+ @property+ def mapping_partial(self) -> bool:+ """:func:`mostly_unmapped` over distinct source files, as for the aggregate."""+ mapped = len({r.file_path for r in self.records})+ missed = len(set(self.unmatched)) + len(set(self.ambiguous))+ return mostly_unmapped(mapped, mapped + missed)+# Extensions that make a test-id prefix look like a real source path (rather# than a bare suite name), so we only try to resolve path-shaped ids.@@ -1125,6 +1204,7 @@ def build_coverage_map(path_prefix: str | None = None,report_prefixes: Mapping[Path, str | None] | None = None,ignore: Sequence[str] = (),+ allow_partial: bool = False,) -> tuple[ResolvedCoverage, list[tuple[Path, str]]]:"""Read + parse + resolve coverage reports end-to-end.@@ -1136,6 +1216,10 @@ def build_coverage_map(a ``coverage.paths`` mapping entry), overriding *path_prefix*. *ignore* is``coverage.ignore``. A Go coverprofile's import paths are mapped back tothe directories of the ``go.mod`` files on disk.++ A partial mapping (:func:`mostly_unmapped`) keeps no coverage unless+ *allow_partial*; it comes back ``withheld`` so nothing stores or scores a+ fragment as the repository's coverage."""prefixes = report_prefixes or {}parsed: list[CoverageReport] = []@@ -1172,6 +1256,8 @@ def build_coverage_map(else ()),)+ if resolved.mapping_partial and not allow_partial:+ resolved.coverage_map, resolved.files, resolved.withheld = {}, [], Truereturn resolved, errorsdiff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.pyindex 43035c3f9..7b461d06e 100644--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py@@ -192,6 +192,7 @@ def _build_pipeline_coverage(from repowise.core.analysis.health.coverage import (CoverageConfig,build_coverage_map,+ prefix_hint,)from repowise.core.repo_config import load_repo_config@@ -219,22 +220,24 @@ def _build_pipeline_coverage(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}",+ f"→ coverage: {0 if resolved.withheld else resolved.matched} files "+ f"matched from {names}{more}",)skipped = len(resolved.unmatched) + len(resolved.ambiguous)- if skipped:- sample = ", ".join((resolved.unmatched + resolved.ambiguous)[:3])+ sample = ", ".join((resolved.unmatched + resolved.ambiguous)[:3])+ if resolved.withheld: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.",+ f" ↳ {skipped} report file(s) did not map (e.g. {sample}), more "+ "than half the report, so no coverage was kept; "+ f"{prefix_hint(resolved.suggested_prefixes)}.",)- if resolved.mapping_partial:+ elif skipped:progress.on_message("warning",- " ↳ more than half the report did not map: the stored "- "coverage is a fragment, not the whole repository.",+ 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}")diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.pyindex d03852f23..fda6b327d 100644--- a/tests/unit/cli/test_coverage_cmd.py+++ b/tests/unit/cli/test_coverage_cmd.py@@ -400,3 +400,66 @@ def test_coverage_add_dot_coverage_without_contexts_stores_nothing(assert "Nothing was stored." in output# The paths were never the problem, so no prefix advice.assert "strip_prefix" not in output+++_MONOREPO_KEYS = {"web/src/a.py", "api/src/a.py", "web/src/b.py", "api/src/b.py", "web/src/c.py"}+++def _package_report(tmp_path) -> None:+ """A web package's lcov, paths from the package root: two tie, one maps."""+ (tmp_path / "lcov.info").write_text(+ "".join(f"SF:src/{n}.py\nDA:1,1\nend_of_record\n" for n in "abc"), encoding="utf-8"+ )+++def test_coverage_add_stores_nothing_from_a_partial_mapping_and_suggests_a_prefix(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ stored = _fake_ingest(monkeypatch, tmp_path, _MONOREPO_KEYS)+ _package_report(tmp_path)++ result = CliRunner().invoke(cli, ["coverage", "add", "lcov.info"])++ output = " ".join(result.output.split())+ assert result.exit_code == 1, result.output+ assert stored == []+ assert "nothing was stored" in output+ assert "set coverage.path_prefix: web in .repowise/config.yaml" in output+ assert "--allow-partial" in output+++def test_coverage_add_allow_partial_stores_the_flagged_fragment(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ stored = _fake_ingest(monkeypatch, tmp_path, _MONOREPO_KEYS)+ _package_report(tmp_path)++ result = CliRunner().invoke(cli, ["coverage", "add", "lcov.info", "--allow-partial"])++ assert result.exit_code == 0, result.output+ assert [f.file_path for f in stored] == ["web/src/c.py"]+ assert "flagged partial" in " ".join(result.output.split())+++def test_coverage_add_withholds_a_partial_per_test_map(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ _fake_ingest(monkeypatch, tmp_path, {"src/a.py"})+ mapped: list = []++ async def _save_map(session, repository_id, records, **kwargs):+ mapped.extend(records)+ return len(records)++ monkeypatch.setattr("repowise.core.persistence.crud.save_test_coverage", _save_map)+ coverage = pytest.importorskip("coverage")+ data = coverage.CoverageData(basename=str(tmp_path / ".coverage"))+ data.set_context("tests/test_a.py::test_one|run")+ data.add_lines({str(tmp_path / n): [1] for n in ("src/a.py", "gone/b.py", "gone/c.py")})+ data.write()++ result = CliRunner().invoke(cli, ["coverage", "add", ".coverage"])++ assert result.exit_code == 1, result.output+ assert mapped == []+ assert "More than half the per-test map did not map" in " ".join(result.output.split())diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.pyindex 9556d7fb0..eec0129a7 100644--- a/tests/unit/cli/test_update_persist_reliability.py+++ b/tests/unit/cli/test_update_persist_reliability.py@@ -12,6 +12,7 @@ import asynciofrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetimefrom pathlib import Path+from types import SimpleNamespaceimport pytestfrom sqlalchemy import select@@ -279,34 +280,42 @@ def test_reingest_with_nothing_to_read_keeps_stored_coverage(tmp_path: Path, mondef test_reingest_carries_the_ingest_provenance(tmp_path: Path, monkeypatch) -> None:- # A fragment re-ingested on update must be stored as a fragment, with its counts.+ # A re-ingest stores its report's counts beside the rows.from repowise.cli.commands.update_cmd import persistence- from repowise.core.analysis.health.coverage import FileCoverage, ResolvedCoveragemonkeypatch.setattr("repowise.core.repo_config.load_repo_config",lambda _path: {"coverage": {"reingest_on_update": True, "paths": ["c.lcov"]}},)- (tmp_path / "c.lcov").write_text("SF:a.py\nDA:1,1\nend_of_record\n", encoding="utf-8")- resolved = ResolvedCoverage(- coverage_map={"a.py": {}},- files=[FileCoverage("a.py", 100.0, None, [1], 1, [1])],- source_format="lcov",- source_formats=["lcov"],- matched_exact=1,- unmatched=["x/b.py", "x/c.py"],- mapping_partial=True,- )+ _write_lcov(tmp_path / "c.lcov", "a.py", "b.py", "x/c.py")+ parsed = [SimpleNamespace(file_info=SimpleNamespace(path=k)) for k in ("a.py", "b.py")]++ coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, parsed))+ assert coverage.authoritative is True+ assert coverage.provenance.mapping_partial is False+ assert coverage.provenance.report_path_count == 3+ assert coverage.provenance.unmatched_sample == ("x/c.py",)+++def test_reingest_keeps_nothing_from_a_partial_mapping(tmp_path: Path, monkeypatch) -> None:+ # Re-reading a fragment on update clears the coverage, as a fresh index would.+ from repowise.cli.commands.update_cmd import persistence+monkeypatch.setattr(- "repowise.core.analysis.health.coverage.build_coverage_map",- lambda *_a, **_k: (resolved, []),+ "repowise.core.repo_config.load_repo_config",+ lambda _path: {"coverage": {"reingest_on_update": True, "paths": ["c.lcov"]}},)+ _write_lcov(tmp_path / "c.lcov", "a.py", "x/b.py", "x/c.py")+ parsed = [SimpleNamespace(file_info=SimpleNamespace(path="a.py"))]- coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, []))+ coverage = asyncio.run(persistence._coverage_for_rescore(object(), "repo", tmp_path, parsed))assert coverage.authoritative is True- assert coverage.provenance.mapping_partial is True- assert coverage.provenance.report_path_count == 3- assert coverage.provenance.unmatched_sample == ("x/b.py", "x/c.py")+ assert coverage.files == []+ assert coverage.coverage_map == {}+++def _write_lcov(path: Path, *sources: str) -> None:+ path.write_text("".join(f"SF:{s}\nDA:1,1\nend_of_record\n" for s in sources), encoding="utf-8")# ---------------------------------------------------------------------------diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.pyindex 3aac23fca..8d2736312 100644--- a/tests/unit/health/test_coverage_discovery.py+++ b/tests/unit/health/test_coverage_discovery.py@@ -17,7 +17,9 @@ from repowise.core.analysis.health.coverage import (discover_artifacts,expand_report_patterns,normalize_report_path,+ prefix_hint,resolve_reports,+ suggest_prefixes,)from repowise.core.analysis.health.coverage.model import CoverageReport, FileCoverage@@ -315,6 +317,41 @@ def test_build_coverage_map_flags_partial(tmp_path: Path) -> None:resolved, errors = build_coverage_map(tmp_path, [report_path], keys)assert not errorsassert resolved.mapping_partial is True+ # A fragment is withheld: nothing to store or score, diagnostics kept.+ assert resolved.withheld is True+ assert resolved.files == [] and resolved.coverage_map == {}+ assert len(resolved.unmatched) == 2++ kept, _ = build_coverage_map(tmp_path, [report_path], keys, allow_partial=True)+ assert kept.mapping_partial is True and kept.withheld is False+ assert [f.file_path for f in kept.files] == ["src/a.ts"]+++def test_partial_mapping_suggests_the_package_the_mapped_files_live_in() -> None:+ # A package's report names its files from the package root; two names tie+ # between packages and the third resolves, which settles the prefix.+ keys = {"web/src/a.py", "api/src/a.py", "web/src/b.py", "api/src/b.py", "web/src/c.py"}+ report = _report([_fc("src/a.py"), _fc("src/b.py"), _fc("src/c.py")])+ res = resolve_reports([report], keys)+ assert res.mapping_partial is True+ assert res.suggested_prefixes == ("", "web")+ assert prefix_hint(res.suggested_prefixes) == (+ "set coverage.path_prefix: web in .repowise/config.yaml"+ )+++def test_suggest_prefixes_finds_a_build_prefix_to_strip() -> None:+ keys = {"a.py", "b.py", "docs/a.py"}+ assert suggest_prefixes(["/ci/build/a.py", "/ci/build/b.py"], keys) == ("ci/build", "")+++def test_suggest_prefixes_abstains_without_a_clear_winner() -> None:+ keys = {"web/a.py", "api/a.py", "x/b.py"}+ # Two rewrites explain the one path equally, and nothing mapped breaks the tie.+ assert suggest_prefixes(["a.py"], keys) is None+ # One rewrite explains only one of three paths.+ assert suggest_prefixes(["lib/b.py", "lib/q.py", "lib/r.py"], keys) is None+ assert prefix_hint(None).startswith("fix coverage.strip_prefix or coverage.path_prefix")# ---------------------------------------------------------------------------diff --git a/tests/unit/pipeline/test_coverage_ingestion.py b/tests/unit/pipeline/test_coverage_ingestion.pyindex bbbfd0f54..5981f33cb 100644--- a/tests/unit/pipeline/test_coverage_ingestion.py+++ b/tests/unit/pipeline/test_coverage_ingestion.py@@ -115,3 +115,23 @@ def test_dot_coverage_says_why_it_has_no_per_file_coverage(tmp_path: Path) -> Noassert coverage_map == {}assert files == []assert ("warning", f" ↳ coverage .coverage: {COVERAGE_DATA_FILE_NOTE}") in messages+++def test_a_partial_mapping_keeps_no_coverage_and_says_what_to_set(tmp_path: Path) -> None:+ report = tmp_path / "lcov.info"+ report.write_text(+ "".join(f"SF:src/{n}.py\nDA:1,1\nend_of_record\n" for n in "abc"), encoding="utf-8"+ )+ keys = ["web/src/a.py", "api/src/a.py", "web/src/b.py", "api/src/b.py", "web/src/c.py"]+ messages: list[tuple[str, str]] = []+ progress = SimpleNamespace(on_message=lambda level, msg: messages.append((level, msg)))++ coverage_map, files, _fmt, _provenance = _build_pipeline_coverage(+ tmp_path, [_parsed(k) for k in keys], [report], progress=progress+ )++ assert coverage_map == {}+ assert files == []+ assert any(+ "no coverage was kept; set coverage.path_prefix: web" in msg for _, msg in messages+ )