diff --git a/.github/workflows/ci-maintenance.yml b/.github/workflows/ci-maintenance.yml index c3f90dd517..ed1cb25a15 100644 --- a/.github/workflows/ci-maintenance.yml +++ b/.github/workflows/ci-maintenance.yml @@ -21,36 +21,16 @@ jobs: contents: read pull-requests: read steps: - - uses: actions/github-script@v8 + - uses: actions/checkout@v7 with: - script: | - const repo = context.repo; - const pull_number = context.payload.number; - const expected = context.payload.pull_request; - const readPR = async () => (await github.rest.pulls.get({...repo, pull_number})).data; - const pr = await readPR(); - const sameIdentity = current => current.state === 'open' && - current.head.sha === expected.head.sha && current.head.ref === expected.head.ref && - current.head.repo?.id === expected.head.repo?.id && - current.base.ref === expected.base.ref && current.base.repo?.id === expected.base.repo?.id; - if (!sameIdentity(pr) || !pr.head.repo?.id || !pr.base.repo?.id) { - return core.info('PR identity changed; stop diff inspection.'); - } - const readTarget = async () => (await github.rest.repos.getBranch( - {...repo, branch: pr.base.ref})).data.commit.sha; - const target = await readTarget(); - if (pr.base.sha === target) return core.info('PR base snapshot is current.'); - // A changed target tip alone does not prove a wrong comparison. - // REST base updates have no target compare-and-swap: a final GET - // cannot prevent overwriting a concurrent maintainer retarget. - const before = await readPR(); - if (!sameIdentity(before) || before.base.sha !== pr.base.sha) { - return core.info('PR changed during inspection; inspect the newer revision.'); - } - core.info(`Comparison inspection for #${pull_number}: PR base ${pr.base.sha}, ` + - `target ${pr.base.ref} at ${target}, head ${pr.head.sha}. ` + - 'Verify the published inventory against the exact three-dot Git diff before repair. ' + - 'This observation is read-only and does not prove an incorrect diff.'); + ref: ${{ github.workflow_sha }} + fetch-depth: 1 + sparse-checkout: scripts/ci + persist-credentials: false + - name: Verify the published pull request files + env: + GH_TOKEN: ${{ github.token }} + run: python3 scripts/ci/review_gate.py inspect-pr-diff cancel-obsolete-pr: if: github.event_name == 'pull_request_target' && (github.event.action == 'closed' || github.event.action == 'synchronize') diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index 8421b2ee5e..835d3b4172 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -48,6 +48,9 @@ jobs: if: github.event_name != 'pull_request_target' && (github.event_name != 'pull_request' || github.event.action != 'closed') runs-on: ubuntu-latest timeout-minutes: 3 + permissions: + contents: read + pull-requests: read outputs: core_tests: ${{ steps.classify.outputs.core_tests }} backend_tests: ${{ steps.classify.outputs.backend_tests }} @@ -61,6 +64,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + persist-credentials: false - uses: actions/setup-python@v6 with: python-version: "3.11" @@ -81,13 +85,14 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha }} CHECKOUT_SHA: ${{ github.sha }} FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'ci:full') }} + GH_TOKEN: ${{ github.token }} shell: bash run: | set -euo pipefail - extra=() - if [[ "$FORCE_FULL" == true ]]; then extra+=(--force-full); fi + set -- + if [[ "$FORCE_FULL" == true ]]; then set -- --force-full; fi if [[ "$EVENT_NAME" == pull_request ]]; then - python scripts/ci/review_gate.py classify --base "$BASE_SHA" --head "$HEAD_SHA" --plan impact-plan.json "${extra[@]}" >> "$GITHUB_OUTPUT" + python scripts/ci/review_gate.py classify --base "$BASE_SHA" --head "$HEAD_SHA" --verify-pr-diff --plan impact-plan.json "$@" >> "$GITHUB_OUTPUT" else python scripts/ci/review_gate.py classify --base "$CHECKOUT_SHA" --head "$CHECKOUT_SHA" --non-pr --plan impact-plan.json >> "$GITHUB_OUTPUT" fi @@ -99,6 +104,8 @@ jobs: summary.write("## CI job exemptions\n\n") summary.write(f"Change kind: **{plan['change_kind']}**; Python shards: **{plan['python_shards']}**.\n\n") summary.write(plan['reason'] + ".\n\n") + if plan.get("published_diff", {}).get("verified"): + summary.write(f"Published files match Git comparison `{plan['merge_base_sha']}...{plan['head_sha']}`.\n\n") summary.write( f"Backend: {plan['backend_tests']}; Frontend browser: {plan['frontend_tests']}; " f"Compat: {plan['compat_tests']}; Python: {plan['python_tests']}; " diff --git a/docs/development/ci-impact-selection.md b/docs/development/ci-impact-selection.md index bd180e65d1..62d9b39df9 100644 --- a/docs/development/ci-impact-selection.md +++ b/docs/development/ci-impact-selection.md @@ -16,6 +16,21 @@ and runs heavyweight cross-OS, full 6-shard Python/coverage, Node compatibility, Stage 2C, and release/package dry-run matrices on Nightly `schedule`, `push` to `main`, `merge_group`, `workflow_dispatch`, CI-policy/manifest changes, and `ci:full`. +For open PRs, `changes` verifies the complete published PR file inventory +against the Git comparison before granting exemptions. It rechecks PR identity +after reading all pages and allows base-branch advances that keep the same merge +base. A confirmed difference or comparison change fails classification and +therefore `merge-gate`. Unavailable or capped file data selects full +qualification and records why. CI Maintenance runs the same verification from +its pinned trusted workflow checkout using read-only GitHub access. Fork +commits are fetched as Git objects for comparison. + +开放 PR 的 `changes` 先核对已发布的完整文件清单与 Git 比较,再决定能否免跑。 +分页结束后重新确认 PR 身份,目标分支推进但 merge base 一致时继续。确认清单 +或比较范围不一致会使分类失败,并阻止 `merge-gate`。文件数据不可用或达到 API +上限时执行全量检查并记录原因。CI Maintenance 在固定的可信 workflow checkout +运行同一核对,GitHub 权限仅为只读。Fork 提交以 Git 对象的形式用于比较。 + | Whole PR / Event (`change_kind`) | Backend static/TS/contracts (`backend_tests`) | Browser / UI (`frontend_tests`, `presentation_tests`) | Node compat (`compat_tests`) | 6-shard Python / Windows (`python_tests`) | Stage 2C (`stage2c_tests`) | | --- | --- | --- | --- | --- | --- | | Allowlisted root Markdown or `docs/**/*.md` (`docs`) | Skip | Skip | Skip | Skip | Skip | diff --git a/loopx/cli_commands/canary.py b/loopx/cli_commands/canary.py index 557813319b..dea65b9b76 100644 --- a/loopx/cli_commands/canary.py +++ b/loopx/cli_commands/canary.py @@ -1,6 +1,7 @@ from __future__ import annotations import argparse +import os import subprocess import sys from collections.abc import Callable @@ -87,7 +88,8 @@ def _run_git_name_only(repo_root: Path, args: list[str]) -> dict[str, Any]: # `core.quotePath` escapes non-ASCII pathnames, and a repository may turn # that off, at which point a path can carry U+0085/U+2028/U+2029 raw and # `str.splitlines()` splits one path into two. - command = ["git", "-C", str(repo_root), *args, "-z"] + subcommand, *arguments = args + command = ["git", "-C", str(repo_root), subcommand, "-z", *arguments, "--"] completed = subprocess.run( command, check=False, @@ -133,6 +135,69 @@ def _resolve_git_repo_root(candidate: Path) -> Path: return candidate.resolve() +def _run_git_text(repo_root: Path, args: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["git", "--no-replace-objects", "-C", str(repo_root), *args], + check=False, + env={**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0"}, + text=True, + encoding="utf-8", + errors="replace", + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + +def _failed_base_source( + completed: subprocess.CompletedProcess[str], + *, + returncode: int | None = None, + path_error: str | None = None, +) -> dict[str, Any]: + return { + "ok": False, + "returncode": completed.returncode if returncode is None else returncode, + "command": list(completed.args), + "changed_files": [], + "undecodable_path_count": 0, + "path_error": path_error, + "stderr_tail": completed.stderr[-800:], + } + + +def _resolve_base_diff_source( + repo_root: Path, base_ref: str +) -> tuple[dict[str, Any], str | None]: + base_rev = _run_git_text( + repo_root, ["rev-parse", "--verify", "--end-of-options", f"{base_ref}^{{commit}}"] + ) + if base_rev.returncode != 0: + return _failed_base_source(base_rev), None + head_rev = _run_git_text( + repo_root, ["rev-parse", "--verify", "--end-of-options", "HEAD^{commit}"] + ) + if head_rev.returncode != 0: + return _failed_base_source(head_rev), None + base_sha = base_rev.stdout.strip() + head_sha = head_rev.stdout.strip() + merge_bases = _run_git_text(repo_root, ["merge-base", "--all", base_sha, head_sha]) + bases = [line.strip() for line in merge_bases.stdout.splitlines() if line.strip()] + if merge_bases.returncode != 0 or not bases: + return _failed_base_source(merge_bases, returncode=merge_bases.returncode or 1), None + if len(bases) > 1: + detail = ( + f"Git comparison of {base_ref!r} and HEAD requires one unambiguous merge base " + f"(found {len(bases)}); specify an explicit --git-diff-base with a single common ancestor." + ) + return _failed_base_source(merge_bases, returncode=1, path_error=detail), detail + return ( + _run_git_name_only( + repo_root, ["diff", "--name-only", "--end-of-options", f"{bases[0]}..{head_sha}"] + ), + None, + ) + + def collect_git_diff_changed_files( *, repo_root: Path, @@ -141,8 +206,9 @@ def collect_git_diff_changed_files( """Collect committed, staged, unstaged, and untracked paths for canary selection.""" base_ref = (base_ref or "origin/main").strip() or "origin/main" + base_source, base_error = _resolve_base_diff_source(repo_root, base_ref) sources = { - "base": _run_git_name_only(repo_root, ["diff", "--name-only", f"{base_ref}...HEAD"]), + "base": base_source, "staged": _run_git_name_only(repo_root, ["diff", "--name-only", "--cached"]), "unstaged": _run_git_name_only(repo_root, ["diff", "--name-only"]), "untracked": _run_git_name_only(repo_root, ["ls-files", "--others", "--exclude-standard"]), @@ -173,21 +239,30 @@ def collect_git_diff_changed_files( int(source.get("undecodable_path_count") or 0) for source in sources.values() ) - path_error = ( + error = ( "Git returned changed pathnames that are not valid UTF-8; canary " "cannot preserve their identity in the selector output" if undecodable_path_count else None ) + if error is None and not sources["base"]["ok"]: + error = base_error or ( + f"Git could not compare {base_ref!r} with HEAD. Fetch the target branch " + "or set --git-diff-base to a revision with shared history." + ) + elif error is None and warnings: + failed = ", ".join(warning["source"] for warning in warnings) + error = f"Git could not read changed paths from {failed}; selection is incomplete." + selected = changed_files if error is None else [] return { - "ok": bool(successful_sources) and path_error is None, + "ok": error is None, "base_ref": base_ref, "repo_root": str(repo_root), - "changed_files": [] if path_error is not None else changed_files, - "changed_file_count": len(changed_files), + "changed_files": selected, + "changed_file_count": len(selected), "successful_sources": successful_sources, "undecodable_path_count": undecodable_path_count, - **({"error": path_error} if path_error else {}), + **({"error": error} if error else {}), "warnings": warnings, } diff --git a/scripts/ci/impact_plan.py b/scripts/ci/impact_plan.py index 5be44b0017..e3063f3d75 100644 --- a/scripts/ci/impact_plan.py +++ b/scripts/ci/impact_plan.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass import json import os @@ -10,7 +11,10 @@ SCHEMA = "loopx_ci_job_plan_v1" ROOT_DOCS = {"README.md", "README.zh-CN.md", "README.ja.md", "CHANGELOG.md", "CONTRIBUTING.md"} -POLICY_PATHS = ("scripts/ci/impact_plan.py", "scripts/ci/review_gate.py", ".github/workflows/python-tests.yml") +POLICY_PATHS = ( + "scripts/ci/impact_plan.py", "scripts/ci/pull_request_diff.py", + "scripts/ci/review_gate.py", ".github/workflows/python-tests.yml", +) OUTPUTS = ( "core_tests", "backend_tests", @@ -95,6 +99,14 @@ class Change: path: str +@dataclass(frozen=True) +class Comparison: + base_sha: str + head_sha: str + merge_base_sha: str + changes: list[Change] + + def is_document(path: str) -> bool: return path in ROOT_DOCS or (path.startswith("docs/") and PurePosixPath(path).suffix == ".md") @@ -157,7 +169,11 @@ def job_flags(kind: str, *, presentation: bool = False) -> dict[str, bool]: def git(*args: str) -> bytes: - return subprocess.check_output(["git", *args]) + return subprocess.check_output( + ["git", "--no-replace-objects", *args], + env={**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0"}, + stderr=subprocess.PIPE, timeout=30, + ) def revision(ref: str) -> str: @@ -165,12 +181,28 @@ def revision(ref: str) -> str: def diff_changes(base: str, head: str) -> list[Change]: - raw = git("diff", "--name-status", "--no-renames", "-z", base, head, "--").split(b"\0") + raw = git( + "diff", "--no-ext-diff", "--no-textconv", "--name-status", "--no-renames", + "-z", base, head, "--", + ).split(b"\0") if raw[-1] != b"" or (len(raw) - 1) % 2: raise ValueError("malformed NUL-delimited Git changes") return [Change(os.fsdecode(raw[i]), os.fsdecode(raw[i + 1])) for i in range(0, len(raw) - 1, 2)] +def merge_base(base: str, head: str) -> str: + bases = git("merge-base", "--all", base, head).decode("ascii").splitlines() + if len(bases) != 1: + raise ValueError("Git comparison requires one unambiguous merge base") + return bases[0] + + +def compare(base: str, head: str) -> Comparison: + base_sha, head_sha = revision(base), revision(head) + ancestor = merge_base(base_sha, head_sha) + return Comparison(base_sha, head_sha, ancestor, diff_changes(ancestor, head_sha)) + + def trusted_policy(base: str, head: str) -> bool: # A PR cannot introduce its own exemption. No manifest or per-test inventory. for path in POLICY_PATHS: @@ -203,20 +235,29 @@ def declared_python_shards(checkout_sha: str) -> int: return len(shards) -def plan(base: str, head: str, *, pull_request: bool = True, force_full: bool = False) -> dict: - base_sha, head_sha = revision(base), revision(head) - merge_base = git("merge-base", base_sha, head_sha).decode().strip() - changes = diff_changes(merge_base, head_sha) +def plan( + base: str, + head: str, + *, + pull_request: bool = True, + force_full: bool = False, + verify_pr_diff: Callable[[Comparison], str | None] | None = None, +) -> dict: + comparison = compare(base, head) + base_sha, head_sha, changes = comparison.base_sha, comparison.head_sha, comparison.changes + unverified = verify_pr_diff(comparison) if verify_pr_diff is not None else None kind, reason = candidate(changes, pull_request=pull_request) presentation = kind in {"presentation", "mixed"} policy_change = any(item.path.startswith("scripts/ci/") or item.path == POLICY_PATHS[-1] for item in changes) - if kind != "full": + if kind != "full" and unverified is None: for item in changes: - for sha in (merge_base, head_sha): + for sha in (comparison.merge_base_sha, head_sha): mode = git("ls-tree", "--format=%(objectmode)", sha, "--", item.path).decode().strip() if mode and mode not in {"100644", "100755"}: kind, reason = "full", "symlinks and nonregular Git objects cannot grant an exemption" - if force_full: + if unverified is not None: + kind, reason = "full", f"{unverified}; run full qualification" + elif force_full: kind, reason = "full", "explicit force-full override" elif kind in {"presentation", "backend", "mixed"} and not trusted_policy(base_sha, head_sha): kind, reason = "full", "CI exemption policy is not already trusted on the target branch" @@ -229,12 +270,15 @@ def plan(base: str, head: str, *, pull_request: bool = True, force_full: bool = if flags["backend_tests"] else "no Python coverage claim" ) - return {"schema_version": SCHEMA, "base_sha": base_sha, "head_sha": head_sha, - "merge_base_sha": merge_base, "checkout_sha": checkout_sha, "change_kind": kind, + packet = {"schema_version": SCHEMA, "base_sha": base_sha, "head_sha": head_sha, + "merge_base_sha": comparison.merge_base_sha, "checkout_sha": checkout_sha, "change_kind": kind, "force_full": force_full, "reason": reason, **flags, "changes": [{"status": item.status, "path": item.path} for item in changes], "coverage_scope": coverage_scope, "python_shards": declared_python_shards(checkout_sha) if flags["python_tests"] else 0} + if verify_pr_diff is not None: + packet["published_diff"] = {"verified": unverified is None, "unavailable_reason": unverified} + return packet def write_plan(packet: dict, output: str) -> None: diff --git a/scripts/ci/pull_request_diff.py b/scripts/ci/pull_request_diff.py new file mode 100644 index 0000000000..70be24411f --- /dev/null +++ b/scripts/ci/pull_request_diff.py @@ -0,0 +1,156 @@ +"""Verify the published GitHub path inventory against the CI Git comparison.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import subprocess +from typing import Any +from urllib.parse import quote + +from impact_plan import Comparison, git, merge_base + + +class DiffUnavailable(Exception): + """Git is available, but GitHub cannot supply a complete inventory.""" + + +def _commit_oid(value: Any) -> str: + if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value): + raise ValueError("Expected a complete GitHub commit SHA") + return value + + +def _pr_identity(pr: dict[str, Any]) -> tuple: + return ( + pr["number"], pr["base"]["repo"]["id"], pr["base"]["ref"], + pr["head"]["repo"]["id"], pr["head"]["ref"], _commit_oid(pr["head"]["sha"]), + ) + + +def _api(endpoint: str, *, paginate: bool = False) -> Any: + options = ["--paginate", "--slurp"] if paginate else [] + try: + return json.loads(subprocess.check_output( + ["gh", "api", "--method", "GET", *options, endpoint], + stderr=subprocess.PIPE, timeout=45, + )) + except (OSError, subprocess.SubprocessError, ValueError) as exc: + raise DiffUnavailable("GitHub PR comparison read is unavailable") from exc + + +def _fetch_missing_commits(*oids: str) -> None: + shallow = git("rev-parse", "--is-shallow-repository").strip() == b"true" + missing = list(dict.fromkeys(oids)) if shallow else [] + if not shallow: + for oid in dict.fromkeys(oids): + try: + git("cat-file", "-e", f"{oid}^{{commit}}") + except subprocess.CalledProcessError: + missing.append(oid) + if missing: + history = ["--unshallow"] if shallow else [] + git( + "-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", + "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--filter=blob:none", + *history, "origin", *missing, + ) + + +def _published_paths(pages: Any, expected_count: int) -> set[str]: + if not isinstance(pages, list) or any(not isinstance(page, list) for page in pages): + raise DiffUnavailable("GitHub PR file pagination is malformed") + rows = [row for page in pages for row in page] + if len(rows) != expected_count: + raise DiffUnavailable("GitHub PR file pagination is incomplete") + paths: set[str] = set() + for row in rows: + if not isinstance(row, dict): + raise DiffUnavailable("GitHub PR file row is malformed") + path, status = row.get("filename"), row.get("status") + names = [path, row.get("previous_filename")] if status == "renamed" else [path] + if (status not in ("added", "removed", "modified", "renamed", "copied", "changed") + or any(not isinstance(name, str) or not name for name in names) + or len(names) != len(set(names)) or paths.intersection(names)): + raise DiffUnavailable("GitHub PR file inventory has missing or duplicate path identities") + paths.update(names) + return paths + + +class PullRequestDiff: + def __init__(self, repository: str, pr: dict[str, Any]) -> None: + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository): + raise ValueError("Expected the workflow's GitHub owner/repository") + try: + number, base_repo_id, target_ref, head_repo_id, source_ref, head_sha = _pr_identity(pr) + self.base_sha = _commit_oid(pr["base"]["sha"]) + base_repo = pr["base"]["repo"]["full_name"] + except (KeyError, TypeError) as exc: + raise ValueError("Workflow event lacks a complete pull request identity") from exc + if (not all(type(field) is int and field > 0 for field in (number, base_repo_id, head_repo_id)) + or not all(isinstance(ref, str) and ref for ref in (target_ref, source_ref)) + or not isinstance(base_repo, str) or base_repo.lower() != repository.lower() + or pr.get("state") != "open"): + raise ValueError("Workflow event does not identify an open PR in the checkout repository") + self.head_sha = head_sha + self.identity = (number, base_repo_id, target_ref, head_repo_id, source_ref, head_sha) + self.endpoint = f"repos/{repository}/pulls/{number}" + self.target_endpoint = f"repos/{repository}/branches/{quote(target_ref, safe='')}" + + @classmethod + def from_workflow(cls) -> PullRequestDiff: + payload = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + return cls(os.environ["GITHUB_REPOSITORY"], payload["pull_request"]) + + def fetch_event_commits(self) -> None: + # Pulls from forks remain reachable from the base repository's PR refs. + # Fetch objects by OID only; the trusted workflow keeps its own checkout. + _fetch_missing_commits(self.base_sha, self.head_sha) + + def _read_pr(self) -> tuple[str, int]: + pr = _api(self.endpoint) + try: + unchanged = _pr_identity(pr) == self.identity and pr.get("state") == "open" + sha, count = _commit_oid(pr["base"]["sha"]), pr["changed_files"] + except (KeyError, TypeError, ValueError) as exc: + raise DiffUnavailable("GitHub PR comparison metadata is incomplete") from exc + if not unchanged: + raise ValueError("PR head, source repository, target or state changed; qualify the current PR") + if type(count) is not int or count < 0: + raise DiffUnavailable("GitHub PR file count is unavailable") + return sha, count + + def verify(self, comparison: Comparison) -> str | None: + """Reject a demonstrated mismatch or return a reason to run all jobs.""" + if (self.base_sha, self.head_sha) != (comparison.base_sha, comparison.head_sha): + raise ValueError("CI comparison base and head must match the pull request event") + try: + before_base, count = self._read_pr() + # The pull files endpoint is capped even when every page is fetched. + if count > 3000: + return "GitHub PR file count exceeds the published API limit" + pages = _api(f"{self.endpoint}/files?per_page=100", paginate=True) + after_base, after_count = self._read_pr() + if count != after_count: + raise ValueError("PR file count changed during pagination; qualify the current PR") + target = _api(self.target_endpoint) + try: + target_sha = _commit_oid(target["commit"]["sha"]) + except (KeyError, TypeError, ValueError) as exc: + raise DiffUnavailable("GitHub target branch tip is unavailable") from exc + for base in sorted({before_base, after_base, target_sha} - {comparison.base_sha}): + _fetch_missing_commits(base) + if merge_base(base, comparison.head_sha) != comparison.merge_base_sha: + raise ValueError("PR comparison merge base changed; qualify the current target and head") + published = _published_paths(pages, count) + except DiffUnavailable as exc: + return str(exc) + expected = {change.path for change in comparison.changes} + if published != expected: + raise ValueError( + "Published PR file inventory differs from the exact Git comparison " + f"({len(expected - published)} omitted, {len(published - expected)} unexpected)" + ) + return None diff --git a/scripts/ci/review_gate.py b/scripts/ci/review_gate.py index 0bc3dc6a10..e04b266db6 100644 --- a/scripts/ci/review_gate.py +++ b/scripts/ci/review_gate.py @@ -5,7 +5,8 @@ import argparse import json import os -from impact_plan import Change, OUTPUTS, candidate, job_flags, plan, write_plan +from impact_plan import Change, OUTPUTS, candidate, compare, job_flags, plan, write_plan +from pull_request_diff import PullRequestDiff JOB_OUTPUT = { "checks": "core_tests", @@ -65,11 +66,38 @@ def main() -> None: classify.add_argument("--plan") classify.add_argument("--non-pr", action="store_true") classify.add_argument("--force-full", action="store_true") + classify.add_argument("--verify-pr-diff", action="store_true") + sub.add_parser("inspect-pr-diff") sub.add_parser("verify") sub.add_parser("verify-core") args = parser.parse_args() + if args.command == "inspect-pr-diff": + pr = PullRequestDiff.from_workflow() + pr.fetch_event_commits() + comparison = compare(pr.base_sha, pr.head_sha) + try: + unverified = pr.verify(comparison) + except ValueError as exc: + parser.exit(1, f"{exc}\n") + if unverified: + print(f"::warning::{unverified}. CI must use full qualification.") + else: + print(f"Verified the published PR inventory against {comparison.merge_base_sha}...{pr.head_sha}.") + return if args.command == "classify": - packet = plan(args.base, args.head, pull_request=not args.non_pr, force_full=args.force_full) + pr = None + if args.verify_pr_diff: + if args.non_pr: + parser.error("--verify-pr-diff requires a pull request") + pr = PullRequestDiff.from_workflow() + pr.fetch_event_commits() + try: + packet = plan( + args.base, args.head, pull_request=not args.non_pr, + force_full=args.force_full, verify_pr_diff=pr.verify if pr is not None else None, + ) + except ValueError as exc: + parser.exit(1, f"{exc}\n") if args.plan: write_plan(packet, args.plan) print(f"change_kind={packet['change_kind']}") diff --git a/scripts/ci/test_pull_request_diff.py b/scripts/ci/test_pull_request_diff.py new file mode 100644 index 0000000000..eb3e62d6cf --- /dev/null +++ b/scripts/ci/test_pull_request_diff.py @@ -0,0 +1,209 @@ +"""Exercise the shipped CI commands against real Git comparisons and paged PR reads.""" +from __future__ import annotations + +from copy import deepcopy +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from review_gate import JOB_OUTPUT + + +GATE = Path(__file__).resolve().with_name("review_gate.py") +PR_ENDPOINT = "repos/owner/fixture/pulls/17" +FILES_ENDPOINT = PR_ENDPOINT + "/files?per_page=100" +TARGET_ENDPOINT = "repos/owner/fixture/branches/release%2Fstable" + +# The replacement sits on PATH only for the local test. Git and the CI +# entrypoint are real. The API refuses any method other than GET. +GH_FIXTURE = """#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys +assert sys.argv[1:4] == ["api", "--method", "GET"], sys.argv +endpoint = sys.argv[-1] +assert ("--paginate" in sys.argv and "--slurp" in sys.argv) == endpoint.endswith("per_page=100") +root = Path(os.environ["PR_DIFF_TEST_INPUT"]) +calls = root.with_suffix(".calls") +previous = calls.read_text().splitlines() if calls.exists() else [] +with calls.open("a") as log: + log.write(endpoint + "\\n") +responses = json.loads(root.read_text())[endpoint] +result = responses[previous.count(endpoint)] +if result is None: + sys.exit(1) +print(json.dumps(result)) +""" + + +@unittest.skipUnless(os.name == "posix", "CI workflow adapter runs on a POSIX GitHub runner") +class PullRequestDiffTests(unittest.TestCase): + def setUp(self) -> None: + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.repo = self.root / "repo" + self.repo.mkdir() + self.git("init", "-qb", "release/stable") + self.git("config", "user.name", "CI Fixture") + self.git("config", "user.email", "ci@example.invalid") + self.git("config", "commit.gpgsign", "false") + self.git("config", "core.hooksPath", str(self.root / "no-hooks")) + self.write(".github/workflows/python-tests.yml", + "jobs:\n test-shard:\n strategy:\n matrix:\n shard: [1, 2]\n") + self.write("docs/old.md") + self.base = self.commit("base") + self.write("docs/upstream.md") + self.target = self.commit("unrelated target advance") + self.git("switch", "-qc", "work", self.base) + self.git("mv", "docs/old.md", "docs/new.md") + self.earlier_head = self.commit("rename a documentation file") + self.files = [f"docs/file-{index}.md" for index in range(100)] + for name in self.files: + self.write(name) + self.head = self.commit("many documented paths") + self.rows = [{"filename": path, "status": "added"} for path in self.files] + [ + {"filename": "docs/new.md", "status": "renamed", "previous_filename": "docs/old.md"} + ] + self.pr = { + "number": 17, "state": "open", "changed_files": len(self.rows), + "base": {"sha": self.base, "ref": "release/stable", + "repo": {"id": 1, "full_name": "owner/fixture"}}, + "head": {"sha": self.head, "ref": "work", "repo": {"id": 2}}, + } + bin_dir = self.root / "bin" + bin_dir.mkdir() + gh = bin_dir / "gh" + gh.write_text(GH_FIXTURE) + gh.chmod(0o700) + self.responses = self.root / "responses.json" + self.event = self.root / "event.json" + self.plan = self.root / "impact-plan.json" + self.env = { + **os.environ, + "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}", + "GITHUB_REPOSITORY": "owner/fixture", + "GITHUB_EVENT_PATH": str(self.event), + "PR_DIFF_TEST_INPUT": str(self.responses), + } + self.env.pop("GH_TOKEN", None) + self.env.pop("GITHUB_TOKEN", None) + + def git(self, *args: str) -> str: + return subprocess.check_output(["git", *args], cwd=self.repo, text=True).strip() + + def write(self, path: str, content: str = "fixture\n") -> None: + file = self.repo / path + file.parent.mkdir(exist_ok=True, parents=True) + file.write_text(content) + + def commit(self, message: str) -> str: + self.git("add", "--all") + self.git("commit", "-qm", message) + return self.git("rev-parse", "HEAD") + + def command(self, *args: str, env: dict | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(GATE), *args], cwd=self.repo, env=env or self.env, + text=True, capture_output=True, timeout=10, + ) + + def qualify(self, *, pages=..., snapshots=None, target=None, inspect=False, base=None): + self.event.write_text(json.dumps({"pull_request": self.pr})) + self.responses.write_text(json.dumps({ + PR_ENDPOINT: snapshots if snapshots is not None else [self.pr, self.pr], + FILES_ENDPOINT: [[self.rows[:100], self.rows[100:]] if pages is ... else pages], + TARGET_ENDPOINT: [{"commit": {"sha": target or self.target}}], + })) + self.plan.unlink(missing_ok=True) + self.responses.with_suffix(".calls").unlink(missing_ok=True) + if inspect: + return self.command("inspect-pr-diff") + return self.command("classify", "--verify-pr-diff", "--base", base or self.base, + "--head", self.head, "--plan", str(self.plan)) + + def test_complete_paginated_rename_and_harmless_target_advance(self) -> None: + refreshed = deepcopy(self.pr) + refreshed["base"]["sha"] = self.target + result = self.qualify(snapshots=[self.pr, refreshed]) + self.assertEqual(result.returncode, 0, result.stderr) + packet = json.loads(self.plan.read_text()) + self.assertTrue(packet["published_diff"]["verified"]) + self.assertEqual(packet["merge_base_sha"], self.base) + self.assertEqual(packet["change_kind"], "docs") + self.assertFalse(packet["python_tests"]) + self.assertEqual(self.responses.with_suffix(".calls").read_text().splitlines(), + [PR_ENDPOINT, FILES_ENDPOINT, PR_ENDPOINT, TARGET_ENDPOINT]) + inspected = self.qualify(snapshots=[self.pr, refreshed], inspect=True) + self.assertEqual(inspected.returncode, 0, inspected.stderr) + self.assertIn("Verified the published PR inventory", inspected.stdout) + + def test_comparison_mismatch_fails_before_any_exemption(self) -> None: + for files in ([self.rows[0]], self.rows + [{"filename": "loopx/extra.py", "status": "added"}]): + with self.subTest(count=len(files)): + live = {**self.pr, "changed_files": len(files)} + result = self.qualify(pages=[files[:100], files[100:]], snapshots=[live, live]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("differs from the exact Git comparison", result.stderr) + self.assertFalse(self.plan.exists()) + self.assertEqual(result.stdout, "") + needs = {"changes": {"result": "failure"}, + **{name: {"result": "skipped"} for name in JOB_OUTPUT}} + gate = self.command("verify", env={**self.env, "NEEDS_JSON": json.dumps(needs)}) + self.assertNotEqual(gate.returncode, 0) + self.assertIn("change classification did not succeed", gate.stderr) + + def test_unavailable_or_partial_pages_force_full_qualification(self) -> None: + capped = {**self.pr, "changed_files": 3001} + cases = ( + ([self.rows[:100]], [self.pr, self.pr]), + ([self.rows[:100], [self.rows[0]]], [self.pr, self.pr]), + (None, [self.pr, self.pr]), + (None, [capped]), + ) + for pages, snapshots in cases: + with self.subTest(count=snapshots[0]["changed_files"], page_count=len(pages or [])): + result = self.qualify(pages=pages, snapshots=snapshots) + self.assertEqual(result.returncode, 0, result.stderr) + packet = json.loads(self.plan.read_text()) + self.assertFalse(packet["published_diff"]["verified"]) + self.assertEqual(packet["change_kind"], "full") + self.assertTrue(packet["backend_tests"] and packet["python_tests"] and packet["stage2c_tests"]) + + def test_head_source_target_and_state_changes_invalidate_observation(self) -> None: + for field in ("head", "source", "target", "state", "count"): + with self.subTest(field=field): + after = deepcopy(self.pr) + if field == "head": + after["head"]["sha"] = self.earlier_head + elif field == "source": + after["head"]["repo"]["id"] = 3 + elif field == "target": + after["base"]["ref"] = "other" + elif field == "state": + after["state"] = "closed" + else: + after["changed_files"] -= 1 + result = self.qualify(snapshots=[self.pr, after]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("qualify the current PR", result.stderr) + self.assertFalse(self.plan.exists()) + + def test_wrong_event_or_changed_effective_base_requires_new_qualification(self) -> None: + wrong = self.qualify(base=self.earlier_head) + self.assertNotEqual(wrong.returncode, 0) + self.assertIn("must match the pull request event", wrong.stderr) + self.assertFalse(self.plan.exists()) + changed = self.qualify(target=self.earlier_head) + self.assertNotEqual(changed.returncode, 0) + self.assertIn("merge base changed", changed.stderr) + self.assertFalse(self.plan.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/canary/test_git_path_framing.py b/tests/canary/test_git_path_framing.py index c762702e10..be7d961918 100644 --- a/tests/canary/test_git_path_framing.py +++ b/tests/canary/test_git_path_framing.py @@ -176,6 +176,54 @@ def test_git_byte_paths_fail_closed_before_display_and_dedupe(tmp_path: Path) -> assert "selection_inputs" not in payload +@pytest.mark.parametrize( + ("subcommand", "extra"), + [("plan", []), ("premerge", ["--tier", "quick", "--no-execute"])], +) +def test_canary_rejects_a_missing_git_base( + tmp_path: Path, subcommand: str, extra: list[str], +) -> None: + from loopx.canary.planner import DEFAULT_CATALOG_PATH + + repo, _ = _repo_with_odd_python_path(tmp_path) + catalog = repo / "docs/concepts/interaction-pattern-catalog.md" + catalog.parent.mkdir(parents=True) + catalog.write_bytes(DEFAULT_CATALOG_PATH.read_bytes()) + _git(repo, "add", "--", str(catalog.relative_to(repo))) + _git(repo, "commit", "-m", "catalog for premerge") + (repo / "untracked.py").write_text("value = 1\n", encoding="utf-8") + + response = run_source_cli( + ["--format", "json", "canary", subcommand, "--from-git-diff", + "--git-diff-base", "refs/heads/nonexistent-base", *extra], + cwd=repo, check=False, timeout=60, + ) + payload = json.loads(response.stdout) + assert response.returncode != 0, payload + assert payload["ok"] is False + assert "--git-diff-base" in payload["error"] + assert "gate" not in payload and "selection_inputs" not in payload + selector = payload["selector_sources"]["git_diff"] + assert selector["successful_sources"] == ["staged", "unstaged", "untracked"] + assert [warning["source"] for warning in selector["warnings"]] == ["base"] + assert selector["changed_files"] == [] + + +def test_canary_rejects_a_git_base_without_shared_history(tmp_path: Path) -> None: + repo, _ = _repo_with_odd_python_path(tmp_path) + unrelated = subprocess.check_output( + ["git", "commit-tree", "HEAD^{tree}", "-m", "separate root"], cwd=repo, + text=True, + ).strip() + _git(repo, "update-ref", "refs/heads/other-root", unrelated) + + selector = collect_git_diff_changed_files(repo_root=repo, base_ref="other-root") + + assert selector["ok"] is False + assert "shared history" in selector["error"] + assert selector["changed_files"] == [] + + @pytest.mark.skipif( os.name != "posix", reason="literal backslash and trailing space pathnames are POSIX-only", @@ -292,3 +340,95 @@ def test_tracked_python_paths_keeps_a_carriage_return_name(tmp_path: Path) -> No paths = tracked_python_paths(repo) assert repo / name in paths + + +def test_canary_rejects_crisscross_merge_and_allows_genuine_zero_diff(tmp_path: Path) -> None: + """Reject ambiguous criss-cross merge bases while keeping genuine zero-diff passing.""" + from loopx.canary.planner import DEFAULT_CATALOG_PATH + + repo = tmp_path / "repo" + repo.mkdir() + _git(repo, "init", "-b", "main") + _git(repo, "config", "user.name", "LoopX Test") + _git(repo, "config", "user.email", "loopx@example.invalid") + catalog = repo / "docs/concepts/interaction-pattern-catalog.md" + catalog.parent.mkdir(parents=True) + catalog.write_bytes(DEFAULT_CATALOG_PATH.read_bytes()) + (repo / "loopx").mkdir() + (repo / "loopx/runtime.py").write_text("value = 'v0'\n", encoding="utf-8") + (repo / "docs/note.md").write_text("note v0\n", encoding="utf-8") + _git(repo, "add", "--all") + _git(repo, "commit", "-m", "root") + root_sha = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip() + + # Branch m_runtime alters runtime.py; m_doc leaves runtime.py untouched and alters docs/note.md. + _git(repo, "checkout", "-qb", "m-runtime", root_sha) + (repo / "loopx/runtime.py").write_text("value = 'v1'\n", encoding="utf-8") + _git(repo, "add", "loopx/runtime.py") + _git(repo, "commit", "-m", "runtime change") + m_runtime = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip() + + _git(repo, "checkout", "-qb", "m-doc", root_sha) + (repo / "docs/note.md").write_text("note v1\n", encoding="utf-8") + _git(repo, "add", "docs/note.md") + _git(repo, "commit", "-m", "doc change") + m_doc = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip() + + # Build target = merge(m_doc into m_runtime) and feature = criss-cross merge keeping m_doc's tree. + _git(repo, "checkout", "-qb", "target", m_runtime) + _git(repo, "merge", "--no-ff", "--no-edit", m_doc) + + _git(repo, "checkout", "-qb", "feature", m_doc) + _git(repo, "merge", "--no-ff", "-s", "ours", "--no-edit", m_runtime) + + merge_bases = subprocess.check_output( + ["git", "-C", str(repo), "merge-base", "--all", "target", "HEAD"], text=True + ).splitlines() + assert len(merge_bases) == 2 + + # Show why naive `git diff target...HEAD` was dangerous: one ancestor yields an empty diff. + assert {m_doc, m_runtime} == set(merge_bases) + assert subprocess.check_output( + ["git", "-C", str(repo), "diff", "--name-only", f"{m_doc}..HEAD"], text=True + ).strip() == "" + assert "loopx/runtime.py" in subprocess.check_output( + ["git", "-C", str(repo), "diff", "--name-only", f"{m_runtime}..HEAD"], text=True + ) + + selector = collect_git_diff_changed_files(repo_root=repo, base_ref="target") + assert selector["ok"] is False + assert "unambiguous merge base" in selector["error"] + assert "--git-diff-base" in selector["error"] + assert selector["changed_files"] == [] + assert [warning["source"] for warning in selector["warnings"]] == ["base"] + + for subcommand, extra in [("plan", []), ("premerge", ["--tier", "quick", "--no-execute"])]: + response = run_source_cli( + ["--format", "json", "canary", subcommand, "--from-git-diff", "--git-diff-base", "target", *extra], + cwd=repo, check=False, timeout=60, + ) + assert response.returncode != 0, response.stdout + payload = json.loads(response.stdout) + assert payload["ok"] is False + assert "unambiguous merge base" in payload["error"] + assert "gate" not in payload and "selection_inputs" not in payload + + # Genuine zero-diff branch with a single unambiguous merge base succeeds cleanly. + _git(repo, "checkout", "-qb", "clean-zero-diff", "target") + _git(repo, "commit", "--allow-empty", "-m", "empty commit on clean target") + clean_selector = collect_git_diff_changed_files(repo_root=repo, base_ref="target") + assert clean_selector["ok"] is True + assert clean_selector["changed_files"] == [] + assert clean_selector["warnings"] == [] + + for subcommand, extra in [("plan", []), ("premerge", ["--tier", "quick", "--no-execute"])]: + ok_resp = run_source_cli( + ["--format", "json", "canary", subcommand, "--from-git-diff", "--git-diff-base", "target", *extra], + cwd=repo, check=False, timeout=60, + ) + assert ok_resp.returncode == 0, ok_resp.stderr + ok_payload = json.loads(ok_resp.stdout) + assert ok_payload["ok"] is True + assert ok_payload["selector_sources"]["git_diff"]["changed_files"] == [] + selected = ok_payload["selection_inputs"]["changed_files"] if subcommand == "plan" else ok_payload["changed_files"] + assert selected == [] diff --git a/tests/test_ci_resource_policy.py b/tests/test_ci_resource_policy.py index 0e17d2d62e..8ae9a9052e 100644 --- a/tests/test_ci_resource_policy.py +++ b/tests/test_ci_resource_policy.py @@ -149,90 +149,27 @@ def test_diff_inspection_uses_trusted_code_and_read_only_scope(action: str) -> N assert policy["permissions"] == {"contents": "read"} assert job["permissions"] == {"contents": "read", "pull-requests": "read"} assert job["timeout-minutes"] <= 2 - assert all(step["uses"].startswith("actions/github-script@") for step in job["steps"]) - - -def _run_diff_inspection(mode: str, branch: str = "main") -> dict: - script = workflow("ci-maintenance")["jobs"]["inspect-pr-diff"]["steps"][0]["with"]["script"] - harness = r''' -let input = ''; for await (const chunk of process.stdin) input += chunk; -const {script, mode, branch} = JSON.parse(input); -const oldBase = 'a'.repeat(40), head = 'b'.repeat(40), target = 'c'.repeat(40), newer = 'd'.repeat(40); -const pr = {state:'open', head:{sha:head,ref:'work',repo:{id:2}}, - base:{sha:oldBase,ref:branch,repo:{id:1}}, changed_files:9,additions:30,deletions:12}; -const expected = structuredClone(pr); -if (mode === 'closed') pr.state = 'closed'; -if (mode === 'fresh') pr.base.sha = target; -if (mode === 'old_event_head') expected.head.sha = newer; -if (mode === 'old_event_source') expected.head.repo.id = 3; -if (mode === 'old_event_base') expected.base.ref = 'other'; -if (mode === 'missing_source') pr.head.repo = null; -if (mode === 'same_repo') {pr.head.repo.id = 1; expected.head.repo.id = 1;} -let reads = 0, branchReads = 0; -const updates = [], notes = []; -const context = {repo:{owner:'owner',repo:'fixture'}, payload:{number:17,pull_request:expected}}; -const github = {rest:{pulls:{get:async()=>{ - reads++; - if (reads === 2) { - if (mode === 'head_before_write') pr.head.sha = newer; - if (mode === 'source_before_write') pr.head.repo.id = 3; - if (mode === 'base_before_write') pr.base.ref = 'other'; - if (mode === 'refreshed_before_write') pr.base.sha = target; - } - const snapshot = structuredClone(pr); - if (reads === 2 && mode === 'retarget_after_read') pr.base.ref = 'release/stable'; - return {data:snapshot}; -}, update:async params=>{ - updates.push(params); - pr.base.ref = params.base; - if (mode === 'failed_api') throw new Error('provider rejected update'); - if (mode !== 'not_applied') pr.base.sha = mode === 'target_moves' ? newer : target; - if (mode === 'head_during_write') pr.head.sha = newer; - if (mode === 'base_during_write') pr.base.ref = 'other'; - pr.changed_files = 2; pr.additions = 3; pr.deletions = 1; -}}, repos:{getBranch:async params=>{ - if (params.branch !== branch) throw new Error('unverified target'); - branchReads++; - return {data:{commit:{sha:mode === 'target_moves' && branchReads > 1 ? newer : target}}}; -}}}}; -let error = null; -try {await new (Object.getPrototypeOf(async function(){}).constructor)('github','context','core',script) - (github,context,{info:message=>notes.push(message)});} catch(e) {error=e.message;} -process.stdout.write(JSON.stringify({updates,notes,error,pr})); -''' - result = subprocess.run( - ["node", "--input-type=module", "-e", harness], - input=json.dumps({"script": script, "mode": mode, "branch": branch}), - text=True, capture_output=True, check=True, timeout=10, - ) - return json.loads(result.stdout) - - -@pytest.mark.parametrize("branch", ["main", "release/stable"]) -@pytest.mark.parametrize("mode", ["stale", "same_repo", "target_moves"]) -def test_diff_inspection_reports_evidence_without_mutation(mode: str, branch: str) -> None: - observed = _run_diff_inspection(mode, branch) - assert observed["error"] is None - assert observed["updates"] == [] - assert observed["pr"]["base"]["ref"] == branch - assert any("Comparison inspection" in note and "read-only" in note for note in observed["notes"]) - - -@pytest.mark.parametrize("mode", [ - "fresh", "closed", "old_event_head", "old_event_source", "old_event_base", "missing_source", - "head_before_write", "source_before_write", "base_before_write", "refreshed_before_write", -]) -def test_diff_inspection_does_not_publish_stale_evidence(mode: str) -> None: - observed = _run_diff_inspection(mode) - assert observed["updates"] == [] - assert observed["error"] is None - assert not any("Comparison inspection" in note for note in observed["notes"]) - - -def test_diff_inspection_cannot_overwrite_a_last_moment_retarget() -> None: - observed = _run_diff_inspection("retarget_after_read") - assert observed["pr"]["base"]["ref"] == "release/stable" - assert observed["updates"] == [] + checkout, inspect = job["steps"] + assert checkout["uses"] == "actions/checkout@v7" + assert checkout["with"] == { + "ref": "${{ github.workflow_sha }}", + "fetch-depth": 1, + "sparse-checkout": "scripts/ci", + "persist-credentials": False, + } + assert inspect["run"] == "python3 scripts/ci/review_gate.py inspect-pr-diff" + assert inspect["env"] == {"GH_TOKEN": "${{ github.token }}"} + + +def test_published_diff_verification_supplies_required_merge_gate() -> None: + jobs = workflow("python-tests")["jobs"] + changes = jobs["changes"] + classify = next(step for step in changes["steps"] if step.get("id") == "classify") + assert changes["permissions"] == {"contents": "read", "pull-requests": "read"} + assert "--base \"$BASE_SHA\" --head \"$HEAD_SHA\" --verify-pr-diff" in classify["run"] + assert "changes" in jobs["merge-gate"]["needs"] + assert any(step.get("run") == "python scripts/ci/review_gate.py verify" + for step in jobs["merge-gate"]["steps"]) @pytest.mark.parametrize("mode", ["delayed", "never", "changed"]) diff --git a/tests/test_sonarcloud_workflow.py b/tests/test_sonarcloud_workflow.py index 3d4a1e23d2..6f46be1453 100644 --- a/tests/test_sonarcloud_workflow.py +++ b/tests/test_sonarcloud_workflow.py @@ -129,7 +129,11 @@ def test_separate_trusted_cleanup_does_not_activate_analysis() -> None: assert set(maintenance["on"]["pull_request_target"]["types"]) == { "closed", "synchronize", "opened", "reopened", "edited", } - for job in maintenance["jobs"].values(): + for name, job in maintenance["jobs"].items(): assert "uses" not in job and "secrets" not in job - assert all(not step.get("uses", "").startswith("actions/checkout@") for step in job["steps"]) + checkouts = [step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@")] + if name == "inspect-pr-diff": + assert [step["with"]["ref"] for step in checkouts] == ["${{ github.workflow_sha }}"] + else: + assert checkouts == [] _assert_analysis_boundary(workflow, caller)