Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(coverage): report globs, per-report prefixes, ignore globs and a small-change tolerance for the patch gate (#2644)
Raghav Chamadiyaa161f8c74ad3
diff --git a/action.yml b/action.ymlindex 24cbce266..1a5de52a1 100644--- a/action.yml+++ b/action.yml@@ -30,14 +30,22 @@ inputs:default: ""coverage-report:description: >-- Coverage report paths, one per line. Empty uses coverage.paths from- .repowise/config.yaml, else discovery.+ Coverage reports, one per line. Each line is a path or a glob such as+ artifacts/**/lcov.info (Repowise expands it), optionally path=prefix to+ prepend a directory to that report's paths. Empty uses coverage.paths+ from .repowise/config.yaml, else discovery.default: ""coverage-fail-under:description: >-Minimum patch coverage percent. Empty uses coverage.fail_under from.repowise/config.yaml, else reports without gating.default: ""+ coverage-min-coverable-lines:+ description: >-+ Small-change tolerance: a change with fewer changed executable lines+ than this is reported but never fails the coverage gate. Empty uses+ coverage.min_coverable_lines from .repowise/config.yaml.+ default: ""doc-drift-baseline:description: Committed doc-drift baseline file; only findings it does not list fail.default: ""@@ -89,6 +97,7 @@ runs:BASE: ${{ inputs.base }}COVERAGE_REPORT: ${{ inputs.coverage-report }}COVERAGE_FAIL_UNDER: ${{ inputs.coverage-fail-under }}+ COVERAGE_MIN_COVERABLE_LINES: ${{ inputs.coverage-min-coverable-lines }}DOC_DRIFT_BASELINE: ${{ inputs.doc-drift-baseline }}SECURITY_FAIL_ON: ${{ inputs.security-fail-on }}SECURITY_BASELINE: ${{ inputs.security-baseline }}diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.shindex 4bc4cbe9d..d695369bb 100644--- a/ci/github/run-gates.sh+++ b/ci/github/run-gates.sh@@ -63,6 +63,7 @@ if wants coverage; then[[ -n "$report" ]] && args+=(--report "$report")done <<<"$COVERAGE_REPORT"[[ -n "$COVERAGE_FAIL_UNDER" ]] && args+=(--fail-under "$COVERAGE_FAIL_UNDER")+ [[ -n "$COVERAGE_MIN_COVERABLE_LINES" ]] && args+=(--min-coverable-lines "$COVERAGE_MIN_COVERABLE_LINES")run coverage repowise "${args[@]}"fidiff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.ymlindex ae59465c8..61e9eafe1 100644--- a/ci/gitlab/repowise.gitlab-ci.yml+++ b/ci/gitlab/repowise.gitlab-ci.yml@@ -14,10 +14,14 @@## Variables (set them in your .gitlab-ci.yml or the project's CI settings):# REPOWISE_VERSION Version to install; empty installs the latest.-# REPOWISE_COVERAGE_REPORT Coverage report paths, space separated. The coverage-# job runs only when it is set; add `needs:` on your-# test job.+# REPOWISE_COVERAGE_REPORT Coverage reports, space separated: paths or globs+# (artifacts/**/lcov.info, expanded by Repowise), each+# optionally path=prefix. The coverage job runs only+# when it is set; add `needs:` on your test job.# REPOWISE_COVERAGE_FAIL_UNDER Minimum patch coverage percent.+# REPOWISE_COVERAGE_MIN_COVERABLE_LINES+# Small-change tolerance: fewer changed executable+# lines than this never fails the coverage gate.# REPOWISE_DOC_DRIFT_BASELINE Committed doc-drift baseline file.# REPOWISE_SECURITY_BASELINE Committed security baseline file.# REPOWISE_SECURITY_FAIL_ON Lowest severity that fails: high (default), med, low.@@ -36,10 +40,14 @@repowise-coverage:extends: .repowisescript:+ # No shell globbing: the report list is split on spaces, and Repowise+ # expands the globs itself (so a glob matching nothing exits 2).+ - set -f- >repowise coverage check "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD"$(printf -- '--report %s ' $REPOWISE_COVERAGE_REPORT)${REPOWISE_COVERAGE_FAIL_UNDER:+--fail-under "$REPOWISE_COVERAGE_FAIL_UNDER"}+ ${REPOWISE_COVERAGE_MIN_COVERABLE_LINES:+--min-coverable-lines "$REPOWISE_COVERAGE_MIN_COVERABLE_LINES"}--format markdown > repowise-coverage.mdafter_script:- cat repowise-coverage.mddiff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex c8cdcbb8b..787fd3386 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -254,18 +254,27 @@ judge and passes.The threshold comes from `--fail-under`, else `coverage.fail_under` in`.repowise/config.yaml` (read at the repository root, even with `--path`); with-neither, the check reports without gating. 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: 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.+neither, the check reports without gating. `--min-coverable-lines` (else+`coverage.min_coverable_lines`) is the small-change tolerance: a change with+fewer changed executable lines than that, counting only lines the report+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+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:+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.`--format github` writes up to 10 `::warning` annotations (largest uncovered-ranges first), a notice counting the rest, and an `::error::` when the gate-fails, then appends the markdown summary to `$GITHUB_STEP_SUMMARY`. `markdown`-and `json` suit other CI systems. A coverage.py `.coverage` database is not a-text report: export it with `coverage lcov` or `coverage xml` first.+ranges first), a notice counting the rest, an `::error::` when the gate fails+and a notice when the small-change tolerance exempts it, then appends the+markdown summary to `$GITHUB_STEP_SUMMARY`. `markdown` and `json` suit other CI+systems. A coverage.py `.coverage` database is not a text report: export it+with `coverage lcov` or `coverage xml` first.CI checkouts are often shallow, which leaves no merge-base to diff from. Fetchfull history (`fetch-depth: 0` on GitHub Actions, `GIT_DEPTH: 0` on GitLab).@@ -526,10 +535,15 @@ coverage:auto_discover: trueartifacts: # override the discovery globs- "coverage/lcov.info"+ paths: # explicit reports or globs (skip discovery)+ - "coverage/lcov.info"+ - {path: "web/coverage/*.info", path_prefix: web} # per-report prefixformat: lcov # skip format sniffingstrip_prefix: "/build/src/" # trim an absolute prefix from report paths+ ignore: ["**/*_pb2.py"] # gitignore-style globs coverage leaves outreingest_on_update: falsefail_under: 80 # patch-coverage gate for `coverage check` (0-100)+ min_coverable_lines: 5 # small-change tolerance for that gate```Coverage is also auto-discovered and ingested during `init` and `update`, and@@ -543,7 +557,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`, `--path`, `--format` |+| `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--min-coverable-lines`, `--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.mdindex 4b9fcc4dd..c4b517633 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1319,31 +1319,39 @@ are out of scope and only counted.| Flag | Description ||------|-------------|-| `--report` | Coverage report to read. Repeatable, merged hit-wins. Defaults to `coverage.paths`, else discovery |+| `--report` | Coverage report to read: a path or a glob (`artifacts/**/lcov.info`), relative to cwd; `**` skips dependency, cache and build directories. `PATH=PREFIX` prepends `PREFIX` to that report's paths: the whole argument is tried first, and only when it matches nothing is it split on the last `=`. Repeatable, merged hit-wins. Defaults to `coverage.paths`, else discovery || `--report-format` | Force a parser: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` || `--fail-under` | Exit 1 when patch coverage is below this percentage (0-100). Defaults to `coverage.fail_under` in `.repowise/config.yaml`; with neither set the command reports without gating |+| `--min-coverable-lines` | Small-change tolerance: a change with fewer changed executable lines than this (counting only lines the report measures, as the percentage does) is reported against the threshold but never fails (`gate` reads `too_small`). Defaults to `coverage.min_coverable_lines` || `--path` | A path inside the repository (defaults to cwd) || `--format` | `table` (default), `json`, `markdown`, or `github` |`github` writes up to 10 `::warning` annotations (largest uncovered ranges-first), a `::notice` counting the rest, and an `::error::` when the gate fails,-then appends the markdown summary to `$GITHUB_STEP_SUMMARY` when set.-`json` carries `patch_coverage_pct`, `covered_line_count`,-`coverable_line_count`, `threshold`, `gate` (`pass`, `fail`, `no_data`,-`not_set`), `file_counts` (`measured`, `not_in_report`, `no_line_data`,-`no_coverable_changes`, `out_of_scope`), `files[]` (`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`). Percentages are shown floored to one decimal+first), a `::notice` counting the rest, an `::error::` when the gate fails 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`,+`threshold`, `min_coverable_lines`, `gate` (`pass`, `fail`, `no_data`,+`not_set`, `too_small`), `file_counts` (`measured`, `not_in_report`,+`no_line_data`, `no_coverable_changes`, `out_of_scope`), `files[]`+(`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+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+`coverage.path_prefix` is set. Percentages are shown floored to one decimal(79.99% reads 79.9%); the gate compares the unrounded figure.-**Exit codes:** `0` the gate passes or there is nothing to judge (no threshold,-or no measurable changed lines); `1` patch coverage is below `--fail-under`;-`2` the check could not run: no report found, none readable, or none 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 a malformed-`coverage.fail_under`; not a git repository.+**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+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.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@@ -1355,6 +1363,8 @@ commands are inrepowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80repowise coverage check HEAD --format json # one commit, machine-readablerepowise coverage check origin/main...HEAD --report coverage.out --report-format go-coverprofile+repowise coverage check origin/main...HEAD --report 'artifacts/**/lcov.info' --min-coverable-lines 5+repowise coverage check origin/main...HEAD --report web/coverage/lcov.info=web```CI clones are often shallow, so the merge-base is missing and the check exits 2.diff --git a/docs/start/CI.md b/docs/start/CI.mdindex c50721ba1..28ac13ecb 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -106,8 +106,9 @@ release the action installs.| `python-version` | `3.12` | Python to run it with (3.11 or newer). || `working-directory` | `.` | Where to run from. || `base` | from the pull request | Revision range for coverage and security. |-| `coverage-report` | config, else discovery | Report paths, one per line. |+| `coverage-report` | config, else discovery | Reports, one per line: a path or a glob (`artifacts/**/lcov.info`), optionally `path=prefix`. || `coverage-fail-under` | `coverage.fail_under` | Minimum patch coverage percent. |+| `coverage-min-coverable-lines` | `coverage.min_coverable_lines` | Small-change tolerance: a change with fewer changed executable lines than this never fails. || `doc-drift-baseline` | none | Committed baseline file. || `security-fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low`. || `security-baseline` | none | Committed baseline file. |@@ -166,8 +167,11 @@ fails the job. A fourth job, `repowise-code-quality`, runs on the defaultbranch and never fails the pipeline: it publishes the report the widgetcompares a merge request against, so only issues the merge request introducesshow as new. It publishes doc drift only: security judges only what a change-adds, and the default branch has no change to judge. Other-variables: `REPOWISE_VERSION`, `REPOWISE_DOC_DRIFT_BASELINE`,+adds, and the default branch has no change to judge.+`REPOWISE_COVERAGE_REPORT` is space separated and may hold globs and+`path=prefix` entries; Repowise expands the globs, not the shell. Other+variables: `REPOWISE_VERSION`, `REPOWISE_COVERAGE_MIN_COVERABLE_LINES`,+`REPOWISE_DOC_DRIFT_BASELINE`,`REPOWISE_SECURITY_BASELINE`, `REPOWISE_SECURITY_FAIL_ON`. Override any job's`image`, `rules` or `needs` in your own file as usual.@@ -233,8 +237,99 @@ The threshold can live in config instead of the workflow:coverage:paths: [coverage/lcov.info]fail_under: 80+ min_coverable_lines: 5 # small-change tolerance```+With `min_coverable_lines` set, a change touching fewer changed executable+lines than that is still reported against the threshold, but a miss reads+"not applied" (a notice on GitHub) and exits `0`: one uncovered line in a+two-line fix should not block a merge. Like the percentage, the count is of+lines the report measures; a file the report does not name adds nothing to it.++### Monorepos and matrix jobs++A matrix of test jobs leaves one report per shard. `--report` (and each line+of `coverage-report`) takes a glob, relative to the working directory, so+`artifacts/**/lcov.info` reads them all; they merge hit-wins. `**` walks the+tree the way discovery does, skipping dependency, cache and build directories+(`node_modules`, `.venv`, `dist`, ...) and nested repositories. A job whose+reports never arrived exits `2`: a literal path that does not exist, or a+glob that matches nothing, cannot be evaluated. A glob still matches when one+shard of several is missing, so to catch that, list each shard's report on+its own line. `coverage.paths` entries that match nothing are skipped.++On GitHub Actions, each shard uploads its report and the gate job downloads+them all:++```yaml+jobs:+ test:+ strategy:+ matrix: {shard: [1, 2, 3]}+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: pytest tests/shard${{ matrix.shard }} --cov=src --cov-report=lcov:coverage/lcov.info+ - uses: actions/upload-artifact@v4+ with: {name: "coverage-${{ matrix.shard }}", path: coverage/lcov.info}+ coverage:+ needs: test+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with: {fetch-depth: 0}+ - uses: actions/download-artifact@v4+ with: {pattern: "coverage-*", path: artifacts}+ - uses: repowise-dev/repowise@main+ with:+ checks: coverage+ coverage-report: artifacts/**/lcov.info+```++On GitLab, give each parallel shard its own path and let the gate job need+them:++```yaml+test:+ parallel: 3+ script: pytest tests/shard$CI_NODE_INDEX --cov=src --cov-report=lcov:coverage/$CI_NODE_INDEX/lcov.info+ artifacts:+ paths: [coverage/]++variables:+ REPOWISE_COVERAGE_REPORT: "coverage/**/lcov.info"++repowise-coverage:+ needs: [test]+```++When one package's report names paths relative to that package, give it a+per-report prefix: `--report web/coverage/lcov.info=web`. The whole argument+is tried as a path or glob first, so `artifacts/shard=1/*.info` stays one;+only when it matches nothing is it split on the last `=`. In config the same+is a mapping entry, and `paths` entries may be globs, relative to the+repository root:++```yaml+coverage:+ paths:+ - {path: "web/coverage/lcov.info", path_prefix: web}+ - "services/*/coverage.xml"+ ignore: ["**/*_pb2.py", "gen/"] # gitignore syntax+```++`coverage.ignore` leaves generated or vendored files out on both sides:+changed files it matches are dropped before measuring (the summary counts them+as ignored, here and in the editor and agent views), and report entries it+matches are not stored by `repowise coverage add` or indexing. When it leaves+out every entry of the reports, the gate exits `2` and says so.++Go coverprofiles name files by import path. When a module lives in a+subdirectory (`backend/go.mod` declaring `module example.com/m`), paths under+`example.com/m/` are mapped to `backend/` using the `go.mod` files in the+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.+## When a gate exits 2| Message | Fix |@@ -242,5 +337,7 @@ coverage:| no merge-base, or a commit cut off by a shallow clone | fetch full history || 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 |+| 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/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.pyindex 1b40fb115..0dc19ddfb 100644--- a/packages/cli/src/repowise/cli/_instrumented_group.py+++ b/packages/cli/src/repowise/cli/_instrumented_group.py@@ -64,6 +64,14 @@ class InstrumentedGroup(click.Group):#: name -> "module:attr", for commands not yet imported.self._lazy_commands: dict[str, str] = {}+ def main(self, *args, **kwargs):+ # Click expands wildcards in arguments on Windows by default, so a+ # quoted ``--report "artifacts/**/lcov.info"`` arrived as several+ # arguments, without the pruning the commands apply. A command that+ # takes a glob expands it itself, the same on every platform.+ kwargs.setdefault("windows_expand_args", False)+ return super().main(*args, **kwargs)+def add_lazy_command(self, name: str, target: str) -> None:"""Register *name* without importing the module that defines it."""# Last registration wins, which is what ``click.Group.add_command``diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex 09df663b8..5bc7e402d 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -9,8 +9,10 @@ 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, unreadable-report, unknown revision, missing history, bad config).+below ``--fail-under``, 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."""from __future__ import annotations@@ -42,9 +44,10 @@ from repowise.core.persistence.database import has_db_store"--report","reports",multiple=True,- type=click.Path(exists=True, dir_okay=False),- help="Coverage report to read (repeatable; merged hit-wins). "- "Defaults to coverage.paths in .repowise/config.yaml, else discovery.",+ help="Coverage report to read: a path or a glob such as artifacts/**/lcov.info, "+ "relative to cwd (repeatable; merged hit-wins). PATH=PREFIX prepends PREFIX to "+ "that report's paths. Defaults to coverage.paths in .repowise/config.yaml, "+ "else discovery.",)@click.option("--report-format",@@ -59,6 +62,14 @@ from repowise.core.persistence.database import has_db_storehelp="Exit 1 when patch coverage is below this percentage. ""Defaults to coverage.fail_under in .repowise/config.yaml.",)+ "--min-coverable-lines",+ type=click.IntRange(min=0),+ default=None,+ help="Small-change tolerance: a change with fewer changed executable lines "+ "than this is reported but never fails the gate. "+ "Defaults to coverage.min_coverable_lines in .repowise/config.yaml.",+)@click.option("--path","repo",@@ -75,6 +86,7 @@ def coverage_check(reports: tuple[str, ...],report_format: str | None,fail_under: float | None,+ min_coverable_lines: int | None,repo: str | None,fmt: str,) -> None:@@ -90,11 +102,15 @@ def coverage_check(repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80repowise coverage check --report coverage.out --format github+ repowise coverage check --report 'artifacts/**/lcov.info' --min-coverable-lines 5+ repowise coverage check --report web/coverage/lcov.info=webrepowise coverage check HEAD --format json"""notices = ci_notices(fmt)try:- pc = _evaluate(revspec, reports, report_format, fail_under, repo, notices)+ pc = _evaluate(+ revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices+ )except CannotEvaluateError as exc:cannot_evaluate(fmt, exc.code, str(exc))_emit(pc, fmt)@@ -102,13 +118,20 @@ def coverage_check(raise click.exceptions.Exit(EXIT_GATE_FAILED)-def _evaluate(revspec, reports, report_format, fail_under, repo, notices):+def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices):from repowise.core.analysis.patch_coverage import patch_coverage_from_resolvedroot = repo_root(repo)- cfg = _coverage_config(root, validate_threshold=fail_under is None)- threshold = fail_under if fail_under is not None else cfg.fail_under- report_paths = [Path(p) for p in reports] or cfg.report_paths(root)+ cfg = _coverage_config(+ root,+ validate_threshold=fail_under is None,+ validate_min_lines=min_coverable_lines is None,+ )+ # A flag overrides its config key.+ threshold = _first_set(fail_under, cfg.fail_under)+ min_coverable_lines = _first_set(min_coverable_lines, cfg.min_coverable_lines)+ report_prefixes = _cli_reports(reports) if reports else cfg.reports(root)+ report_paths = list(report_prefixes)if not report_paths and not has_db_store(root):raise CannotEvaluateError("no_report", _NO_REPORT)changed, label = change_lines(str(root), revspec)@@ -116,20 +139,57 @@ def _evaluate(revspec, reports, report_format, fail_under, repo, notices):# No report on disk: the index's stored coverage answers, when it can.if notices is console:notices.print("[dim]Reading the coverage stored in the index[/dim]")- return _gateable(run_async(_stored(root, changed, label, threshold)))+ return _gateable(+ run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg.ignore))+ )if notices is console:# Machine formats carry the list in ``scope.reports`` instead.notices.print(f"[dim]Reading {', '.join(escape(str(p)) for p in report_paths)}[/dim]")return patch_coverage_from_resolved(changed,- _resolve_reports(root, cfg, report_paths, report_format, notices),+ _resolve_reports(root, cfg, report_prefixes, report_format, notices),threshold=threshold,label=label,reports=[str(p) for p in report_paths],+ min_coverable_lines=min_coverable_lines,+ ignore=cfg.ignore,)+def _first_set(flag, configured):+ """The flag's value, else the config's: ``0`` is a value, not unset."""+ return configured if flag is None else flag+++def _cli_reports(args: tuple[str, ...]) -> dict[Path, str | None]:+ """``--report`` values: each a path or glob relative to cwd, optionally ``=PREFIX``.++ The whole argument is expanded first, so a path or glob holding ``=``+ (``artifacts/shard=1/*.info``) stays one; only when it matches nothing is+ it split on the last ``=``, and the prefix applies to every file the left+ side matches. One that matches no file cannot be evaluated: a report+ missing from a CI job is a broken setup, not a pass.+ """+ from repowise.core.analysis.health.coverage import expand_report_patterns++ cwd = Path() # relative, so reports read as the caller named them+ out: dict[Path, str | None] = {}+ for arg in args:+ pattern, prefix = arg, None+ matches = expand_report_patterns([arg], cwd)+ if not matches and "=" in arg:+ pattern, _, prefix = arg.rpartition("=")+ matches = expand_report_patterns([pattern], cwd)+ if not matches:+ raise CannotEvaluateError(+ "report_not_found", f"--report {arg}: no coverage report matches {pattern}."+ )+ for path in matches:+ out.setdefault(path, prefix or None)+ return out++_NO_REPORT = ("No coverage report found. Pass one with --report (lcov.info, coverage.xml, ""coverage.out, jacoco.xml, ...), set coverage.paths in .repowise/config.yaml, "@@ -163,7 +223,9 @@ def _gateable(pc):return pc-async def _stored(root: Path, changed, label: str, threshold: float | None):+async def _stored(+ root: Path, changed, label: str, threshold: float | None, min_lines: int | None, ignore+):"""Patch coverage from the index's stored coverage, or ``None`` without one."""from sqlalchemy.exc import SQLAlchemyError@@ -183,6 +245,8 @@ async def _stored(root: Path, changed, label: str, threshold: float | None):label=label,head_commit=git_refs.resolve(str(root), revspec_head(label)),threshold=threshold,+ min_coverable_lines=min_lines,+ ignore=ignore,)except SQLAlchemyError as exc:raise CannotEvaluateError(@@ -190,25 +254,33 @@ async def _stored(root: Path, changed, label: str, threshold: float | None):) from exc-def _resolve_reports(root, cfg, report_paths, report_format, notices):+def _resolve_reports(root, cfg, report_prefixes, report_format, notices):"""Parse the reports against the files git tracks, failing when nothing usable remains."""from repowise.core import git_refsfrom repowise.core.analysis.health.coverage import build_coverage_mapresolved, errors = build_coverage_map(root,- report_paths,+ list(report_prefixes),set(git_refs.tracked_paths(str(root))),coverage_format=report_format or cfg.format,strip_prefix=cfg.strip_prefix,path_prefix=cfg.path_prefix,+ report_prefixes=report_prefixes,+ ignore=cfg.ignore,)for path, err in errors:notices.print(f"[yellow]{escape(path.name)}: {escape(err)}[/yellow]")- if len(errors) == len(report_paths):+ if len(errors) == len(report_prefixes):raise CannotEvaluateError("report_unreadable", "No coverage report could be read; see the messages above.")+ if not resolved.files and resolved.ignored and not resolved.total:+ raise CannotEvaluateError(+ "report_all_ignored",+ f"All {resolved.ignored} report entries match coverage.ignore, so nothing "+ "is left to measure. Narrow coverage.ignore in .repowise/config.yaml.",+ )if not resolved.files:raise CannotEvaluateError("report_unmatched",@@ -223,7 +295,7 @@ def _resolve_reports(root, cfg, report_paths, report_format, notices):return resolved-def _coverage_config(root: Path, *, validate_threshold: bool):+def _coverage_config(root: Path, *, validate_threshold: bool, validate_min_lines: bool):from repowise.core.analysis.health.coverage import CoverageConfigfrom repowise.core.repo_config import RepoConfigError, load_repo_config@@ -233,13 +305,20 @@ def _coverage_config(root: Path, *, validate_threshold: bool):raise CannotEvaluateError("config_invalid", str(exc)) from exccfg = CoverageConfig.from_repo_config(raw)block = raw.get("coverage")- bad = isinstance(block, dict) and block.get("fail_under") is not None and cfg.fail_under is None- if validate_threshold and bad:- # A gate that silently stops gating is worse than no gate.+ block = block if isinstance(block, dict) else {}+ # A gate that silently stops gating (or starts failing tiny changes) is+ # worse than no gate, so a value the config cannot use stops the check.+ if validate_threshold and block.get("fail_under") is not None and cfg.fail_under is None:raise CannotEvaluateError("config_invalid",f"coverage.fail_under must be a number from 0 to 100, got {block['fail_under']!r}.")+ raw_min = block.get("min_coverable_lines")+ if validate_min_lines and raw_min is not None and cfg.min_coverable_lines is None:+ raise CannotEvaluateError(+ "config_invalid",+ f"coverage.min_coverable_lines must be a whole number of 0 or more, got {raw_min!r}."+ )return cfgdiff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.pyindex 72b74484d..e4c815d84 100644--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py@@ -211,6 +211,7 @@ def coverage_add(coverage_format=coverage_format or cfg.format,strip_prefix=cfg.strip_prefix,path_prefix=cfg.path_prefix,+ ignore=cfg.ignore,)for path, err in errors:console.print(f"[yellow] {path.name}: {err}[/yellow]")@@ -271,6 +272,7 @@ def coverage_add(repo_keys,strip_prefix=cfg.strip_prefix,path_prefix=cfg.path_prefix,+ ignore=cfg.ignore,)map_records.extend(rtc.records)map_format = map_format or creport.source_formatdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 43b05637a..b3e857f8b 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -138,16 +138,18 @@ async def _coverage_for_rescore(# Without paths or discovery there is nothing to re-read, so the stored# rows (e.g. from `coverage add`) stay authoritative.if cfg.reingest_on_update and (cfg.paths or cfg.auto_discover):- report_paths = cfg.report_paths(repo_path)- if report_paths:+ reports = cfg.reports(repo_path)+ if reports:repo_keys = {pf.file_info.path for pf in parsed_files}resolved, _errors = build_coverage_map(repo_path,- report_paths,+ list(reports),repo_keys,coverage_format=cfg.format,strip_prefix=cfg.strip_prefix,path_prefix=cfg.path_prefix,+ report_prefixes=reports,+ ignore=cfg.ignore,)if resolved.coverage_map:return RescoreCoverage(diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.mdindex c4fd026a5..06e7f999e 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md@@ -80,7 +80,16 @@ writes paths relative to its own `<source>` root — so we reconcile them.`FileCoverage` rows, and `matched` / `unmatched` / `ambiguous`diagnostics (surfaced so coverage never silently shows 0%).- `build_coverage_map(repo_root, report_paths, repo_keys, ...)` — read +- parse + resolve end-to-end.+ parse + resolve end-to-end. `report_prefixes` gives a report its own+ prefix, `ignore` drops entries `coverage.ignore` matches, resolved or not+ (counted in `ResolvedCoverage.ignored`), and a Go coverprofile's import+ paths under a `go.mod`'s module path (found on disk) are mapped to that+ module's directory.+- `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).### Config (`.repowise/config.yaml`)@@ -92,12 +101,16 @@ coverage:auto_discover: true # discover reports during indexingartifacts: # override the default discovery globs- coverage/lcov.info- paths: # explicit report paths (skip discovery)+ paths: # explicit report paths or globs (skip discovery)- build/coverage/lcov.info+ - {path: "api/**/lcov.info", path_prefix: api} # per-report prefixformat: lcov # force a parser (else content-sniffed)strip_prefix: build # drop a leading prefix from report pathspath_prefix: packages/web # prepend a prefix to report paths+ ignore: ["gen/"] # gitignore-style globs coverage leaves outreingest_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````CoverageConfig.from_repo_config(load_repo_config(repo_path))` parses it.diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.pyindex b423370ce..e289a9795 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py@@ -24,7 +24,9 @@ from .discovery import (ResolvedCoverage,ResolvedTestCoverage,build_coverage_map,+ configured_ignore,discover_artifacts,+ expand_report_patterns,normalize_report_path,resolve_reports,resolve_test_reports,@@ -57,11 +59,13 @@ __all__ = ["ResolvedTestCoverage","TestCoverage","build_coverage_map",+ "configured_ignore","coverage_freshness","decay_for_file","decay_since","detect_format","discover_artifacts",+ "expand_report_patterns","file_coverage","is_test_file","measurement_ref",diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.pyindex b9b28094f..64ff24acd 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py@@ -24,11 +24,13 @@ Two jobs that make ingested coverage *actually line up* with the repo:from __future__ import annotationsfrom collections import defaultdict-from collections.abc import Iterable+from collections.abc import Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom itertools import chainfrom pathlib import Path+import pathspec+from repowise.core.fs_walk import PRUNED_DIRS, WalkSnapshot, iter_globfrom .detector import parse as parse_coverage@@ -90,8 +92,15 @@ class CoverageConfig:auto_discover: bool = True# Override the default discovery globs entirely.artifacts: tuple[str, ...] = ()- # Explicit report paths (relative to repo root) — bypass discovery.+ # Explicit report paths or globs (relative to repo root); bypass discovery.paths: tuple[str, ...] = ()+ # Per-report prefix: a ``paths`` entry written as a mapping+ # ``{path: ..., path_prefix: ...}``, keyed by that entry's path or glob.+ # Overrides ``path_prefix`` for every report the entry matches.+ path_prefixes: dict[str, str] = field(default_factory=dict)+ # Gitignore-style globs (repo-relative) for files coverage leaves out:+ # changed files before patch coverage, report entries before storing.+ ignore: tuple[str, ...] = ()# Force a parser instead of content-sniffing.format: str | None = None# Remove this leading prefix from report paths before matching.@@ -103,6 +112,9 @@ class CoverageConfig:reingest_on_update: bool = False# Patch-coverage gate for ``repowise coverage check`` (percent, 0-100).fail_under: float | None = None+ # Small-change tolerance: a change with fewer changed executable lines+ # than this never fails the gate.+ min_coverable_lines: int | None = None@classmethoddef from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:@@ -117,24 +129,69 @@ class CoverageConfig:return tuple(str(v) for v in val if v)return ()+ paths, path_prefixes = _report_entries(block.get("paths"))return cls(auto_discover=bool(block.get("auto_discover", True)),artifacts=_strs(block.get("artifacts")),- paths=_strs(block.get("paths")),+ paths=paths,+ path_prefixes=path_prefixes,+ ignore=_strs(block.get("ignore")),format=block.get("format") or None,strip_prefix=block.get("strip_prefix") or None,path_prefix=block.get("path_prefix") or None,reingest_on_update=bool(block.get("reingest_on_update", False)),fail_under=_percent(block.get("fail_under")),+ min_coverable_lines=_line_count(block.get("min_coverable_lines")),)- def report_paths(self, repo_root: Path) -> list[Path]:- """The reports this config names: explicit ``paths``, else discovery when on."""+ def reports(self, repo_root: Path) -> dict[Path, str | None]:+ """Each report this config names, mapped to its per-report prefix (or ``None``).++ Explicit ``paths`` (globs expanded; a missing file is skipped), else+ discovery when on. Passed to :func:`build_coverage_map` as both the+ report list and ``report_prefixes``.+ """if self.paths:- return [repo_root / p for p in self.paths if (repo_root / p).is_file()]+ out: dict[Path, str | None] = {}+ for pattern in self.paths:+ for path in expand_report_patterns([pattern], repo_root):+ out.setdefault(path, self.path_prefixes.get(pattern))+ return outif self.auto_discover:- return discover_artifacts(repo_root, globs=self.artifacts or None)- return []+ return dict.fromkeys(discover_artifacts(repo_root, globs=self.artifacts or None))+ return {}+++def configured_ignore(repo_root: Path | str) -> tuple[str, ...]:+ """``coverage.ignore`` from *repo_root*'s config, empty 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.+ """+ from repowise.core.repo_config import RepoConfigError, load_repo_config++ try:+ return CoverageConfig.from_repo_config(load_repo_config(repo_root)).ignore+ except (RepoConfigError, OSError):+ return ()+++def _report_entries(value: object) -> tuple[tuple[str, ...], dict[str, str]]:+ """``coverage.paths``: each entry a path or glob, or ``{path, path_prefix}``."""+ entries = value if isinstance(value, (list, tuple)) else [value]+ paths: list[str] = []+ prefixes: dict[str, str] = {}+ for entry in entries:+ if isinstance(entry, dict):+ path = entry.get("path")+ if not path:+ continue+ paths.append(str(path))+ if entry.get("path_prefix"):+ prefixes[str(path)] = str(entry["path_prefix"])+ elif entry:+ paths.append(str(entry))+ return tuple(paths), prefixesdef _percent(value: object) -> float | None:@@ -144,6 +201,45 @@ def _percent(value: object) -> float | None:return float(value) if 0 <= value <= 100 else None+def _line_count(value: object) -> int | None:+ """A non-negative whole number from config, ``None`` when absent or not one."""+ if isinstance(value, bool) or not isinstance(value, int):+ return None+ return value if value >= 0 else None+++def expand_report_patterns(patterns: Iterable[str], base: Path) -> list[Path]:+ """The report files *patterns* name, relative to *base*.++ A pattern is a literal path or a glob, used by both ``--report`` (relative+ to cwd) and ``coverage.paths`` (relative to the repo root). A path that+ exists as written is taken literally, even when it holds ``[``; anything+ else is expanded like discovery's globs (``**`` through the pruned walk,+ so ``**/lcov.info`` never reaches ``node_modules``). Its leading literal+ directories, absolute ones included, become the walk's root. A glob's+ matches are sorted; files are de-duplicated across patterns, first+ mention first. A pattern that names no file adds nothing.+ """+ snapshots: dict[Path, WalkSnapshot] = {}+ seen: set[Path] = set()+ out: list[Path] = []+ for pattern in patterns:+ if (base / pattern).is_file():+ found = [base / pattern]+ else:+ parts = Path(pattern).parts+ first = next((i for i, part in enumerate(parts) if _has_magic(part)), len(parts))+ root = base.joinpath(*parts[:first])+ rest = "/".join(parts[first:])+ found = sorted(_expand_pattern(root, rest, snapshots)) if rest else []+ for path in found:+ key = path.resolve()+ if key not in seen:+ seen.add(key)+ out.append(path)+ return out++@dataclassclass ResolvedCoverage:"""Outcome of resolving a parsed report against the indexed tree."""@@ -164,6 +260,9 @@ class ResolvedCoverage:matched_suffix: int = 0unmatched: list[str] = field(default_factory=list)ambiguous: list[str] = field(default_factory=list)+ # Report files ``coverage.ignore`` leaves out, resolved or not. Dropped,+ # and counted in neither ``matched`` nor ``unmatched``.+ ignored: int = 0# True when more than half the report's files failed to map to the tree.# Set by :func:`resolve_reports`; consumers must flag the aggregate as# partial rather than reporting the mapped subset's numbers as repo-wide.@@ -230,56 +329,11 @@ def discover_artifacts(capped at :data:`_MAX_ARTIFACTS`."""patterns = tuple(globs) if globs else DEFAULT_DISCOVERY_GLOBS- snapshot: WalkSnapshot | None = None-- def _literal_depth(pattern: str) -> int:- """How many leading directory segments of *pattern* are spelled literally."""- depth = 0- for seg in pattern.split("/")[:-1]:- if any(ch in seg for ch in "*?["):- break- depth += 1- return depth-- def _expand(pattern: str) -> Iterable[Path]:- nonlocal snapshot- if not any(ch in pattern for ch in "*?["):- direct = repo_root / pattern- return (direct,) if direct.is_file() else ()- if "**" not in pattern:- # Single-level wildcards cannot recurse; a plain glob is bounded.- return repo_root.glob(pattern)- # Recursive pattern: split at the first ``**`` into a fixed (or- # shallow-globbed) root and a tail served from the shared snapshot.- prefix, _, tail = pattern.partition("**")- prefix = prefix.rstrip("/")- tail = tail.lstrip("/") or "*"- if snapshot is None:- snapshot = WalkSnapshot(repo_root, prune_dirs=_PRUNE_DIRS)- snap = snapshot- if any(ch in prefix for ch in "*?["):- roots = [d for d in repo_root.glob(prefix) if d.is_dir()]- else:- roots = [repo_root / prefix]- # The snapshot never enters a pruned dir, so a root spelled under- # one is walked live (still pruning below it).- if any(part in _PRUNE_DIRS for part in Path(prefix).parts):- return iter_glob(roots[0], tail, prune_dirs=_PRUNE_DIRS)- return chain.from_iterable(snap.iter_glob(r, tail) for r in roots)-+ snapshots: dict[Path, WalkSnapshot] = {}seen: set[Path] = set()out: list[Path] = []for pattern in patterns:- literal = _literal_depth(pattern)- for match in _expand(pattern):- if not match.is_file():- continue- try:- rel_parts = match.relative_to(repo_root).parts- except ValueError:- rel_parts = match.parts- if any(part in _PRUNE_DIRS for part in rel_parts[literal:-1]):- continue+ for match in _expand_pattern(repo_root, pattern, snapshots):resolved = match.resolve()if resolved in seen:continue@@ -290,6 +344,80 @@ def discover_artifacts(return out+def _has_magic(text: str) -> bool:+ return any(ch in text for ch in "*?[")+++def _expand_pattern(+ root: Path, pattern: str, snapshots: dict[Path, WalkSnapshot]+) -> Iterator[Path]:+ """Files under *root* matching the POSIX *pattern*, through the pruned walk.++ The one expansion behind discovery and ``expand_report_patterns``. A+ literal pattern is a direct file check; single-level wildcards are a+ bounded plain glob; ``**`` is served from a pruned walk of *root*+ (*snapshots* caches one per root), so it never enters dependency, cache+ or build trees, nested repositories, or symlinks. A pruned name spelled+ literally before the first wildcard is an explicit opt-in.+ """+ if not _has_magic(pattern):+ direct = root / pattern+ if direct.is_file():+ yield direct+ return+ if "**" in pattern:+ matches = _recursive_matches(root, pattern, snapshots)+ else:+ # Single-level wildcards cannot recurse; a plain glob is bounded.+ matches = root.glob(pattern)+ literal = _literal_depth(pattern)+ for match in matches:+ # Safety net for the plain-glob paths, which do not prune.+ if match.is_file() and not _under_pruned(match, root, literal):+ yield match+++def _recursive_matches(+ root: Path, pattern: str, snapshots: dict[Path, WalkSnapshot]+) -> Iterable[Path]:+ """A ``**`` pattern split at its first ``**``: a fixed (or shallow-globbed)+ root, and a tail served from the shared snapshot."""+ prefix, _, tail = pattern.partition("**")+ prefix = prefix.rstrip("/")+ tail = tail.lstrip("/") or "*"+ if _has_magic(prefix):+ roots = [d for d in root.glob(prefix) if d.is_dir()]+ elif any(part in _PRUNE_DIRS for part in Path(prefix).parts):+ # The snapshot never enters a pruned dir, so a root spelled under+ # one is walked live (still pruning below it).+ return iter_glob(root / prefix, tail, prune_dirs=_PRUNE_DIRS)+ else:+ roots = [root / prefix]+ if root not in snapshots:+ snapshots[root] = WalkSnapshot(root, prune_dirs=_PRUNE_DIRS)+ snap = snapshots[root]+ return chain.from_iterable(snap.iter_glob(r, tail) for r in roots)+++def _literal_depth(pattern: str) -> int:+ """How many leading directory segments of *pattern* are spelled literally."""+ depth = 0+ for seg in pattern.split("/")[:-1]:+ if _has_magic(seg):+ break+ depth += 1+ return depth+++def _under_pruned(match: Path, root: Path, literal: int) -> bool:+ """Whether *match* sits in a pruned dir below its pattern's literal part."""+ try:+ rel_parts = match.relative_to(root).parts+ except ValueError:+ rel_parts = match.parts+ return any(part in _PRUNE_DIRS for part in rel_parts[literal:-1])++def normalize_report_path(raw: str,*,@@ -436,6 +564,7 @@ def _resolve_path(*,strip_prefix: str | None,path_prefix: str | None,+ go_modules: Sequence[tuple[str, str]] = (),) -> tuple[str | None, bool, bool]:"""``(key, ambiguous, exact)`` for one report path.@@ -447,7 +576,16 @@ def _resolve_path(``src/index.ts``); then the path as written. Ties prefer the report's owndirectory. A configured *path_prefix* already says where the paths live,so it skips the report-directory step.++ Without a *path_prefix*, a path under a Go module's import path+ (*go_modules*, ``(module_path, module_dir)`` longest first) is first+ rewritten into that module's directory, which says where it lives too."""+ located = bool(path_prefix)+ if not path_prefix:+ in_module = _in_go_module(raw, go_modules)+ if in_module is not None:+ raw, located = in_module, Truenorm = normalize_report_path(raw, strip_prefix=strip_prefix, path_prefix=path_prefix)origin = report.origin_dirrelative = not _is_absolute(raw)@@ -462,7 +600,7 @@ def _resolve_path(found[key] = found.get(key, False) or key in (joined, norm)if found:return _one_root(found)- if origin and relative and not path_prefix:+ if origin and relative and not located:key = _under_origin(norm, origin, repo_keys)if key is not None:return key, False, True@@ -478,6 +616,57 @@ def _one_root(found: dict[str, bool]) -> tuple[str | None, bool, bool]:return key, False, exact+def _in_go_module(raw: str, go_modules: Sequence[tuple[str, str]]) -> str | None:+ """*raw* rewritten from a Go import path to its repo path, ``None`` outside every module."""+ for module_path, module_dir in go_modules:+ if raw.startswith(module_path + "/"):+ rest = raw[len(module_path) + 1 :]+ return f"{module_dir}/{rest}" if module_dir else rest+ return None+++#: Directories whose ``go.mod`` is not a module of this repository's own code.+_GO_MOD_SKIP_DIRS = frozenset({"vendor", "testdata"})+++def _go_modules(repo_root: Path) -> list[tuple[str, str]]:+ """``(module_path, module_dir)`` for each ``go.mod`` on disk, longest module path first.++ Go coverprofiles name files by import path (``example.com/m/main.go``), so+ a module in a subdirectory only matches once its path is mapped back. Read+ from disk through the pruned walk, not from the index: the traverser+ never keeps ``go.mod`` as a file.+ """+ modules: dict[str, str] = {}+ found = []+ for go_mod in iter_glob(repo_root, "go.mod"):+ rel = go_mod.relative_to(repo_root)+ if go_mod.is_file() and not _GO_MOD_SKIP_DIRS.intersection(rel.parts):+ found.append(rel)+ # Shallowest first, then by path: when two go.mod files declare the same+ # module path (a copied fixture, an example), the one nearest the root wins.+ for rel in sorted(found, key=lambda p: (len(p.parts), p.as_posix())):+ try:+ text = (repo_root / rel).read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ module_path = _module_directive(text)+ if module_path and module_path not in modules:+ module_dir = rel.parent.as_posix()+ modules[module_path] = "" if module_dir == "." else module_dir+ return sorted(modules.items(), key=lambda m: (-len(m[0]), m[0]))+++def _module_directive(go_mod: str) -> str | None:+ # A local reader rather than the Go import resolver's: importing that+ # pulls the whole ingestion package into the index-free coverage gate.+ for line in go_mod.splitlines():+ parts = line.split("//", 1)[0].split(None, 1)+ if len(parts) == 2 and parts[0] == "module":+ return parts[1].strip().strip("\"`") or None+ return None++def _under_origin(norm: str, origin: str, repo_keys: set[str]) -> str | None:"""*norm* under the report's directory or its nearest parent that has it."""segs = origin.split("/")@@ -510,29 +699,65 @@ def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:)+def _note_format(result: ResolvedCoverage, source_format: str | None) -> None:+ """Record a report's format: the first as ``source_format``, every one once."""+ if source_format in (None, "unknown"):+ return+ if result.source_format is None:+ result.source_format = source_format+ if source_format not in result.source_formats:+ result.source_formats.append(source_format)+++def _merge_keyed(by_key: dict[str, FileCoverage], key: str, fc: FileCoverage) -> None:+ """Add a copy of *fc* under *key*, merged hit-wins with what is there."""+ resolved_fc = FileCoverage(+ file_path=key,+ line_coverage_pct=fc.line_coverage_pct,+ branch_coverage_pct=fc.branch_coverage_pct,+ covered_lines=list(fc.covered_lines),+ total_coverable_lines=fc.total_coverable_lines,+ coverable_lines=list(fc.coverable_lines),+ covered_line_count=fc.covered_line_count,+ )+ if key in by_key:+ _merge_into(by_key[key], resolved_fc)+ else:+ by_key[key] = resolved_fc++def resolve_reports(reports: list[CoverageReport],repo_keys: set[str],*,strip_prefix: str | None = None,path_prefix: str | None = None,+ ignore: Sequence[str] = (),+ go_modules: Sequence[tuple[str, str]] = (),) -> ResolvedCoverage:"""Resolve one or more parsed reports against the indexed tree.Reports are merged hit-wins by canonical key. Returns the engine``coverage_map``, rewritten ``FileCoverage`` rows for persistence, anddiagnostics (matched/unmatched/ambiguous) for loud reporting.++ A report's own ``path_prefix`` wins over *path_prefix*. Entries *ignore*+ matches (gitignore syntax), on their resolved key or, when they resolve to+ none, on their normalized report path, are dropped and counted in+ ``ignored``. *go_modules* applies to Go coverprofiles only and is+ described at :func:`_resolve_path`."""suffix_index = _build_suffix_index(repo_keys)+ ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)result = ResolvedCoverage()by_key: dict[str, FileCoverage] = {}report_file_count = 0for report in reports:- if report.source_format not in (None, "unknown"):- if result.source_format is None:- result.source_format = report.source_format- if report.source_format not in result.source_formats:- result.source_formats.append(report.source_format)+ prefix = report.path_prefix or path_prefix+ # Only a coverprofile names files by import path; ``module web`` must+ # not rewrite an lcov report's ``web/src/x.ts``.+ modules = go_modules if report.source_format == "go-coverprofile" else ()+ _note_format(result, report.source_format)for fc in report.files:report_file_count += 1key, ambiguous, exact = _resolve_path(@@ -541,31 +766,22 @@ def resolve_reports(repo_keys,suffix_index,strip_prefix=strip_prefix,- path_prefix=path_prefix,+ path_prefix=prefix,+ go_modules=modules,)- if key is None:- if ambiguous:- result.ambiguous.append(fc.file_path)- else:- result.unmatched.append(fc.file_path)- continue- if exact:- result.matched_exact += 1- else:- result.matched_suffix += 1- resolved_fc = FileCoverage(- file_path=key,- line_coverage_pct=fc.line_coverage_pct,- branch_coverage_pct=fc.branch_coverage_pct,- covered_lines=list(fc.covered_lines),- total_coverable_lines=fc.total_coverable_lines,- coverable_lines=list(fc.coverable_lines),- covered_line_count=fc.covered_line_count,+ # An entry that resolves is ignored by its key; one that does not,+ # by the path the report wrote.+ where = key or normalize_report_path(+ fc.file_path, strip_prefix=strip_prefix, path_prefix=prefix)- if key in by_key:- _merge_into(by_key[key], resolved_fc)+ if ignore_spec.match_file(where):+ result.ignored += 1+ elif key is None:+ (result.ambiguous if ambiguous else result.unmatched).append(fc.file_path)else:- by_key[key] = resolved_fc+ result.matched_exact += exact+ result.matched_suffix += not exact+ _merge_keyed(by_key, key, fc)# Severe mapping loss is a property of the *report*, not of the matched# subset: a 200-file report that mapped 20 files is a fragment no matter@@ -573,8 +789,10 @@ def resolve_reports(# coverage path already documents as the "treats loss as success" trap# (issue #1746), and it deliberately avoids a hard ratio on the matched# side so monorepos ingesting one package's report stay unflagged.- if report_file_count:- result.mapping_partial = result.matched * 2 < report_file_count+ # Ignored entries were dropped on purpose, so they count on neither side.+ measured_count = report_file_count - result.ignored+ if measured_count:+ result.mapping_partial = result.matched * 2 < measured_countfor key, fc in by_key.items():result.coverage_map[key] = coverage_map_entry(fc, result.source_format)@@ -602,6 +820,8 @@ class ResolvedTestCoverage:ambiguous: list[str] = field(default_factory=list)# How many records had their test's own file resolved to a repo key.test_files_resolved: int = 0+ # Records whose source ``coverage.ignore`` leaves out.+ ignored: int = 0@propertydef matched(self) -> int:@@ -633,21 +853,28 @@ def resolve_test_reports(*,strip_prefix: str | None = None,path_prefix: str | None = None,+ ignore: Sequence[str] = (),) -> ResolvedTestCoverage:"""Resolve per-test records against the indexed tree.Reuses the aggregate path resolver (:func:`normalize_report_path` +:func:`_match_key`) for *both* the source path and the test's own file,so no second resolver is introduced. Records whose source path does not- map to the tree are dropped and counted in ``unmatched`` / ``ambiguous``.+ map to the tree are dropped and counted in ``unmatched`` / ``ambiguous``;+ records whose source *ignore* matches (as in :func:`resolve_reports`) are+ dropped and counted in ``ignored``."""suffix_index = _build_suffix_index(repo_keys)+ ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)out = ResolvedTestCoverage(source_format=report.source_format, has_contexts=report.has_contexts)for rec in report.records:norm = normalize_report_path(rec.file_path, strip_prefix=strip_prefix, path_prefix=path_prefix)key, ambiguous = _match_key(norm, repo_keys, suffix_index)+ if ignore_spec.match_file(key or norm):+ out.ignored += 1+ continueif key is None:if ambiguous:out.ambiguous.append(rec.file_path)@@ -688,13 +915,21 @@ def build_coverage_map(coverage_format: str | None = None,strip_prefix: str | None = None,path_prefix: str | None = None,+ report_prefixes: Mapping[Path, str | None] | None = None,+ ignore: Sequence[str] = (),) -> tuple[ResolvedCoverage, list[tuple[Path, str]]]:"""Read + parse + resolve coverage reports end-to-end.Returns the :class:`ResolvedCoverage` and a list of ``(path, error)``for reports that could not be read or parsed (caller decides how loudto be). Unreadable/empty reports are skipped, never fatal.++ *report_prefixes* gives a report its own prefix (``--report PATH=PREFIX``,+ a ``coverage.paths`` mapping entry), overriding *path_prefix*. *ignore* is+ ``coverage.ignore``. A Go coverprofile's import paths are mapped back to+ the directories of the ``go.mod`` files on disk."""+ prefixes = report_prefixes or {}parsed: list[CoverageReport] = []errors: list[tuple[Path, str]] = []for path in report_paths:@@ -713,9 +948,20 @@ def build_coverage_map(errors.append((path, f"no coverage entries (detected={report.source_format})"))continuereport.origin_dir = _repo_relative_dir(path, repo_root)+ report.path_prefix = prefixes.get(path)parsed.append(report)resolved = resolve_reports(- parsed, repo_keys, strip_prefix=strip_prefix, path_prefix=path_prefix+ parsed,+ repo_keys,+ strip_prefix=strip_prefix,+ path_prefix=path_prefix,+ ignore=ignore,+ # The walk only when a coverprofile needs it.+ go_modules=(+ _go_modules(repo_root)+ if any(r.source_format == "go-coverprofile" for r in parsed)+ else ()+ ),)return resolved, errorsdiff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.pyindex bb1a85663..a6bc022fa 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py@@ -112,6 +112,9 @@ class CoverageReport:# Repo-relative directory of the report file itself, set by whoever read# it from disk; ``None`` when the report did not come from inside the repo.origin_dir: str | None = None+ # Per-report prefix prepended to this report's paths; overrides the+ # configured ``path_prefix`` for this report only.+ path_prefix: str | None = None@dataclassdiff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.pyindex 0395d9f1f..b6df8de85 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py@@ -24,10 +24,12 @@ from __future__ import annotationsimport mathfrom collections.abc import Iterable, Mapping, Sequence-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import PurePosixPathfrom typing import TYPE_CHECKING, Any, Literal, get_args+import pathspec+from ...test_paths import is_test_related_pathfrom ..changed_lines import line_rangesfrom ..health.coverage.freshness import FreshnessStatus@@ -37,7 +39,7 @@ if TYPE_CHECKING:from ..health.coverage.discovery import ResolvedCoverageFileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]-GateStatus = Literal["pass", "fail", "no_data", "not_set"]+GateStatus = Literal["pass", "fail", "no_data", "not_set", "too_small"]@dataclass(frozen=True)@@ -90,6 +92,9 @@ class PatchScope:# but its line numbers describe other code, so every renderer says so.measured_commit: str | None = Nonefreshness: FreshnessStatus = "unknown"+ # Changed files left out by ``coverage.ignore`` before anything was+ # measured. Set by :func:`compute_patch_coverage`.+ ignored_file_count: int = 0def to_dict(self) -> dict[str, Any]:return {@@ -101,6 +106,7 @@ class PatchScope:"mapping_partial": self.mapping_partial,"measured_commit": self.measured_commit,"freshness": self.freshness,+ "ignored_file_count": self.ignored_file_count,}@@ -113,6 +119,9 @@ class PatchCoverage:# Changed files left out because the report does not measure their kind.out_of_scope_count: int = 0scope: PatchScope = field(default_factory=PatchScope)+ # 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@propertydef changed_file_count(self) -> int:@@ -137,7 +146,13 @@ class PatchCoverage:pct = self.patch_coverage_pctif pct is None:return "no_data"- return "pass" if pct >= self.threshold else "fail"+ 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"def with_status(self, status: FileStatus) -> list[FilePatchCoverage]:return [f for f in self.files if f.status == status]@@ -150,6 +165,7 @@ class PatchCoverage:"covered_line_count": self.covered_line_count,"coverable_line_count": self.coverable_line_count,"threshold": self.threshold,+ "min_coverable_lines": self.min_coverable_lines,"gate": self.gate,"file_counts": counts,"files": [f.to_dict() for f in self.files],@@ -164,32 +180,37 @@ def compute_patch_coverage(threshold: float | None = None,scope: PatchScope | None = None,report_paths: Iterable[str] | None = None,+ min_coverable_lines: int | None = None,+ ignore: Sequence[str] = (),) -> PatchCoverage:"""Intersect a change with a coverage report. See the module docstring.*report_paths* is every path the report measures, when *coverage* holdsonly the changed files' entries (a stored report read for one change); it- decides which unlisted files count as ``not_in_report``.+ 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."""measured_suffixes = {PurePosixPath(p).suffix for p in report_paths or coverage}+ ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)files: list[FilePatchCoverage] = []- out_of_scope = 0+ out_of_scope = ignored = 0for path in sorted(changed):lines = set(changed[path])if not lines:continue- fc = coverage.get(path)- if fc is not None:- files.append(_file_patch(path, lines, fc))- elif is_test_related_path(path) or PurePosixPath(path).suffix not in measured_suffixes:+ if ignore_spec.match_file(path):+ ignored += 1+ elif (row := _changed_file(path, lines, coverage, measured_suffixes)) is None:out_of_scope += 1else:- files.append(FilePatchCoverage(path, "not_in_report", len(lines)))+ files.append(row)return PatchCoverage(files=tuple(files),threshold=threshold,out_of_scope_count=out_of_scope,- scope=scope or PatchScope(),+ scope=replace(scope or PatchScope(), ignored_file_count=ignored),+ min_coverable_lines=min_coverable_lines,)@@ -200,6 +221,8 @@ def patch_coverage_from_resolved(threshold: float | None = None,label: str = "",reports: Sequence[str] = (),+ min_coverable_lines: int | None = None,+ ignore: Sequence[str] = (),) -> PatchCoverage:""":func:`compute_patch_coverage` over reports already resolved to repo keys."""unmatched = len(resolved.unmatched) + len(resolved.ambiguous)@@ -207,6 +230,8 @@ def patch_coverage_from_resolved(changed,{fc.file_path: fc for fc in resolved.files},threshold=threshold,+ min_coverable_lines=min_coverable_lines,+ ignore=ignore,scope=PatchScope(label=label,source_formats=tuple(resolved.source_formats),@@ -218,6 +243,21 @@ def patch_coverage_from_resolved()+def _changed_file(+ path: str,+ lines: set[int],+ coverage: Mapping[str, FileCoverage],+ measured_suffixes: set[str],+) -> FilePatchCoverage | None:+ """One changed file's row, or ``None`` when it is out of the report's scope."""+ fc = coverage.get(path)+ if fc is not None:+ return _file_patch(path, lines, fc)+ if is_test_related_path(path) or PurePosixPath(path).suffix not in measured_suffixes:+ return None+ return FilePatchCoverage(path, "not_in_report", len(lines))++def _file_patch(path: str, lines: set[int], fc: FileCoverage) -> FilePatchCoverage:if not fc.coverable_lines:return FilePatchCoverage(path, "no_line_data", len(lines))diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.pyindex 3997270a5..77b63d717 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py@@ -47,6 +47,13 @@ def headline(pc: PatchCoverage, *, markdown: bool = True) -> str:text += f" · below the {fmt_pct(pc.threshold)} gate"elif pc.gate == "pass":text += f" · meets the {fmt_pct(pc.threshold)} gate"+ elif pc.gate == "too_small":+ n = pc.min_coverable_lines+ lines = "line" if n == 1 else "lines"+ text += (+ f" · below the {fmt_pct(pc.threshold)} gate, not applied: fewer than {n} "+ f"changed executable {lines} (min_coverable_lines)"+ )return text@@ -62,6 +69,8 @@ def scope_line(pc: PatchCoverage, *, markdown: bool = True) -> str:files = f"{measured} of {pc.changed_file_count} changed files measured"if pc.out_of_scope_count:files += f", {pc.out_of_scope_count} out of scope"+ if scope.ignored_file_count:+ files += f", {scope.ignored_file_count} ignored by coverage.ignore"parts.append(files)if scope.freshness == "stale":at = f" at {scope.measured_commit[:7]}" if scope.measured_commit else ""@@ -106,8 +115,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. The largest uncovered ranges are marked, capped- at what GitHub displays, with a notice counting the rest.+ 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+ marked, capped at what GitHub displays, with a notice counting the rest."""ranges = sorted(((f.file_path, a, b) for f in pc.with_status("measured") for a, b in f.uncovered_ranges),@@ -124,7 +134,11 @@ def github_annotations(pc: PatchCoverage) -> list[str]:)for path, a, b in ranges]- verdict = [github.error(headline(pc, markdown=False))] if pc.gate == "fail" else []+ verdict = []+ if pc.gate == "fail":+ verdict = [github.error(headline(pc, markdown=False))]+ elif pc.gate == "too_small":+ verdict = [github.notice(headline(pc, markdown=False))]return verdict + github.cap_annotations(warnings, noun="uncovered changed ranges")@@ -151,6 +165,8 @@ def _details(files: list[FilePatchCoverage], where: str) -> list[str]:def _no_data_reason(pc: PatchCoverage) -> str:if not pc.changed_file_count:+ if pc.scope.ignored_file_count:+ return "Every changed file is ignored by coverage.ignore."return "The change has no changed lines."if pc.with_status("no_line_data"):return "The report does not say which lines are executable."diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.pyindex 11f270396..e5087e3f3 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py@@ -7,7 +7,7 @@ REST API, editors) reads what ``coverage add`` or indexing stored. Both end infrom __future__ import annotations-from collections.abc import Iterable, Mapping+from collections.abc import Iterable, Mapping, Sequencefrom sqlalchemy.ext.asyncio import AsyncSession@@ -23,11 +23,14 @@ 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] = (),) -> 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.+ 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."""from repowise.core.persistence.crud import (get_coverage_summary,@@ -48,6 +51,8 @@ async def stored_patch_coverage(changed,coverage,threshold=threshold,+ min_coverable_lines=min_coverable_lines,+ ignore=ignore,report_paths=measured,scope=PatchScope(label=label,diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.pyindex 698d0ccb8..bc57ecad0 100644--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py@@ -190,7 +190,8 @@ def _build_pipeline_coverage(cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))- report_paths = list(explicit_paths) if explicit_paths else cfg.report_paths(repo_path)+ reports = dict.fromkeys(explicit_paths) if explicit_paths else cfg.reports(repo_path)+ report_paths = list(reports)if not report_paths:return {}, [], None, None@@ -202,6 +203,8 @@ def _build_pipeline_coverage(coverage_format=cfg.format,strip_prefix=cfg.strip_prefix,path_prefix=cfg.path_prefix,+ report_prefixes=reports,+ ignore=cfg.ignore,)if progress:diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 6911eb037..cd4408ef0 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@@ -1118,6 +1118,7 @@ async def _patch_coverage_block("""from repowise.core import git_refsfrom repowise.core.analysis.change_risk.features import revspec_head+ from repowise.core.analysis.health.coverage import configured_ignorefrom repowise.core.analysis.patch_coverage import attention_rows, stored_patch_coveragefrom repowise.core.persistence.database import get_session@@ -1136,6 +1137,7 @@ async def _patch_coverage_block(changed,label=result.features.ref,head_commit=head_commit,+ ignore=configured_ignore(ctx.path),)except (LookupError, SQLAlchemyError):return Nonediff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex 005cd5683..f6af5cba3 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@@ -377,12 +377,19 @@ async def health_coverage_patch("""Patch coverage of ``base...head`` from the coverage the index stores.The computation ``repowise coverage check`` gates on. ``null`` when no- coverage has been ingested, which is not the same as 0%.+ coverage has been ingested, which is not the same as 0%. Honours+ ``coverage.ignore``; the small-change tolerance stays with the CLI gate."""+ from repowise.core.analysis.health.coverage import configured_ignorefrom repowise.core.analysis.patch_coverage import stored_patch_coveragechanged, label, head_sha = await asyncio.to_thread(_read_change, repo.local_path, base, head)patch = await stored_patch_coverage(- session, repo.id, changed, label=label, head_commit=head_sha or None+ session,+ repo.id,+ changed,+ label=label,+ head_commit=head_sha or None,+ ignore=configured_ignore(repo.local_path),)return PatchCoverageResponse.model_validate(patch.to_dict()) if patch is not None else Nonediff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.pyindex 661cfc903..c4da540ab 100644--- a/packages/server/src/repowise/server/schemas/patch_coverage.py+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py@@ -50,6 +50,8 @@ class PatchCoverageScope(_Strict):#: ``stale`` when the coverage was measured at another commit than the#: change's head: the figure still computes but describes other code.freshness: FreshnessStatus+ #: Changed files left out by ``coverage.ignore`` before measuring.+ ignored_file_count: intclass PatchCoverageResponse(_Strict):@@ -57,6 +59,9 @@ class PatchCoverageResponse(_Strict):covered_line_count: intcoverable_line_count: intthreshold: float | None+ #: Small-change tolerance: below this many changed executable lines a+ #: missed threshold reads ``too_small`` and does not fail.+ min_coverable_lines: int | Nonegate: GateStatusfile_counts: PatchCoverageFileCountsfiles: list[PatchCoverageFile]diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex c0cb140ee..2e06ec799 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2215,7 +2215,8 @@ export interface PatchCoverageResponse {covered_line_count: number;coverable_line_count: number;threshold: number | null;- gate: "pass" | "fail" | "no_data" | "not_set";+ min_coverable_lines: number | null;+ gate: "pass" | "fail" | "no_data" | "not_set" | "too_small";file_counts: PatchCoverageFileCounts;files: PatchCoverageFile[];scope: PatchCoverageScope;@@ -2230,6 +2231,7 @@ export interface PatchCoverageScope {mapping_partial: boolean;measured_commit: string | null;freshness: "current" | "stale" | "unknown";+ ignored_file_count: number;}/**diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsxindex 76556c704..36221fcf6 100644--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx@@ -13,6 +13,7 @@ function coverage(fileCount: number): PatchCoverageResponse {covered_line_count: fileCount,coverable_line_count: fileCount * 2,threshold: null,+ min_coverable_lines: null,gate: "not_set",file_counts: {measured: fileCount,@@ -39,6 +40,7 @@ function coverage(fileCount: number): PatchCoverageResponse {measured_commit: "abcdef1234",mapping_partial: false,freshness: "current",+ ignored_file_count: 0,},};}@@ -73,5 +75,16 @@ describe("PatchCoverageSummary", () => {render(<PatchCoverageSummary coverage={coverage(1)} />);expect(screen.getByText("1 of 2 changed executable lines covered")).toBeTruthy();expect(screen.queryByText(/measured at/)).toBeNull();+ expect(screen.queryByText(/ignored by/)).toBeNull();+ });++ it("counts changed files coverage.ignore left out", () => {+ const base = coverage(1);+ render(+ <PatchCoverageSummary+ coverage={{ ...base, scope: { ...base.scope, ignored_file_count: 2 } }}+ />,+ );+ expect(screen.getByText(/2 changed files ignored by/)).toBeTruthy();});});diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsxindex 41abcfa21..b2ddfc0a4 100644--- a/packages/ui/src/health/patch-coverage-summary.tsx+++ b/packages/ui/src/health/patch-coverage-summary.tsx@@ -112,6 +112,13 @@ export function PatchCoverageSummary({</p>)}+ {coverage.scope.ignored_file_count > 0 && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {plural(coverage.scope.ignored_file_count, "changed file")} ignored by{" "}+ <code className="font-mono">coverage.ignore</code>+ </p>+ )}+{uncovered.length > 0 && (<ul className="mt-1 flex flex-col gap-0.5">{uncovered.slice(0, MAX_FILES).map((f) => (diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 6f41eb058..7a929911a 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -69,6 +69,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {covered_line_count: 2,coverable_line_count: 3,threshold: null,+ min_coverable_lines: null,gate: "not_set",file_counts: {measured: 1,@@ -109,6 +110,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {measured_commit: "abcdef1234567890",mapping_partial: false,freshness: "stale",+ ignored_file_count: 0,},};diff --git a/tests/unit/analysis/test_patch_coverage.py b/tests/unit/analysis/test_patch_coverage.pyindex 47c5a0f5b..7fe17544e 100644--- a/tests/unit/analysis/test_patch_coverage.py+++ b/tests/unit/analysis/test_patch_coverage.py@@ -66,6 +66,61 @@ def test_gate() -> None:assert compute_patch_coverage({"a.py": {9}}, coverage, threshold=90).gate == "no_data"+def test_small_change_tolerance() -> None:+ # 1 of 2 changed executable lines covered: 50%.+ coverage = _cov("a.py", covered=[1], coverable=[1, 2])+ changed = {"a.py": {1, 2}}++ def gate(threshold, min_lines):+ return compute_patch_coverage(+ changed, coverage, threshold=threshold, min_coverable_lines=min_lines+ ).gate++ assert gate(80, 5) == "too_small"+ # At the minimum the change is big enough to judge.+ assert gate(80, 2) == "fail"+ assert gate(50, 2) == "pass"+ # A pass below the minimum stays a pass; no threshold or no data wins first.+ assert gate(50, 5) == "pass"+ assert gate(None, 5) == "not_set"+ assert compute_patch_coverage(+ {"a.py": {9}}, coverage, threshold=80, min_coverable_lines=5+ ).gate == "no_data"+++def test_too_small_headline_says_the_gate_was_not_applied() -> None:+ coverage = _cov("a.py", covered=[1], coverable=[1, 2])+ pc = compute_patch_coverage({"a.py": {1, 2}}, coverage, threshold=80, min_coverable_lines=5)++ text = headline(pc, markdown=False)+ assert text == (+ "Patch coverage 50.0% (1 of 2 changed executable lines covered) · below the 80.0% "+ "gate, not applied: fewer than 5 changed executable lines (min_coverable_lines)"+ )+ assert pc.to_dict()["min_coverable_lines"] == 5+ lines = github_annotations(pc)+ assert not any(line.startswith("::error") for line in lines)+ # The exemption is visible, not silent.+ assert lines[0].startswith("::notice::Patch coverage 50.0")+ assert "min_coverable_lines" in lines[0]+++def test_ignored_changed_files_are_dropped_and_counted() -> None:+ coverage = _cov("src/a.py", covered=[1], coverable=[1])+ pc = compute_patch_coverage(+ {"src/a.py": {1}, "src/gen/api_pb2.py": {1, 2}, "src/b.py": set()},+ coverage,+ ignore=["**/gen/"],+ )++ assert [f.file_path for f in pc.files] == ["src/a.py"]+ assert pc.scope.ignored_file_count == 1+ assert pc.to_dict()["scope"]["ignored_file_count"] == 1+ assert "1 ignored by coverage.ignore" in render_markdown(pc)+ only_ignored = compute_patch_coverage({"src/gen/x.py": {1}}, coverage, ignore=["src/gen"])+ assert "Every changed file is ignored by coverage.ignore" in headline(only_ignored)++def test_line_ranges() -> None:assert line_ranges([5, 1, 2, 3, 7, 8]) == ((1, 3), (5, 5), (7, 8))assert line_ranges([]) == ()diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.pyindex 160446645..e87802a6c 100644--- a/tests/unit/cli/test_coverage_check_cmd.py+++ b/tests/unit/cli/test_coverage_check_cmd.py@@ -191,6 +191,135 @@ def test_flag_overrides_a_bad_config_threshold(repo) -> None:assert _run(repo, "main...feat", "--report", report, "--fail-under", "50").exit_code == 0+def test_small_change_tolerance_reports_but_does_not_fail(repo) -> None:+ report = _lcov(repo, {1: 1, 2: 1, 3: 0}) # 1 of 2 changed executable lines+ args = ("main...feat", "--report", report, "--fail-under", "80")++ small = _run(repo, *args, "--min-coverable-lines", "5")+ assert small.exit_code == 0, small.output+ assert "not applied: fewer than 5 changed executable lines" in small.output+ github = _run(repo, *args, "--min-coverable-lines", "5", "--format", "github")+ assert github.exit_code == 0+ assert "::notice::Patch coverage 50.0" in github.stdout+ assert _run(repo, *args, "--min-coverable-lines", "2").exit_code == 1+ assert _run(repo, *args, "--min-coverable-lines", "-1").exit_code == 2+++def test_small_change_tolerance_from_config(repo) -> None:+ (repo / ".repowise").mkdir()+ config = repo / ".repowise" / "config.yaml"+ report = _lcov(repo, {2: 1, 3: 0})++ config.write_text("coverage:\n fail_under: 80\n min_coverable_lines: 5\n", encoding="utf-8")+ result = _run(repo, "main...feat", "--report", report, "--format", "json")+ assert result.exit_code == 0, result.output+ data = json.loads(result.stdout)+ assert (data["gate"], data["min_coverable_lines"]) == ("too_small", 5)++ config.write_text("coverage:\n fail_under: 80\n min_coverable_lines: few\n", encoding="utf-8")+ bad = _run(repo, "main...feat", "--report", report, "--format", "json")+ assert bad.exit_code == 2+ assert json.loads(bad.stdout)["error"] == "config_invalid"+ # The flag stands in for a config value it cannot use.+ override = _run(repo, "main...feat", "--report", report, "--min-coverable-lines", "2")+ assert override.exit_code == 1+++def test_report_globs_expand_relative_to_cwd(repo, monkeypatch) -> None:+ from pathlib import Path++ shard = repo / "artifacts" / "unit"+ shard.mkdir(parents=True)+ (shard / "lcov.info").write_text(+ f"SF:{repo / 'src' / 'app.py'}\nDA:2,1\nDA:3,1\nend_of_record\n", encoding="utf-8"+ )+ monkeypatch.chdir(repo)++ result = _run(repo, "main...feat", "--report", "artifacts/**/lcov.info", "--format", "json")+ assert result.exit_code == 0, result.output+ data = json.loads(result.stdout)+ assert data["patch_coverage_pct"] == 100.0+ assert [Path(p) for p in data["scope"]["reports"]] == [Path("artifacts/unit/lcov.info")]+++def test_a_report_argument_matching_no_file_exits_2(repo) -> None:+ for arg in (str(repo / "nope" / "**" / "lcov.info"), str(repo / "missing.lcov")):+ result = _run(repo, "main...feat", "--report", arg, "--format", "json")+ assert result.exit_code == 2, arg+ error = json.loads(result.stdout)+ assert error["error"] == "report_not_found"+ assert arg in error["message"]+++def test_report_path_equals_prefix(repo) -> None:+ report = repo / "web.info"+ report.write_text("SF:app.py\nDA:2,1\nDA:3,1\nend_of_record\n", encoding="utf-8")++ ok = _run(repo, "main...feat", "--report", f"{report}=src", "--format", "json")+ assert ok.exit_code == 0, ok.output+ assert json.loads(ok.stdout)["patch_coverage_pct"] == 100.0+ # The prefix is applied: a wrong one leaves nothing to match.+ assert _run(repo, "main...feat", "--report", f"{report}=nowhere").exit_code == 2+++def test_an_existing_path_holding_equals_is_a_path(repo) -> None:+ report = repo / "cov=v1.info"+ report.write_text(+ f"SF:{repo / 'src' / 'app.py'}\nDA:2,1\nDA:3,1\nend_of_record\n", encoding="utf-8"+ )+ result = _run(repo, "main...feat", "--report", str(report), "--format", "json")+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["patch_coverage_pct"] == 100.0+++def test_a_glob_holding_equals_stays_one_pattern(repo, monkeypatch) -> None:+ shard = repo / "artifacts" / "shard=1"+ shard.mkdir(parents=True)+ (shard / "unit.info").write_text(+ f"SF:{repo / 'src' / 'app.py'}\nDA:2,1\nDA:3,1\nend_of_record\n", encoding="utf-8"+ )+ monkeypatch.chdir(repo)++ result = _run(repo, "main...feat", "--report", "artifacts/shard=1/*.info", "--format", "json")+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["patch_coverage_pct"] == 100.0+++def test_every_report_entry_ignored_exits_2_with_its_own_message(repo) -> None:+ (repo / ".repowise").mkdir()+ (repo / ".repowise" / "config.yaml").write_text(+ "coverage:\n ignore: [src/]\n", encoding="utf-8"+ )+ report = _lcov(repo, {2: 1, 3: 0})++ result = _run(repo, "main...feat", "--report", report, "--format", "json")+ assert result.exit_code == 2+ assert json.loads(result.stdout)["error"] == "report_all_ignored"+++def test_coverage_ignore_drops_changed_files_and_report_entries(repo) -> None:+ (repo / ".repowise").mkdir()+ (repo / ".repowise" / "config.yaml").write_text(+ "coverage:\n ignore: [src/new.py]\n", encoding="utf-8"+ )+ report = repo / "coverage.lcov"+ report.write_text(+ f"SF:{repo / 'src' / 'app.py'}\nDA:2,1\nDA:3,0\nend_of_record\n"+ f"SF:{repo / 'src' / 'new.py'}\nDA:1,0\nend_of_record\n",+ encoding="utf-8",+ )+ result = _run(repo, "main...feat", "--report", str(report), "--format", "json")+ assert result.exit_code == 0, result.output+ data = json.loads(result.stdout)+ assert [f["file_path"] for f in data["files"]] == ["src/app.py"]+ assert data["scope"]["ignored_file_count"] == 1+ # The ignored entry is neither a match nor a miss.+ assert (data["scope"]["report_path_count"], data["scope"]["unmatched_report_path_count"]) == (+ 1,+ 0,+ )++def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:from repowise.cli.ci import CannotEvaluateErrorfrom repowise.cli.commands.coverage_check_cmd import _gateablediff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex ce3f20fcb..cc6995910 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -211,3 +211,15 @@ def test_telemetry_tail_match_does_not_resolve_every_command() -> None:"""loaded = _dispatch_and_report_loaded(["hook", "stats", "--help"])assert loaded == "['hook_cmd']", loaded+++def test_the_root_group_leaves_wildcard_arguments_to_the_commands(monkeypatch) -> None:+ """Click's Windows wildcard expansion is off, so a quoted glob stays one argument."""+ seen: dict = {}++ def _main(self, *args, **kwargs):+ seen.update(kwargs)++ monkeypatch.setattr(click.Group, "main", _main)+ cli.main(["--version"])+ assert seen["windows_expand_args"] is Falsediff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.pyindex 7660942f0..1ac367460 100644--- a/tests/unit/health/test_coverage_discovery.py+++ b/tests/unit/health/test_coverage_discovery.py@@ -13,6 +13,7 @@ from repowise.core.analysis.health.coverage import (CoverageConfig,build_coverage_map,discover_artifacts,+ expand_report_patterns,normalize_report_path,resolve_reports,)@@ -342,6 +343,213 @@ def test_coverage_config_parses_block() -> None:assert cfg.reingest_on_update is True+def test_coverage_config_paths_take_globs_and_per_report_prefixes(tmp_path: Path) -> None:+ for rel in ("web/coverage/lcov.info", "api/coverage/lcov.info", "root.lcov"):+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text("")+ cfg = CoverageConfig.from_repo_config(+ {+ "coverage": {+ "paths": [+ {"path": "*/coverage/lcov.info", "path_prefix": "pkg"},+ "root.lcov",+ "missing.lcov",+ {"path_prefix": "no-path"},+ ],+ "ignore": ["gen/", "**/*_pb2.py"],+ "min_coverable_lines": 5,+ }+ }+ )++ assert cfg.paths == ("*/coverage/lcov.info", "root.lcov", "missing.lcov")+ assert cfg.ignore == ("gen/", "**/*_pb2.py")+ assert cfg.min_coverable_lines == 5+ assert cfg.reports(tmp_path) == {+ tmp_path / "api/coverage/lcov.info": "pkg",+ tmp_path / "web/coverage/lcov.info": "pkg",+ tmp_path / "root.lcov": None,+ }+++def test_coverage_config_rejects_a_bad_min_coverable_lines() -> None:+ for bad in (-1, "5", 2.5, True):+ cfg = CoverageConfig.from_repo_config({"coverage": {"min_coverable_lines": bad}})+ assert cfg.min_coverable_lines is None+++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)+ (tmp_path / rel).write_text("")++ found = expand_report_patterns(["**/lcov.info", "b/lcov.info", "none/*.info"], tmp_path)+ assert found == [tmp_path / "a/deep/lcov.info", tmp_path / "b/lcov.info"]+++def test_expand_report_patterns_never_walks_dependency_trees(tmp_path: Path) -> None:+ for rel in ("web/coverage/lcov.info", "node_modules/x/coverage/lcov.info"):+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text("")++ assert expand_report_patterns(["**/lcov.info"], tmp_path) == [+ tmp_path / "web/coverage/lcov.info"+ ]+ # Leading literal directories, absolute ones too, root the walk.+ absolute = (tmp_path / "web").as_posix() + "/**/lcov.info"+ assert expand_report_patterns([absolute], Path()) == [tmp_path / "web/coverage/lcov.info"]+++def test_an_existing_path_is_taken_literally_before_globbing(tmp_path: Path) -> None:+ odd = tmp_path / "cov[1].info"+ odd.write_text("")+ assert expand_report_patterns(["cov[1].info"], tmp_path) == [odd]+++# ---------------------------------------------------------------------------+# Per-report prefix, coverage.ignore, Go modules+# ---------------------------------------------------------------------------+++def test_a_reports_own_prefix_wins_over_the_global_one() -> None:+ keys = {"web/src/a.ts", "api/src/a.ts"}+ web = CoverageReport(source_format="lcov", files=[_fc("src/a.ts")], path_prefix="web")+ res = resolve_reports([web, _report([_fc("src/a.ts")])], keys, path_prefix="api")+ assert sorted(res.coverage_map) == ["api/src/a.ts", "web/src/a.ts"]+++def test_a_per_report_prefix_skips_the_report_directory_step() -> None:+ # Under its own directory the report would resolve to pkg/src/a.ts.+ keys = {"pkg/src/a.ts", "lib/src/a.ts"}+ report = CoverageReport(+ source_format="lcov", files=[_fc("src/a.ts")], origin_dir="pkg", path_prefix="lib"+ )+ assert list(resolve_reports([report], keys).coverage_map) == ["lib/src/a.ts"]+++def test_build_coverage_map_applies_report_prefixes(tmp_path: Path) -> None:+ report_path = tmp_path / "artifacts" / "web.info"+ report_path.parent.mkdir()+ report_path.write_text("SF:src/a.ts\nDA:1,1\nend_of_record\n")++ res, errors = build_coverage_map(+ tmp_path, [report_path], {"web/src/a.ts"}, report_prefixes={report_path: "web"}+ )+ assert not errors+ assert list(res.coverage_map) == ["web/src/a.ts"]+++def test_ignored_report_entries_are_dropped_and_counted_apart() -> None:+ keys = {"src/a.py", "src/gen/b_pb2.py", "src/gen/c_pb2.py"}+ report = _report(+ [_fc("src/a.py"), _fc("src/gen/b_pb2.py"), _fc("src/gen/c_pb2.py"), _fc("/x/zz.py")]+ )+ res = resolve_reports([report], keys, ignore=["*_pb2.py"])++ assert list(res.coverage_map) == ["src/a.py"]+ assert res.ignored == 2+ assert res.unmatched == ["/x/zz.py"]+ # 1 of the 2 entries that were not ignored mapped: not a fragment.+ assert res.mapping_partial is False+ assert res.total == 2+++def test_ignore_also_drops_entries_that_resolve_to_nothing() -> None:+ # Generated code that is not in the repository at all.+ report = _report([_fc("src/a.py"), _fc("/ci/build/gen/api_pb2.py"), _fc("/ci/gen/b.py")])+ res = resolve_reports([report], {"src/a.py"}, ignore=["gen/"])++ assert res.ignored == 2+ assert res.unmatched == []+ assert res.mapping_partial is False+++def test_ignore_drops_per_test_records() -> None:+ from repowise.core.analysis.health.coverage import resolve_test_reports+ from repowise.core.analysis.health.coverage.model import (+ ContextCoverageReport,+ TestCoverage,+ )++ report = ContextCoverageReport(+ source_format="coverage.py",+ has_contexts=True,+ records=[+ TestCoverage("t::a", "src/a.py", [1]),+ TestCoverage("t::b", "src/gen/b.py", [1]),+ ],+ )+ res = resolve_test_reports(report, {"src/a.py", "src/gen/b.py"}, ignore=["gen/"])+ assert [r.file_path for r in res.records] == ["src/a.py"]+ assert res.ignored == 1+++def _go_repo(tmp_path: Path) -> Path:+ backend = tmp_path / "backend"+ (backend / "pkg").mkdir(parents=True)+ (backend / "go.mod").write_text('module "example.com/m" // the service\n\ngo 1.22\n')+ (backend / "main.go").write_text("package main\n")+ (backend / "pkg" / "x.go").write_text("package pkg\n")+ (tmp_path / "main.go").write_text("package other\n")+ profile = tmp_path / "coverage.out"+ profile.write_text(+ "mode: set\n"+ "example.com/m/main.go:3.13,5.2 1 1\n"+ "example.com/m/pkg/x.go:3.13,5.2 1 0\n"+ )+ return profile+++def test_go_module_paths_map_to_the_module_directory(tmp_path: Path) -> None:+ profile = _go_repo(tmp_path)+ # Indexed keys hold source files only: go.mod is found on disk.+ keys = {"backend/main.go", "backend/pkg/x.go", "main.go"}++ res, errors = build_coverage_map(tmp_path, [profile], keys)+ assert not errors+ assert sorted(res.coverage_map) == ["backend/main.go", "backend/pkg/x.go"]+ assert res.matched_exact == 2+ # An explicit prefix, per report or global, says where the paths live.+ prefixed, _ = build_coverage_map(+ tmp_path, [profile], keys, report_prefixes={profile: "elsewhere"}+ )+ assert "backend/main.go" not in prefixed.coverage_map+ global_prefix, _ = build_coverage_map(tmp_path, [profile], keys, path_prefix="elsewhere")+ assert "backend/main.go" not in global_prefix.coverage_map+++def test_a_duplicate_go_module_path_resolves_to_the_shallowest(tmp_path: Path) -> None:+ from repowise.core.analysis.health.coverage.discovery import _go_modules++ _go_repo(tmp_path)+ for copy in ("examples/deep/copy", "backend/testdata/fixture"):+ (tmp_path / copy).mkdir(parents=True)+ (tmp_path / copy / "go.mod").write_text("module example.com/m\n")+ (tmp_path / "tools").mkdir()+ (tmp_path / "tools" / "go.mod").write_text("module example.com/m/tools\n")++ assert _go_modules(tmp_path) == [("example.com/m/tools", "tools"), ("example.com/m", "backend")]+++def test_a_short_go_module_never_rewrites_other_formats(tmp_path: Path) -> None:+ (tmp_path / "web" / "src").mkdir(parents=True)+ (tmp_path / "web" / "go.mod").write_text("module web\n")+ lcov = tmp_path / "lcov.info"+ lcov.write_text("SF:web/src/x.ts\nDA:1,1\nend_of_record\n")++ res, _ = build_coverage_map(tmp_path, [lcov], {"web/src/x.ts", "web/web/src/x.ts"})+ assert list(res.coverage_map) == ["web/src/x.ts"]+++def test_the_longest_go_module_wins() -> None:+ from repowise.core.analysis.health.coverage.discovery import _in_go_module++ modules = [("example.com/m/tools", "tools"), ("example.com/m", "")]+ assert _in_go_module("example.com/m/tools/gen.go", modules) == "tools/gen.go"+ assert _in_go_module("example.com/m/main.go", modules) == "main.go"+ assert _in_go_module("example.com/mx/main.go", modules) is None++# ---------------------------------------------------------------------------# Directory agreement, report location and Cobertura source roots# ---------------------------------------------------------------------------diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.pyindex 9e7add53c..222ff8759 100644--- a/tests/unit/server/mcp/test_tool_change_risk.py+++ b/tests/unit/server/mcp/test_tool_change_risk.py@@ -388,6 +388,17 @@ async def test_patch_coverage_is_the_gate_computation_on_stored_coverage()assert dirty["scope"]["freshness"] == "unknown"+ # coverage.ignore reaches the agent surface as it does the CLI gate.+ (tmp_path / ".repowise").mkdir(exist_ok=True)+ (tmp_path / ".repowise" / "config.yaml").write_text(+ "coverage:\n ignore: [a.py]\n", encoding="utf-8"+ )+ ignored = await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, "main...HEAD", _scored(), _collector(tmp_path)+ )+ assert ignored["scope"]["ignored_file_count"] == 1+ assert ignored["patch_coverage_pct"] is None+@pytest.mark.asyncioasync 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.pyindex 93e08e9f3..19c4f9a66 100644--- a/tests/unit/server/test_patch_coverage_schema.py+++ b/tests/unit/server/test_patch_coverage_schema.py@@ -13,11 +13,20 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:"b.py": file_coverage("b.py", [1], []),"c.py": file_coverage("c.py", [1], [1]),}- changed = {"a.py": {1, 2, 3}, "b.py": {1}, "c.py": {9}, "new.py": {1}, "t/test_x.py": {1}}+ changed = {+ "a.py": {1, 2, 3},+ "b.py": {1},+ "c.py": {9},+ "new.py": {1},+ "t/test_x.py": {1},+ "gen/out.py": {1},+ }pc = compute_patch_coverage(changed,coverage,threshold=80,+ min_coverable_lines=5,+ ignore=["gen/"],scope=PatchScope(label="main...HEAD",source_formats=("lcov",),@@ -37,4 +46,5 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:"no_coverable_changes","not_in_report",}+ assert (wire["gate"], wire["scope"]["ignored_file_count"]) == ("too_small", 1)assert PatchCoverageResponse.model_validate(wire).model_dump() == wirediff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 134d78c5d..06ca1461a 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -260,3 +260,12 @@ async def test_patch_coverage_reads_stored_coverage(assert data["scope"]["freshness"] == "current"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()+ assert ignored["scope"]["ignored_file_count"] == 1+ assert ignored["files"] == []diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.pyindex a1687f5e1..c8024d09f 100644--- a/tests/unit/test_ci_action.py+++ b/tests/unit/test_ci_action.py@@ -148,6 +148,13 @@ def test_the_default_branch_job_writes_the_doc_drift_report(tmp_path, fake_repowassert json.loads(doc_drift.read_text(encoding="utf-8")) == json.loads(_ISSUE)+def test_the_gitlab_coverage_job_leaves_globs_to_repowise() -> None:+ script = yaml.safe_load(GITLAB.read_text(encoding="utf-8"))["repowise-coverage"]["script"]+ # Globbing off before the unquoted, space-split report list is expanded.+ assert script[0] == "set -f"+ assert "--min-coverable-lines" in script[1]++@pytest.fixturedef fake_repowise(tmp_path: Path) -> Path:"""A ``repowise`` that logs its arguments and exits with ``$FAKE_<GATE>``.@@ -207,6 +214,7 @@ def _run(tmp_path: Path, bin_dir: Path, **env: str) -> tuple[int, str, str]:"BASE": "","COVERAGE_REPORT": "","COVERAGE_FAIL_UNDER": "",+ "COVERAGE_MIN_COVERABLE_LINES": "","DOC_DRIFT_BASELINE": "","SECURITY_FAIL_ON": "high","SECURITY_BASELINE": "",@@ -240,15 +248,18 @@ def test_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:fake_repowise,CHECKS="coverage, security",BASE="origin/main...HEAD",- COVERAGE_REPORT="a.info\nb.xml",+ COVERAGE_REPORT="a.info\nartifacts/**/lcov.info=web",COVERAGE_FAIL_UNDER="80",+ COVERAGE_MIN_COVERABLE_LINES="5",SECURITY_BASELINE=".security-baseline.json",)assert code == 0coverage, security = calls.splitlines()+ # The glob reaches repowise unexpanded, with its prefix.assert coverage == ("coverage check origin/main...HEAD --format github "- "--report a.info --report b.xml --fail-under 80"+ "--report a.info --report artifacts/**/lcov.info=web --fail-under 80 "+ "--min-coverable-lines 5")assert security == ("security check origin/main...HEAD --fail-on high "