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.

fix(coverage): match report paths by directory, report location and source roots (#2637)

Raghav Chamadiya5eeffb9da736
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index fea1fcbf4..f321a8be3 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -659,7 +659,10 @@ change is never reported as untested: `status` becomes `inferred` when the
import graph can name test files reaching the change (candidates, file-level, no
line attribution, and `line_coverage` stays empty because reaching cannot speak
to lines), and `no_map` ("run the full suite") when it cannot. `basis` carries
-the same distinction in one word: `measured`, `inferred`, or absent. Build the
+the same distinction in one word, always present: `measured`, `inferred`, or
+`none`. `tests_to_run_kind` says what each entry is: `test_id` (a coverage-map
+test id, measured) or `test_file` (inferred), null when `basis` is `none`;
+`get_risk`'s directive carries the same field beside `tests_to_run_basis`. Build the
measured map with `coverage run --contexts=test` followed by
`repowise coverage add`.
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 54a6ec3a0..4a466c67d 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -161,7 +161,7 @@ cli/src/repowise/cli/commands/
server/src/repowise/server/
├── mcp_server/
│ ├── tool_health/ # @mcp.tool get_health(targets, include, repo, limit)
-│ ├── tool_risk.py # enriched: health_score, top_biomarkers, coverage_pct
+│ ├── tool_risk.py # enriched: health_score, top_biomarkers, line_coverage_pct
│ ├── tool_context.py # include=["health"]: score, top 2 biomarkers, suggestion
│ └── tool_overview.py # code_health block with KPIs
└── routers/
@@ -761,7 +761,7 @@ Defined in `tool_health/tool.py`, which dispatches to one module per mode and bl
### Enrichments on existing tools
- `get_risk(targets)`: each per-target row carries `health_score`,
- `top_biomarkers`, `coverage_pct`, `branch_coverage_pct`.
+ `top_biomarkers`, `line_coverage_pct`, `branch_coverage_pct`.
- `get_context(targets, include=["health"])`: per-file `score`,
`max_ccn`, `max_nesting`, `nloc`, `module`, `duplication_pct`, top
2 markers (each with a `suggestion` string), a coverage block, and a
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index add844721..b26ce8293 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -123,6 +123,18 @@ whether the measurement matches the indexed commit. Stored patch coverage
reads the same record, so its report path counts are real numbers rather than
null.
+A few rules keep that matching honest in monorepos and mixed layouts:
+
+- A match needs more than the basename when the report names a directory:
+ `other/pkg/utils.py` never maps to `src/utils.py`. A root-level file still
+ matches under an absolute path, because the whole key is the path's tail.
+- A relative path is first tried under the report's own directory and its
+ parents, nearest first, so `packages/web/coverage/lcov.info` naming
+ `src/index.ts` maps to `packages/web/src/index.ts`. A remaining tie prefers
+ the file nearest the report.
+- Cobertura paths are joined to each `<source>` root before matching, which
+ separates files that share a name under different packages.
+
## Building a per-test map
The map needs a report that records *which test* covered each line. Two paths
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index 0bb81f5fe..a19284129 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -231,7 +231,7 @@ def _render_card(name: str, card: dict) -> None:
# payload that no renderer prints is the second silent failure mode of a
# trim, and the one a projection test cannot see.
health = card.get("health_score")
- coverage = card.get("coverage_pct")
+ coverage = card.get("line_coverage_pct")
if health is not None or coverage is not None:
parts = []
if health is not None:
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 8b562bffd..3e0b79d1d 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -15,7 +15,7 @@ from pathlib import Path
from typing import Protocol
from ..change_risk.features import split_revspec
-from ..changed_lines import FileDiff, parse_unified_diff
+from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff
GIT_TIMEOUT_SECONDS = 120
@@ -190,6 +190,10 @@ class GitRevisionSource:
self.repo_path,
check=False,
).strip()
+ if not parent and is_shallow_root(self.repo_path, ref):
+ # A shallow boundary's parents are cut off, not absent; the empty
+ # tree would make every line of the snapshot read as changed.
+ raise ValueError(f"{ref!r} has no parent in this shallow clone; fetch more history")
base = parent or _EMPTY_TREE
return RevisionPair(
f"{ref}^" if parent else _EMPTY_TREE,
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index 006c479ca..dbf7f40e2 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -24,6 +24,7 @@ import re
import subprocess
from collections.abc import Iterable
from dataclasses import dataclass, field
+from pathlib import Path
from .change_risk.features import _git, split_revspec
@@ -213,7 +214,7 @@ def changed_lines(
return _parse_unified_diff(diff), label
_verify_ref(repo_path, revspec)
- if _is_shallow_root(repo_path, revspec):
+ if is_shallow_root(repo_path, revspec):
# A shallow clone's oldest commit has its parents cut off, so git would
# diff it against the empty tree and every line would read as changed.
raise ValueError(f"{revspec!r} has no parent in this shallow clone; fetch more history")
@@ -233,7 +234,15 @@ def _diff(repo_path: str, args: list[str]) -> str:
raise ValueError(detail[-1] if detail else f"git {args[0]} failed") from exc
-def _is_shallow_root(repo_path: str, rev: str) -> bool:
- if _git(["rev-parse", "--is-shallow-repository"], repo_path, check=False).strip() != "true":
+def is_shallow_root(repo_path: str, rev: str) -> bool:
+ """Whether *rev* is a boundary a shallow clone cut its parents from.
+
+ Read from git's own list of grafted commits, so a genuine root commit is
+ never mistaken for a cut one.
+ """
+ shallow = _git(["rev-parse", "--git-path", "shallow"], repo_path, check=False).strip()
+ path = Path(repo_path, shallow)
+ if not shallow or not path.is_file():
return False
- return not _git(["rev-parse", "--verify", "--quiet", f"{rev}^"], repo_path, check=False).strip()
+ sha = _git(["rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"], repo_path, check=False)
+ return bool(sha.strip()) and sha.strip() in path.read_text(encoding="utf-8").split()
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
index 98072f890..2d435139e 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
@@ -69,6 +69,10 @@ def parse_cobertura(text: str) -> CoverageReport:
bucket.branches_found += 2
bucket.branches_hit += 2 if hits > 0 else 0
+ # Filenames are relative to one of these; the resolver tries each.
+ roots = tuple(
+ dict.fromkeys(s.text.strip() for s in root.iter("source") if s.text and s.text.strip())
+ )
files = [
file_coverage(
path,
@@ -79,7 +83,7 @@ def parse_cobertura(text: str) -> CoverageReport:
)
for path, b in per_file.items()
]
- return CoverageReport(source_format="cobertura", files=files)
+ return CoverageReport(source_format="cobertura", files=files, source_roots=roots)
@dataclass
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index 3826ed1d8..b9b28094f 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -339,12 +339,23 @@ def _match_key(
norm_path: str,
repo_keys: set[str],
suffix_index: dict[str, list[str]],
+ *,
+ prefer_dir: str | None = None,
) -> 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).
+ trailing-segment overlap and *prefer_dir* (the report's own directory)
+ does not single one out: we refuse to guess.
+
+ A match must agree on more than the basename when the report names a
+ directory: ``other/pkg/utils.py`` is not ``src/utils.py``. It is accepted
+ when at least one directory also matches, or when the whole repo key is
+ the tail of the report path (a root-level file under an absolute path).
+ A path that runs through a dependency or environment directory
+ (``node_modules``, ``site-packages``) is someone else's file and never
+ matches by suffix.
"""
if norm_path in repo_keys:
return norm_path, False
@@ -353,28 +364,128 @@ def _match_key(
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
+ overlap = _agreed_overlap(report_segs, cand.split("/"))
+ if overlap is None:
+ continue
if overlap > best_overlap:
best_overlap = overlap
winners = [cand]
elif overlap == best_overlap:
winners.append(cand)
+ if len(winners) > 1 and prefer_dir:
+ winners = _nearest(winners, prefer_dir)
if len(winners) == 1:
return winners[0], False
- return None, True
+ return None, bool(winners)
+
+
+#: Directories whose files belong to a dependency or environment, not the repo.
+_VENDORED_DIRS = PRUNED_DIRS | frozenset({"site-packages", "dist-packages", "vendor"})
+
+
+def _common_run(a: Iterable[str], b: Iterable[str]) -> int:
+ """How many leading items *a* and *b* share."""
+ n = 0
+ for x, y in zip(a, b, strict=False):
+ if x != y:
+ break
+ n += 1
+ return n
+
+
+def _agreed_overlap(report_segs: list[str], cand_segs: list[str]) -> int | None:
+ """Trailing segments shared, or ``None`` when the match rests on too little.
+
+ See :func:`_match_key` for what counts as agreement.
+ """
+ overlap = _common_run(reversed(report_segs), reversed(cand_segs))
+ if not (overlap >= 2 or overlap == len(cand_segs) or len(report_segs) == 1):
+ return None
+ if _VENDORED_DIRS.intersection(report_segs[: len(report_segs) - overlap]):
+ return None
+ return overlap
+
+
+def _nearest(keys: list[str], directory: str) -> list[str]:
+ """The keys sharing the longest leading directory run with *directory*."""
+ dir_segs = directory.split("/")
+
+ def shared(key: str) -> int:
+ return _common_run(key.split("/")[:-1], dir_segs)
+
+ best = max(shared(k) for k in keys)
+ return [k for k in keys if shared(k) == best] if best else keys
+
+
+def _is_absolute(raw: str) -> bool:
+ p = raw.strip().replace("\\", "/")
+ return p.startswith("/") or (len(p) >= 2 and p[1] == ":")
+
+
+def _resolve_path(
+ raw: str,
+ report: CoverageReport,
+ repo_keys: set[str],
+ suffix_index: dict[str, list[str]],
+ *,
+ strip_prefix: str | None,
+ path_prefix: str | None,
+) -> tuple[str | None, bool, bool]:
+ """``(key, ambiguous, exact)`` for one report path.
+
+ Tried in order: the path joined to each Cobertura ``<source>`` root, the
+ report's own statement of where its paths live (roots that disagree are
+ ambiguous); then a relative path under the report's own directory and its
+ parents, nearest first, since runners write paths relative to the package
+ they ran in (a monorepo's ``packages/web/coverage/lcov.info`` naming
+ ``src/index.ts``); then the path as written. Ties prefer the report's own
+ directory. A configured *path_prefix* already says where the paths live,
+ so it skips the report-directory step.
+ """
+ norm = normalize_report_path(raw, strip_prefix=strip_prefix, path_prefix=path_prefix)
+ origin = report.origin_dir
+ relative = not _is_absolute(raw)
+ if relative and report.source_roots:
+ found: dict[str, bool] = {} # key -> matched a path exactly
+ for root in report.source_roots:
+ joined = normalize_report_path(
+ f"{root.rstrip('/')}/{raw}", strip_prefix=strip_prefix, path_prefix=path_prefix
+ )
+ key, _ = _match_key(joined, repo_keys, suffix_index, prefer_dir=origin)
+ if key is not None:
+ found[key] = found.get(key, False) or key in (joined, norm)
+ if found:
+ return _one_root(found)
+ if origin and relative and not path_prefix:
+ key = _under_origin(norm, origin, repo_keys)
+ if key is not None:
+ return key, False, True
+ key, ambiguous = _match_key(norm, repo_keys, suffix_index, prefer_dir=origin)
+ return key, ambiguous, key is not None and norm == key
+
+
+def _one_root(found: dict[str, bool]) -> tuple[str | None, bool, bool]:
+ """The source-root step's answer: one key, or ambiguous when roots disagree."""
+ if len(found) > 1:
+ return None, True, False
+ key, exact = next(iter(found.items()))
+ return key, False, exact
+
+
+def _under_origin(norm: str, origin: str, repo_keys: set[str]) -> str | None:
+ """*norm* under the report's directory or its nearest parent that has it."""
+ segs = origin.split("/")
+ for depth in range(len(segs), 0, -1):
+ candidate = "/".join([*segs[:depth], norm])
+ if candidate in repo_keys:
+ return candidate
+ return None
def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:
@@ -424,17 +535,21 @@ def resolve_reports(
result.source_formats.append(report.source_format)
for fc in report.files:
report_file_count += 1
- norm = normalize_report_path(
- fc.file_path, strip_prefix=strip_prefix, path_prefix=path_prefix
+ key, ambiguous, exact = _resolve_path(
+ fc.file_path,
+ report,
+ repo_keys,
+ suffix_index,
+ 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:
+ if exact:
result.matched_exact += 1
else:
result.matched_suffix += 1
@@ -597,8 +712,18 @@ def build_coverage_map(
if not report.files:
errors.append((path, f"no coverage entries (detected={report.source_format})"))
continue
+ report.origin_dir = _repo_relative_dir(path, repo_root)
parsed.append(report)
resolved = resolve_reports(
parsed, repo_keys, strip_prefix=strip_prefix, path_prefix=path_prefix
)
return resolved, errors
+
+
+def _repo_relative_dir(path: Path, repo_root: Path) -> str | None:
+ """*path*'s directory relative to *repo_root* (POSIX), ``None`` outside it or at its root."""
+ try:
+ rel = path.resolve().parent.relative_to(repo_root.resolve()).as_posix()
+ except (OSError, ValueError):
+ return None
+ return rel if rel not in ("", ".") else None
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.py
index 16f146d13..bb1a85663 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py
@@ -106,6 +106,12 @@ class CoverageReport:
source_format: str
files: list[FileCoverage] = field(default_factory=list)
commit_sha: str | None = None
+ # Directories the report's paths are relative to, as the report names
+ # them (Cobertura ``<source>``). Empty for formats that do not say.
+ source_roots: tuple[str, ...] = ()
+ # Repo-relative directory of the report file itself, set by whoever read
+ # it from disk; ``None`` when the report did not come from inside the repo.
+ origin_dir: str | None = None
@dataclass
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 8a128cd4b..6911eb037 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -695,11 +695,18 @@ def _cross_repo_block(
def _empty_impacted(status: str, summary: str) -> dict[str, Any]:
- """Uniform impacted-tests block for the degraded (no tests to name) paths."""
+ """Uniform impacted-tests block for the degraded (no tests to name) paths.
+
+ ``basis`` says which signal named the tests (``none`` here) and
+ ``tests_to_run_kind`` what each entry is: a coverage-map ``test_id`` on
+ the measured basis, a ``test_file`` on the inferred one.
+ """
return {
"status": status,
+ "basis": "none",
"map_present": False,
"tests_to_run": [],
+ "tests_to_run_kind": None,
"total": 0,
"truncated": False,
"line_coverage": {
@@ -1075,6 +1082,7 @@ async def _inferred_impacted(
{
"basis": "inferred",
"tests_to_run": _cap_tests(tests, collector, "inferred"),
+ "tests_to_run_kind": "test_file",
"total": total,
"truncated": total > _IMPACTED_TESTS_LIMIT,
"summary": (
@@ -1197,6 +1205,7 @@ async def _impacted_tests_block(
"basis": "measured",
"map_present": True,
"tests_to_run": _cap_tests(tests, collector, "measured"),
+ "tests_to_run_kind": "test_id",
"total": total,
"truncated": total > _IMPACTED_TESTS_LIMIT,
"line_coverage": _serialize_missing(report),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
index 78cea3a48..e7f0c7d6c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
@@ -57,6 +57,7 @@ _MAY_BREAK_TESTS_LIMIT = 3
#: than the may-break lists (it is what you actually run), but stays glanceable;
#: the overflow and full typed rows live in pr_blast_radius.test_impact.
_TESTS_TO_RUN_LIMIT = 10
+_TESTS_TO_RUN_KIND = {"measured": "test_id", "inferred": "test_file"}
def _breaking_change_directive(
@@ -670,6 +671,8 @@ def _build_pr_directive(
"files_without_measured_tests": [],
"tests_to_run": tests_to_run,
"tests_to_run_basis": tests_to_run_basis,
+ # A measured row names a coverage-map test id; an inferred one a test file.
+ "tests_to_run_kind": _TESTS_TO_RUN_KIND.get(tests_to_run_basis),
"tests_to_run_total": tests_to_run_total,
"tests_to_run_emitted": len(tests_to_run),
"tests_to_run_truncated": tests_capped,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
index 52b31e615..4ec2762fa 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
@@ -323,8 +323,12 @@ async def _enrich_cross_repo(
async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
"""Attach per-file health_score, coverage, and top_biomarkers from the health
tables. Conservative: missing data → no field, never invented. Never raises.
+
+ Coverage comes from the stored coverage rows, the source every other surface
+ reads, not the copy the health pass took of them.
"""
try:
+ from repowise.core.persistence.crud import load_coverage_for_repo
from repowise.core.persistence.models import HealthFileMetric, HealthFinding
target_paths = [r["target"] for r in results if r.get("target")]
@@ -338,6 +342,12 @@ async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
)
)
metric_map = {m.file_path: m for m in m_res.scalars().all()}
+ coverage_map = {
+ c.file_path: c
+ for c in await load_coverage_for_repo(
+ _h_session, repo_id, file_paths=target_paths, include_covered_lines=False
+ )
+ }
f_res = await _h_session.execute(
select(HealthFinding)
@@ -370,10 +380,11 @@ async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
m = metric_map.get(path)
if m is not None:
r["health_score"] = round(m.score, 2)
- if m.line_coverage_pct is not None:
- r["coverage_pct"] = round(m.line_coverage_pct, 2)
- if m.branch_coverage_pct is not None:
- r["branch_coverage_pct"] = round(m.branch_coverage_pct, 2)
+ c = coverage_map.get(path)
+ if c is not None:
+ r["line_coverage_pct"] = round(c.line_coverage_pct, 2)
+ if c.branch_coverage_pct is not None:
+ r["branch_coverage_pct"] = round(c.branch_coverage_pct, 2)
if path in top_by_file:
r["top_biomarkers"] = top_by_file[path]
except Exception:
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 7afe09d10..938cf77ee 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -163,6 +163,11 @@ async def files_index(
degrees = await crud.get_graph_metrics(session, repo_id)
metrics_by_path = {m.file_path: m for m in await crud.get_health_metrics(session, repo_id)}
git_by_path = await crud.get_all_git_metadata(session, repo_id)
+ # The stored report, not the copy the health pass took of it.
+ coverage_by_path = {
+ c.file_path: c.line_coverage_pct
+ for c in await crud.load_coverage_for_repo(session, repo_id, include_covered_lines=False)
+ }
pagerank_pct = _percentile_map({n.node_id: (n.pagerank or 0.0) for n in nodes})
@@ -198,7 +203,9 @@ async def files_index(
"last_commit_at": (
git.last_commit_at.isoformat() if git and git.last_commit_at else None
),
- "coverage_pct": metric.line_coverage_pct if metric else None,
+ "line_coverage_pct": coverage_by_path.get(path),
+ # Deprecated alias of ``line_coverage_pct``, kept for older clients.
+ "coverage_pct": coverage_by_path.get(path),
"is_test": n.is_test,
"is_entry_point": n.is_entry_point,
"community_id": n.community_id,
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index c1b707e20..10493d0f5 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -228,6 +228,9 @@ export interface FileRow {
churn_pct: number | null;
commit_count: number | null;
last_commit_at: string | null;
+ /** Measured line coverage, 0-100, from the stored report. Optional so older servers parse. */
+ line_coverage_pct?: number | null;
+ /** @deprecated The same figure as `line_coverage_pct`; read that. */
coverage_pct: number | null;
is_test: boolean;
is_entry_point: boolean;
diff --git a/packages/ui/src/files/files-index.tsx b/packages/ui/src/files/files-index.tsx
index f57140637..94642d075 100644
--- a/packages/ui/src/files/files-index.tsx
+++ b/packages/ui/src/files/files-index.tsx
@@ -7,7 +7,7 @@ import { bandForScore } from "@repowise-dev/types/health";
import { cn } from "../lib/cn";
import { formatLOC, formatNumber } from "../lib/format";
import { FilesTreemap, type TreemapColor, type TreemapSize } from "./files-treemap";
-import { FilesTable, type SortKey } from "./files-table";
+import { FilesTable, lineCoverage, type SortKey } from "./files-table";
// One `Fig`, shared with the file detail page. The two Files surfaces are meant
// to emphasise a figure identically, and two identical local copies is how that
// stops being true without anyone noticing.
@@ -166,7 +166,7 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
cmp = num(a.loc) - num(b.loc);
break;
case "coverage":
- cmp = num(a.coverage_pct) - num(b.coverage_pct);
+ cmp = num(lineCoverage(a)) - num(lineCoverage(b));
break;
case "name":
cmp = a.file_path.localeCompare(b.file_path);
diff --git a/packages/ui/src/files/files-table.tsx b/packages/ui/src/files/files-table.tsx
index e224c2ae6..9df277f69 100644
--- a/packages/ui/src/files/files-table.tsx
+++ b/packages/ui/src/files/files-table.tsx
@@ -82,6 +82,15 @@ function SortHeader({
const GRID =
"grid grid-cols-[minmax(0,1fr)_auto_56px] sm:grid-cols-[minmax(0,1fr)_92px_64px_64px] md:grid-cols-[minmax(0,1fr)_100px_84px_72px_64px_72px] items-center gap-2 px-3 sm:px-4";
+/** A row's line coverage; an older server sends only the deprecated `coverage_pct`. */
+export function lineCoverage(f: FileRow): number | null {
+ return f.line_coverage_pct ?? f.coverage_pct;
+}
+
+function formatCoverage(pct: number | null): string {
+ return pct != null ? `${Math.round(pct)}%` : "—";
+}
+
export function FilesTable({ files, fileHref, sortKey, sortDir, onSort }: FilesTableProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
@@ -226,7 +235,7 @@ export function FilesTable({ files, fileHref, sortKey, sortDir, onSort }: FilesT
{/* Coverage */}
<span className="hidden justify-end tabular-nums text-[var(--color-text-secondary)] md:flex">
- {f.coverage_pct != null ? `${Math.round(f.coverage_pct)}%` : "—"}
+ {formatCoverage(lineCoverage(f))}
</span>
</a>
);
diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.json
index e2d065c25..35feb06ea 100644
--- a/tests/fixtures/mcp/tool_response_shapes.json
+++ b/tests/fixtures/mcp/tool_response_shapes.json
@@ -1444,7 +1444,7 @@
"co_change_partners_truncated": null,
"commit_count_capped": null,
"contributor_count": null,
- "coverage_pct": null,
+ "line_coverage_pct": null,
"defect_profile": {
"bug_magnet": null,
"fix_count": null,
diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.py
index eb3c2742e..3c19ec269 100644
--- a/tests/unit/analysis/test_changed_lines.py
+++ b/tests/unit/analysis/test_changed_lines.py
@@ -161,3 +161,47 @@ def test_split_revspec() -> None:
assert split_revspec("HEAD~3..") == ("HEAD~3", "..", "HEAD")
assert split_revspec("..HEAD") == ("HEAD", "..", "HEAD")
assert split_revspec("HEAD") is None
+
+
+def test_quoted_non_ascii_header_paths_are_decoded() -> None:
+ # git quotes a non-ASCII path and escapes its UTF-8 bytes in octal.
+ diff = (
+ r'diff --git "a/caf\303\251.py" "b/caf\303\251.py"' "\n"
+ r'--- "a/caf\303\251.py"' "\n"
+ r'+++ "b/caf\303\251.py"' "\n"
+ "@@ -1 +1 @@\n"
+ "-a = 1\n"
+ "+a = 2\n"
+ )
+ assert _parse_unified_diff(diff) == {"café.py": {1}}
+
+
+def test_real_non_ascii_path_matches_its_tree_key(git_repo) -> None:
+ (git_repo / "café.py").write_text("a = 1\n", encoding="utf-8")
+ _git(git_repo, "add", "café.py")
+ _git(git_repo, "commit", "-qm", "add")
+ (git_repo / "café.py").write_text("a = 2\n", encoding="utf-8")
+ _git(git_repo, "commit", "-qam", "edit")
+
+ assert changed_lines(str(git_repo), "HEAD")[0] == {"café.py": {1}}
+
+
+def test_change_health_refuses_a_shallow_boundary_commit(git_repo, tmp_path_factory) -> None:
+ from repowise.core.analysis.change_health.sources import GitRevisionSource
+
+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 3\nd = 4\n", encoding="utf-8")
+ _git(git_repo, "commit", "-qam", "second")
+ clone = tmp_path_factory.mktemp("shallow") / "c"
+ _git(git_repo, "clone", "-q", "--depth", "1", git_repo.as_uri(), str(clone))
+
+ with pytest.raises(ValueError, match="shallow"):
+ GitRevisionSource(str(clone)).resolve("HEAD")
+ # A real root commit in a full clone still diffs against the empty tree.
+ root = subprocess.run(
+ ["git", "rev-list", "--max-parents=0", "HEAD"],
+ cwd=git_repo,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ assert GitRevisionSource(str(git_repo)).resolve(root).base_sha
diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.py
index c3afa0e83..6802b8592 100644
--- a/tests/unit/cli/test_search_collapse.py
+++ b/tests/unit/cli/test_search_collapse.py
@@ -144,7 +144,7 @@ RISK_PAYLOAD = {
"top_symbols": {"_prune_stale_file_rows": 9,
"mark_tombstone_pages": 4}},
"health_score": 3.2,
- "coverage_pct": 61.0,
+ "line_coverage_pct": 61.0,
"top_biomarkers": [
{"biomarker_type": "nested_complexity", "severity": "high",
"function_name": "persist_analysis", "impact": 0.71},
diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.py
index 481c386b8..7660942f0 100644
--- a/tests/unit/health/test_coverage_discovery.py
+++ b/tests/unit/health/test_coverage_discovery.py
@@ -340,3 +340,107 @@ def test_coverage_config_parses_block() -> None:
assert cfg.paths == ("coverage/lcov.info",)
assert cfg.strip_prefix == "build"
assert cfg.reingest_on_update is True
+
+
+# ---------------------------------------------------------------------------
+# Directory agreement, report location and Cobertura source roots
+# ---------------------------------------------------------------------------
+
+
+def test_a_lone_basename_needs_a_matching_directory() -> None:
+ # Only the basename agrees: another package's utils.py is not this one.
+ res = resolve_reports([_report([_fc("other/pkg/utils.py")])], {"src/utils.py"})
+ assert res.unmatched == ["other/pkg/utils.py"]
+ assert res.coverage_map == {}
+
+
+def test_a_root_file_under_an_absolute_path_still_matches() -> None:
+ # The whole key is the tail of the report path.
+ res = resolve_reports([_report([_fc("/home/ci/proj/command.go")])], {"command.go"})
+ assert "command.go" in res.coverage_map
+
+
+def test_relative_paths_resolve_under_the_reports_own_package() -> None:
+ # A monorepo package's report names paths relative to that package.
+ keys = {"src/index.ts", "packages/web/src/index.ts", "packages/api/src/index.ts"}
+ report = CoverageReport(
+ source_format="lcov",
+ files=[_fc("src/index.ts")],
+ origin_dir="packages/web/coverage",
+ )
+ res = resolve_reports([report], keys)
+ assert list(res.coverage_map) == ["packages/web/src/index.ts"]
+ assert res.matched_exact == 1
+
+
+def test_a_tie_prefers_the_reports_own_directory() -> None:
+ keys = {"packages/web/src/util.ts", "packages/api/src/util.ts"}
+ report = CoverageReport(
+ source_format="lcov",
+ files=[_fc("/ci/build/src/util.ts")],
+ origin_dir="packages/api/coverage",
+ )
+ res = resolve_reports([report], keys)
+ assert list(res.coverage_map) == ["packages/api/src/util.ts"]
+
+
+def test_cobertura_source_roots_disambiguate_shared_basenames() -> None:
+ from repowise.core.analysis.health.coverage import parse_cobertura
+
+ xml = (
+ "<coverage><sources><source>/ci/repo/packages/core/src</source></sources>"
+ '<packages><package><classes><class filename="pkg/__init__.py">'
+ '<lines><line number="1" hits="1"/></lines></class></classes></package>'
+ "</packages></coverage>"
+ )
+ report = parse_cobertura(xml)
+ keys = {"packages/core/src/pkg/__init__.py", "packages/cli/src/pkg/__init__.py"}
+
+ assert report.source_roots == ("/ci/repo/packages/core/src",)
+ res = resolve_reports([report], keys)
+ assert list(res.coverage_map) == ["packages/core/src/pkg/__init__.py"]
+
+
+def test_build_coverage_map_records_where_the_report_lives(tmp_path: Path) -> None:
+ pkg = tmp_path / "packages" / "web"
+ (pkg / "coverage").mkdir(parents=True)
+ (pkg / "coverage" / "lcov.info").write_text(
+ "SF:src/index.ts\nDA:1,1\nend_of_record\n", encoding="utf-8"
+ )
+ res, errors = build_coverage_map(
+ tmp_path,
+ [pkg / "coverage" / "lcov.info"],
+ {"src/index.ts", "packages/web/src/index.ts"},
+ )
+ assert not errors
+ assert list(res.coverage_map) == ["packages/web/src/index.ts"]
+
+
+def test_a_dependency_file_never_matches_the_repos_own() -> None:
+ keys = {"index.js", "src/index.js"}
+ res = resolve_reports([_report([_fc("node_modules/x/index.js")])], keys)
+ assert res.coverage_map == {}
+ assert res.unmatched == ["node_modules/x/index.js"]
+
+
+def test_source_roots_that_disagree_are_ambiguous() -> None:
+ keys = {"src/foo/x.py", "lib/foo/x.py"}
+ report = CoverageReport(
+ source_format="cobertura",
+ files=[_fc("foo/x.py")],
+ source_roots=("/ci/repo/src", "/ci/repo/lib"),
+ )
+ res = resolve_reports([report], keys)
+ assert res.ambiguous == ["foo/x.py"]
+
+
+def test_source_roots_win_over_the_report_directory() -> None:
+ keys = {"packages/api/x.py", "packages/api/src/x.py"}
+ report = CoverageReport(
+ source_format="cobertura",
+ files=[_fc("x.py")],
+ source_roots=("/ci/repo/packages/api/src",),
+ origin_dir="packages/api",
+ )
+ res = resolve_reports([report], keys)
+ assert list(res.coverage_map) == ["packages/api/src/x.py"]
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index e0701b6b4..1b7120b32 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -248,6 +248,7 @@ async def test_impacted_tests_line_precise_hit_and_miss(tmp_path, monkeypatch) -
it = result["impacted_tests"]
assert it["status"] == "map_present"
assert it["basis"] == "measured"
+ assert it["tests_to_run_kind"] == "test_id"
assert it["map_present"] is True
# app.py line 3 is covered -> its test is named; other/new are not covering.
assert it["tests_to_run"] == ["tests/test_app.py::test_app"]
@@ -334,6 +335,7 @@ async def test_impacted_tests_falls_back_to_the_graph_without_a_map(tmp_path, mo
assert it["status"] == "inferred"
assert it["basis"] == "inferred"
+ assert it["tests_to_run_kind"] == "test_file"
assert it["map_present"] is False
assert it["tests_to_run"] == ["tests/test_round_trips.py"]
assert it["line_coverage"]["untested_changes"] == []
@@ -410,6 +412,9 @@ async def test_the_two_risk_tools_do_not_share_a_key_for_different_questions() -
empty = module._empty_impacted("no_map", "run the suite")
assert "missing_tests" not in empty
+ # Every shape says which signal named the tests, including none.
+ assert empty["basis"] == "none"
+ assert empty["tests_to_run_kind"] is None
assert set(empty["line_coverage"]) == {
"untested_changes",
"stale_test_candidates",
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 0f0341f3d..cf148ae5f 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -217,6 +217,7 @@ async def test_get_risk_pr_directive_surfaces_coverage_backed_tests_to_run(setup
]
# The graph also reaches this file, and must not dilute a measured answer.
assert directive["tests_to_run_basis"] == "measured"
+ assert directive["tests_to_run_kind"] == "test_id"
assert "2 measured" in directive["summary"]
assert {row["basis"] for row in directive["test_recommendations"]} == {
"measured",
@@ -309,6 +310,7 @@ async def test_get_risk_pr_directive_falls_back_to_the_graph_without_a_map(setup
assert directive["tests_to_run"] == ["tests/test_service.py"]
assert directive["tests_to_run_basis"] == "inferred"
+ assert directive["tests_to_run_kind"] == "test_file"
assert "inferred, not coverage-proven" in directive["summary"]
assert "coverage-backed test(s) guard the change" not in directive["summary"]
@@ -323,6 +325,7 @@ async def test_get_risk_pr_directive_names_no_tests_when_nothing_reaches(setup_m
assert directive["tests_to_run"] == []
assert directive["tests_to_run_basis"] == "none"
+ assert directive["tests_to_run_kind"] is None
assert directive["missing_tests"] == []
assert directive["coverage_analysis"]["status"] == "unavailable"
assert "missing_tests is withheld" in directive["summary"]
@@ -697,3 +700,30 @@ async def test_get_risk_co_change_rows_carry_direction(setup_mcp):
assert p["direction"] == "undirected"
assert "conf_ab" not in p
assert "conf_ba" not in p
+
+
+async def test_get_risk_card_reads_line_coverage_from_the_stored_report(setup_mcp, session):
+ from repowise.core.persistence.crud import save_coverage_files
+ from repowise.server.mcp_server import get_risk
+
+ await save_coverage_files(
+ session,
+ "repo1",
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "line_coverage_pct": 61.5,
+ "branch_coverage_pct": 40.0,
+ "total_coverable_lines": 200,
+ }
+ ],
+ source_format="lcov",
+ )
+ await session.commit()
+
+ card = (await get_risk(["src/auth/service.py"]))["targets"]["src/auth/service.py"]
+
+ assert card["line_coverage_pct"] == 61.5
+ assert card["branch_coverage_pct"] == 40.0
+ assert "coverage_pct" not in card