diff --git a/.github/workflows/approval-review-event.yml b/.github/workflows/approval-review-event.yml new file mode 100644 index 000000000..fd41ff232 --- /dev/null +++ b/.github/workflows/approval-review-event.yml @@ -0,0 +1,14 @@ +name: CI — approval review event + +on: + pull_request_review: + types: [submitted, edited, dismissed] + +permissions: {} + +jobs: + signal: + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - run: echo "Review changed. The trusted approval workflow reads live GitHub data." diff --git a/.github/workflows/independent-approvals.yml b/.github/workflows/independent-approvals.yml new file mode 100644 index 000000000..f6a690e5b --- /dev/null +++ b/.github/workflows/independent-approvals.yml @@ -0,0 +1,35 @@ +name: CI — independent approvals + +on: + pull_request_target: + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft, closed] + workflow_run: + workflows: [CI — approval review event] + types: [completed] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pull-requests: read + statuses: write + +concurrency: + group: independent-approval-status-writer + queue: max + +jobs: + reconcile: + if: github.event_name != 'workflow_run' || github.event.workflow_run.event == 'pull_request_review' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + - name: Reconcile current approvals using trusted main code + env: + GH_TOKEN: ${{ github.token }} + run: python3 -m tools.check_independent_approvals diff --git a/docs/agent-collaboration.md b/docs/agent-collaboration.md index f6686320d..70d794f6d 100644 --- a/docs/agent-collaboration.md +++ b/docs/agent-collaboration.md @@ -113,6 +113,44 @@ is resolved. Record the reason and supporting evidence on the PR. The two valid approvals are still required after dismissal. [GitHub review dismissal](https://docs.github.com/en/pull-requests/how-tos/review-pull-requests/dismissing-a-pull-request-review) +### Independent-approval check rollout (not active) + +The proposed `independent-approvals` observer in #440/#441 does not replace the +live native review rule above. Until the separately accepted ruleset cutover, +two native approvals and resolution or authorized dismissal of blocking +Request changes are still required. The review skill continues to describe that +live rule. + +The observer counts GitHub User accounts with current write access, the exact +first non-empty line `LGTM`, and a formal approval on the current head. GitHub +Bot/App actors and unresolved actor types do not count. It excludes the PR author +and linked commit authors/committers; the integrator still checks parent, +material-contributor and delegation independence separately. A later opinionated +vote replaces that account's approval; another reviewer's dissent stays visible. + +Before each merge, re-read current-head reviews and permissions instead of using +an earlier successful status as proof of current eligibility. The observer's +read-only `--pull-request` mode performs fresh reads; inspect its reported count +and state, since exit zero alone only means reconciliation had no API error. + +**Status-source cutover remains blocked.** The current observer uses the shared +GitHub Actions status identity. Another workflow with `statuses: write` can use +that identity too; checking `github-actions[bot]` or the context name does not +authenticate the originating workflow. GitHub documents both [workflow token +permissions](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#permissions) +and [binding a required check to an expected App](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-status-checks-before-merging). + +Before replacing the native review gate, the owner must record an exclusive +trusted status source, such as a separately permissioned App, and bind the +required check to its identity. Verify on a disposable head that a status written +by a different actor and by another Actions workflow cannot satisfy the gate. +Both negative probes must actually run and fail to satisfy it. Unit tests or a +code-reading claim cannot substitute for that live verification. Keep the native +gate in place if either probe is missing or succeeds. Record the current-head +permission-revocation check, the two-approval/dissent matrix, the merge-box result +and before/after ruleset JSON in #440 before the final cutover. At no point may +both gates be disabled. + ### Agent–Agent: isolated work and conditional handoff ```mermaid diff --git a/tests/test_independent_approvals.py b/tests/test_independent_approvals.py new file mode 100644 index 000000000..b20f32009 --- /dev/null +++ b/tests/test_independent_approvals.py @@ -0,0 +1,121 @@ +from pathlib import Path +from unittest.mock import Mock + +import pytest +import yaml + +from tools import check_independent_approvals as gate + +HEAD = "a" * 40 +OLD = "b" * 40 + + +def pr(number=10, head=HEAD, branch="main"): + return {"number": number, "head": {"sha": head}, "state": "open", "draft": False, + "base": {"ref": branch, "repo": {"full_name": "example/repo"}}, + "user": {"login": "author"}, "commits": 1} + + +def vote(login, state="APPROVED", body="LGTM", head=HEAD, can_push=True, actor_type="User"): + return {"author": {"login": login, "__typename": actor_type}, "state": state, "body": body, + "commit": {"oid": head}, "authorCanPushToRepository": can_push} + + +def test_only_current_eligible_approvals_count(): + reviews = [vote("A", body="\n LGTM \n\nVerified"), vote("a"), vote("B"), + vote("dissent", state="CHANGES_REQUESTED"), vote("revoked", state="DISMISSED"), + vote("old", head=OLD), vote("reader", can_push=False), vote("author"), + vote("commit-author"), vote("case", body="lgtm"), vote("late", body="PASS\nLGTM")] + assert gate.review_candidates(reviews, HEAD, {"author", "commit-author"}) == {"a", "b"} + + +@pytest.mark.parametrize(("login", "actor_type"), [ + ("integration[bot]", "Bot"), ("integration", "Bot"), + ("integration[bot]", "User"), ("unresolved", "Mannequin"), ("unknown", None), +]) +def test_apps_bots_and_unknown_actor_types_cannot_supply_an_approval(login, actor_type): + reviews = [vote("independent"), vote(login, actor_type=actor_type)] + assert gate.review_candidates(reviews, HEAD, set()) == {"independent"} + + +def test_rechecking_the_same_head_does_not_cache_a_revoked_permission(monkeypatch): + item, api = pr(), Mock() + api.pages.return_value = [{"sha": HEAD, "author": None, "committer": None}] + permission = {"can_push": True} + monkeypatch.setattr(gate, "read_reviews", lambda *args: [ + vote("first"), vote("second", can_push=permission["can_push"]), + ]) + assert gate.evaluate(api, item) == 2 + permission["can_push"] = False + assert gate.evaluate(api, item) == 1 + + +@pytest.mark.parametrize(("second_vote", "expected"), [ + ("APPROVED", "success"), ("CHANGES_REQUESTED", "failure"), ("DISMISSED", "failure"), +]) +def test_dissent_only_changes_its_own_vote(monkeypatch, second_vote, expected): + item = pr() + api = Mock() + api.get.side_effect = [item, []] + commit = {"sha": HEAD, "author": {"login": "coauthor"}, "committer": None} + api.pages.side_effect = lambda route: [item] if route.startswith("pulls?") else [commit] + monkeypatch.setattr(gate, "read_reviews", lambda *args: [ + vote("a"), vote("b", state=second_vote), vote("third", state="CHANGES_REQUESTED"), + vote("author"), vote("coauthor"), + ]) + assert gate.reconcile(api, [item], [item]) == 0 + route, status = api.request.call_args.args + assert route == f"statuses/{HEAD}" + assert status["context"] == gate.CONTEXT + assert status["state"] == expected + + +def test_shared_head_is_never_approved(): + first, second = pr(), pr(number=11, branch="other") + api = Mock() + api.get.return_value = [] + assert gate.reconcile(api, [first, second], [first]) == 0 + assert api.request.call_args.args[1]["state"] == "failure" + api.pages.assert_not_called() + + +@pytest.mark.parametrize("before", [HEAD, None, "not-a-sha"]) +def test_synchronize_reconciles_a_peer_after_a_shared_head_splits(monkeypatch, before): + first, second = pr(), pr(number=11) + api, statuses = Mock(), {} + monkeypatch.setattr(gate, "evaluate", lambda *_: 2) + monkeypatch.setattr(gate, "publish", + lambda _api, head, state, _description: statuses.update({head: state})) + assert gate.reconcile(api, [first, second], [first]) == 0 + assert statuses[HEAD] == "failure" + + # PR 11 advances; PR 10 is now the unique owner of the former shared SHA. + moved = pr(number=11, head=OLD) + current = [first, moved] + api.get.side_effect = lambda route: first if route == "pulls/10" else moved + api.pages.return_value = current + event = {"action": "synchronize", "number": 11, "pull_request": moved} + if before is not None: + event["before"] = before + selected = gate.targets(current, "pull_request_target", event) + assert gate.reconcile(api, current, selected) == 0 + assert statuses == {HEAD: "success", OLD: "success"} + + +def test_fork_review_without_run_association_reconciles_from_live_data(): + items = [pr()] + event = {"workflow_run": {"event": "pull_request_review", "pull_requests": []}} + assert gate.targets(items, "workflow_run", event) == items + + +def test_status_writer_does_not_execute_code_from_review_workflow(): + directory = Path(__file__).resolve().parents[1] / ".github" / "workflows" + signal = yaml.load((directory / "approval-review-event.yml").read_text(encoding="utf-8"), + Loader=yaml.BaseLoader) + writer = yaml.load((directory / "independent-approvals.yml").read_text(encoding="utf-8"), + Loader=yaml.BaseLoader) + assert signal["permissions"] == {} + assert writer["on"]["workflow_run"]["workflows"] == [signal["name"]] + assert writer["jobs"]["reconcile"]["steps"][0]["with"] == { + "ref": "main", "persist-credentials": "false", + } diff --git a/tools/check_independent_approvals.py b/tools/check_independent_approvals.py new file mode 100644 index 000000000..f5959ef2a --- /dev/null +++ b/tools/check_independent_approvals.py @@ -0,0 +1,196 @@ +"""Evaluate current-head approvals; advisory until the status-source cutover is accepted.""" + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +from tools.check_knowledge_model_policy import API_ERRORS, SHA, GitHub + +CONTEXT = "independent-approvals" +BRANCH = "main" +REQUIRED = 2 +REVIEW_ERRORS = (*API_ERRORS, subprocess.TimeoutExpired) +REVIEWS = """ +query($owner: String!, $repo: String!, $number: Int!, $endCursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + headRefOid + latestOpinionatedReviews(first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { author { __typename login } authorCanPushToRepository state commit { oid } body } + } + } + } +} +""" + + +def is_target(pr): + return pr["state"] == "open" and pr["base"]["ref"] == BRANCH + + +def review_candidates(reviews, head, contributors): + candidates = set() + for review in reviews: # GitHub provides the latest opinionated vote per reviewer. + if (review["state"] != "APPROVED" or not review["authorCanPushToRepository"] + or not review["author"] or not review["commit"] or review["commit"]["oid"] != head): + continue + login = review["author"]["login"].casefold() + if review["author"].get("__typename") != "User" or login.endswith("[bot]"): + continue + lines = review["body"].strip().splitlines() + first_line = lines[0].strip() if lines else "" + if login not in contributors and first_line == "LGTM": + candidates.add(login) + return candidates + + +def read_reviews(repository, number, head): + owner, repo = repository.split("/") + result = subprocess.run( + ["gh", "api", "graphql", "--paginate", "--slurp", "-f", f"query={REVIEWS}", + "-f", f"owner={owner}", "-f", f"repo={repo}", "-F", f"number={number}"], + capture_output=True, check=False, timeout=90, + ) + if result.returncode != 0: + raise ValueError("Could not read opinionated reviews") + pages = [page["data"]["repository"]["pullRequest"] for page in json.loads(result.stdout)] + if (not pages or any(not page or page["headRefOid"] != head for page in pages) + or pages[-1]["latestOpinionatedReviews"]["pageInfo"]["hasNextPage"]): + raise ValueError("Could not verify all reviews on the current head") + return [review for page in pages for review in page["latestOpinionatedReviews"]["nodes"]] + + +def evaluate(api, pr): + # Fetch permissions and reviews every time: a prior status does not freeze eligibility. + number = pr["number"] + head = pr["head"]["sha"] + reviews = read_reviews(pr["base"]["repo"]["full_name"], number, head) + candidates = review_candidates(reviews, head, {pr["user"]["login"].casefold()}) + if not candidates: + return 0 + + commits = api.pages(f"pulls/{number}/commits") + if len(commits) != pr["commits"] or not commits or commits[-1]["sha"] != head: + raise ValueError("Could not verify the complete PR commit list for this head") + contributors = {commit[field]["login"].casefold() + for commit in commits for field in ("author", "committer") if commit[field]} + return len(candidates - contributors) + + +def targets(prs, event_name, event): + if event_name == "pull_request_target": + # A synchronize can make the former shared head unique again. + heads = {event["pull_request"]["head"]["sha"]} + if event.get("action") == "synchronize": + before = event.get("before") + if not isinstance(before, str) or not SHA.fullmatch(before): + return prs # The previous head is unknown; reconcile from live data. + heads.add(before) + number = event["number"] + return [pr for pr in prs if pr["number"] == number or pr["head"]["sha"] in heads] + if event_name == "workflow_run": + run = event["workflow_run"] + if run["event"] != "pull_request_review": + raise ValueError("Expected a review event workflow") + # Fork review runs may have no PR association. Fall back to live open PRs. + numbers = {pr["number"] for pr in run["pull_requests"]} + if not numbers: + return prs + return [pr for pr in prs if pr["number"] in numbers + or pr["head"]["sha"] == run["head_sha"]] + if event_name in {"push", "workflow_dispatch"}: + return prs + raise ValueError("Unsupported approval check event") + + +def publish(api, head, state, description): + # Reconcile missed events without consuming one status per unchanged sweep. + # Matching github-actions[bot] is only deduplication, not authentication: another + # workflow can use that identity. This status must stay advisory until the cutover + # verifies an exclusive source and rejects an independently published forged success. + statuses = api.get(f"commits/{head}/statuses?per_page=100") + for status in statuses: + if status["context"].casefold() == CONTEXT: + if (status["state"] == state and status["description"] == description + and (status.get("creator") or {}).get("login") == "github-actions[bot]"): + return + break + payload = {"state": state, "context": CONTEXT, "description": description} + if run_id := os.environ.get("GITHUB_RUN_ID"): + repository = os.environ["GITHUB_REPOSITORY"] + payload["target_url"] = f"https://github.com/{repository}/actions/runs/{run_id}" + api.request(f"statuses/{head}", payload) + + +def reconcile(api, prs, selected, dry_run=False): + heads = {} + for pr in prs: + heads.setdefault(pr["head"]["sha"], []).append(pr["number"]) + + failed = False + checked = set() + for pr in filter(is_target, selected): + head = pr["head"]["sha"] + number = pr["number"] + if not SHA.fullmatch(head): + raise ValueError("Invalid PR head") + if head in checked: + continue + checked.add(head) + + description = "Head is shared by multiple open pull requests" + state = "failure" + try: + if heads[head] == [number]: + current = api.get(f"pulls/{number}") + if not is_target(current) or current["head"]["sha"] != head: + continue + count = 0 if current["draft"] else evaluate(api, current) + description = f"{count}/{REQUIRED} eligible current-head approvals" + state = "success" if count >= REQUIRED else "failure" + + # A success calculated for one PR must not be reused by another PR on the same SHA. + if state == "success": + latest = api.pages("pulls?state=open") + owners = [item for item in latest if item["head"]["sha"] == head] + if len(owners) != 1 or owners[0]["number"] != number or not is_target(owners[0]): + state, description = "failure", "PR changed during evaluation" + except REVIEW_ERRORS: + failed = True + state, description = "error", "Could not verify approval evidence" + + print(f"PR #{number}: {state}: {description}") + if not dry_run: + try: + publish(api, head, state, description) + except API_ERRORS: + failed = True + print(f"PR #{number}: could not publish approval status", file=sys.stderr) + return int(failed) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--pull-request", type=int) + args = parser.parse_args() + api = GitHub(os.environ["GITHUB_REPOSITORY"], os.environ["GH_TOKEN"]) + try: + prs = api.pages("pulls?state=open") + if args.pull_request is not None: + selected = [pr for pr in prs if pr["number"] == args.pull_request] + if not selected or not is_target(selected[0]): + raise ValueError("Expected an open pull request against main") + return reconcile(api, prs, selected, dry_run=True) + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + return reconcile(api, prs, targets(prs, os.environ["GITHUB_EVENT_NAME"], event)) + except API_ERRORS: + print("Could not load approval check inputs from GitHub", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main())