Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coverage): path-scoped coverage gates, with suggestions from owners, layout and the graph (#2649)

Raghav Chamadiya0e50aba6f0f5
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index f321a8be3..71aac25a1 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -673,7 +673,12 @@ computation and JSON shape `repowise coverage check --format json` gates on.
coverage never names read `not_in_report` rather than 0%, and
`scope.freshness` is `stale` when the coverage was measured at another commit
than the change's head (`unknown` for uncommitted work), so its line numbers
-may describe other code. The block is absent when no coverage is stored.
+may describe other code. `path_gates` lists the path-scoped gates in
+`coverage.gates`, each judged on the changed files its globs match (`gate`
+reads `fail` when one that is not informational fails). They are judged only
+on coverage measured at the change's head and valid config; otherwise they
+read `no_data`, and `scope.config_errors` names each invalid entry. The block
+is absent when no coverage is stored.
In workspace mode the response also carries `cross_repo`, and every
`cross_repo.consumers[]` row gains a `tests` block: a `state` (`measured`,
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 787fd3386..ca26d07db 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -261,10 +261,20 @@ measures as the percentage does, is reported against the threshold, but a miss
reads `too_small` and does not fail. `--report` takes globs and `PATH=PREFIX`,
`coverage.ignore` leaves generated files out, and Go module paths map to their
`go.mod` directory; see
-[Monorepos and matrix jobs](../start/CI.md#monorepos-and-matrix-jobs). The
+[Monorepos and matrix jobs](../start/CI.md#monorepos-and-matrix-jobs).
+`coverage.gates` adds path-scoped gates: each judges the changed files its
+globs match with the same rule (the small-change tolerance stays the whole
+change's), a file can count in several, and a path-scoped gate that is not
+informational fails the change when it fails, whatever the whole-change
+figure (`path_gates` in the JSON, REST and agent output; the read-only
+surfaces judge them only on coverage measured at the change's head and valid
+config, see [Path-scoped gates](../start/CI.md#path-scoped-gates)).
+`repowise coverage suggest-gates` proposes gates from CODEOWNERS, the
+top-level packages and, when indexed, the graph's communities. The
gate compares the unrounded figure; the displayed one is floored to one
decimal, so 79.99% reads 79.9% and fails an 80% gate. Exit `0` passes (or had
-nothing to judge), `1` is below the gate, `2` means the check could not run:
+nothing to judge), `1` is below the gate or a path-scoped gate fails, `2`
+means the check could not run:
no report found, readable or matching a repository file, an unknown revision,
no merge-base (a shallow clone), a single commit at a shallow clone's
boundary, bad config, or not a git repository.
@@ -544,6 +554,9 @@ coverage:
reingest_on_update: false
fail_under: 80 # patch-coverage gate for `coverage check` (0-100)
min_coverable_lines: 5 # small-change tolerance for that gate
+ gates: # path-scoped gates, judged on the files they match
+ - {name: api, paths: ["/services/api/"], fail_under: 85}
+ - {name: scripts, paths: ["/scripts/"], fail_under: 50, informational: true}
```
Coverage is also auto-discovered and ingested during `init` and `update`, and
@@ -558,6 +571,7 @@ Note that `--coverage-report` is test coverage, while `--coverage` controls
| `repowise coverage add [PATHS...]` | Ingest reports. Auto-discovers when no path is given, merges multiple, builds the per-test map when contexts are present. Flags: `--path`, `--format`, `--verbose` |
| `repowise coverage status` | Coverage summary plus test-to-code map counts. Flag: `--path` |
| `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--min-coverable-lines`, `--path`, `--format` |
+| `repowise coverage suggest-gates` | Propose path-scoped gates for `coverage.gates` as YAML to paste below `coverage:`; writes nothing. Flags: `--path`, `--format` |
| `repowise impacted-tests [REVSPEC]` | The tests a change exercises. Flags: `--path`, `--staged`, `--format` |
Full reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-coverage).
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index c4b517633..6cb94eed8 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1242,6 +1242,7 @@ their tests live.
repowise coverage add [PATHS...] # ingest coverage reports (+ per-test map when contexts are present)
repowise coverage status # show ingested coverage + the map
repowise coverage check [REVSPEC] # gate a change on its patch coverage (CI)
+repowise coverage suggest-gates # propose path-scoped gates for coverage.gates
```
**`add` options:**
@@ -1327,7 +1328,9 @@ are out of scope and only counted.
| `--format` | `table` (default), `json`, `markdown`, or `github` |
`github` writes up to 10 `::warning` annotations (largest uncovered ranges
-first), a `::notice` counting the rest, an `::error::` when the gate fails and
+first), a `::notice` counting the rest, an `::error::` when the gate fails, one
+per failing path-scoped gate that is not informational, a `::notice::` per
+informational gate below its threshold, and
a `::notice::` when the small-change tolerance exempts it, then appends the
markdown summary to `$GITHUB_STEP_SUMMARY` when set. `json` carries
`patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,
@@ -1337,7 +1340,11 @@ markdown summary to `$GITHUB_STEP_SUMMARY` when set. `json` carries
(`file_path`, `status`, `changed_line_count`, `coverable_line_count`,
`covered_line_count`, `patch_coverage_pct`, `uncovered_ranges`) and `scope`
(`label`, `source_formats`, `reports`, `report_path_count`,
-`unmatched_report_path_count`, `ignored_file_count`). Changed files and report
+`unmatched_report_path_count`, `ignored_file_count`, `config_errors`) and
+`path_gates[]` (`name`, `paths`, `threshold`, `informational`,
+`measured_file_count`, `unmeasured_file_count`, `covered_line_count`,
+`coverable_line_count`, `patch_coverage_pct`, `gate`).
+Changed files and report
entries matching `coverage.ignore` (gitignore syntax) are left out and counted
as ignored. Go coverprofile paths under a `go.mod`'s module path are mapped to
that module's directory unless the report has a per-report prefix or
@@ -1346,12 +1353,28 @@ that module's directory unless the report has a per-report prefix or
**Exit codes:** `0` the gate passes or there is nothing to judge (no
threshold, no measurable changed lines, or a change under the small-change
-tolerance); `1` patch coverage is below `--fail-under`; `2` the check could not
+tolerance); `1` patch coverage is below `--fail-under`, or a path-scoped gate
+that is not informational fails; `2` the check could not
run: no report found, a `--report` path or glob matching no file, none
readable, none matching a repository file, or every entry matching
`coverage.ignore`; an unknown revision; no merge-base (a shallow clone); a
single commit at a shallow clone's boundary; bad config or a malformed
-`coverage.fail_under` / `coverage.min_coverable_lines`; not a git repository.
+`coverage.fail_under` / `coverage.min_coverable_lines`, or an unusable
+`coverage.gates` entry (named in the message); not a git repository.
+
+**Path-scoped gates.** Each entry of `coverage.gates` (`name`, `paths` as
+gitignore-style globs relative to the repository root, optional `fail_under`
+0-100, optional `informational`) is judged on the measured changed files its
+globs match, with the same rule as the whole change; a file can count in
+several gates. The small-change tolerance is the whole change's: every gate
+reads `too_small` when the change is under `min_coverable_lines`, never a
+small slice of a big one. Matching changed files the report does not measure
+are counted as `unmeasured_file_count`, outside the percentage. `gate` reads
+`fail` when any gate that is not informational fails, whatever the
+whole-change figure, and the headline then leads with that gate and its
+counts. The table output lists every gate; the markdown lists up to 10,
+failing ones first. See [Path-scoped gates](../start/CI.md#path-scoped-gates)
+and `repowise coverage suggest-gates`.
A coverage.py `.coverage` database is not a text report: export it first with
`coverage lcov` or `coverage xml`. A new file no test loads must still appear
@@ -1371,6 +1394,42 @@ CI clones are often shallow, so the merge-base is missing and the check exits 2.
Fetch full history. The GitHub Action, the GitLab template and recipes for
other CI systems are in [Repowise in CI](../start/CI.md).
+#### `repowise coverage suggest-gates`
+
+Propose path-scoped gates for `coverage.gates`. Sources, in order, each
+labelled in a comment:
+
+- CODEOWNERS: the first of `.github/CODEOWNERS`, `CODEOWNERS`,
+ `docs/CODEOWNERS` and `.gitlab/CODEOWNERS`; one gate per owner. A later
+ pattern that may overlap an owner's paths and is not theirs (owner-less
+ lines included) is carried as a `!` exclusion; a catch-all (`*`) drops the
+ gates before it and is itself none; an owner whose every pattern a later one
+ overrides gets no gate. Escaped spaces, tab-separated comments and GitLab
+ `[Section] @owners` defaults are understood.
+- Top-level packages from `git ls-files`: each directory under `packages/`,
+ `apps/`, `services/` or `libs/` holding a source file that is not a test,
+ else each top-level source directory.
+- Graph communities when the repository is indexed: each with 3 or more
+ source files, over the directories holding them, named by their common
+ directory; the 10 largest, minus any with the same globs as a package gate.
+ The comment names the indexed commit, and says when there is no index, it
+ cannot be read, or it holds no communities.
+
+The first two need no index. Nothing is written and no `fail_under` is set.
+The YAML block is indented to paste directly below your `coverage:` line;
+names repeated across sources get a `-2` suffix, so it is valid config as
+printed.
+
+| Flag | Description |
+|------|-------------|
+| `--path` | A path inside the repository (defaults to cwd) |
+| `--format` | `yaml` (default), a block to paste below `coverage:`; or `json`, `{"sources": [{"source", "detail", "gates": [{"name", "paths"}]}]}` |
+
+```bash
+repowise coverage suggest-gates
+repowise coverage suggest-gates --format json
+```
+
---
### `repowise distill <command>`
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 28ac13ecb..90f007d59 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -330,6 +330,75 @@ subdirectory (`backend/go.mod` declaring `module example.com/m`), paths under
checkout, so files in the module's top-level package match with no prefix.
A per-report prefix or `coverage.path_prefix` turns the mapping off.
+### Path-scoped gates
+
+One threshold over the whole change lets a well-tested package carry an
+untested one. `coverage.gates` adds a gate per part of the repository: each is
+judged on the changed files its globs match, with the same rules as the
+whole-change gate. Globs use gitignore syntax, like `coverage.ignore`, and are
+relative to the repository root; a leading `/` anchors one there (`/api/` is
+the top-level `api` directory, `api/` any directory of that name).
+
+```yaml
+# .repowise/config.yaml
+coverage:
+ fail_under: 70 # the whole change, as before
+ gates:
+ - name: api
+ paths: ["/services/api/"]
+ fail_under: 85
+ - name: web
+ paths: ["/apps/web/", "!/apps/web/generated/"]
+ fail_under: 60
+ - name: scripts
+ paths: ["/scripts/"]
+ fail_under: 50
+ informational: true # reported, never fails
+```
+
+A gate without `fail_under` is reported but judges nothing. A file can match
+several gates; each counts it. The change fails when the whole-change gate
+fails or when any gate that is not `informational` fails. The headline then
+leads with the failing gate and its counts (`Fails: path-scoped gate api 60.0%
+(6 of 10 changed executable lines), below its 85.0% gate.`) before the
+whole-change verdict, the summary adds a table of gates (failing ones first),
+and on GitHub each failing gate is its own `::error::`; an informational gate
+below its threshold is a `::notice::`. The small-change tolerance is the whole
+change's: when the change has fewer changed executable lines than
+`min_coverable_lines`, every gate reads `too_small`, but a small slice of a
+big change is judged. An entry the config cannot use (no name, a repeated
+name, no paths or only `!` exclusions, a `fail_under` outside 0-100, an
+unknown key) makes the check exit `2` naming it.
+
+Like the whole-change figure, a gate counts only changed lines the report
+measures. A changed file it matches that the report does not measure (a new
+file no test loads, a report without line data) is counted apart, as
+`unmeasured_file_count`, and left out of the percentage: a gate over only such
+files reads "no measured changed lines (2 changed files not measured)" and
+fails nothing.
+
+With one report per job, each job would judge the gates on a fragment of the
+change: run `coverage check` once over the combined reports instead, as in
+[Monorepos and matrix jobs](#monorepos-and-matrix-jobs).
+
+The gates live in the committed config, so the Action and the GitLab template
+take no input for them: every job reads the same gates. The editor, REST and
+agent views report the same verdicts when the stored coverage was measured at
+the change's head and the config is valid; on stale coverage, or beside an
+invalid entry (which they list in `scope.config_errors`), their gates read
+`no_data`. To start, let Repowise propose some:
+
+```bash
+repowise coverage suggest-gates # YAML to paste below coverage:
+repowise coverage suggest-gates --format json
+```
+
+It reads CODEOWNERS (one gate per owner), the top-level packages git tracks,
+and, when the repository is indexed, the graph's communities, labelling each
+source in a comment. The block is indented to paste directly below your
+`coverage:` line. It writes nothing and sets no `fail_under`: keep the gates
+you want and choose their thresholds.
+
## When a gate exits 2
| Message | Fix |
@@ -338,6 +407,7 @@ A per-report prefix or `coverage.path_prefix` turns the mapping off.
| unknown revision `origin/<branch>` | fetch the target branch |
| no coverage report found | pass `--report`, or set `coverage.paths` |
| `--report ...`: no coverage report matches | fix the path or glob, or upload the report from the test job |
+| `coverage.gates[N]`: ... | fix that entry of `coverage.gates` |
| all report entries match coverage.ignore | narrow `coverage.ignore` |
| report paths match no file in the repository | set `coverage.strip_prefix` or `coverage.path_prefix` |
| baseline unreadable | commit the file, or drop `--baseline` |
diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
index 5bc7e402d..7b6578bb3 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -9,7 +9,8 @@ executable-line data; otherwise it cannot evaluate.
Exit codes and output channels are the shared CI ones (:mod:`repowise.cli.ci`):
0 when the gate passes or there is nothing to judge, 1 when patch coverage is
-below ``--fail-under``, 2 when the check could not run (no report, a
+below ``--fail-under`` or a path-scoped gate (``coverage.gates``) that is not
+informational fails, 2 when the check could not run (no report, a
``--report`` matching no file, unreadable report, unknown revision, missing
history, bad config). A change under ``--min-coverable-lines`` is reported
against the threshold but exits 0.
@@ -17,6 +18,7 @@ against the threshold but exits 0.
from __future__ import annotations
+from dataclasses import replace
from pathlib import Path
import click
@@ -98,6 +100,10 @@ def coverage_check(
Without it, the base comes from the CI's pull-request variables (GitHub,
GitLab, Jenkins, Bitbucket), else the remote's default branch.
+ Path-scoped gates in coverage.gates (.repowise/config.yaml) are judged
+ too; one that fails and is not informational fails the check. See
+ ``repowise coverage suggest-gates``.
+
Examples:
repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80
@@ -140,7 +146,7 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
if notices is console:
notices.print("[dim]Reading the coverage stored in the index[/dim]")
return _gateable(
- run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg.ignore))
+ run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg))
)
if notices is console:
# Machine formats carry the list in ``scope.reports`` instead.
@@ -154,6 +160,7 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
reports=[str(p) for p in report_paths],
min_coverable_lines=min_coverable_lines,
ignore=cfg.ignore,
+ gates=cfg.gates,
)
@@ -224,7 +231,7 @@ def _gateable(pc):
async def _stored(
- root: Path, changed, label: str, threshold: float | None, min_lines: int | None, ignore
+ root: Path, changed, label: str, threshold: float | None, min_lines: int | None, cfg
):
"""Patch coverage from the index's stored coverage, or ``None`` without one."""
from sqlalchemy.exc import SQLAlchemyError
@@ -245,8 +252,8 @@ async def _stored(
label=label,
head_commit=git_refs.resolve(str(root), revspec_head(label)),
threshold=threshold,
- min_coverable_lines=min_lines,
- ignore=ignore,
+ # The flag overrides its config key, as for a report.
+ config=replace(cfg, min_coverable_lines=min_lines),
)
except SQLAlchemyError as exc:
raise CannotEvaluateError(
@@ -319,6 +326,8 @@ def _coverage_config(root: Path, *, validate_threshold: bool, validate_min_lines
"config_invalid",
f"coverage.min_coverable_lines must be a whole number of 0 or more, got {raw_min!r}."
)
+ if cfg.gate_errors:
+ raise CannotEvaluateError("config_invalid", " ".join(cfg.gate_errors))
return cfg
@@ -336,6 +345,7 @@ def _emit(pc, fmt: str) -> None:
_print_summary(pc)
else:
_print_summary(pc)
+ _print_path_gates(pc)
_print_table(pc)
@@ -346,6 +356,23 @@ def _print_summary(pc) -> None:
console.print(f"[dim]{escape(scope_line(pc, markdown=False))}[/dim]")
+def _print_path_gates(pc) -> None:
+ from rich.table import Table
+
+ from repowise.core.analysis.patch_coverage import path_gate_row
+
+ if not pc.path_gates:
+ return
+ table = Table(show_edge=False, pad_edge=False)
+ table.add_column("Path-scoped gate")
+ table.add_column("Verdict")
+ table.add_column("Covered changed lines", justify="right")
+ table.add_column("Threshold", justify="right")
+ for g in pc.path_gates:
+ table.add_row(*(escape(v) for v in path_gate_row(g)))
+ console.print(table)
+
+
def _print_table(pc) -> None:
from rich.table import Table
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index e4c815d84..03edc6a71 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -16,6 +16,7 @@ import click
from repowise.cli._setup import configure_cli_logging
from repowise.cli.commands.coverage_check_cmd import coverage_check
+from repowise.cli.commands.coverage_suggest_gates_cmd import coverage_suggest_gates
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
@@ -60,6 +61,7 @@ def coverage_group() -> None:
coverage_group.add_command(coverage_check)
+coverage_group.add_command(coverage_suggest_gates)
@coverage_group.command("add")
diff --git a/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py
new file mode 100644
index 000000000..7e7195fb9
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py
@@ -0,0 +1,144 @@
+"""``repowise coverage suggest-gates``: propose path-scoped gates for ``coverage.gates``.
+
+Reads, in order, CODEOWNERS, the repository's top-level packages (from
+``git ls-files``) and, when an index exists, the graph's communities. Prints a
+YAML block to paste directly below the ``coverage:`` line; it never writes
+config and sets no threshold. The first two sources need no index.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+
+from repowise.cli.ci import repo_root
+from repowise.cli.helpers import repo_index_session, run_async
+from repowise.cli.output import emit_json
+
+_UNREADABLE = "index unreadable, so none suggested"
+
+
[email protected]("suggest-gates")
+ "--path",
+ "repo",
+ default=None,
+ help="A path inside the repository (defaults to cwd).",
+)
+ "--format",
+ "fmt",
+ type=click.Choice(["yaml", "json"]),
+ default="yaml",
+ show_default=True,
+ help="yaml prints a block to paste below coverage:; json the same proposals, by source.",
+)
+def coverage_suggest_gates(repo: str | None, fmt: str) -> None:
+ """Propose path-scoped gates (coverage.gates) for this repository.
+
+ Each gate judges the patch coverage of the changed files its globs match,
+ in ``repowise coverage check``. Suggestions come from CODEOWNERS (one gate
+ per owner), top-level packages, and graph communities when the repository
+ is indexed. Nothing is written: paste what you keep directly below the
+ ``coverage:`` line in .repowise/config.yaml and give each gate a fail_under.
+
+ Examples:
+
+ repowise coverage suggest-gates
+ repowise coverage suggest-gates --format json
+ """
+ from repowise.core.analysis.patch_coverage.suggest import render_yaml, unique_names
+
+ root = repo_root(repo)
+ layout = _layout(root)
+ sources = [_codeowners(root), layout, _graph(root, {g.paths for g in layout.gates})]
+ unique_names(sources)
+ if fmt == "json":
+ emit_json({"sources": [s.to_dict() for s in sources]})
+ else:
+ click.echo(render_yaml(sources), nl=False)
+
+
+def _codeowners(root: Path):
+ from repowise.core.analysis.patch_coverage.suggest import (
+ CODEOWNERS_PATHS,
+ GateSource,
+ codeowners_gates,
+ )
+
+ for rel in CODEOWNERS_PATHS:
+ path = root / rel
+ if path.is_file():
+ gates = codeowners_gates(path.read_text(encoding="utf-8", errors="replace"))
+ detail = rel if gates else f"{rel} names no owned paths"
+ return GateSource("codeowners", detail, gates)
+ return GateSource("codeowners", "no CODEOWNERS file")
+
+
+def _layout(root: Path):
+ from repowise.core import git_refs
+ from repowise.core.analysis.patch_coverage.suggest import GateSource, layout_gates
+
+ gates = layout_gates(git_refs.tracked_paths(str(root)))
+ return GateSource("layout", "git ls-files" if gates else "no source directories found", gates)
+
+
+def _graph(root: Path, layout_paths: set[tuple[str, ...]]):
+ """Community gates, minus any whose globs a layout gate already has."""
+ from repowise.core.analysis.patch_coverage.suggest import (
+ MIN_COMMUNITY_FILES,
+ GateSource,
+ community_gates,
+ )
+
+ read = run_async(_read_graph(root))
+ if isinstance(read, str):
+ return GateSource("graph", read)
+ communities, commit = read
+ at = f"the index at {commit[:7]}" if commit else "the index"
+ # One id for every file: the index never computed communities.
+ if len(set(communities.values())) <= 1:
+ return GateSource("graph", f"{at} has no communities computed")
+ gates, cut = community_gates(communities, _file_sizes(root, communities))
+ gates = [g for g in gates if g.paths not in layout_paths]
+ if not gates:
+ return GateSource(
+ "graph",
+ f"{at}: no community of {MIN_COMMUNITY_FILES}+ source files beyond the packages",
+ )
+ return GateSource("graph", at + (f"; {cut} smaller communities not shown" if cut else ""), gates)
+
+
+def _file_sizes(root: Path, files) -> dict[str, int]:
+ """Bytes per file on disk, for naming a root-level community; a missing file is left out."""
+ sizes: dict[str, int] = {}
+ for rel in files:
+ try:
+ sizes[rel] = (root / rel).stat().st_size
+ except OSError:
+ continue
+ return sizes
+
+
+async def _read_graph(root: Path) -> tuple[dict[str, int], str | None] | str:
+ """``({file: community_id}, indexed commit)``, or why the index could not answer."""
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.core.persistence.crud.graph import get_all_file_metrics
+ from repowise.core.persistence.crud.repository import get_repository
+ from repowise.core.persistence.database import has_db_store
+
+ if not has_db_store(root):
+ return "unavailable, no index (run `repowise init` to add them)"
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return _UNREADABLE
+ session, repo_id = opened
+ try:
+ nodes = await get_all_file_metrics(session, repo_id)
+ repo = await get_repository(session, repo_id)
+ except SQLAlchemyError:
+ return _UNREADABLE
+ communities = {n.file_path or n.node_id: n.community_id for n in nodes if not n.is_test}
+ return communities, repo.head_commit if repo else None
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.md
index 06e7f999e..47617f578 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md
+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md
@@ -88,8 +88,9 @@ writes paths relative to its own `<source>` root — so we reconcile them.
- `expand_report_patterns(patterns, base)`: the report files a list of paths
or globs names, shared by `coverage.paths` and `coverage check --report`;
`**` goes through the same pruned walk as discovery.
-- `configured_ignore(repo_root)`: `coverage.ignore` for the stored-coverage
- surfaces (REST, agent tools).
+- `configured_coverage(repo_root)`: the `coverage:` config (defaults when
+ unreadable) for the stored-coverage surfaces (REST, agent tools), so they
+ apply the same `coverage.ignore` and `coverage.gates` as the CLI gate.
### Config (`.repowise/config.yaml`)
@@ -111,9 +112,17 @@ coverage:
reingest_on_update: false # re-parse on every update (else reuse DB rows)
fail_under: 80 # patch-coverage gate for `coverage check`
min_coverable_lines: 5 # small-change tolerance for that gate
+ gates: # path-scoped gates (PathGate); see below
+ - {name: api, paths: ["/services/api/"], fail_under: 85}
```
`CoverageConfig.from_repo_config(load_repo_config(repo_path))` parses it.
+Each `gates` entry is `name`, `paths` (gitignore-style globs, at least one
+not a `!` exclusion), optional `fail_under` (0-100) and optional
+`informational`; valid ones land in `CoverageConfig.gates` as `PathGate`, and
+each invalid one leaves a message naming it in `gate_errors`. `coverage check`
+refuses to run on any; the stored-coverage surfaces carry them as
+`scope.config_errors` and judge no path gate.
## Inputs
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index e289a9795..9545bacbc 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -21,10 +21,11 @@ from .detector import PARSERS, detect_format, is_test_file, paired_test_file, pa
from .discovery import (
CoverageConfig,
CoverageProvenance,
+ PathGate,
ResolvedCoverage,
ResolvedTestCoverage,
build_coverage_map,
- configured_ignore,
+ configured_coverage,
discover_artifacts,
expand_report_patterns,
normalize_report_path,
@@ -55,11 +56,12 @@ __all__ = [
"CoverageReport",
"FileCoverage",
"FreshnessStatus",
+ "PathGate",
"ResolvedCoverage",
"ResolvedTestCoverage",
"TestCoverage",
"build_coverage_map",
- "configured_ignore",
+ "configured_coverage",
"coverage_freshness",
"decay_for_file",
"decay_since",
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 64ff24acd..f6ea2e0ec 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -82,6 +82,24 @@ _PRUNE_DIRS = PRUNED_DIRS | frozenset({"dist", "build"})
_MAX_ARTIFACTS = 50
+@dataclass(frozen=True)
+class PathGate:
+ """One ``coverage.gates`` entry: a patch-coverage gate over the files its globs match.
+
+ *paths* are gitignore-style globs, like ``coverage.ignore``. Without
+ *fail_under* the gate is reported but judges nothing; an *informational*
+ gate is judged but never fails the change.
+ """
+
+ name: str
+ paths: tuple[str, ...]
+ fail_under: float | None = None
+ informational: bool = False
+
+
+_PATH_GATE_KEYS = ("name", "paths", "fail_under", "informational")
+
+
@dataclass
class CoverageConfig:
"""The ``coverage:`` block of ``.repowise/config.yaml``.
@@ -115,6 +133,11 @@ class CoverageConfig:
# Small-change tolerance: a change with fewer changed executable lines
# than this never fails the gate.
min_coverable_lines: int | None = None
+ # Path-scoped gates (``coverage.gates``): the valid entries, and one
+ # message per invalid entry. ``coverage check`` refuses to run on any
+ # message; read-only surfaces evaluate the valid entries.
+ gates: tuple[PathGate, ...] = ()
+ gate_errors: tuple[str, ...] = ()
@classmethod
def from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:
@@ -130,6 +153,7 @@ class CoverageConfig:
return ()
paths, path_prefixes = _report_entries(block.get("paths"))
+ gates, gate_errors = _path_gates(block.get("gates"))
return cls(
auto_discover=bool(block.get("auto_discover", True)),
artifacts=_strs(block.get("artifacts")),
@@ -142,6 +166,8 @@ class CoverageConfig:
reingest_on_update=bool(block.get("reingest_on_update", False)),
fail_under=_percent(block.get("fail_under")),
min_coverable_lines=_line_count(block.get("min_coverable_lines")),
+ gates=gates,
+ gate_errors=gate_errors,
)
def reports(self, repo_root: Path) -> dict[Path, str | None]:
@@ -162,18 +188,104 @@ class CoverageConfig:
return {}
-def configured_ignore(repo_root: Path | str) -> tuple[str, ...]:
- """``coverage.ignore`` from *repo_root*'s config, empty when it cannot be read.
+def configured_coverage(repo_root: Path | str) -> CoverageConfig:
+ """*repo_root*'s ``coverage:`` config, the defaults when it cannot be read.
For the surfaces that read stored coverage (REST, agent tools), so their
- patch coverage leaves out the same files the CLI gate does.
+ patch coverage leaves out the same files and evaluates the same
+ path-scoped gates the CLI gate does.
"""
from repowise.core.repo_config import RepoConfigError, load_repo_config
try:
- return CoverageConfig.from_repo_config(load_repo_config(repo_root)).ignore
+ return CoverageConfig.from_repo_config(load_repo_config(repo_root))
except (RepoConfigError, OSError):
- return ()
+ return CoverageConfig()
+
+
+def _path_gates(value: object) -> tuple[tuple[PathGate, ...], tuple[str, ...]]:
+ """``coverage.gates``: the valid entries, and why each invalid one is not."""
+ if value is None:
+ return (), ()
+ if not isinstance(value, list):
+ return (), ("coverage.gates must be a list of {name, paths} entries.",)
+ gates: list[PathGate] = []
+ errors: list[str] = []
+ for i, entry in enumerate(value):
+ gate = _parse_path_gate(entry, {g.name for g in gates})
+ if isinstance(gate, PathGate):
+ gates.append(gate)
+ continue
+ name = entry.get("name") if isinstance(entry, dict) else None
+ where = f"coverage.gates[{i}]" + (f" ({name!r})" if isinstance(name, str) else "")
+ errors.append(f"{where}: {gate}")
+ return tuple(gates), tuple(errors)
+
+
+class _InvalidGateError(Exception):
+ """Why one ``coverage.gates`` entry cannot be used; the message says so."""
+
+
+def _parse_path_gate(entry: object, taken: set[str]) -> PathGate | str:
+ """One ``coverage.gates`` entry, or what is wrong with it (the first problem found)."""
+ try:
+ fields = _gate_fields(entry)
+ return PathGate(
+ _gate_name(fields.get("name"), taken),
+ _gate_paths(fields.get("paths")),
+ _gate_threshold(fields.get("fail_under")),
+ _gate_informational(fields.get("informational", False)),
+ )
+ except _InvalidGateError as exc:
+ return str(exc)
+
+
+def _gate_fields(entry: object) -> dict:
+ if not isinstance(entry, dict):
+ raise _InvalidGateError("must be a mapping with name and paths.")
+ unknown = sorted(str(k) for k in entry if k not in _PATH_GATE_KEYS)
+ if unknown:
+ raise _InvalidGateError(
+ f"unknown key {', '.join(unknown)}; expected {', '.join(_PATH_GATE_KEYS)}."
+ )
+ return entry
+
+
+def _gate_name(name: object, taken: set[str]) -> str:
+ if not isinstance(name, str) or not name.strip():
+ raise _InvalidGateError("name must be a non-empty string.")
+ if name in taken:
+ raise _InvalidGateError("duplicate name; each gate needs its own.")
+ return name
+
+
+def _gate_paths(raw: object) -> tuple[str, ...]:
+ paths = (raw,) if isinstance(raw, str) else raw
+ if not isinstance(paths, (list, tuple)) or not paths:
+ raise _InvalidGateError("paths must be a non-empty list of globs.")
+ if not all(isinstance(p, str) and p.strip() for p in paths):
+ raise _InvalidGateError("paths must be a non-empty list of globs.")
+ try:
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", paths)
+ except ValueError as exc:
+ raise _InvalidGateError(f"invalid glob in paths: {exc}") from exc
+ if not any(p.include for p in spec.patterns):
+ # Only comments or ``!`` exclusions: the gate could never match a file.
+ raise _InvalidGateError("paths must include a glob that is not a comment or a ! exclusion.")
+ return tuple(paths)
+
+
+def _gate_threshold(raw: object) -> float | None:
+ threshold = _percent(raw)
+ if raw is not None and threshold is None:
+ raise _InvalidGateError(f"fail_under must be a number from 0 to 100, got {raw!r}.")
+ return threshold
+
+
+def _gate_informational(raw: object) -> bool:
+ if not isinstance(raw, bool):
+ raise _InvalidGateError(f"informational must be true or false, got {raw!r}.")
+ return raw
def _report_entries(value: object) -> tuple[tuple[str, ...], dict[str, str]]:
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
index 7268ac1d3..3abc51772 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
@@ -8,6 +8,7 @@ from .compute import (
GateStatus,
PatchCoverage,
PatchScope,
+ PathGateResult,
compute_patch_coverage,
patch_coverage_from_resolved,
)
@@ -19,6 +20,8 @@ from .render import (
format_ranges,
github_annotations,
headline,
+ path_gate_row,
+ path_gate_verdict,
render_markdown,
scope_line,
)
@@ -32,6 +35,7 @@ __all__ = [
"GateStatus",
"PatchCoverage",
"PatchScope",
+ "PathGateResult",
"attention_rows",
"compute_patch_coverage",
"fmt_pct",
@@ -39,6 +43,8 @@ __all__ = [
"github_annotations",
"headline",
"patch_coverage_from_resolved",
+ "path_gate_row",
+ "path_gate_verdict",
"render_markdown",
"scope_line",
"stored_patch_coverage",
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
index b6df8de85..23e4447fc 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
@@ -18,6 +18,10 @@ when 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".
+
+Path-scoped gates (``coverage.gates``) apply the same rule to the measured
+files their globs match. One that fails and is not informational fails the
+change, whatever the whole-change figure says.
"""
from __future__ import annotations
@@ -36,7 +40,7 @@ from ..health.coverage.freshness import FreshnessStatus
from ..health.coverage.model import FileCoverage
if TYPE_CHECKING:
- from ..health.coverage.discovery import ResolvedCoverage
+ from ..health.coverage.discovery import PathGate, ResolvedCoverage
FileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]
GateStatus = Literal["pass", "fail", "no_data", "not_set", "too_small"]
@@ -95,6 +99,9 @@ class PatchScope:
# Changed files left out by ``coverage.ignore`` before anything was
# measured. Set by :func:`compute_patch_coverage`.
ignored_file_count: int = 0
+ # Invalid ``coverage.gates`` entries, one message each. The CLI refuses to
+ # run on them; read-only surfaces carry them and judge no path gate.
+ config_errors: tuple[str, ...] = ()
def to_dict(self) -> dict[str, Any]:
return {
@@ -107,6 +114,64 @@ class PatchScope:
"measured_commit": self.measured_commit,
"freshness": self.freshness,
"ignored_file_count": self.ignored_file_count,
+ "config_errors": list(self.config_errors),
+ }
+
+
+@dataclass(frozen=True)
+class PathGateResult:
+ """One path-scoped gate (``coverage.gates``) judged on the change.
+
+ Counts cover the measured changed files the gate's globs match, and the
+ verdict follows the whole change's rule. The small-change tolerance
+ exempts a small change, not a small slice of a big one, so *small_change*
+ is the whole change's test. An unjudged gate (stale coverage, invalid
+ config) reads ``no_data`` whatever its counts.
+ """
+
+ name: str
+ paths: tuple[str, ...]
+ threshold: float | None
+ informational: bool
+ measured_file_count: int
+ covered_line_count: int
+ coverable_line_count: int
+ # Matching changed files the report does not measure (``not_in_report``,
+ # ``no_line_data``): outside the percentage, but counted so a gate over
+ # only unmeasured files does not read as empty.
+ unmeasured_file_count: int = 0
+ small_change: bool = False
+ judged: bool = True
+
+ @property
+ def patch_coverage_pct(self) -> float | None:
+ return _pct(self.covered_line_count, self.coverable_line_count)
+
+ @property
+ def gate(self) -> GateStatus:
+ if not self.judged:
+ return "no_data"
+ return _gate(
+ self.threshold, self.covered_line_count, self.coverable_line_count, self.small_change
+ )
+
+ @property
+ def fails_change(self) -> bool:
+ """A failed gate that is not informational fails the whole change."""
+ return self.gate == "fail" and not self.informational
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "paths": list(self.paths),
+ "threshold": self.threshold,
+ "informational": self.informational,
+ "measured_file_count": self.measured_file_count,
+ "unmeasured_file_count": self.unmeasured_file_count,
+ "covered_line_count": self.covered_line_count,
+ "coverable_line_count": self.coverable_line_count,
+ "patch_coverage_pct": _round(self.patch_coverage_pct),
+ "gate": self.gate,
}
@@ -122,6 +187,9 @@ class PatchCoverage:
# Small-change tolerance: a change with fewer changed executable lines
# than this is reported against the threshold but never fails it.
min_coverable_lines: int | None = None
+ # Path-scoped gates, in config order. A failing one that is not
+ # informational fails ``gate``; ``flat_gate`` ignores them.
+ path_gates: tuple[PathGateResult, ...] = ()
@property
def changed_file_count(self) -> int:
@@ -139,20 +207,27 @@ class PatchCoverage:
def patch_coverage_pct(self) -> float | None:
return _pct(self.covered_line_count, self.coverable_line_count)
+ @property
+ def flat_gate(self) -> GateStatus:
+ """The whole change against ``threshold``, path-scoped gates aside."""
+ return _gate(
+ self.threshold, self.covered_line_count, self.coverable_line_count, self.small_change
+ )
+
+ @property
+ def small_change(self) -> bool:
+ """Fewer changed executable lines than ``min_coverable_lines``."""
+ n = self.min_coverable_lines
+ return n is not None and self.coverable_line_count < n
+
@property
def gate(self) -> GateStatus:
- if self.threshold is None:
- return "not_set"
- pct = self.patch_coverage_pct
- if pct is None:
- return "no_data"
- if pct >= self.threshold:
- return "pass"
- if self.min_coverable_lines is not None and (
- self.coverable_line_count < self.min_coverable_lines
- ):
- return "too_small"
- return "fail"
+ """``flat_gate``, or ``fail`` when a path-scoped gate fails the change."""
+ return "fail" if self.failing_path_gates else self.flat_gate
+
+ @property
+ def failing_path_gates(self) -> list[PathGateResult]:
+ return [g for g in self.path_gates if g.fails_change]
def with_status(self, status: FileStatus) -> list[FilePatchCoverage]:
return [f for f in self.files if f.status == status]
@@ -170,6 +245,7 @@ class PatchCoverage:
"file_counts": counts,
"files": [f.to_dict() for f in self.files],
"scope": self.scope.to_dict(),
+ "path_gates": [g.to_dict() for g in self.path_gates],
}
@@ -182,6 +258,8 @@ def compute_patch_coverage(
report_paths: Iterable[str] | None = None,
min_coverable_lines: int | None = None,
ignore: Sequence[str] = (),
+ gates: Sequence[PathGate] = (),
+ judge_gates: bool = True,
) -> PatchCoverage:
"""Intersect a change with a coverage report. See the module docstring.
@@ -189,7 +267,9 @@ def compute_patch_coverage(
only the changed files' entries (a stored report read for one change); it
decides which unlisted files count as ``not_in_report``. Changed files
matching *ignore* (``coverage.ignore``, gitignore syntax) are dropped
- before anything is measured and counted in the scope.
+ before 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``.
"""
measured_suffixes = {PurePosixPath(p).suffix for p in report_paths or coverage}
ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)
@@ -205,13 +285,17 @@ def compute_patch_coverage(
out_of_scope += 1
else:
files.append(row)
- return PatchCoverage(
+ pc = PatchCoverage(
files=tuple(files),
threshold=threshold,
out_of_scope_count=out_of_scope,
scope=replace(scope or PatchScope(), ignored_file_count=ignored),
min_coverable_lines=min_coverable_lines,
)
+ small = pc.small_change
+ return replace(
+ pc, path_gates=tuple(_path_gate(files, g, small, judge_gates) for g in gates)
+ )
def patch_coverage_from_resolved(
@@ -223,6 +307,7 @@ def patch_coverage_from_resolved(
reports: Sequence[str] = (),
min_coverable_lines: int | None = None,
ignore: Sequence[str] = (),
+ gates: Sequence[PathGate] = (),
) -> PatchCoverage:
""":func:`compute_patch_coverage` over reports already resolved to repo keys."""
unmatched = len(resolved.unmatched) + len(resolved.ambiguous)
@@ -232,6 +317,7 @@ def patch_coverage_from_resolved(
threshold=threshold,
min_coverable_lines=min_coverable_lines,
ignore=ignore,
+ gates=gates,
scope=PatchScope(
label=label,
source_formats=tuple(resolved.source_formats),
@@ -275,6 +361,42 @@ def _file_patch(path: str, lines: set[int], fc: FileCoverage) -> FilePatchCovera
)
+def _path_gate(
+ files: Sequence[FilePatchCoverage], gate: PathGate, small_change: bool, judged: bool
+) -> PathGateResult:
+ """*gate* over the changed files its globs match; a file may match several gates."""
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", gate.paths)
+ matched = [f for f in files if spec.match_file(f.file_path)]
+ hits = [f for f in matched if f.status == "measured"]
+ return PathGateResult(
+ name=gate.name,
+ paths=gate.paths,
+ threshold=gate.fail_under,
+ informational=gate.informational,
+ measured_file_count=len(hits),
+ 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,
+ judged=judged,
+ )
+
+
+_UNMEASURED = frozenset({"not_in_report", "no_line_data"})
+
+
+def _gate(threshold: float | None, covered: int, coverable: int, small: bool) -> GateStatus:
+ """One rule for the whole change and every path-scoped gate."""
+ if threshold is None:
+ return "not_set"
+ pct = _pct(covered, coverable)
+ if pct is None:
+ return "no_data"
+ if pct >= threshold:
+ return "pass"
+ return "too_small" if small else "fail"
+
+
def _pct(covered: int, coverable: int) -> float | None:
# Unrounded, so a gate never passes on rounding (79.998% is below 80%).
# Rounding happens only where the number is shown or serialized.
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
index 77b63d717..ecd62f477 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
@@ -16,8 +16,8 @@ import math
from collections.abc import Sequence
from ...ci import github
-from ...ci.markdown import ROW_LIMIT, cell, details, more_line
-from .compute import FilePatchCoverage, PatchCoverage
+from ...ci.markdown import ROW_LIMIT, cell, details, more_line, plural
+from .compute import FilePatchCoverage, PatchCoverage, PathGateResult
#: Uncovered ranges shown per file before "+N more".
RANGE_LIMIT = 8
@@ -31,7 +31,20 @@ STATUS_TEXT = {
def headline(pc: PatchCoverage, *, markdown: bool = True) -> str:
- """One-sentence verdict. Bold on the figure only in markdown."""
+ """One-sentence verdict. Bold on the figure only in markdown.
+
+ A failing path-scoped gate that is not informational leads, with its
+ counts, since it is why the change fails; the whole-change verdict follows.
+ """
+ text = _flat_headline(pc, markdown=markdown)
+ failing = pc.failing_path_gates
+ if failing:
+ text = f"Fails: {'; '.join(path_gate_verdict(g) for g in failing)}. {text}"
+ return text
+
+
+def _flat_headline(pc: PatchCoverage, *, markdown: bool) -> str:
+ """The whole-change verdict alone, path-scoped gates aside."""
bold = "**" if markdown else ""
pct = pc.patch_coverage_pct
if pct is None:
@@ -43,11 +56,12 @@ def headline(pc: PatchCoverage, *, markdown: bool = True) -> str:
f"{bold}Patch coverage {fmt_pct(pct)}{bold} ({pc.covered_line_count} of "
f"{pc.coverable_line_count} changed executable lines covered)"
)
- if pc.gate == "fail":
+ gate = pc.flat_gate
+ if gate == "fail":
text += f" · below the {fmt_pct(pc.threshold)} gate"
- elif pc.gate == "pass":
+ elif gate == "pass":
text += f" · meets the {fmt_pct(pc.threshold)} gate"
- elif pc.gate == "too_small":
+ elif gate == "too_small":
n = pc.min_coverable_lines
lines = "line" if n == 1 else "lines"
text += (
@@ -57,6 +71,60 @@ def headline(pc: PatchCoverage, *, markdown: bool = True) -> str:
return text
+def path_gate_verdict(g: PathGateResult) -> str:
+ """``path-scoped gate api 60.0% (6 of 10 changed executable lines), below its 85.0% gate``.
+
+ One wording for the headline, the ``::error::`` of a failing gate and the
+ ``::notice::`` of an informational one below its threshold.
+ """
+ return (
+ f"path-scoped gate {g.name} {fmt_pct(g.patch_coverage_pct)} ({g.covered_line_count} "
+ f"of {g.coverable_line_count} changed executable lines), below its "
+ f"{fmt_pct(g.threshold)} gate"
+ )
+
+
+# A path-scoped gate's verdict in words.
+_PATH_GATE_TEXT = {
+ "pass": "passes",
+ "fail": "fails",
+ "no_data": "no measured changed lines",
+ "not_set": "no threshold",
+ "too_small": "too few changed lines to judge",
+}
+
+
+def path_gate_row(g: PathGateResult) -> tuple[str, str, str, str]:
+ """``(name, verdict, covered, threshold)`` for one path-scoped gate, in plain text."""
+ covered = "n/a"
+ if g.coverable_line_count:
+ covered = (
+ f"{g.covered_line_count} of {g.coverable_line_count} "
+ f"({fmt_pct(g.patch_coverage_pct)})"
+ )
+ threshold = "none" if g.threshold is None else fmt_pct(g.threshold)
+ return g.name, _path_gate_words(g), covered, threshold
+
+
+def _path_gate_words(g: PathGateResult) -> str:
+ if g.informational:
+ words = "below threshold" if g.gate == "fail" else _no_data_words(g)
+ return f"{words} (informational)"
+ return _no_data_words(g)
+
+
+def _no_data_words(g: PathGateResult) -> str:
+ """The verdict in words, saying why a ``no_data`` gate has none."""
+ if g.gate != "no_data":
+ return _PATH_GATE_TEXT[g.gate]
+ if g.coverable_line_count:
+ # Counted but not judged: stale coverage or invalid config.
+ return "not judged"
+ n = g.unmeasured_file_count
+ unmeasured = f" ({plural(n, 'changed file')} not measured)" if n else ""
+ return _PATH_GATE_TEXT["no_data"] + unmeasured
+
+
def scope_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
"""The diff, the reports and how many changed files were measured."""
scope = pc.scope
@@ -97,6 +165,15 @@ def attention_rows(pc: PatchCoverage) -> list[FilePatchCoverage]:
def render_markdown(pc: PatchCoverage) -> str:
"""Markdown for a CI step summary or PR comment."""
out = [headline(pc), "", scope_line(pc)]
+ if pc.path_gates:
+ out += ["", "| Path-scoped gate | Verdict | Covered changed lines | Threshold |"]
+ out += ["|---|---|---|---|"]
+ # Gates failing the change first, so the cap never hides one.
+ for g in sorted(pc.path_gates, key=lambda g: not g.fails_change)[:ROW_LIMIT]:
+ name, verdict, covered, threshold = path_gate_row(g)
+ out.append(f"| `{cell(name)}` | {verdict} | {covered} | {threshold} |")
+ if len(pc.path_gates) > ROW_LIMIT:
+ out += ["", more_line(len(pc.path_gates) - ROW_LIMIT, "path-scoped gates")]
gaps = [f for f in attention_rows(pc) if f.status == "measured"]
if gaps:
out += ["", "| File | Uncovered changed lines | Covered |", "|---|---|---|"]
@@ -115,8 +192,9 @@ def render_markdown(pc: PatchCoverage) -> str:
def github_annotations(pc: PatchCoverage) -> list[str]:
"""GitHub Actions workflow commands for a change's patch coverage.
- A failed gate is an error; one exempted by the small-change tolerance is a
- notice, so the exemption is visible. The largest uncovered ranges are
+ A failed gate is an error, and so is each failing path-scoped gate that is
+ not informational; one exempted by the small-change tolerance, and an
+ informational gate below its threshold, is a notice, so neither is silent. The largest uncovered ranges are
marked, capped at what GitHub displays, with a notice counting the rest.
"""
ranges = sorted(
@@ -135,10 +213,15 @@ def github_annotations(pc: PatchCoverage) -> list[str]:
for path, a, b in ranges
]
verdict = []
- if pc.gate == "fail":
- verdict = [github.error(headline(pc, markdown=False))]
- elif pc.gate == "too_small":
- verdict = [github.notice(headline(pc, markdown=False))]
+ if pc.flat_gate == "fail":
+ verdict = [github.error(_flat_headline(pc, markdown=False))]
+ elif pc.flat_gate == "too_small":
+ verdict = [github.notice(_flat_headline(pc, markdown=False))]
+ for g in pc.path_gates:
+ if g.fails_change:
+ verdict.append(github.error(f"Fails: {path_gate_verdict(g)}."))
+ elif g.informational and g.gate == "fail":
+ verdict.append(github.notice(f"Informational: {path_gate_verdict(g)}."))
return verdict + github.cap_annotations(warnings, noun="uncovered changed ranges")
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
index e5087e3f3..91c16d830 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,17 @@ REST API, editors) reads what ``coverage add`` or indexing stored. Both end in
from __future__ import annotations
-from collections.abc import Iterable, Mapping, Sequence
+from collections.abc import Iterable, Mapping
+from typing import TYPE_CHECKING
from sqlalchemy.ext.asyncio import AsyncSession
from ..health.coverage.freshness import coverage_freshness
from .compute import PatchCoverage, PatchScope, compute_patch_coverage
+if TYPE_CHECKING:
+ from ..health.coverage.discovery import CoverageConfig
+
async def stored_patch_coverage(
session: AsyncSession,
@@ -23,14 +27,18 @@ async def stored_patch_coverage(
label: str = "",
head_commit: str | None = None,
threshold: float | None = None,
- min_coverable_lines: int | None = None,
- ignore: Sequence[str] = (),
+ config: CoverageConfig | None = None,
) -> PatchCoverage | None:
"""Patch coverage of *changed* against stored coverage; ``None`` when none is stored.
*head_commit* is the commit the change ends at; coverage measured anywhere
- else is marked ``stale`` in the scope. *min_coverable_lines* and *ignore*
- are the CLI gate's config; agent and REST surfaces leave them unset.
+ else is marked ``stale`` in the scope. *config* is the repository's
+ ``coverage:`` block: its ``ignore``, ``min_coverable_lines`` and ``gates``
+ apply, while ``fail_under`` does not; only the CLI gate passes *threshold*.
+ Path-scoped gates are judged only on coverage measured at the change's
+ head and with no ``gate_errors`` (invalid ``coverage.gates`` entries), the
+ only coverage and config the CLI gate itself judges; otherwise they read
+ ``no_data`` and the scope carries the errors.
"""
from repowise.core.persistence.crud import (
get_coverage_summary,
@@ -38,6 +46,8 @@ async def stored_patch_coverage(
load_file_coverage,
)
+ from ..health.coverage.discovery import CoverageConfig
+
rows = await load_coverage_for_repo(session, repository_id, include_covered_lines=False)
if not rows:
return None
@@ -47,12 +57,16 @@ async def stored_patch_coverage(
coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}
commit = summary["ingested_commit_sha"]
paths = summary["report_paths"]
+ freshness = coverage_freshness(commit, head_commit)
+ cfg = config or CoverageConfig()
return compute_patch_coverage(
changed,
coverage,
threshold=threshold,
- min_coverable_lines=min_coverable_lines,
- ignore=ignore,
+ min_coverable_lines=cfg.min_coverable_lines,
+ ignore=cfg.ignore,
+ gates=cfg.gates,
+ judge_gates=freshness == "current" and not cfg.gate_errors,
report_paths=measured,
scope=PatchScope(
label=label,
@@ -61,6 +75,7 @@ async def stored_patch_coverage(
unmatched_report_path_count=paths["unmatched"] + paths["ambiguous"] if paths else None,
mapping_partial=bool(summary["mapping_partial"]),
measured_commit=commit,
- freshness=coverage_freshness(commit, head_commit),
+ freshness=freshness,
+ config_errors=cfg.gate_errors,
),
)
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py b/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py
new file mode 100644
index 000000000..0d26319d9
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py
@@ -0,0 +1,317 @@
+"""Suggested path-scoped gates (``coverage.gates``) for ``repowise coverage suggest-gates``.
+
+Pure: each source takes what the command read (CODEOWNERS text, the files git
+tracks, each file's graph community) and returns gate proposals. Nothing here
+writes config or picks a threshold; the user keeps what they want and sets
+``fail_under`` themselves.
+"""
+
+from __future__ import annotations
+
+import json
+import posixpath
+import re
+from collections import defaultdict
+from collections.abc import Iterable, Iterator, Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+
+from ...ingestion.languages.registry import REGISTRY
+from ...test_paths import is_test_related_path
+
+#: Where GitHub and GitLab look for CODEOWNERS; the first found is read.
+CODEOWNERS_PATHS = (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", ".gitlab/CODEOWNERS")
+
+#: Directories whose children are a monorepo's packages.
+MONOREPO_ROOTS = ("packages", "apps", "services", "libs")
+
+#: A graph community with fewer source files than this is not worth a gate.
+MIN_COMMUNITY_FILES = 3
+
+#: Largest communities suggested; the rest are counted in a note.
+COMMUNITY_LIMIT = 10
+
+# CODEOWNERS patterns every file matches: a gate on them is the whole change.
+_CATCH_ALL = frozenset({"*", "**", "/**", "/*"})
+
+_SOURCE_SUFFIXES = REGISTRY.non_infra_code_extensions()
+
+# A ``#`` at the start of a line or after whitespace (space or tab) opens a comment.
+_COMMENT = re.compile(r"(?:^|\s)#.*$")
+# Fields split on whitespace a backslash does not escape (``docs/my\ file.md``).
+_FIELDS = re.compile(r"(?<!\\)\s+")
+# A GitLab section header, ``[Name]`` or ``^[Name][2]``, with optional default owners.
+_SECTION = re.compile(r"^\^?\[[^\]]+\](?:\[\d+\])?(?:\s+(.*))?$")
+_GLOB_CHARS = re.compile(r"[*?\[]")
+
+
+@dataclass(frozen=True)
+class SuggestedGate:
+ name: str
+ paths: tuple[str, ...]
+
+ def to_dict(self) -> dict[str, object]:
+ return {"name": self.name, "paths": list(self.paths)}
+
+
+@dataclass
+class GateSource:
+ """One source of suggestions: its label, where it read from, and its gates."""
+
+ source: str # "codeowners" | "layout" | "graph"
+ detail: str # what was read, or why nothing was
+ gates: list[SuggestedGate] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "source": self.source,
+ "detail": self.detail,
+ "gates": [g.to_dict() for g in self.gates],
+ }
+
+
+def codeowners_gates(text: str) -> list[SuggestedGate]:
+ """One gate per owner, over the patterns that name them.
+
+ CODEOWNERS gives a file to the last pattern matching it, and gitignore
+ globs let a later pattern win the same way, so a later pattern that may
+ overlap an owner's paths (narrower or broader) and is not theirs, owner-less
+ lines included, is carried as a ``!`` exclusion. A catch-all overrides
+ every earlier pattern, so it drops the gates before it, and is itself no
+ gate: a gate on every file is the whole-change gate. An owner whose every
+ pattern a later one fully overrides gets no gate. Under a GitLab
+ ``[Section] @owners`` header, owner-less lines take the section's owners.
+ """
+ paths: dict[str, list[str]] = {}
+ for pattern, owners in _codeowners_rules(text):
+ if pattern in _CATCH_ALL:
+ paths.clear()
+ continue
+ for owner, owned in paths.items():
+ if owner not in owners and any(_may_overlap(p, pattern) for p in owned):
+ owned.append(f"!{pattern}")
+ for owner in owners:
+ paths.setdefault(owner, []).append(pattern)
+ return [
+ SuggestedGate(_gate_name(owner), tuple(owned))
+ for owner, owned in paths.items()
+ if _any_live(owned)
+ ]
+
+
+def _codeowners_rules(text: str) -> Iterator[tuple[str, list[str]]]:
+ """``(pattern, owners)`` per rule line; owner-less lines take a GitLab section's owners."""
+ defaults: list[str] = []
+ for raw in text.splitlines():
+ line = _COMMENT.sub("", raw).strip()
+ if not line:
+ continue
+ if section := _SECTION.match(line):
+ defaults = _FIELDS.split(section.group(1)) if section.group(1) else []
+ continue
+ pattern, *owners = _FIELDS.split(line)
+ yield pattern, owners or defaults
+
+
+def layout_gates(tracked: Iterable[str]) -> list[SuggestedGate]:
+ """One gate per package of a monorepo, else per top-level source directory.
+
+ A directory counts when git tracks a source file under it that is not a
+ test. The monorepo layout wins when any of its roots holds a package.
+ """
+ sources = [p for p in tracked if _is_source(p)]
+ packages = sorted(
+ {
+ "/".join(parts[:2])
+ for parts in (PurePosixPath(p).parts for p in sources)
+ if len(parts) > 2 and parts[0] in MONOREPO_ROOTS
+ }
+ )
+ if packages:
+ # ``apps/web`` and ``packages/web`` both exist: name them by their root too.
+ leaves = [d.split("/")[1] for d in packages]
+ return [
+ SuggestedGate(d.replace("/", "-") if leaves.count(leaf) > 1 else leaf, (f"/{d}/",))
+ for d, leaf in zip(packages, leaves, strict=True)
+ ]
+ top = sorted(
+ {
+ parts[0]
+ for parts in (PurePosixPath(p).parts for p in sources)
+ if len(parts) > 1 and not parts[0].startswith(".")
+ }
+ )
+ return [SuggestedGate(d, (f"/{d}/",)) for d in top]
+
+
+def community_gates(
+ communities: Mapping[str, int], sizes: Mapping[str, int] | None = None
+) -> tuple[list[SuggestedGate], int]:
+ """Gates from graph communities (``{file: community_id}``), and how many were not tried.
+
+ Largest first, each community with at least :data:`MIN_COMMUNITY_FILES`
+ source files becomes a gate over its repository-root files and the
+ directories holding the rest, named by their longest common directory, or
+ by its largest file's stem (*sizes*, bytes) when that is the root. A
+ directory an earlier gate lists is not listed again, and a gate left with
+ fewer than :data:`MIN_COMMUNITY_FILES` of its own files is dropped.
+ Ceiling: a directory still holds other communities' files, since a glob
+ names directories, not the graph's split.
+ """
+ members: dict[int, list[str]] = defaultdict(list)
+ for path, community in communities.items():
+ if _is_source(path):
+ members[community].append(path)
+ big = sorted(
+ (sorted(files) for files in members.values() if len(files) >= MIN_COMMUNITY_FILES),
+ key=lambda files: (-len(files), files[0]),
+ )
+ gates: list[SuggestedGate] = []
+ claimed: list[str] = []
+ tried = 0
+ for files in big:
+ if len(gates) == COMMUNITY_LIMIT:
+ break
+ tried += 1
+ if gate := _community_gate(files, claimed, sizes or {}):
+ gates.append(gate)
+ return gates, len(big) - tried
+
+
+def _community_gate(
+ files: list[str], claimed: list[str], sizes: Mapping[str, int]
+) -> SuggestedGate | None:
+ """One community's gate over what no earlier gate claimed, or ``None`` when too little is left."""
+ dirs = [
+ d
+ for d in _outermost(posixpath.dirname(f) for f in files if posixpath.dirname(f))
+ if not _under(d, claimed)
+ ]
+ loose = [f for f in files if not posixpath.dirname(f)]
+ if len(loose) + sum(_under(f, dirs) for f in files) < MIN_COMMUNITY_FILES:
+ return None
+ claimed.extend(dirs)
+ globs = [f"/{f}" for f in loose] + [f"/{d}/" for d in dirs]
+ return SuggestedGate(_community_name(files, sizes), tuple(globs))
+
+
+def _community_name(files: list[str], sizes: Mapping[str, int]) -> str:
+ """The longest common directory's name, else the largest file's stem."""
+ dirs = {posixpath.dirname(f) for f in files}
+ common = "" if "" in dirs else posixpath.commonpath(sorted(dirs))
+ if common:
+ return PurePosixPath(common).name
+ largest = min(files, key=lambda f: (-sizes.get(f, 0), f))
+ return PurePosixPath(largest).stem
+
+
+def _under(path: str, dirs: Iterable[str]) -> bool:
+ """Whether *path* is one of *dirs* or inside one."""
+ return any(path == d or path.startswith(d + "/") for d in dirs)
+
+
+def unique_names(sources: Sequence[GateSource]) -> None:
+ """Rename repeats across *sources* (``core``, ``core-2``), so the YAML pastes valid."""
+ seen: set[str] = set()
+ for src in sources:
+ for i, gate in enumerate(src.gates):
+ name, n = gate.name, 2
+ while name in seen:
+ name, n = f"{gate.name}-{n}", n + 1
+ seen.add(name)
+ src.gates[i] = SuggestedGate(name, gate.paths)
+
+
+def render_yaml(sources: Sequence[GateSource]) -> str:
+ """A ``gates:`` block, indented to paste directly below a ``coverage:`` line.
+
+ Each source is labelled in a comment. Strings are written as JSON, which
+ YAML reads as-is, so a glob starting with ``*`` or ``!`` needs no quoting.
+ """
+ body: list[str] = []
+ for src in sources:
+ body.append(f" # {_SOURCE_TITLE[src.source]}: {src.detail}")
+ for gate in src.gates:
+ body.append(f" - name: {json.dumps(gate.name)}")
+ body.append(f" paths: {json.dumps(list(gate.paths))}")
+ empty = not any(src.gates for src in sources)
+ return "\n".join(
+ [
+ "# Suggested path-scoped gates. Paste directly below your `coverage:` line in",
+ "# .repowise/config.yaml, keep the ones you want and give each a fail_under (0-100).",
+ " gates: []" if empty else " gates:",
+ *body,
+ ]
+ ) + "\n"
+
+
+_SOURCE_TITLE = {
+ "codeowners": "From CODEOWNERS",
+ "layout": "From top-level packages",
+ "graph": "From graph communities",
+}
+
+
+def _is_source(path: str) -> bool:
+ return PurePosixPath(path).suffix in _SOURCE_SUFFIXES and not is_test_related_path(path)
+
+
+def _gate_name(owner: str) -> str:
+ """``@org/team`` -> ``org-team``; an email owner keeps its local part."""
+ return owner.lstrip("@").split("@", 1)[0].replace("/", "-")
+
+
+def _may_overlap(owned: str, later: str) -> bool:
+ """Whether two patterns could match one file, either the broader. Errs towards yes.
+
+ Exclusions (``!``) in *owned* never need excluding again.
+ """
+ if owned.startswith("!"):
+ return False
+ a, b = _anchor(owned), _anchor(later)
+ if not a or not b: # floating, or anchored at the root with a glob
+ return True
+ return a == b or a.startswith(b + "/") or b.startswith(a + "/")
+
+
+def _any_live(globs: Sequence[str]) -> bool:
+ """Whether some pattern in *globs* is not fully overridden by a later ``!`` exclusion."""
+ return any(
+ not p.startswith("!")
+ and not any(g.startswith("!") and _covers(g[1:], p) for g in globs[i + 1 :])
+ for i, p in enumerate(globs)
+ )
+
+
+def _covers(later: str, earlier: str) -> bool:
+ """Whether literal *later* matches every file *earlier* does (a directory above it)."""
+ top, below = _anchor(later), _anchor(earlier)
+ if not top or below is None or _GLOB_CHARS.search(later):
+ return False
+ return below == top or below.startswith(top + "/")
+
+
+def _anchor(pattern: str) -> str | None:
+ """The literal directory (or file) a pattern is confined to; ``None`` when it floats.
+
+ Gitignore rules: a pattern with a ``/`` before its last character is
+ anchored at the root, one without matches at any depth. ``""`` is an
+ anchored pattern whose first path segment is already a glob.
+ """
+ core = pattern.rstrip("/")
+ if "/" not in core:
+ return None
+ core = core.lstrip("/")
+ head = _GLOB_CHARS.split(core, maxsplit=1)[0]
+ if head == core:
+ return core
+ return head.rsplit("/", 1)[0] if "/" in head else ""
+
+
+def _outermost(dirs: Iterable[str]) -> list[str]:
+ """*dirs* without any whose ancestor is also listed."""
+ kept: list[str] = []
+ for d in sorted(set(dirs)):
+ if not any(d.startswith(k + "/") for k in kept):
+ kept.append(d)
+ return kept
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 cd4408ef0..1db4d6cda 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
@@ -1114,11 +1114,14 @@ async def _patch_coverage_block(
coverage the index stores. ``None`` when there is no index, no stored
coverage, or no readable change: ``impacted_tests`` already says why.
``files`` lists only the files that need attention, capped; the totals and
- ``file_counts`` still count every file.
+ ``file_counts`` still count every file. ``coverage.ignore``,
+ ``coverage.min_coverable_lines`` and the path-scoped ``coverage.gates``
+ apply as they do in the CLI gate; path gates read ``no_data`` on stale
+ coverage or invalid config, which ``scope.config_errors`` names.
"""
from repowise.core import git_refs
from repowise.core.analysis.change_risk.features import revspec_head
- from repowise.core.analysis.health.coverage import configured_ignore
+ from repowise.core.analysis.health.coverage import configured_coverage
from repowise.core.analysis.patch_coverage import attention_rows, stored_patch_coverage
from repowise.core.persistence.database import get_session
@@ -1137,7 +1140,7 @@ async def _patch_coverage_block(
changed,
label=result.features.ref,
head_commit=head_commit,
- ignore=configured_ignore(ctx.path),
+ config=configured_coverage(ctx.path),
)
except (LookupError, SQLAlchemyError):
return 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.py
index f6af5cba3..87371b5d9 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
@@ -378,9 +378,11 @@ async def health_coverage_patch(
The computation ``repowise coverage check`` gates on. ``null`` when no
coverage has been ingested, which is not the same as 0%. Honours
- ``coverage.ignore``; the small-change tolerance stays with the CLI gate.
+ ``coverage.ignore`` and judges the path-scoped gates in ``coverage.gates``
+ (with ``coverage.min_coverable_lines``) on current coverage and valid
+ config; the whole-change threshold stays with the CLI gate.
"""
- from repowise.core.analysis.health.coverage import configured_ignore
+ from repowise.core.analysis.health.coverage import configured_coverage
from repowise.core.analysis.patch_coverage import stored_patch_coverage
changed, label, head_sha = await asyncio.to_thread(_read_change, repo.local_path, base, head)
@@ -390,6 +392,6 @@ async def health_coverage_patch(
changed,
label=label,
head_commit=head_sha or None,
- ignore=configured_ignore(repo.local_path),
+ config=configured_coverage(repo.local_path),
)
return PatchCoverageResponse.model_validate(patch.to_dict()) if patch is not None else None
diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.py
index c4da540ab..4491c23fe 100644
--- a/packages/server/src/repowise/server/schemas/patch_coverage.py
+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py
@@ -52,6 +52,29 @@ class PatchCoverageScope(_Strict):
freshness: FreshnessStatus
#: Changed files left out by ``coverage.ignore`` before measuring.
ignored_file_count: int
+ #: Invalid ``coverage.gates`` entries, one message each; while any is
+ #: present no path-scoped gate is judged.
+ config_errors: list[str]
+
+
+class PatchCoveragePathGate(_Strict):
+ """One path-scoped gate from ``coverage.gates``, judged on the change."""
+
+ name: str
+ #: Gitignore-style globs naming the gate's files.
+ paths: list[str]
+ threshold: float | None
+ #: Judged and shown, but never fails the change.
+ informational: bool
+ #: Measured changed files the globs match; a file may count in several gates.
+ measured_file_count: int
+ #: Matching changed files the report does not measure, outside the percentage.
+ unmeasured_file_count: int
+ covered_line_count: int
+ coverable_line_count: int
+ patch_coverage_pct: float | None
+ #: ``no_data`` too when not judged: stale coverage or ``scope.config_errors``.
+ gate: GateStatus
class PatchCoverageResponse(_Strict):
@@ -66,3 +89,5 @@ class PatchCoverageResponse(_Strict):
file_counts: PatchCoverageFileCounts
files: list[PatchCoverageFile]
scope: PatchCoverageScope
+ #: ``gate`` reads ``fail`` when any one here fails and is not informational.
+ path_gates: list[PatchCoveragePathGate]
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 2e06ec799..fa0f98538 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2210,6 +2210,20 @@ export interface PatchCoverageFileCounts {
out_of_scope: number;
}
+/** One path-scoped gate from ``coverage.gates``, judged on the change. */
+export interface PatchCoveragePathGate {
+ name: string;
+ paths: string[];
+ threshold: number | null;
+ informational: boolean;
+ measured_file_count: number;
+ unmeasured_file_count: number;
+ covered_line_count: number;
+ coverable_line_count: number;
+ patch_coverage_pct: number | null;
+ gate: "pass" | "fail" | "no_data" | "not_set" | "too_small";
+}
+
export interface PatchCoverageResponse {
patch_coverage_pct: number | null;
covered_line_count: number;
@@ -2220,6 +2234,7 @@ export interface PatchCoverageResponse {
file_counts: PatchCoverageFileCounts;
files: PatchCoverageFile[];
scope: PatchCoverageScope;
+ path_gates: PatchCoveragePathGate[];
}
export interface PatchCoverageScope {
@@ -2232,6 +2247,7 @@ export interface PatchCoverageScope {
measured_commit: string | null;
freshness: "current" | "stale" | "unknown";
ignored_file_count: number;
+ config_errors: string[];
}
/**
diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
index 36221fcf6..c0a48e64d 100644
--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
@@ -1,6 +1,9 @@
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
-import type { PatchCoverageResponse } from "@repowise-dev/types/generated/http";
+import type {
+ PatchCoveragePathGate,
+ PatchCoverageResponse,
+} from "@repowise-dev/types/generated/http";
import {
PatchCoverageSummary,
floorPct,
@@ -41,7 +44,28 @@ function coverage(fileCount: number): PatchCoverageResponse {
mapping_partial: false,
freshness: "current",
ignored_file_count: 0,
+ config_errors: [],
},
+ path_gates: [],
+ };
+}
+
+function pathGate(
+ name: string,
+ gate: PatchCoveragePathGate["gate"],
+ informational = false,
+): PatchCoveragePathGate {
+ return {
+ name,
+ paths: [`/${name}/`],
+ threshold: 80,
+ informational,
+ measured_file_count: 1,
+ unmeasured_file_count: 0,
+ covered_line_count: 1,
+ coverable_line_count: 2,
+ patch_coverage_pct: 50,
+ gate,
};
}
@@ -78,6 +102,45 @@ describe("PatchCoverageSummary", () => {
expect(screen.queryByText(/ignored by/)).toBeNull();
});
+ it("marks stale coverage and lists what the report does not measure", () => {
+ const base = coverage(1);
+ render(
+ <PatchCoverageSummary
+ coverage={{
+ ...base,
+ files: [
+ {
+ file_path: "src/core.ts",
+ status: "measured",
+ changed_line_count: 5,
+ coverable_line_count: 3,
+ covered_line_count: 2,
+ patch_coverage_pct: 66.66,
+ uncovered_ranges: [
+ [3, 3],
+ [7, 9],
+ ],
+ },
+ {
+ file_path: "src/new.ts",
+ status: "not_in_report",
+ changed_line_count: 4,
+ coverable_line_count: 0,
+ covered_line_count: 0,
+ patch_coverage_pct: null,
+ uncovered_ranges: [],
+ },
+ ],
+ scope: { ...base.scope, freshness: "stale" },
+ }}
+ />,
+ );
+ expect(screen.getByText("abcdef1")).toBeTruthy();
+ 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();
+ });
+
it("counts changed files coverage.ignore left out", () => {
const base = coverage(1);
render(
@@ -87,4 +150,69 @@ describe("PatchCoverageSummary", () => {
);
expect(screen.getByText(/2 changed files ignored by/)).toBeTruthy();
});
+
+ it("lists path-scoped gates with a verdict in words", () => {
+ render(
+ <PatchCoverageSummary
+ coverage={{
+ ...coverage(1),
+ path_gates: [pathGate("api", "fail"), pathGate("docs", "fail", true)],
+ }}
+ />,
+ );
+ const list = screen.getByRole("list", { name: "Path-scoped gates" });
+ expect(list.textContent).toContain("api");
+ expect(screen.getByText("fails")).toBeTruthy();
+ // An informational miss never reads as a failure.
+ expect(screen.getByText("below threshold (informational)")).toBeTruthy();
+ expect(screen.getAllByText("1 of 2 (50.0%) · gate 80.0%")).toHaveLength(2);
+ // A visible label heads the list.
+ expect(screen.getByText("Path-scoped gates")).toBeTruthy();
+ });
+
+ it("says why a gate is not judged and counts unmeasured files", () => {
+ const base = coverage(1);
+ render(
+ <PatchCoverageSummary
+ coverage={{
+ ...base,
+ scope: { ...base.scope, config_errors: ["coverage.gates[1]: bad"] },
+ path_gates: [
+ pathGate("api", "no_data"),
+ {
+ ...pathGate("new", "no_data"),
+ covered_line_count: 0,
+ coverable_line_count: 0,
+ patch_coverage_pct: null,
+ unmeasured_file_count: 2,
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByText(/1 invalid entry in/)).toBeTruthy();
+ expect(screen.getByText("not judged")).toBeTruthy();
+ expect(
+ screen.getByText("no measured changed lines (2 changed files not measured)"),
+ ).toBeTruthy();
+ });
+
+ it("shows no gate list without path-scoped gates", () => {
+ render(<PatchCoverageSummary coverage={coverage(1)} />);
+ expect(screen.queryByRole("list", { name: "Path-scoped gates" })).toBeNull();
+ expect(screen.queryByText(/invalid entr/)).toBeNull();
+ });
+
+ it("renders a response from a server older than path-scoped gates", () => {
+ const base = coverage(1);
+ const { path_gates: _gates, ...older } = base;
+ const { config_errors: _errors, ...olderScope } = base.scope;
+ render(
+ <PatchCoverageSummary
+ coverage={{ ...older, scope: olderScope } as unknown as PatchCoverageResponse}
+ />,
+ );
+ expect(screen.getByText("1 of 2 changed executable lines covered")).toBeTruthy();
+ expect(screen.queryByRole("list", { name: "Path-scoped gates" })).toBeNull();
+ });
});
diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsx
index b2ddfc0a4..640e42b85 100644
--- a/packages/ui/src/health/patch-coverage-summary.tsx
+++ b/packages/ui/src/health/patch-coverage-summary.tsx
@@ -5,11 +5,15 @@
* A verdict sentence, not a figure with a band. There is no threshold here to
* colour against, and a gate belongs to CI (`repowise coverage check`), so the
* only marked state is stale evidence: coverage measured at another commit
- * describes other code, and the line numbers below it may not line up.
+ * describes other code, and the line numbers below it may not line up. The
+ * exception is path-scoped gates (`coverage.gates`), which carry their own
+ * thresholds: each is a dot plus a word.
*/
+import type { ReactNode } from "react";
import type {
PatchCoverageFile,
+ PatchCoveragePathGate,
PatchCoverageResponse,
} from "@repowise-dev/types/generated/http";
@@ -37,15 +41,33 @@ export function formatLineRanges(ranges: number[][]): string {
.join(", ");
}
-function plural(n: number, word: string): string {
- return `${n} ${word}${n === 1 ? "" : "s"}`;
+function plural(n: number, word: string, many?: string): string {
+ return `${n} ${n === 1 ? word : (many ?? `${word}s`)}`;
}
+type Tone = "error" | "warning" | "success" | "neutral";
+
+const DOT: Record<Tone, string> = {
+ error: "bg-[var(--color-error)]",
+ warning: "bg-[var(--color-warning)]",
+ success: "bg-[var(--color-success)]",
+ neutral: "bg-[var(--color-text-tertiary)]",
+};
+
+/** A path-scoped gate's verdict in words, as `coverage check` prints it. Red
+ * is kept for a gate that fails the change. */
+const GATE_STATUS: Record<PatchCoveragePathGate["gate"], { text: string; tone: Tone }> = {
+ pass: { text: "passes", tone: "success" },
+ fail: { text: "fails", tone: "error" },
+ no_data: { text: "no measured changed lines", tone: "neutral" },
+ not_set: { text: "no threshold", tone: "neutral" },
+ too_small: { text: "too few changed lines to judge", tone: "neutral" },
+};
+
export function PatchCoverageSummary({
coverage,
onOpenFile,
}: PatchCoverageSummaryProps) {
- const pct = coverage.patch_coverage_pct;
const uncovered = coverage.files.filter(
(f) => f.status === "measured" && f.uncovered_ranges.length > 0,
);
@@ -56,60 +78,21 @@ export function PatchCoverageSummary({
return (
<div className="flex flex-col gap-1.5">
- <p className="text-[15px] text-[var(--color-text-secondary)]">
- {pct == null ? (
- // Unknown is a sentence, never 0%: nothing the report measured changed.
- <>
- <span className="font-semibold text-[var(--color-text-primary)]">
- Patch coverage not measured
- </span>{" "}
- · no changed line is an executable line the coverage report measured
- </>
- ) : (
- <>
- <span className="font-semibold text-[var(--color-text-primary)]">
- Patch coverage{" "}
- <span className="tabular-nums">{floorPct(pct)}%</span>
- </span>{" "}
- ·{" "}
- <span className="tabular-nums">
- {coverage.covered_line_count} of{" "}
- {plural(coverage.coverable_line_count, "changed executable line")}{" "}
- covered
- </span>
- </>
- )}
- </p>
+ <Headline coverage={coverage} />
{coverage.scope.freshness === "stale" && (
- <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
- <span
- aria-hidden
- className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]"
- />
- <span>
- <span className="sr-only">Stale: </span>
- Coverage was measured at{" "}
- {measuredAt ? (
- <code className="font-mono">{measuredAt}</code>
- ) : (
- "another commit"
- )}
- , not at this change&apos;s head
- </span>
- </p>
+ <WarningNote>
+ <span className="sr-only">Stale: </span>
+ Coverage was measured at{" "}
+ {measuredAt ? <code className="font-mono">{measuredAt}</code> : "another commit"}
+ , not at this change&apos;s head
+ </WarningNote>
)}
{coverage.scope.mapping_partial && (
- <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
- <span
- aria-hidden
- className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]"
- />
- <span>
- Most report paths did not match this repository, so this covers a fragment
- </span>
- </p>
+ <WarningNote>
+ Most report paths did not match this repository, so this covers a fragment
+ </WarningNote>
)}
{coverage.scope.ignored_file_count > 0 && (
@@ -119,6 +102,12 @@ export function PatchCoverageSummary({
</p>
)}
+ {/* Guarded: a server older than path-scoped gates sends neither field. */}
+ <PathGates
+ gates={coverage.path_gates ?? []}
+ configErrors={coverage.scope.config_errors ?? []}
+ />
+
{uncovered.length > 0 && (
<ul className="mt-1 flex flex-col gap-0.5">
{uncovered.slice(0, MAX_FILES).map((f) => (
@@ -161,6 +150,120 @@ export function PatchCoverageSummary({
);
}
+function Headline({ coverage }: { coverage: PatchCoverageResponse }) {
+ const pct = coverage.patch_coverage_pct;
+ return (
+ <p className="text-[15px] text-[var(--color-text-secondary)]">
+ {pct == null ? (
+ // Unknown is a sentence, never 0%: nothing the report measured changed.
+ <>
+ <span className="font-semibold text-[var(--color-text-primary)]">
+ Patch coverage not measured
+ </span>{" "}
+ · no changed line is an executable line the coverage report measured
+ </>
+ ) : (
+ <>
+ <span className="font-semibold text-[var(--color-text-primary)]">
+ Patch coverage <span className="tabular-nums">{floorPct(pct)}%</span>
+ </span>{" "}
+ ·{" "}
+ <span className="tabular-nums">
+ {coverage.covered_line_count} of{" "}
+ {plural(coverage.coverable_line_count, "changed executable line")} covered
+ </span>
+ </>
+ )}
+ </p>
+ );
+}
+
+/** An amber dot plus a sentence: evidence to read with care. */
+function WarningNote({ children }: { children: ReactNode }) {
+ return (
+ <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ <span aria-hidden className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${DOT.warning}`} />
+ <span>{children}</span>
+ </p>
+ );
+}
+
+/** Path-scoped gates (`coverage.gates`): why none is judged, then each one. */
+function PathGates({
+ gates,
+ configErrors,
+}: {
+ gates: PatchCoveragePathGate[];
+ configErrors: string[];
+}) {
+ return (
+ <>
+ {configErrors.length > 0 && (
+ <WarningNote>
+ {plural(configErrors.length, "invalid entry", "invalid entries")} in{" "}
+ <code className="font-mono">coverage.gates</code>, so no path-scoped gate is
+ judged
+ </WarningNote>
+ )}
+ {gates.length > 0 && (
+ <div className="mt-1 flex flex-col gap-0.5">
+ {/* The list carries the same name, so the visible label is not read twice. */}
+ <p aria-hidden className="px-1.5 text-xs text-[var(--color-text-tertiary)]">
+ Path-scoped gates
+ </p>
+ <ul aria-label="Path-scoped gates" className="flex flex-col gap-0.5">
+ {gates.map((g) => (
+ <PathGateRow key={g.name} gate={g} />
+ ))}
+ </ul>
+ </div>
+ )}
+ </>
+ );
+}
+
+function gateStatus(gate: PatchCoveragePathGate): { text: string; tone: Tone } {
+ if (gate.gate === "fail" && gate.informational) {
+ return { text: "below threshold", tone: "warning" };
+ }
+ if (gate.gate !== "no_data") return GATE_STATUS[gate.gate];
+ // Counted but not judged: stale coverage or invalid config, said above.
+ if (gate.coverable_line_count > 0) return { text: "not judged", tone: "neutral" };
+ const unmeasured = gate.unmeasured_file_count ?? 0;
+ const text = GATE_STATUS.no_data.text;
+ return unmeasured > 0
+ ? { text: `${text} (${plural(unmeasured, "changed file")} not measured)`, tone: "neutral" }
+ : GATE_STATUS.no_data;
+}
+
+function gateFigures(gate: PatchCoveragePathGate): string {
+ const pct = gate.patch_coverage_pct;
+ const covered =
+ pct == null
+ ? "n/a"
+ : `${gate.covered_line_count} of ${gate.coverable_line_count} (${floorPct(pct)}%)`;
+ return gate.threshold == null ? covered : `${covered} · gate ${floorPct(gate.threshold)}%`;
+}
+
+function PathGateRow({ gate }: { gate: PatchCoveragePathGate }) {
+ const { text, tone } = gateStatus(gate);
+ return (
+ <li className="flex items-center gap-2 px-1.5 py-0.5 text-xs" title={gate.paths.join(", ")}>
+ <span aria-hidden className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${DOT[tone]}`} />
+ <span className="min-w-0 flex-1 truncate font-mono text-[var(--color-text-primary)]">
+ {gate.name}
+ </span>
+ <span className="shrink-0 text-[var(--color-text-secondary)]">
+ {text}
+ {gate.informational ? " (informational)" : ""}
+ </span>
+ <span className="shrink-0 font-mono tabular-nums text-[var(--color-text-tertiary)]">
+ {gateFigures(gate)}
+ </span>
+ </li>
+ );
+}
+
function FileRow({
file,
trailing,
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index 7a929911a..a1492496d 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -111,7 +111,22 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
mapping_partial: false,
freshness: "stale",
ignored_file_count: 0,
+ config_errors: [],
},
+ path_gates: [
+ {
+ name: "web-app",
+ paths: ["/src/"],
+ threshold: 80,
+ informational: false,
+ measured_file_count: 1,
+ unmeasured_file_count: 0,
+ covered_line_count: 2,
+ coverable_line_count: 3,
+ patch_coverage_pct: 66.66,
+ gate: "fail",
+ },
+ ],
};
const REPO: RepoInit = {
@@ -468,15 +483,9 @@ describe("risk App", () => {
/>,
);
- // Floored, never rounded up: 66.66 reads 66.6.
+ // The panel renders the shared summary, whose own tests own the wording.
expect(await screen.findByText("66.6%")).toBeTruthy();
- expect(
- screen.getByText("2 of 3 changed executable lines covered"),
- ).toBeTruthy();
- expect(screen.getByText("abcdef1")).toBeTruthy();
- 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.getByRole("list", { name: "Path-scoped gates" })).toBeTruthy();
fireEvent.click(screen.getByTitle("Open src/core.ts"));
expect(openFile).toHaveBeenCalledWith("src/core.ts");
diff --git a/tests/unit/analysis/test_patch_coverage.py b/tests/unit/analysis/test_patch_coverage.py
index 7fe17544e..96f8e866f 100644
--- a/tests/unit/analysis/test_patch_coverage.py
+++ b/tests/unit/analysis/test_patch_coverage.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from repowise.core.analysis.changed_lines import line_ranges
-from repowise.core.analysis.health.coverage import file_coverage
+from repowise.core.analysis.health.coverage import PathGate, file_coverage
from repowise.core.analysis.patch_coverage import (
PatchScope,
compute_patch_coverage,
@@ -256,3 +256,384 @@ def test_serialized_percentage_is_floored_not_rounded() -> None:
{"a.py": set(coverable)}, _cov("a.py", coverable[:31999], coverable), threshold=80
)
assert pc.to_dict()["patch_coverage_pct"] == 79.99
+
+
+# -- path-scoped gates -------------------------------------------------------
+
+
+def _two_packages():
+ """``api`` is 1 of 4 covered, ``web`` 4 of 4: 5 of 8 (62.5%) over the change."""
+ coverage = {
+ **_cov("api/a.py", covered=[1], coverable=[1, 2, 3, 4]),
+ **_cov("web/b.py", covered=[1, 2, 3, 4], coverable=[1, 2, 3, 4]),
+ }
+ return {"api/a.py": {1, 2, 3, 4}, "web/b.py": {1, 2, 3, 4}}, coverage
+
+
+def test_path_gate_judges_only_its_files() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed,
+ coverage,
+ threshold=50,
+ gates=[PathGate("api", ("/api/",), 80), PathGate("web", ("web/**",), 80)],
+ )
+
+ api, web = pc.path_gates
+ assert (api.measured_file_count, api.covered_line_count, api.coverable_line_count) == (1, 1, 4)
+ assert (api.patch_coverage_pct, api.gate) == (25.0, "fail")
+ assert (web.patch_coverage_pct, web.gate) == (100.0, "pass")
+ # The whole change meets its own gate; the failing path gate fails it.
+ assert pc.flat_gate == "pass"
+ assert pc.gate == "fail"
+ assert pc.to_dict()["gate"] == "fail"
+
+
+def test_informational_path_gate_never_fails_the_change() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed, coverage, gates=[PathGate("api", ("/api/",), 80, informational=True)]
+ )
+
+ assert pc.path_gates[0].gate == "fail"
+ assert pc.gate == "not_set"
+ lines = github_annotations(pc)
+ assert not any(line.startswith("::error") for line in lines)
+ # Below its threshold is still said, as a notice.
+ assert lines[0] == (
+ "::notice::Informational: path-scoped gate api 25.0%25 (1 of 4 changed executable "
+ "lines), below its 80.0%25 gate."
+ )
+ assert not headline(pc).startswith("Fails")
+
+
+def test_a_file_can_count_in_several_path_gates() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed,
+ coverage,
+ gates=[PathGate("all", ("*.py",), 50), PathGate("api", ("api/",), 20)],
+ )
+
+ everything, api = pc.path_gates
+ assert everything.measured_file_count == 2
+ assert (everything.covered_line_count, everything.coverable_line_count) == (5, 8)
+ assert api.measured_file_count == 1
+ # Passing path gates fail nothing, and set no whole-change verdict either.
+ assert pc.gate == "not_set"
+
+
+def test_path_gate_without_files_or_threshold() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed,
+ coverage,
+ threshold=10,
+ gates=[PathGate("docs", ("/docs/",), 80), PathGate("api", ("/api/",))],
+ )
+
+ docs, api = pc.path_gates
+ assert docs.measured_file_count == 0
+ assert docs.patch_coverage_pct is None
+ assert docs.gate == "no_data"
+ assert docs.to_dict()["patch_coverage_pct"] is None
+ assert api.gate == "not_set"
+ assert pc.gate == "pass"
+
+
+def test_path_gate_counts_its_unmeasured_files() -> None:
+ coverage = _cov("src/a.py", covered=[1], coverable=[1])
+ pc = compute_patch_coverage(
+ {"src/a.py": {1}, "new/x.py": {1}, "new/y.py": {2}},
+ coverage,
+ gates=[PathGate("new", ("/new/",), 80)],
+ )
+
+ (gate,) = pc.path_gates
+ assert (gate.measured_file_count, gate.unmeasured_file_count, gate.gate) == (0, 2, "no_data")
+ assert "| `new` | no measured changed lines (2 changed files not measured) | n/a | 80.0% |" in (
+ render_markdown(pc)
+ )
+
+
+def test_small_change_tolerance_is_the_whole_changes() -> None:
+ changed, coverage = _two_packages()
+ gates = [PathGate("api", ("/api/",), 80)]
+
+ # A 4-line slice of an 8-line change is not a small change.
+ big = compute_patch_coverage(changed, coverage, min_coverable_lines=5, gates=gates)
+ assert big.path_gates[0].gate == "fail"
+ assert big.gate == "fail"
+ # The whole change under the minimum exempts every gate.
+ small = compute_patch_coverage(changed, coverage, min_coverable_lines=10, gates=gates)
+ assert small.path_gates[0].gate == "too_small"
+ assert small.gate == "not_set"
+
+
+def test_unjudged_path_gates_read_no_data_but_keep_their_counts() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed, coverage, gates=[PathGate("api", ("/api/",), 80)], judge_gates=False
+ )
+
+ (gate,) = pc.path_gates
+ assert (gate.gate, gate.coverable_line_count) == ("no_data", 4)
+ assert pc.gate == "not_set"
+ assert "| `api` | not judged | 1 of 4 (25.0%) | 80.0% |" in render_markdown(pc)
+
+
+def test_path_gate_pct_floors_like_the_whole_change() -> None:
+ coverage = _cov("a.py", covered=[1, 2], coverable=[1, 2, 3])
+ pc = compute_patch_coverage(
+ {"a.py": {1, 2, 3}}, coverage, gates=[PathGate("a", ("a.py",), 66.67)]
+ )
+
+ (gate,) = pc.path_gates
+ # 66.666...% is below 66.67% unrounded, and serialises floored.
+ assert gate.gate == "fail"
+ assert gate.to_dict()["patch_coverage_pct"] == 66.66
+
+
+def test_path_gate_to_dict_shape() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(changed, coverage, gates=[PathGate("api", ("/api/",), 80)])
+
+ assert pc.to_dict()["path_gates"] == [
+ {
+ "name": "api",
+ "paths": ["/api/"],
+ "threshold": 80,
+ "informational": False,
+ "measured_file_count": 1,
+ "unmeasured_file_count": 0,
+ "covered_line_count": 1,
+ "coverable_line_count": 4,
+ "patch_coverage_pct": 25.0,
+ "gate": "fail",
+ }
+ ]
+ assert pc.to_dict()["scope"]["config_errors"] == []
+ assert compute_patch_coverage(changed, coverage).to_dict()["path_gates"] == []
+
+
+def test_failing_path_gate_renders_in_headline_markdown_and_annotations() -> None:
+ changed, coverage = _two_packages()
+ pc = compute_patch_coverage(
+ changed,
+ coverage,
+ threshold=50,
+ gates=[
+ PathGate("api", ("/api/",), 80),
+ PathGate("web", ("/web/",), 80),
+ PathGate("docs", ("/docs/",), 80, informational=True),
+ ],
+ )
+
+ # The failure leads, with its counts; the whole-change verdict follows.
+ assert headline(pc, markdown=False) == (
+ "Fails: path-scoped gate api 25.0% (1 of 4 changed executable lines), below its "
+ "80.0% gate. Patch coverage 62.5% (5 of 8 changed executable lines covered) "
+ "· meets the 50.0% gate"
+ )
+ md = render_markdown(pc)
+ assert "| Path-scoped gate | Verdict | Covered changed lines | Threshold |" in md
+ assert "| `api` | fails | 1 of 4 (25.0%) | 80.0% |" in md
+ assert "| `web` | passes | 4 of 4 (100.0%) | 80.0% |" in md
+ assert "| `docs` | no measured changed lines (informational) | n/a | 80.0% |" in md
+ errors = [line for line in github_annotations(pc) if line.startswith("::error")]
+ assert errors == [
+ "::error::Fails: path-scoped gate api 25.0%25 (1 of 4 changed executable lines), "
+ "below its 80.0%25 gate."
+ ]
+
+
+def test_path_gate_table_is_capped_with_failing_gates_first() -> None:
+ changed, coverage = _two_packages()
+ gates = [PathGate(f"g{i}", ("/api/",)) for i in range(12)]
+ gates.append(PathGate("late", ("/api/",), 80))
+ md = render_markdown(compute_patch_coverage(changed, coverage, gates=gates))
+
+ # The failing gate sits past the cap in config, but leads the table.
+ rows = [line for line in md.splitlines() if line.startswith("| `")]
+ assert rows[0].startswith("| `late` | fails")
+ assert "| `g8` |" in md
+ assert "| `g9` |" not in md
+ assert "and 3 more path-scoped gates." in md
+
+
+def test_no_path_gate_table_without_gates() -> None:
+ changed, coverage = _two_packages()
+ assert "Path-scoped" not in render_markdown(compute_patch_coverage(changed, coverage))
+
+
+# -- suggested gates ---------------------------------------------------------
+
+
+def test_community_gates_name_by_common_directory_and_skip_tiny_ones() -> None:
+ from repowise.core.analysis.patch_coverage.suggest import COMMUNITY_LIMIT, community_gates
+
+ communities = {
+ "svc/api/a.py": 1,
+ "svc/api/deep/b.py": 1,
+ "svc/web/c.py": 1,
+ "svc/web/d.py": 1,
+ "svc/api/test_a.py": 1, # a test: not a source file
+ "main.py": 2,
+ "lib/x.py": 2,
+ "lib/y.py": 2,
+ "tiny/one.py": 3,
+ }
+ # Enough three-file communities to overflow the limit.
+ for i in range(COMMUNITY_LIMIT):
+ communities.update({f"pkg{i:02}/{n}.py": 100 + i for n in "abc"})
+
+ gates, cut = community_gates(communities)
+
+ by_name = {g.name: g.paths for g in gates}
+ assert len(gates) == COMMUNITY_LIMIT
+ assert cut == 2
+ # Nested directories collapse to the outermost; the name is the common one.
+ assert by_name["svc"] == ("/svc/api/", "/svc/web/")
+ assert "tiny" not in by_name
+
+
+def test_community_gates_keep_repository_root_files() -> None:
+ from repowise.core.analysis.patch_coverage.suggest import community_gates
+
+ communities = {"main.py": 1, "lib/x.py": 1, "lib/y.py": 1}
+ gates, _ = community_gates(communities, {"main.py": 900, "lib/x.py": 100})
+
+ # Rooted at the repository root: named after its largest file.
+ assert [(g.name, g.paths) for g in gates] == [("main", ("/main.py", "/lib/"))]
+
+
+def test_community_gates_on_a_flat_layout_claim_each_directory_once() -> None:
+ from repowise.core.analysis.patch_coverage.suggest import (
+ GateSource,
+ community_gates,
+ unique_names,
+ )
+
+ # A flat Go module: loose root files, one shared doc/ directory.
+ communities = {
+ "command.go": 1,
+ "help.go": 1,
+ "run.go": 1,
+ "doc/man.go": 1,
+ "doc/md.go": 1,
+ "args.go": 2,
+ "shell.go": 2,
+ "complete.go": 2,
+ "doc/rest.go": 2,
+ "cobra.go": 3,
+ "doc/util.go": 3,
+ "doc/yaml.go": 3,
+ }
+ sizes = {"command.go": 5000, "complete.go": 3000, "cobra.go": 800}
+
+ gates, cut = community_gates(communities, sizes)
+
+ assert [(g.name, g.paths) for g in gates] == [
+ ("command", ("/command.go", "/help.go", "/run.go", "/doc/")),
+ # doc/ is the first gate's; three loose files are enough on their own.
+ ("complete", ("/args.go", "/complete.go", "/shell.go")),
+ ]
+ # The third keeps one loose file once doc/ is claimed: too few, dropped.
+ assert cut == 0
+ source = GateSource("graph", "the index", gates)
+ unique_names([source])
+ assert len({g.name for g in source.gates}) == len(source.gates)
+
+
+def test_layout_gates_name_clashing_packages_by_their_root() -> None:
+ from repowise.core.analysis.patch_coverage.suggest import layout_gates
+
+ gates = layout_gates(["apps/web/a.ts", "packages/web/b.ts", "packages/core/c.py", "x.py"])
+
+ assert [(g.name, g.paths) for g in gates] == [
+ ("apps-web", ("/apps/web/",)),
+ ("core", ("/packages/core/",)),
+ ("packages-web", ("/packages/web/",)),
+ ]
+
+
+def test_suggested_yaml_pastes_below_the_coverage_line() -> None:
+ import yaml
+
+ from repowise.core.analysis.patch_coverage.suggest import (
+ GateSource,
+ SuggestedGate,
+ render_yaml,
+ )
+
+ empty = render_yaml([GateSource("codeowners", "no CODEOWNERS file")])
+ assert yaml.safe_load("coverage:\n" + empty) == {"coverage": {"gates": []}}
+ assert " # From CODEOWNERS: no CODEOWNERS file" in empty
+ text = render_yaml([GateSource("layout", "git ls-files", [SuggestedGate("api", ("/api/",))])])
+ assert "directly below your `coverage:` line" in text
+ assert yaml.safe_load("coverage:\n fail_under: 80\n" + text) == {
+ "coverage": {"fail_under": 80, "gates": [{"name": "api", "paths": ["/api/"]}]}
+ }
+
+
+# -- CODEOWNERS ----------------------------------------------------------------
+
+
+def _owners(text: str) -> dict[str, tuple[str, ...]]:
+ from repowise.core.analysis.patch_coverage.suggest import codeowners_gates
+
+ return {g.name: g.paths for g in codeowners_gates(text)}
+
+
+def test_codeowners_later_narrower_pattern_is_excluded() -> None:
+ assert _owners("/pkg/ @a\n/pkg/web/ @b\n") == {"a": ("/pkg/", "!/pkg/web/"), "b": ("/pkg/web/",)}
+
+
+def test_codeowners_later_broader_pattern_overrides_and_drops_the_gate() -> None:
+ # /pkg/ @b wins every file /pkg/api/ matched, so @a has no gate left.
+ assert _owners("/pkg/api/ @a\n/pkg/ @b\n") == {"b": ("/pkg/",)}
+ # Only partly overridden: the exclusion stays.
+ assert _owners("/pkg/api/ @a\n/lib/ @a\n/pkg/ @b\n") == {
+ "a": ("/pkg/api/", "/lib/", "!/pkg/"),
+ "b": ("/pkg/",),
+ }
+
+
+def test_codeowners_ownerless_line_excludes_without_a_gate() -> None:
+ assert _owners("/pkg/ @a\n/pkg/vendor/\n") == {"a": ("/pkg/", "!/pkg/vendor/")}
+
+
+def test_codeowners_trailing_catch_all_drops_earlier_gates() -> None:
+ assert _owners("/pkg/ @a\n/lib/ @b\n* @c\n/docs/ @d\n") == {"d": ("/docs/",)}
+ # A leading catch-all overrides nothing after it.
+ assert _owners("* @c\n/pkg/ @a\n") == {"a": ("/pkg/",)}
+
+
+def test_codeowners_escaped_spaces_tab_comments_and_emails() -> None:
+ text = "/docs/my\\ file.md\t@a # the doc\n/src/\[email protected]\t# tab comment\n"
+ assert _owners(text) == {"a": ("/docs/my\\ file.md",), "dev": ("/src/",)}
+
+
+def test_codeowners_gitlab_section_default_owners() -> None:
+ text = (
+ "[Docs] @org/docs\n/docs/\n/guides/ @org/writers\n"
+ "^[Backend][2] @org/api\n/api/\n[Plain]\n/misc/\n"
+ )
+ assert _owners(text) == {
+ "org-docs": ("/docs/",),
+ "org-writers": ("/guides/",),
+ "org-api": ("/api/",),
+ }
+
+
+def test_may_overlap_is_symmetric_and_errs_towards_yes() -> None:
+ from repowise.core.analysis.patch_coverage.suggest import _may_overlap
+
+ assert _may_overlap("/pkg/", "/pkg/web/")
+ assert _may_overlap("/pkg/web/", "/pkg/")
+ assert _may_overlap("/pkg/", "*.md") # floats: any depth
+ assert _may_overlap("docs/", "/pkg/") # floating owned pattern
+ assert _may_overlap("/pkg/*/src/", "/pkg/web/")
+ assert not _may_overlap("/pkg/", "/lib/")
+ assert not _may_overlap("/src/a.py", "/src/b.py")
+ assert not _may_overlap("!/pkg/", "/pkg/web/")
diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.py
index e87802a6c..b7b1eeacb 100644
--- a/tests/unit/cli/test_coverage_check_cmd.py
+++ b/tests/unit/cli/test_coverage_check_cmd.py
@@ -51,12 +51,17 @@ def _run(repo, *args: str, env: dict[str, str] | None = None):
)
+def _check_json(repo, report: str, *, exit_code: int = 0) -> dict:
+ """``coverage check main...feat --format json`` over *report*, at the expected exit code."""
+ result = _run(repo, "main...feat", "--report", report, "--format", "json")
+ assert result.exit_code == exit_code, result.output
+ return json.loads(result.stdout)
+
+
def test_json_reports_patch_coverage_without_an_index(repo) -> None:
report = _lcov(repo, {1: 1, 2: 1, 3: 0})
- result = _run(repo, "main...feat", "--report", report, "--format", "json")
+ data = _check_json(repo, report)
- assert result.exit_code == 0, result.output
- data = json.loads(result.stdout)
assert data["patch_coverage_pct"] == 50.0
assert (data["covered_line_count"], data["coverable_line_count"]) == (1, 2)
assert data["gate"] == "not_set"
@@ -342,3 +347,246 @@ def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:
with pytest.raises(CannotEvaluateError) as missing:
_gateable(None)
assert missing.value.code == "no_report"
+
+
+# -- path-scoped gates -------------------------------------------------------
+
+
+_SRC_GATE = " - {name: src, paths: [src/], fail_under: 80}\n"
+
+
+def _gates_config(repo, gates: str) -> None:
+ (repo / ".repowise").mkdir(exist_ok=True)
+ (repo / ".repowise" / "config.yaml").write_text(
+ f"coverage:\n gates:\n{gates}", encoding="utf-8"
+ )
+
+
+def test_a_failing_path_gate_fails_the_check(repo) -> None:
+ _gates_config(repo, _SRC_GATE)
+ report = _lcov(repo, {2: 1, 3: 0})
+
+ data = _check_json(repo, report, exit_code=1)
+ # No whole-change threshold, yet the path gate fails the change.
+ assert data["threshold"] is None
+ assert data["gate"] == "fail"
+ (gate,) = data["path_gates"]
+ assert (gate["name"], gate["gate"], gate["patch_coverage_pct"]) == ("src", "fail", 50.0)
+ # src/new.py changed but the report does not name it.
+ assert gate["unmeasured_file_count"] == 1
+
+ table = _run(repo, "main...feat", "--report", report)
+ assert table.exit_code == 1
+ assert "Fails: path-scoped gate src 50.0% (1 of 2 changed executable lines)" in table.output
+ assert "Path-scoped gate" in table.output and "fails" in table.output
+
+
+def test_an_informational_path_gate_never_fails_the_check(repo) -> None:
+ _gates_config(
+ repo, " - {name: src, paths: [src/], fail_under: 80, informational: true}\n"
+ )
+ data = _check_json(repo, _lcov(repo, {2: 1, 3: 0}))
+ assert data["path_gates"][0]["gate"] == "fail"
+
+
+def test_github_format_errors_per_failing_path_gate(repo, tmp_path_factory) -> None:
+ _gates_config(repo, _SRC_GATE + " - {name: docs, paths: [docs/], fail_under: 80}\n")
+ summary = tmp_path_factory.mktemp("gh") / "summary.md"
+
+ result = _run(
+ repo,
+ "main...feat",
+ "--report",
+ _lcov(repo, {2: 1, 3: 0}),
+ "--format",
+ "github",
+ env={"GITHUB_STEP_SUMMARY": str(summary)},
+ )
+
+ assert result.exit_code == 1
+ errors = [line for line in result.stdout.splitlines() if line.startswith("::error::")]
+ assert errors == [
+ "::error::Fails: path-scoped gate src 50.0%25 (1 of 2 changed executable lines), "
+ "below its 80.0%25 gate."
+ ]
+ assert "| `docs` | no measured changed lines | n/a | 80.0% |" in summary.read_text(
+ encoding="utf-8"
+ )
+
+
+def test_an_invalid_path_gate_exits_2_naming_it(repo) -> None:
+ _gates_config(repo, " - {name: src, paths: [src/], fail_under: high}\n")
+
+ result = _run(repo, "main...feat", "--report", _lcov(repo, {2: 1}), "--format", "json")
+ assert result.exit_code == 2
+ data = json.loads(result.stdout)
+ assert data["error"] == "config_invalid"
+ assert data["message"].startswith("coverage.gates[0] ('src'): fail_under must be")
+
+
+def test_stored_coverage_is_judged_by_the_configured_path_gates(monkeypatch, tmp_path) -> None:
+ import contextlib
+
+ from repowise.cli.commands import coverage_check_cmd
+ from repowise.core.analysis import patch_coverage
+ from repowise.core.analysis.health.coverage import CoverageConfig, PathGate
+
+ @contextlib.asynccontextmanager
+ async def _session(root):
+ yield object(), "repo-id"
+
+ seen = {}
+
+ async def _stored(session, repo_id, changed, **kwargs):
+ seen.update(kwargs)
+
+ monkeypatch.setattr(coverage_check_cmd, "repo_index_session", _session)
+ monkeypatch.setattr(patch_coverage, "stored_patch_coverage", _stored)
+ cfg = CoverageConfig(ignore=("gen/",), gates=(PathGate("api", ("api/",), 80),))
+
+ run = coverage_check_cmd._stored(tmp_path, {"a.py": {1}}, "HEAD", None, 3, cfg)
+ coverage_check_cmd.run_async(run)
+ assert seen["config"].gates == cfg.gates
+ assert seen["config"].ignore == ("gen/",)
+ assert seen["config"].min_coverable_lines == 3
+
+
+# -- coverage suggest-gates --------------------------------------------------
+
+
+def layout_repo(tmp_path):
+ """A monorepo with CODEOWNERS, two packages, tests and docs."""
+ _git(tmp_path, "init", "-q", "-b", "main")
+ files = {
+ ".github/CODEOWNERS": (
+ "# owners\n* @org/all\n/packages/api/ @org/backend\n"
+ "/packages/api/web/ @org/frontend\n*.md @org/docs\n"
+ ),
+ "packages/api/src/app.py": "x = 1\n",
+ "packages/api/web/view.ts": "export const x = 1;\n",
+ "packages/ui/src/button.tsx": "export {};\n",
+ "packages/ui/README.md": "docs\n",
+ "tests/test_app.py": "def test(): pass\n",
+ "docs/guide.md": "guide\n",
+ }
+ for rel, text in files.items():
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(text, encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ return tmp_path
+
+
+def _suggest(repo, *args: str):
+ return CliRunner().invoke(cli, ["coverage", "suggest-gates", "--path", str(repo), *args])
+
+
+def test_suggest_prints_yaml_from_codeowners_and_packages_without_an_index(layout_repo) -> None:
+ import yaml
+
+ from repowise.core.analysis.health.coverage import CoverageConfig
+
+ result = _suggest(layout_repo)
+
+ assert result.exit_code == 0, result.output
+ text = result.stdout
+ assert "# From CODEOWNERS: .github/CODEOWNERS" in text
+ assert "# From top-level packages: git ls-files" in text
+ assert "# From graph communities: unavailable, no index" in text
+ # Indented to paste directly below the coverage: line.
+ config = yaml.safe_load("coverage:\n" + text)
+ gates = {g["name"]: g for g in config["coverage"]["gates"]}
+ # A later pattern owned by someone else that may reach into a gate's files
+ # is carried as an exclusion (``*.md`` matches at any depth); the leading
+ # catch-all owner gets no gate.
+ assert gates["org-backend"]["paths"] == ["/packages/api/", "!/packages/api/web/", "!*.md"]
+ assert gates["org-frontend"]["paths"] == ["/packages/api/web/", "!*.md"]
+ assert gates["org-docs"]["paths"] == ["*.md"]
+ assert "org-all" not in gates
+ assert gates["api"]["paths"] == ["/packages/api/"]
+ assert gates["ui"]["paths"] == ["/packages/ui/"]
+ # Suggestions pick no threshold, and paste into a valid config.
+ assert all("fail_under" not in g for g in gates.values())
+ cfg = CoverageConfig.from_repo_config(config)
+ assert cfg.gate_errors == ()
+ assert len(cfg.gates) == len(gates)
+
+
+def test_suggest_json_and_the_graph_source(layout_repo, monkeypatch) -> None:
+ from repowise.cli.commands import coverage_suggest_gates_cmd as cmd
+
+ async def _graph(root):
+ return {
+ "packages/api/src/app.py": 1,
+ "packages/api/src/db.py": 1,
+ "packages/api/src/models.py": 1,
+ # Same globs as the ``ui`` package gate: not suggested twice.
+ "packages/ui/a.ts": 2,
+ "packages/ui/b.ts": 2,
+ "packages/ui/c.ts": 2,
+ "packages/ui/src/button.tsx": 3,
+ }, "0123456789abcdef"
+
+ monkeypatch.setattr(cmd, "_read_graph", _graph)
+ result = _suggest(layout_repo, "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ sources = {s["source"]: s for s in json.loads(result.stdout)["sources"]}
+ assert list(sources) == ["codeowners", "layout", "graph"]
+ assert sources["graph"]["detail"] == "the index at 0123456"
+ # Named by its common directory; ``src`` is unique across sources, the
+ # tiny community is skipped and the one repeating a package gate dropped.
+ assert sources["graph"]["gates"] == [{"name": "src", "paths": ["/packages/api/src/"]}]
+
+
+def test_suggest_graph_source_without_communities_or_readable_index(
+ layout_repo, monkeypatch
+) -> None:
+ import contextlib
+
+ from repowise.cli.commands import coverage_suggest_gates_cmd as cmd
+
+ async def _flat(root):
+ return {f"packages/api/src/{n}.py": 0 for n in "abcd"}, None
+
+ monkeypatch.setattr(cmd, "_read_graph", _flat)
+ flat = json.loads(_suggest(layout_repo, "--format", "json").stdout)["sources"][2]
+ assert flat == {"source": "graph", "detail": "the index has no communities computed", "gates": []}
+
+ @contextlib.asynccontextmanager
+ async def _broken(root):
+ yield None
+
+ # A store that exists but cannot be opened is unreadable, not absent.
+ monkeypatch.undo()
+ monkeypatch.setattr("repowise.core.persistence.database.has_db_store", lambda root: True)
+ monkeypatch.setattr(cmd, "repo_index_session", _broken)
+ broken = json.loads(_suggest(layout_repo, "--format", "json").stdout)["sources"][2]
+ assert broken["detail"] == "index unreadable, so none suggested"
+
+
+def test_suggest_without_codeowners_uses_top_level_directories(tmp_path) -> None:
+ _git(tmp_path, "init", "-q", "-b", "main")
+ for rel in ("lib/core.py", "scripts/run.sh", "tests/test_core.py", "setup.py"):
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text("x\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+
+ result = _suggest(tmp_path, "--format", "json")
+ sources = {s["source"]: s for s in json.loads(result.stdout)["sources"]}
+ assert sources["codeowners"] == {
+ "source": "codeowners",
+ "detail": "no CODEOWNERS file",
+ "gates": [],
+ }
+ assert sources["layout"]["gates"] == [{"name": "lib", "paths": ["/lib/"]}]
+
+
+def test_suggest_reads_a_gitlab_codeowners(tmp_path) -> None:
+ _git(tmp_path, "init", "-q", "-b", "main")
+ (tmp_path / ".gitlab").mkdir()
+ (tmp_path / ".gitlab" / "CODEOWNERS").write_text("[API] @api\n/api/\n", encoding="utf-8")
+
+ sources = json.loads(_suggest(tmp_path, "--format", "json").stdout)["sources"]
+ assert sources[0]["detail"] == ".gitlab/CODEOWNERS"
+ assert sources[0]["gates"] == [{"name": "api", "paths": ["/api/"]}]
diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.py
index 1ac367460..3aac23fca 100644
--- a/tests/unit/health/test_coverage_discovery.py
+++ b/tests/unit/health/test_coverage_discovery.py
@@ -11,7 +11,9 @@ from pathlib import Path
from repowise.core.analysis.health.coverage import (
CoverageConfig,
+ PathGate,
build_coverage_map,
+ configured_coverage,
discover_artifacts,
expand_report_patterns,
normalize_report_path,
@@ -378,6 +380,76 @@ def test_coverage_config_rejects_a_bad_min_coverable_lines() -> None:
assert cfg.min_coverable_lines is None
+def test_coverage_config_parses_path_gates() -> None:
+ cfg = CoverageConfig.from_repo_config(
+ {
+ "coverage": {
+ "gates": [
+ {"name": "api", "paths": ["packages/api/", "!**/gen/"], "fail_under": 80},
+ {"name": "docs", "paths": "docs/", "informational": True},
+ ]
+ }
+ }
+ )
+
+ assert cfg.gates == (
+ PathGate("api", ("packages/api/", "!**/gen/"), 80.0),
+ PathGate("docs", ("docs/",), None, informational=True),
+ )
+ assert cfg.gate_errors == ()
+ assert CoverageConfig().gates == ()
+
+
+def test_coverage_config_names_each_invalid_path_gate() -> None:
+ cfg = CoverageConfig.from_repo_config(
+ {
+ "coverage": {
+ "gates": [
+ {"name": "ok", "paths": ["a/"]},
+ {"name": "ok", "paths": ["b/"]},
+ {"name": "nopaths", "paths": []},
+ {"name": "high", "paths": ["c/"], "fail_under": 120},
+ {"name": "typo", "paths": ["d/"], "fail-under": 80},
+ {"name": "docs", "paths": ["e/"], "informational": "yes"},
+ {"paths": ["f/"]},
+ {"name": "none", "paths": ["!g/", "# note"]},
+ "g/",
+ ]
+ }
+ }
+ )
+
+ assert [g.name for g in cfg.gates] == ["ok"]
+ assert cfg.gate_errors == (
+ "coverage.gates[1] ('ok'): duplicate name; each gate needs its own.",
+ "coverage.gates[2] ('nopaths'): paths must be a non-empty list of globs.",
+ "coverage.gates[3] ('high'): fail_under must be a number from 0 to 100, got 120.",
+ "coverage.gates[4] ('typo'): unknown key fail-under; expected name, paths, "
+ "fail_under, informational.",
+ "coverage.gates[5] ('docs'): informational must be true or false, got 'yes'.",
+ "coverage.gates[6]: name must be a non-empty string.",
+ "coverage.gates[7] ('none'): paths must include a glob that is not a comment or "
+ "a ! exclusion.",
+ "coverage.gates[8]: must be a mapping with name and paths.",
+ )
+ bad_block = CoverageConfig.from_repo_config({"coverage": {"gates": {"api": "x/"}}})
+ assert bad_block.gate_errors == (
+ "coverage.gates must be a list of {name, paths} entries.",
+ )
+
+
+def test_configured_coverage_reads_the_repo_config(tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "coverage:\n ignore: [gen/]\n gates:\n - {name: api, paths: [api/], fail_under: 70}\n"
+ )
+
+ cfg = configured_coverage(tmp_path)
+ assert cfg.ignore == ("gen/",)
+ assert cfg.gates == (PathGate("api", ("api/",), 70.0),)
+ assert configured_coverage(tmp_path / "missing").gates == ()
+
+
def test_expand_report_patterns_sorts_and_dedupes(tmp_path: Path) -> None:
for rel in ("b/lcov.info", "a/deep/lcov.info"):
(tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 222ff8759..3e5d593f7 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -399,6 +399,47 @@ async def test_patch_coverage_is_the_gate_computation_on_stored_coverage(
assert ignored["scope"]["ignored_file_count"] == 1
assert ignored["patch_coverage_pct"] is None
+ # So do the path-scoped gates in coverage.gates, and a failing one fails the gate.
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "coverage:\n gates:\n - {name: a, paths: [a.py], fail_under: 80}\n",
+ encoding="utf-8",
+ )
+ gated = await tool._patch_coverage_block(
+ ctx, {"a.py": {1, 2}}, None, "main...HEAD", _scored(), _collector(tmp_path)
+ )
+ (gate,) = gated["path_gates"]
+ assert (gate["name"], gate["patch_coverage_pct"], gate["gate"]) == ("a", 50.0, "fail")
+ assert gated["gate"] == "fail"
+
+ # Uncommitted or stale coverage is not what the CLI gate judges: no verdict.
+ unjudged = await tool._patch_coverage_block(
+ ctx, {"a.py": {1, 2}}, None, None, _scored(working_tree=True), _collector(tmp_path)
+ )
+ assert unjudged["path_gates"][0]["gate"] == "no_data"
+ assert unjudged["gate"] == "not_set"
+ monkeypatch.setattr(git_refs, "resolve", lambda _p, _rev: "other")
+ stale = await tool._patch_coverage_block(
+ ctx, {"a.py": {1, 2}}, None, "main...HEAD", _scored(), _collector(tmp_path)
+ )
+ assert stale["scope"]["freshness"] == "stale"
+ assert stale["path_gates"][0]["gate"] == "no_data"
+
+ # An invalid entry is carried, and no gate is judged beside it.
+ monkeypatch.setattr(git_refs, "resolve", lambda _p, _rev: "abc")
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "coverage:\n gates:\n - {name: a, paths: [a.py], fail_under: 80}\n"
+ " - {name: b, paths: []}\n",
+ encoding="utf-8",
+ )
+ partial = await tool._patch_coverage_block(
+ ctx, {"a.py": {1, 2}}, None, "main...HEAD", _scored(), _collector(tmp_path)
+ )
+ assert partial["scope"]["config_errors"] == [
+ "coverage.gates[1] ('b'): paths must be a non-empty list of globs."
+ ]
+ assert [g["gate"] for g in partial["path_gates"]] == ["no_data"]
+ assert partial["gate"] == "not_set"
+
@pytest.mark.asyncio
async def test_patch_coverage_is_absent_without_a_readable_change_or_index(
diff --git a/tests/unit/server/test_patch_coverage_schema.py b/tests/unit/server/test_patch_coverage_schema.py
index 19c4f9a66..7a782a54e 100644
--- a/tests/unit/server/test_patch_coverage_schema.py
+++ b/tests/unit/server/test_patch_coverage_schema.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from repowise.core.analysis.health.coverage import file_coverage
+from repowise.core.analysis.health.coverage import PathGate, file_coverage
from repowise.core.analysis.patch_coverage import PatchScope, compute_patch_coverage
from repowise.server.schemas.patch_coverage import PatchCoverageResponse
@@ -27,6 +27,10 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:
threshold=80,
min_coverable_lines=5,
ignore=["gen/"],
+ gates=[
+ PathGate("a", ("a.py",), 80),
+ PathGate("none", ("docs/",), None, informational=True),
+ ],
scope=PatchScope(
label="main...HEAD",
source_formats=("lcov",),
@@ -36,6 +40,7 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:
mapping_partial=True,
measured_commit="abc",
freshness="stale",
+ config_errors=("coverage.gates[2]: must be a mapping with name and paths.",),
),
)
wire = pc.to_dict()
@@ -47,4 +52,5 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:
"not_in_report",
}
assert (wire["gate"], wire["scope"]["ignored_file_count"]) == ("too_small", 1)
+ assert [g["gate"] for g in wire["path_gates"]] == ["too_small", "not_set"]
assert PatchCoverageResponse.model_validate(wire).model_dump() == wire
diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.py
index 06ca1461a..c1fb77b96 100644
--- a/tests/unit/server/test_risk_range.py
+++ b/tests/unit/server/test_risk_range.py
@@ -245,14 +245,24 @@ async def test_patch_coverage_reads_stored_coverage(
empty = await client.get(url, params={"base": base})
assert empty.status_code == 200 and empty.json() is None
- await save_coverage_files(
- session,
- repo["id"],
- [file_coverage("src/a.py", [1, 2], [1, 2, 3])],
- source_format="lcov",
- ingested_commit_sha=head,
- )
- await session.commit()
+ async def _ingest(commit: str) -> None:
+ await save_coverage_files(
+ session,
+ repo["id"],
+ [file_coverage("src/a.py", [1, 2], [1, 2, 3])],
+ source_format="lcov",
+ ingested_commit_sha=commit,
+ )
+ await session.commit()
+
+ async def _with_config(coverage_block: str) -> dict:
+ (git_repo / ".repowise").mkdir(exist_ok=True)
+ (git_repo / ".repowise" / "config.yaml").write_text(
+ f"coverage:\n{coverage_block}", encoding="utf-8"
+ )
+ return (await client.get(url, params={"base": base})).json()
+
+ await _ingest(head)
data = (await client.get(url, params={"base": base})).json()
assert data["patch_coverage_pct"] == 66.66
@@ -261,11 +271,26 @@ async def test_patch_coverage_reads_stored_coverage(
assert data["scope"]["label"] == f"{base}...HEAD"
assert (await client.get(url, params={"base": "nope"})).status_code == 400
- # coverage.ignore reaches the stored-coverage surface as it does the CLI gate.
- (git_repo / ".repowise").mkdir(exist_ok=True)
- (git_repo / ".repowise" / "config.yaml").write_text(
- "coverage:\n ignore: [src/a.py]\n", encoding="utf-8"
- )
- ignored = (await client.get(url, params={"base": base})).json()
+ # The repository's coverage config reaches the stored-coverage surface as
+ # it does the CLI gate; the compute tests own what each verdict is.
+ ignored = await _with_config(" ignore: [src/a.py]\n")
assert ignored["scope"]["ignored_file_count"] == 1
assert ignored["files"] == []
+ assert ignored["path_gates"] == []
+
+ one_gate = " gates:\n - {name: src, paths: [src/], fail_under: 50}\n"
+ gated = await _with_config(one_gate)
+ assert [(g["name"], g["gate"]) for g in gated["path_gates"]] == [("src", "pass")]
+
+ # An invalid entry is carried, and no gate is judged beside it.
+ partial = await _with_config(one_gate + " - {name: src, paths: [lib/]}\n")
+ assert partial["scope"]["config_errors"] == [
+ "coverage.gates[1] ('src'): duplicate name; each gate needs its own."
+ ]
+ assert [g["gate"] for g in partial["path_gates"]] == ["no_data"]
+
+ # Coverage measured at another commit gets no verdict either.
+ await _ingest(base)
+ stale = await _with_config(one_gate)
+ assert stale["scope"]["freshness"] == "stale"
+ assert [g["gate"] for g in stale["path_gates"]] == ["no_data"]