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): give files changed since a stale coverage report no figures (#3735)
Swati Ahuja913cd85c2aaf
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex d4c214163..504f635f2 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -207,6 +207,7 @@ REST patch-coverage route the editor reads.| `no_coverable_changes` | The report names the file, but no changed line is executable | No || `not_in_report` | The report does not name the file (e.g. a new file no test loaded) | No; listed, never 0% || `no_line_data` | The report names the file but gives no executable-line set | No |+| `stale_file` | Stored coverage only: the file changed since the commit the coverage was measured at | No; listed, no figures |Exit `0` passes or had nothing to judge, `1` is below a gate, `2` means thecheck could not run (no usable report, unknown revision, shallow clone withoutdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 7642b18bf..0b6068cc4 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1452,7 +1452,7 @@ carries `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,`threshold`, `min_coverable_lines`, `gate` (`pass`, `fail`, `no_data`,`not_set`, `too_small`; `fail` when any gate fails), `file_counts`(`measured`, `not_in_report`, `no_line_data`, `no_coverable_changes`,-`out_of_scope`), `files[]` (`file_path`, `status`, `changed_line_count`,+`stale_file` (stored coverage only, always 0 here), `out_of_scope`), `files[]` (`file_path`, `status`, `changed_line_count`,`coverable_line_count`, `covered_line_count`, `patch_coverage_pct`,`uncovered_ranges`, `branch_taken`, `branch_total`, `partial_ranges` (0 andempty without branch data), `risk`: `fix_pressure`, `dependents`, `hotspot`,diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 65df2eac6..2c81c8fcb 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -264,7 +264,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`**impacted_tests.** The same selection `repowise impacted-tests` makes over the whole change (every touched path, whatever the score's filters). `status` is `selected` or `run_all` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last; `why` gives each listed file's reason. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test; `basis_by_file` names the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.-**patch_coverage.** Present when the index stores coverage; the same computation and JSON shape `repowise coverage check --format json` gates on. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.+**patch_coverage.** Present when the index stores coverage; the same computation and JSON shape `repowise coverage check --format json` gates on. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head; then a file git shows changed since that commit reads `stale_file`, with no figures, and only untouched files keep theirs. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.**fix_history.** `is_fix` applies a fixed keyword rule to the commit subject, not the conventional-commit type. `overlap` adds a diff-shape filter and needs an index: per file, `fix_count`, `overlapping_lines` (labelled `approximate`: past fix ranges are numbered against their own parent commit, so read it as "this area was patched before"), `last_fix_days_ago`, `changed_lines` and `share_of_change`. `concentration` names a file holding at least half the changed lines. The block never names the commit that introduced a bug, and is absent on an index with no fix history.diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex 7a57b9794..2e985a547 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -331,6 +331,7 @@ async def _stored(threshold=threshold,# The flag overrides its config key, as for a report.config=replace(cfg, min_coverable_lines=min_lines),+ repo_path=str(root),)except SQLAlchemyError as exc:raise CannotEvaluateError(diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.pyindex ab5b1f6a9..07dafc052 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py@@ -17,7 +17,9 @@ untested source file is surfaced rather than dropped; it is out of scopewhen it is a test file or a type the report never measures (docs, config).Ceiling: a not-in-report file is reported but excluded from the percentage,because its executable lines are unknown. A stricter gate can count it once a-report format carries "file present, nothing executed".+report format carries "file present, nothing executed". A measured file that+changed since the report was measured is ``stale_file`` and likewise left+out: the report's line numbers describe other code.Path-scoped gates (``coverage.gates``) apply the same rule to the measuredfiles their globs match. One that fails and is not informational fails the@@ -37,7 +39,7 @@ whether that is because the coverage carries no per-line branch data at allfrom __future__ import annotationsimport math-from collections.abc import Iterable, Mapping, Sequence+from collections.abc import Collection, Iterable, Mapping, Sequencefrom dataclasses import dataclass, field, replacefrom pathlib import PurePosixPathfrom typing import TYPE_CHECKING, Any, Literal, get_args@@ -55,7 +57,9 @@ if TYPE_CHECKING:from .hints import TestHintfrom .risk import FileRisk-FileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]+FileStatus = Literal[+ "measured", "not_in_report", "no_line_data", "no_coverable_changes", "stale_file"+]#: Whether the coverage read carries per-line branch counts: ``per_line`` it#: does, ``none`` the report has none, ``stored_before`` the stored rows were#: written before per-line branches were kept.@@ -403,6 +407,7 @@ def compute_patch_coverage(ignore: Sequence[str] = (),gates: Sequence[PathGate] = (),judge_gates: bool = True,+ stale: Collection[str] = (),) -> PatchCoverage:"""Intersect a change with a coverage report. See the module docstring.@@ -412,7 +417,9 @@ def compute_patch_coverage(matching *ignore* (``coverage.ignore``, gitignore syntax) are droppedbefore anything is measured and counted in the scope. Each of *gates*(``coverage.gates``) is judged on the measured files its globs match;- with *judge_gates* false they are counted but read ``no_data``.+ with *judge_gates* false they are counted but read ``no_data``. Changed+ files in *stale* (changed since the coverage was measured) read+ ``stale_file``, with no numbers."""measured_suffixes = {PurePosixPath(p).suffix for p in report_paths or coverage}ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)@@ -425,6 +432,8 @@ def compute_patch_coverage(continueif ignore_spec.match_file(path):ignored += 1+ elif path in stale:+ files.append(FilePatchCoverage(path, "stale_file", len(lines)))elif (row := _changed_file(path, lines, coverage, measured_suffixes)) is None:out_of_scope += 1else:@@ -531,7 +540,7 @@ def _path_gate(threshold=gate.fail_under,informational=gate.informational,measured_file_count=len(hits),- unmeasured_file_count=sum(f.status in _UNMEASURED for f in matched),+ unmeasured_file_count=sum(f.status in UNMEASURED for f in matched),covered_line_count=sum(f.covered_line_count for f in hits),coverable_line_count=sum(f.coverable_line_count for f in hits),small_change=small_change,@@ -539,7 +548,8 @@ def _path_gate()-_UNMEASURED = frozenset({"not_in_report", "no_line_data"})+#: Statuses of a changed file the report could not measure, in the order readers list them.+UNMEASURED: tuple[FileStatus, ...] = ("not_in_report", "stale_file", "no_line_data")def _gate(threshold: float | None, covered: int, coverable: int, small: bool) -> GateStatus:diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.pyindex 9cb4711cd..c08b973ed 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py@@ -20,7 +20,7 @@ from collections.abc import Callable, Sequencefrom ...ci import githubfrom ...ci.markdown import ROW_LIMIT, cell, details, more_line, plural-from .compute import FilePatchCoverage, PatchCoverage, PathGateResult+from .compute import UNMEASURED, FilePatchCoverage, PatchCoverage, PathGateResultfrom .delta import IndirectCause, IndirectChange, ProjectDeltafrom .hints import RANGE_LIMIT, TestHint, first_hint, hint_phrasefrom .risk import FileRisk@@ -30,6 +30,7 @@ STATUS_TEXT = {"not_in_report": "not in report","no_line_data": "report has no line data","no_coverable_changes": "no executable lines changed",+ "stale_file": "changed since coverage was measured",}@@ -285,8 +286,8 @@ def attention_rows(pc: PatchCoverage) -> list[FilePatchCoverage]:key=risk_order_key,)unmeasured = sorted(- pc.with_status("not_in_report") + pc.with_status("no_line_data"),- key=lambda f: (f.status != "not_in_report", *risk_order_key(f)),+ (f for f in pc.files if f.status in UNMEASURED),+ key=lambda f: (UNMEASURED.index(f.status), *risk_order_key(f)),)return gaps + unmeasured@@ -306,6 +307,7 @@ def render_markdown(pc: PatchCoverage) -> str:out += _path_gate_table(pc)out += _gap_table(pc)out += _details(pc.with_status("not_in_report"), "not in the coverage report")+ out += _details(pc.with_status("stale_file"), "changed since the coverage was measured")out += _details(pc.with_status("no_line_data"), "in a report without line data")out += _outside_section(pc)return "\n".join(out) + "\n"@@ -648,6 +650,8 @@ def _no_data_reason(pc: PatchCoverage) -> str:if pc.scope.ignored_file_count:return "Every changed file is ignored by coverage.ignore."return "The change has no changed lines."+ if pc.with_status("stale_file"):+ return "The changed source files changed since the coverage was measured."if pc.with_status("no_line_data"):return "The report does not say which lines are executable."if pc.with_status("not_in_report"):diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.pyindex 1699df654..89a47e846 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py@@ -7,13 +7,16 @@ REST API, editors) reads what ``coverage add`` or indexing stored. Both end infrom __future__ import annotations+import asyncioimport json+import subprocessfrom collections.abc import Iterable, Mappingfrom dataclasses import replacefrom typing import TYPE_CHECKING, Anyfrom sqlalchemy.ext.asyncio import AsyncSession+from ..git_cli import _git, untracked_pathsfrom ..health.coverage.discovery import CoverageScopefrom ..health.coverage.freshness import coverage_freshness, working_tree_freshnessfrom .compute import BranchData, PatchCoverage, PatchScope, compute_patch_coverage@@ -34,6 +37,7 @@ async def stored_patch_coverage(threshold: float | None = None,config: CoverageConfig | None = None,working_tree_mtime: float | None = None,+ repo_path: str | None = None,) -> PatchCoverage | None:"""Patch coverage of *changed* against stored coverage; ``None`` when none is stored.@@ -50,6 +54,10 @@ async def stored_patch_coverage(commit names that code, so freshness is whether the last ingest came afterit (``working_tree_freshness``). :func:`attach_history_delta` adds theproject delta.+ Stale coverage keeps numbers only for files git shows unchanged between the+ measured commit and the change's head in *repo_path*; the rest read+ ``stale_file``. Every measured file does when that cannot be told (no+ *repo_path*, no measured commit, a commit this clone lacks)."""from repowise.core.persistence.crud import (get_coverage_summary,@@ -64,14 +72,18 @@ async def stored_patch_coverage(return Nonesummary = await get_coverage_summary(session, repository_id, rows=rows)measured = {row.file_path for row in rows}- wanted = sorted(set(changed) & measured)- coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}commit = summary["ingested_commit_sha"]paths = summary["report_paths"]if working_tree_mtime is not None:freshness = working_tree_freshness(summary["ingested_at"], working_tree_mtime)else:freshness = coverage_freshness(commit, head_commit)+ stale: set[str] = set()+ if freshness == "stale":+ until = None if working_tree_mtime is not None else head_commit+ stale = await _stale_files(set(changed) & measured, repo_path, commit, until)+ wanted = sorted(set(changed) & measured - stale)+ coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}cfg = config or CoverageConfig()return compute_patch_coverage(changed,@@ -82,6 +94,7 @@ async def stored_patch_coverage(gates=cfg.gates,judge_gates=freshness == "current" and not cfg.gate_errors,report_paths=measured,+ stale=stale,scope=PatchScope(label=label,source_formats=tuple(summary["source_formats"]),@@ -96,6 +109,31 @@ async def stored_patch_coverage()+async def _stale_files(+ files: set[str], repo_path: str | None, measured_commit: str | None, until: str | None+) -> set[str]:+ """The *files* that changed since *measured_commit*; all of them when git cannot tell."""+ if not repo_path or not measured_commit:+ return files+ since = await asyncio.to_thread(_changed_since, repo_path, measured_commit, until)+ return files if since is None else files & since+++def _changed_since(repo_path: str, since: str, until: str | None) -> set[str] | None:+ """Files that differ between *since* and *until* (the working tree when ``None``).++ ``None`` when git cannot tell. Two dots: any content difference moves the+ report's line numbers, whichever side made it.+ """+ tail = [until] if until else []+ try:+ listing = _git(["diff", "--name-only", "-z", "--no-renames", since, *tail], repo_path)+ except (subprocess.SubprocessError, OSError):+ return None+ paths = {p for p in listing.split("\0") if p}+ return paths | set(untracked_paths(repo_path)) if until is None else paths++async def _stored_branch_data(session: AsyncSession, repository_id: str, rows: list[Any]) -> BranchData:diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.pyindex 2c6781bb7..efefc2384 100644--- a/packages/server/src/repowise/server/mcp_server/_change_health.py+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py@@ -91,20 +91,16 @@ def patch_coverage_action(block: dict[str, Any] | None) -> str | None:Names the scope and the tests to extend from the rows' hints, riskiestfile first, so the agent writes the missing test where the suite already- exercises the code. Stale coverage leads instead: its gaps are not real yet.+ exercises the code. Files changed since the coverage was measured lead+ instead: they carry no figure until the tests run again."""+ if stale := _stale_action(block):+ return staleuncovered = block["coverable_line_count"] - block["covered_line_count"] if block else 0if uncovered <= 0:return _partial_action(block)lines = f"{uncovered} changed executable line{'' if uncovered == 1 else 's'}"lines += _scope_words(block["scope"].get("label") or "")- if block["scope"]["freshness"] == "stale":- # Stale line numbers describe other code: the fix is a fresh run first.- return (- "Stored coverage predates this change: re-run the tests with coverage, then "- "`repowise coverage add` (the hook does it automatically) and call again "- f"({lines} read as uncovered until then)"- )tests = _hinted_tests(block["files"])text = f"{lines} {'is' if uncovered == 1 else 'are'} uncovered; "if tests:@@ -112,10 +108,22 @@ def patch_coverage_action(block: dict[str, Any] | None) -> str | None:return text + "add tests for them (patch_coverage.files)"+def _stale_action(block: dict[str, Any] | None) -> str | None:+ """Re-measure first when changed files have no figure because they changed since."""+ stale = ((block or {}).get("file_counts") or {}).get("stale_file", 0)+ if not stale:+ return None+ return (+ "Stored coverage predates this change: re-run the tests with coverage, then "+ "`repowise coverage add` (the hook does it automatically) and call again "+ f"({stale} changed file{'' if stale == 1 else 's'} not measured until then)"+ )++def _partial_action(block: dict[str, Any] | None) -> str | None:"""The next action when every changed line ran but some took only part of their branches."""partial = _partial_line_count(block)- if not partial or block["scope"]["freshness"] == "stale":+ if not partial:return Nonelines = f"{partial} changed line{'' if partial == 1 else 's'}"lines += _scope_words(block["scope"].get("label") or "")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.pyindex 985a91534..b10fc761f 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@@ -1373,6 +1373,7 @@ async def _patch_coverage_block(head_commit=head_commit,config=configured_coverage(ctx.path),working_tree_mtime=mtime,+ repo_path=str(ctx.path),)# An unreadable index row leaves risk to git alone and hints null.if patch is not None:diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex beaf18a80..a9d663b81 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -421,6 +421,7 @@ async def health_coverage_patch(label=label,head_commit=head_sha or None,config=configured_coverage(repo.local_path),+ repo_path=repo.local_path,)if patch is None:return Nonediff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.pyindex bef710690..65e1dc073 100644--- a/packages/server/src/repowise/server/schemas/patch_coverage.py+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py@@ -85,6 +85,7 @@ class PatchCoverageFileCounts(_Strict):not_in_report: intno_line_data: intno_coverable_changes: int+ stale_file: intout_of_scope: intdiff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 9a032f5c8..70f30a370 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2499,7 +2499,7 @@ export interface PatchCoverageBranches {export interface PatchCoverageFile {file_path: string;- status: "measured" | "not_in_report" | "no_line_data" | "no_coverable_changes";+ status: "measured" | "not_in_report" | "no_line_data" | "no_coverable_changes" | "stale_file";changed_line_count: number;coverable_line_count: number;covered_line_count: number;@@ -2517,6 +2517,7 @@ export interface PatchCoverageFileCounts {not_in_report: number;no_line_data: number;no_coverable_changes: number;+ stale_file: number;out_of_scope: number;}diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsxindex 7253ec7b4..0c148a2e3 100644--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx@@ -28,6 +28,7 @@ function coverage(fileCount: number): PatchCoverageResponse {not_in_report: 0,no_line_data: 0,no_coverable_changes: 0,+ stale_file: 0,out_of_scope: 0,},files: Array.from({ length: fileCount }, (_, i) => ({@@ -284,6 +285,20 @@ describe("PatchCoverageSummary", () => {risk: null,hints: null,},+ {+ file_path: "src/old.ts",+ status: "stale_file",+ changed_line_count: 2,+ coverable_line_count: 0,+ covered_line_count: 0,+ patch_coverage_pct: null,+ uncovered_ranges: [],+ branch_taken: 0,+ branch_total: 0,+ partial_ranges: [],+ risk: null,+ hints: null,+ },],scope: { ...base.scope, freshness: "stale" },}}@@ -293,6 +308,7 @@ describe("PatchCoverageSummary", () => {expect(screen.getByText(/not at this change's head/)).toBeTruthy();expect(screen.getByText("lines 3, 7-9")).toBeTruthy();expect(screen.getByText("not in report")).toBeTruthy();+ expect(screen.getByText("changed since measured")).toBeTruthy();});it("counts changed files coverage.ignore left out", () => {diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsxindex 384b941e5..ddcb01d6f 100644--- a/packages/ui/src/health/patch-coverage-summary.tsx+++ b/packages/ui/src/health/patch-coverage-summary.tsx@@ -222,11 +222,19 @@ function gapText(file: PatchCoverageFile): string {return parts.join(" · ");}-/** Not-in-report files before those without line data, then by risk: the core's order. */+/** How an unmeasured file reads, in the core's order (`attention_rows`). */+const UNMEASURED_TEXT: Partial<Record<PatchCoverageFile["status"], string>> = {+ not_in_report: "not in report",+ stale_file: "changed since measured",+ no_line_data: "no line data",+};+const UNMEASURED_ORDER = Object.keys(UNMEASURED_TEXT);++/** Not-in-report files, then stale ones, then those without line data, then by risk. */function unmeasuredFiles(files: PatchCoverageFile[]): PatchCoverageFile[] {- const rank = (f: PatchCoverageFile) => Number(f.status !== "not_in_report");+ const rank = (f: PatchCoverageFile) => UNMEASURED_ORDER.indexOf(f.status);return files- .filter((f) => f.status === "not_in_report" || f.status === "no_line_data")+ .filter((f) => rank(f) >= 0).sort((a, b) => rank(a) - rank(b) || byRisk(a, b));}@@ -505,7 +513,7 @@ function UnmeasuredList({<FileRowkey={f.file_path}file={f}- trailing={f.status === "not_in_report" ? "not in report" : "no line data"}+ trailing={UNMEASURED_TEXT[f.status] ?? ""}onOpenFile={onOpenFile}/>))}diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 3c4478e79..035c239f8 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -76,6 +76,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {not_in_report: 1,no_line_data: 0,no_coverable_changes: 0,+ stale_file: 0,out_of_scope: 0,},files: [diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.pyindex 42f62021a..eec4637f3 100644--- a/tests/unit/cli/test_coverage_check_cmd.py+++ b/tests/unit/cli/test_coverage_check_cmd.py@@ -1038,6 +1038,8 @@ def test_stored_coverage_is_judged_by_the_configured_path_gates(monkeypatch, tmpassert seen["config"].gates == cfg.gatesassert seen["config"].ignore == ("gen/",)assert seen["config"].min_coverable_lines == 3+ # The checkout to diff stale coverage against, as every other reader passes it.+ assert seen["repo_path"] == str(tmp_path)# -- coverage suggest-gates --------------------------------------------------diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.pyindex 3dffca534..aa2800d30 100644--- a/tests/unit/persistence/test_coverage_loaders.py+++ b/tests/unit/persistence/test_coverage_loaders.py@@ -154,6 +154,68 @@ async def test_stored_patch_coverage_marks_coverage_from_another_commit(assert stored is not Noneassert stored.scope.freshness == "stale"assert "measured at abcdef0, not at this change's head" in render_markdown(stored)+ # No checkout to diff: nothing tells which files kept their line numbers.+ assert [f.status for f in stored.files] == ["stale_file"]+ assert stored.patch_coverage_pct is None+++def _git(cwd, *args: str) -> str:+ import subprocess++ out = subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+ return out.stdout.strip()+++async def test_stale_coverage_keeps_figures_only_for_files_untouched_since(+ async_session, repo, tmp_path+) -> None:+ from repowise.core.analysis.patch_coverage import stored_patch_coverage++ _git(tmp_path, "init", "-q")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "src").mkdir()+ for name in ("a.py", "b.py"):+ (tmp_path / "src" / name).write_text("x = 1\ny = 2\n", encoding="utf-8")+ _git(tmp_path, "add", ".")+ _git(tmp_path, "commit", "-qm", "base")+ base = _git(tmp_path, "rev-parse", "HEAD")+ # Coverage measured at A, after both files changed; then B edits a.py alone.+ (tmp_path / "src" / "b.py").write_text("x = 1\ny = 3\n", encoding="utf-8")+ (tmp_path / "src" / "a.py").write_text("x = 1\ny = 3\n", encoding="utf-8")+ _git(tmp_path, "commit", "-qam", "A")+ measured = _git(tmp_path, "rev-parse", "HEAD")+ (tmp_path / "src" / "a.py").write_text("x = 1\ny = 4\nz = 5\n", encoding="utf-8")+ _git(tmp_path, "commit", "-qam", "B")+ head = _git(tmp_path, "rev-parse", "HEAD")+ files = [file_coverage("src/a.py", [1], [1, 2]), file_coverage("src/b.py", [1], [1, 2])]+ await save_coverage_files(+ async_session, repo.id, files, source_format="lcov", ingested_commit_sha=measured+ )+ changed = {"src/a.py": {2, 3}, "src/b.py": {2}}++ stored = await stored_patch_coverage(+ async_session, repo.id, changed, label=f"{base}..{head}", head_commit=head,+ repo_path=str(tmp_path),+ )++ assert stored is not None and stored.scope.freshness == "stale"+ a, b = stored.files+ assert (a.file_path, a.status, a.coverable_line_count, a.uncovered_ranges) == (+ "src/a.py", "stale_file", 0, ()+ )+ assert (b.file_path, b.status, b.uncovered_ranges) == ("src/b.py", "measured", ((2, 2),))+ assert stored.patch_coverage_pct == 0.0+ assert stored.to_dict()["file_counts"]["stale_file"] == 1++ # Uncommitted work diffs against the working tree: an edit on disk is stale too.+ (tmp_path / "src" / "b.py").write_text("x = 1\ny = 9\n", encoding="utf-8")+ working = await stored_patch_coverage(+ async_session, repo.id, changed, working_tree_mtime=float("inf"),+ repo_path=str(tmp_path),+ )+ assert [f.status for f in working.files] == ["stale_file", "stale_file"]+ assert working.patch_coverage_pct is Noneasync def test_stored_patch_coverage_is_none_without_coverage(async_session, repo) -> None:diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.pyindex e2ac1e13e..1de3a921f 100644--- a/tests/unit/server/mcp/test_tool_change_risk.py+++ b/tests/unit/server/mcp/test_tool_change_risk.py@@ -760,10 +760,16 @@ def test_the_directive_names_the_scope_and_the_tests_to_extend():"1 changed executable line in the working tree is uncovered; ""add tests for them (patch_coverage.files)")- # Stale coverage leads: its gaps are not real until the tests run again.- assert patch_coverage_action(_patch_block(0, 1, hints, freshness="stale")).startswith(+ # Files changed since the coverage was measured lead: they have no figure yet.+ stale = {**_patch_block(0, 1, hints, freshness="stale"), "file_counts": {"stale_file": 2}}+ assert patch_coverage_action(stale) == ("Stored coverage predates this change: re-run the tests with coverage, then "- "`repowise coverage add`"+ "`repowise coverage add` (the hook does it automatically) and call again "+ "(2 changed files not measured until then)"+ )+ # A file untouched since the measurement keeps real figures, stale or not.+ assert patch_coverage_action(_patch_block(0, 1, freshness="stale")).endswith(+ "is uncovered; add tests for them (patch_coverage.files)")