Skip to content

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

feat(ci): fail security and doc-drift gates when the committed baseline grows (#4299)

Raghav Chamadiya34b6d8b1e160
diff --git a/action.yml b/action.yml
index 4f4ca25a4..2da0464c0 100644
--- a/action.yml
+++ b/action.yml
@@ -88,6 +88,12 @@ inputs:
security-baseline:
description: Committed security baseline file; only findings it does not list fail.
default: ""
+ fail-on-baseline-growth:
+ description: >-
+ "true" fails doc-drift and security when their baseline lists a finding
+ the same file at the change's base does not, so a change cannot hide new
+ findings by re-saving the baseline. A baseline new in the change passes.
+ default: "false"
risk-fail-above-percentile:
description: >-
Fail when the change ranks above this percentile of the repository's
@@ -180,6 +186,7 @@ runs:
DOC_DRIFT_BASELINE: ${{ inputs.doc-drift-baseline }}
SECURITY_FAIL_ON: ${{ inputs.security-fail-on }}
SECURITY_BASELINE: ${{ inputs.security-baseline }}
+ FAIL_ON_BASELINE_GROWTH: ${{ inputs.fail-on-baseline-growth }}
RISK_FAIL_ABOVE_PERCENTILE: ${{ inputs.risk-fail-above-percentile }}
SARIF: ${{ inputs.upload-sarif }}
SARIF_DIR: ${{ runner.temp }}/repowise-sarif
diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.sh
index 7bccfe5d4..9f9c7c95d 100644
--- a/ci/github/run-gates.sh
+++ b/ci/github/run-gates.sh
@@ -25,8 +25,11 @@ for name in $names; do
done
# Coverage, security and risk diff the change, so they need its history and
-# the target branch; risk also ranks it against recent commits.
-if wants coverage || wants security || wants risk; then
+# the target branch; risk also ranks it against recent commits. Baseline growth
+# reads the doc-drift baseline at the change's base.
+growth=()
+[[ "${FAIL_ON_BASELINE_GROWTH:-}" == "true" ]] && growth=(--fail-on-baseline-growth)
+if wants coverage || wants security || wants risk || { wants doc-drift && [[ -n "$DOC_DRIFT_BASELINE" && ${#growth[@]} -gt 0 ]]; }; then
here=${0//\\//}
source "${here%/*}/fetch-base.sh"
fi
@@ -70,9 +73,9 @@ if wants coverage; then
fi
drift=(doc-drift --check)
-[[ -n "$DOC_DRIFT_BASELINE" ]] && drift+=(--baseline "$DOC_DRIFT_BASELINE")
+[[ -n "$DOC_DRIFT_BASELINE" ]] && drift+=(--baseline "$DOC_DRIFT_BASELINE" ${growth[@]+"${growth[@]}"})
security=(security check ${base[@]+"${base[@]}"} --fail-on "$SECURITY_FAIL_ON")
-[[ -n "$SECURITY_BASELINE" ]] && security+=(--baseline "$SECURITY_BASELINE")
+[[ -n "$SECURITY_BASELINE" ]] && security+=(--baseline "$SECURITY_BASELINE" ${growth[@]+"${growth[@]}"})
wants doc-drift && run doc-drift repowise "${drift[@]}" --format github
wants security && run security repowise "${security[@]}" --format github
diff --git a/docs/layers/DOC_DRIFT.md b/docs/layers/DOC_DRIFT.md
index 4c0e9360a..1434aecbf 100644
--- a/docs/layers/DOC_DRIFT.md
+++ b/docs/layers/DOC_DRIFT.md
@@ -162,7 +162,8 @@ repowise doc-drift --check --baseline .doc-drift-baseline.json
Baseline entries are keyed on the document, the reference class and the target,
not the line number, so editing a document above a known finding does not turn
-it back into a new one.
+it back into a new one. Add `--fail-on-baseline-growth` in CI to fail a change
+that adds entries to the committed baseline instead of fixing the drift.
On a pull request you can instead gate only the drift the change is answerable
for, with no baseline to maintain:
diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.md
index bd8b507ff..2b67a016f 100644
--- a/docs/layers/SECURITY.md
+++ b/docs/layers/SECURITY.md
@@ -285,6 +285,7 @@ result as a place to look.
| `--fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low` |
| `--baseline FILE` | none | Accept findings listed in this file |
| `--write-baseline FILE` | none | Add this change's findings to the file and exit 0 |
+| `--fail-on-baseline-growth` | off | Exit 1 when `--baseline` lists a finding the file at the change's base does not |
| `--staged` | off | Check staged changes; takes no revspec |
| `--path DIR` | cwd | A path inside the repository |
| `--format` | `table` | `table`, `json`, `markdown`, `github`, `sarif`, `gitlab` |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 1e047b188..ac8cd7b30 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -823,6 +823,7 @@ to check, never applied.
| `--fail-on-confidence` | With `--check`, fail on findings at or above this confidence (default: 0.7) |
| `--baseline` | With `--check`, accept the findings recorded in this file; only new ones fail |
| `--write-baseline` | With `--check`, record the current findings to this file and exit 0 |
+| `--fail-on-baseline-growth` | With `--baseline`, exit 1 when the file lists a finding the same file at the change's base does not (the `--since` base, else the CI target branch). A baseline the base lacks is new and passes |
| `--since` | With `--check`, gate only drift this change is answerable for: documents it edits, documents naming files it deletes or renames, anchors into documents it edits, commands whose manifest it edits, and symbols whose defining file it edits or removes. A bare ref means `REF...HEAD` plus uncommitted changes; `auto` reads the target branch from CI |
| `--format` | Output: `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
@@ -1030,6 +1031,7 @@ default branch.
| `--fail-on` | Exit 1 on a finding of this severity or above: `high` (default), `med`, `low`. A secret under a test, fixture, spec, mock or example path is `low` |
| `--baseline` | Accept the findings recorded in this file; only new ones fail |
| `--write-baseline` | Add this change's findings to this file, keeping its entries and those of `--baseline`, and exit 0 |
+| `--fail-on-baseline-growth` | With `--baseline`, exit 1 when the file lists a finding the same file at the change's base does not, so a re-saved baseline cannot hide new findings. A baseline the base lacks is new and passes |
| `--path` | A path inside the repository (defaults to cwd) |
| `--staged` | Check the staged lines, read from the index, for a pre-commit hook: no history scan, no REVSPEC; `security.patterns` still comes from the working tree |
| `--format` | `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 439155d3e..0acc27f13 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -88,6 +88,11 @@ Security has a baseline too, for accepting a finding a change adds on purpose
from then on. A `repowise-security-ignore` comment silences one false positive
([details](../layers/SECURITY.md#silencing-one-finding-repowise-security-ignore)).
+`--fail-on-baseline-growth` (the action's `fail-on-baseline-growth` input) keeps a
+baseline shrink-only: it fails either gate when the baseline lists a finding the
+same file at the change's base does not, so a change cannot hide new findings by
+re-saving it. A baseline the change adds for the first time passes.
+
## GitHub Actions
The repository is itself an action. It installs Repowise, runs the gates you
@@ -134,6 +139,7 @@ release the action installs.
| `doc-drift-baseline` | none | Committed baseline file. |
| `security-fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low`. |
| `security-baseline` | none | Committed baseline file. |
+| `fail-on-baseline-growth` | `false` | Fail doc drift and security when their baseline gains an entry over the change's base. |
| `risk-fail-above-percentile` | none | With `risk` in `checks`, fail when the change ranks above this percentile of recent commits. Empty reports the rank without gating. |
| `upload-sarif` | `false` | Upload doc drift and security findings to code scanning. |
| `impacted-tests` | `false` | Select the tests the change needs (needs a cached `.repowise` index); see [below](#selecting-the-tests-a-change-needs). |
diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.py
index 5e32c651c..e26cce637 100644
--- a/packages/cli/src/repowise/cli/ci.py
+++ b/packages/cli/src/repowise/cli/ci.py
@@ -116,6 +116,80 @@ def change_set(root: str, revspec: str | None, *, staged: bool = False) -> Any:
return read_change_set(root, revspec, staged=staged)
+def baseline_growth(root: Path, path: Path, revspec: str | None) -> list[dict]:
+ """The entries the baseline at *path* adds over the same file at the change's base.
+
+ The base is the commit *revspec*'s diff starts from, or ``HEAD`` for staged
+ changes (``None``). This reads both sides from the checkout and git; the
+ comparison is :func:`repowise.core.ci.baseline.baseline_growth`.
+ """
+ import subprocess
+
+ from repowise.core import git_refs
+ from repowise.core.analysis.git_cat_file import cat_file_batch
+ from repowise.core.ci.baseline import BaselineError
+ from repowise.core.ci.baseline import baseline_growth as growth_between
+
+ try:
+ relative = path.resolve().relative_to(root.resolve()).as_posix()
+ except ValueError:
+ raise CannotEvaluateError(
+ "baseline_outside_repository",
+ f"Baseline growth is read from git history, and {path} is outside the "
+ f"repository at {root}.",
+ ) from None
+ if revspec is None:
+ base = git_refs.resolve(str(root), "HEAD")
+ else:
+ base = git_refs.change_base(str(root), revspec)
+ if not base:
+ raise CannotEvaluateError(
+ "base_not_found",
+ f"Could not find the base of {revspec or 'the staged changes'} to compare "
+ f"the baseline with. {SHALLOW_CLONE_HINT}",
+ )
+ try:
+ # A resolved commit, so a miss is the file the base lacks, not an unknown rev.
+ # ``./`` resolves against *root*, which may sit below the git toplevel.
+ read = cat_file_batch(str(root), [f"{base}:./{relative}"], check=True)
+ head = path.read_bytes()
+ except (subprocess.SubprocessError, OSError) as exc:
+ raise CannotEvaluateError("git_failed", f"Could not read the baseline: {exc}") from exc
+ try:
+ return growth_between(read[0][1] if read else None, head, name=str(path))
+ except BaselineError as exc:
+ raise CannotEvaluateError("baseline_unreadable", str(exc)) from exc
+
+
+def report_baseline_growth(fmt: str, path: Path | None, added: list[dict] | None) -> None:
+ """Say which entries *path* gained, if any; the caller exits :data:`EXIT_GATE_FAILED`.
+
+ ``json`` carries them in its own document; ``github`` adds an ``::error::``.
+ """
+ from rich.markup import escape
+
+ from repowise.core.ci.github import error
+
+ if fmt == "json" or not added:
+ return
+ noun = "entry" if len(added) == 1 else "entries"
+ header = (
+ f"Baseline grew: {path} lists {len(added)} {noun} its base does not. A baseline "
+ "only shrinks; fix the new findings instead of accepting them."
+ )
+ rows = [
+ " ".join(str(e[k]) for k in ("file_path", "kind", "target") if e.get(k))
+ or e["fingerprint"]
+ for e in added
+ ]
+ if fmt == "github":
+ click.echo(error(f"{header} Added: {'; '.join(rows)}"))
+ notices = ci_notices(fmt)
+ notices.print(f"[red]{escape(header)}[/red]")
+ for row in rows:
+ notices.print(f" {escape(row)}")
+
+
@contextlib.contextmanager
def _reading_change(what: str, *, shallow_hint: bool = True) -> Iterator[None]:
"""Turn a failed diff of *what* into :class:`CannotEvaluateError`."""
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
index 89a8c2df8..22b098925 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -16,9 +16,13 @@ from repowise.cli.ci import (
CI_FORMATS,
EXIT_GATE_FAILED,
SHALLOW_CLONE_HINT,
+ CannotEvaluateError,
append_step_summary,
+ baseline_growth,
cannot_evaluate,
ci_notices,
+ ci_revspec,
+ report_baseline_growth,
)
from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
from repowise.cli.output import emit_json, emit_refusal, format_option
@@ -297,6 +301,7 @@ def _run_check(
baseline_path: Path | None,
write_baseline_path: Path | None,
since: str | None = None,
+ fail_on_growth: bool = False,
) -> None:
from repowise.cli.helpers import silence_logs_for_machine_output_until_close
from repowise.core.analysis.doc_drift.gate import evaluate_gate
@@ -326,6 +331,7 @@ def _run_check(
return
baseline = _read_check_baseline(baseline_path, fmt)
+ grown = _baseline_growth(root, baseline_path, since, fmt) if fail_on_growth else None
gate = evaluate_gate(findings, fail_on=fail_on, baseline=baseline)
payload = _payload(root, findings, min_confidence)
payload.update(
@@ -336,8 +342,11 @@ def _run_check(
)
if scope is not None:
payload["scope"] = scope
+ if grown is not None:
+ payload["baseline_growth"] = grown
_emit(fmt, payload, gate=gate, report=report, accepted=baseline or frozenset())
- if not gate.passed:
+ report_baseline_growth(fmt, baseline_path, grown)
+ if not gate.passed or grown:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
@@ -379,6 +388,21 @@ def _read_check_baseline(path: Path | None, fmt: str) -> frozenset[str] | None:
cannot_evaluate(fmt, "baseline_unreadable", str(exc))
+def _baseline_growth(root: Path, path: Path | None, since: str | None, fmt: str) -> list[dict]:
+ """The entries *path* adds over its base: *since*'s, else the CI target branch's."""
+ from repowise.core.analysis.change_risk.features import split_revspec
+
+ if path is None: # the command refuses the flag without --baseline
+ return []
+ try:
+ revspec = ci_revspec(str(root), None if since in (None, "auto") else since)
+ if split_revspec(revspec) is None:
+ revspec = f"{revspec}...HEAD" # a bare ref, as --since reads it
+ return baseline_growth(root, path, revspec)
+ except CannotEvaluateError as exc:
+ cannot_evaluate(fmt, exc.code, str(exc))
+
+
@click.command("doc-drift")
@click.argument("path", required=False, default=None)
@click.option(
@@ -434,6 +458,17 @@ def _read_check_baseline(path: Path | None, fmt: str) -> frozenset[str] | None:
default=None,
help="With --check, record the current findings to this file and exit 0.",
)
+ "--fail-on-baseline-growth",
+ "fail_on_growth",
+ is_flag=True,
+ default=False,
+ help=(
+ "With --baseline, exit 1 when the file lists a finding the same file at the "
+ "change's base does not (the --since base, else the CI target branch). A "
+ "baseline the base lacks is new and passes."
+ ),
+)
@click.option(
"--since",
metavar="REVSPEC",
@@ -464,6 +499,7 @@ def doc_drift_command(
fail_on_confidence: float,
baseline_path: Path | None,
write_baseline_path: Path | None,
+ fail_on_growth: bool,
since: str | None,
repo_alias: str | None,
no_workspace: bool,
@@ -474,6 +510,8 @@ def doc_drift_command(
raise click.UsageError("--baseline and --write-baseline require --check.")
if since is not None and not check:
raise click.UsageError("--since requires --check.")
+ if fail_on_growth and (baseline_path is None or write_baseline_path is not None):
+ raise click.UsageError("--fail-on-baseline-growth needs --baseline, not --write-baseline.")
if since is not None and write_baseline_path:
raise click.UsageError("--write-baseline records every finding; drop --since.")
root = _repo_path(path, repo_alias, no_workspace, fmt)
@@ -489,6 +527,7 @@ def doc_drift_command(
baseline_path=baseline_path,
write_baseline_path=write_baseline_path,
since=since,
+ fail_on_growth=fail_on_growth,
)
return
diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.py
index 586562062..8bcb26cf2 100644
--- a/packages/cli/src/repowise/cli/commands/security_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py
@@ -6,7 +6,8 @@ Subcommands:
the same pattern registry the indexer uses, and persist any secrets or
risky patterns into the shared ``security_findings`` table — tagged with
the commit that introduced them. Re-runs are idempotent.
- check [REVSPEC | --staged] [--fail-on high|med|low] [--baseline FILE] [--format ...]
+ check [REVSPEC | --staged] [--fail-on high|med|low] [--baseline FILE]
+ [--fail-on-baseline-growth] [--format ...]
Gate a change on the findings it adds: its changed lines at the head,
plus secrets committed and removed inside it. Git only, no index and no
database; exit codes are the shared CI ones (:mod:`repowise.cli.ci`).
@@ -26,10 +27,13 @@ from repowise.cli.ci import (
EXIT_GATE_FAILED,
CannotEvaluateError,
append_step_summary,
+ baseline_growth,
cannot_evaluate,
change_lines,
ci_notices,
+ ci_revspec,
repo_root,
+ report_baseline_growth,
)
from repowise.cli.helpers import (
console,
@@ -237,6 +241,15 @@ def security_scan(
help="Add this change's findings to this file, keeping its entries and those of "
"--baseline, and exit 0.",
)
+ "--fail-on-baseline-growth",
+ "fail_on_growth",
+ is_flag=True,
+ default=False,
+ help="Exit 1 when --baseline lists a finding the same file at the change's base "
+ "does not, so a re-saved baseline cannot hide new findings. A baseline the base "
+ "lacks is new and passes.",
+)
@click.option(
"--path",
"repo",
@@ -261,6 +274,7 @@ def security_check(
fail_on: str,
baseline_path: Path | None,
write_baseline_path: Path | None,
+ fail_on_growth: bool,
repo: str | None,
staged: bool,
fmt: str,
@@ -292,11 +306,22 @@ def security_check(
"""
if staged and revspec:
raise click.UsageError("--staged checks the staged changes; drop REVSPEC.")
+ if fail_on_growth and (baseline_path is None or write_baseline_path is not None):
+ raise click.UsageError("--fail-on-baseline-growth needs --baseline, not --write-baseline.")
if fmt != "table":
silence_logs_for_machine_output_until_close()
try:
_check(
- _CheckOptions(revspec, fail_on, baseline_path, write_baseline_path, repo, staged, fmt)
+ _CheckOptions(
+ revspec,
+ fail_on,
+ baseline_path,
+ write_baseline_path,
+ repo,
+ staged,
+ fmt,
+ fail_on_growth=fail_on_growth,
+ )
)
except (click.exceptions.Exit, click.ClickException, click.Abort):
raise
@@ -316,6 +341,7 @@ class _CheckOptions:
repo: str | None
staged: bool
fmt: str
+ fail_on_growth: bool = False
@dataclass(frozen=True)
@@ -327,12 +353,15 @@ class _Verdict:
label: str
accepted: frozenset[str]
patterns: tuple[CustomPattern, ...]
+ #: Baseline entries the base lacks, under ``--fail-on-baseline-growth``.
+ grown: list[dict] | None = None
def _check(opts: _CheckOptions) -> None:
from repowise.core.analysis.security_gate import evaluate
fmt = opts.fmt
+ grown: list[dict] | None = None
try:
root = repo_root(opts.repo)
patterns = _custom_patterns(root)
@@ -342,6 +371,8 @@ def _check(opts: _CheckOptions) -> None:
if opts.write_baseline_path is not None:
_record_baseline(opts.write_baseline_path, scan, fmt, also_keep=accepted or [])
return
+ if opts.fail_on_growth:
+ grown = _growth(root, opts)
except CannotEvaluateError as exc:
cannot_evaluate(fmt, exc.code, str(exc))
@@ -351,11 +382,21 @@ def _check(opts: _CheckOptions) -> None:
gate = evaluate(
scan.findings, fail_on=opts.fail_on, baseline=baseline, suppressed=scan.suppressed
)
- _EMITTERS.get(fmt, _print_check)(_Verdict(scan, gate, label, baseline or frozenset(), patterns))
- if not gate.passed:
+ verdict = _Verdict(scan, gate, label, baseline or frozenset(), patterns, grown)
+ _EMITTERS.get(fmt, _print_check)(verdict)
+ report_baseline_growth(fmt, opts.baseline_path, grown)
+ if not gate.passed or grown:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
+def _growth(root: Path, opts: _CheckOptions) -> list[dict]:
+ """The entries ``--baseline`` adds over the change's base (``HEAD`` when staged)."""
+ if opts.baseline_path is None: # the command refuses the flag without --baseline
+ return []
+ revspec = None if opts.staged else ci_revspec(str(root), opts.revspec)
+ return baseline_growth(root, opts.baseline_path, revspec)
+
+
def _custom_patterns(root: Path) -> tuple[CustomPattern, ...]:
"""``security.patterns`` from the repo config; any invalid entry stops the check."""
from repowise.core.analysis.security_gate import custom_patterns
@@ -438,17 +479,18 @@ def _record_baseline(path: Path, scan: ChangeScan, fmt: str, *, also_keep: list[
def _emit_json(v: _Verdict) -> None:
from repowise.core.analysis.security_gate import DETECTION_BASIS
- emit_json(
- {
- "revspec": v.label,
- "files_scanned": v.scan.files_scanned,
- "commits_scanned": v.scan.commits_scanned,
- "long_lines_skipped": v.scan.long_lines_skipped,
- "findings_basis": DETECTION_BASIS,
- "findings": v.scan.findings,
- "gate": v.gate.to_dict(),
- }
- )
+ doc = {
+ "revspec": v.label,
+ "files_scanned": v.scan.files_scanned,
+ "commits_scanned": v.scan.commits_scanned,
+ "long_lines_skipped": v.scan.long_lines_skipped,
+ "findings_basis": DETECTION_BASIS,
+ "findings": v.scan.findings,
+ "gate": v.gate.to_dict(),
+ }
+ if v.grown is not None:
+ doc["baseline_growth"] = v.grown
+ emit_json(doc)
def _emit_sarif(v: _Verdict) -> None:
diff --git a/packages/core/src/repowise/core/ci/baseline.py b/packages/core/src/repowise/core/ci/baseline.py
index 74bf78d2a..e07f45336 100644
--- a/packages/core/src/repowise/core/ci/baseline.py
+++ b/packages/core/src/repowise/core/ci/baseline.py
@@ -9,6 +9,10 @@ Each feature supplies its entries (a ``fingerprint`` plus whatever a reader
needs to recognise the finding) and their order; this module owns the envelope.
One entry per fingerprint, sorted, deterministic bytes, so rewriting an
unchanged baseline is a no-op diff.
+
+A baseline only shrinks: :func:`baseline_growth` names what a change added
+over the same file at its base, so a gate can refuse a re-saved baseline that
+hides new findings.
"""
from __future__ import annotations
@@ -52,6 +56,36 @@ def read_entries(path: Path | str) -> list[dict]:
text = Path(path).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as exc:
raise BaselineError(f"cannot read baseline {path}: {exc}") from exc
+ return _parse_entries(text, path)
+
+
+def baseline_growth(
+ base: bytes | None, head: bytes | None, *, name: str = "baseline"
+) -> list[dict]:
+ """The entries the *head* baseline adds over the *base* one, each given as file bytes.
+
+ ``None`` is a side without the file: a baseline new at the head adds
+ nothing, since adopting one is a change reviewed on its own, and a deleted
+ one adds nothing either. Removed entries are never growth. Raises
+ :class:`BaselineError` when a side is unusable. Reads no files, so a caller
+ may take the bytes from a checkout, git or a forge API.
+ """
+ if base is None or head is None:
+ return []
+ known = {entry["fingerprint"] for entry in _parse_bytes(base, f"{name} at base")}
+ return [entry for entry in _parse_bytes(head, name) if entry["fingerprint"] not in known]
+
+
+def _parse_bytes(data: bytes, name: str) -> list[dict]:
+ try:
+ text = data.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise BaselineError(f"cannot read baseline {name}: {exc}") from exc
+ return _parse_entries(text, name)
+
+
+def _parse_entries(text: str, path: Path | str) -> list[dict]:
+ """The entries of a baseline document read from *path*; raises :class:`BaselineError`."""
try:
doc = json.loads(text)
except json.JSONDecodeError as exc:
diff --git a/tests/unit/cli/test_doc_drift_check.py b/tests/unit/cli/test_doc_drift_check.py
index 5440f8f36..8879b8916 100644
--- a/tests/unit/cli/test_doc_drift_check.py
+++ b/tests/unit/cli/test_doc_drift_check.py
@@ -397,3 +397,57 @@ def test_kind_symbol_with_an_index_reports_a_renamed_symbol(monkeypatch, tmp_pat
assert finding["suggested_line"] == "Call `parse_conf()`."
assert finding["suggestion_columns"] == [[7, 21]]
assert finding["defined_in"] == ["src/app.py"]
+
+
+def _git(cwd, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)
+
+
+def _baseline_on_main(tmp_path, findings):
+ """A repository whose ``main`` commits the baseline for *findings*, on a branch off it."""
+ from repowise.core.analysis.doc_drift.baseline import write_baseline
+
+ _git(tmp_path, "init", "-q", "-b", "main")
+ for key, value in (("user.email", "[email protected]"), ("user.name", "t"), ("core.autocrlf", "false")):
+ _git(tmp_path, "config", key, value)
+ baseline = tmp_path / "baseline.json"
+ write_baseline(baseline, findings)
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "baseline")
+ _git(tmp_path, "switch", "-qc", "feature")
+ return baseline
+
+
+def test_a_baseline_that_grew_over_the_base_fails(monkeypatch, tmp_path):
+ from repowise.core.analysis.doc_drift.baseline import write_baseline
+
+ baseline = _baseline_on_main(tmp_path, [_finding()])
+ findings = [_finding(), _finding(target="src/other.py")]
+ write_baseline(baseline, findings)
+ args = ["--baseline", str(baseline), "--since", "main", "--fail-on-baseline-growth"]
+ result = _invoke(monkeypatch, tmp_path, findings, args)
+ assert result.exit_code == 1
+ assert "docs/a.md path src/other.py" in result.output
+
+ doc = json.loads(_invoke(monkeypatch, tmp_path, findings, [*args, "--format", "json"]).stdout)
+ assert [e["target"] for e in doc["baseline_growth"]] == ["src/other.py"]
+
+
+def test_a_baseline_that_did_not_grow_passes(monkeypatch, tmp_path):
+ baseline = _baseline_on_main(tmp_path, [_finding()])
+ args = ["--baseline", str(baseline), "--since", "main", "--fail-on-baseline-growth"]
+ result = _invoke(monkeypatch, tmp_path, [_finding()], args)
+ assert result.exit_code == 0, result.output
+
+
+def test_baseline_growth_without_a_baseline_is_refused(monkeypatch, tmp_path):
+ result = _invoke(monkeypatch, tmp_path, [], ["--fail-on-baseline-growth"])
+ assert result.exit_code == 2
+ assert "needs --baseline" in result.output
+
+
+def test_baseline_growth_refuses_write_baseline(monkeypatch, tmp_path):
+ args = ["--baseline", "b.json", "--write-baseline", "c.json", "--fail-on-baseline-growth"]
+ result = _invoke(monkeypatch, tmp_path, [], args)
+ assert result.exit_code == 2
+ assert "not --write-baseline" in result.output
diff --git a/tests/unit/cli/test_security_check_cmd.py b/tests/unit/cli/test_security_check_cmd.py
index 85442205c..f4bafe63d 100644
--- a/tests/unit/cli/test_security_check_cmd.py
+++ b/tests/unit/cli/test_security_check_cmd.py
@@ -273,3 +273,56 @@ def test_suppressed_findings_stay_out_of_a_written_baseline(repo, tmp_path):
assert json.loads(result.stdout)["recorded"] == 1
entries = json.loads(baseline.read_text(encoding="utf-8"))["entries"]
assert [e["kind"] for e in entries] == ["os_system"]
+
+
+def _baseline_on_main(repo, *fingerprints: str):
+ """Commit a baseline listing *fingerprints* on ``main``, then return to ``feature``."""
+ _git(repo, "switch", "-q", "main")
+ entries = [{"fingerprint": f} for f in fingerprints]
+ _commit(repo, "baseline.json", json.dumps({"version": 1, "entries": entries}))
+ _git(repo, "switch", "-q", "feature")
+ _git(repo, "merge", "-q", "main")
+ return repo / "baseline.json"
+
+
+def test_a_re_saved_baseline_that_grew_fails(repo):
+ baseline = _baseline_on_main(repo, "old")
+ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ assert _check(repo, "--write-baseline", str(baseline)).exit_code == 0
+ assert _check(repo, "--baseline", str(baseline)).exit_code == 0
+
+ result = _check(repo, "--baseline", str(baseline), "--fail-on-baseline-growth")
+ assert result.exit_code == 1
+ assert "Baseline grew" in result.output and "cfg.py aws_access_key" in result.output
+
+ doc = json.loads(
+ _check(
+ repo, "--baseline", str(baseline), "--fail-on-baseline-growth", "--format", "json"
+ ).stdout
+ )
+ assert doc["gate"]["passed"] is True
+ assert [e["kind"] for e in doc["baseline_growth"]] == ["aws_access_key"]
+
+
+def test_a_baseline_that_did_not_grow_passes(repo):
+ baseline = _baseline_on_main(repo, "old", "gone")
+ baseline.write_text('{"version": 1, "entries": [{"fingerprint": "old"}]}', encoding="utf-8")
+ _commit(repo, "app.py", "x = 2\n")
+ result = _check(repo, "--baseline", str(baseline), "--fail-on-baseline-growth")
+ assert result.exit_code == 0, result.output
+
+
+def test_baseline_growth_annotates_in_github_format(repo):
+ baseline = _baseline_on_main(repo)
+ baseline.write_text('{"version": 1, "entries": [{"fingerprint": "new"}]}', encoding="utf-8")
+ result = _check(
+ repo, "--baseline", str(baseline), "--fail-on-baseline-growth", "--format", "github"
+ )
+ assert result.exit_code == 1
+ assert "::error::Baseline grew" in result.stdout
+
+
+def test_baseline_growth_needs_a_baseline(repo):
+ result = _check(repo, "--fail-on-baseline-growth")
+ assert result.exit_code == 2
+ assert "needs --baseline" in result.output
diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.py
index 2b04e74fa..9797a8a21 100644
--- a/tests/unit/test_ci_action.py
+++ b/tests/unit/test_ci_action.py
@@ -258,6 +258,7 @@ def _run(tmp_path: Path, bin_dir: Path, **env: str) -> tuple[int, str, str]:
"DOC_DRIFT_BASELINE": "",
"SECURITY_FAIL_ON": "high",
"SECURITY_BASELINE": "",
+ "FAIL_ON_BASELINE_GROWTH": "false",
"RISK_FAIL_ABOVE_PERCENTILE": "",
"SARIF": "false",
"SARIF_DIR": str(tmp_path / "sarif"),
@@ -308,6 +309,23 @@ def test_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:
)
+def test_baseline_growth_reaches_each_gate_with_a_baseline(tmp_path, fake_repowise) -> None:
+ code, _, calls = _run(
+ tmp_path,
+ fake_repowise,
+ CHECKS="doc-drift,security",
+ DOC_DRIFT_BASELINE=".doc-drift-baseline.json",
+ FAIL_ON_BASELINE_GROWTH="true",
+ )
+ assert code == 0
+ drift, security = calls.splitlines()
+ assert drift == (
+ "doc-drift --check --baseline .doc-drift-baseline.json "
+ "--fail-on-baseline-growth --format github"
+ )
+ assert "growth" not in security
+
+
def test_base_report_inputs_reach_the_coverage_command(tmp_path, fake_repowise) -> None:
code, _, calls = _run(
tmp_path,
diff --git a/tests/unit/test_ci_baseline_growth.py b/tests/unit/test_ci_baseline_growth.py
new file mode 100644
index 000000000..84a5d7701
--- /dev/null
+++ b/tests/unit/test_ci_baseline_growth.py
@@ -0,0 +1,129 @@
+"""A baseline only shrinks: entries added over the same file at the change's base."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from repowise.cli.ci import CannotEvaluateError
+from repowise.cli.ci import baseline_growth as growth_since_base
+from repowise.core.ci.baseline import BaselineError, baseline_growth
+
+
+def _git(cwd, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+
+def _doc(*fingerprints: str) -> str:
+ return json.dumps({"version": 1, "entries": [{"fingerprint": f} for f in fingerprints]})
+
+
+def _bytes(*fingerprints: str) -> bytes:
+ return _doc(*fingerprints).encode("utf-8")
+
+
+def _entries(*fingerprints: str) -> list[dict]:
+ return [{"fingerprint": f} for f in fingerprints]
+
+
+def test_growth_names_only_what_the_base_lacks():
+ assert baseline_growth(_bytes("a", "b"), _bytes("a", "c")) == _entries("c")
+
+
+def test_removed_and_unchanged_entries_are_not_growth():
+ assert baseline_growth(_bytes("a", "b"), _bytes("a")) == []
+ assert baseline_growth(_bytes("b", "a"), _bytes("a", "b")) == []
+
+
+def test_a_baseline_missing_at_the_base_or_the_head_is_not_growth():
+ assert baseline_growth(None, _bytes("a")) == []
+ assert baseline_growth(_bytes("a"), None) == []
+
+
+ ("base", "head", "match"),
+ [
+ (b"{not json", _bytes("a"), "x.json at base is not valid JSON"),
+ (_bytes("a"), b'{"version": 2, "entries": []}', "has version 2"),
+ (_bytes("a"), b"\xff", "cannot read baseline x.json"),
+ (_bytes("a"), b'{"version": 1, "entries": [{}]}', "has no fingerprint"),
+ ],
+)
+def test_a_malformed_side_is_refused(base, head, match):
+ with pytest.raises(BaselineError, match=match):
+ baseline_growth(base, head, name="x.json")
+
+
+def repo(tmp_path):
+ _git(tmp_path, "init", "-q", "-b", "main")
+ for key, value in (("user.email", "[email protected]"), ("user.name", "t"), ("core.autocrlf", "false")):
+ _git(tmp_path, "config", key, value)
+ (tmp_path / "app.py").write_text("x = 1\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "base")
+ return tmp_path
+
+
+def _commit_baseline(repo, text: str) -> None:
+ (repo / "baseline.json").write_text(text, encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "baseline")
+
+
+def test_the_checkout_is_compared_with_the_merge_base(repo):
+ _commit_baseline(repo, _doc("a", "b"))
+ _git(repo, "switch", "-qc", "feature")
+ (repo / "baseline.json").write_text(_doc("b", "c"), encoding="utf-8")
+ grown = growth_since_base(repo, repo / "baseline.json", "main...HEAD")
+ assert grown == _entries("c")
+
+
+def test_a_root_below_the_git_toplevel_reads_its_own_baseline(repo):
+ package = repo / "pkg"
+ package.mkdir()
+ (package / "baseline.json").write_text(_doc("a"), encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "package baseline")
+ _git(repo, "switch", "-qc", "feature")
+ (package / "baseline.json").write_text(_doc("a", "n"), encoding="utf-8")
+ grown = growth_since_base(package, package / "baseline.json", "main...HEAD")
+ assert grown == _entries("n")
+
+
+def test_a_baseline_new_in_the_change_is_not_growth(repo):
+ _git(repo, "switch", "-qc", "feature")
+ _commit_baseline(repo, _doc("a"))
+ assert growth_since_base(repo, repo / "baseline.json", "main...HEAD") == []
+
+
+def test_staged_changes_compare_with_head(repo):
+ _commit_baseline(repo, _doc("a"))
+ (repo / "baseline.json").write_text(_doc("a", "n"), encoding="utf-8")
+ assert growth_since_base(repo, repo / "baseline.json", None) == _entries("n")
+
+
+def test_a_malformed_base_file_cannot_evaluate(repo):
+ _commit_baseline(repo, "{not json")
+ _git(repo, "switch", "-qc", "feature")
+ (repo / "baseline.json").write_text(_doc("a"), encoding="utf-8")
+ with pytest.raises(CannotEvaluateError) as exc:
+ growth_since_base(repo, repo / "baseline.json", "main...HEAD")
+ assert exc.value.code == "baseline_unreadable"
+
+
+def test_an_unknown_base_cannot_evaluate(repo):
+ with pytest.raises(CannotEvaluateError) as exc:
+ growth_since_base(repo, repo / "baseline.json", "nope...HEAD")
+ assert exc.value.code == "base_not_found"
+
+
+def test_a_baseline_outside_the_repository_cannot_evaluate(repo, tmp_path_factory):
+ outside = tmp_path_factory.mktemp("elsewhere") / "baseline.json"
+ with pytest.raises(CannotEvaluateError) as exc:
+ growth_since_base(repo, outside, "main...HEAD")
+ assert exc.value.code == "baseline_outside_repository"