diff --git a/.github/agent-safety-manifest.json b/.github/agent-safety-manifest.json index 5b1db71ba8..1de6ccda5a 100644 --- a/.github/agent-safety-manifest.json +++ b/.github/agent-safety-manifest.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "description": "Paths whose changes require one current-head cross-vendor independent review.", + "description": "Paths whose changes require a current-head independent review. The review-verdict check and the manual protected-safety-review workflow both read this list.", "areas": [ { "id": "verification-authority", @@ -18,7 +18,11 @@ "packages/flow/openadapt_flow/runtime/effects/**", "packages/flow/openadapt_flow/local_state_sources.py", "packages/flow/tests/test_verify_run.py", - "packages/flow/tests/test_verify_tools.py" + "packages/flow/tests/test_verify_tools.py", + "packages/flow/openadapt_flow/verifier_audit/**", + "packages/flow/openadapt_flow/verification.py", + "packages/flow/openadapt_flow/terminal_verification_v2.py", + "packages/flow/openadapt_flow/scaffold_verifier.py" ] }, { @@ -50,7 +54,14 @@ "packages/flow/tests/test_write_receipt.py", "packages/flow/tests/test_offline_seal.py", "packages/flow/tests/test_cloud_seal.py", - "packages/types/tests/test_seal.py" + "packages/types/tests/test_seal.py", + "packages/flow/openadapt_flow/receipt_*.py", + "packages/flow/openadapt_flow/cli_receipt.py", + "packages/flow/openadapt_flow/seal_*.py", + "packages/flow/openadapt_flow/public_seal.py", + "packages/flow/openadapt_flow/cli_local_seal.py", + "packages/flow/openadapt_flow/bundle_sealing.py", + "packages/flow/openadapt_flow/sealed_*.py" ] }, { @@ -84,7 +95,46 @@ "scripts/ci/__init__.py", "docs/agent-safety-evidence-v1.md", "tests/test_attestation.py", - "tests/test_protected_safety_review.py" + "tests/test_protected_safety_review.py", + ".github/review-verdict.json", + "scripts/ci/review_verdict.py", + "tests/test_review_verdict.py", + "tests/fixtures/review_verdict/**", + "docs/maintainers/review-verdict-rollout.md", + "packages/flow/tests/failopen/sites/review_verdict.py" + ] + }, + { + "id": "wrap-and-transducer", + "rationale": "The wrap SDK and the simplex transducer decide what an agent's write is allowed to commit and what it reports back.", + "paths": [ + "openadapt/wrap_sdk.py", + "openadapt/simplex_transducer.py", + "openadapt/transducer_*.py" + ] + }, + { + "id": "governed-kernel", + "rationale": "The kernel enforces signed policy and produces the receipts the rest of the product trusts.", + "paths": [ + "packages/kernel/**" + ] + }, + { + "id": "runtime-replay-and-confirmation", + "rationale": "Replay, target resolution and commit confirmation decide which on-screen element is acted on and whether a write is reported as committed.", + "paths": [ + "packages/flow/openadapt_flow/runtime/replay/**", + "packages/flow/openadapt_flow/runtime/resolver.py", + "packages/flow/openadapt_flow/runtime/worklist_copilot.py" + ] + }, + { + "id": "ci-workflows", + "rationale": "Workflows and composite actions run with repository tokens and decide which checks a pull request must pass.", + "paths": [ + ".github/workflows/**", + ".github/actions/**" ] } ] diff --git a/.github/review-verdict.json b/.github/review-verdict.json new file mode 100644 index 0000000000..1c9f7c5b2b --- /dev/null +++ b/.github/review-verdict.json @@ -0,0 +1,14 @@ +{ + "schema_version": 1, + "status_context": "review-verdict", + "protected_paths_manifest": ".github/agent-safety-manifest.json", + "sources": ["issue_comment", "pull_request_review"], + "authors": [ + { + "login": "abrichr", + "reviewers": ["Grok", "Codex"], + "native_reviews": false, + "note": "Founder account. Grok and Codex post their reviews from it today, so each comment must name its reviewer in a From: line." + } + ] +} diff --git a/.github/workflows/README.md b/.github/workflows/README.md index bcb11d4a42..0d1db81917 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -97,6 +97,45 @@ EOF Then remove the `legacy-run-ci` and `legacy-packages-gate` jobs from ci.yml. App 15368 is GitHub Actions, the app the current checks are pinned to. +## Review verdict + +review-verdict.yml publishes a commit status named `review-verdict`. It +reads the Grok and Codex review comments, so a pull request can't merge +over an open REQUEST CHANGES the way #2769 did. + +- A pull request that changes no path in `.github/agent-safety-manifest.json` + passes with "no protected paths". The manifest is the one list of + protected paths. It covers the verifier, receipts and seals, replay and + commit confirmation, `wrap_sdk.py`, the transducer, `packages/kernel/**` + and `.github/workflows/**`. +- Otherwise the newest review from an account in `.github/review-verdict.json`, + with a `From: Grok` or `From: Codex` line, must name the current head in + its `Reviewed-Head:` line and say exactly `APPROVE`. A conditional approval, + BLOCK, REQUEST CHANGES, a stale head or no review fails. +- A REQUEST CHANGES at the current head stands until the same reviewer + approves. Another reviewer's APPROVE doesn't clear it. +- A review stays current across merges from main when each merge is clean + and the pull request's own diff is unchanged. +- In the merge queue the check re-reads the comments for every queued pull + request, so a REQUEST CHANGES posted after queueing stops the merge. + +The full rule is in the docstring of `scripts/ci/review_verdict.py`, and +the tests are in `tests/test_review_verdict.py`. The job runs on pull request +pushes, on comments that contain `Reviewed-Head`, on pull request reviews +and in the merge queue. It always runs the script from `main`. To re-check a +pull request by hand, for example a fork's, run the workflow with its number: + +```bash +gh workflow run review-verdict.yml --repo OpenAdaptAI/OpenAdapt -f pull_request= +``` + +Until an admin adds `review-verdict` to the required checks, it reports but +doesn't block. The steps are in `docs/maintainers/review-verdict-rollout.md`. +protected-safety-review.yml stays manual-only. Both read the same manifest. +The one rule it has that `review-verdict` lacks is the author-vendor rule (the +reviewer's vendor must differ from the author's), so decide about that rule +before deleting it. + ## Jobs by tier | Workflow | Job | PR tier | Queue tier | Post-merge tier | diff --git a/.github/workflows/review-verdict.yml b/.github/workflows/review-verdict.yml new file mode 100644 index 0000000000..48a64a3067 --- /dev/null +++ b/.github/workflows/review-verdict.yml @@ -0,0 +1,65 @@ +name: Review verdict + +# Publishes the `review-verdict` commit status. A pull request that changes +# a protected path (.github/agent-safety-manifest.json) needs the newest Grok +# or Codex review to approve its current head. The rule is in the docstring +# of scripts/ci/review_verdict.py; the rollout steps are in +# docs/maintainers/review-verdict-rollout.md. +# +# The script and its config always come from a checkout of main. Pull +# request commits are fetched as git objects for the merge-from-main check +# and are never checked out or run. There is no pull_request_target trigger. +on: + pull_request: + types: [opened, synchronize, reopened] + issue_comment: + types: [created, edited, deleted] + pull_request_review: + types: [submitted, edited, dismissed] + merge_group: + types: [checks_requested] + workflow_dispatch: + inputs: + pull_request: + description: Pull request number to re-evaluate + required: true + type: number + +permissions: + contents: read + pull-requests: read + statuses: write + +jobs: + evaluate: + name: Evaluate review verdict + # Skip, without taking a runner, comments that can't change a verdict: + # comments on plain issues, and comments without a Reviewed-Head line. + # Skipping is safe only here, because the verdict is the status. + if: >- + github.event_name != 'issue_comment' || + (github.event.issue.pull_request && + (contains(github.event.comment.body, 'Reviewed-Head') || + contains(github.event.changes.body.from, 'Reviewed-Head'))) + # Jobs for one pull request queue behind each other, so the newest one + # reads the newest comments and publishes last. This sits on the job, not + # the workflow: a skipped comment run must not replace a pending + # evaluation in the queue. + concurrency: + group: review-verdict-${{ github.event.pull_request.number || github.event.issue.number || inputs.pull_request || github.event.merge_group.head_sha || github.run_id }} + cancel-in-progress: false + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out main (trusted code only) + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + fetch-depth: 0 + filter: blob:none + persist-credentials: false + - name: Evaluate and publish the review-verdict status + env: + GITHUB_TOKEN: ${{ github.token }} + DISPATCH_PULL_REQUEST: ${{ inputs.pull_request }} + run: python3 scripts/ci/review_verdict.py diff --git a/docs/maintainers/review-verdict-rollout.md b/docs/maintainers/review-verdict-rollout.md new file mode 100644 index 0000000000..216feb5bd3 --- /dev/null +++ b/docs/maintainers/review-verdict-rollout.md @@ -0,0 +1,125 @@ +# Rolling out the review-verdict check + +`review-verdict` is a commit status. `.github/workflows/review-verdict.yml` +publishes it from `scripts/ci/review_verdict.py`. It reports on every pull +request as soon as the workflow is on `main`, but it blocks nothing until an +admin makes it required. The agent that built it changed no repository +settings. A repository admin takes the steps below. + +## Before you start + +- The workflow must be on `main`. GitHub runs comment-triggered workflows only + from the default branch, so the check can't react to review comments + before then. +- Run it once on a pull request with a protected path and once on one without, + and confirm that the `review-verdict` status shows "GitHub Actions" as its + source. Also confirm that a Dependabot pull request's own run can publish + the status. The workflow asks for `statuses: write`, which GitHub grants to + Dependabot runs; if it doesn't, every Dependabot pull request waits for a + manual run once the check is required: + + ```bash + gh workflow run review-verdict.yml --repo OpenAdaptAI/OpenAdapt -f pull_request= + ``` + +## 1. Add `review-verdict` to the required checks on `main` + +This replaces the whole list, so it repeats the three current checks: + +```bash +gh api -X PATCH repos/OpenAdaptAI/OpenAdapt/branches/main/protection/required_status_checks --input - <<'EOF' +{"strict": false, "checks": [{"context": "ci", "app_id": 15368}, {"context": "gitleaks", "app_id": 15368}, {"context": "dependency-review", "app_id": 15368}, {"context": "review-verdict", "app_id": 15368}]} +EOF +``` + +App 15368 is GitHub Actions. Pinning the app means a status that someone posts +with a personal token doesn't count. If GitHub refuses the pin for a commit +status, use `"app_id": -1` (any source) and say so in the PR that records the +change. + +After the change: + +- Every open pull request needs a `review-verdict` status on its head before + it can merge. A push, a review comment or a manual run sets it. To set it on + all open pull requests at once: + + ```bash + for n in $(gh pr list --repo OpenAdaptAI/OpenAdapt --state open --limit 200 --json number -q '.[].number'); do gh workflow run review-verdict.yml --repo OpenAdaptAI/OpenAdapt -f pull_request="$n"; done + ``` + +- Check that the merge queue waits for `review-verdict` on its first group. + The status goes on the merge-group commit. +- Pull requests from forks get a read-only token, so their own push can't + publish the status. A review comment or a manual run publishes it instead. +- Dependabot pull requests that bump actions change `.github/workflows/**`, + so they need a review too. + +## 2. Create GitHub App identities for Grok and Codex + +Today Grok and Codex post from the founder's account, and the check trusts +that account's comments when they carry `From: Grok` or `From: Codex`. + +**Until this step is done, the check can be spoofed.** Every agent session +that posts as `abrichr` (Claude, Gemini, Grok, Codex, or a script using the +founder's token) can write a comment that starts +`## Independent adversarial review: APPROVE` / `From: Grok` / +`Reviewed-Head: `, and the check will pass it. Nothing in a comment +proves which model wrote it. The `From:` line only labels it. Until the +reviewers have identities of their own, `review-verdict` catches the +accidents it was built for, such as merging over a REQUEST CHANGES, a stale +approval or no review at all. It doesn't stop a session that writes its own +approval. + +Separate identities fix this: + +1. Create one GitHub App per reviewer, for example `openadapt-grok-review` + and `openadapt-codex-review`, owned by the OpenAdaptAI organization. Give + each one Pull requests: Read and write and Contents: Read only. Install + each app on `OpenAdaptAI/OpenAdapt` only. +2. Give each reviewer harness its app's private key, and have it post with an + installation token. +3. Add each app's bot login to `.github/review-verdict.json` in a reviewed + pull request: + + ```json + {"login": "openadapt-grok-review[bot]", "reviewers": ["Grok"], "native_reviews": true} + ``` + + With `native_reviews: true`, a real GitHub review from that app counts: its + state is the verdict and its `commit_id` is the reviewed head. Comments from + the app still need the usual header. +4. When both apps are posting, remove the `abrichr` entry, and optionally set + `"sources": ["pull_request_review"]` so that only real reviews count. + +## 3. Require one approval on protected paths + +The workflow file runs from the pull request's own merge commit, so a pull +request that edits `.github/workflows/review-verdict.yml` could change what +the check does for itself. Code-owner review closes this: + +1. In `.github/CODEOWNERS`, add owners for the protected paths that aren't + listed yet, at least `/.github/workflows/`, `/.github/review-verdict.json`, + `/.github/agent-safety-manifest.json`, `/scripts/ci/review_verdict.py`, + `/openadapt/wrap_sdk.py`, `/openadapt/simplex_transducer.py`, + `/openadapt/transducer_*.py` and `/packages/kernel/`. Do this in a + reviewed pull request. +2. In branch protection for `main`, set required approvals to 1 and turn on + "Require review from Code Owners". Leave stale-review dismissal off; + `review-verdict` already handles stale heads. +3. Do this only after step 2. Agents open pull requests from the founder's + account, and GitHub doesn't let an author approve their own pull request. + With the founder as the only code owner, every protected pull request would + be stuck. Make the reviewer apps code owners of those paths, or add a second + human code owner, before you turn the requirement on. + +## Not done, and why + +- protected-safety-review.yml stays as it is: manual-only since #2678. + `review-verdict` covers what it checked. Both read the same manifest, so + deleting it later loses nothing. Its stricter author-vendor rule (a review + must come from a vendor other than the author's) isn't part of + `review-verdict`. Decide whether to keep that rule before deleting the old + workflow. +- #2678 turned off the old automatic gate, partly because its comment trigger + took a runner for every comment. This job skips, without a runner, comments + that have no `Reviewed-Head` line or aren't on a pull request. diff --git a/packages/flow/tests/failopen/sites/review_verdict.py b/packages/flow/tests/failopen/sites/review_verdict.py new file mode 100644 index 0000000000..9743ddc3e3 --- /dev/null +++ b/packages/flow/tests/failopen/sites/review_verdict.py @@ -0,0 +1,164 @@ +"""scripts/ci/review_verdict.evaluate (C1 C2 C3): the review-verdict check. + +The results are the review comments on a pull request that changes a +protected path. The check passes only when the newest Grok or Codex review +approves the current head. An empty comment list, a dropped approval, a +blocking copy of an approval, a perturbed head, a heading nobody listed and a +merge-from-main probe that raises must all fail. +""" + +from __future__ import annotations + +import copy +import importlib.util +import json +import sys +from pathlib import Path +from typing import Any + +from tests.failopen.harness import Seed, SiteSpec, key, register + +ROOT = Path(__file__).resolve().parents[5] +HEAD = "009f73ddc4665b2851c534aaa785f9a039c8a891" +OLD = "37a44504062797de54814efe4f83f482cd7a94c1" +PROTECTED = [{"filename": "packages/flow/openadapt_flow/runtime/replay/confirming.py"}] + + +def load_module(path: Path) -> Any: + spec = importlib.util.spec_from_file_location(f"_vendored_{path.stem}", path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + # Dataclasses look their module up in sys.modules while the class is made. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _comment( + verdict: str, head: str, at: str, cid: int, reviewer: str = "Grok" +) -> dict: + return { + "id": cid, + "html_url": f"https://example.invalid/{cid}", + "created_at": at, + "user": {"login": "abrichr"}, + "body": ( + f"## Independent adversarial review: {verdict}\n" + f"From: {reviewer}\nReviewed-Head: {head}\n\nFindings." + ), + } + + +def _evidence(comments: list[dict], *, equivalent: tuple[str, ...] = ()) -> dict: + # Like merge_currency, equivalence is a fact about a (reviewed, head) pair. + return { + "head": HEAD, + "files": copy.deepcopy(PROTECTED), + "comments": comments, + "equivalent": [[old, HEAD] for old in equivalent], + } + + +def review_verdict_spec(module: Any, id: str, kind: str) -> SiteSpec: + config = module.load_config(json.loads(module.CONFIG_PATH.read_text())) + patterns = module.protected_patterns( + json.loads((module.ROOT / config.manifest_path).read_text()) + ) + + def run(ev: Any) -> Any: + ev = copy.deepcopy(ev) + head = ev.get("head") + raises = ev.get("probe_raises") + + def currency(reviewed: str) -> tuple[str, str]: + if raises is not None: + raise raises + if reviewed == head: + return module.SAME, "same" + if [reviewed, head] in (ev.get("equivalent") or []): + return module.EQUIVALENT, "clean merges from main" + return module.STALE, "not the current head" + + return module.evaluate( + head=head, + files=ev.get("files") or [], + files_complete=True, + comments=ev.get("comments") or [], + reviews=[], + config=config, + patterns=patterns, + currency=currency, + ) + + def bad_item(item: Any) -> Any: + bad = copy.deepcopy(item) + bad["body"] = bad["body"].replace("review: APPROVE", "review: REQUEST CHANGES") + return bad + + def probe_raise(ev: Any, exc: BaseException) -> Any: + ev = copy.deepcopy(ev) + ev["probe_raises"] = exc + return ev + + return SiteSpec( + id=id, + classes="C1 C2 C3", + target="scripts/ci/review_verdict.py:evaluate", + kind=kind, + run=run, + is_pass=lambda out: out.passed, + seeds=lambda: [ + Seed( + _evidence([_comment("APPROVE", HEAD, "2026-11-29T22:00:00Z", 1)]), + True, + "approve at head", + ), + Seed( + _evidence( + [_comment("APPROVE", OLD, "2026-11-29T22:00:00Z", 1)], + equivalent=(OLD,), + ), + True, + "approve before clean merges from main", + ), + Seed( + _evidence([_comment("APPROVE", OLD, "2026-11-29T22:00:00Z", 1)]), + False, + "stale approve", + ), + Seed( + _evidence( + [ + _comment("REQUEST CHANGES", HEAD, "2026-11-29T21:00:00Z", 1), + _comment("APPROVE", HEAD, "2026-11-29T22:00:00Z", 2, "Codex"), + ] + ), + False, + "Grok's blocker at this head stands over Codex's approve", + ), + Seed( + _evidence( + [ + _comment( + "APPROVE if Richard OKs", HEAD, "2026-11-29T22:00:00Z", 1 + ) + ] + ), + False, + "conditional approve", + ), + ], + items=key("comments"), + bad_item=bad_item, + values=(key("head"),), + probe_raise=probe_raise, + ) + + +register( + review_verdict_spec( + load_module(ROOT / "scripts/ci/review_verdict.py"), + "review_verdict.evaluate", + "site", + ) +) diff --git a/scripts/ci/protected_safety_review.py b/scripts/ci/protected_safety_review.py index d7a9e861d7..2498a08da7 100644 --- a/scripts/ci/protected_safety_review.py +++ b/scripts/ci/protected_safety_review.py @@ -90,7 +90,7 @@ def validate_manifest(manifest: Any) -> dict[str, Any]: for path in paths ): raise EvidenceError(f"manifest area {area_id!r} contains an invalid path") - if seen != required_areas: + if not required_areas <= seen: raise EvidenceError("manifest must enumerate all six required safety areas") required_sources = { "verification-authority": { diff --git a/scripts/ci/review_verdict.py b/scripts/ci/review_verdict.py new file mode 100644 index 0000000000..250b00f55c --- /dev/null +++ b/scripts/ci/review_verdict.py @@ -0,0 +1,1127 @@ +"""The required ``review-verdict`` check: read the newest independent review. + +Grok and Codex review pull requests and post the result as a comment. This +check reads that comment, so a pull request that changes a protected path +cannot merge over an open REQUEST CHANGES, a stale approval or no review. + +What passes +----------- +A pull request that changes no path listed in +``.github/agent-safety-manifest.json`` passes with "no protected paths". +Renames count both the old and the new path. + +Otherwise the newest recognized review must name the pull request's current +head and say APPROVE. A review is recognized when all of these hold: + +* It is an issue comment or a pull request review, as allowed by ``sources`` + in ``.github/review-verdict.json``. +* Its author's login is listed under ``authors`` in that file. +* Its header block (the leading lines before the first line of prose) has a + ``From:`` line naming one of that author's reviewers, and the comment has a + ``Reviewed-Head:`` line. + +The header Grok and Codex use today looks like this, sometimes with blank +lines between the three lines:: + + ## Independent adversarial review: APPROVE + From: Grok + Reviewed-Head: 009f73ddc4665b2851c534aaa785f9a039c8a891 + +Text inside fenced code blocks is ignored. A header that is inside an HTML +comment, quoted with ``>`` or below a line of prose can't approve: the +comment counts as a malformed review, so it still blocks. Comments from +other reviewers (``From: Claude``, ``From: Gemini``) are not recognized and +never mask a recognized one. + +A recognized review fails closed when it is malformed. That covers no +verdict heading, more than one heading, ``From:`` or ``Reviewed-Head:`` line, +or a head that isn't a full 40-character SHA. It also covers a verdict other +than exactly ``APPROVE``, ``REQUEST CHANGES`` or ``BLOCK``, so a conditional +"APPROVE if Richard OKs" fails. + +"Newest" means the latest creation time; editing an old comment doesn't +make it newer. One rule goes beyond the newest review: a REQUEST CHANGES, +BLOCK or malformed review at the current head stands until the reviewer who +posted it approves the current head. Another reviewer's later APPROVE +doesn't clear it. #2769 merged over an unresolved REQUEST CHANGES for its +exact head. To drop this rule, delete the loop marked "blocker stands" in +``evaluate``. + +Merges from main +---------------- +A review of head ``R`` still counts for the current head ``H`` when only +merges from main happened since. All of these must hold: + +1. Walking first parents from ``H`` reaches ``R``, and every commit on the + way is a merge with exactly two parents whose second parent is an + ancestor of ``origin/main``. +2. Each of those merges is clean. ``git merge-tree --write-tree`` of its two + parents gives no conflict and exactly the merge's tree, so the merge holds + no conflict resolution and no hand edits. +3. The pull request's own diff is unchanged. ``git diff -U0`` from + ``merge-base(origin/main, X)`` to ``X`` lists the same files, with the + same added and removed lines in the same order, for ``X = R`` and + ``X = H``. Hunk positions and context lines may differ, because main + moved underneath. + +Anything else is stale, including an ``R`` that isn't reachable from ``H`` +after a force-push. If git can't decide (a fetch or command failed), an +approval doesn't count and a blocking review does. + +Merge queue +----------- +The queue uses the MERGE method, so a merge-group head is a chain of merge +commits on top of the group's base, one per queued pull request, each with +that pull request's head as its second parent. A ``merge_group`` run walks +that chain and re-evaluates every queued pull request at its queued head, +with its live comments and reviews. The status goes on the group head and +passes only if every pull request in the group passes. A pull request whose +head moved after it was queued fails. + +Trust +----- +The workflow checks out ``main`` and runs this file and its config from +there, never from the pull request. Pull request commits are fetched as git +objects for the merge check and are never checked out or executed. On +``pull_request`` and ``merge_group``, GitHub still takes the workflow *file* +from the pull request's merge commit, so a pull request that edits the +workflow can change what runs for itself. ``.github/workflows/**`` is a +protected path; code-owner review on it closes that gap (see +``docs/maintainers/review-verdict-rollout.md``). This check catches accidents +like #2769. It isn't a defence against a maintainer acting in bad faith. +Until Grok and Codex post from identities of their own, any session that +posts as an allowed account can also write an approval it labels +``From: Grok``. Nothing in a comment proves who wrote it. +""" + +from __future__ import annotations + +import fnmatch +import json +import os +import re +import subprocess +import sys +import unicodedata +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable + +try: + from openadapt_flow.verdict import verdict_site +except ImportError: # the workflow runs this file with only the standard library + + def verdict_site(site: str, *, classes: str = "") -> Any: + def _wrap(fn: Any) -> Any: + fn.__verdict_site__ = site + return fn + + return _wrap + + +ROOT = Path(__file__).resolve().parents[2] +CONFIG_PATH = ROOT / ".github" / "review-verdict.json" +FULL_SHA = re.compile(r"[0-9a-f]{40}") +SOURCES = ("issue_comment", "pull_request_review") +APPROVE = "APPROVE" +REQUEST_CHANGES = "REQUEST CHANGES" +BLOCK = "BLOCK" +VERDICTS = (APPROVE, REQUEST_CHANGES, BLOCK) +BLOCKING = (REQUEST_CHANGES, BLOCK) +MAX_MERGE_CHAIN = 50 +MAX_QUEUE_ENTRIES = 100 +DESCRIPTION_LIMIT = 140 + +SAME = "same" +EQUIVALENT = "equivalent" +STALE = "stale" +UNKNOWN = "unknown" + + +class ReviewVerdictError(Exception): + """The check can't reach a verdict, so it fails closed.""" + + +def short(sha: str | None) -> str: + return (sha or "none")[:8] + + +# --- configuration -------------------------------------------------------- + + +@dataclass(frozen=True) +class Author: + login: str + reviewers: tuple[str, ...] + native_reviews: bool + + +@dataclass(frozen=True) +class Config: + status_context: str + manifest_path: str + sources: frozenset[str] + authors: dict[str, Author] + + def author(self, login: Any) -> Author | None: + if not isinstance(login, str): + return None + return self.authors.get(login.casefold()) + + +def load_config(data: Any) -> Config: + """Validate ``.github/review-verdict.json``. Unknown keys are refused.""" + keys = { + "schema_version", + "status_context", + "protected_paths_manifest", + "sources", + "authors", + } + if not isinstance(data, dict) or set(data) != keys: + raise ReviewVerdictError(f"config must have exactly {sorted(keys)}") + if data["schema_version"] != 1: + raise ReviewVerdictError("unsupported config schema_version") + context = data["status_context"] + manifest = data["protected_paths_manifest"] + if not isinstance(context, str) or not context: + raise ReviewVerdictError("status_context must be a non-empty string") + if not isinstance(manifest, str) or not manifest or ".." in Path(manifest).parts: + raise ReviewVerdictError("protected_paths_manifest must be a repo path") + sources = data["sources"] + if ( + not isinstance(sources, list) + or not sources + or not set(sources) <= set(SOURCES) + or len(set(sources)) != len(sources) + ): + raise ReviewVerdictError(f"sources must be a non-empty subset of {SOURCES}") + authors: dict[str, Author] = {} + entries = data["authors"] + if not isinstance(entries, list) or not entries: + raise ReviewVerdictError("authors must be a non-empty list") + for entry in entries: + if not isinstance(entry, dict) or not {"login", "reviewers"} <= set(entry): + raise ReviewVerdictError("each author needs login and reviewers") + if not set(entry) <= {"login", "reviewers", "native_reviews", "note"}: + raise ReviewVerdictError("author entry has unknown keys") + login = entry["login"] + reviewers = entry["reviewers"] + native = entry.get("native_reviews", False) + if not isinstance(login, str) or not re.fullmatch( + r"[A-Za-z0-9-]+(\[bot\])?", login + ): + raise ReviewVerdictError(f"invalid author login {login!r}") + if ( + not isinstance(reviewers, list) + or not reviewers + or not all( + isinstance(r, str) and re.fullmatch(r"[A-Za-z]+", r) for r in reviewers + ) + ): + raise ReviewVerdictError(f"author {login} needs reviewer names") + if not isinstance(native, bool): + raise ReviewVerdictError(f"author {login}: native_reviews must be a bool") + if native and len(reviewers) != 1: + raise ReviewVerdictError( + f"author {login}: a native-review identity speaks for one reviewer" + ) + if login.casefold() in authors: + raise ReviewVerdictError(f"author {login} is listed twice") + authors[login.casefold()] = Author(login, tuple(reviewers), native) + return Config(context, manifest, frozenset(sources), authors) + + +def protected_patterns(manifest: Any) -> list[str]: + """Every path pattern in the agent-safety manifest (the one source).""" + areas = manifest.get("areas") if isinstance(manifest, dict) else None + if not isinstance(areas, list) or not areas: + raise ReviewVerdictError("protected-path manifest has no areas") + patterns: list[str] = [] + for area in areas: + paths = area.get("paths") if isinstance(area, dict) else None + if not isinstance(paths, list) or not all( + isinstance(p, str) and p for p in paths + ): + raise ReviewVerdictError("protected-path manifest area is malformed") + patterns.extend(paths) + return patterns + + +def changed_paths(files: list[dict[str, Any]]) -> list[str]: + paths: list[str] = [] + for item in files: + for key in ("filename", "previous_filename"): + value = item.get(key) + if isinstance(value, str) and value: + paths.append(value) + return paths + + +def protected_matches(paths: list[str], patterns: list[str]) -> list[str]: + """Paths matching any pattern. ``*`` also matches ``/``, so ``**`` works.""" + return sorted( + {p for p in paths if any(fnmatch.fnmatchcase(p, pat) for pat in patterns)} + ) + + +# --- parsing review text -------------------------------------------------- + +_INVISIBLE = dict.fromkeys(map(ord, "​‌‍⁠")) +_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") +_HEADING = re.compile( + r"^ {0,3}#{1,6}[ \t]*independent[ \t]+adversarial[ \t]+review[ \t]*:" + r"[ \t]*(.*?)[ \t]*$", + re.IGNORECASE, +) +_FROM = re.compile(r"^ {0,3}From[ \t]*:[ \t]*(.*?)[ \t]*$", re.IGNORECASE) +_HEAD = re.compile(r"^ {0,3}Reviewed-Head[ \t]*:[ \t]*(.*?)[ \t]*$", re.IGNORECASE) + + +def visible_lines(body: str, *, keep_html_comments: bool = False) -> list[str]: + """Lines a reader sees: no HTML comments, no fenced code. + + With ``keep_html_comments`` the text inside HTML comments is kept (only + the markers go). That view finds reviews that something hides, so hiding + a review can withdraw an approval but never a blocker. + """ + text = unicodedata.normalize("NFKC", body).translate(_INVISIBLE) + text = text.replace("\r\n", "\n").replace("\r", "\n") + kept: list[str] = [] + cursor = 0 + while True: + start = text.find("", start + 4) + if keep_html_comments: + kept.append("\n") + if end < 0: + kept.append(text[start + 4 :]) + break + kept.append(text[start + 4 : end]) + kept.append("\n") + elif end < 0: + break # an unterminated comment hides the rest + cursor = end + 3 + lines: list[str] = [] + fence: str | None = None + for line in "".join(kept).split("\n"): + match = _FENCE.match(line) + if fence is not None: + if ( + match + and match.group(1)[0] == fence[0] + and len(match.group(1)) >= len(fence) + ): + fence = None + continue + if match: + fence = match.group(1) + continue + lines.append(line.rstrip()) + return lines + + +@dataclass(frozen=True) +class ReviewText: + from_names: tuple[str, ...] # first word of each From: line in the header + heads: tuple[str, ...] # every Reviewed-Head: value in the visible text + headings: tuple[str, ...] # every verdict heading in the visible text + heading_in_header: bool + + +def parse_review_text(body: Any) -> ReviewText: + lines = visible_lines(body if isinstance(body, str) else "") + header: list[str] = [] + heading_in_header = False + for line in lines: + if not line.strip(): + continue + if _HEADING.match(line): + heading_in_header = True + elif not (_FROM.match(line) or _HEAD.match(line)): + break + header.append(line) + from_names = [] + for line in header: + match = _FROM.match(line) + if match: + words = match.group(1).split() + from_names.append(words[0] if words else "") + heads = tuple(m.group(1) for m in map(_HEAD.match, lines) if m) + headings = tuple( + re.sub(r"[ \t]+#*$", "", m.group(1)) for m in map(_HEADING.match, lines) if m + ) + return ReviewText( + tuple(from_names), + heads, + headings, + heading_in_header, + ) + + +# --- collecting reviews --------------------------------------------------- + + +@dataclass(frozen=True) +class Review: + source: str + id: int + author: str + reviewer: str + head: str | None + verdict: str | None + created_at: str + url: str + problems: tuple[str, ...] = field(default=()) + + @property + def label(self) -> str: + kind = self.verdict or ("malformed review" if self.problems else "review") + return f"{self.reviewer} {kind} at {short(self.head)}" + + +def _text_review( + item: dict[str, Any], author: Author, source: str, created_at: str +) -> Review | None: + parsed = parse_review_text(item.get("body")) + allowed = {name.casefold(): name for name in author.reviewers} + named = [ + allowed[n.casefold()] for n in parsed.from_names if n.casefold() in allowed + ] + if not named or not parsed.heads: + return _misplaced_review(item, author, source, created_at) + problems: list[str] = [] + if len(parsed.from_names) != 1: + problems.append("more than one From: line") + head: str | None = None + if len(parsed.heads) != 1: + problems.append(f"{len(parsed.heads)} Reviewed-Head: lines") + elif FULL_SHA.fullmatch(parsed.heads[0]): + head = parsed.heads[0] + else: + problems.append("Reviewed-Head: is not a full 40-character SHA") + verdict: str | None = None + if not parsed.headings: + problems.append("no verdict heading") + elif len(parsed.headings) != 1 or not parsed.heading_in_header: + problems.append("verdict heading is ambiguous") + else: + value = " ".join(parsed.headings[0].split()).upper() + if value in VERDICTS: + verdict = value + else: + problems.append(f"unrecognized verdict {parsed.headings[0][:40]!r}") + return Review( + source=source, + id=int(item.get("id") or 0), + author=author.login, + reviewer=named[0], + head=head, + verdict=verdict if not problems else None, + created_at=created_at, + url=str(item.get("html_url") or ""), + problems=tuple(problems), + ) + + +_QUOTE = re.compile(r"^[ \t>*_]+") + + +def _misplaced_review( + item: dict[str, Any], author: Author, source: str, created_at: str +) -> Review | None: + """A Grok or Codex review whose header is hidden, quoted or not on top. + + It can't approve, but it counts as the newest review and as a possible + blocker, so a REQUEST CHANGES with a line of preamble still blocks. + """ + lines = [ + _QUOTE.sub("", line) + for line in visible_lines( + item.get("body") if isinstance(item.get("body"), str) else "", + keep_html_comments=True, + ) + ] + allowed = {name.casefold(): name for name in author.reviewers} + named = [] + for match in map(_FROM.match, lines): + words = match.group(1).split() if match else [] + if words and words[0].strip("*_").casefold() in allowed: + named.append(allowed[words[0].strip("*_").casefold()]) + heads = [m.group(1).strip("`*_") for m in map(_HEAD.match, lines) if m] + if not named or not heads: + return None # not a Grok or Codex review from this author + head = heads[0] if len(set(heads)) == 1 and FULL_SHA.fullmatch(heads[0]) else None + return Review( + source=source, + id=int(item.get("id") or 0), + author=author.login, + reviewer=named[0], + head=head, + verdict=None, + created_at=created_at, + url=str(item.get("html_url") or ""), + problems=("the review header is hidden, quoted or not at the top",), + ) + + +_NATIVE_STATES = {"APPROVED": APPROVE, "CHANGES_REQUESTED": REQUEST_CHANGES} + + +def _native_review( + item: dict[str, Any], author: Author, created_at: str +) -> Review | None: + """A GitHub review from a reviewer App identity: state + commit_id.""" + verdict = _NATIVE_STATES.get(str(item.get("state"))) + if verdict is None: + return None # COMMENTED and PENDING carry no verdict + head = item.get("commit_id") + problems: list[str] = [] + if not isinstance(head, str) or not FULL_SHA.fullmatch(head): + problems.append("review has no commit_id") + head = None + text = _text_review(item, author, "pull_request_review", created_at) + if text is not None and ( + text.problems or text.head != head or text.verdict != verdict + ): + problems.append("review body header disagrees with the review state") + return Review( + source="pull_request_review", + id=int(item.get("id") or 0), + author=author.login, + reviewer=author.reviewers[0], + head=head, + verdict=verdict if not problems else None, + created_at=created_at, + url=str(item.get("html_url") or ""), + problems=tuple(problems), + ) + + +def collect_reviews( + comments: list[dict[str, Any]], reviews: list[dict[str, Any]], config: Config +) -> list[Review]: + """Recognized reviews, oldest first.""" + found: list[Review] = [] + if "issue_comment" in config.sources: + for item in comments: + author = config.author((item.get("user") or {}).get("login")) + created = item.get("created_at") + if author is None or not isinstance(created, str): + continue + review = _text_review(item, author, "issue_comment", created) + if review is not None: + found.append(review) + if "pull_request_review" in config.sources: + for item in reviews: + author = config.author((item.get("user") or {}).get("login")) + created = item.get("submitted_at") + if author is None or not isinstance(created, str): + continue + if item.get("state") in {"DISMISSED", "PENDING"}: + continue + if author.native_reviews: + review = _native_review(item, author, created) + else: + review = _text_review(item, author, "pull_request_review", created) + if review is not None: + found.append(review) + return sorted(found, key=lambda r: (r.created_at, r.source, r.id)) + + +# --- the verdict ---------------------------------------------------------- + + +@dataclass(frozen=True) +class Outcome: + passed: bool + description: str + details: tuple[str, ...] = () + + @property + def state(self) -> str: + """The commit status state GitHub takes.""" + return "success" if self.passed else "failure" + + +def _fail(description: str, *details: str) -> Outcome: + return Outcome(False, description, details) + + +Currency = Callable[[str], tuple[str, str]] + + +@verdict_site("review_verdict.evaluate", classes="C1 C2 C3") +def evaluate( + *, + head: str, + files: list[dict[str, Any]], + files_complete: bool, + comments: list[dict[str, Any]], + reviews: list[dict[str, Any]], + config: Config, + patterns: list[str], + currency: Currency, +) -> Outcome: + """Decide the check for one pull request at ``head``. + + ``currency(reviewed_head)`` returns ``(SAME | EQUIVALENT | STALE | + UNKNOWN, reason)`` for that reviewed head against ``head``. + """ + protected = protected_matches(changed_paths(files), patterns) + if files_complete and not protected: + return Outcome(True, "no protected paths") + touched = ( + [f"protected: {p}" for p in protected[:20]] + if files_complete + else ["the file list is truncated, so every pull request counts as protected"] + ) + found = collect_reviews(comments, reviews, config) + if not found: + return _fail( + "protected paths changed and there is no Grok or Codex review", *touched + ) + newest = found[-1] + seen = [f"newest review: {newest.label} ({newest.url})", *touched] + if newest.problems: + return _fail( + f"newest {newest.reviewer} review is malformed: {newest.problems[0]}", + *newest.problems, + *seen, + ) + if newest.verdict != APPROVE: + return _fail(f"newest review is {newest.label}", *seen) + assert newest.head is not None + state, reason = currency(newest.head) + if state not in (SAME, EQUIVALENT): + return _fail( + f"newest {newest.reviewer} APPROVE is for {short(newest.head)}, " + f"not head {short(head)}", + reason, + *seen, + ) + for review in found: # blocker stands + # A malformed review (conditional approval, hidden header) blocks + # like REQUEST CHANGES: its reviewer hasn't approved. + if review.verdict not in BLOCKING and not review.problems: + continue + if review.head is not None and currency(review.head)[0] == STALE: + continue + cleared = any( + later.reviewer == review.reviewer + and later.verdict == APPROVE + and (later.created_at, later.source, later.id) + > (review.created_at, review.source, review.id) + and later.head is not None + and currency(later.head)[0] in (SAME, EQUIVALENT) + for later in found + ) + if not cleared: + return _fail( + f"{review.label} still stands; {review.reviewer} has not " + "approved this head", + review.url, + *seen, + ) + if state == SAME: + return Outcome(True, f"APPROVE from {newest.reviewer} at {short(head)}") + return Outcome( + "success", + f"APPROVE from {newest.reviewer} at {short(newest.head)}; " + f"only clean merges from main since", + (reason,), + ) + + +# --- git: merges from main and merge-queue chains ------------------------- + + +class Git: + """Read-only git queries against a checkout. Never checks out PR code.""" + + def __init__(self, repo: Path, main_ref: str = "refs/remotes/origin/main"): + self.repo = repo + self.main_ref = main_ref + + def run(self, *args: str) -> subprocess.CompletedProcess[str]: + env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"} + return subprocess.run( + ["git", "-c", "core.quotepath=false", *args], + cwd=self.repo, + env=env, + capture_output=True, + text=True, + check=False, + ) + + def out(self, *args: str) -> str: + result = self.run(*args) + if result.returncode != 0: + raise ReviewVerdictError( + f"git {' '.join(args[:2])} failed: {result.stderr.strip()[:200]}" + ) + return result.stdout + + def has_commit(self, sha: str) -> bool: + return self.run("cat-file", "-e", f"{sha}^{{commit}}").returncode == 0 + + def parents(self, sha: str) -> list[str]: + return self.out("rev-list", "--parents", "-n", "1", sha).split()[1:] + + def is_ancestor(self, ancestor: str, descendant: str) -> bool: + result = self.run("merge-base", "--is-ancestor", ancestor, descendant) + if result.returncode not in (0, 1): + raise ReviewVerdictError(f"git merge-base failed: {result.stderr.strip()}") + return result.returncode == 0 + + def tree(self, sha: str) -> str: + return self.out("rev-parse", f"{sha}^{{tree}}").strip() + + def clean_merge_tree(self, first: str, second: str) -> str | None: + """The tree of a conflict-free merge, or None when it conflicts.""" + result = self.run("merge-tree", "--write-tree", "--no-messages", first, second) + if result.returncode == 1: + return None + if result.returncode != 0: + raise ReviewVerdictError(f"git merge-tree failed: {result.stderr.strip()}") + return result.stdout.split()[0] + + def own_diff(self, sha: str) -> dict[str, tuple[str, ...]]: + """The PR's own change at ``sha``: changed lines per file, no context.""" + base = self.out("merge-base", self.main_ref, sha).strip() + text = self.out( + "diff", + "-U0", + "--no-renames", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--full-index", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + sha, + ) + return parse_own_diff(text) + + +def parse_own_diff(text: str) -> dict[str, tuple[str, ...]]: + files: dict[str, list[str]] = {} + current: list[str] | None = None + post_image = "" + for line in text.split("\n"): + if line.startswith("diff --git "): + rest = line[len("diff --git ") :] + if rest.startswith("a/") and len(rest) % 2 == 1: + half = (len(rest) - 1) // 2 + path = rest[2:half] # "a/

b/

" with the same

twice + else: + path = rest + current = files.setdefault(path, []) + post_image = "" + continue + if current is None or line.startswith(("+++ ", "--- ", "@@")): + continue + if line.startswith("index "): + post_image = line.split("..")[-1].split()[0] if ".." in line else "" + elif line.startswith("Binary files "): + current.append(f"binary {post_image}") + elif line.startswith( + ( + "+", + "-", + "\\", + "new file mode", + "deleted file mode", + "old mode", + "new mode", + ) + ): + current.append(line) + return {path: tuple(lines) for path, lines in files.items()} + + +def merge_currency(git: Git, reviewed: str, head: str) -> tuple[str, str]: + """Whether a review of ``reviewed`` still covers ``head`` (docstring rule).""" + if reviewed == head: + return SAME, "the review names the current head" + try: + if not git.has_commit(reviewed): + return STALE, f"{short(reviewed)} is not in the pull request's history" + cursor = head + for _ in range(MAX_MERGE_CHAIN): + if cursor == reviewed: + break + parents = git.parents(cursor) + if len(parents) != 2: + return STALE, f"{short(cursor)} is not a merge from main" + first, second = parents + if not git.is_ancestor(second, git.main_ref): + return ( + STALE, + f"merge {short(cursor)} brings in a commit that is not on main", + ) + merged = git.clean_merge_tree(first, second) + if merged is None: + return STALE, f"merge {short(cursor)} resolved conflicts" + if merged != git.tree(cursor): + return STALE, f"merge {short(cursor)} differs from a clean merge" + cursor = first + else: + return STALE, f"{short(reviewed)} is not reachable through merges from main" + if cursor != reviewed: + return STALE, f"{short(reviewed)} is not reachable through merges from main" + if git.own_diff(reviewed) != git.own_diff(head): + return STALE, "the pull request's own diff changed" + except ReviewVerdictError as error: + return UNKNOWN, str(error) + return EQUIVALENT, ( + f"{short(head)} is {short(reviewed)} plus clean merges from main; " + "the pull request's own diff is unchanged" + ) + + +def queued_heads(git: Git, base_sha: str, head_sha: str) -> list[str]: + """Pull request heads in a MERGE-method merge group, in queue order.""" + heads: list[str] = [] + cursor = head_sha + while cursor != base_sha: + if len(heads) >= MAX_QUEUE_ENTRIES: + raise ReviewVerdictError("merge group chain does not reach its base") + parents = git.parents(cursor) + if len(parents) != 2: + raise ReviewVerdictError( + f"merge group commit {short(cursor)} is not a merge commit" + ) + heads.append(parents[1]) + cursor = parents[0] + if not heads: + raise ReviewVerdictError("merge group contains no pull requests") + return list(reversed(heads)) + + +# --- GitHub --------------------------------------------------------------- + + +class GitHub: + def __init__( + self, token: str, repository: str, api_url: str = "https://api.github.com" + ): + self.token = token + self.base = f"{api_url}/repos/{repository}" + + def request(self, path: str, *, method: str = "GET", data: Any = None) -> Any: + body = None if data is None else json.dumps(data).encode() + request = urllib.request.Request( + self.base + path, + data=body, + method=method, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "review-verdict", + }, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + payload = response.read() + except urllib.error.HTTPError as error: + raise ReviewVerdictError( + f"GitHub {method} {path} returned {error.code}" + ) from error + return json.loads(payload) if payload else None + + def pages(self, path: str, limit: int = 30) -> list[dict[str, Any]]: + items: list[dict[str, Any]] = [] + separator = "&" if "?" in path else "?" + for page in range(1, limit + 1): + batch = self.request(f"{path}{separator}per_page=100&page={page}") + if not isinstance(batch, list): + raise ReviewVerdictError(f"GitHub {path} did not return a list") + items.extend(batch) + if len(batch) < 100: + return items + raise ReviewVerdictError(f"GitHub {path} has more than {limit} pages") + + +@dataclass +class Evidence: + number: int + pull: dict[str, Any] + files: list[dict[str, Any]] + files_complete: bool + comments: list[dict[str, Any]] + reviews: list[dict[str, Any]] + + @property + def head(self) -> str: + sha = (self.pull.get("head") or {}).get("sha") + if not isinstance(sha, str) or not FULL_SHA.fullmatch(sha): + raise ReviewVerdictError(f"#{self.number} has no head SHA") + return sha + + +def fetch_evidence(api: Any, number: int, config: Config) -> Evidence: + pull = api.request(f"/pulls/{number}") + if not isinstance(pull, dict): + raise ReviewVerdictError(f"#{number} is not a pull request") + files = api.pages(f"/pulls/{number}/files") + changed = pull.get("changed_files") + complete = isinstance(changed, int) and changed == len(files) and len(files) < 3000 + comments = api.pages(f"/issues/{number}/comments") + reviews = ( + api.pages(f"/pulls/{number}/reviews") + if "pull_request_review" in config.sources + else [] + ) + return Evidence(number, pull, files, complete, comments, reviews) + + +def pull_for_head(api: Any, sha: str) -> int: + pulls = api.request(f"/commits/{sha}/pulls") + matches = [ + p["number"] + for p in pulls or [] + if isinstance(p, dict) + and p.get("state") == "open" + and (p.get("base") or {}).get("ref") == "main" + and (p.get("head") or {}).get("sha") == sha + ] + if len(matches) != 1: + raise ReviewVerdictError( + f"queued head {short(sha)} maps to {len(matches)} open pull requests" + ) + return int(matches[0]) + + +# --- entry point ---------------------------------------------------------- + + +def pull_number( + event_name: str, event: dict[str, Any], dispatch: str | None +) -> int | None: + if event_name in ("pull_request", "pull_request_review"): + return int(event["pull_request"]["number"]) + if event_name == "issue_comment": + issue = event.get("issue") or {} + return int(issue["number"]) if issue.get("pull_request") else None + if event_name == "workflow_dispatch": + if not dispatch or not dispatch.isdigit(): + raise ReviewVerdictError("workflow_dispatch needs a pull_request number") + return int(dispatch) + raise ReviewVerdictError(f"unsupported event {event_name}") + + +def _git_currency( + git_factory: Callable[[list[str]], Git | None], refs: list[str], head: str +) -> Currency: + cache: dict[str, tuple[str, str]] = {} + holder: dict[str, Git | None] = {} + + def currency(reviewed: str) -> tuple[str, str]: + if reviewed == head: + return SAME, "the review names the current head" + if reviewed not in cache: + if "git" not in holder: + holder["git"] = git_factory(refs) + git = holder["git"] + cache[reviewed] = ( + merge_currency(git, reviewed, head) + if git is not None + else (UNKNOWN, "could not fetch the pull request's commits") + ) + return cache[reviewed] + + return currency + + +def judge( + evidence: Evidence, + head: str, + config: Config, + patterns: list[str], + currency: Currency, +) -> Outcome: + return evaluate( + head=head, + files=evidence.files, + files_complete=evidence.files_complete, + comments=evidence.comments, + reviews=evidence.reviews, + config=config, + patterns=patterns, + currency=currency, + ) + + +def run( + *, + event_name: str, + event: dict[str, Any], + api: Any, + git_factory: Callable[[list[str]], Git | None], + dispatch: str | None = None, + root: Path = ROOT, +) -> tuple[str | None, Outcome, list[str]]: + """Evaluate one event. Returns (status SHA, outcome, report lines).""" + config = load_config( + json.loads((root / ".github" / "review-verdict.json").read_text()) + ) + manifest = json.loads((root / config.manifest_path).read_text()) + patterns = protected_patterns(manifest) + report: list[str] = [] + + if event_name == "merge_group": + group = event["merge_group"] + base, group_head = group["base_sha"], group["head_sha"] + git = git_factory([group["head_ref"]]) + if git is None: + raise ReviewVerdictError("could not fetch the merge group commits") + failures: list[str] = [] + heads = queued_heads(git, base, group_head) + for queued in heads: + number = pull_for_head(api, queued) + evidence = fetch_evidence(api, number, config) + if evidence.head != queued: + outcome = _fail( + f"head moved to {short(evidence.head)} after it was queued" + ) + else: + currency = _git_currency(lambda _refs: git, [], queued) + outcome = judge(evidence, queued, config, patterns, currency) + report.append( + f"#{number} at {short(queued)}: {outcome.state}: {outcome.description}" + ) + report.extend(f" {line}" for line in outcome.details) + if not outcome.passed: + failures.append(f"#{number}: {outcome.description}") + if failures: + return group_head, _fail("; ".join(failures)), report + passed = f"all {len(heads)} queued pull request(s) pass" + return group_head, Outcome(True, passed), report + + number = pull_number(event_name, event, dispatch) + if number is None: + return None, Outcome(True, "not a pull request"), ["not a pull request"] + evidence = fetch_evidence(api, number, config) + if evidence.pull.get("state") != "open": + return ( + None, + Outcome(True, "pull request is closed"), + [f"#{number} is closed"], + ) + head = evidence.head + currency = _git_currency( + git_factory, + [f"+refs/pull/{number}/head:refs/review-verdict/pull/{number}"], + head, + ) + outcome = judge(evidence, head, config, patterns, currency) + report.append(f"#{number} at {short(head)}: {outcome.state}: {outcome.description}") + report.extend(f" {line}" for line in outcome.details) + return head, outcome, report + + +def publish( + api: Any, sha: str, outcome: Outcome, context: str, target_url: str | None +) -> None: + description = outcome.description + if len(description) > DESCRIPTION_LIMIT: + description = description[: DESCRIPTION_LIMIT - 1] + "…" + payload: dict[str, Any] = { + "state": outcome.state, + "context": context, + "description": description, + } + if target_url: + payload["target_url"] = target_url + api.request(f"/statuses/{sha}", method="POST", data=payload) + + +def checkout_git(repo: Path) -> Callable[[list[str]], Git | None]: + """Fetch the given refs into the trusted checkout, as objects only.""" + + def factory(refs: list[str]) -> Git | None: + git = Git(repo) + fetch = [ + "fetch", + "--no-tags", + "--quiet", + "origin", + "+refs/heads/main:refs/remotes/origin/main", + *refs, + ] + result = git.run(*fetch) + if result.returncode != 0: + print(f"::warning::git fetch failed: {result.stderr.strip()[:300]}") + return None + return git + + return factory + + +def main() -> int: + event_name = os.environ["GITHUB_EVENT_NAME"] + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) + repository = os.environ["GITHUB_REPOSITORY"] + api = GitHub( + os.environ["GITHUB_TOKEN"], + repository, + os.environ.get("GITHUB_API_URL", "https://api.github.com"), + ) + target_url = None + if os.environ.get("GITHUB_RUN_ID"): + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com") + target_url = f"{server}/{repository}/actions/runs/{os.environ['GITHUB_RUN_ID']}" + config = load_config(json.loads(CONFIG_PATH.read_text())) + status_sha: str | None = None + try: + status_sha, outcome, report = run( + event_name=event_name, + event=event, + api=api, + git_factory=checkout_git(ROOT), + dispatch=os.environ.get("DISPATCH_PULL_REQUEST"), + ) + except (ReviewVerdictError, KeyError, ValueError, TypeError) as error: + status_sha = _fallback_sha(event_name, event) + outcome = _fail(f"review-verdict could not decide: {error}") + report = [outcome.description] + for line in report: + print(line) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write("### review-verdict\n\n```\n" + "\n".join(report) + "\n```\n") + if status_sha is None: + return 0 if outcome.passed else 1 + try: + publish(api, status_sha, outcome, config.status_context, target_url) + except ReviewVerdictError as error: + print(f"::error::could not publish the {config.status_context} status: {error}") + return 1 + print(f"published {config.status_context}={outcome.state} on {status_sha}") + if event_name in ("pull_request", "merge_group") and not outcome.passed: + return 1 + return 0 + + +def _fallback_sha(event_name: str, event: dict[str, Any]) -> str | None: + """Where to put an error status when evaluation itself failed.""" + if event_name == "merge_group": + return (event.get("merge_group") or {}).get("head_sha") + pull = event.get("pull_request") + if isinstance(pull, dict): + return (pull.get("head") or {}).get("sha") + return None + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/fixtures/review_verdict/real_comments.json b/tests/fixtures/review_verdict/real_comments.json new file mode 100644 index 0000000000..5365b87ccb --- /dev/null +++ b/tests/fixtures/review_verdict/real_comments.json @@ -0,0 +1,120 @@ +{ + "2756": [ + { + "id": 7249235811, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2756#issuecomment-7249235811", + "created_at": "2026-11-29T02:08:31Z", + "updated_at": "2026-11-29T02:08:31Z", + "body": "## Independent adversarial review: REQUEST CHANGES\nFrom: Grok\nReviewed-Head: 37a44504062797de54814efe4f83f482cd7a94c1\n\nThis re-review covers the push since my review at `a009ddd9`. The new commit fixes item 1 of that review. Items 2 and 3 are unchanged, because `resolver.py` is byte-identical between the two heads. CI is red on a different gate, and one new fail-open came up in the relative postconditions.\n\n### Status of the previous findings\n1. **Fixed.** The three `mypy` errors are gone (`mypy` on `identity.py`, `identity_template.py`, `compile.py`, `semantic_gates.py`, `replayer.py` and `replay/confirming.py` reports no issues). The file-size ratchet passes because the helpers moved to `runtime/semantic_gates.py`. I checked that move against the removed code and found it behavior-preserving, with two harmless differences: the three drift messages now use `;` where they used `—`, and `_step_live_affine` is now cleared to `None` on the drift-error paths.\n2. **Not fixed.** Rung 3d still runs the constellation grounder ahead of landmark geometry, and it still returns the wrong row. I re-ran the table probe through `resolve()` with an icon-only row action, so the duplicate-text ambiguity rung does not fire first. The probe has three rows ` Active `, with the target on Ada's row. Names and dates are dropped from the constellation, as the compiler does.\n - Ada on row 1, as recorded: `rung=grounder`, point `(735, 100)`, confidence 1.0. Correct.\n - Ada moved to row 2 (expected y=150): `rung=grounder`, `(735, 100)`, confidence 1.0. Wrong row.\n - Ada absent (expected abstain): `rung=grounder`, `(735, 100)`, confidence 0.93 at this head and 1.0 when merged with current `main` (with #2755). Wrong row.\n\n After the PHI tokens are removed, the constellation holds only `Action`, `Active` and `Status` (plus `Name` and `DOB` with #2755). Every row matches it equally, so this rung cannot tell rows apart. A reversible step without identity evidence gets a confident click on the wrong row. Either gate Rung 3d to steps whose identity check runs at the resolved point, or make the grounder abstain when its winning tokens repeat on several rows. Please add resolver-level tests for a moved row and a missing row. The PR still has no such test.\n3. **Not fixed.** The Rung 3d comment still says \"on pixel surfaces only\", but the guard is still `structural is None and grounder is not None`.\n\n### New: the region_stable OCR fallback accepts a changed value\n`Confirming._semantic_region_match` runs after the pHash check fails whenever a semantic grounder is configured. It passes when the recorded text appears as a long common block in the live OCR of a padded box around the region. Polarity words and digits are checked as substrings only. I called it directly with fake OCR on the recorded crop and the live region:\n\n| recorded | live | returns |\n|---|---|---|\n| `Approved` | `Unapproved` | True |\n| `Complete` | `Incomplete` | True |\n| `Saved` | `Not saved` | True |\n| `Qty 10` | `Qty 100` | True |\n| `Status: Active` | `Status: Inactive` | False |\n| `Balance 25.00` | `Balance 125.00` | False |\n\nA `region_stable` postcondition should fail when the content in the region changes, and this fallback passes on a negated state or a changed number. The fix should cover the whole class, not add words to the polarity list. Compare whole tokens, in order, against the lines inside the mapped region, and require the token sequences to match apart from OCR glyph confusions. Include tests for negation prefixes, added negation words and digit insertions.\n\n### CI is red: the verdict-folds gate fails when merged with current main\n`flow core unit (shard 2/4)`, `flow default at rest (shard 2/4)` and `smoke` all fail on `check_verdict_folds.py` with `swallow: 915 (baseline 914)`. I reproduced this locally. The check passes on `main` (`d2b414a8`) and on the PR head alone, and fails on the merge of the two. A per-file diff between `main` and the merge shows the folds this PR adds: `replay/confirming.py` swallow 2→5 (plus swallow_wide 5→6), from the new `except Exception:` blocks in `exact_ocr_value`, `_scaled_region_match` and `_semantic_region_match`, and `constellation_grounder.py` swallow 2→3, from `load_bundle_constellations`. Main's remaining slack covers three of these four. Build these on `verdict.settle` in a `@verdict_site`, or have them return an explicit not-checked value, as `docs/FAIL_CLOSED.md` describes.\n\n### Tests (exact head, Linux, py3.12)\nI ran 20 files: `test_whole_run_semantic_gates`, `test_constellation_grounder`, `test_resolver`, `test_resolver_ambiguity`, `test_resolver_global_landmark_guard`, `test_identity`, `test_identity_template`, `test_identity_row_rung`, `test_render_scale`, `test_local_grounder`, `test_ocr_anchor_grounder`, `test_identity_ladder`, `test_pixel_identity_aligned`, `test_identity_census`, `test_layout_drift`, `test_layout_drift_replay`, `test_page_scale_postcondition`, `test_postcondition_fuzz`, `test_focus_on_postcondition` and `test_verdict_folds_check`.\n- PR head: 406 passed, 3 skipped.\n- Merged with current `main`: 410 passed, 3 skipped, 1 failed (`test_verdict_folds_check::test_main_is_within_the_baseline`, the CI failure above).\n- `ruff check`, `ruff format --check`, `mypy`, `check_file_size_ratchet.py` and `check_engine_generality.py` pass.\n- The probes are temporary local scripts that use fake OCR and blank frames. No real input was involved. I did not reproduce the 39-run sweep or run any live replay.\n\n**Generality gate:** point 1 (no hardcoded app or benchmark) passes. Point 2 (fix the whole class) fails twice: Rung 3d has no row-identity guard, and the OCR region fallback checks values by substring.\n\n**CI at this head:** `smoke`, `flow core unit (shard 2/4)` and `flow default at rest (shard 2/4)` fail on the verdict-folds check, and the `ci`, `run-ci` and `packages-gate` roll-ups fail as a result. `windows replay (Patient Notes, WindowsBackend)` fails in `test_native_keyboard_lease.py`, which also fails on every other PR branch today. Auto-merge is enabled on this PR while this review requests changes.\n\nI did not push to this branch.\n", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7259994196, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2756#issuecomment-7259994196", + "created_at": "2026-11-29T17:49:38Z", + "updated_at": "2026-11-29T17:49:38Z", + "body": "## Independent adversarial review: REQUEST CHANGES\n\nFrom: Grok\nReviewed-Head: a56440d6059ec9b89c1d162e3809acbcec4547fe\n\nThe only change since my review at `bb6793b4` is a56440d6, a merge from main. I diffed the PR's own diff against its merge-base, before and after. The 13 files are the same, and no added or removed line differs; only the surrounding context changed, which is why the patch-id changed. The blockers from my earlier review are unaddressed.\n\nThe previous REQUEST CHANGES verdict at `bb6793b4` still applies.\n\nCI at this head: `windows replay (Patient Notes, WindowsBackend)` fails, as it does on every open flow PR today. Other checks were still running when I posted. Auto-merge is on, so **it should be turned off** until the blockers are fixed.\n", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7263432014, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2756#issuecomment-7263432014", + "created_at": "2026-11-29T22:08:12Z", + "updated_at": "2026-11-29T22:08:12Z", + "body": "## Independent adversarial review: APPROVE\nFrom: Grok\nReviewed-Head: 009f73ddc4665b2851c534aaa785f9a039c8a891\n\nThis re-review covers 009f73dd, the only commit since `c2d77e2a`. It changes `constellation_grounder.py`, `identity.py`, `identity_template.py`, `replay/confirming.py`, `semantic_gates.py` and two test files. All four blockers from my review at `bb6793b4` are fixed. I re-ran the original probes at this head.\n\n### 1. Rung 3d wrong row: fixed\n`disambiguate_candidates` now calls `_row_identity_supported`. On a repeating row (`row_band_mode`, or live sibling rows with the same column structure), every own-row token that isn't constant must be read in its column on the candidate's row. Constant tokens are those in `row_constant_tokens`, or those seen on a live sibling. With no identity token left, the candidate is refused.\n\n| case (icon-only Delete, names and DOBs dropped as the compiler does) | `c2d77e2a` | this head |\n|---|---|---|\n| Ada on row 1, as recorded | grounder (735, 100) | abstains |\n| Ada moved to row 2 | **(735, 100), wrong row** | abstains |\n| Ada absent | **(735, 100)** | abstains |\n| only one other patient's row shown | n/a | abstains |\n\nWith the row identity kept in the constellation, Ada on row 1 grounds correctly at 1.0. Ada moved, Ada absent, a different single row, and Ada with a one-day-off DOB all abstain. The PR adds resolver-level tests for moved and missing rows.\n\n### 2. `region_stable` OCR fallback: fixed\nEach recorded line must now appear as a contiguous run of whole, exactly equal tokens, with no negation word before it that the recording lacked. `Approved`→`Unapproved`, `Complete`→`Incomplete`, `Status: Active`→`Status: Inactive`, `Qty 10`→`Qty 100`, `Balance 25.00`→`Balance 125.00` and `Saved`→`Not saved` all give `holds: False`. An unchanged `Status: Active` still holds.\n\n### 3. Masked read-back inferred from wording: fixed\n`is_masked_type_step` now accepts only `step.secret`, a param listed in `workflow.secret_params`, or a structural locator (role or `[type=password]` selector) on the TYPE step or the click before it. A recovery email after \"Forgot password?\", a \"Password hint\" field, a `pin_code` param and a username field next to \"Password\" all give `allow_masked=False`. So `old@example.com`→`nex@example.com` and `Smith`→`Smyth` are no longer accepted as landed.\n\n### 4. Clipped placeholder rule from `bb6793b4`: reverted\n`_CLIPPABLE_LABEL_SUFFIXES` and the fragment path are removed from both `identity.py` and `identity_template.py`. All eight of my clipped-name cases are now `mismatch` in plain and hashed mode, including `Nam`→`Na`, `Nam`→`Ne`, `Dae`→`Da` and `Su`→`Sui`.\n\n### Non-blocking\n- **Lost coverage:** icon-only row actions whose identity cells are dropped as PHI now always abstain at Rung 3d, even when the row is correct. That fails closed. Later rungs or the VLM must ground them.\n- **Single live row:** when the recorded target crop is blank, `row_band_mode` is never set. If the live table then shows only one row, with no siblings, `_row_identity_supported` returns `True` without checking identity. In my probe the grounder then picked another patient's single row at 1.0. The pre-click identity check (`verify_target_identity` gives `mismatch` on that band) still blocks the click. Clicks on blank row targets are uncommon, so I'm not blocking on this. Consider also requiring row identity when the recording itself had sibling rows.\n\n### Tests at this head (Linux, Python 3.12)\n- `test_whole_run_semantic_gates`, `test_constellation_grounder`, `test_resolver*`, `test_identity*`, `test_render_scale`, `test_local_grounder`, `test_ocr_anchor_grounder`, `test_pixel_identity_aligned`, `test_layout_drift*`, `test_page_scale_postcondition`, `test_postcondition_fuzz`, `test_focus_on_postcondition`, `test_verdict_folds_check` and `test_living_program`: **1647 passed, 3 skipped**.\n- `ruff check` and `ruff format --check` (948 files): clean. `mypy` on the five changed engine modules: no issues. `check_verdict_folds.py`: OK.\n- Probes: my earlier `clipped_names`, `rung3d_icon`, `rung3d_rows`, `semantic_region`, `masked_type` and `masked_landed` scripts, plus new Rung 3d variants with drawn icon targets, kept row identity and single-row live tables. They use fake OCR and synthetic names, and ran as temporary local scripts.\n\n**Generality gate:** pass on both points. The new guards key on table geometry, token equality, structural locator roles and selectors, and declared secret params. None of them use app strings. All four classes are closed, and the remaining edge case is in the notes above. `check_engine_generality.py` reports \"Engine generality OK (7 baseline hits left)\".\n\n**CI at this head:** 28 pass, 22 skipped, 1 failed: `windows replay (Patient Notes, WindowsBackend)`. That job isn't a required check and fails on other open flow PRs today. All Flow core unit and default-at-rest shards pass. GitHub reports the PR as MERGEABLE.\n\n**Not run:** live replay, and the Windows and remote-display runs.\n\nI didn't push to this branch, and I won't merge it.\n", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7264233184, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2756#issuecomment-7264233184", + "created_at": "2026-11-29T23:08:51Z", + "updated_at": "2026-11-29T23:08:51Z", + "body": "## Independent adversarial review: REQUEST CHANGES\n\nFrom: Grok\n\nReviewed-Head: ab11b31ecbbe3c3a9d87f3b6e031a6d31ae1fd63\n\n**Delta since 009f73dd (which I approved):** one commit, `fix(flow): refuse region_stable OCR match on number continuation or nearby negation/failure`. It changes `runtime/replay/confirming.py` (+76 −12) and `tests/test_whole_run_semantic_gates.py`. It isn't a rebase. `_semantic_region_match` now:\n- tokenizes numbers whole, keeping sign, currency and separators;\n- matches each recorded line within a single live OCR line, instead of across the joined text of all lines;\n- refuses on a number continuing either side of the match;\n- refuses on a negation or failure word within 3 tokens on either side.\n\n### Blocker (a regression introduced by this delta): a negation on a separate OCR line no longer refuses\nAt 009f73dd, the live lines were joined before matching, so the token just before the match was checked for negation even when OCR had split it onto its own line. Now each live line is matched alone, so the context from neighbouring lines is lost. The same probe gives different results at each head:\n\n| recorded | live OCR lines | 009f73dd | ab11b31e |\n|---|---|---|---|\n| `Saved` | `Not` / `Saved` | False (refused) | **True (stable)** |\n\nA status cell that wraps (`Not` / `saved`) or a negation chip next to the label is exactly where OCR splits lines. A True here lets `region_stable` pass on a flipped status with no pixel match. The fix is small: include the last `_REGION_WINDOW` tokens of the adjacent preceding and following live lines (by vertical order) in `before` and `after`. Please also add the two-line case to the negative table.\n\n### Delta findings: the fixes work\nThese cases now refuse correctly: `Qty 10.5`, `Qty -10`, `Total ,000`, `Qty 10 000`, `Saved failed`, `Approved: No`, `Not yet complete`, and `Saved. No errors` (stricter, which fails safe). These still hold: `Qty 10.5`, `Total: $1,000`, `Qty -10`, `Draft saved.`, `Approved by Ada` and `Qty 10 items`.\n\nNot new, and not blocking, but worth adding to the vocabulary or the number rule while you're here. These all still return True: `Total - 10` and `Total − 10` (a sign separated from the number by a space), `Saved unsuccessfully`, `Approved revoked`, `Approved = false`, `Qty 10%`, and `Saved` / `Failed` on the next line. The adjacent-line context above would cover the last one. A recorded line split across two live lines (`Status` / `Approved`) now refuses, which fails safe.\n\n### Tests at this head (Linux, Python 3.12)\n- `tests/test_whole_run_semantic_gates.py`: 27 passed. `ruff check` on the module and test: clean.\n- `tests/test_drift_oracle.py`, `tests/test_replayer.py`, `tests/test_postcondition_fuzz.py`, `tests/test_whole_run_semantic_gates.py`, `tests/test_page_scale_postcondition.py`, `tests/e2e/test_region_stable_theme_regression.py` and `tests/e2e/test_cosmetic_drift.py`: 238 passed, 5 failed. The 5 failures are `TestScaleDriftSafeHalts::test_scale_drift_halts_at_step_000_without_saving[kwargs0,1,2,7,8]`. The same 5 fail at 009f73dd on this box, so they aren't caused by this delta.\n- Probes: 19 recorded/live pairs through `Replayer._semantic_region_match` with a fake OCR, run at both heads. They ran as a temporary local test, which I deleted afterwards.\n\n**Generality gate:** point 1 passes. There are no app strings, and `check_engine_generality.py` reports \"Engine generality OK (7 baseline hits left)\". Point 2 (fix the whole class) fails, because of the cross-line negation regression above.\n\n**CI at this head (when I posted):** GitHub reports no check runs yet for ab11b31e, and mergeability is UNKNOWN.\n\n**Not run:** real OCR engines, and live replay.\n\nI didn't push to this branch, and I won't merge it.\n", + "user": { + "login": "abrichr", + "type": "User" + } + } + ], + "2769": [ + { + "id": 7264023413, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2769#issuecomment-7264023413", + "created_at": "2026-11-29T22:52:59Z", + "updated_at": "2026-11-29T22:52:59Z", + "body": "## Independent adversarial review: REQUEST CHANGES\n\nFrom: Grok\n\nReviewed-Head: 53549f357c4af8f6d16a1e1b0b06ccd31f65c5a9\n\n**Delta since ade25b63:** one commit, `fix(flow): pixel commit observer requires a newly introduced, non-chrome confirmation`. It changes `runtime/worklist_copilot.py` (+71 −9) and `tests/test_worklist_copilot.py`. It isn't a rebase. A confirmation or skip phrase now has to occur more often on the current frame than in the draft frame's own OCR. Words inside a fixed list of chrome phrases (\"signed in\", \"last signed\", \"submitted for review\", ...) never count.\n\n### Prior blocker: confirmation text already on the draft frame\n- **Fixed:** text that was already on screen plus an unrelated change. A draft frame that already shows \"Prior note: signed by Dr A\", plus a \"Loading...\" change, now stays WAITING. \"Signed in as Dr A\" and \"Last signed ... by Dr B\" chrome stays WAITING too. The new tests cover both.\n- **Still open: a pre-commit prompt phrased as a question or in the future tense.** This was part of the same blocker, which asked for a test for it, and none was added. On a clean draft frame, a newly appearing prompt still returns **COMMITTED** when nobody has signed:\n - \"Are you sure this should be signed? Confirm\"\n - \"This note will be signed. Continue?\"\n - \"Note to be signed by attending\"\n\n These are exactly the dialogs that appear *between* pressing Sign and the actual commit. After a false COMMITTED, the runner goes on to read-back and can mint a `VERIFIED_COMMITTED` receipt for an item no one confirmed.\n\n### Other false commits found in the same probe run\nThese aren't new in this delta, but they show the count comparison doesn't close the whole class:\n- A newly appearing tooltip, \"Help: once signed the note is locked\".\n- A toast about a different record, \"Note for patient Q signed\".\n- A second history row scrolling into view, \"Older note: signed by Dr C\".\n- Chrome outside the fixed list, \"Signed off by Dr A\".\n- An OCR miss of an existing history line on the draft read that is then read on the current frame.\n\nAll of these return COMMITTED, because counting is still frame-wide. Real commits (\"Record signed\" alone, or next to existing history) correctly return COMMITTED.\n\n### Suggested fix\n- Treat future, modal and question context as non-affirming. That covers \"will be\", \"to be\", \"should be\", \"be signed?\", and any phrase in a sentence ending in \"?\".\n- Scope the phrase count to the changed region (`diff_popup_region`) rather than the whole frame, so toasts and tooltips elsewhere and scrolled history don't count.\n- Add tests for the three prompts above.\n\n### Tests at this head (Linux, Python 3.12)\n- `tests/test_worklist_copilot.py`: **55 passed**. `ruff check` on the module and tests: clean.\n- Probes: 10 pixel-observer cases, using frames rendered from the test helper with a fake OCR word list and synthetic text. They ran as a temporary local test, which I deleted afterwards.\n\n**Generality gate:** point 1 passes. There are no app strings, and `check_engine_generality.py` reports \"Engine generality OK (7 baseline hits left)\". Point 2 (fix the whole class) still fails for the pixel observer, as described above.\n\n**CI at this head (when I posted):** GitHub reports no check runs yet for 53549f35, and mergeability is UNKNOWN.\n\n**Not run:** a live Canvas or RDP surface, and real OCR on the observer path.\n\nI didn't push to this branch, and I won't merge it.\n", + "user": { + "login": "abrichr", + "type": "User" + } + } + ], + "2411": [ + { + "id": 7068798258, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2411#issuecomment-7068798258", + "created_at": "2026-11-21T20:30:11Z", + "updated_at": "2026-11-21T20:30:11Z", + "body": "From: Gemini\nReviewed-Head: 9eb34524eceeba16e7ccd6c1ac9e7fc27774ac6e\n\nCI-only fix: added `allow_abbrev=False` to all 5 `hooks` child parsers in `packages/flow/openadapt_flow/hooks/cli.py` so `test_cli_no_abbreviations.py` passes (8 passed, ruff check/format green).", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7068830339, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2411#issuecomment-7068830339", + "created_at": "2026-11-21T20:32:48Z", + "updated_at": "2026-11-21T20:32:48Z", + "body": "## Independent adversarial review: APPROVE\n\nFrom: Codex\nReviewed-Head: 9eb34524eceeba16e7ccd6c1ac9e7fc27774ac6e\n\nAll five hooks subcommands now require full option names. I exercised the registered parser for `install`, `status`, `uninstall`, `approve` and `run`. Each accepted the documented option, selected the existing handler and rejected a shortened option with exit 2 before dispatch. This is the entire change since the [previous approval](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411#issuecomment-7068624565). Both task registries, the public verification key registry, the eight report/receipt pairs and their validator have identical Git blobs at both heads.\n\nThe current #2394 tip `af70c507` and this head merge cleanly in a dry Git merge. #2411 remains a draft. Hosted CI failed at the draft check and skipped package tests. The author separately reports eight local CLI tests passed. [Hosted draft check](https://github.com/OpenAdaptAI/OpenAdapt/actions/runs/44946475212/job/136974806119)\n", + "user": { + "login": "abrichr", + "type": "User" + } + } + ], + "2440": [ + { + "id": 7087695677, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2440#issuecomment-7087695677", + "created_at": "2026-11-22T23:36:12Z", + "updated_at": "2026-11-22T23:36:12Z", + "body": "From: Claude\nReviewed-Head: cdd78029f996d4777740c4496fa7c01f7317b558", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7087695925, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2440#issuecomment-7087695925", + "created_at": "2026-11-22T23:36:13Z", + "updated_at": "2026-11-22T23:36:13Z", + "body": "## Independent adversarial review: APPROVE\nFrom: Claude\nReviewed-Head: cdd78029f996d4777740c4496fa7c01f7317b558\n\nDelta check of the merge of claude/form-tx-weekend 0c61aaf8 and its follow-ups: OK. Conflicts in _page_quiescence.py and playwright_surface.py were resolved keeping both sides (top-window paint check with main's stall fallback; frame-scoped request ownership). Follow-up: the root-frame settle reads main's new {ticks, stalled} probe shape (it raised KeyError: 0).\n\nLocal single-process runs (load under 15) passed on this head.\n", + "user": { + "login": "abrichr", + "type": "User" + } + }, + { + "id": 7092979389, + "html_url": "https://github.com/OpenAdaptAI/OpenAdapt/pull/2440#issuecomment-7092979389", + "created_at": "2026-11-23T06:04:17Z", + "updated_at": "2026-11-23T06:04:17Z", + "body": "## Independent adversarial review: APPROVE\n\nFrom: Claude\nReviewed-Head: b2e252988eefe48b1551e029c39a34bc7d18fbd1\n\nThis head is b2e252988, a further merge of ef4f5cc88 on top of d7e485093. Delta since cdd78029f: two merges of claude/form-tx-weekend, with no new commits of this branch's own.\n\nConflicts:\n- In d7e485093 (`playwright_surface.py`), this branch's `_DOM_HELPERS_JS` substitutions and the `_CLIENT_ABORT_MARKERS`/`_is_client_abort` block are both kept.\n- In b2e252988, the CAPABILITIES row moves to `capabilities/04-.../0115-...md`, following #2518, and keeps this branch's iframe and shadow-root wording.\n\nSince the last approval, this head carries the #2429 engine commits (the 2xx save answer, the ledger check before signing, a signer refusal as a stop, and keying by sequence, popup and screen). Every `_actuate_control` call site in this head passes `session` and `in_popup_subroutine`, there is one signing site, and it is guarded by `_unrecorded_actuations` and the `ValueError` stop. I checked the call sites statically.\n\nOwn changes preserved: `git diff ef4f5cc88 b2e252988 --stat` gives 9 files, +1336/-225. The file set and line changes are the same as before, except that the CAPABILITIES.md row now lives in the row file and one blank line differs.\n\nTests: none were reported for this head, and I did not run any.\n", + "user": { + "login": "abrichr", + "type": "User" + } + } + ] +} \ No newline at end of file diff --git a/tests/test_protected_safety_review.py b/tests/test_protected_safety_review.py index 893d162c38..5d34f7e860 100644 --- a/tests/test_protected_safety_review.py +++ b/tests/test_protected_safety_review.py @@ -94,12 +94,14 @@ def _evaluate( def test_manifest_covers_six_required_areas_and_gate_self() -> None: validated = validate_manifest(_manifest()) - assert len(validated["areas"]) == 6 + assert len(validated["areas"]) >= 6 def test_missing_manifest_area_fails_closed() -> None: manifest = _manifest() - manifest["areas"].pop() + manifest["areas"] = [ + area for area in manifest["areas"] if area["id"] != "safety-gate-itself" + ] with pytest.raises(EvidenceError): validate_manifest(manifest) diff --git a/tests/test_review_verdict.py b/tests/test_review_verdict.py new file mode 100644 index 0000000000..8ee94d03bc --- /dev/null +++ b/tests/test_review_verdict.py @@ -0,0 +1,865 @@ +"""Tests for the required ``review-verdict`` check (scripts/ci/review_verdict.py). + +The comment bodies in ``fixtures/review_verdict/real_comments.json`` are real +Grok, Codex, Claude and Gemini comments copied from #2756, #2769, #2411 and +#2440. The merge-from-main and merge-queue tests build real git repositories. +""" + +from __future__ import annotations + +import json +import re +import subprocess +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from scripts.ci import review_verdict as rv + +FIXTURES = json.loads( + ( + Path(__file__).parent / "fixtures" / "review_verdict" / "real_comments.json" + ).read_text(encoding="utf-8") +) +CONFIG = rv.load_config(json.loads(rv.CONFIG_PATH.read_text(encoding="utf-8"))) +PATTERNS = rv.protected_patterns( + json.loads((rv.ROOT / CONFIG.manifest_path).read_text(encoding="utf-8")) +) +PROTECTED = [{"filename": "packages/flow/openadapt_flow/runtime/replay/confirming.py"}] +UNPROTECTED = [{"filename": "README.md"}] + +# Heads named by the real comments. +H2756_RC1 = "37a44504062797de54814efe4f83f482cd7a94c1" +H2756_MERGE = "a56440d6059ec9b89c1d162e3809acbcec4547fe" +H2756_APPROVED = "009f73ddc4665b2851c534aaa785f9a039c8a891" +H2756_RC_AFTER = "ab11b31ecbbe3c3a9d87f3b6e031a6d31ae1fd63" +H2769 = "53549f357c4af8f6d16a1e1b0b06ccd31f65c5a9" +H2411 = "9eb34524eceeba16e7ccd6c1ac9e7fc27774ac6e" +OTHER = "f" * 40 + + +def real(pr: int, head: str | None = None, first_line: str | None = None) -> list[dict]: + items = FIXTURES[str(pr)] + if head is not None: + items = [c for c in items if f"Reviewed-Head: {head}" in c["body"]] + if first_line is not None: + items = [c for c in items if c["body"].startswith(first_line)] + assert items, (pr, head, first_line) + return items + + +def comment(body: str, *, at: str, login: str = "abrichr", cid: int = 1) -> dict: + return { + "id": cid, + "html_url": f"https://example.invalid/{cid}", + "created_at": at, + "user": {"login": login}, + "body": body, + } + + +def header(verdict: str, reviewer: str, head: str) -> str: + return ( + f"## Independent adversarial review: {verdict}\n" + f"From: {reviewer}\nReviewed-Head: {head}\n\nBody text." + ) + + +def only_same(head: str): + def currency(reviewed: str) -> tuple[str, str]: + if reviewed == head: + return rv.SAME, "same" + return rv.STALE, "not the current head" + + return currency + + +def verdict( + head: str, + comments: list[dict], + *, + files: list[dict] = PROTECTED, + reviews: list[dict] | None = None, + currency=None, + config: rv.Config = CONFIG, + files_complete: bool = True, +) -> rv.Outcome: + return rv.evaluate( + head=head, + files=files, + files_complete=files_complete, + comments=comments, + reviews=reviews or [], + config=config, + patterns=PATTERNS, + currency=currency or only_same(head), + ) + + +# --- protected paths ------------------------------------------------------- + + +def test_unprotected_pull_request_passes_without_a_review() -> None: + outcome = verdict(OTHER, [], files=UNPROTECTED) + assert outcome.passed + assert outcome.description == "no protected paths" + + +def test_truncated_file_list_counts_as_protected() -> None: + outcome = verdict(OTHER, [], files=UNPROTECTED, files_complete=False) + assert not outcome.passed + + +@pytest.mark.parametrize( + "path", + [ + "openadapt/wrap_sdk.py", + "openadapt/simplex_transducer.py", + "openadapt/transducer_macros.py", + "packages/kernel/src/openadapt_kernel/policy.py", + ".github/workflows/ci.yml", + ".github/actions/apt-install/action.yml", + ".github/review-verdict.json", + "scripts/ci/review_verdict.py", + "packages/flow/openadapt_flow/verifier.py", + "packages/flow/openadapt_flow/runtime/replay/confirming.py", + "packages/flow/openadapt_flow/runtime/worklist_copilot.py", + "packages/flow/openadapt_flow/receipt_log.py", + "packages/flow/openadapt_flow/seal_keys.py", + ], +) +def test_protected_paths_come_from_the_manifest(path: str) -> None: + assert rv.protected_matches([path], PATTERNS) == [path] + + +def test_unlisted_paths_are_not_protected() -> None: + paths = ["README.md", "packages/flow/openadapt_flow/cli.py", "openadapt/cli.py"] + assert rv.protected_matches(paths, PATTERNS) == [] + + +def test_renaming_a_protected_file_away_counts() -> None: + files = [{"filename": "attic/old.py", "previous_filename": "openadapt/wrap_sdk.py"}] + assert not verdict(OTHER, [], files=files).passed + + +def test_every_area_of_the_old_gate_is_still_present() -> None: + manifest = json.loads((rv.ROOT / CONFIG.manifest_path).read_text()) + ids = {area["id"] for area in manifest["areas"]} + assert { + "verification-authority", + "receipts-and-signing", + "safety-gate-itself", + "wrap-and-transducer", + "governed-kernel", + "runtime-replay-and-confirmation", + "ci-workflows", + } <= ids + + +# --- real comments ----------------------------------------------------------- + + +def test_no_review_fails() -> None: + outcome = verdict(OTHER, []) + assert not outcome.passed + assert "no Grok or Codex review" in outcome.description + + +def test_real_request_changes_at_the_exact_head_fails() -> None: + # #2769 merged over this. + outcome = verdict(H2769, real(2769, H2769)) + assert not outcome.passed + assert ( + outcome.description == f"newest review is Grok REQUEST CHANGES at {H2769[:8]}" + ) + + +def test_real_request_changes_then_approve_passes() -> None: + comments = [ + *real(2756, H2756_RC1), + *real(2756, H2756_MERGE), + *real(2756, H2756_APPROVED), + ] + outcome = verdict(H2756_APPROVED, comments) + assert outcome.passed, outcome + assert outcome.description == f"APPROVE from Grok at {H2756_APPROVED[:8]}" + + +def test_real_approve_for_an_older_head_is_stale() -> None: + comments = [*real(2756, H2756_RC1), *real(2756, H2756_APPROVED)] + outcome = verdict(H2756_RC_AFTER, comments) + assert not outcome.passed + assert outcome.description == ( + f"newest Grok APPROVE is for {H2756_APPROVED[:8]}, not head {H2756_RC_AFTER[:8]}" + ) + + +def test_real_request_changes_after_an_approve_fails() -> None: + comments = [*real(2756, H2756_APPROVED), *real(2756, H2756_RC_AFTER)] + outcome = verdict(H2756_RC_AFTER, comments) + assert not outcome.passed + assert "REQUEST CHANGES" in outcome.description + + +def test_real_codex_approve_passes_and_a_gemini_note_is_ignored() -> None: + comments = real(2411) + assert any(c["body"].startswith("From: Gemini") for c in comments) + outcome = verdict(H2411, comments) + assert outcome.passed + assert outcome.description == f"APPROVE from Codex at {H2411[:8]}" + + +def test_real_claude_and_gemini_reviews_neither_count_nor_mask() -> None: + claude = real(2440) + head = re.search(r"Reviewed-Head: ([0-9a-f]{40})", claude[1]["body"]).group(1) + assert not verdict(head, claude).passed + # A later From: Claude APPROVE doesn't hide Grok's open REQUEST CHANGES. + masked = [ + *real(2769, H2769), + comment(header("APPROVE", "Claude", H2769), at="2026-11-30T00:00:00Z"), + comment(header("APPROVE", "Gemini", H2769), at="2026-11-30T00:01:00Z"), + ] + outcome = verdict(H2769, masked) + assert not outcome.passed + assert "Grok REQUEST CHANGES" in outcome.description + + +def test_a_review_body_from_an_unlisted_account_is_ignored() -> None: + body = real(2756, H2756_APPROVED)[0]["body"] + outcome = verdict( + H2756_APPROVED, [comment(body, at="2026-11-30T00:00:00Z", login="mallory")] + ) + assert not outcome.passed + assert "no Grok or Codex review" in outcome.description + + +# --- strict parsing ---------------------------------------------------------- + + +@pytest.mark.parametrize( + "heading", + [ + "APPROVE if Richard OKs", + "APPROVE (pending founder sign-off)", + "APPROVE, conditionally", + "LGTM", + "**APPROVE**", + ], +) +def test_conditional_or_unrecognized_approve_fails(heading: str) -> None: + body = real(2756, H2756_APPROVED)[0]["body"].replace( + "review: APPROVE", f"review: {heading}", 1 + ) + outcome = verdict(H2756_APPROVED, [comment(body, at="2026-11-30T00:00:00Z")]) + assert not outcome.passed + assert "malformed" in outcome.description + + +def test_block_fails() -> None: + body = header("BLOCK", "Codex", OTHER) + outcome = verdict(OTHER, [comment(body, at="2026-11-30T00:00:00Z")]) + assert not outcome.passed + assert outcome.description == f"newest review is Codex BLOCK at {OTHER[:8]}" + + +def test_blank_lines_and_spacing_in_the_header_are_accepted() -> None: + body = ( + "## Independent adversarial review: APPROVE \n\n" + "From: Codex\n\nReviewed-Head: " + OTHER + "\n\nText." + ) + assert verdict(OTHER, [comment(body, at="2026-11-30T00:00:00Z")]).passed + + +def test_a_header_in_fenced_code_is_not_a_review() -> None: + body = "Notes.\n\n```\n" + header("APPROVE", "Grok", OTHER) + "\n```\n" + outcome = verdict(OTHER, [comment(body, at="2026-11-30T00:00:00Z")]) + assert not outcome.passed + assert "no Grok or Codex review" in outcome.description + + +@pytest.mark.parametrize( + "body", + [ + "\nNotes.", + "> " + header("APPROVE", "Grok", OTHER).replace("\n", "\n> "), + "Intro prose first.\n\n" + header("APPROVE", "Grok", OTHER), + ], +) +def test_hidden_quoted_or_late_headers_cannot_approve(body: str) -> None: + outcome = verdict(OTHER, [comment(body, at="2026-11-30T00:00:00Z")]) + assert not outcome.passed + assert "hidden, quoted or not at the top" in outcome.description + + +def test_a_request_changes_with_preamble_still_blocks() -> None: + approve = comment( + header("APPROVE", "Grok", OTHER), at="2026-11-29T10:00:00Z", cid=1 + ) + blocker = comment( + "Re-review below.\n\n" + header("REQUEST CHANGES", "Grok", OTHER), + at="2026-11-29T11:00:00Z", + cid=2, + ) + assert not verdict(OTHER, [approve, blocker]).passed + hidden = comment( + "", + at="2026-11-29T11:00:00Z", + cid=3, + ) + assert not verdict(OTHER, [approve, hidden]).passed + # Another reviewer's approval doesn't clear it; the same reviewer's does. + codex = comment(header("APPROVE", "Codex", OTHER), at="2026-11-29T12:00:00Z", cid=4) + outcome = verdict(OTHER, [approve, blocker, codex]) + assert not outcome.passed + assert "Grok malformed review" in outcome.description + grok = comment(header("APPROVE", "Grok", OTHER), at="2026-11-29T13:00:00Z", cid=5) + assert verdict(OTHER, [approve, blocker, codex, grok]).passed + + +def test_a_conditional_approve_is_not_cleared_by_another_reviewer() -> None: + conditional = comment( + header("APPROVE if Richard OKs", "Grok", OTHER), + at="2026-11-29T10:00:00Z", + cid=1, + ) + codex = comment(header("APPROVE", "Codex", OTHER), at="2026-11-29T11:00:00Z", cid=2) + assert not verdict(OTHER, [conditional, codex]).passed + + +@pytest.mark.parametrize( + ("body", "problem"), + [ + ( + header("APPROVE", "Grok", OTHER) + f"\nReviewed-Head: {'e' * 40}", + "2 Reviewed-Head", + ), + (header("APPROVE", "Grok", OTHER[:12]), "not a full 40-character SHA"), + (f"From: Grok\nReviewed-Head: {OTHER}\n\nLooks fine.", "no verdict heading"), + ( + header("APPROVE", "Grok", OTHER) + + "\n\n## Independent adversarial review: REQUEST CHANGES", + "ambiguous", + ), + ( + f"## Independent adversarial review: APPROVE\nFrom: Grok\nFrom: Codex\n" + f"Reviewed-Head: {OTHER}", + "more than one From", + ), + ], +) +def test_malformed_recognized_reviews_fail_closed(body: str, problem: str) -> None: + outcome = verdict(OTHER, [comment(body, at="2026-11-30T00:00:00Z")]) + assert not outcome.passed + assert problem in " ".join([outcome.description, *outcome.details]) + + +def test_newest_means_created_not_edited() -> None: + old_approve = comment( + header("APPROVE", "Grok", OTHER), at="2026-11-29T10:00:00Z", cid=1 + ) + old_approve["updated_at"] = "2026-11-30T10:00:00Z" + newer_block = comment( + header("REQUEST CHANGES", "Grok", OTHER), at="2026-11-29T11:00:00Z", cid=2 + ) + assert not verdict(OTHER, [newer_block, old_approve]).passed + + +# --- a blocker stands until its reviewer approves --------------------------- + + +def test_another_reviewers_approve_does_not_clear_a_blocker_at_this_head() -> None: + comments = [ + comment( + header("REQUEST CHANGES", "Grok", OTHER), at="2026-11-29T10:00:00Z", cid=1 + ), + comment(header("APPROVE", "Codex", OTHER), at="2026-11-29T11:00:00Z", cid=2), + ] + outcome = verdict(OTHER, comments) + assert not outcome.passed + assert "Grok has not approved this head" in outcome.description + comments.append( + comment(header("APPROVE", "Grok", OTHER), at="2026-11-29T12:00:00Z", cid=3) + ) + assert verdict(OTHER, comments).passed + + +def test_a_blocker_on_a_replaced_head_does_not_stand() -> None: + comments = [ + comment( + header("REQUEST CHANGES", "Grok", "e" * 40), + at="2026-11-29T10:00:00Z", + cid=1, + ), + comment(header("APPROVE", "Codex", OTHER), at="2026-11-29T11:00:00Z", cid=2), + ] + assert verdict(OTHER, comments).passed + + +def test_when_git_cannot_decide_an_approve_fails_and_a_blocker_stands() -> None: + def unknown(reviewed: str) -> tuple[str, str]: + if reviewed == OTHER: + return rv.SAME, "same" + return rv.UNKNOWN, "fetch failed" + + approve_old = [ + comment(header("APPROVE", "Grok", "e" * 40), at="2026-11-29T10:00:00Z") + ] + assert not verdict(OTHER, approve_old, currency=unknown).passed + blocker_old = [ + comment( + header("REQUEST CHANGES", "Grok", "e" * 40), + at="2026-11-29T10:00:00Z", + cid=1, + ), + comment(header("APPROVE", "Codex", OTHER), at="2026-11-29T11:00:00Z", cid=2), + ] + assert not verdict(OTHER, blocker_old, currency=unknown).passed + + +# --- configuration ----------------------------------------------------------- + + +def _config(**changes: Any) -> dict[str, Any]: + data = json.loads(rv.CONFIG_PATH.read_text()) + data.update(changes) + return data + + +def test_app_identity_native_reviews_count_when_configured() -> None: + config = rv.load_config( + _config( + sources=["pull_request_review"], + authors=[ + { + "login": "openadapt-grok[bot]", + "reviewers": ["Grok"], + "native_reviews": True, + } + ], + ) + ) + native = { + "id": 9, + "user": {"login": "openadapt-grok[bot]"}, + "state": "APPROVED", + "commit_id": OTHER, + "submitted_at": "2026-11-30T00:00:00Z", + "body": "Looks right.", + } + outcome = verdict(OTHER, real(2769, H2769), reviews=[native], config=config) + assert outcome.passed, outcome # comments are no longer a source + changes = {**native, "state": "CHANGES_REQUESTED"} + assert not verdict(OTHER, [], reviews=[changes], config=config).passed + dismissed = {**native, "state": "DISMISSED"} + assert not verdict(OTHER, [], reviews=[dismissed], config=config).passed + disagree = {**native, "body": header("REQUEST CHANGES", "Grok", OTHER)} + assert not verdict(OTHER, [], reviews=[disagree], config=config).passed + + +def test_founder_pull_request_review_bodies_are_parsed_like_comments() -> None: + review = { + "id": 3, + "user": {"login": "abrichr"}, + "state": "COMMENTED", + "submitted_at": "2026-11-30T00:00:00Z", + "body": header("APPROVE", "Codex", OTHER), + } + assert verdict(OTHER, [], reviews=[review]).passed + + +@pytest.mark.parametrize( + "changes", + [ + {"sources": ["email"]}, + {"sources": []}, + {"authors": []}, + {"authors": [{"login": "a b", "reviewers": ["Grok"]}]}, + { + "authors": [ + { + "login": "x[bot]", + "reviewers": ["Grok", "Codex"], + "native_reviews": True, + } + ] + }, + {"authors": [{"login": "abrichr", "reviewers": ["Grok"], "admin": True}]}, + {"schema_version": 2}, + {"extra": 1}, + ], +) +def test_bad_config_is_refused(changes: dict[str, Any]) -> None: + with pytest.raises(rv.ReviewVerdictError): + rv.load_config(_config(**changes)) + + +def test_shipped_config_lists_only_the_founder_relay_today() -> None: + assert set(CONFIG.authors) == {"abrichr"} + assert CONFIG.authors["abrichr"].reviewers == ("Grok", "Codex") + assert CONFIG.status_context == "review-verdict" + + +# --- git: merges from main ---------------------------------------------------- + + +def _git_version() -> tuple[int, ...]: + out = subprocess.run(["git", "--version"], capture_output=True, text=True).stdout + return tuple(int(x) for x in re.findall(r"\d+", out)[:2]) + + +requires_merge_tree = pytest.mark.skipif( + _git_version() < (2, 38), reason="git merge-tree --write-tree needs git 2.38" +) + + +class Repo: + def __init__(self, path: Path): + self.path = path + self.git("init", "-q", "-b", "main") + self.git("config", "user.email", "test@example.invalid") + self.git("config", "user.name", "Test") + self.git("config", "commit.gpgsign", "false") + + def git(self, *args: str, check: bool = True) -> str: + result = subprocess.run( + ["git", *args], cwd=self.path, capture_output=True, text=True + ) + if check and result.returncode != 0: + raise AssertionError(result.stderr) + return result.stdout.strip() + + def write(self, name: str, lines: list[str]) -> None: + (self.path / name).write_text("\n".join(lines) + "\n") + + def commit(self, message: str) -> str: + self.git("add", "-A") + self.git("commit", "-q", "-m", message) + return self.git("rev-parse", "HEAD") + + def edit(self, name: str, line: int, text: str) -> None: + lines = (self.path / name).read_text().splitlines() + lines[line] = text + self.write(name, lines) + + def merge_main(self) -> str: + self.git("merge", "-q", "--no-edit", "main") + return self.git("rev-parse", "HEAD") + + +LINES = [f"line {i}" for i in range(30)] + + +@pytest.fixture +def repo(tmp_path: Path) -> Repo: + r = Repo(tmp_path) + r.write("a.txt", LINES) + r.write("b.txt", LINES) + r.commit("base") + r.git("checkout", "-q", "-b", "pr") + r.edit("b.txt", 15, "pr change") + r.commit("pr change") + return r + + +def _main_moves(r: Repo, name: str, line: int, text: str) -> None: + r.git("checkout", "-q", "main") + r.edit(name, line, text) + r.commit(f"main edits {name}:{line}") + r.git("checkout", "-q", "pr") + + +def _currency(r: Repo, reviewed: str, head: str) -> tuple[str, str]: + return rv.merge_currency(rv.Git(r.path, main_ref="refs/heads/main"), reviewed, head) + + +@requires_merge_tree +def test_clean_merge_from_main_keeps_the_review_current(repo: Repo) -> None: + reviewed = repo.git("rev-parse", "HEAD") + # main changes a context line next to the PR's change, as on #2756. + _main_moves(repo, "b.txt", 13, "main change near the pr") + _main_moves(repo, "a.txt", 2, "main change elsewhere") + head = repo.merge_main() + assert _currency(repo, reviewed, head)[0] == rv.EQUIVALENT + # And a second merge from main on top, as on #2756 (a56440d6, c2d77e2a). + _main_moves(repo, "a.txt", 25, "later main change") + head2 = repo.merge_main() + state, reason = _currency(repo, reviewed, head2) + assert state == rv.EQUIVALENT, reason + + +@requires_merge_tree +def test_merge_with_a_hand_edit_is_stale(repo: Repo) -> None: + reviewed = repo.git("rev-parse", "HEAD") + _main_moves(repo, "a.txt", 2, "main change") + repo.git("merge", "-q", "--no-commit", "main") + repo.edit("b.txt", 20, "smuggled in the merge") + head = repo.commit("Merge branch 'main' into pr") + state, reason = _currency(repo, reviewed, head) + assert state == rv.STALE + assert "differs from a clean merge" in reason + + +@requires_merge_tree +def test_merge_that_resolved_conflicts_is_stale(repo: Repo) -> None: + reviewed = repo.git("rev-parse", "HEAD") + _main_moves(repo, "b.txt", 15, "main's competing change") + repo.git("merge", "-q", "main", check=False) + repo.edit("b.txt", 15, "pr change") + lines = [ + line + for line in (repo.path / "b.txt").read_text().splitlines() + if not line.startswith(("<<<<<<<", "=======", ">>>>>>>", "main's competing")) + ] + repo.write("b.txt", lines) + head = repo.commit("Merge branch 'main' into pr") + state, reason = _currency(repo, reviewed, head) + assert state == rv.STALE + assert "resolved conflicts" in reason + + +@requires_merge_tree +def test_merge_from_a_branch_not_on_main_is_stale(repo: Repo) -> None: + reviewed = repo.git("rev-parse", "HEAD") + repo.git("checkout", "-q", "-b", "side", "main") + repo.edit("a.txt", 3, "side change") + repo.commit("side") + repo.git("checkout", "-q", "pr") + repo.git("merge", "-q", "--no-edit", "side") + head = repo.git("rev-parse", "HEAD") + state, reason = _currency(repo, reviewed, head) + assert state == rv.STALE + assert "not on main" in reason + + +@requires_merge_tree +def test_a_new_commit_after_the_review_is_stale(repo: Repo) -> None: + reviewed = repo.git("rev-parse", "HEAD") + _main_moves(repo, "a.txt", 2, "main change") + repo.merge_main() + repo.edit("b.txt", 22, "new pr work") + head = repo.commit("more work") + state, reason = _currency(repo, reviewed, head) + assert state == rv.STALE + assert "is not a merge from main" in reason + + +@requires_merge_tree +def test_main_absorbing_part_of_the_pr_changes_its_own_diff(repo: Repo) -> None: + repo.edit("a.txt", 5, "pr change two") + reviewed = repo.commit("second pr change") + _main_moves(repo, "a.txt", 5, "pr change two") # main lands the same line + head = repo.merge_main() + state, reason = _currency(repo, reviewed, head) + assert state == rv.STALE + assert "own diff changed" in reason + + +@requires_merge_tree +def test_a_force_pushed_away_head_is_stale(repo: Repo) -> None: + head = repo.git("rev-parse", "HEAD") + state, _ = _currency(repo, "e" * 40, head) + assert state == rv.STALE + + +def test_parse_own_diff_ignores_positions_and_context() -> None: + first = ( + "diff --git a/x.py b/x.py\nindex 1..2 100644\n--- a/x.py\n+++ b/x.py\n" + "@@ -10 +10 @@\n-old\n+new\n" + ) + moved = first.replace("@@ -10 +10 @@", "@@ -42 +42 @@") + assert ( + rv.parse_own_diff(first) + == rv.parse_own_diff(moved) + == {"x.py": ("-old", "+new")} + ) + + +# --- merge queue ------------------------------------------------------------- + + +def _queue(repo: Repo) -> tuple[str, list[str], str]: + base = repo.git("rev-parse", "main") + pr1 = repo.git("rev-parse", "pr") + repo.git("checkout", "-q", "-b", "pr2", "main") + repo.edit("a.txt", 7, "pr2 change") + pr2 = repo.commit("pr2") + repo.git("checkout", "-q", "-b", "queue", "main") + repo.git("merge", "-q", "--no-ff", "--no-edit", pr1) + repo.git("merge", "-q", "--no-ff", "--no-edit", pr2) + return base, [pr1, pr2], repo.git("rev-parse", "HEAD") + + +def test_queued_heads_walks_the_merge_group_chain(repo: Repo) -> None: + base, heads, group = _queue(repo) + git = rv.Git(repo.path, main_ref="refs/heads/main") + assert rv.queued_heads(git, base, group) == heads + + +def test_queued_heads_refuses_a_squashed_group(repo: Repo) -> None: + base = repo.git("rev-parse", "main") + repo.git("checkout", "-q", "-b", "squashed", "main") + repo.edit("a.txt", 9, "squashed") + group = repo.commit("squash") + with pytest.raises(rv.ReviewVerdictError): + rv.queued_heads(rv.Git(repo.path, main_ref="refs/heads/main"), base, group) + + +# --- the whole run, with a recorded GitHub API -------------------------------- + + +class FakeGitHub: + def __init__(self, pulls: dict[int, dict[str, Any]]): + self.pulls = pulls + self.posted: list[tuple[str, dict[str, Any]]] = [] + + def request(self, path: str, *, method: str = "GET", data: Any = None) -> Any: + if method == "POST": + self.posted.append((path, data)) + return {} + if match := re.fullmatch(r"/pulls/(\d+)", path): + return self.pulls[int(match.group(1))]["pull"] + if match := re.fullmatch(r"/commits/([0-9a-f]{40})/pulls", path): + return [ + p["pull"] + for p in self.pulls.values() + if p["pull"]["head"]["sha"] == match.group(1) + ] + raise AssertionError(path) + + def pages(self, path: str) -> list[dict[str, Any]]: + number, kind = re.fullmatch(r"/(?:pulls|issues)/(\d+)/(\w+)", path).groups() + return self.pulls[int(number)][kind] + + +def _pull(number: int, head: str, files: list[dict], comments: list[dict]) -> dict: + return { + "pull": { + "number": number, + "state": "open", + "changed_files": len(files), + "base": {"ref": "main"}, + "head": {"sha": head}, + }, + "files": files, + "comments": comments, + "reviews": [], + } + + +def test_run_on_a_pull_request_event_reads_live_comments() -> None: + api = FakeGitHub({2769: _pull(2769, H2769, PROTECTED, real(2769, H2769))}) + event = {"pull_request": {"number": 2769, "head": {"sha": "0" * 40}}} + sha, outcome, report = rv.run( + event_name="pull_request", event=event, api=api, git_factory=lambda refs: None + ) + assert sha == H2769 # the live head, not the event payload's + assert not outcome.passed + assert report[0].startswith("#2769 at 53549f35: failure") + + +def test_run_on_a_comment_that_is_not_on_a_pull_request_does_nothing() -> None: + sha, outcome, _ = rv.run( + event_name="issue_comment", + event={"issue": {"number": 5}}, + api=FakeGitHub({}), + git_factory=lambda refs: None, + ) + assert sha is None and outcome.passed + + +def test_run_on_a_merge_group_re_evaluates_every_queued_pull_request( + repo: Repo, +) -> None: + base, (pr1, pr2), group = _queue(repo) + approve = [comment(header("APPROVE", "Grok", pr1), at="2026-11-30T00:00:00Z")] + api = FakeGitHub( + { + 1: _pull(1, pr1, PROTECTED, approve), + 2: _pull(2, pr2, UNPROTECTED, []), + } + ) + event = { + "merge_group": { + "base_sha": base, + "head_sha": group, + "head_ref": "refs/heads/gh-readonly-queue/main/pr-2-x", + } + } + git = rv.Git(repo.path, main_ref="refs/heads/main") + sha, outcome, report = rv.run( + event_name="merge_group", event=event, api=api, git_factory=lambda refs: git + ) + assert sha == group + assert outcome.passed, report + # Grok posts REQUEST CHANGES while #1 sits in the queue (#2756's case). + api.pulls[1]["comments"].append( + comment( + header("REQUEST CHANGES", "Grok", pr1), at="2026-11-30T01:00:00Z", cid=2 + ) + ) + _, outcome, _ = rv.run( + event_name="merge_group", event=event, api=api, git_factory=lambda refs: git + ) + assert not outcome.passed + assert outcome.description.startswith("#1: newest review is Grok REQUEST CHANGES") + + +def test_publish_posts_one_status_with_a_short_description() -> None: + api = FakeGitHub({}) + rv.publish( + api, OTHER, rv._fail("x" * 300), "review-verdict", "https://example.invalid" + ) + path, payload = api.posted[0] + assert path == f"/statuses/{OTHER}" + assert payload["context"] == "review-verdict" + assert payload["state"] == "failure" + assert len(payload["description"]) == rv.DESCRIPTION_LIMIT + + +# --- the workflow -------------------------------------------------------------- + +WORKFLOW = rv.ROOT / ".github" / "workflows" / "review-verdict.yml" + + +def test_workflow_triggers_permissions_and_pins() -> None: + text = WORKFLOW.read_text() + data = yaml.safe_load(text) + triggers = data[True] # YAML reads the bare key `on` as True + code = "\n".join(line.split("#", 1)[0] for line in text.splitlines()) + assert "pull_request_target" not in code + assert set(triggers) == { + "pull_request", + "issue_comment", + "pull_request_review", + "merge_group", + "workflow_dispatch", + } + assert set(triggers["pull_request"]["types"]) == { + "opened", + "synchronize", + "reopened", + } + assert {"created", "edited"} <= set(triggers["issue_comment"]["types"]) + assert {"submitted", "edited"} <= set(triggers["pull_request_review"]["types"]) + for trigger in triggers.values(): + assert "paths" not in (trigger or {}) and "paths-ignore" not in (trigger or {}) + assert data["permissions"] == { + "contents": "read", + "pull-requests": "read", + "statuses": "write", + } + (job,) = data["jobs"].values() + steps = job["steps"] + for step in steps: + if "uses" in step: + assert re.fullmatch(r"[\w./-]+@[0-9a-f]{40}", step["uses"]), step["uses"] + checkout = next(s for s in steps if "uses" in s and "checkout" in s["uses"]) + assert checkout["with"]["ref"] == "main" + assert checkout["with"]["persist-credentials"] is False + # The job may be skipped only for comments that can't change a verdict. + assert "issue_comment" in job["if"] + # Job-level concurrency: a skipped run never replaces a pending one. + assert "concurrency" not in data + assert job["concurrency"]["cancel-in-progress"] is False