Skip to content

Update docs/callers/detect-unreviewed-merge.md #16

Update docs/callers/detect-unreviewed-merge.md

Update docs/callers/detect-unreviewed-merge.md #16

Workflow file for this run

name: Cursor Review (reusable)
# Reusable, label-triggered multi-model code review. A multi-lab × 2-review-type
# panel (one cursor-agent cell per model × pass; 6 by default) runs adversarial +
# edge-case passes, then a
# judge model consolidates the findings into ONE review posted on the PR,
# with per-finding severity badges (critical/high/medium/low/nit).
#
# Single source of truth: the prompts and the output/post/notify scripts
# live in THIS repo under .github/cursor-review/. Consumer repos add only a
# thin caller — they don't carry copies of the review logic, so there's no
# drift to keep in sync.
#
# Credential isolation (same two-job split pr-size.yml uses). The invariant:
# NO job both checks out PR code and holds a write-scoped credential. The jobs
# that check out PR code and run cursor-agent over it — `review` and
# `consolidate` — hold `contents: read` and nothing else; the consolidated
# review is posted from a separate `post-review` job that checks out NO PR code
# and receives its payload as an artifact. The jobs that DO carry
# `pull-requests: write` and the BOT_APP_PRIVATE_KEY mint — `post-review`,
# `over-cap-comment`, `dismiss-stale-approval` and `round-cap` — check out
# nothing but this repo's pinned assets. The
# panel and the judge run `cursor-agent --print --trust` without `--sandbox`,
# and print mode can use write and shell tools, so a prompt-injected model could
# rewrite the assets checkout or a downloaded action inside its own job; on a
# fresh runner with a fresh pinned checkout there is nothing tampered for the
# minted token to meet. The optional `runs_on` input moves ONLY the
# credential-free jobs (`diff-size`, `preflight`, `review`, `consolidate`) to a
# caller's pool; every job that mints the App token or holds a write scope is
# hard-pinned to GitHub-hosted `ubuntu-latest`, so a pool never meets one. `.github/cursor-review/tests/test_workflow_job_isolation.py`
# pins this.
#
# Axes alongside the panel (`axes_alongside_panel`, default off). A caller that
# runs cursor-approve's axes normally starts them only after this whole
# workflow finishes, so an approved round waits the panel AND then the axes.
# With the input on, `approve-start-early` calls cursor-approve.yml's `start`
# phase right after `round-cap` (approve_gate `pending`: the card lists the
# axes with no axes-lane marker), and `axis-correctness` / `axis-conformance`
# run beside the panel on the same head; `axes-closeout` rewrites the
# still-pending card when the panel did not pass. None of them is in
# `panel-integrity`'s or `blocking-gate`'s `needs:` — an axis never gates the
# panel's own checks. The caller's decide stays where it was, on
# `approve_gate == 'pass'`, reading this run's `axis-*` artifacts; the
# `axes_started` output tells it to skip its own start and axes, and
# `axes_ok` (false when an axis job here failed) to skip its decide. Nesting is
# four levels — caller → cursor-review → cursor-approve / axis-<name> →
# cursor-axis-base — inside GitHub's limit of ten. Every such job is
# `if: inputs.axes_alongside_panel && …`, so with the input off it is skipped
# and nothing else changes.
#
# Caller pattern (place in source repo at .github/workflows/ci-cursor-review.yml):
#
# name: CI - Cursor Review
# on:
# # The BLOCKING caller shape, because this example sets `blocking: true`
# # below. A required check must report on the head SHA, and a label-only
# # `types: [labeled, unlabeled]` delivers no event on push — the check
# # would sit at "Expected" and brick the PR until someone toggled the
# # label. `pull_request_review_thread` is what flips the gate green the
# # moment the last finding thread is resolved. Advisory callers
# # (`blocking` unset) can keep the narrower label-only pair; see
# # docs/callers/cursor-review.md for both shapes.
# # `pull_request_target`, not `pull_request`, once APPROVER_TOKEN is in
# # play: the caller file then comes from the BASE branch, so a PR cannot
# # rewrite it to read the token (docs/callers/cursor-review.md#trust-model).
# # Plain `pull_request` still works and is fine without APPROVER_TOKEN.
# pull_request_target:
# types: [opened, reopened, ready_for_review, synchronize, labeled, unlabeled]
# pull_request_review_thread:
# types: [resolved, unresolved]
# permissions:
# contents: read
# pull-requests: write
# concurrency:
# # KEEP THIS. The reusable owns a workflow-level `concurrency:` block of
# # its own — that is what makes skip-cursor-review cancel a panel already
# # running — but it REFINES this group rather than replacing it: under the
# # default `run_without_label: false` it does not cancel on push. Never
# # name a caller group `cursor-review-reusable-*` (a caller sharing the
# # reusable's group deadlocks its own run), and call this from a dedicated
# # workflow file, not one job of a larger ci.yml — cancellation is
# # run-scoped. PR number ONLY: `github.event.label.name` is empty on every
# # widened event, so keying on it splits one PR across groups that cannot
# # cancel each other.
# group: cursor-review-pr-${{ github.event.pull_request.number }}
# cancel-in-progress: true
# jobs:
# cursor-review:
# uses: Comfy-Org/github-workflows/.github/workflows/cursor-review.yml@<sha> # v1
# with:
# # Repo-specific generated/vendored paths. Fed to the shared
# # check-pr-size classifier, so they're excluded from BOTH the size gate
# # and the reviewed diff — the same codegen detection the PR-size cap
# # uses (lockfiles, base-ref linguist-generated, Go markers are already
# # built in). Use diff_excludes only for diff-only, non-generated paths.
# # Setting this REPLACES the default list, so the defaults are re-stated
# # verbatim here before the repo's own paths. These are plain globs, not
# # git pathspecs (no `:!` prefix — that is diff_excludes' syntax), and
# # the shape is load-bearing both ways: a pattern with no `/` matches
# # the base name only, while one WITH a `/` is anchored to the whole
# # repo-relative path unless it opens with `**/` — so the
# # data/object_info.json.gz below is root-only on purpose.
# extra_generated_globs: >-
# **/node_modules/**
# **/dist/**
# **/vendor/**
# **/*.generated.*
# **/*.min.js
# **/*.min.css
# data/object_info.json.gz
# **/*.snap
# # REQUIRED. Pin the assets ref to the SAME commit SHA you pin `uses:`
# # to — otherwise the workflow is pinned but its scripts are not.
# # The workflow checks this against the uses: pin at run time and fails
# # on a mismatch.
# workflows_ref: <same-sha-as-uses>
# # Optional: post the review under your own GitHub App so its threads are
# # a distinct, queryable identity instead of github-actions[bot]. Supply
# # your App's id + private key (App IDs aren't secret, so id is an input).
# bot_app_id: ${{ vars.REVIEW_BOT_APP_ID }}
# # Optional: make the review blocking. true → the "Blocking gate" check
# # goes red while any cursor-review finding thread is unresolved. To
# # actually block merge you must ALSO mark "Blocking gate" as a required
# # status check in this repo's branch-protection / ruleset settings —
# # see docs/callers/cursor-review.md for the full flow, including the
# # pull_request_review_thread trigger that re-checks on thread resolution.
# blocking: true
# # Optional, with APPROVER_TOKEN: the environment holding it as an
# # ENVIRONMENT secret, deployment branches = the base branch only.
# approver_environment: cursor-approver
# secrets:
# CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
# SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
# # Optional — the private key paired with bot_app_id.
# BOT_APP_PRIVATE_KEY: ${{ secrets.REVIEW_BOT_PRIVATE_KEY }}
on:
workflow_call:
inputs:
judge_model:
description: >-
Single judge model that adjudicates panel findings into one
consolidated review. Currently the SAME pin as the panel's Anthropic
cell (`claude-opus-5-5-xhigh`) — it used to sit one reasoning tier
below it, until the cell itself moved to `-xhigh` on 2026-10-07. The
judge adjudicates a bounded text payload with no tools, and ran at
xhigh until 2026-07-18 with no recorded quality gap, while `max` cost
~10% of every run's spend.
type: string
required: false
default: claude-opus-5-5-xhigh
diff_size_cap:
description: >-
Max counted changed lines. PRs over the cap are skipped — too large
for a useful single-pass review. "Counted" is added + removed lines
after the shared classifier's generated-file exclusion and (when
ignore_comments is true) blank/comment-line discounting. The skip is
NOT silent: it emits a ::warning:: annotation and a step-summary block,
and upserts one sticky PR comment saying no panel ran — as the bot app
when bot_app_id + BOT_APP_PRIVATE_KEY are configured, else as
github-actions[bot] — flipped to ✅ once the PR is back under the cap.
The run stays green either way; nothing gates.
type: number
required: false
default: 5000
ignore_comments:
description: >-
Discount blank lines and comment-only lines from the counted total, so
AI-generated comment volume doesn't push a PR over the cap and skip the
review. Count-only: comments are still sent to the review panel (a
reviewer should catch wrong or misleading comments). Heuristic
(per-language, single-line comment markers; multi-line block-comment
bodies and string literals aren't lexed), so it's approximate. Default
true; set false to count every changed line.
type: boolean
required: false
default: true
review_label:
description: Label whose addition triggers the review.
type: string
required: false
default: cursor-review
extra_generated_globs:
description: >-
Extra glob patterns treated as generated, fed to the shared
check-pr-size classifier. Matching files are excluded from BOTH the
diff-size gate AND the diff handed to the review panel + judge — the
exact same "what is codegen" logic the PR-size cap uses, so the two
workflows can't drift. `*` matches within a path segment, `**` across
segments, `?` one character; a pattern without `/` matches the base
name at any depth, while a pattern WITH a `/` is anchored to the whole
repo-relative path unless it opens with `**/` (`data/gen.json` misses
`pkg/x/data/gen.json`). These are plain globs, not git pathspecs — a
`:!` prefix carried over from `diff_excludes` is matched literally and
excludes nothing. This is the preferred knob for generated/vendored
paths: the classifier already covers eight common dependency lockfiles
(see `extra_lockfiles` for the exact set — anything outside it, e.g.
Gemfile.lock or composer.lock, must be added there), files
marked `linguist-generated` in the BASE ref's `.gitattributes` (so a
PR can't exempt itself), and the canonical Go
`// Code generated ... DO NOT EDIT.` marker — so you rarely need more.
Because this classification decides what the review panel SEES, the
Go marker is honored only from the BASE blob (same base-ref invariant
as `.gitattributes`): a PR cannot hide a file from review by adding
the marker, and a file NEW in the PR never matches it — cover newly
generated files with a glob here or a base `.gitattributes` rule.
Supplying this input REPLACES the default list wholesale, so restate
the defaults you still want: a repo whose `.claude/` tree is
vendored/tool-installed output (a BMAD-method install, say) rather
than hand-authored agent instructions should pass the defaults plus
its own `**/.claude/**` glob — hand-authored agent instructions are
prose worth reviewing, so the default no longer excludes them. Until
such a repo does, that tree counts against `diff_size_cap`, and a PR
over the cap is skipped silently (no review, no Slack notice).
type: string
required: false
default: >-
**/node_modules/**
**/dist/**
**/vendor/**
**/*.generated.*
**/*.min.js
**/*.min.css
extra_lockfiles:
description: >-
Extra dependency-lockfile base names to exclude (count + diff), on top
of the classifier's built-ins (go.sum, go.work.sum, package-lock.json,
pnpm-lock.yaml, yarn.lock, Cargo.lock, poetry.lock, uv.lock).
Whitespace- or comma-separated; matched at any directory depth.
type: string
required: false
default: ''
diff_excludes:
description: >-
Additional git pathspecs excluded from the reviewed diff ONLY (not the
size gate), applied verbatim ON TOP of the shared classifier's
generated-file exclusion. Back-compat escape hatch for one-off paths
that aren't "generated" per se; for generated/vendored paths prefer
`extra_generated_globs`, which also keeps them out of the size gate.
Folded scalar collapses newlines to spaces so the value word-splits
into pathspec args. Paths with a leading underscore need the long-form
`:(exclude)` syntax — the short-form `:!` parser reads `_` as pathspec
magic. (Previously this fed both the count and the diff and defaulted
to the lockfile/vendored list; that list now lives in the classifier
and `extra_generated_globs`, so the default here is empty. Callers that
listed generated paths here should move them to `extra_generated_globs`
to keep them out of the size gate too.)
type: string
required: false
default: ''
workflows_ref:
description: >-
REQUIRED. Ref of Comfy-Org/github-workflows to load the prompts and
scripts from. Must be the SAME commit SHA you pin `uses:` to —
otherwise the workflow is pinned but the code it runs is not. There is
deliberately no default: a floating `main` default would silently load
mutable scripts into jobs that hold write permissions.
type: string
required: true
bot_app_id:
description: >-
GitHub App ID. When set (with the bot_app_private_key secret), the
consolidated review + per-finding line comments post under that App's
identity (your App's "<app>[bot]" login) instead of
github-actions[bot], so its threads are distinct and queryable.
Optional — omit to post as github-actions[bot] (default; unchanged for
OSS consumers). App IDs aren't secret, so this is an input, not a secret.
type: string
required: false
default: ''
ledger_prior_review:
description: >-
Give each review round the PRIOR rounds' findings and the author's
replies (the "prior-review ledger"), so a finding that was refuted,
declined, or deferred earlier is not silently re-litigated. Set false
to disable the ledger — the kill switch for the case where it degrades
reviews after rollout; flipping this input beats reverting SHA pins
across every consumer. With it false the panel/judge prompts are
exactly the pre-ledger ones. Default true.
type: boolean
required: false
default: true
rereview_command:
description: >-
Opt-in: the comment command that asks for ANOTHER round on the SAME
commit, e.g. `/review`. Empty (the default) leaves the same-commit
dedupe absolute, exactly as before. When set, this workflow does not
skip a round if an authorized commenter posted that command AFTER the
newest consolidated review for the current HEAD SHA — so a round that
reached no decision because reviewers errored can be re-run without
pushing an empty commit. It does NOT by itself give anyone a way to
TRIGGER a run: the command has to reach the review label, which is
`cursor-review-auto-label.yml`'s `issue_comment` moment. Authorized
means an OWNER / MEMBER / COLLABORATOR association on the comment,
the same bar `pr-derisk.yml` applies to `/derisk`. `max_rounds` still
caps how many rounds a PR can have.
type: string
required: false
default: ''
auto_retry_errored_rounds:
description: >-
Opt-in: re-run a round AUTOMATICALLY when it could not decide because
reviewers errored — a capacity error, a cell timeout — rather than
because of anything in the diff. Default false. The round is re-run
once per PR (the existing auto-retry ceiling), the status card says so
before it happens, and `max_rounds` still applies; a round that failed
for a structural reason, or that found something above the threshold,
is never re-run because the next round would hit the same wall.
Independent of `rereview_command`, which is the HUMAN path: that one
keys on an authorized comment, and the retry posts no comment. The
retry's own force signal is the marked block decide already writes
(`AUTO_RETRY_MARKER`), which the gate accepts when it is newer than
the newest consolidated review for this commit and was posted by a
Bot or by the identity that applied the label — so one marked block
buys exactly one round. No effect without `approve_max_severity`,
and needs `bot_app_id` or APPROVER_TOKEN to relabel.
type: boolean
required: false
default: false
auto_retry_delay_minutes:
description: >-
How long to wait before an automatic retry relabels, in minutes.
Default 0 (immediately), which is the behaviour every existing caller
has. Worth setting for `auto_retry_errored_rounds`, because the
failures it retries are usually provider capacity and a few minutes
is what makes the second attempt different from the first. The wait
happens on a runner, so it costs runner-minutes on a private repo —
that is the whole cost of this feature. Clamped to 30 rather than
holding a runner all day; anything unparsable waits not at all. The
status card names the start time (UTC) before the wait begins.
type: number
required: false
default: 0
auto_rereview_after_dismissal:
description: >-
Opt-in: when a push dismisses the approver's approval, start the next
round AUTOMATICALLY — after `auto_rereview_delay_minutes`, and only if
the head is still the one that dismissed it (so a burst of pushes
costs one round), no round has started since, the PR is open and not
a draft, it carries neither `skip-cursor-review` nor
`needs-human-review`, and it is under `max_rounds`. Once per head
commit, recorded on the status card. Default false: the card is still
marked stale on every such dismissal, and asks for a relabel. Needs
`bot_app_id` or APPROVER_TOKEN to relabel. No effect without
`approve_max_severity`, for an author `approve_authors` does not
list, or under `run_without_label` (the push starts that round).
With `approve_only_on_push` on too, a push on a round whose panel
blocked (its card carries the panel-blocked marker) is scheduled the
same way, though no approval was dismissed.
type: boolean
required: false
default: false
auto_rereview_delay_minutes:
description: >-
How long `auto_rereview_after_dismissal` waits before relabelling, in
minutes: the debounce that lets a burst of pushes settle. Default 10.
The wait happens on a runner. Clamped to 30; anything unparsable
waits not at all. The status card names the start time (UTC) before the wait begins.
type: number
required: false
default: 10
carry_forward_unchanged_diff:
description: >-
Opt-in: when a push or a retarget would dismiss the approver's
approval but leaves the PR's OWN changes identical to the ones a
round reviewed (the PR was only rebased or re-merged onto a moved
base, e.g. a lower PR of a stack changed or landed), re-approve the
live head instead of dismissing. Identical means the compare-API
diff from the merge base the approval recorded to the reviewed
commit equals the diff from the live base to the live head, file by
file, context lines and hunk headings included (hunk line numbers
ignored, the distance between a file's hunks not). File modes are
not compared: the compare API does not report them. An approval
records its merge base only when the compare API and the round's
own sentinel agree on it; one that records none (every approval an
earlier version posted) never carries. Fails closed — dismisses as
before — on 300+ files, a file with no or an empty patch (binary or
too large, except a pure rename), any read error, an edited
approval, a recorded merge base that is not an ancestor of the
reviewed commit, a newer request for changes by the approver, an
`approve_max_severity` stricter than the one the approval was
granted under, a draft, a veto or `needs-human-review` label, an
author `approve_authors` does not list, an empty
`approve_max_severity`, rounds or approvals posted as
`github-actions[bot]` (set `bot_app_id`), or any event other than
`pull_request_target`. Only an approval GitHub still shows as
APPROVED is carried, so after a squash or rebase merge of a lower
PR, a retarget read before the rebase (its diff still holds that
PR's commits) dismisses it, and the rebase has nothing left to
carry. The new approval records the commit and merge base the round
reviewed, and the threshold the approval was granted under, so a
chain of such pushes keeps comparing against what a round actually
read, and the card keeps its approval (no round is scheduled).
Default false.
type: boolean
required: false
default: false
approve_only_on_push:
description: >-
Opt-in: on a push (`synchronize`, or `reopened`) to a PR whose LAST
panel round passed and whose axes ran (the cursor-approve card says
so), run NO panel — set `approve_gate` to `pass` instead, so the
caller's cursor-approve jobs judge the new head with the axes alone.
After `auto_rereview_delay_minutes` (the same debounce; a burst of
pushes yields one re-check, on the head that is still live), and
only while the PR is open, not a draft, carries the review label and
neither `skip-cursor-review` nor `needs-human-review`, has no
approval by the approver already standing on that head, no open
review thread above `approve_max_severity` (or unbadged), no review
label applied since the approver's last decision (a full round in
flight), and is under `approve_only_max_runs` for its panel round.
Never counts toward `max_rounds`: no consolidated review is posted.
Needs `max_rounds` > 0 (an uncapped round's card names no round to
count re-checks under), and never follows the LAST round of
`max_rounds` — that one is a human's. A panel round that fails (or
any round's own card) leaves the lane, so the next push asks for a
full round as before; so does a card anyone but the approver
identity ever edited (its edit history), for good. Takes the push
from `auto_rereview_after_dismissal`: when it re-checks, no round is
relabelled. Relabelling still runs a full round. Needs
APPROVER_TOKEN, `approve_max_severity` and `pull_request_target`
(the caller's cursor-approve jobs need all three anyway); no effect
under `run_without_label` (the push starts that round). With
`auto_rereview_after_dismissal` on as well, a push on a round whose
PANEL blocked (cursor-review's own decide requested changes — never an
untrusted or capped round) starts a full round itself instead, through
the same debounced `auto-rereview` relabel. Default false.
type: boolean
required: false
default: false
approve_only_max_runs:
description: >-
Cap on `approve_only_on_push` re-checks per panel round, counted on
the cursor-approve card; at the cap a push is left to a relabel (or
`auto_rereview_after_dismissal`), and a new panel round resets the
count. Clamped to 50, the heads the card's record keeps; anything
unparsable re-checks nothing.
Default 10.
type: number
required: false
default: 10
run_without_label:
description: >-
Run on plain pull_request events (opened / reopened / ready_for_review
/ synchronize) instead of requiring the trigger label — for repos with
no labeling automation. The fork skip, the skip-cursor-review label,
and the same-commit dedupe all still apply. Default false
(label-triggered, unchanged for existing callers).
type: boolean
required: false
default: false
panel_models:
description: >-
Optional JSON array of Cursor catalog model ids that REPLACES the
default panel list (see the preflight "Define panel models" step for
the current defaults). Each id still runs both review types and is
validated against the live catalog by preflight, so a typo or a
delisted id fails loud before any cell spends. Intended for
per-repo experiments — e.g. an A/B of `-xhigh` vs `-max` reasoning
tiers — without forking the workflow. Empty (default) = built-in list.
type: string
required: false
default: ''
openai_direct_model:
description: >-
OPT-IN. An OpenAI model id (e.g. `gpt-6.1-sol`) reviewed through the
OpenAI API directly, via the Codex CLI, as two cells — adversarial
and edge-case, the same passes and prompts a Cursor model gets.
Empty (default) = the job is skipped and nothing changes. Requires the
`OPENAI_API_KEY` secret and a plain id (`[A-Za-z0-9._-]`); set
without either, preflight warns, the cells stay off and the panel is
unchanged.
Deliberately NOT part of `panel_models`: that list is validated
against the live CURSOR catalog, which a direct-API id is not in.
By default the cells REPLACE the Cursor OpenAI cells rather than
adding to them, and then GATE like them; see
`openai_direct_replaces_cursor_openai`.
type: string
required: false
default: ''
openai_direct_replaces_cursor_openai:
description: >-
When the direct cells are in effect (`openai_direct_model` set, a
plain id, and its key present), drop the Cursor-hosted OpenAI cells
from the panel so the lane is reviewed once rather than twice. Default
true: the direct cells REPLACE them, and so gate exactly as the Cursor
cells would — counted in `Panel integrity` and the auto-approve gate
(`approve_max_failed_reviewers`), a failed one red in the rollup and
named in the review's "did not contribute" line. Matching is by vendor prefix
(`gpt-`) against the resolved panel list, which is how every OpenAI id
in Cursor's catalog is spelled today — the other labs' ids are
untouched. Set false to run both for a side-by-side comparison of the
two backends on identical diffs; the direct cells are then ADVISORY —
their findings reach the judge, but the legs never fail the run and
are not counted. Refuses to leave the Cursor panel empty: if
every remaining id would be dropped, preflight fails rather than
silently shrinking the panel to the direct cells alone.
type: boolean
required: false
default: true
anthropic_direct_model:
description: >-
OPT-IN. An Anthropic model id (e.g. `claude-opus-5-5`) reviewed
through the Anthropic API directly, via the Claude Code CLI, as two
cells — adversarial and edge-case, the same passes and prompts a
Cursor model gets. The Anthropic twin of `openai_direct_model`, with
the same rules: empty (default) = the job is skipped and nothing
changes; requires the `ANTHROPIC_API_KEY` secret and a plain id
(`[A-Za-z0-9._-]`) other than `openai_direct_model`'s, and set
without any of those, preflight warns, the cells stay off and the
panel is unchanged. The same holds for a key that is present but
UNUSABLE: `gate` probes it with one 1-token call each round, and a
usage-limit, billing or 401/403 refusal, or 429/529/5xx after
retries, keeps the Cursor `claude-*` cells for that run, with a
warning, a job summary line and a note under the review header; an
unknown model id fails the run instead. Unlike the OpenAI cells,
which see the diff only, the agent also reads a read-only checkout of
the PR with Read, Grep and Glob alone — no Bash or other
code-running tool — and `--restricted` confines those file tools to
that checkout. This panel reviews private-repo diffs and the workflow
cannot check the Anthropic organization's data-retention terms, so a
caller on a private repo must use a key from an organization with
zero data retention. By default the cells REPLACE the Cursor
Anthropic cells; see `anthropic_direct_replaces_cursor_anthropic`.
type: string
required: false
default: ''
anthropic_direct_effort:
description: >-
Reasoning effort for the direct Anthropic cells (`--effort`): one of
`low`, `medium`, `high`, `xhigh`, `max`. Any other value warns and
falls back to `xhigh`, the default. Ignored unless
`anthropic_direct_model` is in effect.
type: string
required: false
default: xhigh
anthropic_direct_replaces_cursor_anthropic:
description: >-
The Anthropic twin of `openai_direct_replaces_cursor_openai`, with
the same semantics: when the direct Anthropic cells are in effect,
drop the Cursor-hosted Anthropic cells (vendor prefix `claude-`,
case-insensitive) so they REPLACE them and gate exactly as they
would. Set false for a side-by-side comparison in which the direct
cells are ADVISORY. Refuses to leave the Cursor panel empty. Never
touches `judge_model`.
type: boolean
required: false
default: true
judge_direct_model:
description: >-
OPT-IN. An Anthropic model id (e.g. `claude-opus-5-5`) that runs the
JUDGE through the Anthropic API directly, via the same pinned Claude
Code CLI and `ANTHROPIC_API_KEY` secret as `anthropic_direct_model`,
instead of `judge_model` through Cursor. Empty (default) = the judge
stays on Cursor and nothing changes. Requires a plain id
(`[A-Za-z0-9._-]`, at most 100) and the key; set without either,
preflight warns and the Cursor judge runs — as it does when `gate`'s
probe finds the key unusable (see `anthropic_direct_model`). Same prompt, same
structured-output tool, same timeout and same degraded panel-union
fallback as the Cursor judge. The agent reads the PR checkout with
Read, Grep and Glob alone — no Bash or other code-running tool —
confined to it by `--restricted`. It runs in its own `judge-direct`
job on GitHub-hosted `ubuntu-latest`, whatever `runs_on` says, so the
key never reaches `consolidate`. This judge reads private-repo diffs
and the workflow cannot check the Anthropic organization's
data-retention terms, so a caller on a private repo must use a key
from an organization with zero data retention.
type: string
required: false
default: ''
judge_direct_effort:
description: >-
Reasoning effort for the direct judge (`--effort`): one of `low`,
`medium`, `high`, `xhigh`, `max`. Any other value warns and falls
back to `xhigh`, the default. Ignored unless `judge_direct_model` is
in effect.
type: string
required: false
default: xhigh
skip_bot_branch_prefixes:
description: >-
Space-separated head-branch prefixes that skip the review when the PR
AUTHOR is a GitHub App / Bot account. Targets machine-generated pin
bumps and catalog refreshes (`ci/bump-…`, `chore/refresh-…`,
`auto/refresh-…`) that otherwise pay for a full panel with nothing a
reviewer can judge. Matched only for `user.type == Bot` authors, so a
human pushing to a `ci/bump-…` branch is still reviewed. Set to '' to
review every bot PR. Skips are logged in the gate step, and the
`skip-cursor-review` label remains the per-PR override in both
directions.
type: string
required: false
default: ci/bump- chore/refresh- auto/refresh-
blocking:
description: >-
Opt-in merge gate (restored by BE-4691 after #31 dropped it). false
(default) → the review is advisory, exactly as before: it posts
findings but never fails a check on them, so no caller's behavior
changes until it opts in. true → a final "Blocking gate" job fails
(red check) while the PR has unresolved, non-outdated cursor-review
finding threads, and passes once they are all resolved — idempotent
on re-run, and fail-closed: a fresh panel that was supposed to post
its review and didn't refuses to pass. NOTE: this workflow cannot set
branch protection. To actually block the merge you must ALSO mark the
"Blocking gate" check as a required status check in the caller repo's
branch-protection / ruleset settings — until you do, the red check is
visible but non-blocking. Require THIS check and no other: a skipped
required check counts as passing, and "Consolidate panel" /
"Post review" skip exactly when no review ran. See
docs/callers/cursor-review.md for the resolve→re-check flow.
type: boolean
required: false
default: false
approve_max_severity:
description: >-
Opt-in auto-approve. '' (default) → off: the bot never approves or
requests changes. `medium`, `low` or `nit` → after a round, the bot
APPROVES (pinned to the reviewed commit) when every finding is at or
below that severity, and REQUESTS CHANGES when any finding is above
it. Any other value fails the run. No approval when the judge did not
adjudicate, a panel reviewer did not complete (beyond what
`approve_max_failed_reviewers` tolerates), the review did not land
as threads, the head moved or the base was retargeted mid-run, an
earlier critical/high thread is still open, or the reviewed diff is
empty (every changed path excluded by diff_excludes / the
generated-file classifier). A caller
that sets this must also deliver `synchronize`, `reopened` and
`edited`, so a push or a base retarget dismisses the bot's earlier
approval; that dismissal runs whether or not this input is still
set, so unsetting it stops new approvals without stranding old ones. Pass a
repo variable (e.g. `vars.CURSOR_APPROVE_MAX_SEVERITY`) to flip it
without a PR. The approval only counts where the approving identity
can satisfy the ruleset — see APPROVER_TOKEN and
docs/callers/cursor-review.md. TRUST MODEL: the decision rests on
model output over the PR's own content, so a diff that prompt-injects
the panel and judge can earn an approval; and for `pull_request`
events this input is read from the caller workflow at the PR's head,
so a same-repo PR can switch it on for itself. Enabling it makes the
approval no stronger than push access — see the guide's trust-model
section before letting it satisfy a required review.
type: string
required: false
default: ''
approve_authors:
description: >-
Per-author opt-in for auto-approve. A comma- or space-separated list
of GitHub logins (case-insensitive; a leading `@` is ignored). ''
(default) → every author, the behaviour before this input existed.
Otherwise a PR whose author (`pull_request.user.login`) is not listed
gets auto-approve OFF: `approve_gate` is `off`, no APPROVE or
REQUEST_CHANGES is posted (the decision note says "auto-approve not
enabled for author <login>"), and the panel still reviews and posts
its threads. `Dismiss stale auto-approval` still withdraws an earlier
marked approval as usual. No effect unless `approve_max_severity` is
set. Pass a repo variable (e.g. `vars.CURSOR_APPROVE_AUTHORS`) to
change it without a PR — and note it is read from the caller at the
PR's head, like `approve_max_severity`, so it is no stronger than
push access either.
type: string
required: false
default: ''
approve_scope:
description: >-
What an auto-approve round after the first gates on. `delta`
(default) → a finding above `approve_max_severity` blocks only when it
sits inside a hunk of the verified incremental block (the changes
since the last reviewed commit), re-raises an earlier finding whose
thread is still unresolved (named in `repeat_of`, or on the path and
line of an earlier round's still-open thread), or is High/Critical
anywhere in the reviewed diff. Every other finding is still posted, as a thread
marked "Outside this round's changes: not blocking auto-approve",
and is never auto-resolved. Round 1, an incremental block that was
unavailable, discarded or empty (a pure rebase), one naming a path
that cannot be parsed, an unknown prior-review ledger, an
unreadable list of earlier open threads and an explicitly empty
value all fail closed to `full`. `full` → every finding counts, wherever it
sits (the behaviour before this input existed). The panel reviews
the full diff either way. No effect unless `approve_max_severity` is
set; any other value fails the decision step.
type: string
required: false
default: delta
defer_approval:
description: >-
For a caller that runs cursor-approve's per-axis approval after this
workflow. false (default) → no change. true → a round that would
APPROVE still reports `approve_gate` = `pass`, but posts no review and
auto-resolves no thread; it withdraws the approver identity's own
earlier auto-approvals (and requests for changes) instead, so cursor-approve's `phase: decide`
is the only approver and no severity-only approval stands while the
axes judge — nor after a run that fails before they start.
REQUEST_CHANGES is still posted. No effect unless
`approve_max_severity` is set. See docs/callers/cursor-approve.md.
type: boolean
required: false
default: false
approve_max_failed_reviewers:
description: >-
How many panel reviewers may ERROR (status `error`: the cell ran but
failed, timed out, or never uploaded) before auto-approve withholds its
decision. 0 (default) → any reviewer that did not complete withholds,
as before. N → up to N errored reviewers are tolerated and the round
is decided normally (the decision names them, e.g. "approved with
1/6 reviewers errored: <model>:edge-case"), but it is still withheld
when more than N errored, a reviewer has any other status, the panel
metadata is missing, or a review type (`adversarial` or `edge-case`)
has no reviewer that completed. Applies to the decision `defer_approval`
hands to cursor-approve too. No effect unless `approve_max_severity`
is set. A tolerated errored cell still turns THIS WORKFLOW's called job
red (the leg itself, and `Panel integrity` with it), so a caller that
chains jobs off it — the cursor-approve axes above all — must guard
them with `!cancelled()` or GitHub's default `needs:` rule skips them
and the tolerance buys nothing. `!cancelled()` also drops the implicit
success requirement on EVERY other `needs:` entry, so restate those
explicitly (the axes keep `needs.approve-start.result == 'success'`).
See docs/callers/cursor-approve.md ("A red panel cell must not skip
the axes").
type: number
required: false
default: 0
cell_timeout_minutes:
description: >-
Wall-clock cap, in minutes, on ONE reviewer cell's agent step —
`Run cursor review` for a Cursor cell, `Run direct-API review` for a
direct-OpenAI one. 15 (default) is the historical value, so an unset
input changes nothing. A cell that runs out of clock exits 130,
uploads `status: error` with no findings, fails its leg and so fails
`Panel integrity` — the cap is a guillotine, not a safety net, and
raising it is the only way to review a diff that honestly needs
longer. It is also the budget a cell's RETRIES share
(`resource_exhausted` is retried in-step), so it bounds attempts plus
backoff, not one attempt. Three further caps are DERIVED from this and
cannot be set separately, which is what keeps the panel and its judge
in step: each cell's JOB cap is this + 15 (checkout, CLI install,
artifact up/download — overhead outside the agent step), the judge's
`Run judge` step cap is this x 2 but never below 30 (it reads EVERY
cell's findings at the same reasoning tier, so it needs more than any
one of them, and its workload scales with the panel, not with this
cap), and the judge's job cap is its step + 10. At the default that
reproduces today's 30 / 15 / 30 / 40 exactly. Bounded 10-45 by
preflight, which
fails before any cell spends rather than letting a typo mint an
hours-long job.
type: number
required: false
default: 15
max_rounds:
description: >-
Cap on review rounds per PR. Before the panel starts, the run counts
the consolidated reviews the posting identity has already left on this
PR; at or over this number it runs NO panel, labels the PR
`needs-human-review` (creating the label if missing), posts one
comment listing the latest round's open findings above
`approve_max_severity` (every open finding when that is empty), and
sets the `approve_gate` output to `capped`. Auto-approve never
approves a PR carrying that label. Removing the label resets the
count: only rounds after its most recent removal count. A round whose
own decision found the PR head had moved (a newer push superseded
it) does not count either, at most once per reviewed commit and at
most `max_rounds` times, so a PR runs at most twice the cap's
panels. 0 → no cap. A
count that cannot be read, or a label that cannot be applied, fails
open (the panel runs). Creating the label needs `issues: write`, so
pre-create it unless the bot App has it. Default 5.
type: number
required: false
default: 5
runs_on:
description: >-
JSON-encoded `runs-on` for the four jobs that hold no write-scoped
credential and do the heavy lifting: `diff-size`, `preflight`, the
`review` panel and `consolidate`. Same shape as
cursor-review-auto-label.yml's `runs_on`, so one repo variable can
feed both. Default '"ubuntu-latest"' (a JSON string); an empty value
falls back to it too. Pass a JSON array for a self-hosted pool, e.g.
'["self-hosted", "linux", "x64"]'. Every other job — the gate, the
ledger, the Slack notices, and every job that mints the App token or
holds `pull-requests: write` — stays on GitHub-hosted `ubuntu-latest`
regardless, so a pool never sees a write credential, as do the
direct-API cells and the direct judge, which hold a model key.
Review and consolidate run models with unsandboxed shell over the
PR's code, so pick a pool that gives each job a fresh pod (fresh filesystem and
$HOME), carries no cloud identity or service-account token, and
cannot reach private networks or the metadata server — anything a
prompt-injected PR runs there can reach whatever the runner can. The
image must be linux/x64 (the cursor-agent installer pins that one
artifact) with bash, git, curl, jq, python3, gh, tar and GNU
coreutils (sha256sum); diff-size installs Go itself.
type: string
required: false
default: '"ubuntu-latest"'
approver_environment:
description: >-
The caller-repo environment that holds APPROVER_TOKEN, declared as
`environment:` on exactly the jobs that read it (`post-review`,
`dismiss-stale-approval`, `auto-retry`, `auto-rereview`,
`approve-only`, `axes-closeout`), on
`pull_request_target` runs only. Give the environment a
deployment-branch policy of the base branch only and store
APPROVER_TOKEN as an ENVIRONMENT secret there (not a repo secret):
the token is then unreachable from `pull_request` runs, which a PR
head controls. Pair with a `pull_request_target` caller — see
docs/callers/cursor-review.md#trust-model. Empty (default) = no
environment, exactly as before. With `axes_alongside_panel` it is
also passed to cursor-approve's start phase (`approve-start-early`),
which declares it there.
type: string
required: false
default: ''
axes_alongside_panel:
description: >-
Opt-in: start cursor-approve's `start` phase and the gating axes
(`axes`) as soon as `round-cap` has run, alongside the panel,
instead of leaving them to the caller after this workflow finishes —
so a passing round's tail after the panel is the caller's decide
job alone. Same requirements as the caller-side axes:
`pull_request_target`, `approve_max_severity`, APPROVER_TOKEN, and
an author `approve_authors` lets through — plus `defer_approval`
(without it the start is skipped). A round over the diff-size cap,
or with a failed preflight, runs no axis. The start card is written
with `approve_gate` `pending` (no axes-lane marker, so
`approve_only_on_push` never reads an undecided round as a passed
one); a round the cap hands to a human writes the capped card and
runs no axis. When the panel then does NOT pass, `axes-closeout`
rewrites that still-pending card to "No decision this round" (and
on a `pass` whose axis job failed); on `pass` the caller's decide
downloads this run's `axis-*` artifacts as usual. The caller keeps
its decide job, still gated on `approve_gate == 'pass'` — the only
panel-pass guard — and on `axes_ok` when `axes_started` is
`success`, and gates its own start and axes on `axes_started` so
they do not run twice. Default false: every job it adds is skipped.
type: boolean
required: false
default: false
axes:
description: >-
With `axes_alongside_panel`: the comma-separated axes the start card
lists, as cursor-approve's `axes`: a non-empty subset of
`correctness` and `conformance`, the only axes run here (anything
else fails the start phase). Pass the same list to the caller's
decide. Default `correctness,conformance`.
type: string
required: false
default: correctness,conformance
axis_prior_rounds:
description: >-
With `axes_alongside_panel`: cursor-approve's `prior_rounds`, passed
to its start phase and to every axis run here (0..3; 0 = off). Pass
the same value to the caller's decide. Default 0.
type: number
required: false
default: 0
axis_direct_model:
description: >-
With `axes_alongside_panel`: the axis workflows' `axis_direct_model`
(run the axis on the direct Anthropic API with ANTHROPIC_API_KEY).
Default '' = Cursor.
type: string
required: false
default: ''
secrets:
CURSOR_API_KEY:
description: Cursor API key for cursor-agent (the panel + judge models bill through it).
required: true
OPENAI_API_KEY:
description: >-
OpenAI API key for the optional direct-API review cell. Required only
when the `openai_direct_model` input is set; ignored otherwise. Use a
service-account key scoped to its own project with a spend limit, not
a user key — the cell bills per call against it directly rather than
against a pooled seat.
required: false
ANTHROPIC_API_KEY:
description: >-
Anthropic API key for the optional direct-API Anthropic review cells
and direct judge. Required only when the `anthropic_direct_model` or
`judge_direct_model` input is set; ignored otherwise. Only the gate
(a presence check and a 1-token usability probe), the direct cells
and the `judge-direct` job read it, all on GitHub-hosted
`ubuntu-latest`. A key the probe finds capped or refused puts those
lanes on Cursor for that run. Use a key scoped to its
own Anthropic workspace with a spend limit, never a personal key —
the cells and judge bill per call against it directly rather than
against a pooled seat.
required: false
SLACK_BOT_TOKEN:
description: Slack bot token for the start/complete DM notifications. Optional — DMs are skipped if absent.
required: false
BOT_APP_PRIVATE_KEY:
description: PEM private key matching the bot_app_id input. Required only when bot_app_id is set.
required: false
APPROVER_TOKEN:
description: >-
Optional token for approve_max_severity's reviews (approve, request
changes, dismiss). Use a user account's token where the ruleset needs a
CODE OWNER approval — a GitHub App cannot be a code owner. Absent → the
bot_app_id identity, else github-actions[bot], which can approve only
when the repo/org setting "Allow GitHub Actions to create and approve
pull requests" is on. Whichever identity it is must also be allowed to
dismiss reviews if branch protection restricts dismissals.
required: false
outputs:
approve_gate:
description: >-
The round's severity-gate verdict, for a downstream workflow that
must run only after a round passed. Exactly one of: `pass` (the
auto-approve decision was APPROVE — posted, unless `defer_approval`
left it to cursor-approve), `fail` (REQUEST_CHANGES, or an
open thread above the threshold withheld approval), `untrusted` (the
judge was degraded, a panel cell failed beyond what
`approve_max_failed_reviewers` tolerates, the review was not delivered,
the head moved — or no round was delivered by this run at all, e.g. a
skipped or already-reviewed event), `capped` (the `max_rounds` cap was
hit this run, or the PR carries `needs-human-review` while
`max_rounds` or `approve_max_severity` is set), `off`
(`approve_max_severity` is empty, or `approve_authors` does not list
the PR's author, and the cap was not hit). Under
`approve_only_on_push`, a push the `approve-only` job re-checks is
`pass` with no panel run: the caller's cursor-approve jobs judge the
pushed head.
value: ${{ (jobs.round-cap.outputs.capped == 'true' || jobs.round-cap.outputs.labelled == 'true') && 'capped' || (inputs.approve_max_severity == '' || jobs.gate.outputs.approve_author_ok == 'false') && 'off' || jobs.approve-only.outputs.go == 'true' && 'pass' || jobs.post-review.outputs.approve_gate || 'untrusted' }}
round:
description: >-
The 1-based number of the review round this run delivered, counted
the way `max_rounds` counts (the posting identity's consolidated
reviews since `needs-human-review` was last removed; a round that
reviewed nothing, or whose decision found the head had moved, does
not count). It is computed before the round runs, so a round its own
decision later excuses still reports N, and the next counted round
reports N again. When this run hit the cap, the
number of the last round instead. An `approve_only_on_push`
re-check reports the panel round it re-checks under (its card's). Empty when the run delivered no
round, the count could not be read, or `max_rounds` is 0 (nothing is
counted then).
value: ${{ jobs.round-cap.outputs.capped == 'true' && jobs.round-cap.outputs.rounds || jobs.post-review.outputs.delivered == 'true' && jobs.round-cap.outputs.next_round || jobs.approve-only.outputs.go == 'true' && jobs.approve-only.outputs.round || '' }}
max_rounds:
description: >-
The effective round cap: the `max_rounds` input as applied, `0` when
there is no cap (including a value the cap step rejected as not a
whole number). Pairs with `round` for a "round R of M" display.
value: ${{ jobs.round-cap.outputs.max_rounds || (inputs.max_rounds > 0 && inputs.max_rounds) || 0 }}
approve_scope_effective:
description: >-
The scope this run's auto-approve decision actually gated under:
`delta` only when `approve_scope` was `delta` and the round did not
fall back to `full` (round 1, an unavailable, discarded or empty
incremental block, an unparseable path, an unknown ledger, an
unreadable list of earlier open threads); `full` otherwise, including
when no decision ran or the round withdrew it (`untrusted`/`capped`). Pass it to cursor-approve's
`approve_scope` so a deferred approval resolves threads under the
same rule this round's decide used.
value: ${{ jobs.post-review.outputs.approve_scope_effective || 'full' }}
axes_started:
description: >-
Under `axes_alongside_panel`, the result of the job that ran
cursor-approve's start phase here: `success` (the axes ran in this
run — the caller's decide reads their artifacts, and it must not run
its own start or axes), `failure`, `cancelled`, or `skipped` (off,
or not eligible this run: the caller's own start and axes run as
before). Empty or `skipped` whenever `axes_alongside_panel` is false.
value: ${{ jobs.approve-start-early.result }}
axes_ok:
description: >-
Under `axes_alongside_panel`: `true` when every axis job this run
started succeeded (or was not listed in `axes`), else `false`. A
caller's decide must not run when `axes_started` is `success` and
this is `false`: a failed axis job may mean its genuine verdict
upload lost to a forged `axis-<name>` artifact another job in the run
claimed first, and decide reads the artifact by name.
`axes-closeout` writes "No decision this round" on that path.
value: ${{ contains(fromJSON('["success","skipped"]'), jobs.axis-correctness.result) && contains(fromJSON('["success","skipped"]'), jobs.axis-conformance.result) }}
concurrency:
# Owned by the REUSABLE so every caller gets it at its next pin bump — the
# same shape pr-size.yml and pr-area-label.yml use here. The `-reusable-`
# infix keeps the name off what a caller would naturally pick: a caller that
# declares the SAME group DEADLOCKS its own run, holding the group while its
# `uses:` job waits to acquire it (see the note in ci-groom.yml and
# docs/callers/pr-size.md).
#
# Slot rule: the trigger label AND the `skip-cursor-review` veto label share
# one `trigger` slot, so applying skip-cursor-review mid-flight CANCELS the
# running panel — the Gate's "skip-cursor-review wins" precedence, made true
# for in-flight runs too — and removing it cancels nothing that matters
# before starting a fresh one. Every OTHER label gets its own namespaced
# `label-<name>` slot, so an unrelated label add never kills a running
# review. `format('label-{0}', …)` is what stops a label literally named
# `trigger` (or `Trigger`; group names are case-insensitive) from reaching
# the shared slot.
#
# Non-label events carry an EMPTY `github.event.label.name`, so they fall to
# `label-` and share one slot among themselves. That is deliberate for
# `pull_request_review_thread` on a blocking caller: resolving a thread must
# never cancel a panel. But a `run_without_label` caller STARTS panels from
# plain PR events, so those four actions — and only those four, mirroring the
# Gate's own case list — join `trigger` as well; otherwise a
# synchronize-triggered panel would sit in a slot the veto label cannot
# reach, which is the case this block exists for.
#
# `inputs.review_label != ''` guards the first disjunct because the input is
# `required: false` and a caller CAN pass an empty string. GitHub coerces a
# missing `github.event.label` and `''` alike in a mixed comparison, so
# without the guard every non-label event — `pull_request_review_thread`
# included — would compare EQUAL and join `trigger`, making a thread resolve
# cancel a running panel: the exact case the paragraph above calls impossible.
#
# KNOWN GAP, case. `==` here is case-INSENSITIVE (GitHub expression
# semantics) while the Gate's own test is a case-SENSITIVE shell `=` and its
# veto check a case-sensitive `jq index(...)`. A label that differs from
# `review_label` only in case therefore reaches `trigger` and cancels the
# panel, then no-ops in the Gate — a review destroyed with nothing replacing
# it. Unfixable in an expression (there is no `lower()`, and `contains()` is
# case-insensitive too); it needs a case-matched `review_label`, which is the
# caller's to get right. Reachable only via that misconfiguration.
#
# Cancellation is ASYNCHRONOUS and SLOT-SCOPED, not ordered and total: a
# superseded run keeps unwinding after the new one starts, and only same-slot
# runs are cancelled at all. Anything reasoning about the state a cancelled
# run leaves behind has to allow for both — see the blocking-gate gotchas in
# docs/callers/cursor-review.md for the one place it is observable.
#
# `inputs` is an allowed context in a called workflow's workflow-level
# `concurrency:`, same as the `env:` block below.
group: cursor-review-reusable-${{ github.event.pull_request.number || github.ref }}-${{ ((inputs.review_label != '' && github.event.label.name == inputs.review_label) || github.event.label.name == 'skip-cursor-review' || (inputs.run_without_label && (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && (github.event.action == 'opened' || github.event.action == 'reopened' || github.event.action == 'ready_for_review' || github.event.action == 'synchronize'))) && 'trigger' || format('label-{0}', github.event.label.name) }}
cancel-in-progress: true
# DIFF_SIZE_CAP / REVIEW_LABEL / JUDGE_MODEL / DIFF_EXCLUDES are mapped from
# `inputs` here so the run steps below read them verbatim from the original
# (private-repo) workflow without per-step plumbing. `inputs` is available to
# workflow-level env in a called workflow; `secrets` is not (those stay in jobs).
env:
DIFF_SIZE_CAP: ${{ inputs.diff_size_cap }}
REVIEW_LABEL: ${{ inputs.review_label }}
JUDGE_MODEL: ${{ inputs.judge_model }}
DIFF_EXCLUDES: ${{ inputs.diff_excludes }}
EXTRA_GENERATED_GLOBS: ${{ inputs.extra_generated_globs }}
EXTRA_LOCKFILES: ${{ inputs.extra_lockfiles }}
# Where the assets checkout lands (this repo, .github/cursor-review/*).
CURSOR_REVIEW_ASSETS: ${{ github.workspace }}/_cursor_review_assets/.github/cursor-review
# Cursor CLI pin — a versioned, checksummed artifact instead of the mutable
# cursor.com/install script (BE-5869). Old versions stay downloadable, so a
# Cursor release never breaks this; the pin moves only via a reviewed PR.
# Consumed by .github/cursor-review/install-cursor-cli.sh, the ONE installer
# all three CLI-using jobs run (preflight, review matrix, consolidate).
CURSOR_CLI_VERSION: 2026.10.01-e373342
# sha256 of the linux/x64 agent-cli-package.tar.gz (all jobs run ubuntu-latest).
# Cross-checked against nixpkgs pkgs/by-name/cu/cursor-cli at pin time.
CURSOR_CLI_SHA256: a79726c6e644520e993970be4c45775a6889802b67abe461a677a53219ae28e8
jobs:
gate:
name: Gate
runs-on: ubuntu-latest
permissions:
contents: read
# Also covers `rereview_command`'s read of the PR's conversation
# comments: `issues/{n}/comments` on a PULL REQUEST is authorized by
# Pull requests, not Issues. Do NOT add `issues: read` — a nested job
# cannot exceed its caller's grant, and the documented caller grants
# only `contents` + `pull-requests`, so every caller would fail at
# startup on the pin bump, whether or not it set the command.
pull-requests: read
outputs:
should_run: ${{ steps.check.outputs.should_run }}
already_reviewed: ${{ steps.dup.outputs.already_reviewed }}
approve_author_ok: ${{ steps.author.outputs.approve_author_ok }}
openai_key_present: ${{ steps.openai_key.outputs.present }}
anthropic_key_present: ${{ steps.anthropic_key.outputs.present }}
# Whether the key is USABLE, per lane: usable / unusable / invalid, or
# empty when not probed. See `Probe the direct Anthropic key`.
anthropic_cells_probe: ${{ steps.anthropic_probe.outputs.cells_probe }}
anthropic_cells_probe_reason: ${{ steps.anthropic_probe.outputs.cells_probe_reason }}
anthropic_judge_probe: ${{ steps.anthropic_probe.outputs.judge_probe }}
anthropic_judge_probe_reason: ${{ steps.anthropic_probe.outputs.judge_probe_reason }}
anthropic_fallback_note: ${{ steps.anthropic_probe.outputs.fallback_note }}
steps:
- name: Resolve OPENAI_API_KEY presence
# A boolean for `preflight`, which cannot read the secret itself: it
# follows the caller's `runs_on` pool, and a `secrets.` expression is
# evaluated ON the runner, so even `!= ''` would ship the key there.
# This job is GitHub-hosted and checks out nothing, so the key meets
# no PR-authored code here. Only read when the direct cell is opted in.
id: openai_key
if: inputs.openai_direct_model != ''
env:
OPENAI_KEY_PRESENT: ${{ secrets.OPENAI_API_KEY != '' }}
run: echo "present=${OPENAI_KEY_PRESENT}" >> "$GITHUB_OUTPUT"
- name: Resolve ANTHROPIC_API_KEY presence
# Same as `Resolve OPENAI_API_KEY presence` above, for the direct
# Anthropic cells and the direct judge.
id: anthropic_key
if: inputs.anthropic_direct_model != '' || inputs.judge_direct_model != ''
env:
ANTHROPIC_KEY_PRESENT: ${{ secrets.ANTHROPIC_API_KEY != '' }}
run: echo "present=${ANTHROPIC_KEY_PRESENT}" >> "$GITHUB_OUTPUT"
- name: Resolve the auto-approve author opt-in
# approve_authors, resolved ONCE here so the workflow-level
# `approve_gate` output (which must say `off` on every event, round or
# not) and `Auto-approve decision` read the same answer. Runs on every
# event, before any skip below. `false` when a non-empty list does not
# name the PR author — including a list that names nobody (`,`, `@`):
# a restriction that evaluates empty fails closed. An empty (or
# all-whitespace) list is everyone. No PR author (a non-PR event) leaves
# the output unset, so `approve_gate` keeps its "no round" meaning.
id: author
env:
APPROVE_AUTHORS: ${{ inputs.approve_authors }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
set -f # the list is caller text: no glob expansion of its words
if [ -z "$(printf '%s' "$APPROVE_AUTHORS" | tr -d '[:space:]')" ]; then
echo "approve_authors is empty — no author restriction."
echo "approve_author_ok=true" >> "$GITHUB_OUTPUT"
exit 0
fi
if [ -z "$PR_AUTHOR" ]; then
echo "No PR author on this event — approve_authors not evaluated."
exit 0
fi
author="$(printf '%s' "$PR_AUTHOR" | tr '[:upper:]' '[:lower:]')"
listed=false
for login in $(printf '%s' "$APPROVE_AUTHORS" | tr ',' ' '); do
login="$(printf '%s' "${login#@}" | tr '[:upper:]' '[:lower:]')"
[ -n "$login" ] || continue
if [ "$login" = "$author" ]; then listed=true; fi
done
if [ "$listed" = true ]; then
echo "approve_author_ok=true" >> "$GITHUB_OUTPUT"
else
echo "approve_authors does not list the PR author '$PR_AUTHOR' — auto-approve is off for this PR."
echo "approve_author_ok=false" >> "$GITHUB_OUTPUT"
fi
- name: Check trigger label
id: check
env:
LABEL_NAME: ${{ github.event.label.name }}
PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}
GH_EVENT_ACTION: ${{ github.event.action }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
BASE_REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_NAME: ${{ github.event_name }}
RUN_WITHOUT_LABEL: ${{ inputs.run_without_label }}
PR_AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
SKIP_BOT_PREFIXES: ${{ inputs.skip_bot_branch_prefixes }}
run: |
# PRs from forks can't run this review. The pull_request event grants
# fork PRs no access to secrets — so CURSOR_API_KEY is empty and every
# panel cell fails before submitting output — and a read-only GITHUB_TOKEN, so
# posting the consolidated review returns HTTP 403. The review can
# neither analyze nor post, so skip cleanly instead of burning the
# 8-cell matrix + judge and failing red on every external contribution.
# (head.repo.full_name != github.repository is the cross-repo signal.)
# Under a `pull_request_target` caller this skip is LOAD-BEARING, not
# just a saving: there a fork run DOES get secrets, and the panel runs
# unsandboxed models over the fork's code.
# Fail closed: on a PR event an EMPTY head repo (a deleted fork — its
# code is still on refs/pull/<n>/merge) skips too.
if [ -n "$PR_NUMBER" ] && [ "$HEAD_REPO" != "$BASE_REPO" ]; then
echo "PR is from a fork (${HEAD_REPO:-deleted fork} != $BASE_REPO) — review needs secrets and write access a fork PR can't have. Skipping."
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# skip-cursor-review wins even if the trigger label is also present.
if echo "$PR_LABELS" | jq -e 'index("skip-cursor-review")' > /dev/null; then
echo "skip-cursor-review label present — skipping."
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# Under `pull_request_target` a Dependabot PR's run gets the repo's
# REAL secrets (not the Dependabot store), and the panel would run
# `--trust` agents holding them over upstream-authored content.
if [ "$EVENT_NAME" = "pull_request_target" ] && [ "$PR_AUTHOR" = "dependabot[bot]" ]; then
echo "Dependabot PR under pull_request_target — skipping the panel (it would run with the repo's real secrets)."
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# Machine-generated PRs (bot author AND a configured branch prefix)
# skip the panel: a pinned-SHA bump or a catalog refresh has nothing a
# reviewer can judge, and each one otherwise costs a full matrix run.
# Author TYPE is checked, not just the branch, so a human pushing a
# `ci/bump-…` branch is still reviewed. Configurable per caller via
# skip_bot_branch_prefixes ('' disables).
if [ "$PR_AUTHOR_TYPE" = "Bot" ]; then
for prefix in $SKIP_BOT_PREFIXES; do
case "$HEAD_REF" in
"$prefix"*)
echo "Bot-authored PR ($PR_AUTHOR) on '$HEAD_REF' matches skip prefix '$prefix' — skipping the panel."
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
;;
esac
done
fi
# Label-free mode (run_without_label input): callers in repos with no
# labeling automation opt in to running on plain PR events. Sits
# BELOW the fork skip and skip-cursor-review checks — those still
# veto — and the same-commit dedupe below still prevents re-reviews.
if [ "$RUN_WITHOUT_LABEL" = "true" ]; then
case "$GH_EVENT_ACTION" in
opened|reopened|ready_for_review|synchronize)
echo "run_without_label mode — running on '$GH_EVENT_ACTION'."
echo "should_run=true" >> "$GITHUB_OUTPUT"
exit 0
;;
esac
fi
# Only adding the trigger label fires the matrix. Adding or removing
# the trigger label, and ADDING skip-cursor-review, all resolve to the
# reusable's shared `trigger` concurrency slot (see the workflow-level
# `concurrency:` block), so GitHub has REQUESTED cancellation of any
# in-flight same-slot run for this PR by the time this step decides —
# which is what makes the skip-cursor-review veto above true for a
# panel that is still running, not just for one that has yet to
# start. Requested, not completed: cancellation is asynchronous, so
# the superseded run is still unwinding alongside this one, and it is
# slot-scoped, so a run sitting in a `label-<name>` slot is not
# cancelled at all. Do not add a panel starter outside `trigger` on
# the assumption that this step runs after the field is clear. A
# caller pinned BELOW that commit has only its own label-scoped group,
# which covers the trigger label alone: there, applying
# skip-cursor-review does not stop a running panel.
if [ "$LABEL_NAME" = "$REVIEW_LABEL" ] && [ "$GH_EVENT_ACTION" = "labeled" ]; then
echo "$REVIEW_LABEL label added — running."
echo "should_run=true" >> "$GITHUB_OUTPUT"
exit 0
fi
# Removing skip-cursor-review while the trigger label is present
# unblocks a previously skipped review — treat it as a fresh trigger.
# This event shares the `trigger` concurrency slot too, so a same-slot
# run in flight for this PR has been asked to cancel (asynchronously
# — it may still be unwinding here); the dup check below still covers
# the case where a review COMPLETED at this SHA.
if [ "$LABEL_NAME" = "skip-cursor-review" ] && [ "$GH_EVENT_ACTION" = "unlabeled" ]; then
if echo "$PR_LABELS" | jq -e --arg l "$REVIEW_LABEL" 'index($l)' > /dev/null; then
echo "skip-cursor-review removed while $REVIEW_LABEL is present — running."
echo "should_run=true" >> "$GITHUB_OUTPUT"
exit 0
fi
fi
echo "Label '$LABEL_NAME' is not the trigger label — skipping."
echo "should_run=false" >> "$GITHUB_OUTPUT"
- name: Check for prior review on this commit
id: dup
if: steps.check.outputs.should_run == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
REREVIEW_COMMAND: ${{ inputs.rereview_command }}
AUTO_RETRY_ERRORED: ${{ inputs.auto_retry_errored_rounds }}
# Who fired this event: on a relabel, the identity that applied the
# label. The auto-retry relabels as the same identity decide posted
# its marked block under, so the two logins match (see below).
EVENT_SENDER: ${{ github.event.sender.login }}
run: |
# Idempotency: skip the matrix if a Cursor Review consolidated
# review already exists for this exact HEAD SHA. Protects against
# label remove+re-add (or any other event-replay path) from
# re-running the panel on unchanged content.
#
# Escape hatches:
# - Push commits → new HEAD SHA, check finds nothing, runs.
# - `rereview_command` (below) → an authorized command comment newer
# than the review lets ONE re-labeled run through. Dismissing the
# review is not a hatch: it is posted COMMENTED, which GitHub will
# not dismiss (DISMISSED is still filtered out, for older reviews).
#
# API failure falls through to running, not skipping — better to
# double-review than silently no-op.
#
# The `user.type == "Bot"` term is a permission check, not a tidiness
# one (BE-4691). The consolidated marker is PUBLIC text in a public
# repo, and anyone who can open a PR can submit a review on it — so
# matching the body alone let any user post a body-only review
# carrying the marker and have this step declare the SHA already
# reviewed. That skips the panel, the judge and the post, and under
# `blocking: true` it also waives the gate's fresh-review guard and
# greens a required check over a PR nothing ever looked at. It also
# made the documented remedy for a genuine error review (re-trigger on
# the same SHA) a silent no-op, since that review carries the marker
# too.
#
# Matched on the TYPE rather than a login because the poster is
# caller-configurable: `github-actions[bot]` by default, or whatever
# bot the caller's `bot_app_id` App resolves to — a login this job
# cannot know without minting that token, which is the credential
# split's whole point. `Bot` narrows the set from "every GitHub user"
# to "Apps a repo admin installed here", which is the boundary that
# matters. Residual, accepted: another installed App could post a
# marked review. Closing THAT needs the identity check to move into
# the posting job, where the token exists.
#
# Every page, slurped: the endpoint returns 30 per page oldest-first,
# so on a long-lived PR the newest round is exactly what page 1 drops.
# A failed fetch degrades to "no prior review", as it always has.
REVIEWS=$( { gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/reviews" 2>/dev/null || true; } \
| jq -c -s 'add // []' 2>/dev/null) || REVIEWS='[]'
EXISTING=$(printf '%s' "$REVIEWS" \
| jq --arg sha "$HEAD_SHA" '[.[] | select(.commit_id == $sha and .state != "DISMISSED" and (.user.type == "Bot") and (.body | startswith("## 🔍 Cursor Review — Consolidated panel")))] | length' \
2>/dev/null || echo 0)
# An explicit re-review request overrides the dedupe above, which is
# otherwise ABSOLUTE for a given commit: the only documented escape
# hatches were a new commit or dismissing the existing review, and
# the review this step matches is posted COMMENTED — a state GitHub
# does not let anyone dismiss. So "look again at this same commit"
# had no working path at all, which matters most in exactly the case
# it is wanted: a round that reached no decision because reviewers
# errored, where the code is fine and nothing needs pushing.
#
# The signal is a command comment NEWER than the review it overrides,
# so one request buys exactly one round: the round it triggers posts
# a newer review, and the next run dedupes again. A stale command
# from three rounds ago can never re-fire.
#
# Authorization is the comment's association, the bar `/derisk`
# uses. It is checked HERE rather than trusted from whoever applied
# the label, because the label is how the request arrives and a
# label says nothing about who asked.
#
# Nothing from the comment is echoed: these logs are public and a
# comment body is attacker-authored text.
FORCED=0
case "${REREVIEW_COMMAND:-}" in
*[[:space:]]*)
echo "::warning::rereview_command contains whitespace, so it can never match a comment's first token — use a single token such as /review." ;;
esac
# Two force signals, deliberately separate. A HUMAN asks with
# `rereview_command` and is authorized by the comment's association.
# The workflow's own auto-retry posts no comment at all — it writes
# the marked block below — and must not be able to reach the human
# path, or any App comment could force rounds.
LAST_REVIEW=""
if [ "$EXISTING" -gt 0 ] \
&& { [ -n "${REREVIEW_COMMAND:-}" ] || [ "${AUTO_RETRY_ERRORED:-}" = "true" ]; }; then
LAST_REVIEW=$(printf '%s' "$REVIEWS" \
| jq -r --arg sha "$HEAD_SHA" '[.[] | select(.commit_id == $sha and .state != "DISMISSED" and (.user.type == "Bot") and (.body | startswith("## 🔍 Cursor Review — Consolidated panel"))) | .submitted_at] | max // ""' \
2>/dev/null || echo "")
fi
if [ -n "$LAST_REVIEW" ] && [ -n "${REREVIEW_COMMAND:-}" ]; then
FORCED=$(gh api --paginate "repos/$REPO/issues/$PR_NUMBER/comments" 2>/dev/null \
| jq -s --arg cmd "$REREVIEW_COMMAND" --arg since "$LAST_REVIEW" \
'[.[][] | select(.created_at > $since)
| select(.author_association == "OWNER" or .author_association == "MEMBER" or .author_association == "COLLABORATOR")
| select(((.body // "") | split("\n")[0] // "" | sub("\r$"; "") | sub("^[ \t]+"; "") | sub("[ \t].*$"; "")) == $cmd)] | length' \
2>/dev/null || echo 0)
case "$FORCED" in ''|*[!0-9]*) FORCED=0 ;; esac
fi
# The workflow's own retry. `decide` writes a block carrying
# AUTO_RETRY_MARKER once it has decided to re-run the round, and the
# `auto-retry` job relabels afterwards — so a marked block NEWER than
# the newest consolidated review for this commit IS the request, and
# it buys exactly one round: the round it starts posts a newer
# review, after which the marker is older than that review and counts
# for nothing.
#
# Newer by review `id`, not `submitted_at`: ids increase
# monotonically, while timestamps have one-second precision and decide
# posts its block right after the consolidated review, so the two can
# share a second.
#
# Who may have written it. decide posts under APPROVER_TOKEN when one
# is set — a PAT, so `user.type` is "User" — else under the bot App.
# This job holds neither token, so it cannot learn the approver login
# (the credential split's point). It accepts the block when its author
# is a Bot (the App case, and the residual the dedupe above already
# accepts: another installed App), or when its author is the identity
# that fired THIS event — the PAT case, since `auto-retry` relabels as
# the same identity decide posted under. A human can satisfy the
# second only by relabelling themselves, which already needs label
# write on the repo. The block must also be decide's own shape (it
# starts with the auto-approve marker, and carries the retry marker as
# a line of its own, not quoted inside other text) and not DISMISSED.
#
# What bounds a forged marker is `max_rounds` and who can post one —
# not this check, which counts a request rather than capping retries;
# decide's own one-per-PR budget caps the retries it starts.
#
# The markers are duplicated from auto-approve.py's APPROVE_MARKER
# and AUTO_RETRY_MARKER on purpose — the gate runs before any asset is
# loaded — and a test pins them equal, as the relabel's label constant
# already is.
if [ "$FORCED" -eq 0 ] && [ -n "$LAST_REVIEW" ] && [ "${AUTO_RETRY_ERRORED:-}" = "true" ]; then
LAST_REVIEW_ID=$(printf '%s' "$REVIEWS" \
| jq -r --arg sha "$HEAD_SHA" '[.[] | select(.commit_id == $sha and .state != "DISMISSED" and (.user.type == "Bot") and (.body | startswith("## 🔍 Cursor Review — Consolidated panel"))) | .id | numbers] | max // 0' \
2>/dev/null || echo 0)
case "$LAST_REVIEW_ID" in ''|*[!0-9]*) LAST_REVIEW_ID=0 ;; esac
RETRIED=$(printf '%s' "$REVIEWS" \
| jq --arg sha "$HEAD_SHA" --argjson since "$LAST_REVIEW_ID" \
--arg sender "${EVENT_SENDER:-}" \
--arg approve '<!-- cursor-review-auto-approve -->' \
--arg marker '<!-- cursor-review-auto-retry -->' \
'[.[] | select(.commit_id == $sha and .state != "DISMISSED" and ((.id // 0) | numbers) > $since and ((.user.type == "Bot") or ($sender != "" and (.user.login // "") == $sender)) and ((.body // "") | startswith($approve)) and ((.body // "") | split("\n") | any(. == $marker)))] | length' \
2>/dev/null || echo 0)
case "$RETRIED" in ''|*[!0-9]*) RETRIED=0 ;; esac
if [ "$LAST_REVIEW_ID" -gt 0 ] && [ "$RETRIED" -gt 0 ]; then
FORCED=1
echo "An automatic retry was requested after the last round — proceeding."
fi
fi
if [ "$EXISTING" -gt 0 ] && [ "$FORCED" -eq 0 ]; then
echo "Already reviewed at $HEAD_SHA ($EXISTING existing review(s)) — skipping matrix."
echo "already_reviewed=true" >> "$GITHUB_OUTPUT"
elif [ "$EXISTING" -gt 0 ]; then
echo "Already reviewed at $HEAD_SHA, but an authorized re-review was requested after that review — proceeding."
echo "already_reviewed=false" >> "$GITHUB_OUTPUT"
else
echo "No prior review for $HEAD_SHA — proceeding."
echo "already_reviewed=false" >> "$GITHUB_OUTPUT"
fi
- name: Probe the direct Anthropic key
# Presence is not usability: a key whose organization hit its usage
# limit (an HTTP 400 naming the reset time), ran out of credit, or was
# revoked fails every direct cell and the direct judge, and the round
# ends with no decision. One 1-token Messages call per configured model
# tells, so `preflight` can treat an UNUSABLE key exactly like an absent
# one (the Cursor cells and the Cursor judge run). An unknown model id
# (a 404) is `invalid` — preflight fails the run on it, never falls
# back on a typo — except a dash-free Claude Code alias (`opus`), which
# the CLI resolves and the raw API does not: that one is not probed.
# 429 / 529 / 5xx / no answer are retried, then read as unusable, as is
# any other refusal (an unrecognised 4xx; a redirect, never followed).
# Here, not in `preflight`, for the reason the presence steps above
# give: this job is GitHub-hosted and checks out nothing. Only for a
# round that will run. The script is byte-identical to
# cursor-axis-base.yml's `Probe the direct Anthropic key` (a test pins
# it); it never prints the key or any header. Best effort: a crash
# here leaves the outputs empty, which preflight reads as "not probed".
id: anthropic_probe
if: steps.check.outputs.should_run == 'true' && steps.dup.outputs.already_reviewed != 'true' && steps.anthropic_key.outputs.present == 'true'
continue-on-error: true
# Two models at worst: 2 x (3 x 20 s + 60 s) = 4 minutes; the script
# stops retrying at PROBE_BUDGET_SECONDS, and writes every output in
# one go at the end, so a timeout here still leaves none.
timeout-minutes: 5
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
ANTHROPIC_PROBE_URL: https://api.anthropic.com/v1/messages
PROBE_RETRY_DELAYS: '15 45'
PROBE_BUDGET_SECONDS: '240'
PROBE_LANES: cells judge
PROBE_MODEL_CELLS: ${{ inputs.anthropic_direct_model }}
PROBE_MODEL_JUDGE: ${{ inputs.judge_direct_model }}
run: |
python3 -I - <<'PY'
import json, os, re, time, urllib.error, urllib.request
KEY = os.environ.get("ANTHROPIC_API_KEY", "")
DELAYS = [int(d) for d in os.environ.get("PROBE_RETRY_DELAYS", "").split()]
# `timeout=` bounds each socket operation, not a request, so the retries
# also stop at this wall-clock budget, inside the step's timeout-minutes.
DEADLINE = time.monotonic() + float(os.environ.get("PROBE_BUDGET_SECONDS") or "inf")
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""A redirect would carry x-api-key to another URL: refuse it (a 3xx)."""
def redirect_request(self, *args, **kwargs):
return None
OPENER = urllib.request.build_opener(NoRedirect)
def clean(text):
"""One printable line of API text, the key redacted, bounded."""
text = str(text)
if KEY:
text = text.replace(KEY, "***")
return re.sub(r"[^\x20-\x7e]+", " ", text).strip()[:300]
def call(model):
"""(status or None, error type, error message) for one request."""
body = json.dumps({"model": model, "max_tokens": 1,
"messages": [{"role": "user", "content": "ping"}]}).encode()
request = urllib.request.Request(
os.environ["ANTHROPIC_PROBE_URL"], data=body, method="POST",
headers={"x-api-key": KEY, "anthropic-version": "2023-06-01",
"content-type": "application/json"})
try:
with OPENER.open(request, timeout=20) as response:
return response.status, "", ""
except urllib.error.HTTPError as e:
# Only the JSON body is read: never the headers, never str(e).
try:
error = json.loads(e.read(65536).decode("utf-8", "replace")).get("error") or {}
except Exception: # a truncated body (IncompleteRead) included
error = {}
if not isinstance(error, dict):
error = {}
return e.code, clean(error.get("type", "")), clean(error.get("message", ""))
except Exception as e: # no answer, or a broken one: never a crash mid-loop
return None, "", clean(f"no answer ({type(e).__name__})")
def classify(status, etype, message):
"""usable / unusable / invalid / retry, and the reason class."""
lowered = message.lower()
if status is not None and 200 <= status < 300:
return "usable", "ok"
if status == 402 or etype == "billing_error" or "credit balance" in lowered:
return "unusable", "billing"
if status == 400 and "usage limit" in lowered:
return "unusable", "usage-limit"
# An unknown id is a 404 `not_found_error`. A 400 is never read as
# one: its text is a guess ("invalid max_tokens for this model").
if status == 404 or etype == "not_found_error":
return "invalid", "unknown-model"
if status in (401, 403):
return "unusable", "unauthorized"
if status is None or status in (408, 429) or status >= 500:
return "retry", "unavailable"
# Any other refusal (an unrecognised 4xx, a refused redirect) is
# unusable too: the direct lane would get the same answer.
return "unusable", f"http-{status}"
def probe(model):
for attempt in range(len(DELAYS) + 1):
status, etype, message = call(model)
verdict, reason = classify(status, etype, message)
print(f"probe {model}: attempt {attempt + 1} -> HTTP {status or '-'} ({reason})")
if verdict != "retry":
break
if attempt == len(DELAYS) or time.monotonic() + DELAYS[attempt] > DEADLINE:
verdict = "unusable" # still unavailable, out of retries or time
break
time.sleep(DELAYS[attempt])
# Only the reason class, and a usage limit's reset time, leave this
# step: the review, annotations and summaries are world-readable on a
# public repo, and an API message can name the organization (a 429)
# or its credit state.
detail = reason
reset = re.search(r"\d{4}-\d{2}-\d{2}(?:T| at )\d{2}:\d{2}(?::\d{2})?(?: ?UTC|Z)?", message)
if reset:
detail = f"{reason}: access returns {reset.group(0)}"
if verdict == "invalid" and "-" not in model:
# A CLI model alias (`opus`, `sonnet`, `opusplan`): the lanes'
# `--model` resolves it, the raw API does not. Not probed.
return "", f"{reason}: an alias, not probed"
return verdict, detail
results, fallen, lines = {}, [], []
for lane in os.environ.get("PROBE_LANES", "").split():
model = os.environ.get(f"PROBE_MODEL_{lane.upper()}", "")
if not re.fullmatch(r"[A-Za-z0-9._-]{1,100}", model):
continue # unset, or not a plain id: the consumer warns
if model not in results:
results[model] = probe(model)
verdict, detail = results[model]
lines.append(f"{lane}_probe={verdict}\n{lane}_probe_reason={detail}\n")
if verdict == "unusable":
fallen.append((lane, detail))
if fallen:
# One shared reason reads once; lanes that failed differently
# (two models: billing vs. unavailable) each carry their own.
if len({detail for _, detail in fallen}) == 1:
lanes = ", ".join(lane for lane, _ in fallen)
note = f"({fallen[0][1]}), so these lanes ran on Cursor: {lanes}."
else:
note = "so these lanes ran on Cursor: " + "; ".join(
f"{lane} ({detail})" for lane, detail in fallen) + "."
lines.append(f"fallback_note=The direct Anthropic key was unusable this run {note}\n")
# One write, at the end: a probe that dies midway leaves every lane
# unprobed, never one lane decided and the other (or the note) missing.
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as out:
out.write("".join(lines))
PY
ledger:
# Prior-review ledger: what earlier rounds already raised on THIS PR, and how
# the author answered. Without it every round re-derives the PR from zero, so
# a finding refuted/declined/deferred in round 1 comes back in rounds 2 and 3
# and the author hand-writes the same rebuttal again. A dedupe filter can't
# fix that — the judge rewrites each finding's prose every round, so a true
# repeat pair scores LOWER on text similarity than two unrelated findings on
# the same file. The prior context has to enter the prompt.
#
# One fetch, nine consumers: the 8 review cells and consolidate all download
# the `cursor-review-ledger` artifact this job publishes.
#
# This job must never fail the run — the review matrix `needs:` it, so a hard
# failure here would skip the whole panel. Every step is continue-on-error
# and a fallback guarantees the artifact exists, degrading to status=unknown
# (which is reported, never silently reported as `empty`).
name: Prior-review ledger
needs: gate
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true'
runs-on: ubuntu-latest
# Deliberately longer than the per-step timeouts below: a hung step must
# trip its OWN timeout (which continue-on-error absorbs) rather than the
# job's, because a FAILED job here would skip the entire review matrix.
timeout-minutes: 20
permissions:
contents: read
pull-requests: read
outputs:
status: ${{ steps.build.outputs.status || steps.fallback.outputs.status }}
rounds: ${{ steps.build.outputs.rounds || steps.fallback.outputs.rounds }}
last_reviewed_sha: ${{ steps.build.outputs.last_reviewed_sha }}
# The merge base the LAST round recorded in its own review (BE-15598), read back
# out of the round sentinel. The `incremental` step in `diff-size` builds its OLD
# patch against exactly this commit, and skips the block outright when it is empty
# — there is no fallback to the current base, which is what made a retargeted PR
# drop hunks the panel had never seen. Like `last_reviewed_sha` this has no
# fallback-step reading: a degraded ledger legitimately records nothing.
last_reviewed_merge_base: ${{ steps.build.outputs.last_reviewed_merge_base }}
steps:
- name: Resolve the asset ref
# This job must never fail (see the job comment), so the fail-closed
# `Require a pinned workflows_ref` guard the other jobs run is not an
# option here. Resolve the ref in a step that can only WARN instead, and
# let the checkout below skip itself when there is nothing safe to check
# out. Skipping is safe by construction: the `Build prior-review ledger`
# step then fails under its `continue-on-error: true`, and the
# `Ensure ledger artifact exists` fallback publishes status=unknown — the
# already-designed degraded path, reported rather than silently `empty`.
#
# The fallback is `job.workflow_sha` — the commit THIS reusable workflow
# was resolved from via the caller's `uses:` pin — so an omitted
# `workflows_ref` still pins to an immutable SHA, never to this repo's
# moving default branch. It is NOT `github.job_workflow_sha`, which this
# step used to read: that is an OIDC token claim, not a `github` context
# property, so Actions expanded it to '' and `actions/checkout` read
# `ref: ''` as "the default branch" — the exact hole the comment here
# claimed to close (BE-8077). `job.workflow_sha` is the `job`-context
# accessor added in runner v2.334.0 (Apr 2026); `ubuntu-latest` is always
# current, so only a stale self-hosted runner reaches the warn branch.
# (actionlint <= 1.7.12 false-positives on it — its `job`-context schema
# predates that runner release; nothing here runs actionlint.)
id: resolve_ref
continue-on-error: true
# Every step in this job is time-boxed BELOW the job's own
# `timeout-minutes` on purpose (see the job comment): a hung step must
# trip its own timeout, which continue-on-error absorbs, rather than the
# job's, which would fail the job and skip the whole review matrix.
timeout-minutes: 2
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref || job.workflow_sha }}
# The `uses:` commit on its own, WITHOUT the fallback above, so the
# cross-check at the end of the script has something to compare
# against. Bound here rather than interpolated into the script body,
# like every other value this workflow reads.
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# Bracket RANGES (`A-Z`) match by COLLATION order, so under a glibc
# locale such as en_US.UTF-8 they also match accented letters and the
# negated class below quietly stops rejecting them. Pin the byte order.
export LC_ALL=C
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here — and JS `trim()` strips U+00A0/U+FEFF that POSIX
# `[:space:]` leaves alone, so stripping cannot be how this decides.
# Nor can it emit a stripped value: `tr -d` removes INTERIOR whitespace
# too, so `a b` would be silently rewritten into the different-but-real
# ref `ab` instead of being rejected. Validate the SHAPE and emit the
# value UNTOUCHED. The class is deliberately narrower than git's own
# ref rules (which also permit `(`, `)`, `,`, `%` and UTF-8) — a policy
# restriction, not a validity claim — and it keeps out every Unicode
# space and every newline that could smuggle a ::workflow command::
# into the log or into $GITHUB_OUTPUT. Anything outside it resolves to
# the empty output that skips the checkout below.
REF="$WORKFLOWS_REF"
case "$REF" in
*[!A-Za-z0-9._/@+-]*) REF='' ;;
esac
if [ -z "$REF" ]; then
echo "::warning::Could not resolve a usable ref for the cursor-review assets: either the workflows_ref input is empty AND job.workflow_sha resolved to '' (which needs an Actions runner older than v2.334.0), or the value contains characters outside the set this workflow accepts (A-Z a-z 0-9 . _ / - @ +) — a deliberate policy restriction, narrower than git's own ref rules. Skipping the asset checkout rather than silently loading them from this repo's default branch — the prior-review ledger degrades to status=unknown for this run. Set workflows_ref: to the same commit SHA the caller's uses: line pins."
fi
# Warn-only cross-check — the counterpart of the fail-closed equality
# test the guarded jobs run. This job must never fail (see the job
# comment), so a mismatch cannot `exit` here. It is reported anyway
# because the ledger is where the signal would otherwise be invisible:
# this job runs for every caller, including one whose guarded jobs all
# skip, so its run log can be the only place a split pin is recorded.
#
# $REF is the right left-hand side even though it carries the
# `|| job.workflow_sha` fallback: when the input was omitted it IS
# WORKFLOW_SHA, so it cannot differ, and a difference therefore means
# the caller passed a workflows_ref naming a different commit than its
# `uses:` line. An unusable input has already been rewritten to '' and
# warned about above, so skip it here rather than warn twice; an empty
# $SHA means a runner older than v2.334.0, which cannot be checked at
# all. Lower-cased on both sides, like the guarded jobs' copy of this
# test: hex is case-insensitive, so an upper-case pin naming the same
# commit is not a difference. $REF itself stays untouched — it is the
# value the checkout below consumes. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -n "$REF_LC" ] && [ -n "$SHA" ] && [ "$REF_LC" != "$SHA" ]; then
echo "::warning::workflows_ref ($REF) differs from job.workflow_sha ($SHA); the prior-review ledger is being read with assets from a different commit than the workflow. Set the uses: pin and workflows_ref to the same commit."
fi
echo "ref=$REF" >> "$GITHUB_OUTPUT"
- name: Load cursor-review assets
# Skipped when the ref could not be resolved — see `resolve_ref` above.
if: steps.resolve_ref.outputs.ref != ''
continue-on-error: true
timeout-minutes: 5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ steps.resolve_ref.outputs.ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Build prior-review ledger
id: build
continue-on-error: true
timeout-minutes: 8
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
LEDGER_ENABLED: ${{ inputs.ledger_prior_review }}
run: |
mkdir -p /tmp/ledger
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" build \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--pr-author "$PR_AUTHOR" \
--out-dir /tmp/ledger \
--enabled "$LEDGER_ENABLED"
- name: Ensure ledger artifact exists
id: fallback
if: always()
run: |
# The build step handles its own fetch failures (status=unknown). This
# covers the harder failure — the checkout or the interpreter itself
# died — so the downstream download always finds a well-formed ledger
# and the review body still tells the reader context was missing.
mkdir -p /tmp/ledger
if [ -f /tmp/ledger/ledger.json ]; then
exit 0
fi
echo '{"status": "unknown", "rounds": 0, "total_rounds": 0, "entries": [], "entry_count": 0, "unanswered_count": 0, "failed_call": "ledger job", "reason": "the ledger step did not produce an output file (see the job log)"}' > /tmp/ledger/ledger.json
: > /tmp/ledger/ledger.md
: > /tmp/ledger/ledger-judge.md
printf '%s' "⚠️ prior-review context unavailable (ledger job: the ledger step did not produce an output file) — findings may repeat earlier rounds." > /tmp/ledger/ledger-note.txt
{
echo "status=unknown"
echo "rounds=0"
} >> "$GITHUB_OUTPUT"
echo "::warning::Prior-review ledger step produced no output — running without prior-round context."
- name: Upload ledger artifact
if: always()
# continue-on-error like every other step in this job, for the reason in
# the job comment: `review` needs this job and has no always() guard, and
# `consolidate` then drops out on `needs.review.result != 'skipped'`. An
# artifact-upload hiccup failing THIS job would therefore post no review
# at all — strictly worse than the degraded path, where the panel simply
# runs without prior context and the review body says so (the consumers
# of the artifact all download it continue-on-error, and consolidate
# emits the unavailable banner when the file does not arrive).
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: cursor-review-ledger
path: /tmp/ledger
if-no-files-found: error
retention-days: 7
round-cap:
# Per-PR review-round cap (inputs.max_rounds). Runs ahead of the panel on
# every fresh round — `diff-size`, and through it everything that spends,
# `needs:` it — and decides `capped`. Counting needs the POSTING identity's
# login (a body match alone would let any user burn a PR's rounds with a
# marker-carrying review), and that login is only known after the bot token
# is minted, so this is a write-token job: it checks out NO PR code, only
# this repo's assets at the pinned `workflows_ref`, and stays on
# GitHub-hosted ubuntu-latest. The logic lives in auto-approve.py's
# `round-cap`, which fails OPEN on a read error (the panel runs).
name: Round cap
needs: gate
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
pull-requests: write
env:
# `secrets` cannot be read in `if:`, so the credentials-present test is
# evaluated here — the same guard over-cap-comment uses. An app id without
# its key is a permitted config and must not take the panel down.
BOT_CONFIGURED: ${{ inputs.bot_app_id != '' && secrets.BOT_APP_PRIVATE_KEY != '' }}
outputs:
capped: ${{ steps.cap.outputs.capped }}
labelled: ${{ steps.cap.outputs.labelled }}
rounds: ${{ steps.cap.outputs.rounds }}
next_round: ${{ steps.cap.outputs.next_round }}
max_rounds: ${{ steps.cap.outputs.max_rounds }}
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Mint bot-identity token (optional)
id: bot_token
if: ${{ env.BOT_CONFIGURED == 'true' && inputs.max_rounds > 0 }}
# Best-effort: a failed mint degrades to github-actions[bot] below rather
# than failing this job, which `diff-size` (and so the panel) hangs off.
# The count then matches no bot-posted round and fails open.
continue-on-error: true
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
- name: Count review rounds
id: cap
if: ${{ inputs.max_rounds > 0 }}
env:
# The identity post-review posts under: the bot when configured, else
# github-actions[bot]. Its reviews are the rounds, and its token writes
# the label and the comment.
GH_TOKEN: ${{ steps.bot_token.outputs.token || secrets.GITHUB_TOKEN }}
APP_SLUG: ${{ steps.bot_token.outputs.app-slug }}
MAX_ROUNDS: ${{ inputs.max_rounds }}
THRESHOLD: ${{ inputs.approve_max_severity }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
run: |
if [ -n "$APP_SLUG" ]; then LOGIN="${APP_SLUG}[bot]"; else LOGIN="github-actions[bot]"; fi
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" round-cap \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--max-rounds "$MAX_ROUNDS" \
--threshold "$THRESHOLD" \
--poster-login "$LOGIN"
diff-size:
name: Diff size check
# Needs `ledger` (not just `gate`) so it can build the incremental
# "hunks new since the last reviewed round" diff here too, alongside the
# main reviewed diff — one checkout, one artifact, instead of every panel
# cell (plus consolidate) re-deriving it from its own PR checkout.
# `round-cap` is the panel's off switch: every job that spends hangs off this
# one, so a capped PR (or a red cap job) runs no panel at all.
needs: [gate, ledger, round-cap]
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.round-cap.outputs.capped != 'true'
runs-on: ${{ fromJSON(inputs.runs_on || '"ubuntu-latest"') }}
permissions:
contents: read
# within_cap is derived from the shared check-pr-size tool's `over_cap`
# output: counted = non-generated changed lines (minus any comment/blank
# discount), compared against the review cap passed as --max. Failure
# handling is explicit and two-tier (see the classify step): a git-level
# failure fails THIS JOB — fail closed, no review — while a tool-level
# failure falls back to the RAW changed-line count with no exclusions
# (strictly >= the classified count), so a degraded run can still review a
# small PR but can never feed an unbounded diff to the panel.
outputs:
within_cap: ${{ steps.check.outputs.over_cap != 'true' }}
# The counted total behind that verdict, so the over-cap comment can name
# the number the author has to get under. Written by the tool on the
# normal path and by the raw-count fallback below on the degraded one, so
# it always agrees with whichever count actually decided `over_cap`.
counted: ${{ steps.check.outputs.counted }}
# Whether that count came from the raw-numstat fallback (classifier tool
# failed) rather than the classifier. The over-cap comment needs it to
# describe the number honestly: on the degraded path NOTHING was excluded,
# so calling it "after generated-file exclusion" would send an author
# hunting for a lockfile that was, in fact, counted.
degraded: ${{ steps.check.outputs.degraded }}
# Whether the incremental "hunks new since last round" block really was
# the subset of the reviewed diff the prompt calls it (BE-15558).
# `true` both when the block passed the fail-safe and when there is no
# block at all (round 1, an unresolvable last-reviewed SHA, an over-cap
# run where this step never ran) — in none of those cases was anything
# dropped. `false` ONLY when the fail-safe fired and discarded a block
# that had been built, which is the one case a panel-integrity signal
# should report. Written with `!= 'false'` rather than read straight
# through so the skipped-step empty string reads as `true`, not `''`.
incremental_subset: ${{ steps.incremental.outputs.incremental_subset != 'false' }}
# What the incremental block IS, for approve_scope (auto-approve.py
# resolve_scope): `none` (no usable last-reviewed SHA — round 1, or a re-run
# on the same head), `built` (verified; EMPTY on a pure rebase),
# `unavailable` (a later round whose block could not be built) or
# `discarded` (the fail-safe threw it away). A skipped step reads as
# `unavailable`, which fails closed to `full`.
incremental_state: ${{ steps.incremental.outputs.incremental_state || 'unavailable' }}
# The merge base THIS round's reviewed diff was taken against — the exact left
# tree `check-pr-size` resolves `BASE_SHA...HEAD_SHA` to. Consumed by `post-review`
# (BE-15598), which writes it into the consolidated review's round sentinel so the
# NEXT round can rebuild "what the panel already saw" against this tree rather than
# recomputing a merge base from a base that may have moved since (a retarget, a
# base-branch rewrite). Empty when git could not resolve it, which the next round
# reads as "no recorded merge base" and fails closed to no incremental block.
merge_base_sha: ${{ steps.merge_base.outputs.merge_base_sha }}
steps:
- name: Checkout PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
# The head commit and its tree, nothing else. This used to be
# a full-history clone — every branch and tag of the consumer, ~2 min per
# round on a large monorepo, on the review's critical path. The
# BASE...HEAD three-dot diff, the tool's base-ref reads
# (linguist-generated via `check-attr --source`, deleted-file blob
# fallbacks) and the incremental block need only BASE, HEAD, their
# merge base, and the last-reviewed commits; "Fetch the base commit
# and the merge-base history" below fetches exactly that, with the
# same shared script pr-size.yml uses.
fetch-depth: 1
persist-credentials: false
ref: ${{ github.event.pull_request.head.sha }}
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load check-pr-size tool
# The SAME classifier the PR-size cap uses — the single source of truth
# for "what is codegen". Comes from THIS repo (public, pinned via
# workflows_ref), never the PR checkout, so a malicious PR can't rewrite
# the logic that decides which of its files skip review.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _pr_size_tool
persist-credentials: false
- name: Fetch the base commit and the merge-base history
# The other half of the narrowed checkout above (pr-size.yml's BE-8940
# fetch, from the ONE script both workflows call). Fails this job — fail
# closed, no review — when BASE/HEAD cannot be fetched or no trustworthy
# merge base exists, with an error naming which. The last-reviewed head
# and its recorded merge base ride along best-effort so the incremental
# block's ancestry checks are answered from a graph that can vouch for
# them; neither is ever fatal here. The script comes from the pinned
# checkout of THIS repo, never the PR's.
env:
# The job's own read-only token (`permissions: contents: read`),
# handed to git through GIT_CONFIG_* env for this step only — never
# written to `.git/config`.
FETCH_TOKEN: ${{ github.token }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
LAST_REVIEWED_SHA: ${{ needs.ledger.outputs.last_reviewed_sha }}
LAST_REVIEWED_MERGE_BASE: ${{ needs.ledger.outputs.last_reviewed_merge_base }}
run: |
bash _pr_size_tool/scripts/check-pr-size/fetch-history.sh \
"$LAST_REVIEWED_SHA" "$LAST_REVIEWED_MERGE_BASE"
- name: Resolve this round's merge base
# Recorded in the consolidated review by `post-review`, and read back by the
# NEXT round to pin the OLD side of its incremental block (BE-15598). Plain
# shell rather than a check-pr-size output on purpose: the tool does resolve
# the same commit internally, but it is skipped entirely on the degraded
# raw-numstat fallback path, and a round that records no merge base costs the
# NEXT round its whole incremental block. This step runs on both paths.
#
# Best-effort by construction — it must never fail the job. `git merge-base`
# exits non-zero when the two commits share no history (an unrelated-histories
# base), and there is
# nothing to do about that except record nothing and say so.
id: merge_base
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
#
# No line-break guard on the value, unlike `resolveMergeBase` in
# scripts/check-pr-size/main.go, which rejects a result containing \r or \n. The
# divergence is deliberate, not an oversight: `git merge-base` with two commits
# and no --all prints exactly ONE line, and `$( )` strips every trailing newline
# off it, so there is no value this step can emit that the Go check would refuse.
# post-review.py's `field()` re-validates the shape before it reaches the
# sentinel besides, and build-ledger.py's `_FULL_SHA_RE` again on the way back.
run: |
MERGE_BASE="$(git merge-base "$BASE_SHA" "$HEAD_SHA" 2>/dev/null || true)"
if [ -n "$MERGE_BASE" ]; then
echo "Round merge base: ${MERGE_BASE}"
else
echo "::warning::Could not resolve the merge base of ${BASE_SHA} and ${HEAD_SHA} — this round records none, so the next round will skip its incremental diff block rather than diff against the wrong tree."
fi
echo "merge_base_sha=${MERGE_BASE}" >> "$GITHUB_OUTPUT"
- name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: _pr_size_tool/scripts/check-pr-size/go.mod
# Dependency-free module (no go.sum) — nothing to cache.
cache: false
- name: Build check-pr-size
env:
# See pr-size.yml: the tool is checked out UNDER the consumer repo's
# checkout, so a root go.work would otherwise refuse the build. The
# tool is dependency-free; disable workspace mode and build standalone.
# Quoted "off" — unquoted off is coerced to GOWORK=false by the Actions
# YAML parser, which Go then rejects as a bad workspace-file path.
GOWORK: "off"
run: |
# Drop anything the PR checkout could have pre-seeded under the tool
# path so the build compiles only the pinned sources.
git -C _pr_size_tool clean -ffdx
(cd _pr_size_tool/scripts/check-pr-size && go build -o "${RUNNER_TEMP}/check-pr-size" .)
- name: Classify generated files, check size, and build reviewed diff
id: check
env:
# This is the current target-branch tip, not necessarily the commit
# the PR forked from. check-pr-size resolves BASE_SHA + HEAD_SHA to
# their merge base once and uses that commit for both classification
# and the reviewed patch, so later main-only commits never enter an
# unrebased PR's review.
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
# Read by the tool's --ignore-comments default: discount blank/comment
# lines from the counted total (count-only; the reviewed diff keeps them).
PR_SIZE_IGNORE_COMMENTS: ${{ inputs.ignore_comments }}
run: |
# Reuse the PR-size classifier as the single source of truth. --max is
# THIS review's cap (DIFF_SIZE_CAP), so the tool's `over_cap` output
# means "non-generated changed lines exceed the review cap" — exactly
# the gate we want. --mode warn: the tool never exits non-zero on
# overage (this workflow gates via within_cap, not the tool's own
# pass/fail). The same run writes the reviewed diff (the PR's patch
# with every generated file's section filtered out, minus any caller
# diff_excludes pathspecs) to --reviewed-diff-out, so classification
# happens ONCE and the count and the reviewed diff can never disagree.
# Filtering the patch — instead of expanding one exclude pathspec per
# generated file onto argv — means an unbounded number of generated
# files (they cost nothing against the cap) can't overflow ARG_MAX.
#
# --marker-from-base: this classification decides what a (potentially
# blocking) review SEES, so the Go generated marker is honored only
# from the BASE blob — a PR can't hide hand-written code from the
# panel by prepending the one-line marker. Matches the base-ref
# invariant the linguist-generated attribute path already enforces.
#
# Failure handling is two-tier, both explicit:
# - git-level breakage (bad ref, missing history): the fallback
# `git diff --numstat` below dies under `set -e` and FAILS this
# job — fail closed, a loud red X, never a silent skip.
# - tool-level failure (classifier bug, patch-write error): fall
# back to the RAW changed-line count with no exclusions —
# strictly >= the classified count, so a degraded run still
# reviews a small PR but can never feed an unbounded diff to the
# panel jobs. The next step rebuilds the diff with
# diff_excludes only (the pre-classifier behavior).
rc=0
"${RUNNER_TEMP}/check-pr-size" \
--base "${BASE_SHA}" \
--head "${HEAD_SHA}" \
--max "${DIFF_SIZE_CAP}" \
--mode warn \
--marker-from-base \
--extra-generated-globs "${EXTRA_GENERATED_GLOBS}" \
--extra-lockfiles "${EXTRA_LOCKFILES}" \
--diff-excludes "${DIFF_EXCLUDES}" \
--reviewed-diff-out "${RUNNER_TEMP}/pr-diff.patch" || rc=$?
if [ "$rc" -eq 0 ]; then
if [ -f "${RUNNER_TEMP}/pr-diff.patch" ]; then
echo "Reviewed diff size: $(wc -l < "${RUNNER_TEMP}/pr-diff.patch") lines"
fi
else
echo "::warning::check-pr-size exited ${rc} — gating on the raw line count and reviewing with no generated-file exclusions (diff_excludes still apply)."
rm -f "${RUNNER_TEMP}/pr-diff.patch"
echo "degraded=true" >> "$GITHUB_OUTPUT"
# Raw-count gate: no exclusions, so always >= the classified count.
# Appended after any over_cap the tool already wrote — the last
# value wins, so a raw overage can only tighten the gate. The
# numstat runs as its own statement (not inside a pipeline, whose
# exit status `set -e` would ignore) so git-level breakage fails
# the job here (fail closed, above).
git diff --numstat "${BASE_SHA}...${HEAD_SHA}" > "${RUNNER_TEMP}/raw-numstat"
RAW=$(awk '{ if ($1 != "-") total += $1; if ($2 != "-") total += $2 } END { print total + 0 }' "${RUNNER_TEMP}/raw-numstat")
echo "Raw changed lines (no exclusions): ${RAW} (cap: ${DIFF_SIZE_CAP})"
# Same last-value-wins append as over_cap below: whichever count
# decided the gate is the one the skip notice must quote. Without
# this the tool's pre-crash `counted` (or nothing at all) would be
# reported next to a verdict the RAW count actually made.
echo "counted=${RAW}" >> "$GITHUB_OUTPUT"
if [ "${RAW}" -gt "${DIFF_SIZE_CAP}" ]; then
echo "over_cap=true" >> "$GITHUB_OUTPUT"
fi
fi
- name: Announce over-cap skip
# The over-cap path used to run NOTHING: every downstream job is gated
# on within_cap, the tool runs in --mode warn (never non-zero), so the
# whole run went green with no review and no signal — indistinguishable
# from "the panel reviewed this and found nothing" (BE-7646). This
# annotation + summary is the credential-free half of the signal, so it
# reaches Dependabot PRs (whose runs read the Dependabot secret store,
# not Actions secrets) and any consumer whose comment write fails. NOT
# fork PRs: `gate` sets should_run=false for a cross-repo head before
# this job runs at all, so an over-cap fork PR reaches neither half of
# the signal — it is skipped for being a fork first.
if: steps.check.outputs.over_cap == 'true'
env:
COUNTED: ${{ steps.check.outputs.counted }}
run: |
# `counted` is written on both paths above, but a tool that died
# before writing outputs AND left the raw count within the cap can
# still leave it empty while over_cap came from elsewhere — say
# "unknown" rather than render an empty number as fact.
COUNTED_TEXT="${COUNTED:-unknown}"
echo "::warning::Cursor review SKIPPED — counted ${COUNTED_TEXT} changed lines exceeds diff_size_cap=${DIFF_SIZE_CAP}. This PR gets no review panel. Split the PR or reduce the counted diff."
{
echo "## ⚠️ Cursor review skipped (over cap)"
echo "Counted ${COUNTED_TEXT} changed lines > cap ${DIFF_SIZE_CAP} — no panel ran."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build reviewed diff (degraded fallback)
# Only when the classifier tool failed but the raw count is within the
# cap: no generated-file exclusions are available, so build the diff
# with just the caller's diff_excludes (the pre-classifier behavior).
# The raw-count gate above already bounded this diff's size.
if: steps.check.outputs.over_cap != 'true' && steps.check.outputs.degraded == 'true'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
# $DIFF_EXCLUDES is intentionally unquoted so bash word-splits it into
# pathspec args.
# shellcheck disable=SC2086
git diff "${BASE_SHA}...${HEAD_SHA}" -- . $DIFF_EXCLUDES \
> "${RUNNER_TEMP}/pr-diff.patch"
echo "Reviewed diff size: $(wc -l < "${RUNNER_TEMP}/pr-diff.patch") lines"
- name: Build incremental diff since last review
# The subset of the reviewed diff that changed since the last reviewed
# round — PRIORITIZATION, not narrowing, the full diff above stays the
# primary input; this just tells the panel where to spend budget. Built
# here (this job already holds the fetched history) so it can
# ride the same shared artifact instead of every consumer re-deriving it.
# Best-effort: an unresolvable SHA (force-push, base-branch rewrite)
# simply produces no incremental block.
#
# It is built by DIFFING TWO PR PATCHES, never a commit range (BE-15558).
# `git diff LAST_REVIEWED...HEAD` looks like the obvious formulation and
# is wrong: when HEAD is a merge commit that pulled the base branch into
# the branch, LAST is an ancestor of HEAD, the merge base of the two IS
# LAST, and the range therefore contains every commit that merge brought
# in. Measured on a consumer repo, one round built a 9,800-line block
# against a 1,234-line reviewed diff (119 of its 133 files outside the
# PR) and two PRs built ~1.16M-line blocks; the prompt went from ~98 KB
# to ~826 KB, most legs timed out, and the legs that finished reviewed
# files from the base branch rather than the PR. Each patch here is taken
# against a MERGE BASE instead, so each carries only the branch's own
# changes and neither can name a base-branch commit.
#
# NEW is `pr-diff.patch` ITSELF — the diff this round is actually
# reviewing — not a freshly-computed BASE...HEAD diff. Every emitted
# section is then a verbatim slice of the reviewed diff, so the subset
# property the prompt asserts holds by construction, and a generated
# file the classifier stripped from the reviewed diff can never reappear
# in the block (which would trip the fail-safe and discard the lot).
#
# Each patch is pinned to the merge base ITS OWN round used: OLD to the one
# round N recorded in its review's round sentinel, NEW (via check-pr-size) to
# merge-base(BASE, HEAD) for this round. Recomputing OLD's from the CURRENT
# base is the bug BE-15598 fixes — after a retarget or a base-branch rewrite
# `BASE...LAST_REVIEWED` diffs against a merge base round N never used, so
# hunks the panel has never seen read as "already reviewed" and are dropped
# from the block. The subset fail-safe cannot catch that: a block that is too
# SMALL is still a subset. With no recorded merge base there is no honest
# answer, so the step emits no block at all rather than guessing one.
#
# KNOWN, and not fixed here: on the retarget path this pin exists FOR, the two
# merge bases can be nearly disjoint, so almost nothing in NEW is in OLD and the
# block comes out close to the full reviewed diff — which the prompt then carries
# twice. `check` cannot catch it (`foreign == 0` and `new_lines <= full_lines`
# both hold), because the block really is a faithful subset; it is just a useless
# one. The cost is prompt budget on an uncommon path, never coverage, and the
# alternative — declining a block whose length approaches `full_lines` — needs a
# threshold nothing here has grounds to pick yet. Left as a known waste rather
# than guessed at.
#
# The two merge bases still differ whenever the base branch was merged in
# between rounds. A file the base branch AND the branch both touched then reads
# as changed even if the author's own edit did not move. That is over-inclusion
# strictly WITHIN the PR's own files, which costs a little prompt budget and
# never breaks the subset property; it is the accepted direction, because the
# alternative hides a hunk whose surrounding code really did change under it.
id: incremental
if: steps.check.outputs.over_cap != 'true'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
LAST_REVIEWED_SHA: ${{ needs.ledger.outputs.last_reviewed_sha }}
# The merge base round N recorded, NOT this round's — see above. Empty for
# every round reviewed before the round sentinel existed, and for one whose
# sentinel did not parse or did not name the reviewed commit.
LAST_REVIEWED_MERGE_BASE: ${{ needs.ledger.outputs.last_reviewed_merge_base }}
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
NEW_PATCH="${RUNNER_TEMP}/pr-diff-new.patch"
OLD_PATCH="${RUNNER_TEMP}/pr-diff-old.patch"
FULL_PATCH="${RUNNER_TEMP}/pr-diff.patch"
# The helper comes from the pinned checkout of THIS repo (same one the
# classifier was built from), never the PR checkout — a PR must not be
# able to rewrite the logic that decides what the panel is shown.
INCREMENTAL_PY="_pr_size_tool/.github/cursor-review/incremental-diff.py"
: > "$NEW_PATCH"
# An OLD patch larger than this is declined rather than parsed. NEW is
# bounded by diff_size_cap; OLD is NOT — the last-reviewed patch keeps
# the generated-file sections the classifier strips out of the
# reviewed diff, and those cost nothing against that cap — so a PR
# comfortably under the review cap can still hand this step a patch
# big enough to burn the runner's memory on. Declining fails closed to
# "no block", the same as every other case below.
OLD_PATCH_MAX_BYTES=33554432 # 32 MiB
# Wrapped in a function so the shellcheck directive sits in front of a
# complete command — it is rejected in front of an `elif` branch.
build_old_patch() {
# core.quotePath=false to match check-pr-size's `writeReviewedDiff`,
# which builds the NEW side. Under the default (quoting ON) a
# non-ASCII path arrives C-quoted here and PLAIN there, so the two
# sides key differently and every such file is re-emitted in full on
# every round — including a pure rebase.
# TWO-DOT, against the RECORDED merge base: that commit is the exact left
# tree round N diffed, so this is the same two-tree diff its own
# `mergeBase...head` resolved to — and check-pr-size builds NEW the same
# way. Three dots here would re-resolve a merge base from a ref that has
# already moved, which is precisely the bug (BE-15598).
# $DIFF_EXCLUDES is intentionally unquoted so bash word-splits it
# into pathspec args.
# shellcheck disable=SC2086
git -c core.quotePath=false diff "${LAST_REVIEWED_MERGE_BASE}" "${LAST_REVIEWED_SHA}" -- . $DIFF_EXCLUDES > "$OLD_PATCH"
}
# Default the output to the honest "nothing was discarded" value, and
# let the fail-safe below append 'false' over it — same last-value-wins
# append the raw-count fallback above uses.
echo "incremental_subset=true" >> "$GITHUB_OUTPUT"
# Same last-value-wins append for approve_scope's view of the block.
echo "incremental_state=unavailable" >> "$GITHUB_OUTPUT"
# Every "can't build one" case below leaves the block EMPTY and
# `incremental_subset` true: nothing was discarded, there was simply
# nothing to prioritize, and the panel reviews the full diff as it
# does on round 1. Only the fail-safe at the bottom writes `false`.
if [ -z "$LAST_REVIEWED_SHA" ] || [ "$LAST_REVIEWED_SHA" = "$HEAD_SHA" ]; then
echo "No usable last-reviewed SHA — skipping the incremental diff block."
echo "incremental_state=none" >> "$GITHUB_OUTPUT"
elif ! git cat-file -e "${LAST_REVIEWED_SHA}^{commit}" 2>/dev/null \
|| ! git merge-base --is-ancestor "$LAST_REVIEWED_SHA" "$HEAD_SHA" 2>/dev/null; then
# The ancestor test keeps the block's old reach. Under the former
# full-history clone a force-pushed-away head was simply absent; the
# narrowed fetch asks for it BY SHA, and GitHub can still serve it, so
# presence alone would now build a block (and widen approve_scope's
# `delta`) on exactly the rounds that used to get none. "An ancestor
# of this head" is what an un-rewritten branch's last round always is.
echo "Last-reviewed SHA ${LAST_REVIEWED_SHA} is unreachable or no longer in this head's history (force-push or base-branch rewrite) — skipping the incremental diff block."
elif [ -z "$LAST_REVIEWED_MERGE_BASE" ]; then
# Fail CLOSED, and do NOT fall back to ${BASE_SHA}: that fallback IS the bug
# (BE-15598). Every live PR sees this once after rollout — the round it is
# comparing against was posted before the sentinel existed — and then the
# block comes back on the round after, which is the first one with a
# recorded merge base to pin to.
echo "No recorded merge base for round ${LEDGER_ROUNDS:-?} (reviewed before the round sentinel existed, or the sentinel did not parse) — skipping the incremental diff block."
elif ! git cat-file -e "${LAST_REVIEWED_MERGE_BASE}^{commit}" 2>/dev/null \
|| ! git merge-base --is-ancestor "$LAST_REVIEWED_MERGE_BASE" "$LAST_REVIEWED_SHA" 2>/dev/null; then
# The recorded commit has to be reachable in THIS checkout and has to still
# be an ancestor of the commit it was the merge base of. A base-branch
# rewrite can drop the commit entirely, and a rewritten PR branch can leave
# it reachable but no longer in the last-reviewed commit's history — in
# which case `git diff <merge base> <last reviewed>` succeeds and returns
# something that is not "what round N saw" at all.
echo "Recorded merge base ${LAST_REVIEWED_MERGE_BASE} is unreachable or not an ancestor of the last-reviewed commit ${LAST_REVIEWED_SHA} — skipping the incremental diff block."
elif [ ! -s "$FULL_PATCH" ]; then
echo "The reviewed diff is empty — skipping the incremental diff block."
elif ! build_old_patch || [ ! -s "$OLD_PATCH" ]; then
# Fail CLOSED to "no block" — for a FAILED build and an EMPTY one
# alike. Falling through with an empty OLD would make every file
# read as new and emit the whole reviewed diff a second time: a
# doubled prompt that prioritizes nothing, which the fail-safe
# below cannot catch either (nothing is foreign, and new_lines
# EQUALS full_lines rather than exceeding it). An empty OLD is not
# an error git reports — it is simply what the recorded merge base
# against the last-reviewed commit yields whenever round N's own
# patch was empty (the recorded merge base IS that commit), or
# whenever $DIFF_EXCLUDES filters every file out.
echo "Could not build a non-empty last-reviewed patch (${LAST_REVIEWED_SHA}) — skipping the incremental diff block."
elif [ "$(wc -c < "$OLD_PATCH")" -gt "$OLD_PATCH_MAX_BYTES" ]; then
echo "The last-reviewed patch is larger than ${OLD_PATCH_MAX_BYTES} bytes — skipping the incremental diff block rather than parsing it."
elif ! python3 "$INCREMENTAL_PY" build \
--old "$OLD_PATCH" --new "$FULL_PATCH" --out "$NEW_PATCH"; then
echo "::warning::Could not build the incremental diff block — the panel will run on the full reviewed diff alone."
: > "$NEW_PATCH"
else
echo "Incremental diff since round ${LEDGER_ROUNDS:-?} (${LAST_REVIEWED_SHA}): $(wc -l < "$NEW_PATCH") lines"
# Fail-safe. The prompt tells the panel this block "is the subset of
# the diff above", so VERIFY it rather than trusting the builder:
# any path the reviewed diff does not carry, or more lines than the
# reviewed diff, and the block is discarded whole. The panel then
# runs on the full diff alone, which is always correct.
if SUBSET_OUT="$(python3 "$INCREMENTAL_PY" check --new "$NEW_PATCH" --full "$FULL_PATCH")"; then
echo "Incremental block verified as a subset of the reviewed diff."
echo "incremental_state=built" >> "$GITHUB_OUTPUT"
else
FOREIGN="$(printf '%s\n' "$SUBSET_OUT" | sed -n 's/^foreign=//p')"
NEW_LINES="$(printf '%s\n' "$SUBSET_OUT" | sed -n 's/^new_lines=//p')"
FULL_LINES="$(printf '%s\n' "$SUBSET_OUT" | sed -n 's/^full_lines=//p')"
: > "$NEW_PATCH"
echo "::warning::Incremental diff discarded: it was not a subset of the reviewed diff (${FOREIGN:-unknown} foreign file(s), ${NEW_LINES:-unknown} vs ${FULL_LINES:-unknown} lines)."
echo "incremental_subset=false" >> "$GITHUB_OUTPUT"
echo "incremental_state=discarded" >> "$GITHUB_OUTPUT"
fi
fi
- name: Upload reviewed diff
# Shared with the panel cells + judge so the diff is generated ONCE, and
# those jobs need no PR checkout of their own.
if: steps.check.outputs.over_cap != 'true'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: pr-diff
path: |
${{ runner.temp }}/pr-diff.patch
${{ runner.temp }}/pr-diff-new.patch
if-no-files-found: error
retention-days: 7
# Sticky PR comment for the over-cap skip. Modelled on pr-size.yml's `comment`
# job, same best-effort contract: the verdict lives in `diff-size` (its
# ::warning:: annotation and step summary), and this path may never redden the
# run — hence continue-on-error on both the mint and the upsert.
#
# Non-blocking on purpose. cursor-review is advisory by default — it posts a
# review, it does not gate (gating is the opt-in `blocking` input's separate
# Blocking gate job, and even for a blocking caller an over-cap skip is a
# documented pass-through there, not a failure) — so failing the run over an
# over-cap PR would gate nothing while breaking the reusable's contract for
# every caller. The fix here is VISIBILITY, not enforcement.
#
# Isolation: this job checks out NO code at all — it only reads job outputs
# and calls the comments API — so its write-scoped token is never present in
# a job that held a PR checkout.
over-cap-comment:
name: Comment when over the diff-size cap
needs: [gate, diff-size]
# Gating on diff-size's RESULT, not on within_cap, is load-bearing twice
# over. A git-level diff-size failure leaves every output empty, and an
# empty within_cap satisfies `!= 'true'` — which would post a confident
# "over cap" comment about a job that never counted anything. And the job
# must ALSO run on within-cap runs, because that is the only way a stale
# over-cap comment ever gets flipped to ✅ once the PR is trimmed.
#
# `!cancelled()` rather than `always()`: the documented caller sets
# cancel-in-progress, so a superseded run reaching here would PATCH its
# obsolete verdict over the newer run's — and this comment's whole content
# is "did a review run", the one thing that must not go stale. The upsert
# additionally re-checks the live PR head, which covers the other half
# (someone manually re-running an old, uncancelled run).
if: ${{ !cancelled() && needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.result == 'success' }}
runs-on: ubuntu-latest
# Bounded like every other job here. The work is two API calls, but the list
# paginates over an attacker-growable comment list, so the 6-hour default
# would let a rate-limited or hung call hold a runner all day.
timeout-minutes: 5
permissions:
contents: read
# For the GITHUB_TOKEN fallback below. Not a new demand on callers:
# `post-review` already requires this exact scope to post the review, so
# every caller that can run this workflow at all already grants it.
pull-requests: write
env:
# The `secrets` context is unavailable in `if` conditions, so the
# credentials-present test is evaluated here (job env allows it) and the
# mint below gates on the result. Absent creds are NOT the end of the
# road any more — the upsert falls back to the run token.
BOT_CONFIGURED: ${{ inputs.bot_app_id != '' && secrets.BOT_APP_PRIVATE_KEY != '' }}
steps:
- name: Mint bot token
id: bot
if: env.BOT_CONFIGURED == 'true'
# Best-effort: a consumer whose bot app lacks the requested scope (or
# has creds misconfigured) falls back to the run token below, and never
# gets a red check from the comment path.
continue-on-error: true
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
# Exactly what the upsert uses. The sticky comment rides the
# issues-comments API on a PULL REQUEST, and for GitHub Apps that
# endpoint checks the app's Pull requests permission (not Issues) — so
# pull-requests:write is the one scope required (read is implied for
# the list GET). Requesting an ungranted extra (e.g. issues:write)
# would 422 the mint on installations that never granted it.
permission-pull-requests: write
- name: Upsert sticky over-cap comment
id: upsert
# Same best-effort contract as the mint: a runtime permission failure
# (e.g. a 403 because the bot app lacks Pull requests on this
# installation) must not fail the job — "Note degraded mode" reports it.
continue-on-error: true
env:
# Dedicated bot identity when configured, else github-actions[bot] —
# the same fallback `consolidate` uses to post the review itself.
# Without it the sticky half of this fix would never fire for the
# (likely majority) of callers that configure no bot app, leaving them
# with exactly the silent green run BE-7646 is about.
GH_TOKEN: ${{ steps.bot.outputs.token || secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
# The minted token's OWN bot login. app-slug comes from the mint, so
# it identifies this installation whether bot_app_id was given as a
# numeric App ID or a Client ID (`Iv1.…`). Empty when no app is
# configured or the mint failed; RUN_LOGIN then carries the identity.
BOT_LOGIN: ${{ steps.bot.outputs.app-slug && format('{0}[bot]', steps.bot.outputs.app-slug) || '' }}
# The fallback identity. BOTH logins are matched when finding the
# sticky comment, because the identity can change between runs (a bot
# app added later, or a mint that fails once) and a finder that knew
# only the current one would post a second comment beside the old one
# and then maintain two contradictory verdicts. Still safe as an
# author filter: a PR author cannot post as either login.
RUN_LOGIN: github-actions[bot]
WITHIN_CAP: ${{ needs.diff-size.outputs.within_cap }}
COUNTED: ${{ needs.diff-size.outputs.counted }}
DEGRADED: ${{ needs.diff-size.outputs.degraded }}
run: |
set -euo pipefail
# Don't let an obsolete run overwrite a newer verdict. `!cancelled()`
# covers the cancel-in-progress path; this covers a manual re-run of
# an older run, whose event payload still carries the head SHA that
# was current when it was queued.
#
# FAILS CLOSED. A lookup that errors leaves us unable to tell a
# current run from an obsolete one, and writing anyway would let a
# stale "no panel ran" (or a premature ✅) land on top of the right
# answer — the one failure this guard exists to prevent. Skipping
# costs little: the list and write below hit the same API with the
# same token, so a real outage would take them out a line later
# regardless. `exit 1` under continue-on-error routes it to "Note
# degraded mode", which reports it against the annotation + summary
# that remain the primary signal.
if ! LIVE_HEAD="$(gh api "repos/${REPO}/pulls/${PR_NUMBER}" --jq '.head.sha')" || [ -z "$LIVE_HEAD" ]; then
echo "Could not read the PR's current head (see gh error above) — refusing to write a verdict that may already be stale." >&2
exit 1
fi
if [ "$LIVE_HEAD" != "$EVENT_HEAD_SHA" ]; then
echo "This run's head (${EVENT_HEAD_SHA}) is no longer the PR head (${LIVE_HEAD}) — a newer run owns the verdict. Not writing."
exit 0
fi
# Distinct from the panel's CONSOLIDATED_MARKER (gate-unresolved.py):
# that one matches PR *reviews*, this one an issue comment, and
# nothing in cursor-review reads issues/*/comments at all — so the two
# cannot collide.
MARKER='<!-- cursor-review-over-cap -->'
COUNTED_TEXT="${COUNTED:-an unknown number of}"
# On the degraded path `counted` is the RAW numstat total — the
# classifier never ran, so no generated file was excluded from it.
# Describing it as "after generated-file exclusion" there would tell
# an author whose lockfile tipped the PR over the cap to go shrink a
# number the stated rule says already excludes their lockfile.
if [ "${DEGRADED:-}" = "true" ]; then
BASIS='raw changed lines; the generated-file classifier failed on this run, so nothing was excluded from the count'
else
BASIS='changed lines, after generated-file exclusion'
fi
if [ "$WITHIN_CAP" = "true" ]; then
{
printf '%s\n\n' "$MARKER"
# Deliberately claims only what THIS job knows. It needs just
# `gate` + `diff-size`, so it runs alongside the panel and cannot
# see whether the panel finished, failed preflight, or was
# cancelled — asserting "the panel ran" here would re-create the
# false green this whole change exists to kill.
# shellcheck disable=SC2016
printf '✅ **Now under the cap** — this PR no longer exceeds `diff_size_cap`, so the review is no longer skipped for size. Check this run for the panel'"'"'s result.\n'
} > body.md
else
{
printf '%s\n\n' "$MARKER"
# The backticks are a markdown code span in the comment body, not
# a command substitution — single quotes are what keeps them so.
# shellcheck disable=SC2016
printf '⚠️ **Cursor review skipped** — the counted diff (%s %s) exceeds `diff_size_cap` (%s). **No review panel ran on this PR.**\n\n' \
"$COUNTED_TEXT" "$BASIS" "$DIFF_SIZE_CAP"
# NOT "re-runs automatically on the next push": the documented
# caller subscribes to `types: [labeled, unlabeled]` only, so a
# push fires nothing and the gate only sets should_run on a
# `labeled` event (or in run_without_label mode). Telling the
# author to push would leave them waiting on a run that never
# starts, under a comment that never flips.
# shellcheck disable=SC2016
printf 'Reduce the counted diff or split the PR, then re-apply the `%s` label to trigger a fresh review. (If this repo runs the review on every push, a push is enough.)\n' \
"$REVIEW_LABEL"
} > body.md
fi
# Find our existing sticky comment(s) by the hidden marker, so we
# update across pushes instead of stacking new ones. Both filters are
# load-bearing, and this mirrors pr-size.yml's `comment` job (and
# `find_sticky` in scripts/pr-risk/publish-risk-surfaces.sh)
# deliberately — same hazards, so the same shape rather than a third
# dialect of it.
#
# .user.login is one of OUR two possible identities (the bot app, if
# configured, and the run token's github-actions[bot]) — the
# marker is published in this PUBLIC workflow file, so without an
# author filter a PR author could pre-seed a comment carrying it
# and we would PATCH THEIRS instead of posting ours, after which
# they rewrite the "no review ran" notice freely. Matching the
# LOGIN (not merely `.user.type == "Bot"`) also keeps us off any
# OTHER app's comment that happens to echo author-controlled text
# as its first line. Neither login is postable by a human.
#
# startswith, not contains — the body renders the marker as its
# FIRST line, while another bot QUOTING this comment carries the
# marker nested in its own prose.
#
# Both values are passed as jq DATA (--arg), never spliced into the
# program text, so nothing can turn the filter into a syntax error —
# which under `set -euo pipefail` plus continue-on-error would become
# a silent "no comment posted".
existing="$(gh api "repos/${REPO}/issues/${PR_NUMBER}/comments" --paginate \
| jq -r --arg m "$MARKER" --arg login "$BOT_LOGIN" --arg run_login "$RUN_LOGIN" '
# $login is "" when no app token was minted; the != "" guard
# keeps that empty string from matching a login-less comment.
.[] | select(($login != "" and (.user.login // "") == $login)
or (.user.login // "") == $run_login)
| select((.user.type // "") == "Bot")
| select(((.body // "") | startswith($m)))
| .id')"
if [ -n "$existing" ]; then
# Update EVERY match, not just the first: the find-then-post is
# check-then-act with no lock, so two runs that both list before
# either posts leave two comments — reachable for a caller that adds
# `synchronize` to its `types:` (or runs in run_without_label mode),
# where a push can race a label toggle into a different concurrency
# group. Updating every copy keeps the duplicates in AGREEMENT
# instead of split-brained. Taking `head -n1` would pin
# one forever while the other displayed a stale verdict — and here a
# stale verdict says a review did or did not run, which is the whole
# point of the comment. Unquoted on purpose: the ids are numeric and
# newline-separated, so word splitting is the right parse.
#
# Per-id failure is TOLERATED rather than fatal — under
# `set -euo pipefail` a bare call would abort the loop on the first
# error and leave the remaining copies stale, exactly the split
# brain this loop exists to prevent. A 404 is expected: a maintainer
# (or another run) deleting one between the list and the write.
patched=0
failed=0
for id in $existing; do
if gh api -X PATCH "repos/${REPO}/issues/comments/${id}" -F body=@body.md >/dev/null; then
echo "Updated sticky over-cap comment ${id}."
patched=$((patched + 1))
else
failed=$((failed + 1))
# gh's stderr is deliberately NOT discarded: a 403 from
# permission drift, a 422 on an over-long body and a concurrent
# delete all land here.
echo "Failed to update sticky over-cap comment ${id} (see gh error above); continuing." >&2
fi
done
# Fail the step only when NOTHING was patched — a partial failure is
# the case this loop exists for, and reporting it as a step failure
# would make the degraded-mode note below claim no comment was
# posted, which is affirmatively false.
if [ "$patched" -eq 0 ] && [ "$failed" -gt 0 ]; then
echo "No sticky comment could be updated (${failed} failed); the PR may show a stale verdict." >&2
exit 1
elif [ "$failed" -gt 0 ]; then
echo "Updated ${patched} sticky comment(s); ${failed} could not be updated (see errors above)."
fi
elif [ "$WITHIN_CAP" != "true" ]; then
gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -F body=@body.md >/dev/null
echo "Posted over-cap skip comment."
else
# Never POST on the happy path — a PR that was always under the cap
# gets a review, not a comment about not getting one.
echo "Within the cap and no existing comment — nothing to post."
fi
- name: Note degraded mode
# The upsert no longer depends on the bot app — it falls back to the run
# token — so the only way no comment is written is the upsert itself
# failing. Reported here so the job never goes green silently; the
# ::warning:: annotation and step summary from the diff-size job remain
# the signal in that case. A failed MINT alone is not degraded mode (the
# run token covered it), but it is worth naming, since it changes which
# identity authored the comment.
if: steps.upsert.outcome == 'failure' || steps.bot.outcome == 'failure'
env:
BOT_OUTCOME: ${{ steps.bot.outcome }}
UPSERT_OUTCOME: ${{ steps.upsert.outcome }}
WITHIN_CAP: ${{ needs.diff-size.outputs.within_cap }}
run: |
if [ "$BOT_OUTCOME" = "failure" ]; then
echo "Bot app token could not be minted for this repo — the run token (github-actions[bot]) was used instead."
fi
if [ "$UPSERT_OUTCOME" != "failure" ]; then
exit 0
fi
echo "Sticky comment NOT written: the upsert failed at runtime — see the 'Upsert sticky over-cap comment' step log above for the actual error (a network/5xx failure, a GitHub rate limit, or a 403 from a token without Pull requests: write on this repo)."
if [ "$WITHIN_CAP" != "true" ]; then
echo "This PR is OVER diff_size_cap and got no review panel — the ::warning:: annotation and step summary on the 'Diff size check' job are the signal."
else
echo "This PR is within diff_size_cap, so there is no skip to announce; nothing was owed on this run."
fi
preflight:
# Validate the panel's pinned model ids against the LIVE Cursor catalog
# once, before the 8-cell fan-out. When Cursor delists a pinned id the
# per-cell `cursor-agent --model <id>` call cannot submit structured output.
# Failing here turns that drift into a loud, visible job failure before the
# fan-out starts. This job is ALSO the single source of truth for the
# matrix model list (emitted as an output the `review` matrix consumes), so
# the validated list and the reviewed list can never drift apart.
name: Preflight — validate model catalog
needs: [gate, diff-size]
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true'
runs-on: ${{ fromJSON(inputs.runs_on || '"ubuntu-latest"') }}
timeout-minutes: 10
permissions:
contents: read
outputs:
models: ${{ steps.models.outputs.models }}
# 'true' only when the direct-API cell can actually run: a model id is
# set, it is artifact-name safe, and OPENAI_API_KEY reached this
# workflow. `review-openai-direct` gates on THIS rather than on the raw
# input, so a misconfigured opt-in neither drops the Cursor OpenAI cell
# nor schedules a cell that can only error.
openai_direct: ${{ steps.models.outputs.openai_direct }}
# 'true' when the direct-API cells are in effect AND replace the Cursor
# OpenAI lane: they are then that lane, so they gate exactly like Cursor
# cells (counted in ok_count/total, leg red on failure). Side by side
# ('false') they stay advisory.
openai_direct_counts: ${{ steps.models.outputs.openai_direct_counts }}
# The same pair for the direct Anthropic cells (`review-anthropic-direct`).
anthropic_direct: ${{ steps.models.outputs.anthropic_direct }}
anthropic_direct_counts: ${{ steps.models.outputs.anthropic_direct_counts }}
# 'true' only when an unusable key turned the direct cells off and the
# panel list had no Cursor claude-* cell to run instead (post-review says so).
anthropic_cells_no_cursor: ${{ steps.models.outputs.anthropic_cells_no_cursor }}
# `anthropic_direct_effort`, validated: always one of the allowed levels.
anthropic_direct_effort: ${{ steps.models.outputs.anthropic_direct_effort }}
# 'true' only when the judge can actually run direct: `judge_direct_model`
# is a plain id and ANTHROPIC_API_KEY reached this workflow. `consolidate`
# switches its runner and its judge steps on THIS, never the raw input.
judge_direct: ${{ steps.models.outputs.judge_direct }}
# `judge_direct_effort`, validated: always one of the allowed levels.
judge_direct_effort: ${{ steps.models.outputs.judge_direct_effort }}
# The caps DERIVED from `cell_timeout_minutes`, computed here because
# Actions expressions have no arithmetic: `${{ x + 15 }}` is a parse
# error that fails the workflow at load for every caller. Consumers
# read them through `fromJSON(needs.preflight.outputs.*)`.
cell_job_timeout: ${{ steps.cell_timeout.outputs.cell_job }}
judge_step_timeout: ${{ steps.cell_timeout.outputs.judge_step }}
judge_job_timeout: ${{ steps.cell_timeout.outputs.judge_job }}
steps:
- name: Validate the cell timeout
id: cell_timeout
# FIRST, and before a single cell spends. `type: number` buys only
# numeric-ness: 0, -5 and 600 all parse. The three derived caps make a
# bad value worse than it looks — the judge's job cap is 2x + 10, so a
# typo'd 600 mints a 20-hour job and a 0 makes every cell fail
# instantly with no clue why. Neither is visible in a diff of this
# file, because the numbers are expressions now.
#
# Bounded rather than clamped, deliberately: silently correcting a
# caller's 600 to 45 would review a long diff on a budget nobody chose
# and report success. The floor is 10 because `Run cursor review`'s
# wrapper may start its last `resource_exhausted` retry as late as 300s
# in (`--retry-window 300`), and that attempt still needs room for a
# healthy 3-7 minute review; at 5 a retried cell was all but certain to
# hit the cap. The ceiling is 45 because that is already a 100-minute
# judge job, and anything needing more is a diff-size problem, not a
# timeout problem. The length check runs first because an all-digit
# value too long for a 64-bit integer makes `[ -lt ]` error, and an
# erroring test inside `if` reads as false, so it would pass.
env:
CELL_TIMEOUT: ${{ inputs.cell_timeout_minutes }}
run: |
set -euo pipefail
case "$CELL_TIMEOUT" in
''|*[!0-9]*)
echo "::error::cell_timeout_minutes must be a whole number of minutes between 10 and 45; got '${CELL_TIMEOUT}'."
exit 1
;;
esac
if [ "${#CELL_TIMEOUT}" -gt 2 ] || [ "$CELL_TIMEOUT" -lt 10 ] || [ "$CELL_TIMEOUT" -gt 45 ]; then
echo "::error::cell_timeout_minutes must be between 10 and 45; got ${CELL_TIMEOUT}. The judge's job cap is twice this plus 10, so the ceiling is what keeps a typo from minting an hours-long job."
exit 1
fi
# 10# forces base 10; a two-digit value with a leading zero is < 10
# and already rejected above, but this keeps "08" from reading as octal.
cell=$((10#$CELL_TIMEOUT))
judge_step=$((cell * 2))
# Never below 30: the judge's workload grows with the panel, not with
# the cell cap, so tightening cells to fail fast must not starve it.
if [ "$judge_step" -lt 30 ]; then judge_step=30; fi
echo "::notice::Cell agent cap ${cell}m; cell job $((cell + 15))m; judge step ${judge_step}m; judge job $((judge_step + 10))m."
{
echo "cell_job=$((cell + 15))"
echo "judge_step=${judge_step}"
echo "judge_job=$((judge_step + 10))"
} >> "$GITHUB_OUTPUT"
- name: Define panel models
id: models
# Single source of truth for the per-lab model pins. The `review`
# matrix consumes this list via fromJSON, and the catalog check below
# validates every entry — so a bump only ever touches this one list.
# Keep in sync with the README model table.
#
# Three labs. OpenAI: GPT-5.6 Sol is the 5.6-family coding flagship
# (Luna is the cost tier, Terra mid; the Codex line stops at 5.3).
# Anthropic: Opus 5.5 at the `xhigh` tier — confirmed present and
# ZDR-eligible against the live catalog, which prints
# `claude-opus-5-5-xhigh - Claude Opus 5.5 1M Extra High` with no
# NO-ZDR marker (preflight log of run 37688671671). That is a positive
# read of the id's own line, not an inference from the family: an id
# with no marker is not thereby ZDR-eligible, and the preflight below
# only checks existence. Fable tops the catalog but every Fable entry
# IS marked NO ZDR, and this panel reviews private-repo diffs, so that
# family stays excluded. Note 5.5 ships NO `-thinking-` variants —
# Opus 5 had both lines, 5.5 has only `claude-opus-5-5-<tier>`, so
# `claude-opus-5-thinking-max` has no literal counterpart and the
# nearest is a plain tier id. That plain line IS the thinking model:
# Cursor labels non-thinking explicitly where it applies (every plain
# Haiku 5.5 entry reads "No Thinking") and no Opus 5.5 or Sonnet 5.5
# entry carries that marker. Moonshot: Kimi K3 at the `max` tier —
# RESTORED 2026-10-09 after the `-high` tier proved capacity-bound; see
# the note below. No NO-ZDR marker.
#
# Gemini 3.1 Pro was removed 2026-08-27. Over 1,450 judge-kept
# findings (172 PRs), its two cells were the sole raiser of 2.5% of
# kept findings and 3 of 213 critical/high ones, while costing ~9% of
# every run; every other Gemini finding was also raised by the OpenAI
# or Anthropic cell. The Kimi tier drop and the judge's move to
# `-xhigh` come from the same spend review, and the Anthropic cell
# moved from Opus 5 `-thinking-max` to Opus 5.5 `-xhigh` on
# 2026-10-07 for the same reason: a newer model one reasoning notch
# down. That is deliberately TWO axes at once (version + tier) — it
# is a default change, not an attribution experiment.
#
# Kimi went BACK to `-max` on 2026-10-09. The `-high` tier turned
# capacity-bound, not slow: cells died in ~25 seconds with
# `RetriableError: [resource_exhausted]` after three internal
# reconnects, zero findings, leg red, `Panel integrity` red with it.
# Measured on one consumer over 56 panels: 24 of 76 `kimi-k3-high`
# cells red (32%), 19 of them this error, and 12 of 22 on the last day.
# It is not a property of one repo — the same model threw the same error
# the same day on two unrelated consumers — and #388's in-step retry
# does not rescue it, because the condition is sustained rather than
# transient: both cells on github-workflows#392's own panel exhausted
# all three attempts.
#
# `-max` rather than dropping the lane, because the lane EARNS its
# place. Re-running the 2026-08-27 attribution over 1,158 judge-kept
# findings (82 PRs), normalised per finding raised so panel size does
# not flatter anyone: Kimi was the sole raiser of 17% of what it raised
# at `-max` and 27% at `-high` — 1.05 unique findings per PR at BOTH
# tiers — and uniquely caught 3 of 58 critical/high at `-max`. Compare
# Gemini, cut for exactly this reason: 12% and 0.33 per PR, 0 of 58
# critical/high. Dropping Kimi would cost roughly three times what
# dropping Gemini did.
#
# What this trades away is the spend the tier drop was for, so it is a
# deliberate reversal of part of #243, not an oversight. The reliability
# it buys is also NOT established at this tier under present conditions:
# `-max` was 0 of 36 cells red, but that was measured on 2026-10-07,
# before the capacity trouble, and the two tiers may well share a pool.
# If `-max` goes the same way, the evidence above says drop to a
# two-lab Cursor panel rather than substitute Gemini or Grok — Grok
# `4.7-high` was tried on 2026-10-09 and raised 0 unique findings in 17
# while timing out on 11 of 20 cells.
#
# The `panel_models` input — or the CURSOR_PANEL_MODELS variable, see the
# env block below — overrides this list for A/B experiments.
#
# The OpenAI cell moved from `gpt-5.6-sol-max` to `gpt-5.6-sol-xhigh`:
# one reasoning notch down, to cut the timeouts and run-to-cap
# failures seen on that lane. `gpt-5.6-sol-xhigh` is a live catalog id.
#
# Pins last checked 2026-08-27. This date is deliberately the OLDEST
# pin's audit, and deliberately the only `last checked` literal in the
# 40 lines above the heredoc: catalog-drift.py's `_LAST_CHECKED` does a
# plain `re.search` over that window and applies the FIRST date it
# finds to the WHOLE pin set. Putting a fresher per-lab date here — the
# Anthropic cell was re-audited 2026-10-07 — resets the staleness clock
# for every pin that was NOT re-audited, silently suppressing a finding
# that is already due. Keep this line last, keep it the oldest, and
# phrase any per-lab re-check so the regex cannot match it.
env:
# Falls back to a VARIABLE when the caller passes no input, so the
# panel list is settable in ONE place for the whole fleet with no
# caller edit. `vars` inside a reusable resolves against the CALLER's
# repo and org — same as CURSOR_REVIEW_DM_EMAIL_MAP further down — so
# an org-level CURSOR_PANEL_MODELS reaches every enrolled repo, and a
# repo-level one of the same name overrides it for that repo alone.
# Unset at both levels is '' → the built-in list below. An explicit
# `panel_models` input still wins, so a caller pinning its own list is
# unaffected.
PANEL_MODELS_OVERRIDE: ${{ inputs.panel_models || vars.CURSOR_PANEL_MODELS }}
# Which of the two won, for the log line below. With two sources the
# effective list alone no longer says where to go change it.
PANEL_MODELS_INPUT: ${{ inputs.panel_models }}
# Drive the direct-cell replacement below. Read here rather than in
# the `review` job so ONE resolved list feeds the matrix, the judge's
# `expected` set and `Panel integrity` alike — filtering anywhere else
# would leave consolidate expecting a cell that was never scheduled.
OPENAI_DIRECT_MODEL: ${{ inputs.openai_direct_model }}
OPENAI_DIRECT_REPLACES: ${{ inputs.openai_direct_replaces_cursor_openai }}
# Resolved in the hosted `gate` job: this one follows `runs_on`, so
# it must not reference the secret at all.
OPENAI_KEY_PRESENT: ${{ needs.gate.outputs.openai_key_present }}
# The same three for the direct Anthropic cells.
ANTHROPIC_DIRECT_MODEL: ${{ inputs.anthropic_direct_model }}
ANTHROPIC_DIRECT_REPLACES: ${{ inputs.anthropic_direct_replaces_cursor_anthropic }}
ANTHROPIC_DIRECT_EFFORT: ${{ inputs.anthropic_direct_effort }}
ANTHROPIC_KEY_PRESENT: ${{ needs.gate.outputs.anthropic_key_present }}
# `gate`'s usability probe, per lane: unusable reads as an absent
# key, invalid fails the run, empty (not probed) changes nothing.
ANTHROPIC_CELLS_PROBE: ${{ needs.gate.outputs.anthropic_cells_probe }}
ANTHROPIC_CELLS_PROBE_REASON: ${{ needs.gate.outputs.anthropic_cells_probe_reason }}
# The direct judge (touches no panel list).
JUDGE_DIRECT_MODEL: ${{ inputs.judge_direct_model }}
JUDGE_DIRECT_EFFORT: ${{ inputs.judge_direct_effort }}
JUDGE_PROBE: ${{ needs.gate.outputs.anthropic_judge_probe }}
JUDGE_PROBE_REASON: ${{ needs.gate.outputs.anthropic_judge_probe_reason }}
run: |
cat > /tmp/models.json <<'JSON'
[
"gpt-5.6-sol-xhigh",
"claude-opus-5-5-xhigh",
"kimi-k3-max"
]
JSON
if [ -n "$(printf '%s' "$PANEL_MODELS_OVERRIDE" | tr -d '[:space:]')" ]; then
# Caller override. Must be a non-empty JSON array of catalog-shaped
# ids; the shape check here and the live-catalog check below both
# fail loud, so a bad override costs zero cells.
# Bounded at BOTH ends. The matrix fans out to models x 2 review
# types and GitHub caps a matrix at 256 jobs, so an oversized array
# fails the whole run at startup (permanently red under
# `blocking: true`) — and every extra id is another full
# cursor-agent pass over the diff. 12 is far above any real panel
# (the built-in list is 3) and far below the cap.
# Slurped (-s) and held to exactly ONE document: jq reads a stream,
# so `["a"] ["b"]` or `null ["a"]` would otherwise pass on its last
# value and normalize to two lines, not the one array the matrix
# needs.
if ! printf '%s' "$PANEL_MODELS_OVERRIDE" | jq -e -s \
'length == 1 and (.[0] | type == "array" and length > 0 and length <= 12 and all(.[]; type == "string" and test("^[a-z0-9][a-z0-9._-]*$")))' > /dev/null; then
# Echo the rejected value with newlines stripped and truncated.
# This input is caller-settable, and a caller wiring it to a
# variable makes it settable with no PR at all, so a raw
# multi-line echo would let it smuggle ::workflow commands:: into
# a PUBLIC repo's run log. Same reason the `Require a pinned
# workflows_ref` step below strips before echoing.
SAFE_OVERRIDE="$(printf '%s' "$PANEL_MODELS_OVERRIDE" | tr -d '\n\r' | cut -c1-200)"
echo "::error::panel_models must be a JSON array of 1-12 Cursor model ids (e.g. [\"gpt-5.6-sol-xhigh\", \"claude-opus-5-5-xhigh\"]); got: $SAFE_OVERRIDE"
exit 1
fi
printf '%s' "$PANEL_MODELS_OVERRIDE" | jq -c -s '.[0] | unique' > /tmp/models.json
if [ -n "$(printf '%s' "$PANEL_MODELS_INPUT" | tr -d '[:space:]')" ]; then
SRC="panel_models input"
else
SRC="CURSOR_PANEL_MODELS variable"
fi
echo "panel_models override in effect (from the $SRC): $(cat /tmp/models.json)"
else
# Logged in BOTH branches so the run says which list produced the
# review. A caller driving panel_models from a variable makes the
# empty case reachable by DELETING that variable, and without this
# line a mid-experiment deletion is indistinguishable in the log
# from one that was never set — the panel quietly reverts and the
# rounds either side of it look the same.
echo "panel_models not set (no input, no CURSOR_PANEL_MODELS variable) — using the built-in list: $(jq -c . /tmp/models.json)"
fi
# The direct-API cell reviews the OpenAI lane itself, so by default the
# Cursor-hosted OpenAI cell comes OUT of the panel — otherwise that lane
# is reviewed twice and billed twice. Applied after the override has
# been resolved, so it filters whichever list actually won.
#
# Resolved to ONE verdict first, because replacing the Cursor cell is
# only safe when the direct cell will genuinely run: a set input with
# no key, or an id `upload-artifact` would reject (a fine-tuned
# `ft:...` id carries `:`), would otherwise drop the OpenAI lane AND
# leave nothing reviewing it. Either case warns and leaves the panel
# exactly as it would be without the opt-in.
openai_direct=false
if [ -n "$(printf '%s' "${OPENAI_DIRECT_MODEL:-}" | tr -d '[:space:]')" ]; then
# `grep -x` matches line by line, so a multi-line value would pass
# on any one clean line; refuse every whitespace character (a
# newline included, which a grep could not see) first.
case "$OPENAI_DIRECT_MODEL" in *[[:space:]]*) openai_ws=true ;; *) openai_ws=false ;; esac
if [ "$openai_ws" = "true" ] \
|| ! printf '%s' "$OPENAI_DIRECT_MODEL" | grep -Eqx '[A-Za-z0-9._-]{1,100}'; then
echo "::warning::openai_direct_model is not a plain model id (letters, digits, '.', '_', '-'; at most 100), so the direct-API cell is off for this run and the panel is unchanged."
elif [ "${OPENAI_KEY_PRESENT:-false}" != "true" ]; then
echo "::warning::openai_direct_model is set but the OPENAI_API_KEY secret did not reach this workflow, so the direct-API cell is off for this run and the panel is unchanged. Pass the secret through from the caller to enable it."
else
openai_direct=true
fi
fi
echo "openai_direct=${openai_direct}" >> "$GITHUB_OUTPUT"
openai_direct_counts=false
if [ "$openai_direct" = "true" ] \
&& [ "${OPENAI_DIRECT_REPLACES:-true}" = "true" ]; then
openai_direct_counts=true
# ascii_downcase so a differently-cased id cannot slip past the
# vendor match and leave a duplicate OpenAI cell running.
dropped="$(jq -c '[.[] | select((ascii_downcase | startswith("gpt-")))]' /tmp/models.json)"
kept="$(jq -c '[.[] | select((ascii_downcase | startswith("gpt-")) | not)]' /tmp/models.json)"
if [ "$(printf '%s' "$dropped" | jq 'length')" -gt 0 ]; then
if [ "$(printf '%s' "$kept" | jq 'length')" -eq 0 ]; then
echo "::error::openai_direct_model is set and openai_direct_replaces_cursor_openai is true, but every id in the panel list is an OpenAI id, so replacing them would leave no Cursor cell at all. Set openai_direct_replaces_cursor_openai: false, or widen panel_models."
exit 1
fi
printf '%s' "$kept" > /tmp/models.json
echo "direct-API cell is on, so the Cursor OpenAI cell(s) $dropped were dropped from the panel; remaining: $kept"
else
echo "direct-API cell is on, but the panel list carries no Cursor OpenAI id to replace; panel unchanged."
fi
fi
echo "openai_direct_counts=${openai_direct_counts}" >> "$GITHUB_OUTPUT"
# The direct Anthropic cells, by exactly the rules above: one verdict
# first, then the replacement, applied to whatever the OpenAI branch
# left, so the empty-panel check sees both drops. `judge_model` is
# never touched — the judge stays on Cursor.
anthropic_direct=false
anthropic_no_cursor=false
if [ -n "$(printf '%s' "${ANTHROPIC_DIRECT_MODEL:-}" | tr -d '[:space:]')" ]; then
# `grep -x` matches line by line, so a multi-line value would pass
# on any one clean line; refuse every whitespace character (a
# newline included, which a grep could not see) first.
case "$ANTHROPIC_DIRECT_MODEL" in *[[:space:]]*) anthropic_ws=true ;; *) anthropic_ws=false ;; esac
if [ "$anthropic_ws" = "true" ] \
|| ! printf '%s' "$ANTHROPIC_DIRECT_MODEL" | grep -Eqx '[A-Za-z0-9._-]{1,100}'; then
echo "::warning::anthropic_direct_model is not a plain model id (letters, digits, '.', '_', '-'; at most 100), so the direct-API Anthropic cells are off for this run and the panel is unchanged."
elif [ "${ANTHROPIC_KEY_PRESENT:-false}" != "true" ]; then
echo "::warning::anthropic_direct_model is set but the ANTHROPIC_API_KEY secret did not reach this workflow, so the direct-API Anthropic cells are off for this run and the panel is unchanged. Pass the secret through from the caller to enable it."
elif [ "$openai_direct" = "true" ] \
&& [ "$(printf '%s' "$ANTHROPIC_DIRECT_MODEL" | tr 'A-Z' 'a-z')" = "$(printf '%s' "$OPENAI_DIRECT_MODEL" | tr 'A-Z' 'a-z')" ]; then
# Both direct jobs name their artifact findings-direct-<type>-<id>,
# so one id in both lanes collides (one upload fails) and the
# aggregator, which assigns by model id, credits every record to
# the OpenAI lab.
echo "::warning::anthropic_direct_model is the same id as openai_direct_model, so the direct-API Anthropic cells are off for this run and the panel is unchanged. Give each lane its own lab's model id."
elif [ "${ANTHROPIC_CELLS_PROBE:-}" = "invalid" ]; then
# After the collision check: an OpenAI id the Anthropic API
# rejects is that documented warning, not a failed run.
echo "::error::the Anthropic API does not know anthropic_direct_model '$ANTHROPIC_DIRECT_MODEL' ($ANTHROPIC_CELLS_PROBE_REASON). Fix the id; an unknown model never falls back to Cursor."
exit 1
elif [ "${ANTHROPIC_CELLS_PROBE:-}" = "unusable" ]; then
if jq -e 'any(.[]; ascii_downcase | startswith("claude-"))' /tmp/models.json > /dev/null; then
echo "::warning::the ANTHROPIC_API_KEY secret is unusable for anthropic_direct_model this run ($ANTHROPIC_CELLS_PROBE_REASON), so the direct-API Anthropic cells are off and the Cursor Anthropic cells run: the review cells fell back to Cursor."
echo "Direct Anthropic review cells: fell back to Cursor, the key is unusable ($ANTHROPIC_CELLS_PROBE_REASON)." >> "$GITHUB_STEP_SUMMARY"
else
# Exactly an absent key's panel, said as it is: a panel_models
# list with no claude-* id has no Cursor cell to fall back to.
anthropic_no_cursor=true
echo "::warning::the ANTHROPIC_API_KEY secret is unusable for anthropic_direct_model this run ($ANTHROPIC_CELLS_PROBE_REASON), so the direct-API Anthropic cells are off, and the panel list carries no Cursor Anthropic (claude-*) id to fall back to: no Anthropic review cell runs this round."
echo "Direct Anthropic review cells: off, the key is unusable ($ANTHROPIC_CELLS_PROBE_REASON) and the panel list has no Cursor claude-* id, so no Anthropic review cell ran." >> "$GITHUB_STEP_SUMMARY"
fi
else
anthropic_direct=true
fi
fi
echo "anthropic_direct=${anthropic_direct}" >> "$GITHUB_OUTPUT"
echo "anthropic_cells_no_cursor=${anthropic_no_cursor}" >> "$GITHUB_OUTPUT"
case "${ANTHROPIC_DIRECT_EFFORT:-}" in
low|medium|high|xhigh|max) anthropic_direct_effort="$ANTHROPIC_DIRECT_EFFORT" ;;
*)
anthropic_direct_effort=xhigh
if [ "$anthropic_direct" = "true" ]; then
echo "::warning::anthropic_direct_effort is not one of low, medium, high, xhigh, max, so the direct-API Anthropic cells use xhigh."
fi ;;
esac
echo "anthropic_direct_effort=${anthropic_direct_effort}" >> "$GITHUB_OUTPUT"
anthropic_direct_counts=false
if [ "$anthropic_direct" = "true" ] \
&& [ "${ANTHROPIC_DIRECT_REPLACES:-true}" = "true" ]; then
anthropic_direct_counts=true
dropped="$(jq -c '[.[] | select((ascii_downcase | startswith("claude-")))]' /tmp/models.json)"
kept="$(jq -c '[.[] | select((ascii_downcase | startswith("claude-")) | not)]' /tmp/models.json)"
if [ "$(printf '%s' "$dropped" | jq 'length')" -gt 0 ]; then
if [ "$(printf '%s' "$kept" | jq 'length')" -eq 0 ]; then
echo "::error::anthropic_direct_model is set and anthropic_direct_replaces_cursor_anthropic is true, but every id left in the panel list is an Anthropic id, so replacing them would leave no Cursor cell at all. Set anthropic_direct_replaces_cursor_anthropic: false, or widen panel_models."
exit 1
fi
printf '%s' "$kept" > /tmp/models.json
echo "direct-API Anthropic cells are on, so the Cursor Anthropic cell(s) $dropped were dropped from the panel; remaining: $kept"
else
echo "direct-API Anthropic cells are on, but the panel list carries no Cursor Anthropic id to replace; panel unchanged."
fi
fi
echo "anthropic_direct_counts=${anthropic_direct_counts}" >> "$GITHUB_OUTPUT"
# The direct judge, by the cells' rules: a plain id (no whitespace at
# all) and the key present, or it warns and the Cursor judge runs.
# No collision check — the judge uploads no per-model artifact.
judge_direct=false
if [ -n "$(printf '%s' "${JUDGE_DIRECT_MODEL:-}" | tr -d '[:space:]')" ]; then
case "$JUDGE_DIRECT_MODEL" in *[[:space:]]*) judge_ws=true ;; *) judge_ws=false ;; esac
if [ "$judge_ws" = "true" ] \
|| ! printf '%s' "$JUDGE_DIRECT_MODEL" | grep -Eqx '[A-Za-z0-9._-]{1,100}'; then
echo "::warning::judge_direct_model is not a plain model id (letters, digits, '.', '_', '-'; at most 100), so the judge runs on Cursor (judge_model) for this run."
elif [ "${ANTHROPIC_KEY_PRESENT:-false}" != "true" ]; then
echo "::warning::judge_direct_model is set but the ANTHROPIC_API_KEY secret did not reach this workflow, so the judge runs on Cursor (judge_model) for this run. Pass the secret through from the caller to enable it."
elif [ "${JUDGE_PROBE:-}" = "invalid" ]; then
echo "::error::the Anthropic API does not know judge_direct_model '$JUDGE_DIRECT_MODEL' ($JUDGE_PROBE_REASON). Fix the id; an unknown model never falls back to Cursor."
exit 1
elif [ "${JUDGE_PROBE:-}" = "unusable" ]; then
echo "::warning::the ANTHROPIC_API_KEY secret is unusable for judge_direct_model this run ($JUDGE_PROBE_REASON), so the judge fell back to Cursor (judge_model)."
echo "Direct judge: fell back to Cursor, the key is unusable ($JUDGE_PROBE_REASON)." >> "$GITHUB_STEP_SUMMARY"
else
judge_direct=true
echo "The judge runs direct through the Anthropic API ($JUDGE_DIRECT_MODEL)."
fi
fi
echo "judge_direct=${judge_direct}" >> "$GITHUB_OUTPUT"
case "${JUDGE_DIRECT_EFFORT:-}" in
low|medium|high|xhigh|max) judge_direct_effort="$JUDGE_DIRECT_EFFORT" ;;
*)
judge_direct_effort=xhigh
if [ "$judge_direct" = "true" ]; then
echo "::warning::judge_direct_effort is not one of low, medium, high, xhigh, max, so the direct judge uses xhigh."
fi ;;
esac
echo "judge_direct_effort=${judge_direct_effort}" >> "$GITHUB_OUTPUT"
echo "models=$(jq -c . /tmp/models.json)" >> "$GITHUB_OUTPUT"
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
# Same trusted-assets checkout the review/consolidate jobs do — this
# job needs it for install-cursor-cli.sh.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Install Cursor agent CLI
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
# Fork PRs (and any run without the secret) get no CURSOR_API_KEY, so
# `cursor-agent models` can't authenticate. Skip cleanly — matches the
# gate's fork handling, which already sets should_run=false for forks.
if [ -z "$CURSOR_API_KEY" ]; then
echo "No CURSOR_API_KEY (fork PR or unset secret) — skipping catalog preflight."
exit 0
fi
bash "$CURSOR_REVIEW_ASSETS/install-cursor-cli.sh"
- name: Validate model pins against live catalog
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
if [ -z "$CURSOR_API_KEY" ]; then
echo "No CURSOR_API_KEY — skipping catalog preflight (matches fork handling)."
exit 0
fi
# Capture the live catalog. A failure here (auth/network) is itself a
# hard fail — better red than a silently degraded panel.
if ! cursor-agent models > /tmp/catalog.txt 2>/tmp/catalog-stderr.txt; then
echo "::error::'cursor-agent models' failed — cannot verify the panel model pins."
cat /tmp/catalog-stderr.txt
exit 1
fi
echo "=== Cursor catalog ==="
cat /tmp/catalog.txt
python3 - <<'PY'
import json
import re
import sys
with open("/tmp/models.json", encoding="utf-8") as f:
pins = json.load(f)
with open("/tmp/catalog.txt", encoding="utf-8") as f:
catalog_raw = f.read()
catalog_lines = [ln.strip() for ln in catalog_raw.splitlines() if ln.strip()]
def present(model_id):
# Match the id as a whole token so `kimi-k2.5` doesn't match inside
# `kimi-k2.55`; ids contain `.`/`-`, so bound on those too.
pattern = r"(?<![\w.-])" + re.escape(model_id) + r"(?![\w.-])"
return re.search(pattern, catalog_raw) is not None
missing = [m for m in pins if not present(m)]
if not missing:
print("All pinned models present in the Cursor catalog:")
for m in pins:
print(f" - {m}")
sys.exit(0)
print(f"::error::Cursor catalog is missing pinned model id(s): {', '.join(missing)}")
for m in missing:
lab = re.split(r"[-.]", m, maxsplit=1)[0]
hints = sorted({ln for ln in catalog_lines if lab.lower() in ln.lower()})
hint = ", ".join(hints) if hints else "(no same-lab id found)"
print(f" - {m}: closest available for lab '{lab}': {hint}")
print(
"Update the pin in the preflight 'Define panel models' step (and the "
"README model table) to a current catalog id."
)
sys.exit(1)
PY
review:
# Each cell produces a findings artifact. No cell posts a review —
# consolidate adjudicates the panel and posts ONE review at the end.
name: '${{ matrix.review_type }} (${{ matrix.model }})'
# `preflight` gates the fan-out: if a pinned model is delisted it fails
# there, and this job is skipped instead of quietly running a lab short.
needs: [gate, diff-size, preflight, ledger]
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true'
runs-on: ${{ fromJSON(inputs.runs_on || '"ubuntu-latest"') }}
# DERIVED from `cell_timeout_minutes`, and deliberately not settable alone.
# This coupling used to be a comment telling the next editor to bump three
# other numbers by hand: the judge reads all of this panel's artifacts at
# the same reasoning tier, so it needs at least a cell's budget, and its job
# cap must sit above its step cap so a hung judge trips the step (degraded
# fallback still posts) rather than the job (all panel cells discarded). A
# cell cap that outgrew them recreated exactly the silent skew that fix was
# for — so the arithmetic lives in `preflight` now (expressions cannot do
# it), where it cannot be half-applied. The +15 is this job's non-agent overhead: checkout, CLI
# install, artifact download and upload, none of which the step cap covers.
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.cell_job_timeout) }}
permissions:
contents: read
strategy:
fail-fast: false
matrix:
# Model list comes from the preflight job (single source of truth); it
# is validated against the live catalog there.
model: ${{ fromJSON(needs.preflight.outputs.models) }}
review_type: [adversarial, edge-case]
steps:
- name: Seed default findings artifact
# Pre-seed a minimal artifact tagged status=error so this cell
# ALWAYS shows up in the panel summary, even if a later step
# (checkout, Cursor install, prompt build, tool submission) fails. The
# MCP output tool overwrites this on success. Without
# this, an early-failing cell silently disappears from the panel
# and the consolidated review undercounts the matrix.
env:
MODEL: ${{ matrix.model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
mkdir -p /tmp/findings-out
python3 - <<'PY'
import json, os
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"status": "error",
"error": "Cell did not complete structured output submission.",
"findings": [],
}
with open("/tmp/findings-out/findings.json", "w", encoding="utf-8") as f:
json.dump(record, f)
PY
- name: Checkout PR repo
# Pinned to the PR head SHA, as `diff-size` and `review-anthropic-direct`
# are: under `pull_request_target` the default is the BASE branch, and
# `refs/pull/<n>/merge` is neither immutable (each job resolves it
# separately, and the test merge lags a push) nor present on a
# conflicted PR, which `pull_request_target` still runs on.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
# The head tree only, as `review-anthropic-direct` takes it. No step
# here reads history — the reviewed diff, the incremental diff and the
# ledger arrive as artifacts — and a full clone of a large consumer
# cost ~2 min of this round's critical path.
fetch-depth: 1
persist-credentials: false
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
# Trusted prompts/scripts come from THIS workflow's repo (public,
# pinned via workflows_ref) — never from the PR checkout, so a
# malicious PR can't rewrite the prompt to exfiltrate the diff or
# smuggle instructions to the model.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Download reviewed diff
# The generated-file-excluded diff (plus the incremental "hunks new
# since the last reviewed round" diff) is built ONCE in the diff-size
# job and shared here, so this cell needs no PR checkout of its own —
# the only PR-authored content it ever sees is the diff text it reviews.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Download prior-review ledger
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Install Cursor agent CLI
run: bash "$CURSOR_REVIEW_ASSETS/install-cursor-cli.sh"
- name: Verify Cursor agent version
# The installer already asserts this once. Re-asserted here, on the
# PATH-resolved binary immediately before the review runs, so a swap
# between install and use (a CLI self-update, a stale symlink) can't
# quietly hand the review to unpinned bits — and the version still
# lands in the log for forensics.
run: |
installed="$(cursor-agent --version)"
if [ "$installed" != "$CURSOR_CLI_VERSION" ]; then
echo "::error::cursor-agent reports '${installed}', expected the pinned '${CURSOR_CLI_VERSION}'."
exit 1
fi
echo "cursor-agent ${installed} (matches CURSOR_CLI_VERSION)."
- name: Configure structured review output
env:
MODEL: ${{ matrix.model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
python3 "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode reviewer \
--out /tmp/findings-out/findings.json \
--model "$MODEL" \
--review-type "$REVIEW_TYPE" \
--init
rm -rf -- .cursor
mkdir -m 700 .cursor
python3 - <<'PY'
import json, os, sys, tempfile
if os.path.islink(".cursor"):
raise SystemExit("Refusing to write Cursor config through a symlinked .cursor directory")
config = {
"mcpServers": {
"cursor-review-output": {
"type": "stdio",
"command": sys.executable,
"args": [
os.path.join(os.environ["CURSOR_REVIEW_ASSETS"], "review-output-mcp.py"),
"--mode", "reviewer",
"--out", "/tmp/findings-out/findings.json",
"--model", os.environ["MODEL"],
"--review-type", os.environ["REVIEW_TYPE"],
],
}
}
}
cli_config = {
"permissions": {
"allow": [
"Mcp(cursor-review-output:cursor_review_record_finding)",
"Mcp(cursor-review-output:cursor_review_finish)",
],
"deny": [],
}
}
for filename, value in (("mcp.json", config), ("cli.json", cli_config)):
fd, temporary = tempfile.mkstemp(dir=".cursor", prefix=f".{filename}-")
with os.fdopen(fd, "w", encoding="utf-8") as output:
json.dump(value, output)
os.replace(temporary, os.path.join(".cursor", filename))
PY
- name: Build prompt
env:
REVIEW_TYPE: ${{ matrix.review_type }}
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
# Splice the prior-review ledger in AFTER the static instructions and
# BEFORE the diff. With no ledger (first round, kill switch off, or a
# failed fetch) the spliced prompt is BYTE-IDENTICAL to the prompt file
# — that is the no-regression property this whole feature rests on.
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" splice \
--prompt "$CURSOR_REVIEW_ASSETS/prompt-${REVIEW_TYPE}.md" \
--marker '=== BEGIN DIFF ===' \
--insert /tmp/ledger/ledger.md \
--out /tmp/prompt-head.txt
# The reviewed diff is `git diff BASE...HEAD` — attacker-authored PR
# file bytes — spliced straight into this prompt, so static literal
# fences are no control at all: the diff can contain the close fence.
# The BEGIN/END markers carry an unguessable per-prompt nonce instead
# (BE-7645), minted HERE, long after the head SHA the diff is built
# from was fixed, so a PR cannot have written it into its own bytes.
#
# Minted into a SHELL variable, never a step `env:` entry and never a
# job output: Actions prints a step's env map into the run log before
# the script runs, and consumer run logs are public. Each of the 8
# panel cells (and the judge) mints its own, so a nonce that does leak
# — a model quoting a marker back in its printed output — cannot forge
# a fence anywhere else.
diff_nonce="$(python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" mint)"
# The prompt files END with the bare `=== BEGIN DIFF ===` line, which
# is also the splice --marker above, so it has to stay verbatim in the
# .md. Drop it here and let fence-diff.py re-emit it carrying the
# nonce, so the whole attacker-authored region — the diff AND the
# incremental hunks — sits inside fences a PR cannot forge.
# fence-diff.py copies the diff bytes through unchanged.
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" strip-marker \
--file /tmp/prompt-head.txt \
--marker '=== BEGIN DIFF ==='
{
cat /tmp/prompt-head.txt
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff.patch --label DIFF --nonce "$diff_nonce"
if [ -s /tmp/pr-diff-new.patch ]; then
echo ""
# Guidance ABOUT the block stays OUTSIDE it: instructions to the
# reviewer never share a fence with untrusted data. It names the
# block BELOW it, since it now sits between two closed regions.
echo "The block below is the subset of the diff above that changed since"
echo "the last reviewed commit. Prioritize it — but the full diff above"
echo "is still in scope."
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff-new.patch \
--label "HUNKS NEW SINCE ROUND ${LEDGER_ROUNDS:-?}" \
--nonce "$diff_nonce"
fi
} > /tmp/prompt.txt
echo "Prompt size: $(wc -c < /tmp/prompt.txt) bytes"
- name: Run cursor review
# Step cap (`cell_timeout_minutes`, default 15), absorbed by
# continue-on-error (same idiom as the judge step): healthy cells finish
# in 3-7 min and every cell's p90 is under 12 min, but a stalled agent —
# almost always one that never reaches its MCP submission — used to run
# to the JOB timeout, which GitHub reports as a cancelled job and a
# cancelled run, and stretched the whole review past it. Killing the
# step instead leaves the pre-seeded status=error artifact for the judge
# to count as a non-contributing cell, exactly what the job timeout
# produced, but a cap earlier and without CANCELLING the run. The job
# cap is derived as this + 15, so that ordering holds at every value.
#
# The cap is what this `continue-on-error` absorbs, and that is all it
# absorbs: the LEG is not green on this path. `Fail the leg when the
# cell did not submit` reads the artifact back at the end of the job and
# fails it deliberately, so a cell that never submitted is a red check in
# the PR's rollup instead of a silent hole in the panel count. Keeping
# the absorption HERE rather than dropping `continue-on-error` is what
# lets the artifact upload still run, so the panel keeps consolidating.
#
# The cap is for cells that never submit. A cell that HAS submitted —
# its findings.json parses and reads `status: ok` — is ended by
# stop-on-submit.py within 30 seconds of the submission instead of
# idling to the cap (some agents keep running after
# `cursor_review_finish`). The wrapper only READS findings.json, so the
# artifact is byte-for-byte what the MCP tool wrote; it exits 0 on that
# path, and a cell that never reaches `status: ok` is not stopped, so
# it still runs to this cap and fails its leg exactly as before.
#
# The wrapper also retries Cursor's own transient capacity error: an
# agent that exits non-zero with `RetriableError: [resource_exhausted]`
# (~25s in, before recording anything) is re-run after 30s, then 90s.
# Only a cell with no recorded findings is re-run, and no retry starts
# later than 300s in, so the last attempt still has all but ~5 min of
# this cap for a full review — which is why the cap's floor is 10, not
# lower. Each retry is a `::warning::` naming the cell; a
# cell that exhausts them fails its leg exactly as before. A retry
# re-reads the whole prompt because the wrapper rewinds its stdin, so
# keep feeding it as `< /tmp/prompt.txt`: a pipe cannot be rewound,
# and turns the retries off.
continue-on-error: true
timeout-minutes: ${{ inputs.cell_timeout_minutes }}
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
MODEL: ${{ matrix.model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
# --sandbox is intentionally omitted. The hosted runner is already
# an ephemeral VM — and a `runs_on` pool must be one too: one job per
# fresh pod, no cloud identity, no private-network reach (see the
# input) — so the agent's AppArmor sandbox doesn't add
# protection — and as of cursor-agent 2026.05.05 it fails to start
# on ubuntu-latest, producing empty output.
#
# Capture the exit code without tripping the shell's `set -e`. If the
# agent fails before finishing its MCP submission, the pre-seeded
# structured artifact remains status=error. stop-on-submit.py writes
# its own `stop-on-submit:` status lines into the stderr capture.
#
# The step cap and a run cancel signal THIS shell, which would die
# without passing the signal on, leaving the wrapper and the agent's
# own process group running past the step and still able to write
# findings.json while the always() steps below read and upload it.
# So the wrapper runs in the background with the signals forwarded,
# and the shell waits it out (a trapped signal interrupts `wait`, so
# keep waiting until the wrapper is actually gone, then collect its
# real status).
CURSOR_PID=
CURSOR_SIGNALLED=
forward_signal() {
CURSOR_SIGNALLED=1
if [ -n "$CURSOR_PID" ]; then kill "-$1" "$CURSOR_PID" 2>/dev/null || true; fi
}
trap 'forward_signal INT' INT
trap 'forward_signal TERM' TERM
trap 'forward_signal HUP' HUP
python3 "$CURSOR_REVIEW_ASSETS/stop-on-submit.py" \
--retry-delays 30,90 --retry-window 300 \
--cell "$REVIEW_TYPE/$MODEL" \
--findings /tmp/findings-out/findings.json -- \
cursor-agent \
--print \
--trust \
--approve-mcps \
--model "$MODEL" \
< /tmp/prompt.txt \
> /tmp/review-raw.txt 2>/tmp/review-stderr.txt &
CURSOR_PID=$!
while kill -0 "$CURSOR_PID" 2>/dev/null; do
wait "$CURSOR_PID" || true
done
wait "$CURSOR_PID" && CURSOR_EXIT=0 || CURSOR_EXIT=$?
trap - INT TERM HUP
echo "$CURSOR_EXIT" > /tmp/review-exit-code
echo "cursor-agent exit code: $CURSOR_EXIT"
echo "=== Raw output (first 500 chars) ==="
head -c 500 /tmp/review-raw.txt
echo ""
echo "=== Stderr ==="
cat /tmp/review-stderr.txt
# A signalled step still fails as one, as it did before the wrapper.
if [ -n "$CURSOR_SIGNALLED" ]; then exit "$CURSOR_EXIT"; fi
- name: Show structured findings
if: always()
run: |
echo "=== Structured findings ==="
cat /tmp/findings-out/findings.json
echo ""
- name: Upload findings artifact
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: findings-${{ matrix.review_type }}-${{ matrix.model }}
path: /tmp/findings-out/findings.json
if-no-files-found: error
retention-days: 7
- name: Fail the leg when the cell did not submit
# Panel integrity has to be readable from the CHECK-RUN ROLLUP, not only
# from a line in this job's log. Before this step a cell that never
# submitted — overwhelmingly the 15-minute `Run cursor review` cap above,
# absorbed by its `continue-on-error` — left the pre-seeded status=error
# artifact and exited GREEN, so a reader of `statusCheckRollup` saw a
# complete panel while `Aggregate panel findings` was quietly reporting
# "2/6 cells contributed findings". Measured on one consumer repo over 92
# panel runs: 38 runs had at least one errored leg, 52 of 552 cells
# errored, and every leg check in every one of those runs reported
# `success` (BE-15554).
#
# Deliberately AFTER the upload, so failing here costs the panel nothing:
# the artifact is already published, `consolidate` and `notify-complete`
# gate on `needs.review.result != 'skipped'` (a FAILED matrix is not a
# skipped one), and `post-review` gates on `consolidate`. The
# consolidated review still posts — the only thing that changes is that
# the gap is now visible. `Panel integrity` further down aggregates the
# same fact into one panel-level context.
#
# SCOPE, because the check reads stronger than it is: the verdict is the
# `status` this cell's OWN agent wrote, and that agent runs `--trust`
# with shell access over attacker-authored diff text, so a prompt-injected
# cell can write status=ok with no findings and green both this leg and
# the panel count. This is an AVAILABILITY signal — it catches the stalls,
# crashes and step caps that are what every observed failure has been —
# not an attestation that a review happened. A forgery-resistant count
# needs the submission recorded outside the cell's own writable job.
if: always()
env:
MODEL: ${{ matrix.model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
# findings.json is untrusted: this cell's own agent runs `--trust`
# with shell access in this job, so it can write whatever it likes
# there. Read the status defensively (a missing or unparseable file is
# "did not submit", not a traceback) and sanitize before it reaches a
# ::workflow command:: line. The substitution REPLACES a disallowed
# character rather than dropping it — deleting would let a crafted
# "o k" collapse into the one value that passes.
#
# `ValueError`, not `json.JSONDecodeError`: the file is opened as
# utf-8, so invalid UTF-8 — reachable precisely BECAUSE these bytes
# are agent-written — raises `UnicodeDecodeError`, which is NOT a
# JSONDecodeError. Under `set -e` that traceback would kill the step
# and lose the `::error::` naming which cell failed, turning the one
# case this step exists to report into an unlabelled crash. Both
# exception types subclass `ValueError`, so one clause covers the pair.
status=$(python3 - <<'PY'
import json, re
try:
with open("/tmp/findings-out/findings.json", encoding="utf-8") as f:
cell = json.load(f)
except (OSError, ValueError):
cell = None
value = cell.get("status") if isinstance(cell, dict) else None
if not isinstance(value, str):
value = "error"
print(re.sub(r"[^A-Za-z0-9_.-]", "_", value)[:32] or "error")
PY
)
if [ "$status" != "ok" ]; then
echo "::error::Reviewer cell ${REVIEW_TYPE}/${MODEL} did not submit a review (status=$status). Its findings artifact was uploaded and the panel still consolidates; this leg is red so the gap is visible in the rollup."
exit 1
fi
echo "Reviewer cell ${REVIEW_TYPE}/${MODEL} submitted its findings."
review-openai-direct:
# An OPT-IN pair of cells (adversarial + edge-case, the same two passes and
# prompts as a Cursor model) that reach their model through the OpenAI API
# directly, via the Codex CLI, instead of through Cursor. By default they
# REPLACE the Cursor-hosted OpenAI cells (preflight drops that id from the
# panel list) so the lane is reviewed once, not twice; set
# `openai_direct_replaces_cursor_openai: false` to run both for a
# side-by-side comparison. Default OFF:
# `openai_direct_model` is '' unless a caller sets it, and this job is then
# skipped outright, so every enrolled repo sees exactly today's behaviour
# until it opts in.
#
# Why a SEPARATE job rather than another entry in the `review` matrix:
# that matrix's model list is validated against the live CURSOR catalog in
# `preflight`, and a delisted id there fails the run loud by design
# (BE-2627). A direct-API id is not in Cursor's catalog at all, so feeding
# it to that list would fail preflight for the right reason and the wrong
# cause. Separation also means a failure here can neither cancel nor skip
# a Cursor matrix leg.
#
# How the judge picks it up: `consolidate` downloads `pattern: findings-*`
# and globs `findings-*/findings.json`, so this cell's artifact
# (`findings-direct-...`) is read alongside the others, and `consolidate`
# lists this job in `needs:` so it never downloads before the upload
# lands. The `direct-` prefix is what `Aggregate panel findings` keys on
# to tell these cells apart from the Cursor ones (aggregate-panel.py).
#
# Credential posture: `contents: read` only, no write-scoped token (see
# SECURITY.md), and the only PR-authored content the agent sees is the
# same nonce-fenced diff text — this job does NOT check out the PR. The
# OpenAI key reaches `codex exec` as CODEX_API_KEY in that ONE step's env
# and is never written to disk (no `codex login`, whose auth.json the
# read-only sandbox could still read), and the sandboxed shell's env is
# cut to the core set so the agent cannot echo it back.
#
# Gating follows the role (preflight's `openai_direct_counts`):
# - REPLACING the Cursor OpenAI lane: these cells ARE that lane, so they
# gate exactly like a Cursor cell — counted in ok_count/total, which
# `Panel integrity` and the auto-approve gate read, and the leg goes red
# when the cell did not submit. While they were advisory, a failed
# direct cell cost nothing against `approve_max_failed_reviewers`, so a
# run could approve with the OpenAI lane silent; counted, it spends that
# allowance like a failed Cursor cell, so the gate covers the full panel
# again.
# - SIDE BY SIDE (replace false): ADVISORY, as when the backend was first
# characterised — job-level `continue-on-error`, never counted — since
# the Cursor OpenAI cells already gate that lane.
#
# Scope: one model, one round, no retry.
name: '${{ matrix.review_type }} direct (${{ inputs.openai_direct_model }})'
needs: [gate, diff-size, preflight, ledger]
if: >-
needs.preflight.outputs.openai_direct == 'true'
&& needs.gate.outputs.should_run == 'true'
&& needs.gate.outputs.already_reviewed != 'true'
&& needs.diff-size.outputs.within_cap == 'true'
# GitHub-hosted, NOT the caller's `runs_on` pool: this job holds
# OPENAI_API_KEY, and a pool is where a prompt-injected model cell may
# have run. Only CURSOR_API_KEY-only, read-only jobs may follow `runs_on`.
runs-on: ubuntu-latest
# Advisory only side by side; when replacing, a failed cell is as red as a
# failed Cursor cell.
continue-on-error: ${{ needs.preflight.outputs.openai_direct_counts != 'true' }}
# Matches the `review` job's cap so the judge's budget reasoning (see
# `review`) holds for this cell too; the agent step caps lower, at
# `cell_timeout_minutes`. DERIVED from that input, the same +15 as the
# Cursor cells above and for the same overhead; see that job's note.
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.cell_job_timeout) }}
permissions:
contents: read
strategy:
fail-fast: false
matrix:
review_type: [adversarial, edge-case]
steps:
- name: Seed default findings artifact
# Same contract as the `review` job: pre-seed status=error so the cell
# ALWAYS appears in the panel summary even if a later step dies. The
# MCP output tool overwrites this on success.
env:
MODEL: ${{ inputs.openai_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
mkdir -p /tmp/findings-out
python3 - <<'PY'
import json, os
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"status": "error",
"error": "Direct-API cell did not reach the submission step.",
"findings": [],
}
with open("/tmp/findings-out/findings.json", "w", encoding="utf-8") as f:
json.dump(record, f, indent=2)
PY
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Download reviewed diff
# Built once in the diff-size job (generated files already excluded),
# shared here, so this cell needs no PR checkout of its own.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Download prior-review ledger
# Same artifact, same tolerance as the `review` job: absent on round 1.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Check the API key is present
id: key
# Belt and braces: preflight already keeps this job off when the key is
# absent. Should the two ever disagree, this attributes the errored
# record clearly rather than leaving a confusing CLI auth failure.
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
if [ -z "${OPENAI_API_KEY:-}" ]; then
echo "::warning::openai_direct_model is set but the OPENAI_API_KEY secret is absent, so the direct-API cell is skipped. Pass the secret through from the caller to enable it."
python3 -c 'import json; p = "/tmp/findings-out/findings.json"; r = json.load(open(p)); r["error"] = "OPENAI_API_KEY secret was not provided to the reusable workflow."; json.dump(r, open(p, "w"), indent=2)'
echo "present=false" >> "$GITHUB_OUTPUT"
else
echo "present=true" >> "$GITHUB_OUTPUT"
fi
- name: Install Codex CLI
if: steps.key.outputs.present == 'true'
# The pin lives in .github/cursor-review/package.json in THIS repo and
# arrives with the assets checkout above, so it is resolved at the same
# SHA as the prompts and scripts. Mirrors the groom precedent exactly,
# including rejecting a non-exact pin: an inline `npm install -g
# pkg@1.2.3` is invisible to every dependency ecosystem.
run: |
manifest="$CURSOR_REVIEW_ASSETS/package.json"
if [ ! -f "$manifest" ]; then
echo "::error::$manifest is missing — it is the single source of truth for the direct-API cell's CLI pin."
exit 1
fi
if ! version=$(jq -r '
if type != "object" then ""
elif (.dependencies | type) != "object" then ""
else (.dependencies["@openai/codex"] // "")
end' "$manifest"); then
echo "::error::$manifest is not valid JSON — it is the single source of truth for the direct-API cell's CLI pin."
exit 1
fi
version="$(printf '%s' "$version" | tr -d '\r\n')"
case "$version" in
""|*[!0-9.]*)
echo "::error::dependencies[\"@openai/codex\"] must be an EXACT version (digits and dots only, no ^ or ~); got a value this job will not install."
exit 1 ;;
esac
echo "CODEX_CLI_VERSION=$version" >> "$GITHUB_ENV"
npm install -g "@openai/codex@${version}"
- name: Verify Codex CLI version
if: steps.key.outputs.present == 'true'
# Re-asserted on the PATH-resolved binary immediately before the review,
# so a swap between install and use cannot hand the review to unpinned
# bits, and the version lands in the log for forensics.
run: |
# stdout only, first line (`codex-cli 0.162.0`): a stray stderr
# notice must not become the last field compared below.
installed="$(codex --version 2>/dev/null | head -n 1 | tr -d '\r' | awk '{print $NF}')"
if [ "$installed" != "$CODEX_CLI_VERSION" ]; then
echo "::error::codex reports '${installed}', expected the pinned '${CODEX_CLI_VERSION}'."
exit 1
fi
echo "codex ${installed}"
- name: Build prompt
if: steps.key.outputs.present == 'true'
# Byte-identical construction to the Cursor cells' `Build prompt`, so a
# finding difference is attributable to the model or the backend rather
# than to the prompt: the same prompt-<review_type>.md with the same
# prior-review ledger spliced in, the same marker stripped and
# re-emitted by fence-diff.py, the same new-hunks block from round 2
# on, and a fresh per-prompt nonce minted into a shell variable (never
# a step `env:`) so a leaked marker from one cell cannot forge a fence
# in another. See that step for the full rationale.
env:
REVIEW_TYPE: ${{ matrix.review_type }}
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" splice \
--prompt "$CURSOR_REVIEW_ASSETS/prompt-${REVIEW_TYPE}.md" \
--marker '=== BEGIN DIFF ===' \
--insert /tmp/ledger/ledger.md \
--out /tmp/prompt-head.txt
diff_nonce="$(python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" mint)"
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" strip-marker \
--file /tmp/prompt-head.txt \
--marker '=== BEGIN DIFF ==='
{
cat /tmp/prompt-head.txt
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff.patch --label DIFF --nonce "$diff_nonce"
if [ -s /tmp/pr-diff-new.patch ]; then
echo ""
echo "The block below is the subset of the diff above that changed since"
echo "the last reviewed commit. Prioritize it — but the full diff above"
echo "is still in scope."
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff-new.patch \
--label "HUNKS NEW SINCE ROUND ${LEDGER_ROUNDS:-?}" \
--nonce "$diff_nonce"
fi
} > /tmp/prompt.txt
- name: Run direct-API review
if: steps.key.outputs.present == 'true'
continue-on-error: true
# Capped well under the job so a hung agent trips the STEP and the
# seeded artifact still uploads below, rather than tripping the job and
# discarding the cell. Same `cell_timeout_minutes` the Cursor cells get.
timeout-minutes: ${{ inputs.cell_timeout_minutes }}
env:
MODEL: ${{ inputs.openai_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
# `codex exec` reads its API key from this variable, so the key lives
# only in this step's process env: never argv (visible in the process
# list), never a file (`codex login` writes ~/.codex/auth.json, which
# the read-only sandbox can still READ, so a prompt-injected agent
# could encode it into a finding). Verified against 0.162.0.
CODEX_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
mkdir -p /tmp/findings-out
# A fresh, empty home under RUNNER_TEMP (emptied after every job): no
# stale credential or config from anything else that ran on this
# runner, nothing persisted for the next, and not under /tmp, where
# 0.162.0 refuses to create its helper binaries.
CODEX_HOME="$(mktemp -d -p "$RUNNER_TEMP")"
export CODEX_HOME
python3 "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode reviewer \
--out /tmp/findings-out/findings.json \
--model "$MODEL" \
--review-type "$REVIEW_TYPE" \
--init
# The SAME MCP submission tool the Cursor cells use, so the findings
# schema the judge reads is produced by one implementation for both
# backends. `default_tools_approval_mode=approve` is required: under
# `codex exec`'s default policy the tool calls are rejected and the
# cell submits nothing. `shell_environment_policy.inherit=core` hands
# the agent's shell only HOME/PATH/etc., never CODEX_API_KEY.
args_toml="$(python3 - <<'PY'
import json, os
print(json.dumps([
os.path.join(os.environ["CURSOR_REVIEW_ASSETS"], "review-output-mcp.py"),
"--mode", "reviewer",
"--out", "/tmp/findings-out/findings.json",
"--model", os.environ["MODEL"],
"--review-type", os.environ["REVIEW_TYPE"],
]))
PY
)"
codex exec --json --ignore-user-config --skip-git-repo-check \
-s read-only \
-c shell_environment_policy.inherit=core \
-c model="$MODEL" \
-c model_reasoning_effort=max \
-c mcp_servers.cursor_review_output.command=python3 \
-c mcp_servers.cursor_review_output.default_tools_approval_mode=approve \
-c "mcp_servers.cursor_review_output.args=$args_toml" \
< /tmp/prompt.txt > /tmp/codex-events.jsonl
- name: Report cell outcome
if: always()
env:
MODEL: ${{ inputs.openai_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
COUNTS: ${{ needs.preflight.outputs.openai_direct_counts }}
# Status and a count only — NOT the findings verbatim, unlike the Cursor
# cells: the run log is public, and finding bodies are model output
# steered by PR-authored text. The full record still reaches the judge
# through the artifact below.
run: |
read -r status count < <(python3 - <<'PY'
import json, re
try:
with open("/tmp/findings-out/findings.json", encoding="utf-8") as f:
cell = json.load(f)
except (OSError, ValueError):
cell = None
value = cell.get("status") if isinstance(cell, dict) else None
if not isinstance(value, str):
value = "error"
findings = cell.get("findings") if isinstance(cell, dict) else None
print(re.sub(r"[^A-Za-z0-9_.-]", "_", value)[:32] or "error",
len(findings) if isinstance(findings, list) else 0)
PY
)
echo "Direct-API cell: status=${status}, ${count} finding(s)."
if [ "$status" = "ok" ]; then
echo "Direct-API cell ${REVIEW_TYPE}/${MODEL} submitted its findings."
else
# WHY it failed, not just THAT it did. The agent reports an
# API-level failure in its STRUCTURED OUTPUT, which is redirected
# to a file and — unlike the Cursor cells, which echo 500 chars of
# raw output and all of stderr — never echoed, because that file
# also holds the agent's prose. So a real outage
# (`insufficient_quota` / `credit_balance_exhausted`, naming its
# own cause) was discarded and this log showed only a non-zero
# exit, leaving the lane's failures to be inferred from job
# DURATION. agent-error.py prints an ALLOWLIST of provider error
# metadata and never the prose, and exits 0 on anything — a
# truncated or non-JSON file must not turn the diagnosis into a
# second failure.
# `|| true` because this step runs under `bash -e`: the script's
# own exit-0 contract cannot cover a script that never STARTED
# (a skipped assets checkout, so `python3` exits 2), and aborting
# here would lose the status and `::warning::` lines below.
python3 "$CURSOR_REVIEW_ASSETS/agent-error.py" \
--events /tmp/codex-events.jsonl \
--label "${REVIEW_TYPE}/${MODEL}" || true
if [ "$COUNTS" = "true" ]; then
# Failed AFTER the upload below, by `Fail the leg when the cell did
# not submit`, so the errored record still reaches the judge.
echo "Direct-API cell ${REVIEW_TYPE}/${MODEL} did not submit (status=$status); it replaces the Cursor OpenAI lane, so it counts as a failed reviewer."
else
echo "::warning::Direct-API cell ${REVIEW_TYPE}/${MODEL} did not submit (status=$status). Its record still reaches the judge; this leg stays green because the cell is advisory."
fi
fi
- name: Upload findings artifact
if: always()
# `findings-*` so `consolidate` globs it; `direct-` so it can never
# collide with a Cursor cell's `findings-<review_type>-<model>` (with
# replacement off the two may share an id) and so `consolidate` can
# tell it apart. The id is charset-checked in preflight.
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: findings-direct-${{ matrix.review_type }}-${{ inputs.openai_direct_model }}
path: /tmp/findings-out/findings.json
if-no-files-found: error
retention-days: 7
- name: Fail the leg when the cell did not submit
# Only when these cells REPLACE the Cursor OpenAI lane — the same
# rollup-visibility contract as the `review` job's step of this name
# (BE-15554), and like it deliberately AFTER the upload, so the errored
# record still reaches the judge and the consolidated review still
# posts. Side by side the cell is advisory and this step is skipped.
# Same availability-not-attestation scope as that step: the status is
# read from a file this cell's own agent could write.
if: always() && needs.preflight.outputs.openai_direct_counts == 'true'
env:
MODEL: ${{ inputs.openai_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
# Read defensively and sanitized for a ::workflow command:: line, as
# in the `review` job (`ValueError` covers invalid UTF-8 too).
status=$(python3 - <<'PY'
import json, re
try:
with open("/tmp/findings-out/findings.json", encoding="utf-8") as f:
cell = json.load(f)
except (OSError, ValueError):
cell = None
value = cell.get("status") if isinstance(cell, dict) else None
if not isinstance(value, str):
value = "error"
print(re.sub(r"[^A-Za-z0-9_.-]", "_", value)[:32] or "error")
PY
)
if [ "$status" != "ok" ]; then
echo "::error::Direct-API reviewer cell ${REVIEW_TYPE}/${MODEL} did not submit a review (status=$status). It replaces the Cursor OpenAI lane, so it counts as a failed reviewer; its findings artifact was uploaded and the panel still consolidates."
exit 1
fi
echo "Direct-API reviewer cell ${REVIEW_TYPE}/${MODEL} submitted its findings."
review-anthropic-direct:
# The Anthropic twin of `review-openai-direct`: the same OPT-IN pair of
# cells (adversarial + edge-case), reaching their model through the
# Anthropic API directly, via the Claude Code CLI, instead of through
# Cursor. Everything that job's header says — why it is a separate job, how
# the judge picks it up, gating by role (here preflight's
# `anthropic_direct_counts`), scope — holds here; only the differences are
# noted below.
#
# The one deliberate difference: this agent ALSO reads a read-only
# checkout of the PR (`_pr`, its working directory) with Read, Grep and
# Glob — no Bash or other code-running tool — because a diff-only cell
# misses every finding that needs a file outside the diff.
#
# Credential posture: `contents: read` only, no write-scoped token (see
# SECURITY.md); the PR checkout persists no credential. ANTHROPIC_API_KEY
# reaches `claude` in that ONE step's env and is never written to disk.
# The agent cannot run code, and its file tools cannot reach
# `/proc/self/environ`: `--restricted` confines them to the checkout, and
# deny rules on /proc and /sys hold independently of that flag. The
# literal-match guard on the record before upload is a last tripwire.
name: '${{ matrix.review_type }} direct (${{ inputs.anthropic_direct_model }})'
needs: [gate, diff-size, preflight, ledger]
if: >-
needs.preflight.outputs.anthropic_direct == 'true'
&& needs.gate.outputs.should_run == 'true'
&& needs.gate.outputs.already_reviewed != 'true'
&& needs.diff-size.outputs.within_cap == 'true'
# GitHub-hosted, never `runs_on`: this job holds ANTHROPIC_API_KEY (see
# `review-openai-direct`).
runs-on: ubuntu-latest
continue-on-error: ${{ needs.preflight.outputs.anthropic_direct_counts != 'true' }}
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.cell_job_timeout) }}
permissions:
contents: read
strategy:
fail-fast: false
matrix:
review_type: [adversarial, edge-case]
steps:
- name: Seed default findings artifact
# Same contract as `review-openai-direct`'s seed.
env:
MODEL: ${{ inputs.anthropic_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
mkdir -p /tmp/findings-out
python3 - <<'PY'
import json, os
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"status": "error",
"error": "Direct-API cell did not reach the submission step.",
"findings": [],
}
with open("/tmp/findings-out/findings.json", "w", encoding="utf-8") as f:
json.dump(record, f, indent=2)
PY
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Checkout PR repo
# The read-only tree the agent's file tools read: the PR head, the
# RIGHT side of the reviewed diff (the default merge ref would mix in
# base-only changes and shift line numbers). No credential persisted.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
path: _pr
fetch-depth: 1
persist-credentials: false
- name: Remove symlinks from the PR checkout
# A symlink planted in the PR could lead the file tools outside the
# tree (e.g. to the runner's home), so none survive into the review.
run: find _pr -type l -delete
- name: Remove PR-authored Claude config
# The Cursor cells' `rm -rf .cursor`, for this CLI: `_pr` is claude's
# cwd, so a PR-planted `.claude/settings*.json` (env such as
# ANTHROPIC_BASE_URL, hooks, extra directories) or `.mcp.json` must
# never be there to load. `--restricted` and `--setting-sources ""`
# already ignore them; this removes them outright. CLAUDE.md stays:
# `--setting-sources ""` keeps it from loading as instructions (on the
# pinned CLI a planted "reply with one word" CLAUDE.md was ignored),
# and the agent can still Read it as ordinary review context.
run: rm -rf _pr/.claude _pr/.mcp.json _pr/CLAUDE.local.md
- name: Download reviewed diff
# Built once in the diff-size job (generated files already excluded),
# shared here, so this cell needs no PR checkout of its own.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Download prior-review ledger
# Same artifact, same tolerance as the `review` job: absent on round 1.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Check the API key is present
id: key
# Belt and braces, as in `review-openai-direct`.
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
if [ -z "${ANTHROPIC_API_KEY:-}" ]; then
echo "::warning::anthropic_direct_model is set but the ANTHROPIC_API_KEY secret is absent, so the direct-API Anthropic cell is skipped. Pass the secret through from the caller to enable it."
python3 -c 'import json; p = "/tmp/findings-out/findings.json"; r = json.load(open(p)); r["error"] = "ANTHROPIC_API_KEY secret was not provided to the reusable workflow."; json.dump(r, open(p, "w"), indent=2)'
echo "present=false" >> "$GITHUB_OUTPUT"
else
echo "present=true" >> "$GITHUB_OUTPUT"
fi
- name: Install Claude Code CLI
if: steps.key.outputs.present == 'true'
# Pinned in .github/cursor-review/package.json, read exactly as
# `review-openai-direct`'s `Install Codex CLI` reads its pin.
run: |
manifest="$CURSOR_REVIEW_ASSETS/package.json"
if [ ! -f "$manifest" ]; then
echo "::error::$manifest is missing — it is the single source of truth for the direct-API cell's CLI pin."
exit 1
fi
if ! version=$(jq -r '
if type != "object" then ""
elif (.dependencies | type) != "object" then ""
else (.dependencies["@anthropic-ai/claude-code"] // "")
end' "$manifest"); then
echo "::error::$manifest is not valid JSON — it is the single source of truth for the direct-API cell's CLI pin."
exit 1
fi
version="$(printf '%s' "$version" | tr -d '\r\n')"
case "$version" in
""|*[!0-9.]*)
echo "::error::dependencies[\"@anthropic-ai/claude-code\"] must be an EXACT version (digits and dots only, no ^ or ~); got a value this job will not install."
exit 1 ;;
esac
echo "CLAUDE_CLI_VERSION=$version" >> "$GITHUB_ENV"
npm install -g "@anthropic-ai/claude-code@${version}"
- name: Verify Claude Code CLI version
if: steps.key.outputs.present == 'true'
# As `Verify Codex CLI version`: `claude --version` prints
# `2.1.286 (Claude Code)`, so the FIRST field is the version.
run: |
installed="$(claude --version 2>/dev/null | head -n 1 | tr -d '\r' | awk '{print $1}')"
if [ "$installed" != "$CLAUDE_CLI_VERSION" ]; then
echo "::error::claude reports '${installed}', expected the pinned '${CLAUDE_CLI_VERSION}'."
exit 1
fi
echo "claude ${installed}"
# The confinement rests on these flags, so a bump whose CLI dropped
# or renamed one fails HERE, by name, rather than at argv parsing
# mid-review — or, worse, by silently running unconfined.
help="$(claude --help 2>&1)"
for flag in --restricted --setting-sources --strict-mcp-config \
--disallowedTools --permission-prompts --no-session-persistence; do
if ! printf '%s\n' "$help" | grep -qE -- "(^|[[:space:],])${flag}([[:space:],]|$)"; then
echo "::error::claude ${installed} does not advertise ${flag}, which the direct-API cell's confinement relies on."
exit 1
fi
done
- name: Build prompt
if: steps.key.outputs.present == 'true'
# Byte-identical construction to the Cursor cells' `Build prompt`, so a
# finding difference is attributable to the model or the backend rather
# than to the prompt: the same prompt-<review_type>.md with the same
# prior-review ledger spliced in, the same marker stripped and
# re-emitted by fence-diff.py, the same new-hunks block from round 2
# on, and a fresh per-prompt nonce minted into a shell variable (never
# a step `env:`) so a leaked marker from one cell cannot forge a fence
# in another. See that step for the full rationale.
env:
REVIEW_TYPE: ${{ matrix.review_type }}
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" splice \
--prompt "$CURSOR_REVIEW_ASSETS/prompt-${REVIEW_TYPE}.md" \
--marker '=== BEGIN DIFF ===' \
--insert /tmp/ledger/ledger.md \
--out /tmp/prompt-head.txt
diff_nonce="$(python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" mint)"
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" strip-marker \
--file /tmp/prompt-head.txt \
--marker '=== BEGIN DIFF ==='
{
cat /tmp/prompt-head.txt
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff.patch --label DIFF --nonce "$diff_nonce"
if [ -s /tmp/pr-diff-new.patch ]; then
echo ""
echo "The block below is the subset of the diff above that changed since"
echo "the last reviewed commit. Prioritize it — but the full diff above"
echo "is still in scope."
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff-new.patch \
--label "HUNKS NEW SINCE ROUND ${LEDGER_ROUNDS:-?}" \
--nonce "$diff_nonce"
fi
} > /tmp/prompt.txt
- name: Run direct-API review
if: steps.key.outputs.present == 'true'
continue-on-error: true
# Step-capped below the job, as in `review-openai-direct`.
timeout-minutes: ${{ inputs.cell_timeout_minutes }}
working-directory: _pr
env:
MODEL: ${{ inputs.anthropic_direct_model }}
EFFORT: ${{ needs.preflight.outputs.anthropic_direct_effort }}
REVIEW_TYPE: ${{ matrix.review_type }}
# Process env of this ONE step only: never argv, never a file.
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
# No telemetry or error report may carry private-diff context.
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1'
run: |
mkdir -p /tmp/findings-out
# A fresh, empty config dir under RUNNER_TEMP, as CODEX_HOME is.
CLAUDE_CONFIG_DIR="$(mktemp -d -p "$RUNNER_TEMP")"
export CLAUDE_CONFIG_DIR
# `-I` on every python3 here: the cwd is the PR checkout, and a stdin
# script puts '' (the cwd) first on sys.path, so a PR-planted json.py
# would run with ANTHROPIC_API_KEY in its env. Isolated mode drops it.
python3 -I "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode reviewer \
--out /tmp/findings-out/findings.json \
--model "$MODEL" \
--review-type "$REVIEW_TYPE" \
--init
# The SAME MCP submission tool the Cursor and Codex cells use, as the
# only MCP server (`--strict-mcp-config`). The agent's tools are
# Read, Grep and Glob, confined to this checkout by `--restricted`,
# plus the two submission calls. The `--disallowedTools` deny rules
# (a Read rule covers Grep and Glob too) are a second, independent
# layer over /proc and /sys — `/proc/self/environ` holds the key — so
# a CLI bump that loosened `--restricted` alone still cannot reach it.
mcp_config="$(python3 -I - <<'PY'
import json, os
print(json.dumps({"mcpServers": {"cursor-review-output": {
"command": "python3",
"args": [
"-I",
os.path.join(os.environ["CURSOR_REVIEW_ASSETS"], "review-output-mcp.py"),
"--mode", "reviewer",
"--out", "/tmp/findings-out/findings.json",
"--model", os.environ["MODEL"],
"--review-type", os.environ["REVIEW_TYPE"],
],
}}}))
PY
)"
# The result JSON goes to a file that is never echoed: the run log
# is public and the result is model output steered by PR text.
# Deliberately NOT `--bare`: on the pinned CLI it drops Grep and Glob
# from `--tools`, leaving the agent Read alone, which cannot search
# the checkout. What `--bare` would skip is already off here: no
# settings, hooks or plugins (`--setting-sources ""` and a fresh
# CLAUDE_CONFIG_DIR, which also keep CLAUDE.md from loading as
# instructions), no other MCP server (`--strict-mcp-config`), no
# telemetry (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC), and auth is
# the env key alone.
claude -p --restricted --setting-sources "" \
--tools "Read,Grep,Glob" \
--strict-mcp-config --mcp-config "$mcp_config" \
--allowedTools "Read,Grep,Glob,mcp__cursor-review-output__cursor_review_record_finding,mcp__cursor-review-output__cursor_review_finish" \
--disallowedTools "Read(//proc/**),Read(//sys/**)" \
--permission-prompts none \
--model "$MODEL" --effort "$EFFORT" \
--output-format json --no-session-persistence \
< /tmp/prompt.txt > /tmp/claude-result.json
- name: Refuse a record carrying the API key
# groom.yml's finder guard: should a prompt-injected agent get the key
# into its findings, error the record rather than publish it (to the
# judge, and from there to the PR). Literal match only.
if: always()
env:
MODEL: ${{ inputs.anthropic_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
set -uo pipefail
out=/tmp/findings-out/findings.json
if [ -n "${ANTHROPIC_API_KEY:-}" ] && [ -f "$out" ] \
&& LC_ALL=C grep -qF -- "$ANTHROPIC_API_KEY" "$out"; then
echo "::error::direct-API Anthropic findings contain ANTHROPIC_API_KEY — refusing to publish (possible prompt-injection exfil)."
python3 - <<'PY'
import json, os
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"status": "error",
"error": "findings contained the API key; refusing to publish",
"findings": [],
}
with open("/tmp/findings-out/findings.json", "w", encoding="utf-8") as f:
json.dump(record, f, indent=2)
PY
fi
- name: Report cell outcome
if: always()
env:
MODEL: ${{ inputs.anthropic_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
COUNTS: ${{ needs.preflight.outputs.anthropic_direct_counts }}
# Status and a count only — NOT the findings verbatim, unlike the Cursor
# cells: the run log is public, and finding bodies are model output
# steered by PR-authored text. The full record still reaches the judge
# through the artifact below.
run: |
read -r status count < <(python3 - <<'PY'
import json, re
try:
with open("/tmp/findings-out/findings.json", encoding="utf-8") as f:
cell = json.load(f)
except (OSError, ValueError):
cell = None
value = cell.get("status") if isinstance(cell, dict) else None
if not isinstance(value, str):
value = "error"
findings = cell.get("findings") if isinstance(cell, dict) else None
print(re.sub(r"[^A-Za-z0-9_.-]", "_", value)[:32] or "error",
len(findings) if isinstance(findings, list) else 0)
PY
)
echo "Direct-API cell: status=${status}, ${count} finding(s)."
if [ "$status" = "ok" ]; then
echo "Direct-API cell ${REVIEW_TYPE}/${MODEL} submitted its findings."
else
# WHY it failed, not just THAT it did. The agent reports an
# API-level failure in its STRUCTURED OUTPUT, which is redirected
# to a file and — unlike the Cursor cells, which echo 500 chars of
# raw output and all of stderr — never echoed, because that file
# also holds the agent's prose. So a real outage
# (`insufficient_quota` / `credit_balance_exhausted`, naming its
# own cause) was discarded and this log showed only a non-zero
# exit, leaving the lane's failures to be inferred from job
# DURATION. agent-error.py prints an ALLOWLIST of provider error
# metadata and never the prose, and exits 0 on anything — a
# truncated or non-JSON file must not turn the diagnosis into a
# second failure.
# `|| true` because this step runs under `bash -e`: the script's
# own exit-0 contract cannot cover a script that never STARTED
# (a skipped assets checkout, so `python3` exits 2), and aborting
# here would lose the status and `::warning::` lines below.
python3 "$CURSOR_REVIEW_ASSETS/agent-error.py" \
--events /tmp/claude-result.json \
--label "${REVIEW_TYPE}/${MODEL}" || true
if [ "$COUNTS" = "true" ]; then
# Failed AFTER the upload below, by `Fail the leg when the cell did
# not submit`, so the errored record still reaches the judge.
echo "Direct-API cell ${REVIEW_TYPE}/${MODEL} did not submit (status=$status); it replaces the Cursor Anthropic lane, so it counts as a failed reviewer."
else
echo "::warning::Direct-API cell ${REVIEW_TYPE}/${MODEL} did not submit (status=$status). Its record still reaches the judge; this leg stays green because the cell is advisory."
fi
fi
- name: Upload findings artifact
if: always()
# `findings-*` so `consolidate` globs it; `direct-` so it can never
# collide with a Cursor cell's `findings-<review_type>-<model>` (with
# replacement off the two may share an id) and so `consolidate` can
# tell it apart. The id is charset-checked in preflight.
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: findings-direct-${{ matrix.review_type }}-${{ inputs.anthropic_direct_model }}
path: /tmp/findings-out/findings.json
if-no-files-found: error
retention-days: 7
- name: Record token usage
# The API's own token counts for this cell, as Claude Code totals them
# across its calls, so a caller can measure what the cells cost without
# an Admin API key. Counts only — no prices (they vary by contract and
# over time) and nothing model-written: the result JSON is model output
# steered by PR text, so only its integers and model ids are copied.
# `measured` is false when the cell left no result (a timeout kills
# it first) or any count in it is malformed, never a guessed zero.
# Best effort, like the upload: accounting must never fail a cell.
if: always() && steps.key.outputs.present == 'true'
continue-on-error: true
env:
MODEL: ${{ inputs.anthropic_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: |
mkdir -p /tmp/usage-out
python3 -I - <<'PY'
import json, os, re
malformed = []
def count(value, field):
# A token count is a plain non-negative integer; absent reads as
# 0. Anything else makes the whole record unmeasured.
if value is None:
return 0
if type(value) is int and value >= 0:
return value
malformed.append(field)
return 0
def mapping(value, field):
if value is None or isinstance(value, dict):
return value or {}
malformed.append(field)
return {}
try:
with open("/tmp/claude-result.json", encoding="utf-8") as f:
result = json.load(f)
except (OSError, ValueError):
result = None
if not isinstance(result, dict):
result = {}
usage = result.get("usage")
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"run_attempt": int(os.environ.get("RUN_ATTEMPT") or 0),
"measured": False,
}
if isinstance(usage, dict):
written = mapping(usage.get("cache_creation"), "cache_creation")
totals = {
"input_tokens": count(usage.get("input_tokens"), "input_tokens"),
"output_tokens": count(usage.get("output_tokens"), "output_tokens"),
"cache_read_input_tokens": count(usage.get("cache_read_input_tokens"), "cache_read_input_tokens"),
"cache_creation_input_tokens": count(usage.get("cache_creation_input_tokens"), "cache_creation_input_tokens"),
"ephemeral_5m_input_tokens": count(written.get("ephemeral_5m_input_tokens"), "ephemeral_5m_input_tokens"),
"ephemeral_1h_input_tokens": count(written.get("ephemeral_1h_input_tokens"), "ephemeral_1h_input_tokens"),
}
# Per model, in case the CLI ever spends on a second one.
models = {}
for name, m in mapping(result.get("modelUsage"), "modelUsage").items():
if not re.fullmatch(r"[A-Za-z0-9._-]{1,100}", name) or not isinstance(m, dict):
malformed.append("modelUsage")
continue
models[name] = {
"input_tokens": count(m.get("inputTokens"), "inputTokens"),
"output_tokens": count(m.get("outputTokens"), "outputTokens"),
"cache_read_input_tokens": count(m.get("cacheReadInputTokens"), "cacheReadInputTokens"),
"cache_creation_input_tokens": count(m.get("cacheCreationInputTokens"), "cacheCreationInputTokens"),
}
if not malformed:
record.update(measured=True, usage=totals, models=models)
for field in ("num_turns", "duration_ms"):
value = result.get(field)
record[field] = value if type(value) is int and value >= 0 else 0
with open("/tmp/usage-out/usage.json", "w", encoding="utf-8") as f:
json.dump(record, f, indent=2)
# Field names only, never values: the run log is public.
print(f"Token usage recorded: measured={str(record['measured']).lower()}"
+ (f" (malformed: {', '.join(sorted(set(malformed)))})." if malformed else "."))
PY
- name: Upload usage artifact
# Not `findings-*`, so `consolidate` never reads it as a cell. Kept
# longer than the findings so a weekly cost report can still read it.
# Best effort: accounting must never fail a review cell.
if: always() && steps.key.outputs.present == 'true'
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: usage-direct-${{ matrix.review_type }}-${{ inputs.anthropic_direct_model }}
path: /tmp/usage-out/usage.json
if-no-files-found: ignore
retention-days: 30
- name: Fail the leg when the cell did not submit
# Only when these cells REPLACE the Cursor Anthropic lane — the same
# rollup-visibility contract as the `review` job's step of this name
# (BE-15554), and like it deliberately AFTER the upload, so the errored
# record still reaches the judge and the consolidated review still
# posts. Side by side the cell is advisory and this step is skipped.
# Same availability-not-attestation scope as that step: the status is
# read from a file this cell's own agent could write.
if: always() && needs.preflight.outputs.anthropic_direct_counts == 'true'
env:
MODEL: ${{ inputs.anthropic_direct_model }}
REVIEW_TYPE: ${{ matrix.review_type }}
run: |
# Read defensively and sanitized for a ::workflow command:: line, as
# in the `review` job (`ValueError` covers invalid UTF-8 too).
status=$(python3 - <<'PY'
import json, re
try:
with open("/tmp/findings-out/findings.json", encoding="utf-8") as f:
cell = json.load(f)
except (OSError, ValueError):
cell = None
value = cell.get("status") if isinstance(cell, dict) else None
if not isinstance(value, str):
value = "error"
print(re.sub(r"[^A-Za-z0-9_.-]", "_", value)[:32] or "error")
PY
)
if [ "$status" != "ok" ]; then
echo "::error::Direct-API reviewer cell ${REVIEW_TYPE}/${MODEL} did not submit a review (status=$status). It replaces the Cursor Anthropic lane, so it counts as a failed reviewer; its findings artifact was uploaded and the panel still consolidates."
exit 1
fi
echo "Direct-API reviewer cell ${REVIEW_TYPE}/${MODEL} submitted its findings."
judge-direct:
# The direct-Anthropic judge (`judge_direct_model`, preflight's
# `judge_direct`): `consolidate`'s Cursor judge, through `claude -p` and
# the Anthropic API. Its own job so ANTHROPIC_API_KEY — sent to a job for
# every step that references it, skipped steps included — reaches ONLY a
# job whose one agent has Read, Grep and Glob and no shell, on
# GitHub-hosted `ubuntu-latest`, never `consolidate` (a Cursor shell agent
# over PR text, on the caller's `runs_on` pool).
#
# It rebuilds the judge's input exactly as `consolidate` does — the
# `Aggregate panel findings` and `Build judge prompt` steps are
# byte-identical to consolidate's (pinned by test_workflow_judge_direct.py)
# — then hands back ONE file, /tmp/judge-findings.json, as the
# `cursor-review-judge-direct` artifact. `consolidate` adopts it over its
# own seed, so everything downstream (the degraded fallback, the
# consolidated file, the post) is the Cursor judge's path unchanged.
# It also uploads the API's token counts for the judge as
# `usage-direct-judge-<model>`, which nothing in this workflow reads.
name: Direct judge
needs: [gate, diff-size, preflight, review, review-openai-direct, review-anthropic-direct, ledger]
# `consolidate`'s condition, plus the direct judge being in effect.
if: ${{ !cancelled() && needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true' && needs.review.result != 'skipped' && needs.preflight.outputs.judge_direct == 'true' }}
# Holds ANTHROPIC_API_KEY: never the caller's `runs_on` pool.
runs-on: ubuntu-latest
# `consolidate`'s cap, for the same reason: the judge step below trips
# first and is absorbed, so the upload always runs. The 10m slack covers
# this job's overhead — checkout, three downloads, the CLI install
# (itself capped at 5m) and its check (2m), and the upload.
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.judge_job_timeout) }}
permissions:
contents: read
steps:
- name: Checkout PR repo
# Pinned to the PR head SHA, as `diff-size` and `review-anthropic-direct`
# are: under `pull_request_target` the default is the BASE branch, and
# `refs/pull/<n>/merge` is neither immutable (each job resolves it
# separately, and the test merge lags a push) nor present on a
# conflicted PR, which `pull_request_target` still runs on.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
# The head tree only, as `review-anthropic-direct` takes it. No step
# here reads history — the reviewed diff, the incremental diff and the
# ledger arrive as artifacts — and a full clone of a large consumer
# cost ~2 min of this round's critical path.
fetch-depth: 1
persist-credentials: false
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Download reviewed diff
# Same generated-file-excluded diff (plus the incremental "hunks new
# since the last reviewed round" diff) the panel reviewed, built once
# in diff-size — so the judge adjudicates against exactly what the
# panel saw, and this job needs no PR checkout.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Install Claude Code CLI
id: claude_install
# `review-anthropic-direct`'s install, verbatim: the pin is read out of
# .github/cursor-review/package.json, its one home. Absorbed, unlike
# there: a judge that cannot start must cost the adjudication only, so
# `Run judge (direct)` is skipped and the seed takes the degraded
# panel-union path, as a failed Cursor judge does. Time-boxed for the
# same reason: a hung registry fetch must trip this step, not the job
# cap, whose kill never reaches the upload below.
continue-on-error: true
timeout-minutes: 5
run: |
manifest="$CURSOR_REVIEW_ASSETS/package.json"
if [ ! -f "$manifest" ]; then
echo "::error::$manifest is missing — it is the single source of truth for the direct judge's CLI pin."
exit 1
fi
if ! version=$(jq -r '
if type != "object" then ""
elif (.dependencies | type) != "object" then ""
else (.dependencies["@anthropic-ai/claude-code"] // "")
end' "$manifest"); then
echo "::error::$manifest is not valid JSON — it is the single source of truth for the direct judge's CLI pin."
exit 1
fi
version="$(printf '%s' "$version" | tr -d '\r\n')"
case "$version" in
""|*[!0-9.]*)
echo "::error::dependencies[\"@anthropic-ai/claude-code\"] must be an EXACT version (digits and dots only, no ^ or ~); got a value this job will not install."
exit 1 ;;
esac
echo "CLAUDE_CLI_VERSION=$version" >> "$GITHUB_ENV"
npm install -g "@anthropic-ai/claude-code@${version}"
- name: Verify Claude Code CLI version
id: claude_verify
if: steps.claude_install.outcome == 'success'
# `review-anthropic-direct`'s check, verbatim, and absorbed for the
# same reason as the install: a CLI that is off-pin, or no longer
# advertises a flag the confinement relies on, never runs.
continue-on-error: true
timeout-minutes: 2
run: |
installed="$(claude --version 2>/dev/null | head -n 1 | tr -d '\r' | awk '{print $1}')"
if [ "$installed" != "$CLAUDE_CLI_VERSION" ]; then
echo "::error::claude reports '${installed}', expected the pinned '${CLAUDE_CLI_VERSION}'."
exit 1
fi
echo "claude ${installed}"
help="$(claude --help 2>&1)"
for flag in --restricted --setting-sources --strict-mcp-config \
--disallowedTools --permission-prompts --no-session-persistence; do
if ! printf '%s\n' "$help" | grep -qE -- "(^|[[:space:],])${flag}([[:space:],]|$)"; then
echo "::error::claude ${installed} does not advertise ${flag}, which the direct judge's confinement relies on."
exit 1
fi
done
- name: Download prior-review ledger
id: ledger_download
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Download panel findings
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
path: /tmp/panel
pattern: findings-*
- name: Configure structured final review
# The `--init` seed, as in `consolidate`: a judge that never submits
# leaves status=error, and `consolidate` takes the degraded path.
env:
JUDGE_DIRECT_MODEL: ${{ inputs.judge_direct_model }}
run: |
python3 -I "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode judge \
--out /tmp/judge-findings.json \
--model "$JUDGE_DIRECT_MODEL (direct)" \
--review-type judge \
--init
- name: Aggregate panel findings
id: aggregate
env:
PANEL_MODELS: ${{ needs.preflight.outputs.models }}
# The direct-API cells COUNT only when they replace the Cursor OpenAI
# lane; side by side they stay advisory. See aggregate-panel.py.
DIRECT_MODEL: ${{ needs.preflight.outputs.openai_direct == 'true' && inputs.openai_direct_model || '' }}
DIRECT_COUNTS: ${{ needs.preflight.outputs.openai_direct_counts }}
# The matrices' RESULTS, not their artifacts: a cell can upload under
# another cell's name, but it cannot turn the honest leg's 409 green.
# `Fail the leg when the cell did not submit` reds every non-ok cell,
# so a red matrix whose artifacts all read ok is a forgery or a
# post-review failure — either way, panel_inconsistent=true.
REVIEW_RESULT: ${{ needs.review.result }}
DIRECT_RESULT: ${{ needs.review-openai-direct.result }}
# The same three for the direct Anthropic cells, counted per lab.
ANTHROPIC_DIRECT_MODEL: ${{ needs.preflight.outputs.anthropic_direct == 'true' && inputs.anthropic_direct_model || '' }}
ANTHROPIC_DIRECT_COUNTS: ${{ needs.preflight.outputs.anthropic_direct_counts }}
ANTHROPIC_DIRECT_RESULT: ${{ needs.review-anthropic-direct.result }}
run: |
# Each artifact directory contains one findings.json. Combine into
# a single panel.json array preserving cell metadata, and emit the
# ok_count/total/panel_inconsistent `Panel integrity` and auto-approve
# gate on.
python3 "$CURSOR_REVIEW_ASSETS/aggregate-panel.py" \
--panel-dir /tmp/panel \
--models "$PANEL_MODELS" \
--direct-model "$DIRECT_MODEL" \
--direct-counts "${DIRECT_COUNTS:-false}" \
--review-result "$REVIEW_RESULT" \
--direct-result "${DIRECT_RESULT:-skipped}" \
--anthropic-direct-model "$ANTHROPIC_DIRECT_MODEL" \
--anthropic-direct-counts "${ANTHROPIC_DIRECT_COUNTS:-false}" \
--anthropic-direct-result "${ANTHROPIC_DIRECT_RESULT:-skipped}" \
--out /tmp/panel.json \
--github-output "$GITHUB_OUTPUT"
- name: Build judge prompt
if: steps.aggregate.outputs.ok_count != '0'
env:
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
# The judge is the repeat-policy enforcement point, so it gets the
# judge-flavored ledger block (repeat_of requirement + the per-review
# repeat cap). Byte-identical to the old prompt when there's no ledger.
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" splice \
--prompt "$CURSOR_REVIEW_ASSETS/prompt-judge.md" \
--marker '=== BEGIN PANEL FINDINGS ===' \
--insert /tmp/ledger/ledger-judge.md \
--out /tmp/judge-prompt-head.txt
# Nonce'd fences as in the panel (BE-7645) — the judge reads the same
# attacker-authored diff, so it gets the same delimiting. Its nonce is
# minted HERE and is its OWN: the panel jobs never see it. That is
# what stops a laundering path — panel.json is model output produced
# with the panel's nonce in context, and it is spliced ABOVE the diff
# here, so a shared value could be echoed by a steered panel model into
# a region the judge has been told is authoritative and used to forge a
# close/open fence pair around a fake diff.
#
# panel.json is fenced with the same nonce for the same reason: it is
# model output derived from the untrusted diff, so "only a marker
# carrying this nonce ends a region" has to hold for it too, not just
# for the diff. Today only json.dump's newline escaping keeps a forged
# marker off a line start — that is not a control to rely on.
judge_nonce="$(python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" mint)"
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" strip-marker \
--file /tmp/judge-prompt-head.txt \
--marker '=== BEGIN PANEL FINDINGS ==='
{
cat /tmp/judge-prompt-head.txt
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/panel.json --label "PANEL FINDINGS" --nonce "$judge_nonce"
echo ""
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff.patch --label DIFF --nonce "$judge_nonce"
if [ -s /tmp/pr-diff-new.patch ]; then
echo ""
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff-new.patch \
--label "HUNKS NEW SINCE ROUND ${LEDGER_ROUNDS:-?}" \
--nonce "$judge_nonce"
fi
} > /tmp/judge-prompt.txt
echo "Judge prompt size: $(wc -c < /tmp/judge-prompt.txt) bytes"
- name: Run judge (direct)
# `consolidate`'s `Run judge`, through the Anthropic API instead of Cursor: the
# same /tmp/judge-prompt.txt, the same `review-output-mcp.py --mode
# judge` writing the same /tmp/judge-findings.json, the same step cap
# and the same absorption — a judge that fails, times out or never
# submits leaves the seed, and `Build consolidated findings file` takes
# the degraded panel-union path exactly as it does for Cursor. Skipped
# (seed left in place, same path) when the CLI did not install clean.
#
# Confinement, as in `review-anthropic-direct`: ANTHROPIC_API_KEY is
# in this ONE step's env (never argv, never a file), and the agent has
# Read, Grep and Glob — no Bash or other code-running tool — confined
# to the PR checkout (its cwd) by `--restricted`, with /proc and /sys
# denied independently of that flag, since /proc/self/environ is the
# key. The result JSON is never echoed: the run log is public and the
# result is model output steered by PR text.
id: judge_direct
if: steps.aggregate.outputs.ok_count != '0' && steps.claude_verify.outcome == 'success'
continue-on-error: true
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.judge_step_timeout) }}
env:
JUDGE_DIRECT_MODEL: ${{ inputs.judge_direct_model }}
JUDGE_DIRECT_EFFORT: ${{ needs.preflight.outputs.judge_direct_effort }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
# No telemetry or error report may carry private-diff context.
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1'
run: |
if [ -z "${ANTHROPIC_API_KEY:-}" ]; then
# Belt and braces: preflight already required the key.
echo "::warning::judge_direct_model is in effect but ANTHROPIC_API_KEY is empty here, so the judge did not run."
exit 0
fi
# A planted symlink could lead the file tools outside the tree, and
# a planted .claude/settings*.json or .mcp.json must never be there
# to load (`--restricted` and `--setting-sources ""` ignore them
# already; this removes them outright).
find . -type l -delete
rm -rf ./.claude ./.mcp.json ./CLAUDE.local.md
CLAUDE_CONFIG_DIR="$(mktemp -d -p "$RUNNER_TEMP")"
export CLAUDE_CONFIG_DIR
# `-I`: the cwd is the PR checkout, and a stdin script puts '' first
# on sys.path, so a PR-planted json.py would run beside the key.
mcp_config="$(python3 -I - <<'PY'
import json, os
print(json.dumps({"mcpServers": {"cursor-review-output": {
"command": "python3",
"args": [
"-I",
os.path.join(os.environ["CURSOR_REVIEW_ASSETS"], "review-output-mcp.py"),
"--mode", "judge",
"--out", "/tmp/judge-findings.json",
"--model", os.environ["JUDGE_DIRECT_MODEL"] + " (direct)",
"--review-type", "judge",
],
}}}))
PY
)"
# Deliberately NOT `--bare`: on the pinned CLI it drops Grep and
# Glob from `--tools` (see `review-anthropic-direct`). What it would
# skip is already off: `--setting-sources ""` and a fresh
# CLAUDE_CONFIG_DIR, `--strict-mcp-config`, and
# CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC.
claude -p --restricted --setting-sources "" \
--tools "Read,Grep,Glob" \
--strict-mcp-config --mcp-config "$mcp_config" \
--allowedTools "Read,Grep,Glob,mcp__cursor-review-output__cursor_review_submit_final" \
--disallowedTools "Read(//proc/**),Read(//sys/**)" \
--permission-prompts none \
--model "$JUDGE_DIRECT_MODEL" --effort "$JUDGE_DIRECT_EFFORT" \
--output-format json --no-session-persistence \
< /tmp/judge-prompt.txt > /tmp/judge-claude-result.json \
&& JUDGE_EXIT=0 || JUDGE_EXIT=$?
echo "claude (judge) exit code: $JUDGE_EXIT"
- name: Refuse a judge review carrying the API key
# The direct cells' exfil guard, for the judge: should a
# prompt-injected judge get the key into its final review, replace the
# review with the `--init` error seed, so the degraded path posts the
# panel union instead. Literal match only. `always()`, so a judge
# killed by its step cap AFTER submitting is still checked. Then the
# status and finding count — never the review itself (see above).
if: always()
env:
JUDGE_DIRECT_MODEL: ${{ inputs.judge_direct_model }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
set -uo pipefail
out=/tmp/judge-findings.json
if [ -n "${ANTHROPIC_API_KEY:-}" ] && [ -f "$out" ] \
&& LC_ALL=C grep -qF -- "$ANTHROPIC_API_KEY" "$out"; then
echo "::error::the direct judge's final review contains ANTHROPIC_API_KEY — refusing to publish it (possible prompt-injection exfil); the panel union is posted instead."
python3 -I "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode judge \
--out "$out" \
--model "$JUDGE_DIRECT_MODEL (direct)" \
--review-type judge \
--init
fi
# `-I`, as everywhere in this job: the cwd is the PR checkout, and a
# stdin script puts '' first on sys.path, so a PR-planted json.py
# would run beside the key.
python3 -I - <<'PY'
import json
try:
with open("/tmp/judge-findings.json", encoding="utf-8") as f:
record = json.load(f)
except (OSError, ValueError):
record = {}
if not isinstance(record, dict):
record = {}
status = record.get("status")
findings = record.get("findings")
# Fixed vocabulary only: `status` is written by a tool the agent
# drives, so anything else is reported as `?`, never echoed.
status = status if status in ("ok", "error") else "?"
count = len(findings) if isinstance(findings, list) else 0
print(f"Direct judge: status={status}, {count} finding(s).")
PY
- name: Upload direct judge review
# Always, so `consolidate` sees the seed rather than nothing on a
# judge that did not submit. NOT absorbed: a failed upload (a 409
# because something else took the name first included) fails this
# job, and `consolidate` adopts only from a job that succeeded.
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: cursor-review-judge-direct
path: /tmp/judge-findings.json
if-no-files-found: error
retention-days: 7
- name: Record token usage
# `review-anthropic-direct`'s step, over the judge's result: the API's
# own token counts for the judge, so a caller can measure what the
# direct judge costs as it does the direct cells. Counts only — nothing
# model-written, no prices — and `measured` is false when the judge
# left no usable result. The script is the cells', byte for byte, but
# for the result path (test_workflow_judge_direct.py pins that). It
# runs whenever the judge step did, so a judge its cap killed is still
# recorded, as unmeasured. Best effort, and after the review's upload:
# accounting must never fail or delay the judge's hand-off. Time-boxed
# too: `continue-on-error` does not absorb the JOB cap, and a job that
# ends cancelled loses its already-uploaded review to `consolidate`.
if: always() && steps.judge_direct.outcome != 'skipped'
continue-on-error: true
timeout-minutes: 1
env:
MODEL: ${{ inputs.judge_direct_model }}
REVIEW_TYPE: judge
RUN_ATTEMPT: ${{ github.run_attempt }}
run: |
mkdir -p /tmp/usage-out
python3 -I - <<'PY'
import json, os, re
malformed = []
def count(value, field):
# A token count is a plain non-negative integer; absent reads as
# 0. Anything else makes the whole record unmeasured.
if value is None:
return 0
if type(value) is int and value >= 0:
return value
malformed.append(field)
return 0
def mapping(value, field):
if value is None or isinstance(value, dict):
return value or {}
malformed.append(field)
return {}
try:
with open("/tmp/judge-claude-result.json", encoding="utf-8") as f:
result = json.load(f)
except (OSError, ValueError):
result = None
if not isinstance(result, dict):
result = {}
usage = result.get("usage")
record = {
"model": os.environ["MODEL"],
"review_type": os.environ["REVIEW_TYPE"],
"run_attempt": int(os.environ.get("RUN_ATTEMPT") or 0),
"measured": False,
}
if isinstance(usage, dict):
written = mapping(usage.get("cache_creation"), "cache_creation")
totals = {
"input_tokens": count(usage.get("input_tokens"), "input_tokens"),
"output_tokens": count(usage.get("output_tokens"), "output_tokens"),
"cache_read_input_tokens": count(usage.get("cache_read_input_tokens"), "cache_read_input_tokens"),
"cache_creation_input_tokens": count(usage.get("cache_creation_input_tokens"), "cache_creation_input_tokens"),
"ephemeral_5m_input_tokens": count(written.get("ephemeral_5m_input_tokens"), "ephemeral_5m_input_tokens"),
"ephemeral_1h_input_tokens": count(written.get("ephemeral_1h_input_tokens"), "ephemeral_1h_input_tokens"),
}
# Per model, in case the CLI ever spends on a second one.
models = {}
for name, m in mapping(result.get("modelUsage"), "modelUsage").items():
if not re.fullmatch(r"[A-Za-z0-9._-]{1,100}", name) or not isinstance(m, dict):
malformed.append("modelUsage")
continue
models[name] = {
"input_tokens": count(m.get("inputTokens"), "inputTokens"),
"output_tokens": count(m.get("outputTokens"), "outputTokens"),
"cache_read_input_tokens": count(m.get("cacheReadInputTokens"), "cacheReadInputTokens"),
"cache_creation_input_tokens": count(m.get("cacheCreationInputTokens"), "cacheCreationInputTokens"),
}
if not malformed:
record.update(measured=True, usage=totals, models=models)
for field in ("num_turns", "duration_ms"):
value = result.get(field)
record[field] = value if type(value) is int and value >= 0 else 0
with open("/tmp/usage-out/usage.json", "w", encoding="utf-8") as f:
json.dump(record, f, indent=2)
# Field names only, never values: the run log is public.
print(f"Token usage recorded: measured={str(record['measured']).lower()}"
+ (f" (malformed: {', '.join(sorted(set(malformed)))})." if malformed else "."))
PY
- name: Upload usage artifact
# The cells' `usage-direct-<review_type>-<model>` family, review type
# `judge`. Neither `findings-*` nor `cursor-review-judge-direct`, so
# neither `consolidate` nor the hand-back ever reads it. Best effort,
# and time-boxed for the same reason as `Record token usage`.
id: usage_upload
if: always() && steps.judge_direct.outcome != 'skipped'
continue-on-error: true
timeout-minutes: 2
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: usage-direct-judge-${{ inputs.judge_direct_model }}
path: /tmp/usage-out/usage.json
if-no-files-found: ignore
retention-days: 30
- name: Warn on unrecorded usage
# The name is fixed and known before the job runs, so a panel cell (an
# agent over PR code that runs first) can upload under it and make this
# upload 409. `continue-on-error` would hide that, leaving the squatter's
# counts as the judge's record; say so on the run. `usage-direct-*`
# records are unauthenticated either way: treat them as indicative.
if: always() && steps.usage_upload.outcome == 'failure'
continue-on-error: true
timeout-minutes: 1
run: echo "::warning::The direct judge's usage artifact did not upload; any usage-direct-judge-* record on this run is not the judge's."
consolidate:
# Adjudicates the panel cell artifacts into one consolidated review.
# Calls cursor-agent one more time as the judge, with prompt-judge.md —
# or, with `judge_direct_model` in effect (preflight's `judge_direct`),
# adopts the review the `judge-direct` job above wrote instead: same
# prompt, same structured-output tool, same file, same degraded fallback.
# That judge runs in its OWN job so ANTHROPIC_API_KEY never shares one
# with this job's Cursor judge (an unsandboxed shell agent over PR text)
# or its `runs_on` pool.
#
# Holds no write credential: the payload is handed to the `post-review` job
# below as an artifact, and that job does the mint + post. See the header's
# "Credential isolation" note for why the judge must not share a job with
# a write-scoped token.
name: Consolidate panel
# `review-openai-direct` and `review-anthropic-direct` are here for
# ORDERING — their artifacts must land before `Download panel findings`
# runs (and `judge-direct`'s before `Download direct judge review`). None
# gates this job: when one is skipped (the default) or
# fails, `!cancelled()` below still runs, and a failed cell is counted
# from its artifact (or its absence) instead. Each one's result is read
# once, by `Aggregate panel findings`, as a consistency check on those
# artifacts (see aggregate-panel.py).
needs: [gate, diff-size, preflight, review, review-openai-direct, review-anthropic-direct, ledger, judge-direct]
# `!cancelled()`, not `always()`: the judge is the most expensive call in
# the workflow, and the only job that does anything with its payload,
# `post-review`, is itself `!cancelled()`. On a cancelled run — now an
# advertised escape hatch, since applying `skip-cursor-review` mid-panel
# cancels the run — `always()` spent up to 30 minutes adjudicating partial
# cell output that nothing could ever post. Individual cell FAILURES are a
# different thing and are still judged: `cancelled()` asks whether the RUN
# was cancelled, so a red or cancelled matrix cell still reaches the judge,
# which is what `always()` was here for.
if: ${{ !cancelled() && needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true' && needs.review.result != 'skipped' }}
runs-on: ${{ fromJSON(inputs.runs_on || '"ubuntu-latest"') }}
# ABOVE the `review` cap, never under it. The judge reads every cell's
# artifact with the same top reasoning tier one cell uses, so it is the
# strictly harder call — yet at 15m it was capped at HALF the panel it
# adjudicates. A diff slow enough to stretch the panel stretches the judge
# with it, so the failure mode was the expensive one: every cell runs green
# for ~25m, then the judge is killed at the last step and every cell's work
# is discarded with nothing posted to the PR. GitHub reports a
# timeout-minutes kill as `cancelled`, not `failed`, so it reads on the run
# page like a human stopped it — which is how this went unnoticed. Observed
# twice in one day on a consumer repo, both at 15m0Xs (~3% of runs).
#
# Deliberately longer than the `Run judge` step cap below, same idiom as
# the `ledger` job: raising the JOB cap alone would only move the cliff,
# since a job-level kill takes `Build consolidated findings file` and the
# payload upload with it and is the one failure mode that can never reach
# the degraded panel-union fallback. The step trips first and is absorbed,
# so a hung judge costs the adjudication, not the panel. The slack over
# the step (10m) covers this job's own overhead — a PR-head
# checkout, the CLI install, three artifact downloads and the upload —
# which a panel cell does not all pay, so the judge's effective MODEL
# budget is the step cap, not this one.
#
# DERIVED from `cell_timeout_minutes` (step = max(30, x 2), job = step
# + 10 slack), so raising a
# cell's cap carries the judge with it instead of leaving it behind.
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.judge_job_timeout) }}
# contents: read ONLY. This job checks out PR-authored code and runs the
# judge agent over it, so it must carry nothing write-scoped — `post-review`
# below holds pull-requests: write and the bot credentials instead.
permissions:
contents: read
# Panel-integrity facts, for the `Panel integrity` job at the bottom of this
# file. They are the same numbers the steps below already print; a job output
# is what makes them readable from OUTSIDE this job's log, which is the whole
# point — `Aggregate panel findings` reporting "2/6 cells contributed" in a
# log nobody opens is not a signal a merge gate can act on.
outputs:
ok_count: ${{ steps.aggregate.outputs.ok_count }}
total: ${{ steps.aggregate.outputs.total }}
# 'true' when a counted cell artifact may not be its own cell's: a
# reviewer matrix did not succeed although every counted cell of it
# reads `ok`, or a record is `mismatch`. Written by aggregate-panel.py
# BEFORE the judge runs in this job; `Auto-approve decision` and `Panel
# integrity` read it from here, never from consolidated.json.
panel_inconsistent: ${{ steps.aggregate.outputs.panel_inconsistent }}
degraded: ${{ steps.consolidated.outputs.degraded }}
# Untrusted: this is whatever string the judge agent's own tool wrote as
# `status` in /tmp/judge-findings.json, in a job running `cursor-agent
# --trust` over PR-authored text. It is neither validated against an enum
# nor escaped on the way out. Anything that consumes it must flatten AND
# percent-escape it before it reaches a ::workflow command:: line —
# stripping newlines alone is not enough, because the runner unescapes
# `%0A` back into one. `Panel integrity` does both.
judge_status: ${{ steps.consolidated.outputs.judge_status }}
steps:
- name: Checkout PR repo
# Pinned to the PR head SHA, as `diff-size` and `review-anthropic-direct`
# are: under `pull_request_target` the default is the BASE branch, and
# `refs/pull/<n>/merge` is neither immutable (each job resolves it
# separately, and the test merge lags a push) nor present on a
# conflicted PR, which `pull_request_target` still runs on.
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
# The head tree only, as `review-anthropic-direct` takes it. No step
# here reads history — the reviewed diff, the incremental diff and the
# ledger arrive as artifacts — and a full clone of a large consumer
# cost ~2 min of this round's critical path.
fetch-depth: 1
persist-credentials: false
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Download reviewed diff
# Same generated-file-excluded diff (plus the incremental "hunks new
# since the last reviewed round" diff) the panel reviewed, built once
# in diff-size — so the judge adjudicates against exactly what the
# panel saw, and this job needs no PR checkout.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Install Cursor agent CLI
# Not needed when the judge runs direct, and a transient Cursor
# download failure here would fail this job before the degraded
# panel-union path, discarding a completed panel.
if: needs.preflight.outputs.judge_direct != 'true'
run: bash "$CURSOR_REVIEW_ASSETS/install-cursor-cli.sh"
- name: Download prior-review ledger
id: ledger_download
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Download panel findings
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
path: /tmp/panel
pattern: findings-*
- name: Configure structured final review
env:
# The seed names the judge that will run: `<id> (direct)` for the
# direct judge, so a judge that never submits is not attributed to
# the Cursor model.
JUDGE_DIRECT: ${{ needs.preflight.outputs.judge_direct }}
JUDGE_DIRECT_MODEL: ${{ inputs.judge_direct_model }}
run: |
judge_label="$JUDGE_MODEL"
if [ "$JUDGE_DIRECT" = "true" ]; then
judge_label="$JUDGE_DIRECT_MODEL (direct)"
fi
python3 "$CURSOR_REVIEW_ASSETS/review-output-mcp.py" \
--mode judge \
--out /tmp/judge-findings.json \
--model "$judge_label" \
--review-type judge \
--init
rm -rf -- .cursor
mkdir -m 700 .cursor
python3 - <<'PY'
import json, os, sys, tempfile
if os.path.islink(".cursor"):
raise SystemExit("Refusing to write Cursor config through a symlinked .cursor directory")
config = {
"mcpServers": {
"cursor-review-output": {
"type": "stdio",
"command": sys.executable,
"args": [
os.path.join(os.environ["CURSOR_REVIEW_ASSETS"], "review-output-mcp.py"),
"--mode", "judge",
"--out", "/tmp/judge-findings.json",
"--model", os.environ["JUDGE_MODEL"],
"--review-type", "judge",
],
}
}
}
cli_config = {
"permissions": {
"allow": [
"Mcp(cursor-review-output:cursor_review_submit_final)",
],
"deny": [],
}
}
for filename, value in (("mcp.json", config), ("cli.json", cli_config)):
fd, temporary = tempfile.mkstemp(dir=".cursor", prefix=f".{filename}-")
with os.fdopen(fd, "w", encoding="utf-8") as output:
json.dump(value, output)
os.replace(temporary, os.path.join(".cursor", filename))
PY
- name: Aggregate panel findings
id: aggregate
env:
PANEL_MODELS: ${{ needs.preflight.outputs.models }}
# The direct-API cells COUNT only when they replace the Cursor OpenAI
# lane; side by side they stay advisory. See aggregate-panel.py.
DIRECT_MODEL: ${{ needs.preflight.outputs.openai_direct == 'true' && inputs.openai_direct_model || '' }}
DIRECT_COUNTS: ${{ needs.preflight.outputs.openai_direct_counts }}
# The matrices' RESULTS, not their artifacts: a cell can upload under
# another cell's name, but it cannot turn the honest leg's 409 green.
# `Fail the leg when the cell did not submit` reds every non-ok cell,
# so a red matrix whose artifacts all read ok is a forgery or a
# post-review failure — either way, panel_inconsistent=true.
REVIEW_RESULT: ${{ needs.review.result }}
DIRECT_RESULT: ${{ needs.review-openai-direct.result }}
# The same three for the direct Anthropic cells, counted per lab.
ANTHROPIC_DIRECT_MODEL: ${{ needs.preflight.outputs.anthropic_direct == 'true' && inputs.anthropic_direct_model || '' }}
ANTHROPIC_DIRECT_COUNTS: ${{ needs.preflight.outputs.anthropic_direct_counts }}
ANTHROPIC_DIRECT_RESULT: ${{ needs.review-anthropic-direct.result }}
run: |
# Each artifact directory contains one findings.json. Combine into
# a single panel.json array preserving cell metadata, and emit the
# ok_count/total/panel_inconsistent `Panel integrity` and auto-approve
# gate on.
python3 "$CURSOR_REVIEW_ASSETS/aggregate-panel.py" \
--panel-dir /tmp/panel \
--models "$PANEL_MODELS" \
--direct-model "$DIRECT_MODEL" \
--direct-counts "${DIRECT_COUNTS:-false}" \
--review-result "$REVIEW_RESULT" \
--direct-result "${DIRECT_RESULT:-skipped}" \
--anthropic-direct-model "$ANTHROPIC_DIRECT_MODEL" \
--anthropic-direct-counts "${ANTHROPIC_DIRECT_COUNTS:-false}" \
--anthropic-direct-result "${ANTHROPIC_DIRECT_RESULT:-skipped}" \
--out /tmp/panel.json \
--github-output "$GITHUB_OUTPUT"
- name: Build judge prompt
if: steps.aggregate.outputs.ok_count != '0'
env:
LEDGER_ROUNDS: ${{ needs.ledger.outputs.rounds }}
run: |
# The judge is the repeat-policy enforcement point, so it gets the
# judge-flavored ledger block (repeat_of requirement + the per-review
# repeat cap). Byte-identical to the old prompt when there's no ledger.
python3 "$CURSOR_REVIEW_ASSETS/build-ledger.py" splice \
--prompt "$CURSOR_REVIEW_ASSETS/prompt-judge.md" \
--marker '=== BEGIN PANEL FINDINGS ===' \
--insert /tmp/ledger/ledger-judge.md \
--out /tmp/judge-prompt-head.txt
# Nonce'd fences as in the panel (BE-7645) — the judge reads the same
# attacker-authored diff, so it gets the same delimiting. Its nonce is
# minted HERE and is its OWN: the panel jobs never see it. That is
# what stops a laundering path — panel.json is model output produced
# with the panel's nonce in context, and it is spliced ABOVE the diff
# here, so a shared value could be echoed by a steered panel model into
# a region the judge has been told is authoritative and used to forge a
# close/open fence pair around a fake diff.
#
# panel.json is fenced with the same nonce for the same reason: it is
# model output derived from the untrusted diff, so "only a marker
# carrying this nonce ends a region" has to hold for it too, not just
# for the diff. Today only json.dump's newline escaping keeps a forged
# marker off a line start — that is not a control to rely on.
judge_nonce="$(python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" mint)"
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" strip-marker \
--file /tmp/judge-prompt-head.txt \
--marker '=== BEGIN PANEL FINDINGS ==='
{
cat /tmp/judge-prompt-head.txt
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/panel.json --label "PANEL FINDINGS" --nonce "$judge_nonce"
echo ""
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff.patch --label DIFF --nonce "$judge_nonce"
if [ -s /tmp/pr-diff-new.patch ]; then
echo ""
python3 "$CURSOR_REVIEW_ASSETS/fence-diff.py" emit \
--body /tmp/pr-diff-new.patch \
--label "HUNKS NEW SINCE ROUND ${LEDGER_ROUNDS:-?}" \
--nonce "$judge_nonce"
fi
} > /tmp/judge-prompt.txt
echo "Judge prompt size: $(wc -c < /tmp/judge-prompt.txt) bytes"
- name: Run judge
if: steps.aggregate.outputs.ok_count != '0' && needs.preflight.outputs.judge_direct != 'true'
# Time-boxed BELOW the job cap and absorbed, so a hung judge loses only
# the adjudication: the steps below then read the `--init` seed left by
# `Configure structured final review` (status=error), take the degraded
# panel-union path and still post what the cells found. At least the
# `review` job cap at the default (30) and always at least twice the
# cell step cap, so the judge is never given less model time than one of
# the cells it reads. `continue-on-error` is what makes the
# timeout absorbable — without it the step failure fails the job and
# lands back on the all-cells-discarded outcome this is fixing. It
# hides no real signal: the cursor-agent exit code is already captured
# in-script, and a judge that did not submit is reported to the PR as
# `judge_status` by `Post review`.
continue-on-error: true
# DERIVED: twice `cell_timeout_minutes`, never below 30. The judge
# adjudicates EVERY cell's findings at the same reasoning tier, so a
# budget equal to one cell's is the floor, not the target — and its
# workload scales with the panel, so a tightened cell cap must not
# shrink it below today's 30.
timeout-minutes: ${{ fromJSON(needs.preflight.outputs.judge_step_timeout) }}
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
cursor-agent \
--print \
--trust \
--approve-mcps \
--model "$JUDGE_MODEL" \
< /tmp/judge-prompt.txt \
> /tmp/judge-raw.txt 2>/tmp/judge-stderr.txt \
&& JUDGE_EXIT=0 || JUDGE_EXIT=$?
echo "cursor-agent (judge) exit code: $JUDGE_EXIT"
echo "=== Judge raw output (first 1000 chars) ==="
head -c 1000 /tmp/judge-raw.txt
echo ""
echo "=== Judge stderr ==="
cat /tmp/judge-stderr.txt
echo "=== Structured final review ==="
cat /tmp/judge-findings.json
echo ""
- name: Download direct judge review
# Only from a `judge-direct` job that SUCCEEDED. A panel cell runs an
# agent over PR code before that job starts and could upload an
# artifact under this name first; the job's own upload then 409s, the
# job fails, and nothing is adopted — the seed below stays and the
# degraded panel-union path posts instead.
if: steps.aggregate.outputs.ok_count != '0' && needs.preflight.outputs.judge_direct == 'true' && needs.judge-direct.result == 'success'
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-judge-direct
path: /tmp/judge-direct
- name: Adopt direct judge review
# Over the `--init` seed `Configure structured final review` wrote,
# and only when it is a JSON object: anything else leaves the seed,
# so `Build consolidated findings file` takes the degraded path
# exactly as for a Cursor judge that never submitted.
if: steps.aggregate.outputs.ok_count != '0' && needs.preflight.outputs.judge_direct == 'true'
run: |
python3 -I - <<'PY'
import json, os, shutil
src = "/tmp/judge-direct/judge-findings.json"
try:
if os.path.islink(src):
raise ValueError("symlink")
with open(src, encoding="utf-8") as f:
record = json.load(f)
except (OSError, ValueError):
record = None
if isinstance(record, dict):
shutil.copyfile(src, "/tmp/judge-findings.json")
print("Adopted the direct judge's review.")
else:
print("No usable direct judge review — the seed stays (degraded panel-union path).")
PY
- name: Build consolidated findings file
id: consolidated
env:
OK_COUNT: ${{ steps.aggregate.outputs.ok_count }}
# From the step output, not /tmp/panel.json: the judge ran in this job
# since `Aggregate panel findings` wrote it, and can rewrite the file.
PANEL_INCONSISTENT: ${{ steps.aggregate.outputs.panel_inconsistent }}
run: |
# If no cells completed, short-circuit — post-review.py will render
# a "no contributors" review with the panel summary. Otherwise the
# judge's MCP tool has already written /tmp/judge-findings.json.
if [ "$OK_COUNT" = "0" ]; then
echo "No panel cells contributed findings — skipping judge."
echo '{"status": "ok", "findings": []}' > /tmp/judge-findings.json
fi
# If the judge did not call its final-review tool, surface that to
# the next step rather than silently claiming "no findings".
JUDGE_STATUS=$(python3 -c "import json,sys; print(json.load(open('/tmp/judge-findings.json')).get('status','?'))")
echo "Judge status: $JUDGE_STATUS"
echo "judge_status=$JUDGE_STATUS" >> "$GITHUB_OUTPUT"
# Combine judge findings with panel metadata (model, review_type,
# status only — drop full per-cell findings to keep the post payload
# small) for the post-review script. If the judge did not submit,
# fall back to the raw per-cell findings so the run still surfaces
# what the panel found.
python3 - <<'PY'
import json, os
with open("/tmp/panel.json", encoding="utf-8") as f:
panel = json.load(f)
# Counted cells only: auto-approve counts failed reviewers from this
# list, so an ADVISORY direct-API cell must not appear here. A counted
# one does, tagged `direct` so the posted review names its backend.
# Advisory findings still reach the degraded fallback via `panel`.
panel_meta = []
for c in panel:
if c.get("advisory") is True:
continue
meta = {"model": c.get("model"), "review_type": c.get("review_type"), "status": c.get("status")}
if c.get("direct_api") is True:
meta["direct"] = True
panel_meta.append(meta)
with open("/tmp/judge-findings.json", encoding="utf-8") as f:
judge = json.load(f)
degraded = judge.get("status") != "ok"
if not degraded:
findings = judge.get("findings") or []
else:
# Judge unusable — union the per-cell findings, deduping identical
# (file, line, body) across cells to cut the obvious cross-cell
# repetition the judge would normally collapse.
seen, findings = set(), []
for cell in panel:
if cell.get("status") != "ok":
continue
for fnd in cell.get("findings") or []:
if not isinstance(fnd, dict):
continue
key = (fnd.get("file"), fnd.get("line"), fnd.get("body"))
if key in seen:
continue
seen.add(key)
findings.append(fnd)
# auto-approve withholds on it (a reviewer leg did not succeed
# although every panel cell reports ok).
panel_inconsistent = os.environ.get("PANEL_INCONSISTENT") == "true"
consolidated = {"findings": findings, "panel": panel_meta, "panel_inconsistent": panel_inconsistent}
with open("/tmp/consolidated.json", "w", encoding="utf-8") as f:
json.dump(consolidated, f)
with open(os.environ["GITHUB_OUTPUT"], "a") as g:
g.write(f"consolidated_count={len(findings)}\n")
g.write(f"degraded={'true' if degraded else 'false'}\n")
print(
f"Consolidated: {len(findings)} finding(s) "
f"({'degraded panel fallback' if degraded else 'judge-adjudicated'}), "
f"{len(panel_meta)} panel cells."
)
PY
- name: Resolve triggerer
id: triggerer
env:
GH_ACTOR: ${{ github.actor }}
PR_ASSIGNEES: ${{ toJSON(github.event.pull_request.assignees.*.login) }}
run: |
# github.actor on pull_request.labeled is the user who applied the
# label — but when the auto-labeler workflow applies it via a bot
# App token, github.actor becomes "<app>[bot]" and the human who
# actually triggered the chain (by assigning themselves) is lost.
# Recover them by falling back to the PR's first assignee whenever
# the actor is a bot.
if [[ "$GH_ACTOR" == *"[bot]" ]]; then
FALLBACK=$(echo "$PR_ASSIGNEES" | jq -r '.[0] // empty')
if [ -n "$FALLBACK" ]; then
echo "Actor $GH_ACTOR is a bot — using assignee '$FALLBACK' for attribution."
echo "triggered_by=$FALLBACK" >> "$GITHUB_OUTPUT"
else
echo "Actor $GH_ACTOR is a bot and no assignee found — keeping bot attribution."
echo "triggered_by=$GH_ACTOR" >> "$GITHUB_OUTPUT"
fi
else
echo "triggered_by=$GH_ACTOR" >> "$GITHUB_OUTPUT"
fi
- name: Bundle consolidate outputs
# Hand the review payload to the isolated `post-review` job below.
# The step outputs ride in a small JSON file rather than as job outputs
# so a single artifact download reconstitutes everything that job needs.
# `ledger_download` travels with them because the ledger banner asks two
# separate questions — did the JUDGE get prior-round context (this job's
# download), and can the poster READ the note (its own download).
# `degraded` is diagnostic as far as the REVIEW is concerned: the
# review's own degradation banner keys on `judge_status`, so nothing it
# carries here reaches the PR body. It is also a job output of this job,
# read by `Panel integrity`.
env:
JUDGE_STATUS: ${{ steps.consolidated.outputs.judge_status }}
CONSOLIDATED_COUNT: ${{ steps.consolidated.outputs.consolidated_count }}
DEGRADED: ${{ steps.consolidated.outputs.degraded }}
TRIGGERED_BY: ${{ steps.triggerer.outputs.triggered_by }}
LEDGER_DOWNLOAD: ${{ steps.ledger_download.outcome }}
run: |
python3 - <<'PY'
import json, os
# Collapse newlines: every value below is written back out as one
# `key=value` GITHUB_OUTPUT line in the post job, and triggered_by is
# derived from PR data, so a smuggled newline must not become a second
# line there.
def one_line(value):
return " ".join(value.splitlines()).strip()
meta = {
key.lower(): one_line(os.environ.get(key, ""))
for key in (
"JUDGE_STATUS",
"CONSOLIDATED_COUNT",
"DEGRADED",
"TRIGGERED_BY",
"LEDGER_DOWNLOAD",
)
}
with open("/tmp/consolidated-meta.json", "w", encoding="utf-8") as f:
json.dump(meta, f)
print(json.dumps(meta, indent=2))
PY
- name: Upload consolidated review payload
# An artifact, not job outputs: the job holding the bot write-token must
# never run in the same context as the PR checkout and the judge agent.
# Deliberately NOT `if: always()` — a consolidate that died before this
# step produced no review to post, and a half-built payload must not be
# posted. `post-review` is gated on this job SUCCEEDING, so it simply
# does not run; the failure stays visible as this job's own red status
# and `notify-complete` names which half broke.
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: cursor-review-consolidated
path: |
/tmp/consolidated.json
/tmp/judge-findings.json
/tmp/consolidated-meta.json
if-no-files-found: error
retention-days: 7
post-review:
# Posts the ONE consolidated review on the PR, under the bot identity when
# the caller configured one.
#
# This is the write half of the credential split described in the header.
# It checks out NO PR code — just this repo's assets at the pinned
# `workflows_ref`, plus artifacts. Both untrusted inputs it renders (the consolidated
# findings, the reviewed diff) are downloaded, not re-derived from a
# checkout, and the diff comes from the `pr-diff` artifact `diff-size`
# published rather than from the copy the judge job had shell access to.
name: Post review
# `diff-size` for its `merge_base_sha` alone (BE-15598) — the round sentinel this
# job writes has to record the merge base THIS round's reviewed diff was taken
# against. Already a transitive dependency (consolidate → review → diff-size), so
# this adds no ordering, only the outputs. `round-cap` likewise (diff-size
# already `needs:` it), for the round number on the status card decide
# writes (BE-19489).
# `preflight` (already transitive through consolidate) for whether a cells
# fallback found any Cursor claude-* cell to run.
# `approve-start-early` (`axes_alongside_panel`; skipped otherwise) for
# ORDER only: it writes the pending start card, and a start delayed past
# this job (an environment wait, queueing) would overwrite the round card
# decide writes here with that pending one. It adds no wait on the axes;
# with the input off it only orders this job after `dismiss-stale-approval`
# (its one need not already upstream here), a short job that starts with
# the run and has long finished by the time the panel has.
needs: [gate, consolidate, ledger, diff-size, round-cap, preflight, approve-start-early]
# The caller environment holding APPROVER_TOKEN (docs/callers/cursor-review.md#trust-model);
# '' = none. Only the APPROVER_TOKEN jobs declare it — never a job that
# checks out PR code — and only under `pull_request_target`: any other
# event runs on `refs/pull/<n>/merge`, which a base-branch-only deployment
# policy rejects before a step runs.
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
# `!cancelled()` rather than `always()`, for the same reason
# `over-cap-comment` documents at its own `if:`: the documented caller sets
# `cancel-in-progress: true`, and `always()` runs a job even when the RUN is
# cancelled. In the common supersede ordering `consolidate` has already
# finished and uploaded before the new push cancels the run, so its result
# is still `success` and a `needs.consolidate.result != 'cancelled'` test
# sails right past — this job would then post a review pinned to the
# superseded head SHA, alongside the new run's. Splitting the post into its
# own job WIDENED that window (cancellation used to kill the post step
# mid-job), so the run-level test is the one that has to be here.
#
# `== 'success'` rather than "ran at all": this job's whole input is a
# downloaded artifact, and artifact names are run-global. A prompt-injected
# panel cell (the header concedes those have shell access) can claim
# `cursor-review-consolidated` first; v4+ artifacts are immutable without
# `overwrite`, so the REAL upload then fails, `consolidate` goes red — and a
# gate that accepted a failed consolidate would download the spoofed payload
# and post it under the bot's write token. A failed `consolidate` is already
# visible as its own red job and is reported by `notify-complete`; there is
# nothing here worth posting on that path. A judge that never submitted is
# NOT this case: its step is `continue-on-error`, so `consolidate` still
# succeeds and the degraded review still posts.
if: ${{ !cancelled() && needs.consolidate.result == 'success' }}
runs-on: ubuntu-latest
# Three artifact downloads, a token mint, and post-review.py's ONE
# `gh api POST /pulls/N/reviews` carrying every inline comment in a single
# payload — plus, on a POST failure that is not a pre-write rejection, at most
# one paginated read of the PR's reviews (one `gh` command, but one request PER
# PAGE), to tell a review that never landed from one that landed despite the
# error (`pull-requests: write` already implies that read, so no permission
# changes here) — minutes of work at most. Every one of those calls is bounded:
# the reads by GH_LIST_REVIEWS_TIMEOUT_SECONDS and the POSTs by
# GH_POST_REVIEW_TIMEOUT_SECONDS, both well under this budget, so a wedged call
# cannot eat the job's whole allowance and take the fallback POST — or the job
# summary that is written after it — down with it.
#
# A THROTTLED write (429, one of the 403 wordings that mean "slow down", or a 403
# carrying its own `Retry-After`) adds a bounded WAIT in front of the landed-review
# read — otherwise that read goes out on the token GitHub just throttled and comes
# back "could not tell", which is the answer that used to cost a duplicate review.
# The wait is `Retry-After` (or the `X-RateLimit-Reset` window) clamped to
# THROTTLE_DELAY_MAX_SECONDS, and it is ONE window per throttled POST: the inline
# path's read and its body-only fallback share a single deadline, so the fallback
# finishes the remainder rather than sitting out a second full wait. Worst case is
# therefore two 90s waits plus two bounded reads and two bounded POSTs — 7 minutes,
# inside this budget with the artifact downloads and the token mint alongside it.
#
# Nothing here retries an unconfirmed write: a throttle whose landed-review read is
# still unreadable after the wait declines the fallback and goes red with the review
# in the job summary. Nor does anything call the API inside a window GitHub closed —
# a declared embargo longer than THROTTLE_DELAY_MAX_SECONDS (a primary rate limit
# sends hour-long values) skips the wait, the read and the fallback outright and
# goes straight to the job summary, since retrying inside it escalates the limit for
# the whole App installation.
#
# Bounded like every other job here so a rate-limited or hung call cannot hold a
# runner for the 6-hour default.
timeout-minutes: 10
permissions:
contents: read
pull-requests: write
# The blocking gate's POSITIVE delivery signal (BE-4691). This job's
# `result` cannot answer "did a review carrying resolvable finding threads
# land on the PR" — post-review.py exits 0 after a read-only-token 403, after
# the body-only "Review failed" review, after the all-cells-failed
# no-findings review and after the 422 inline fallback, and every one of
# those leaves the gate's thread query empty. So the script states it
# instead; see its emit_delivery for the contract. Unset (the script died
# before deciding) reads as false at the gate — fail-closed by default.
#
# `posted` is the DM's weaker sibling (BE-10017), not a duplicate of
# `delivered`: it says only that SOME review body reached the PR. The two
# disagree in both directions of interest — the error review and the
# all-cells-failed review post but do not deliver, and the read-only-403
# degradation neither posts nor delivers while still exiting 0. The gate
# wants `delivered`; `notify-complete`'s "one consolidated review is on the
# PR" wants `posted`, or it congratulates the author over a PR with no
# review on it.
outputs:
delivered: ${{ steps.post.outputs.delivered }}
gated_findings: ${{ steps.post.outputs.gated_findings }}
ungated_findings: ${{ steps.post.outputs.ungated_findings }}
posted: ${{ steps.post.outputs.posted }}
# pass / fail / untrusted / capped, written by auto-approve.py `decide`;
# empty when auto-approve is off (the workflow-level output then says
# `off`) or the step died before deciding (it then says `untrusted`).
approve_gate: ${{ steps.approve.outputs.approve_gate }}
# `delta` or `full`, written by the same `decide`; empty when it never ran.
approve_scope_effective: ${{ steps.approve.outputs.approve_scope_effective }}
# BE-19526: `true` when decide left a marked block and the `auto-retry`
# job should relabel; see that job.
auto_retry: ${{ steps.approve.outputs.auto_retry }}
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Download consolidated review payload
id: payload
# Tolerated here so the guard below can name the real cause; a bare
# download failure reads as "artifact plumbing broke" when what actually
# happened is upstream.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-consolidated
path: /tmp/consolidated
- name: Require the consolidated payload
env:
PAYLOAD_OUTCOME: ${{ steps.payload.outcome }}
run: |
if [ "$PAYLOAD_OUTCOME" != "success" ]; then
echo "::error::The consolidate job did not publish cursor-review-consolidated, so there is no review to post — see that job for the failure."
exit 1
fi
# A successful download is not a complete bundle. `if-no-files-found:
# error` on the upload fires only when ZERO of its three paths match,
# so a partial artifact uploads cleanly. Name the missing file here:
# the alternative is an unhandled FileNotFoundError inside `Read
# consolidate outputs` or inside the JUDGE_ERROR one-liner, which
# reads as "the poster is broken" when what happened is upstream —
# and which kills the run on exactly the degraded path the panel-union
# fallback exists to survive.
MISSING=""
for f in consolidated.json consolidated-meta.json judge-findings.json; do
[ -f "/tmp/consolidated/$f" ] || MISSING="$MISSING $f"
done
if [ -n "$MISSING" ]; then
echo "::error::cursor-review-consolidated downloaded but is missing:${MISSING} — the consolidate job uploaded a partial payload, see that job."
exit 1
fi
- name: Download reviewed diff
# The same generated-file-excluded diff the panel and the judge read,
# taken from `diff-size`'s artifact — post-review.py anchors its inline
# comments against it, so this job needs no PR checkout.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: pr-diff
path: /tmp
- name: Download prior-review ledger
id: ledger_download
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: cursor-review-ledger
path: /tmp/ledger
- name: Read consolidate outputs
id: meta
run: |
python3 - <<'PY'
import json, os, re
# `triggered_by` is the one header field post-review.py interpolates
# RAW — `_Triggered by @{value}._`, not routed through
# neutralize_mentions. That was safe while the value was `github.actor`
# read in the posting job itself; since the split it arrives out of a
# meta file assembled inside the job this workflow declares
# prompt-injectable, so it now crosses the trust boundary the split
# draws. Pin it to the shape of a GitHub login (39 chars max,
# alphanumerics and hyphens, plus the `[bot]` suffix `Resolve
# triggerer` can legitimately emit) and drop anything else: an
# `@org/team` mass-mention, a `[text](url)` phishing link or arbitrary
# markdown must not reach a review posted under the bot's write-scoped
# identity. post-review.py omits the attribution line entirely for an
# empty value, so dropping degrades to "no attribution", not to a lie.
LOGIN = re.compile(r"^[A-Za-z0-9-]{1,39}(\[bot\])?$")
with open("/tmp/consolidated/consolidated-meta.json", encoding="utf-8") as f:
meta = json.load(f)
print(json.dumps(meta, indent=2))
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as g:
# `degraded` is deliberately absent: it is diagnostic, printed
# above with the rest of the payload, and no step below reads it.
for key in (
"judge_status",
"consolidated_count",
"triggered_by",
"ledger_download",
):
value = " ".join(str(meta.get(key, "")).splitlines()).strip()
if key == "triggered_by" and value and not LOGIN.match(value):
print(
f"::warning::meta triggered_by is not a GitHub login shape "
f"({len(value)} chars) — dropping the attribution line."
)
value = ""
g.write(f"{key}={value}\n")
PY
- name: Mint bot-identity token (optional)
id: bot_token
if: ${{ inputs.bot_app_id != '' }}
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
- name: Post review
id: post
env:
# Dedicated bot identity when configured (bot_app_id), else github-actions[bot].
GH_TOKEN: ${{ steps.bot_token.outputs.token || secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
# The two halves of the round sentinel post-review.py writes under the review
# header (BE-15598). BASE_SHA is diagnostic; MERGE_BASE_SHA is the one the
# NEXT round pins its "already reviewed" patch to, and an empty value is
# recorded as empty so that round skips its block rather than guessing.
BASE_SHA: ${{ github.event.pull_request.base.sha }}
MERGE_BASE_SHA: ${{ needs.diff-size.outputs.merge_base_sha }}
TRIGGERED_BY: ${{ steps.meta.outputs.triggered_by }}
JUDGE_STATUS: ${{ steps.meta.outputs.judge_status }}
CONSOLIDATED_COUNT: ${{ steps.meta.outputs.consolidated_count }}
LEDGER_STATUS: ${{ needs.ledger.outputs.status }}
# This job's own download (can the poster READ the note) …
LEDGER_DOWNLOAD: ${{ steps.ledger_download.outcome }}
# … and the consolidate job's (did the JUDGE get prior-round context).
LEDGER_DOWNLOAD_JUDGE: ${{ steps.meta.outputs.ledger_download }}
# approve_scope: post-review.py marks the threads auto-approve will not
# count, from the same inputs `Auto-approve decision` passes below.
# Empty for an author approve_authors does not list: no decision is
# taken for them, so no thread may claim it is "not blocking" one.
APPROVE_THRESHOLD: ${{ needs.gate.outputs.approve_author_ok != 'false' && inputs.approve_max_severity || '' }}
APPROVE_SCOPE: ${{ inputs.approve_scope }}
INCREMENTAL_STATE: ${{ needs.diff-size.outputs.incremental_state }}
# Set only when `gate` found the direct Anthropic key unusable and
# the direct lanes fell back to Cursor: says so under the header.
RUNNER_NOTE: ${{ needs.gate.outputs.anthropic_fallback_note }}
NO_CURSOR_ANTHROPIC: ${{ needs.preflight.outputs.anthropic_cells_no_cursor }}
run: |
# The gate wrote its note before the panel was known: when the cells
# fell back to a panel with no Cursor claude-* cell, say none ran.
if [ -n "$RUNNER_NOTE" ] && [ "$NO_CURSOR_ANTHROPIC" = "true" ]; then
RUNNER_NOTE="$RUNNER_NOTE The panel list has no Cursor claude-* id, though, so no Anthropic review cell ran this round."
fi
# Prior-review ledger line for the review header: either the
# round/ledger summary, or the "context unavailable" banner naming the
# failed call. A guard that could not read its input SAYS SO — a
# context-free re-review must never render identically to a genuine
# first-round review.
#
# The DELIVERY of the ledger is checked separately from its CONTENT.
# Every ledger download is continue-on-error, so an upload or download
# that failed leaves no ledger-note.txt while the ledger job still
# reports status=ok — and the panel prompts were spliced with an EMPTY
# block. Reading only LEDGER_STATUS there would emit no banner and the
# context-free re-review would render as a genuine first round, the
# exact partial failure the banner exists to catch. So: file ABSENT
# (delivery failed) is a banner; file PRESENT but empty is a real
# "nothing to say" (first round / kill switch / no prior findings).
#
# The two halves are reported SEPARATELY because they mean different
# things to the author. If the JUDGE's download failed, the panel
# genuinely reviewed without prior-round context and findings may
# repeat earlier rounds. If only the POSTER's download failed — a case
# that exists only because this job now fetches the note itself — the
# panel and judge DID have the context and only this header could not
# be rendered; telling the author "findings may repeat" there would be
# false.
LEDGER_NOTE=""
JUDGE_LEDGER_OK=true
if [ "${LEDGER_DOWNLOAD_JUDGE:-failure}" != "success" ]; then
JUDGE_LEDGER_OK=false
fi
POST_LEDGER_OK=true
if [ "${LEDGER_DOWNLOAD:-failure}" != "success" ] || [ ! -f /tmp/ledger/ledger-note.txt ]; then
POST_LEDGER_OK=false
fi
if [ "$JUDGE_LEDGER_OK" != "true" ]; then
LEDGER_NOTE="⚠️ prior-review context unavailable (the ledger artifact did not reach the review jobs: judge=${LEDGER_DOWNLOAD_JUDGE:-missing}, post=${LEDGER_DOWNLOAD:-missing}) — the panel ran without prior-round context, so findings may repeat earlier rounds."
elif [ "$POST_LEDGER_OK" != "true" ]; then
LEDGER_NOTE="⚠️ prior-review summary unavailable (the ledger note did not reach the posting job: post=${LEDGER_DOWNLOAD:-missing}). The panel and judge DID read prior-round context, so findings are not repeats for want of it — only this header could not be rendered."
else
LEDGER_NOTE="$(cat /tmp/ledger/ledger-note.txt)"
if [ -z "$LEDGER_NOTE" ]; then
case "${LEDGER_STATUS:-missing}" in
ok|empty|disabled) ;;
*)
LEDGER_NOTE="⚠️ prior-review context unavailable (ledger job: status=${LEDGER_STATUS:-missing}) — findings may repeat earlier rounds."
;;
esac
fi
fi
# What post-review.py adjudicates a judge `repeat_of` against (BE-12630).
# `--ledger` is passed UNCONDITIONALLY — the download is continue-on-error
# and load_shown_repeat_urls degrades on a missing file, so gating on the
# POSTER's download would only convert a graceful degradation into a
# different one.
#
# `--no-judge-ledger` is a different question with a different answer. The
# two downloads fail independently, and it is the JUDGE's that decides what
# the judge was SHOWN: when it failed, the judge prompt was spliced an EMPTY
# ledger block, so every repeat_of it emitted is unfounded — even though this
# job's own copy of ledger.json may have arrived intact and be full of real
# thread URLs. Without this flag the membership check would treat those URLs
# as "shown" and wave the re-raise through on exactly the degraded run
# $LEDGER_NOTE already banners above.
LEDGER_FLAGS=(--ledger /tmp/ledger/ledger.json)
# --open-anchors-out: the earlier rounds' open threads, read before this
# review posts; `Auto-approve decision` gates on that same snapshot, and
# without it (an unreadable thread list) fails closed to `full`.
SCOPE_FLAGS=(--approve-threshold "$APPROVE_THRESHOLD" --approve-scope "$APPROVE_SCOPE"
--incremental /tmp/pr-diff-new.patch --incremental-state "$INCREMENTAL_STATE"
--open-anchors-out /tmp/open-anchors.json)
if [ "$JUDGE_LEDGER_OK" != "true" ]; then
LEDGER_FLAGS+=(--no-judge-ledger)
fi
# Three cases:
# 1. Judge ok → normal consolidated review.
# 2. Judge failed, panel has findings → post the raw per-cell findings
# with a notice banner (degraded, but NOT a bare "Review failed").
# 3. Judge failed, no findings → honest error review.
if [ "$JUDGE_STATUS" = "ok" ]; then
python3 "$CURSOR_REVIEW_ASSETS/post-review.py" \
--findings /tmp/consolidated/consolidated.json \
--pr-number "$PR_NUMBER" \
--repo "$REPO" \
--commit-sha "$HEAD_SHA" \
--base-sha "$BASE_SHA" \
--merge-base-sha "$MERGE_BASE_SHA" \
--triggered-by "$TRIGGERED_BY" \
--diff /tmp/pr-diff.patch \
"${LEDGER_FLAGS[@]}" \
"${SCOPE_FLAGS[@]}" \
--ledger-note "$LEDGER_NOTE" \
--runner-note "$RUNNER_NOTE"
elif [ "${CONSOLIDATED_COUNT:-0}" != "0" ]; then
# No JUDGE_ERROR is read here on purpose: this branch passes --notice with
# $JUDGE_STATUS and never --error-message, so the message had nowhere to go
# — and extracting it could still kill the step. json.load accepts an
# escaped lone surrogate in `error`, print() then raises UnicodeEncodeError,
# and under this step's `bash -e` a standalone assignment inherits its
# command substitution's exit status, so the shell would exit before the raw
# un-adjudicated panel review is posted. That review is the whole point of
# this branch.
python3 "$CURSOR_REVIEW_ASSETS/post-review.py" \
--findings /tmp/consolidated/consolidated.json \
--pr-number "$PR_NUMBER" \
--repo "$REPO" \
--commit-sha "$HEAD_SHA" \
--base-sha "$BASE_SHA" \
--merge-base-sha "$MERGE_BASE_SHA" \
--triggered-by "$TRIGGERED_BY" \
--diff /tmp/pr-diff.patch \
"${LEDGER_FLAGS[@]}" \
"${SCOPE_FLAGS[@]}" \
--ledger-note "$LEDGER_NOTE" \
--runner-note "$RUNNER_NOTE" \
--notice "⚠️ The judge step did not submit a final review through its structured-output tool (status=${JUDGE_STATUS}). The findings below are the raw, un-adjudicated panel output — they may contain duplicates or false positives the judge would normally filter."
else
# Bound the message HERE, before it becomes a single argv element: Linux
# rejects one argument over ~128 KiB at execve, so an unbounded
# $JUDGE_ERROR would fail the exec and produce no error review and no job
# summary at all — precisely the largest failures post-review.py's own
# message budget was added for, which can only run once Python has started.
# A BYTE cut cannot guarantee post-review.py's CHARACTER budget
# (MAX_ERROR_MESSAGE_CHARS) then trips: 100 KB of emoji decodes to 25,000
# characters and of CJK to ~33,000, both under it, so a message severed here
# would reach post_error_review looking complete and carry no "(truncated…)"
# marker. Raising the byte cut to make that impossible would breach
# MAX_ARG_STRLEN, so say it HERE instead — the marker is appended only when
# the cut actually fired. (Command substitution also strips trailing
# newlines and cannot carry NUL; neither changes what the reader is told.)
JUDGE_ERROR=$(python3 -c "import json; e = str(json.load(open('/tmp/consolidated/judge-findings.json')).get('error', '(no error message)')).encode('utf-8', 'replace'); cut = e[:100000]; print(cut.decode('utf-8', 'ignore') + ('' if len(cut) == len(e) else ' …(truncated: the error message exceeded the 100 KB argument budget)'))")
python3 "$CURSOR_REVIEW_ASSETS/post-review.py" \
--findings /tmp/consolidated/consolidated.json \
--pr-number "$PR_NUMBER" \
--repo "$REPO" \
--commit-sha "$HEAD_SHA" \
--base-sha "$BASE_SHA" \
--merge-base-sha "$MERGE_BASE_SHA" \
--triggered-by "$TRIGGERED_BY" \
"${LEDGER_FLAGS[@]}" \
--ledger-note "$LEDGER_NOTE" \
--runner-note "$RUNNER_NOTE" \
--error-message "Judge call failed (status=${JUDGE_STATUS}): ${JUDGE_ERROR}"
fi
- name: Auto-approve decision
# Opt-in (inputs.approve_max_severity). Runs only after `Post review`
# succeeded, so the decision is about a review that is on the PR. All of
# the fail-closed rules live in auto-approve.py (see its docstring); this
# job checks out no PR code, so the PR cannot rewrite the logic judging it.
# continue-on-error: the decision is advisory to THIS job. A refused
# approval (e.g. the github-actions[bot] fallback with "Allow GitHub
# Actions to create and approve pull requests" off) must not turn
# `post-review` red, because the blocking gate reads that job's result as
# "the review did not land" — and it did land. The step's own ::error::
# and red step mark still show the refusal.
id: approve
if: ${{ inputs.approve_max_severity != '' }}
continue-on-error: true
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
BOT_TOKEN: ${{ steps.bot_token.outputs.token }}
APP_SLUG: ${{ steps.bot_token.outputs.app-slug }}
FALLBACK_TOKEN: ${{ secrets.GITHUB_TOKEN }}
THRESHOLD: ${{ inputs.approve_max_severity }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
JUDGE_STATUS: ${{ steps.meta.outputs.judge_status }}
DELIVERED: ${{ steps.post.outputs.delivered }}
UNGATED: ${{ steps.post.outputs.ungated_findings }}
# The base this round diffed against (`BASE_SHA` above is this
# event's too): decide refuses if the live base differs, and records
# it in the review so a later retarget is caught from live state.
BASE_REF: ${{ github.event.pull_request.base.ref }}
DEFER_APPROVAL: ${{ inputs.defer_approval }}
APPROVE_SCOPE: ${{ inputs.approve_scope }}
INCREMENTAL_STATE: ${{ needs.diff-size.outputs.incremental_state }}
MAX_FAILED_REVIEWERS: ${{ inputs.approve_max_failed_reviewers }}
RETRY_ERRORED_ROUNDS: ${{ inputs.auto_retry_errored_rounds }}
RETRY_DELAY_MINUTES: ${{ inputs.auto_retry_delay_minutes }}
# aggregate-panel.py's step output, written before the judge ran —
# not consolidated.json, which `consolidate` builds after the judge
# (`--trust`, same job) could have rewritten its inputs.
PANEL_INCONSISTENT: ${{ needs.consolidate.outputs.panel_inconsistent }}
# approve_authors, resolved by `gate`: `false` → decide posts nothing
# and reports `off` for this author.
AUTHOR_ENABLED: ${{ needs.gate.outputs.approve_author_ok }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
# For the cursor-approve status card decide writes every round
# (BE-19489): round-cap's count is the heading's "round R of M".
ROUND: ${{ needs.round-cap.outputs.next_round }}
MAX_ROUNDS: ${{ needs.round-cap.outputs.max_rounds }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EVENT_NAME: ${{ github.event_name }}
APPROVER_ENVIRONMENT: ${{ inputs.approver_environment }}
run: |
# Trust model (docs/callers/cursor-review.md#trust-model): only
# `pull_request_target` loads the caller from the base branch. Every
# other event (`pull_request`, `pull_request_review_thread`, …) loads
# it from the PR, so a PR can read APPROVER_TOKEN there: such a round
# APPROVES nothing. It keeps the same identity, though, and goes
# through `--defer-approval`, so it still withdraws that identity's
# own earlier approvals and can still request changes — switching to
# another login would strand an approval the token already posted.
# With approver_environment set, a non-target run has no token at all
# (the environment is declared only under `pull_request_target`), and
# it must not approve under the fallback identity either.
if [ "$EVENT_NAME" != "pull_request_target" ]; then
if [ -n "$APPROVER_TOKEN" ]; then
echo "::error::APPROVER_TOKEN on a '$EVENT_NAME' run is readable by any PR-head workflow, so this round posts no approval (it still withdraws stale ones); call this reusable from pull_request_target with approver_environment (docs/callers/cursor-review.md#trust-model)"
DEFER_APPROVAL=true
elif [ -n "$APPROVER_ENVIRONMENT" ]; then
echo "::notice::approver_environment is declared only under pull_request_target, so this '$EVENT_NAME' run posts no approval; the next pull_request_target round decides."
DEFER_APPROVAL=true
fi
elif [ -n "$APPROVER_TOKEN" ] && [ -z "$APPROVER_ENVIRONMENT" ]; then
echo "::warning::APPROVER_TOKEN without approver_environment is a repo secret that any PR-head pull_request workflow can read; move it into a base-branch-only environment and pass approver_environment (docs/callers/cursor-review.md#trust-model)"
fi
# Same identity precedence as `Dismiss stale auto-approval`: the login
# passed here is the one whose earlier approvals an untrusted round
# withdraws.
# CAN_RELABEL: whether this token can re-run a round by removing and
# re-adding the review label (BE-19526). A GITHUB_TOKEN-applied label
# fires NO workflow run — the reason cursor-review-auto-label.yml
# exists at all — so the fallback identity must never auto-retry: the
# relabel would land and start nothing. A PAT and an App token both
# fire runs. Needs label write on whichever is configured.
if [ -n "$APPROVER_TOKEN" ]; then
export GH_TOKEN="$APPROVER_TOKEN"
LOGIN="$(gh api user --jq .login)"
CAN_RELABEL=true
elif [ -n "$BOT_TOKEN" ]; then
export GH_TOKEN="$BOT_TOKEN"
LOGIN="${APP_SLUG}[bot]"
CAN_RELABEL=true
else
export GH_TOKEN="$FALLBACK_TOKEN"
LOGIN="github-actions[bot]"
CAN_RELABEL=false
fi
# The identity `Post review` posted the findings under — keyed on the
# same `bot_token.outputs.token || GITHUB_TOKEN` choice it made, not on
# the slug alone: on APPROVE, only threads it started are auto-resolved.
if [ -n "$BOT_TOKEN" ] && [ -n "$APP_SLUG" ]; then POSTER="${APP_SLUG}[bot]"; else POSTER="github-actions[bot]"; fi
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" decide \
--threshold "$THRESHOLD" \
--findings /tmp/consolidated/consolidated.json \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--commit-sha "$HEAD_SHA" \
--judge-status "$JUDGE_STATUS" \
--delivered "$DELIVERED" \
--ungated "${UNGATED:-0}" \
--approver-login "$LOGIN" \
--reviewed-diff /tmp/pr-diff.patch \
--base-ref "$BASE_REF" \
--poster-login "$POSTER" \
--defer-approval "$DEFER_APPROVAL" \
--approve-scope "$APPROVE_SCOPE" \
--incremental /tmp/pr-diff-new.patch \
--incremental-state "$INCREMENTAL_STATE" \
--ledger /tmp/ledger/ledger.json \
--open-anchors /tmp/open-anchors.json \
--max-failed-reviewers "${MAX_FAILED_REVIEWERS:-0}" \
--panel-inconsistent "$PANEL_INCONSISTENT" \
--author-enabled "$AUTHOR_ENABLED" \
--pr-author "$PR_AUTHOR" \
--card true \
--round "$ROUND" \
--max-rounds "$MAX_ROUNDS" \
--run-url "$RUN_URL" \
--review-label "$REVIEW_LABEL" \
--can-relabel "$CAN_RELABEL" \
--retry-errored-rounds "$RETRY_ERRORED_ROUNDS" \
--retry-delay-minutes "$RETRY_DELAY_MINUTES"
dismiss-stale-approval:
# Companion to `Auto-approve decision`. A ruleset with
# `dismiss_stale_reviews_on_push: false` keeps an approval valid for every
# later commit, so when what was reviewed changes the bot withdraws its own
# auto-approve APPROVALS. A request-changes stays on a push: a push under a
# label-triggered caller starts no new round, so only a later round's own
# review may supersede the veto. It is withdrawn only once no round is
# coming: the PR carries `skip-cursor-review` or `needs-human-review`, or
# `approve_max_severity` is empty (`--threshold`). Only reviews carrying the auto-approve
# marker and authored by the approver identity are touched. Independent of
# `gate`: it must run on a push whether or not a panel runs. Checks out no
# PR code.
#
# With `carry_forward_unchanged_diff` (BE-20585), a stale approval whose
# PR's own changes are still identical to the ones a round reviewed — a
# rebase or re-merge onto a moved base, the stacked-PR case — is re-posted
# on the live head instead, and then the old one is dismissed. What a round
# reviewed comes only from the approver identity's own records (the merge
# base the approval recorded, or what a carried approval copied forward),
# never from a review the bot identity posted. Only under
# `pull_request_target`; it compares compare-API diffs and never reads the
# PR's tree.
#
# NOT gated on `approve_max_severity`: unsetting that input is the kill
# switch for NEW approvals, and an approval already on the PR must still be
# withdrawn by the next push. On a caller that never approved, the job lists
# the reviews, finds none of its own marked approvals, and does nothing.
#
# Three events change what was reviewed: `synchronize` (a push), `reopened`
# (a push that landed while the PR was closed arrives as this, not as
# `synchronize`) and an `edited` that carries `changes.base` (a retarget —
# same head, different diff). Each fires only if the caller lists it in
# `types:`. Staleness is read from the PR's LIVE head and base, never from
# the event, so the job runs on EVERY action of an open PR: any event in the
# same concurrency slot can cancel an in-flight dismissal, and whichever run
# replaces it must redo that dismissal from live state. Each approval
# records its base, so a retarget is caught that way too; `BASE_FROM`
# (`--all-approvals`) only covers approvals posted before that record.
# A third trigger is the `skip-cursor-review` veto label (auto-approve.py's
# VETO_LABELS, read off the live PR): `gate` runs no round on a vetoed PR,
# so a `labeled` event reaching this job is what withdraws EVERY marked
# approval, same head or not — as does `needs-human-review`, the hand-off
# (BE-19492). Hence no `github.event.action` filter here.
# Open PRs only: a title edit on a merged PR must not try a dismissal.
name: Dismiss stale auto-approval
if: >-
${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') &&
github.event.pull_request.state == 'open' &&
github.event.pull_request.head.repo.full_name == github.repository }}
# The caller environment holding APPROVER_TOKEN (docs/callers/cursor-review.md#trust-model);
# '' = none. Only the APPROVER_TOKEN jobs declare it — never a job that
# checks out PR code — and only under `pull_request_target`: any other
# event runs on `refs/pull/<n>/merge`, which a base-branch-only deployment
# policy rejects before a step runs.
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
pull-requests: write
outputs:
# BE-20262: set when the step marked the card stale for a moved head and
# `auto_rereview_after_dismissal` wants the next round started.
auto_rereview: ${{ steps.dismiss.outputs.auto_rereview }}
rereview_head: ${{ steps.dismiss.outputs.rereview_head }}
env:
# Now that this job runs for every caller, not only auto-approve ones, a
# `bot_app_id` caller reaches it on runs with no secrets (Dependabot PRs
# read the Dependabot store). Mint only when the key is present; the
# `secrets` context is unavailable in step `if:`, hence the job env.
BOT_CONFIGURED: ${{ inputs.bot_app_id != '' && secrets.BOT_APP_PRIVATE_KEY != '' }}
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Mint bot-identity token (optional)
id: bot_token
if: env.BOT_CONFIGURED == 'true'
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
- name: Dismiss stale auto-approve reviews
id: dismiss
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
BOT_TOKEN: ${{ steps.bot_token.outputs.token }}
APP_SLUG: ${{ steps.bot_token.outputs.app-slug }}
FALLBACK_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BOT_APP_ID: ${{ inputs.bot_app_id }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
# The head at event delivery: a fallback ONLY for when the live head
# cannot be read — staleness is judged against the live PR otherwise.
EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
# Non-empty only on a base retarget (`edited` with `changes.base`).
BASE_FROM: ${{ github.event.changes.base.ref.from }}
# Empty = auto-approve is off: its standing requests for changes are
# withdrawn, since no round will ever approve over them.
THRESHOLD: ${{ inputs.approve_max_severity }}
EVENT_NAME: ${{ github.event_name }}
APPROVER_ENVIRONMENT: ${{ inputs.approver_environment }}
# BE-20262: the stale card, and whether the next round starts itself.
APPROVE_AUTHORS: ${{ inputs.approve_authors }}
MAX_ROUNDS: ${{ inputs.max_rounds }}
AUTO_REREVIEW: ${{ inputs.auto_rereview_after_dismissal }}
AUTO_REREVIEW_DELAY: ${{ inputs.auto_rereview_delay_minutes }}
RUN_WITHOUT_LABEL: ${{ inputs.run_without_label }}
# BE-20585: re-approve instead of dismissing when the push left the
# PR's own diff identical. auto-approve.py posts that approval only
# under pull_request_target, and reads the compare API with
# FALLBACK_TOKEN (this job's contents: read), not the approver token.
CARRY_FORWARD: ${{ inputs.carry_forward_unchanged_diff }}
# Only the stale card's next-step sentence: the `approve-only` job
# decides the re-check itself.
APPROVE_ONLY: ${{ inputs.approve_only_on_push }}
run: |
# Trust model (docs/callers/cursor-review.md#trust-model). Like
# `Auto-approve decision` this step still ACTS as APPROVER_TOKEN under
# `pull_request`: it only withdraws that identity's own approvals, and
# dropping to another login would strand a stale approval it posted.
# The one approval it can post (carry_forward_unchanged_diff) needs
# `pull_request_target`; auto-approve.py refuses it on any other event.
if [ -n "$APPROVER_TOKEN" ] && [ "$EVENT_NAME" != "pull_request_target" ]; then
echo "::error::APPROVER_TOKEN under a pull_request trigger is readable by any PR-head workflow; call this reusable from pull_request_target with approver_environment (docs/callers/cursor-review.md#trust-model)"
elif [ -n "$APPROVER_TOKEN" ] && [ "$EVENT_NAME" = "pull_request_target" ] && [ -z "$APPROVER_ENVIRONMENT" ]; then
echo "::warning::APPROVER_TOKEN without approver_environment is a repo secret that any PR-head pull_request workflow can read; move it into a base-branch-only environment and pass approver_environment (docs/callers/cursor-review.md#trust-model)"
fi
# Same identity precedence as `Auto-approve decision`, so the login
# whose reviews are dismissed is the login that posted them.
# CAN_RELABEL as in `Auto-approve decision`: a GITHUB_TOKEN-applied
# label fires no run, so only these two identities may start a round.
CAN_RELABEL=false
if [ -n "$APPROVER_TOKEN" ]; then
export GH_TOKEN="$APPROVER_TOKEN"
LOGIN="$(gh api user --jq .login)"
# `auto-rereview` refuses APPROVER_TOKEN off pull_request_target,
# so promise no automatic round the card cannot keep.
if [ "$EVENT_NAME" = "pull_request_target" ]; then CAN_RELABEL=true; fi
elif [ -n "$BOT_TOKEN" ]; then
export GH_TOKEN="$BOT_TOKEN"
LOGIN="${APP_SLUG}[bot]"
CAN_RELABEL=true
elif [ -n "$BOT_APP_ID" ]; then
# The App is the approver identity but its key is not in this run's
# secrets (e.g. a Dependabot PR), so we can neither name nor act as
# it. Read-only with the job token and an EMPTY login: nothing is
# dismissed, and any stale marked approval turns the job red.
echo "::warning::bot_app_id is set but BOT_APP_PRIVATE_KEY is not available to this run — checking for stale auto-approvals without dismissing any."
export GH_TOKEN="$FALLBACK_TOKEN"
LOGIN=""
else
export GH_TOKEN="$FALLBACK_TOKEN"
LOGIN="github-actions[bot]"
fi
# A retarget: the head did not move, the diff did — so an approval
# pinned to the head is as stale as an off-head one. (Approvals that
# record their base are caught without this; older ones are not.)
# Under APPROVER_TOKEN / the fallback, a stale marked approval by any
# OTHER login (e.g. APPROVER_TOKEN unavailable on a Dependabot PR)
# also turns the job red rather than passing unchecked.
ALL=()
if [ -n "$BASE_FROM" ]; then
ALL=(--all-approvals)
fi
# The identity round-cap counts rounds under (its `Count review rounds`).
if [ -n "$APP_SLUG" ]; then POSTER="${APP_SLUG}[bot]"; else POSTER="github-actions[bot]"; fi
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" dismiss-stale \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--approver-login "$LOGIN" \
--head-sha "$EVENT_HEAD_SHA" \
--threshold "$THRESHOLD" \
--approve-authors "$APPROVE_AUTHORS" \
--max-rounds "$MAX_ROUNDS" \
--poster-login "$POSTER" \
--review-label "$REVIEW_LABEL" \
--auto-rereview "$AUTO_REREVIEW" \
--auto-rereview-delay-minutes "$AUTO_REREVIEW_DELAY" \
--can-relabel "$CAN_RELABEL" \
--run-without-label "$RUN_WITHOUT_LABEL" \
--carry-forward "$CARRY_FORWARD" \
--event-name "$EVENT_NAME" \
--approve-only "$APPROVE_ONLY" \
--approve-only-delay-minutes "$AUTO_REREVIEW_DELAY" \
"${ALL[@]}"
panel-integrity:
# ONE advisory check-run that says whether the panel that just ran was whole.
#
# Everything it reports was already knowable — and none of it reached a
# check-run conclusion, which is the only surface an automated merge gate
# reads. `Aggregate panel findings` printed "2/6 cells contributed findings"
# into a log; post-review.py emitted `ungated_findings=<n>` as a job output
# nothing consumed; a leg that never submitted exited green. Measured on one
# consumer repo over 92 panel runs: 38 runs had at least one errored leg, 52
# of 552 cells errored, and every leg check in every one of those runs
# reported `success`, so `statusCheckRollup` was fully green over panels that
# were a third of a panel (BE-15554).
#
# This is the panel-level half of that fix; `Fail the leg when the cell did
# not submit` in the `review` job is the per-cell half. This job is what a
# gate should read, because a matrix leg's context name carries the model id
# and therefore CHANGES whenever the panel list does — a required check on
# `edge-case (kimi-k3-max)` bricks every PR the day that pin moves.
#
# ADVISORY by default, exactly like `Blocking gate`: red here fails no other
# job IN THIS WORKFLOW, gates no merge, and does not gate `post-review` — a
# caller that wants it to block marks `<caller job id> / Panel integrity` a
# required check in its own ruleset. See docs/callers/cursor-review.md.
#
# "Advisory" stops at this workflow's edge, and the distinction is not
# academic. Red here puts the CALLER's `uses:` job in `failure`, so any
# caller job chained off it with a bare `needs:` is skipped by GitHub's
# default rule — which is how one errored cell silently stopped the
# cursor-approve axes from running at all, and withheld every approval, on a
# caller that had set `approve_max_failed_reviewers: 1` precisely to tolerate
# it. A red matrix leg does this on its own too, so dropping the check would
# not have helped. Downstream caller jobs must be guarded with `!cancelled()`
# and gated on `approve_gate`, which already fails closed; see
# docs/callers/cursor-approve.md ("A red panel cell must not skip the axes").
#
# `always()`, and the same four gate conditions `consolidate` uses, so this
# reports on exactly the runs where a panel was supposed to happen and stays
# skipped on the ones where nothing was (no trigger label, already reviewed,
# capped by `max_rounds`, over the diff-size cap, panel skipped). `always()` rather than
# `!cancelled()` for `Blocking gate`'s reason: GitHub counts a SKIPPED
# required check as passing, so green-on-cancel would be a fail-open for any
# caller that requires this. A cancelled run therefore reports red here —
# under the documented `cancel-in-progress` caller that check lands on the
# superseded head SHA, not the new one.
#
# That same "skipped counts as passing" rule is why those four conditions
# cannot be read STRAIGHT off `gate`, `diff-size` and the matrix. Three of
# them are job OUTPUTS, and a job that FAILED has empty outputs — so a gate
# whose dup-check API call errored, or a diff-size that could not build the
# diff at all, would make all four false, skip this job, and mint a GREEN
# required check on a run where whether the PR was reviewed is unknown. The
# fourth, `needs.review.result != 'skipped'`, has the same hole from the
# other end: the matrix declares `needs: [gate, diff-size, preflight,
# ledger]`, so a non-success in ANY of those four skips the whole matrix and
# leaves a 'skipped' result that reads exactly like the deliberate no-panel
# branches — a green check over a run where not one cell ever started. An
# undecided run is not a clean run. So the condition below runs this job
# whenever an upstream DECISION job (`gate`, `diff-size`, `preflight`,
# `ledger`) did not succeed, and `Fail if the panel decision itself did
# not complete` turns that into red — the same fail-closed shape, and the
# same reasoning, as `Blocking gate`'s first two guards. The deliberate
# skips are unchanged: they are the branches where `gate` and `diff-size`
# both SUCCEEDED and said no panel was warranted.
#
# Every job the matrix `needs:` must be listed here. That list is the
# invariant — not the four names that happen to be in it today — because a
# job added to `review`'s `needs:` without being added here re-opens this
# exact fail-open silently, which is how `preflight` and then `ledger` were
# each missed in turn. `test_workflow_panel_integrity.py` pins the two lists
# against each other so the next one cannot be.
#
# `round-cap` is the one decision job the matrix does NOT need directly: it
# sits upstream of `diff-size`, whose own `if:` skips on `capped == 'true'`.
# So it is read here on BOTH sides. A `round-cap` that did not succeed skips
# `diff-size` and the panel with it — undecided, so red, like the four
# above. A `round-cap` that SUCCEEDED and said `capped` is the deliberate
# `max_rounds` stop: no panel was warranted on this head, the PR is labelled
# `needs-human-review`, and the Blocking gate already fails closed on it, so
# this check skips exactly as it does over the diff-size cap. Without the
# `capped` disjunct the skipped `diff-size` reads as a failure and the guard
# below goes red telling the caller to "re-run the failed job" — which just
# hits the cap again.
name: Panel integrity
needs: [gate, round-cap, diff-size, preflight, ledger, review, consolidate, post-review]
if: ${{ always() && (needs.gate.result != 'success' || (needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && (needs.round-cap.result != 'success' || (needs.round-cap.outputs.capped != 'true' && (needs.diff-size.result != 'success' || (needs.diff-size.outputs.within_cap == 'true' && (needs.preflight.result != 'success' || needs.ledger.result != 'success' || needs.review.result != 'skipped'))))))) }}
runs-on: ubuntu-latest
# Reads job outputs and prints. No API call, no checkout, no network.
timeout-minutes: 5
# Nothing at all: this job reads `needs` outputs and writes annotations.
# An empty block is not the same as an absent one — a `workflow_call`
# reusable with no `permissions:` INHERITS the caller job's, and the
# documented caller grants `pull-requests: write`.
permissions: {}
steps:
- name: Fail if the panel decision itself did not complete
# Fail-closed guard, and it has to come FIRST because every cause in the
# step below is phrased in terms of job outputs that are EMPTY when the
# job producing them failed — and every one of those causes treats the
# empty string as a pass. Reaching `Report panel integrity` on this path
# would print "no review delivered" over a run whose panel was never
# even decided on, which is a true statement about the wrong question.
#
# This condition is exact GIVEN the job `if:` above, which admits only
# four ways to arrive here with an upstream decision job unfinished:
# `gate` did not succeed; `gate` selected a fresh in-scope review and
# `round-cap` did not succeed; `round-cap` succeeded uncapped and
# `diff-size` did not succeed; or all three succeeded and said review,
# and `preflight` or `ledger` did not succeed. All five are read back
# verbatim. (`within_cap` can only be the string 'true' when `diff-size`
# succeeded, and a `capped` round-cap skips the job outright, so neither
# deliberate stop ever reaches this step.)
#
# `preflight` and `ledger` are here because they are the decision jobs
# whose failure is invisible from the outputs: `review` needs BOTH, so a
# non-success in either SKIPS the whole matrix, `needs.review.result` is
# then 'skipped' — indistinguishable from the deliberate no-panel
# branches — and gating on that alone skipped this job and minted a
# GREEN required check on a run where NOTHING was reviewed. The job
# `if:` therefore admits a non-success `preflight` or `ledger` under a
# within-cap fresh review, and this step turns it red. A panel that
# never started is not a whole one.
#
# `ledger` is the one that reads like it cannot happen: every step in it
# is `continue-on-error`, precisely so it never skips the matrix. That
# makes a red `ledger` rare, NOT unreachable — its own job comment is
# written around the consequence. `Ensure ledger artifact exists` carries
# no `continue-on-error`; the job's 20-minute cap sits above only 15
# minutes of step caps, so the two untimed steps can trip the JOB
# timeout; and a cancelled or infrastructure-lost `ledger` is neither
# 'success' nor a step outcome at all. Rare is the wrong bar for a guard
# whose failure mode is handing out a green required check.
#
# Note these are read as RESULTS, not as a reason to believe the matrix
# ran: if `review` ran at all, all four succeeded, so this guard can only
# fire on runs where the panel never started.
if: ${{ needs.gate.result != 'success' || needs.round-cap.result != 'success' || needs.diff-size.result != 'success' || needs.preflight.result != 'success' || needs.ledger.result != 'success' }}
env:
GATE_RESULT: ${{ needs.gate.result }}
ROUND_CAP_RESULT: ${{ needs.round-cap.result }}
DIFF_SIZE_RESULT: ${{ needs.diff-size.result }}
PREFLIGHT_RESULT: ${{ needs.preflight.result }}
LEDGER_RESULT: ${{ needs.ledger.result }}
run: |
echo "::error::Panel integrity cannot be judged: the jobs that decide whether a panel should run did not succeed (gate: ${GATE_RESULT}, round cap: ${ROUND_CAP_RESULT}, diff size: ${DIFF_SIZE_RESULT}, preflight: ${PREFLIGHT_RESULT}, ledger: ${LEDGER_RESULT}). Whether this PR was reviewed at all is unknown — re-run the failed job."
exit 1
- name: Report panel integrity
env:
OK_COUNT: ${{ needs.consolidate.outputs.ok_count }}
TOTAL: ${{ needs.consolidate.outputs.total }}
PANEL_INCONSISTENT: ${{ needs.consolidate.outputs.panel_inconsistent }}
DEGRADED: ${{ needs.consolidate.outputs.degraded }}
JUDGE_STATUS: ${{ needs.consolidate.outputs.judge_status }}
DELIVERED: ${{ needs.post-review.outputs.delivered }}
GATED: ${{ needs.post-review.outputs.gated_findings }}
UNGATED: ${{ needs.post-review.outputs.ungated_findings }}
# The RESULTS of the two jobs every value above comes out of. Each
# cause below is phrased against an OUTPUT, and an output is the empty
# string when the job producing it failed, was skipped or was
# cancelled — a state every one of those causes would otherwise read
# as a pass. `OK_COUNT != TOTAL` is the sharpest case: both are empty
# on a dead `consolidate`, so the comparison is unset-vs-unset and
# says "whole panel". That is caught today only because `DELIVERED`
# happens to be empty on those same runs, which is coincidence, not a
# guard — `post-review.py` writes `delivered=true` the moment the POST
# returns and keeps working, so a `post-review` that dies in a LATER
# step leaves delivered=true behind a red job. Read both signals, the
# way `Blocking gate`'s second guard does.
CONSOLIDATE_RESULT: ${{ needs.consolidate.result }}
POST_REVIEW_RESULT: ${{ needs.post-review.result }}
# LIVE since #321, which landed the incremental-diff fix this used to
# wait on: `diff-size` now declares the output on every run it
# completes, so this expression is the literal 'true' or 'false', and
# empty only when `diff-size` did NOT succeed — a path the guard step
# above has already exited 1 on.
#
# Read what 'false' MEANS, though, because it is not what the name
# suggests and it is why this is reported below as a ::warning:: that
# does NOT count toward `causes`. #321 made the subset check fail
# CLOSED: a block that does not verify is DISCARDED WHOLE and the
# panel runs on the full reviewed diff alone. So a 'false' run hands
# the cells byte-identical input to a run that never built a block at
# all — round 1, or any "could not build one" branch — and both of
# those report 'true'. The panel is provably just as whole; nothing
# was skipped and no finding was suppressed. `Panel integrity` is a
# check callers are told to mark REQUIRED, so reddening it over a run
# whose reviewed content is indistinguishable from a normal one is a
# merge-blocking false positive. The anomaly is still worth seeing —
# a 'false' means the BUILDER emitted a non-subset, a real defect —
# so it is annotated, just not as a panel-integrity failure.
INCREMENTAL_SUBSET: ${{ needs.diff-size.outputs.incremental_subset }}
run: |
# Every value below is a job output, and two of them (`JUDGE_STATUS`
# from the judge agent's own tool output, and the counts that follow a
# panel cell's artifact) originate in agent-written files inside jobs
# that run `--trust` over PR code. They land in ::workflow command::
# lines here, where a newline would forge a second command, so flatten
# and clamp before echoing.
#
# Escaping `%` is the other half of that, and it is not optional: the
# runner UNESCAPES `%25`, `%0D` and `%0A` in a command's message, so
# deleting real newlines alone is not enough. A judge that writes its
# `status` as `error%0A::stop-commands::x` reaches this line carrying
# no newline at all — and the runner puts one back, forging the second
# command `tr` was supposed to prevent. `%` -> `%25` turns that into
# the inert literal text `%0A`. It is the same escape every checker in
# this repo already applies before annotating (`check_agents_md.py`,
# `check_workflow_pins.py`, `check-org-repo-literals.sh`), and only
# `JUDGE_STATUS` can actually carry a `%` today: the counts are
# python-formatted integers and the rest are job results.
#
# Order is load-bearing at both ends. AFTER `tr`, so a real newline is
# dropped rather than escaped back into one by the runner; and AFTER
# `cut`, so the clamp can never split a `%25` it just created (`cut`
# only ever removes characters, so it cannot forge one either).
flatten() { printf '%s' "$1" | tr -d '\r\n' | cut -c1-64 | sed 's/%/%25/g'; }
causes=0
# Job-result causes FIRST, so a dead producer is named as itself
# rather than inferred from the empty outputs it left behind.
if [ "$CONSOLIDATE_RESULT" != "success" ]; then
echo "::error::The panel was never adjudicated: the Consolidate panel job did not succeed (result=$(flatten "${CONSOLIDATE_RESULT:-<unset>}")). Its cell counts and judge status are unavailable, so panel completeness is unknown rather than clean."
causes=$((causes + 1))
fi
if [ "$POST_REVIEW_RESULT" != "success" ]; then
echo "::error::The Post review job did not succeed (result=$(flatten "${POST_REVIEW_RESULT:-<unset>}")), so whether a review with resolvable threads reached this PR is unknown — delivered=true is written the moment the POST returns, before the rest of that job runs."
causes=$((causes + 1))
fi
# An EMPTY count is not a matching count. Guarded separately from the
# comparison below because unset-vs-unset compares EQUAL in `test`,
# which is the one way this check could print "whole panel" having
# counted nothing at all.
if [ -z "$OK_COUNT" ] || [ -z "$TOTAL" ]; then
echo "::error::Panel cell counts are missing (ok_count=$(flatten "${OK_COUNT:-<unset>}"), total=$(flatten "${TOTAL:-<unset>}")), so how many reviewer cells submitted cannot be established. Treat this as an incomplete panel, not a whole one."
causes=$((causes + 1))
elif [ "$OK_COUNT" != "$TOTAL" ]; then
echo "::error::Panel incomplete: $(flatten "$OK_COUNT") of $(flatten "$TOTAL") reviewer cells submitted a review. The consolidated review was adjudicated over a short panel — see the red leg checks for which cells did not submit."
causes=$((causes + 1))
fi
# Separate from the counts: here they can MATCH, and that is the
# problem. See aggregate-panel.py's two cross-checks.
if [ "$PANEL_INCONSISTENT" = "true" ]; then
echo "::error::A findings artifact may not be its own cell's: a reviewer leg did not succeed although every findings artifact reads ok, or a record disagrees with the artifact name it sits under (see the Aggregate panel findings warnings). Something other than that cell uploaded it, or an upload failed after the review. The panel count is untrusted; see the red leg checks."
causes=$((causes + 1))
fi
# Non-empty AND greater than zero: an EMPTY value means post-review
# never got as far as deciding, which `DELIVERED` below reports on its
# own terms rather than as a phantom unanchored finding.
if [ -n "$UNGATED" ] && [ "$UNGATED" != "0" ]; then
echo "::error::$(flatten "$UNGATED") finding(s) could not be anchored to the reviewed diff and were demoted to the review body, where they have no thread to resolve. Read the review body, not just the inline comments."
causes=$((causes + 1))
fi
if [ "$DELIVERED" != "true" ]; then
echo "::error::No review carrying resolvable finding threads was delivered to this PR (post-review delivered=$(flatten "${DELIVERED:-<unset>}")). The findings, if any, are in the post-review job summary."
causes=$((causes + 1))
fi
if [ "$DEGRADED" = "true" ]; then
echo "::error::The judge did not adjudicate this panel (judge status=$(flatten "${JUDGE_STATUS:-?}")); the review was built from the raw union of the cells' findings, so duplicates and false positives were not filtered."
causes=$((causes + 1))
fi
# Deliberately NOT a cause, and deliberately not phrased as one —
# see the INCREMENTAL_SUBSET comment above. The block was thrown
# away, so the cells read the full reviewed diff, exactly as they do
# on round 1. Surfaced because a non-subset block means the BUILDER
# misbehaved, never because this panel came up short.
if [ "$INCREMENTAL_SUBSET" = "false" ]; then
echo "::warning::The incremental \"new since the last reviewed round\" block failed its subset check and was discarded, so the panel reviewed the full diff without a prioritization hint. Nothing was skipped and no finding was suppressed — see the 'Incremental diff discarded' warning on the Diff size check job for the counts."
fi
if [ "$causes" -ne 0 ]; then
echo "Panel integrity: $causes problem(s) above."
exit 1
fi
echo "::notice::Panel integrity: $(flatten "$OK_COUNT")/$(flatten "$TOTAL") cells, $(flatten "${GATED:-0}") anchored finding(s), 0 unanchored."
blocking-gate:
# Opt-in merge gate (inputs.blocking), restored by BE-4691 after #31
# dropped it unintentionally. Fails this check while the PR has unresolved,
# non-outdated cursor-review finding threads, so a caller that marks
# "Blocking gate" a required status check blocks merge until every finding
# thread is addressed. With blocking:false (default) this job is skipped
# entirely — the review stays advisory and no enrolled caller's behavior
# changes.
#
# With blocking on, this job runs on EVERY delivered event — deliberately
# NOT conditioned on `should_run`, unlike the original #16 job. A skipped
# required check counts as PASSING, so any run where the trigger step says
# "don't review" (an unrelated label toggled, skip-cursor-review present,
# the trigger label removed) would otherwise mint a green "Blocking gate"
# over open finding threads. Running unconditionally makes the verdict
# event-independent: are there live unresolved cursor-review threads on
# this PR right now. That is also what makes a pull_request_review_thread
# trigger in the caller's `on:` block a pure re-check — the trigger step
# leaves should_run=false, so the panel, comments and DMs all stay skipped
# while this gate re-queries thread state and flips green on the last
# resolve. The same holds for plain PR events under a label-gated caller,
# so a blocking caller that widens its `types:` gets a gate verdict on
# every push instead of a required check stuck at "Expected".
# (Fork PRs never gate red: their runs can post no review, so they have no
# finding threads to be unresolved.)
#
# `needs: post-review` orders it after the review's threads exist on a
# fresh run; `always()` (not `!cancelled()`) is what keeps it reporting.
# post-review uses `!cancelled()` because it WRITES and must not race the
# run that superseded it — this job writes nothing, it re-reads live thread
# state, so a superseded run and its replacement can only agree. What
# `!cancelled()` would cost is the whole point of the job: a cancelled run
# skips it, GitHub counts a skipped required check as PASSING, and the
# documented caller makes cancellation easy to reach (`cancel-in-progress`
# puts thread-resolve events in the same group as panel runs, and an author
# can cancel by hand). Green-on-cancel is the exact fail-OPEN this job
# exists to close, so it runs on cancellation too — and if the teardown
# takes its steps down with it, the check goes RED, which is the safe side.
name: Blocking gate
needs: [gate, round-cap, diff-size, post-review]
if: ${{ always() && inputs.blocking }}
runs-on: ubuntu-latest
# One paged GraphQL query through gh — minutes at most; bounded like every
# other job here so a hung API call cannot hold a runner for the 6-hour
# default.
timeout-minutes: 10
permissions:
contents: read
pull-requests: read
steps:
- name: Fail if the trigger decision itself failed
# FIRST fail-closed guard, and it has to come first because every guard
# below is phrased in terms of `needs.gate.outputs.*`. Those outputs are
# EMPTY when the gate job failed — its dup-check API call and its label
# `jq` can both error — so `should_run == 'true'` is false, every
# downstream guard skips, and the run falls through to a thread query
# that finds nothing on a PR nobody ever decided to review. That is a
# green required check produced by a red job, on exactly the path these
# guards exist to close. An undecided run is not a clean run.
if: ${{ needs.gate.result != 'success' }}
env:
GATE_RESULT: ${{ needs.gate.result }}
run: |
echo "::error::The cursor-review trigger job did not succeed (gate: $GATE_RESULT), so whether this PR should have been reviewed is unknown — refusing to pass the blocking gate. Re-run the failed job."
exit 1
- name: Fail if the fresh review did not land
# SECOND fail-closed guard. A gate that passed while the review it gates
# on never landed would be fail-OPEN: no threads exist, the query below
# finds nothing, green check. So on the fresh path — the trigger step
# said a panel should run and no dedupe hit — refuse to pass unless the
# pipeline actually delivered a review.
#
# Two things are checked, and BOTH are needed:
#
# * `needs.post-review.result == 'success'`. post-review, not
# consolidate, is the terminal write since the credential split: a
# consolidate that succeeded into a failed post still posted nothing.
# * `needs.post-review.outputs.delivered == 'true'`. The job result is
# NOT sufficient on its own — post-review.py exits 0 after a
# read-only-token 403 (review written to the job summary, never to the
# PR), after the body-only "Review failed" error review, after the
# no-findings review a run posts when every panel cell errored, and
# after the 422 inline-anchor fallback. Each of those is a zero exit
# over a round that adjudicated nothing, and each leaves the thread
# query below empty. The script therefore emits the claim positively
# (see its emit_delivery); an unset value — the script died before
# deciding — is not `'true'`, so the default is closed.
#
# Over the cap is NOT exempt any more. It used to fall through to the
# thread query as a "documented, announced skip", but diff size is fully
# author-controlled: padding a PR past `diff_size_cap` skipped the panel
# AND outdated every thread an earlier under-cap round had posted, so one
# commit both cleared the existing findings and greened the gate. "Too
# big to review" is not evidence a PR is clean. For a blocking caller the
# over-cap path now holds the check red (post-review is skipped, so this
# guard fires) until the diff comes under the cap or the caller raises
# `diff_size_cap`. Only the genuinely review-free paths stay exempt —
# should_run=false events and the already_reviewed re-trigger — and those
# fall through to the live thread query, which is the whole verdict there.
if: ${{ needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && (needs.diff-size.result != 'success' || needs.post-review.result != 'success' || needs.post-review.outputs.delivered != 'true') }}
env:
DIFF_SIZE_RESULT: ${{ needs.diff-size.result }}
WITHIN_CAP: ${{ needs.diff-size.outputs.within_cap }}
POST_REVIEW_RESULT: ${{ needs.post-review.result }}
DELIVERED: ${{ needs.post-review.outputs.delivered }}
CAPPED: ${{ needs.round-cap.outputs.capped }}
run: |
# The round cap is not exempt either, for the same reason as the size
# cap below: no panel looked at this head. The PR is handed to a human
# (needs-human-review); removing that label resets the cap.
if [ "$CAPPED" = "true" ]; then
echo "::error::This PR hit cursor-review's max_rounds cap, so no review ran on this head and it is labelled needs-human-review — an unreviewed head cannot pass a blocking gate. Have a human review it, then remove the label to resume automated rounds."
exit 1
fi
if [ "$DIFF_SIZE_RESULT" = "success" ] && [ "$WITHIN_CAP" != "true" ]; then
echo "::error::This PR's counted diff exceeds diff_size_cap, so no review ran — and an unreviewed PR cannot pass a blocking gate. Split the PR under the cap and re-trigger the review, or raise diff_size_cap on the caller."
exit 1
fi
echo "::error::A fresh review was triggered but did not land on this PR (diff-size: $DIFF_SIZE_RESULT, post-review: $POST_REVIEW_RESULT, delivered: ${DELIVERED:-<unset>}) — refusing to pass the blocking gate. Re-run the failed jobs or re-trigger the review."
exit 1
- name: Fail if the review landed with no resolvable threads
# THIRD fail-closed guard, for the one delivery that is real and still
# invisible to the query below. post-review.py demotes a finding whose
# anchor misses the reviewed diff into the review BODY, and falls back to
# a wholly body-only review when GitHub 422s the inline payload. Neither
# creates a thread. A round in which EVERY finding was demoted posts N
# real findings and leaves zero threads — indistinguishable, to a thread
# query, from a clean PR — so the gate would report green over findings
# nobody can even reply to, which is precisely the "every finding was
# explicitly looked at and closed out" claim falsified.
#
# Scoped to the fully-degraded round (threads == 0 while body-only
# findings exist) on purpose. A PARTIALLY demoted round keeps its inline
# half, so the gate already holds red on those threads; failing on the
# demoted half too would be a check no thread resolution could ever clear
# — a bricked PR rather than a gate. That residual is documented in the
# setup guide's blocking-gate gotchas rather than papered over here.
if: ${{ needs.post-review.outputs.delivered == 'true' && needs.post-review.outputs.gated_findings == '0' && needs.post-review.outputs.ungated_findings != '0' && needs.post-review.outputs.ungated_findings != '' }}
env:
UNGATED: ${{ needs.post-review.outputs.ungated_findings }}
run: |
echo "::error::The review landed but every one of its $UNGATED finding(s) was posted in the review body with no inline thread (the anchors missed the reviewed diff, or GitHub rejected the inline payload), so there is nothing for this gate to watch resolve. Read the findings in the review body, push a fix, and re-trigger the review."
exit 1
- name: Require a pull-request event
# gate-unresolved.py's --pr-number is argparse `type=int`, and this job
# runs on EVERY delivered event by design. On any payload without a pull
# request — `merge_group` (which a merge queue runs required checks on),
# `workflow_dispatch`, `push`, `issue_comment` — the expression below is
# empty and argparse exits 2, leaving a required check permanently red
# whose only explanation is a traceback and which no thread resolution
# can clear. Say what is wrong instead. Still a FAILURE, not a skip: a
# skipped required check counts as passing, and this gate cannot judge a
# PR it was not handed. The fix is the caller's `on:` block — see the
# blocking caller shape in docs/callers/cursor-review.md.
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_NAME: ${{ github.event_name }}
run: |
if [ -z "$PR_NUMBER" ]; then
echo "::error::The blocking gate was triggered by '$EVENT_NAME', which carries no pull_request payload, so it cannot read this PR's review threads. Trigger cursor-review from pull_request (or pull_request_target) / pull_request_review_thread events (see the blocking caller shape in docs/callers/cursor-review.md)."
exit 1
fi
- name: Fail while the PR is handed to a human (round cap)
# The `round-cap` output above only exists on a run that counted rounds.
# Every later non-review event on a capped PR — a thread resolve, an
# unrelated label, the bot's own label write — skips `round-cap`, so the
# CAPPED check above never fires and the thread query alone would pass
# once the old threads are resolved or outdated, over a head no panel
# reviewed. The label is the cap's persistent state (removing it is the
# reset), so read it live on every event. A failed read fails closed,
# like every other guard here.
if: ${{ inputs.max_rounds > 0 }}
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
if ! labels="$(gh api "repos/$REPO/pulls/$PR_NUMBER" --jq '.labels[].name')"; then
echo "::error::Could not read this PR's labels to check the max_rounds cap — refusing to pass the blocking gate. Re-run the job."
exit 1
fi
if printf '%s\n' "$labels" | grep -qixF 'needs-human-review'; then
echo "::error::This PR carries needs-human-review (cursor-review's max_rounds cap, or a human hand-off), so automated rounds are paused and no panel has reviewed this head — an unreviewed head cannot pass a blocking gate. Have a human review it, then remove the label to resume automated rounds."
exit 1
fi
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Fail on unresolved cursor-review threads
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
run: |
python3 "$CURSOR_REVIEW_ASSETS/gate-unresolved.py" \
--repo "$REPO" \
--pr-number "$PR_NUMBER"
notify-start:
name: Notify start
needs: [gate, diff-size]
if: needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Resolve triggerer
id: triggerer
env:
GH_ACTOR: ${{ github.actor }}
PR_ASSIGNEES: ${{ toJSON(github.event.pull_request.assignees.*.login) }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [[ "$GH_ACTOR" == *"[bot]" ]]; then
ASSIGNEE=$(echo "$PR_ASSIGNEES" | jq -r '.[0] // empty')
# Prefer PR author for DM routing — they opened the work and most want
# the review status. Falls back to assignee, then empty (skips DM) if
# the author is also a bot (e.g. Dependabot PRs).
RESOLVED="${PR_AUTHOR:-${ASSIGNEE:-}}"
if [[ "$RESOLVED" == *"[bot]" ]]; then RESOLVED=""; fi
echo "triggered_by=$RESOLVED" >> "$GITHUB_OUTPUT"
else
echo "triggered_by=$GH_ACTOR" >> "$GITHUB_OUTPUT"
fi
- name: DM triggerer — review starting
continue-on-error: true
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
DM_GITHUB_USER: ${{ steps.triggerer.outputs.triggered_by }}
# JSON GitHub-handle → email-prefix overrides, kept out of this public
# repo. Set it as an org/repo Actions variable; absent = handle is used
# as the email prefix verbatim.
DM_EMAIL_MAP: ${{ vars.CURSOR_REVIEW_DM_EMAIL_MAP }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_URL: ${{ github.event.pull_request.html_url }}
run: |
chmod +x "$CURSOR_REVIEW_ASSETS/slack-notify.sh"
MSG="*${PR_TITLE}*"$'\n'"${PR_URL}"$'\n'"8-cell panel running, then a judge consolidates."
"$CURSOR_REVIEW_ASSETS/slack-notify.sh" \
"warning" \
"Cursor review starting" \
"$MSG"
notify-complete:
name: Notify complete
needs: [gate, diff-size, review, consolidate, post-review]
# `!cancelled()` for the same reason `consolidate` above uses it, plus one
# of its own: this job reads a skipped/cancelled `post-review` as a posting
# failure and DMs the triggerer "Cursor review failed to post". On a
# cancelled run that message is simply false — the veto label, or a newer
# push, stopped the panel on purpose — so a run someone deliberately
# stopped should not page anyone. Genuine failures are untouched: a failed
# cell, judge or post is not a cancelled RUN and still notifies. (It also
# keeps this job's `needs: consolidate` honest now that `consolidate` is
# itself `!cancelled()` and no longer runs on a cancelled run.)
if: ${{ !cancelled() && needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' && needs.diff-size.outputs.within_cap == 'true' && needs.review.result != 'skipped' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Resolve triggerer
id: triggerer
env:
GH_ACTOR: ${{ github.actor }}
PR_ASSIGNEES: ${{ toJSON(github.event.pull_request.assignees.*.login) }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [[ "$GH_ACTOR" == *"[bot]" ]]; then
ASSIGNEE=$(echo "$PR_ASSIGNEES" | jq -r '.[0] // empty')
# Prefer PR author for DM routing — they opened the work and most want
# the review status. Falls back to assignee, then empty (skips DM) if
# the author is also a bot (e.g. Dependabot PRs).
RESOLVED="${PR_AUTHOR:-${ASSIGNEE:-}}"
if [[ "$RESOLVED" == *"[bot]" ]]; then RESOLVED=""; fi
echo "triggered_by=$RESOLVED" >> "$GITHUB_OUTPUT"
else
echo "triggered_by=$GH_ACTOR" >> "$GITHUB_OUTPUT"
fi
- name: DM triggerer — review complete
continue-on-error: true
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
DM_GITHUB_USER: ${{ steps.triggerer.outputs.triggered_by }}
# See notify-start: JSON handle → email-prefix overrides, supplied as
# an org/repo Actions variable so the roster stays out of this repo.
DM_EMAIL_MAP: ${{ vars.CURSOR_REVIEW_DM_EMAIL_MAP }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_URL: ${{ github.event.pull_request.html_url }}
CONSOLIDATE_RESULT: ${{ needs.consolidate.result }}
POST_REVIEW_RESULT: ${{ needs.post-review.result }}
# Not redundant with the result above (BE-10017): post-review.py exits
# 0 — so the job is green — after a read-only-token 403, having written
# the review to the run's job summary instead of the PR. Deliberate (a
# caller that forgot `pull-requests: write` still gets its review
# somewhere), but it made the success DM claim a review that is not
# there. Unset reads as not-'true', which is the fail-closed direction:
# the worst case is a degraded DM on a review that did post.
REVIEW_POSTED: ${{ needs.post-review.outputs.posted }}
# `posted` and `delivered` disagree in BOTH directions, so the DM needs
# both: the "Review failed" error review and the all-cells-failed review
# DO reach the PR (posted) while adjudicating nothing (not delivered).
# Claiming "review complete" over those is the same class of lie this
# ticket fixes, one branch further in — the blocking gate refuses that
# exact round. Unset reads as not-'true', i.e. fail-closed here too.
REVIEW_DELIVERED: ${{ needs.post-review.outputs.delivered }}
run: |
chmod +x "$CURSOR_REVIEW_ASSETS/slack-notify.sh"
# Keyed on the POST job, not on consolidate: since the credential
# split it is `post-review` that puts the review on the PR, so a green
# consolidate alone no longer justifies "one consolidated review is on
# the PR". The two failures are distinguished so the DM says which
# half broke.
if [ "$POST_REVIEW_RESULT" = "success" ] && [ "$REVIEW_POSTED" = "true" ] && [ "$REVIEW_DELIVERED" = "true" ]; then
STATUS="success"
TITLE="Cursor review complete"
DETAIL="One consolidated review is on the PR."
elif [ "$POST_REVIEW_RESULT" = "success" ] && [ "$REVIEW_POSTED" = "true" ]; then
# A body reached the PR but adjudicated nothing: the "Review failed"
# error review, or the review a round posts when every panel cell
# errored. Pointing at the PR is right — there IS something to read
# there — but calling it complete is not.
STATUS="warning"
TITLE="Cursor review incomplete"
DETAIL="A review was posted on the PR, but it adjudicated nothing — the judge failed, or every reviewer in the panel errored. See the run for the underlying cause."
elif [ "$POST_REVIEW_RESULT" = "success" ]; then
# Green job, nothing on the PR. The designed-for case is the
# read-only-token degradation, but this branch is reached by every
# green run that did not post, so state the OBSERVATION as fact and
# the cause as likelihood: is_read_only_token_error treats every 403
# EXCEPT a throttle as read-only (BE-12612), so an SSO/IP-allowlist
# or archived-repo rejection lands here too, as does an App
# installation without pull-request write (where the caller's
# permissions block is not the knob) and a workflows_ref resolving
# to a post-review.py too old to emit `posted` at all. A throttle
# GitHub WORDS as one no longer arrives here: it takes the
# landed-review check instead and fails red if nothing landed, which
# the failure branch below already covers. An unworded 403 — what an
# edge, a WAF or a GHES proxy returns with no JSON body — carries
# nothing to tell those apart by, so it is read as standing and does
# still land here; hence "most often", not "always".
STATUS="warning"
TITLE="Cursor review degraded"
DETAIL="No review was posted on the PR — the full text is in the run's job summary. Most often the run's token lacks pull-requests: write (check the caller's permissions block); another standing 403 (SSO/IP allowlist, archived repo) or a stale workflows_ref pin reaches this too. A 403 GitHub worded as a rate limit does not reach this — it takes the landed-review check and fails the job red if nothing landed — but a 403 carrying no message at all (an edge or proxy) is indistinguishable from a standing refusal and does, so check the run log for the actual error before ruling a throttle out."
elif [ "$CONSOLIDATE_RESULT" != "success" ]; then
STATUS="warning"
TITLE="Cursor review failed to post"
DETAIL="Consolidate step did not succeed — see the run for details."
else
STATUS="warning"
TITLE="Cursor review failed to post"
DETAIL="The panel consolidated, but the post-review job did not succeed — see the run for details."
fi
MSG="*${PR_TITLE}*"$'\n'"${PR_URL}"$'\n'"${DETAIL}"
"$CURSOR_REVIEW_ASSETS/slack-notify.sh" \
"$STATUS" \
"$TITLE" \
"$MSG"
auto-retry:
# BE-19526: re-run a round the head outran, once per PR. `Auto-approve
# decision` decides it and leaves the marked standing block and the card;
# this job only does the relabel, and runs LAST on purpose. Removing and
# re-adding the label fires `unlabeled`/`labeled` events that land in the
# documented caller's `cancel-in-progress` group (and this reusable's own
# `trigger` slot), cancelling whatever of THIS run is still going — so every
# job that reports on the round (the Blocking gate and Panel integrity
# checks, the completion DM) must be done first. `needs:` them all, with
# `!cancelled()` so a skipped or red one does not skip the retry; a push that
# cancels this run before it gets here leaves the card's "if no new round
# starts, re-run it by hand" as the recovery.
name: Re-run the round
needs: [post-review, panel-integrity, blocking-gate, notify-complete]
if: ${{ !cancelled() && needs.post-review.outputs.auto_retry == 'true' }}
# The caller environment holding APPROVER_TOKEN (docs/callers/cursor-review.md#trust-model);
# '' = none. Only the APPROVER_TOKEN jobs declare it — never a job that
# checks out PR code — and only under `pull_request_target`: any other
# event runs on `refs/pull/<n>/merge`, which a base-branch-only deployment
# policy rejects before a step runs.
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
runs-on: ubuntu-latest
# 5 for the relabel itself, plus the 30 `auto_retry_delay_minutes` is
# clamped to: a job killed mid-wait would leave the card promising a round
# that never starts. A ceiling, not a reservation — a caller that set no
# delay still finishes in seconds.
timeout-minutes: 35
permissions:
contents: read
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Mint bot-identity token (optional)
id: bot_token
if: ${{ inputs.bot_app_id != '' }}
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
- name: Wait before re-running
# The failures this retries are overwhelmingly provider capacity, so a
# few minutes is what makes the second attempt different from the
# first. Default 0 keeps every existing caller's behaviour.
#
# The wait is a sleeping runner, which is this feature's whole cost on
# a private repo. Clamped to 30 minutes, and anything unparsable is
# treated as 0 rather than holding a runner on a typo.
#
# The wait widens the window in which this job can be cancelled: a
# caller whose concurrency group is keyed on the PR alone, with
# `cancel-in-progress: true`, loses the pending retry to ANY event on
# the PR during the sleep — a label, an edit — not only a push. The
# card's "if no new round starts, re-run it by hand" is the recovery;
# docs/callers/cursor-review.md says so.
if: ${{ inputs.auto_retry_delay_minutes != 0 }}
env:
DELAY_MINUTES: ${{ inputs.auto_retry_delay_minutes }}
run: |
mins="${DELAY_MINUTES:-0}"
case "$mins" in ''|*[!0-9]*) mins=0 ;; esac
# More than three digits is over the cap whatever it says, and a long
# enough one overflows bash's integers before the test below can clamp it.
if [ "${#mins}" -gt 3 ]; then mins=30; fi
if [ "$mins" -gt 30 ]; then mins=30; fi
if [ "$mins" -eq 0 ]; then
echo "No usable retry delay — re-running immediately."
exit 0
fi
echo "Waiting ${mins} minute(s) before re-running the round, so a transient provider failure has time to clear."
sleep "$(( mins * 60 ))"
- name: Remove and re-add the review label
env:
# The token decide held (same precedence), never GITHUB_TOKEN: a
# GITHUB_TOKEN-applied label fires no workflow run. decide only sets
# `auto_retry` when one of these two is configured.
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
BOT_TOKEN: ${{ steps.bot_token.outputs.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
REVIEW_LABEL: ${{ inputs.review_label }}
EVENT_NAME: ${{ github.event_name }}
APPROVER_ENVIRONMENT: ${{ inputs.approver_environment }}
run: |
# Trust model (docs/callers/cursor-review.md#trust-model): only
# `pull_request_target` loads the caller from the base branch; on any
# other event a PR can read APPROVER_TOKEN — do not act as it. (A
# relabel approves nothing, so the fallback identity is fine here.)
if [ -n "$APPROVER_TOKEN" ] && [ "$EVENT_NAME" != "pull_request_target" ]; then
echo "::error::APPROVER_TOKEN on a '$EVENT_NAME' run is readable by any PR-head workflow; call this reusable from pull_request_target with approver_environment (docs/callers/cursor-review.md#trust-model)"
APPROVER_TOKEN=""
elif [ -n "$APPROVER_TOKEN" ] && [ -z "$APPROVER_ENVIRONMENT" ]; then
echo "::warning::APPROVER_TOKEN without approver_environment is a repo secret that any PR-head pull_request workflow can read; move it into a base-branch-only environment and pass approver_environment (docs/callers/cursor-review.md#trust-model)"
fi
if [ -n "$APPROVER_TOKEN" ]; then
export GH_TOKEN="$APPROVER_TOKEN"
elif [ -n "$BOT_TOKEN" ]; then
export GH_TOKEN="$BOT_TOKEN"
else
echo "::error::No APPROVER_TOKEN or bot App token, so the round cannot be re-run (a GITHUB_TOKEN label fires no run). Re-run it by hand."
exit 1
fi
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" auto-retry \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--review-label "$REVIEW_LABEL"
approve-only:
# `approve_only_on_push`: on a push past a passing panel, run no panel and
# hand the new head to the caller's cursor-approve jobs (the `approve_gate`
# output reads `go`). `auto-approve.py approve-only` decides; see its block
# comment for every condition. Two stages either side of the debounce:
# `check` (eligible? announce it on the card; `auto-rereview` stands down
# on `eligible`) and `start` (re-read everything live, record the head on
# the card's re-check sentinel, write `go` and `round`).
#
# After `Dismiss stale auto-approval`, so its stale-card write lands first
# and this job's announcement replaces that card's next step; and only
# after it SUCCEEDED, since a failed dismissal may leave a stale approval
# standing beside the head this run's axes judge.
#
# Debounce: the wait lives in this run, and a newer push's run takes the
# same `label-` slot of the workflow-level `concurrency:` above
# (cancel-in-progress), cancelling it — so a burst of pushes runs one
# re-check, on the last head. `start` also re-reads the live head and
# stands down if it moved. KNOWN GAP, as `auto-rereview`'s: any other event
# in that slot (a `pull_request_review_thread` run, e.g. resolving a thread
# right after the push) cancels the wait too, and no re-check starts; the
# card's "for the full panel instead, relabel" and the next push cover it.
#
# The decide phase re-reads the head and base before it approves
# (auto-approve.py approve-external), so a head that moves while the axes
# run is `superseded`, never approved.
name: Approver-only re-check
needs: dismiss-stale-approval
if: >-
${{ !cancelled() && inputs.approve_only_on_push && !inputs.run_without_label &&
inputs.approve_max_severity != '' &&
needs.dismiss-stale-approval.result == 'success' &&
github.event_name == 'pull_request_target' &&
(github.event.action == 'synchronize' || github.event.action == 'reopened') &&
github.event.pull_request.state == 'open' &&
github.event.pull_request.head.repo.full_name == github.repository }}
# One waiter per PR + head, serialised (a `reopened` and a `synchronize`
# for the same head): the second reads the first's record and skips.
concurrency:
group: cursor-review-reusable-approve-only-${{ github.repository }}-${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}
cancel-in-progress: false
# The caller environment holding APPROVER_TOKEN (docs/callers/cursor-review.md#trust-model);
# '' = none. Only under `pull_request_target`, which the `if:` requires.
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
runs-on: ubuntu-latest
# 5 for the reads and writes, plus the 30 `auto_rereview_delay_minutes` is
# clamped to.
timeout-minutes: 35
permissions:
contents: read
pull-requests: write
outputs:
eligible: ${{ steps.check.outputs.eligible }}
go: ${{ steps.start.outputs.go }}
round: ${{ steps.start.outputs.round }}
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Is this push re-checked by the axes alone
id: check
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
THRESHOLD: ${{ inputs.approve_max_severity }}
APPROVE_AUTHORS: ${{ inputs.approve_authors }}
MAX_RUNS: ${{ inputs.approve_only_max_runs }}
MAX_ROUNDS: ${{ inputs.max_rounds }}
DELAY_MINUTES: ${{ inputs.auto_rereview_delay_minutes }}
APPROVER_ENVIRONMENT: ${{ inputs.approver_environment }}
run: |
# The card lives under the approver identity, and the caller's
# cursor-approve jobs this hands the head to act as it too: without
# APPROVER_TOKEN there is nothing to re-check with.
if [ -z "$APPROVER_TOKEN" ]; then
echo "eligible=false" >> "$GITHUB_OUTPUT"
echo "::warning::approve_only_on_push needs APPROVER_TOKEN (the cursor-approve identity) — not re-checking this push."
exit 0
fi
if [ -z "$APPROVER_ENVIRONMENT" ]; then
echo "::warning::APPROVER_TOKEN without approver_environment is a repo secret that any PR-head pull_request workflow can read; move it into a base-branch-only environment and pass approver_environment (docs/callers/cursor-review.md#trust-model)"
fi
export GH_TOKEN="$APPROVER_TOKEN"
LOGIN="$(gh api user --jq .login)"
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" approve-only --stage check \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--head-sha "$HEAD_SHA" \
--approver-login "$LOGIN" \
--review-label "$REVIEW_LABEL" \
--threshold "$THRESHOLD" \
--approve-authors "$APPROVE_AUTHORS" \
--max-runs "$MAX_RUNS" \
--max-rounds "$MAX_ROUNDS" \
--delay-minutes "$DELAY_MINUTES"
- name: Wait before re-checking
# The debounce, shared with `auto-rereview`: clamped to 30 minutes;
# anything unparsable is treated as 0.
if: steps.check.outputs.eligible == 'true'
env:
DELAY_MINUTES: ${{ inputs.auto_rereview_delay_minutes }}
run: |
mins="${DELAY_MINUTES:-0}"
case "$mins" in ''|*[!0-9]*) mins=0 ;; esac
if [ "${#mins}" -gt 3 ]; then mins=30; fi
if [ "$mins" -gt 30 ]; then mins=30; fi
echo "Waiting ${mins} minute(s) before re-checking, so further pushes can land first."
sleep "$(( mins * 60 ))"
- name: Re-check if it is still wanted
id: start
if: steps.check.outputs.eligible == 'true'
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
THRESHOLD: ${{ inputs.approve_max_severity }}
APPROVE_AUTHORS: ${{ inputs.approve_authors }}
MAX_RUNS: ${{ inputs.approve_only_max_runs }}
MAX_ROUNDS: ${{ inputs.max_rounds }}
run: |
export GH_TOKEN="$APPROVER_TOKEN"
LOGIN="$(gh api user --jq .login)"
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" approve-only --stage start \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--head-sha "$HEAD_SHA" \
--approver-login "$LOGIN" \
--review-label "$REVIEW_LABEL" \
--threshold "$THRESHOLD" \
--approve-authors "$APPROVE_AUTHORS" \
--max-runs "$MAX_RUNS" \
--max-rounds "$MAX_ROUNDS"
auto-rereview:
# BE-20262: start the round a dismissal left wanting, once per head, after
# a debounce. `Dismiss stale auto-approval` decides it (and marks the card
# stale either way); this job waits, then `auto-approve.py auto-rereview`
# re-reads everything live and relabels only if the head is still the one
# that was dismissed and has no round of its own yet, nothing has started
# a round since the approval the card reports, the PR is open, not a
# draft, unvetoed and under `max_rounds`.
# A newer push during the wait reaches its own dismiss job, which
# schedules its own wait. KNOWN GAP: the wait lives in the source run, so
# any later event in the same `label-` concurrency slot cancels it. A
# `pull_request`/`pull_request_target` event replaces it (its dismiss job
# re-schedules from the stale card); a `pull_request_review_thread` run,
# e.g. resolving a thread right after the push, does not, and no round
# starts. The card's "If none starts, re-run it by hand" covers that.
#
# Under `approve_only_on_push` it waits on `approve-only` and stands down
# only when that job actually started the re-check (`go`): the axes judge
# the head, so no full round is relabelled for it. Gating on `go`, not
# `eligible`, keeps the round when `start` stands down after the debounce
# (the live PR turned ineligible, or the card could not record it) —
# `approve_gate` is then `untrusted` and no axes run either. `approve-only`
# is skipped (empty output) for every caller that did not opt in.
name: Start the next round after a dismissal
needs: [dismiss-stale-approval, approve-only]
if: ${{ !cancelled() && needs.dismiss-stale-approval.outputs.auto_rereview == 'true' && needs.approve-only.outputs.go != 'true' }}
# Every later PR event re-schedules a waiter from the stale card, so
# waiters for one head are serialised, never run side by side: the next
# one starts after the first has recorded its round on the card, reads
# that record and skips. Not cancel-in-progress — that would kill the
# wait a burst of label/edit events keeps re-scheduling.
concurrency:
group: cursor-review-reusable-auto-rereview-${{ github.repository }}-${{ github.event.pull_request.number }}-${{ needs.dismiss-stale-approval.outputs.rereview_head }}
cancel-in-progress: false
# The caller environment holding APPROVER_TOKEN (docs/callers/cursor-review.md#trust-model);
# '' = none. Only the APPROVER_TOKEN jobs declare it — never a job that
# checks out PR code — and only under `pull_request_target`: any other
# event runs on `refs/pull/<n>/merge`, which a base-branch-only deployment
# policy rejects before a step runs.
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
runs-on: ubuntu-latest
# 5 for the relabel, plus the 30 `auto_rereview_delay_minutes` is clamped to.
timeout-minutes: 35
permissions:
contents: read
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Mint bot-identity token (optional)
id: bot_token
if: ${{ inputs.bot_app_id != '' }}
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ inputs.bot_app_id }}
private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
- name: Wait before starting the round
# The debounce: a burst of pushes settles into one round. Clamped to
# 30 minutes; anything unparsable is treated as 0.
env:
DELAY_MINUTES: ${{ inputs.auto_rereview_delay_minutes }}
run: |
mins="${DELAY_MINUTES:-0}"
case "$mins" in ''|*[!0-9]*) mins=0 ;; esac
if [ "${#mins}" -gt 3 ]; then mins=30; fi
if [ "$mins" -gt 30 ]; then mins=30; fi
echo "Waiting ${mins} minute(s) before starting the round, so further pushes can land first."
sleep "$(( mins * 60 ))"
- name: Start the round if it is still wanted
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
BOT_TOKEN: ${{ steps.bot_token.outputs.token }}
APP_SLUG: ${{ steps.bot_token.outputs.app-slug }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ needs.dismiss-stale-approval.outputs.rereview_head }}
MAX_ROUNDS: ${{ inputs.max_rounds }}
EVENT_NAME: ${{ github.event_name }}
APPROVER_ENVIRONMENT: ${{ inputs.approver_environment }}
run: |
# Trust model as in `Re-run the round`; the same identity the dismiss
# job wrote the card under, so it finds (and records on) that card.
if [ -n "$APPROVER_TOKEN" ] && [ "$EVENT_NAME" != "pull_request_target" ]; then
echo "::error::APPROVER_TOKEN on a '$EVENT_NAME' run is readable by any PR-head workflow; call this reusable from pull_request_target with approver_environment (docs/callers/cursor-review.md#trust-model)"
exit 1
elif [ -n "$APPROVER_TOKEN" ] && [ -z "$APPROVER_ENVIRONMENT" ]; then
echo "::warning::APPROVER_TOKEN without approver_environment is a repo secret that any PR-head pull_request workflow can read; move it into a base-branch-only environment and pass approver_environment (docs/callers/cursor-review.md#trust-model)"
fi
if [ -n "$APPROVER_TOKEN" ]; then
export GH_TOKEN="$APPROVER_TOKEN"
LOGIN="$(gh api user --jq .login)"
elif [ -n "$BOT_TOKEN" ]; then
export GH_TOKEN="$BOT_TOKEN"
LOGIN="${APP_SLUG}[bot]"
else
echo "::error::No APPROVER_TOKEN or bot App token, so the round cannot be started (a GITHUB_TOKEN label fires no run). Re-run it by hand."
exit 1
fi
if [ -n "$APP_SLUG" ]; then POSTER="${APP_SLUG}[bot]"; else POSTER="github-actions[bot]"; fi
python3 "$CURSOR_REVIEW_ASSETS/auto-approve.py" auto-rereview \
--repo "$REPO" \
--pr-number "$PR_NUMBER" \
--head-sha "$HEAD_SHA" \
--approver-login "$LOGIN" \
--poster-login "$POSTER" \
--review-label "$REVIEW_LABEL" \
--max-rounds "$MAX_ROUNDS"
approve-start-early:
# `axes_alongside_panel` (see the header): cursor-approve's `start` phase,
# right after `round-cap` instead of after this whole workflow. Same
# eligibility the caller's own start has — `pull_request_target`,
# auto-approve on, an author `approve_authors` lets through — plus a round
# this run actually starts. `approve_gate` is `pending` (the panel has not
# decided; the card carries no axes-lane marker, which
# `approve_only_on_push` reads as "the panel passed") or `capped` (the
# hand-off card, and its withdrawal of the standing block; no axis runs).
# `round` is the REAL next round: `card.py prior` keeps only rounds
# strictly below it, so an empty one would feed an axis its own re-run.
# `contents: read` only: a nested job cannot exceed its caller's grant,
# and the documented caller grants `contents` + `pull-requests`, so
# anything more here (or in cursor-approve.yml) fails every caller at
# startup, whether or not it set this input.
#
# `defer_approval` is required: without it `post-review` approves on
# severity alone, and nothing withdraws that approval while the axes run
# (the caller's own start, which would, is skipped on `axes_started`).
# A round the panel itself will not review — over the diff-size cap, or a
# preflight that failed — starts no axis either (two billable agents for a
# verdict nobody reads); only the capped/labelled hand-off runs without
# them, since `diff-size` is skipped there. After `dismiss-stale-approval`
# (as `approve-only` is): both withdraw approvals and write the card, and
# unordered they race. `!cancelled()` because those jobs can be skipped.
name: Axes alongside the panel (start)
needs: [gate, round-cap, diff-size, preflight, dismiss-stale-approval]
if: >-
${{ !cancelled() && inputs.axes_alongside_panel && github.event_name == 'pull_request_target' &&
inputs.defer_approval &&
needs.gate.outputs.should_run == 'true' && needs.gate.outputs.already_reviewed != 'true' &&
needs.round-cap.result == 'success' && inputs.approve_max_severity != '' &&
needs.gate.outputs.approve_author_ok != 'false' &&
needs.dismiss-stale-approval.result != 'failure' && needs.dismiss-stale-approval.result != 'cancelled' &&
(needs.round-cap.outputs.capped == 'true' || needs.round-cap.outputs.labelled == 'true' ||
(needs.diff-size.outputs.within_cap == 'true' && needs.preflight.result == 'success')) }}
permissions:
contents: read
uses: ./.github/workflows/cursor-approve.yml
with:
workflows_ref: ${{ inputs.workflows_ref }}
phase: start
approver_environment: ${{ inputs.approver_environment }}
commit_sha: ${{ github.event.pull_request.head.sha }}
axes: ${{ inputs.axes }}
round: ${{ (needs.round-cap.outputs.capped == 'true' && needs.round-cap.outputs.rounds) || needs.round-cap.outputs.next_round }}
max_rounds: ${{ needs.round-cap.outputs.max_rounds }}
approve_gate: ${{ (needs.round-cap.outputs.capped == 'true' || needs.round-cap.outputs.labelled == 'true') && 'capped' || 'pending' }}
prior_rounds: ${{ inputs.axis_prior_rounds }}
secrets:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
axis-correctness:
# The gating axes, beside the panel on the same head. `!cancelled()` plus
# an explicit `result == 'success'`: a start phase that failed to withdraw
# an approval skips the axes, which the caller's decide reads as "no
# result". Deliberately NOT in `panel-integrity`'s or `blocking-gate`'s
# `needs:`. Secrets are passed explicitly, never inherited. The axis list
# is the start phase's `axes` output: `axes` normalized (whitespace and
# case) and validated there, which fails the start on anything but a
# non-empty subset of correctness,conformance — an axis no job here runs
# would otherwise sit pending on the card with nothing to judge it.
name: Axes alongside the panel (correctness)
needs: [round-cap, approve-start-early]
if: >-
${{ !cancelled() && inputs.axes_alongside_panel && needs.approve-start-early.result == 'success' &&
needs.round-cap.outputs.capped != 'true' && needs.round-cap.outputs.labelled != 'true' &&
contains(format(',{0},', needs.approve-start-early.outputs.axes), ',correctness,') }}
permissions:
contents: read
uses: ./.github/workflows/axis-correctness.yml
with:
commit_sha: ${{ github.event.pull_request.head.sha }}
prior_rounds: ${{ inputs.axis_prior_rounds }}
axis_direct_model: ${{ inputs.axis_direct_model }}
secrets:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
axis-conformance:
# As `axis-correctness`.
name: Axes alongside the panel (conformance)
needs: [round-cap, approve-start-early]
if: >-
${{ !cancelled() && inputs.axes_alongside_panel && needs.approve-start-early.result == 'success' &&
needs.round-cap.outputs.capped != 'true' && needs.round-cap.outputs.labelled != 'true' &&
contains(format(',{0},', needs.approve-start-early.outputs.axes), ',conformance,') }}
permissions:
contents: read
uses: ./.github/workflows/axis-conformance.yml
with:
commit_sha: ${{ github.event.pull_request.head.sha }}
prior_rounds: ${{ inputs.axis_prior_rounds }}
axis_direct_model: ${{ inputs.axis_direct_model }}
secrets:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
axes-closeout:
# The early start card says every axis is pending. On `pass` the caller's
# decide rewrites it with the verdicts; on any other outcome nothing is
# sure to (the caller's start and decide run only on `pass`/`capped`, and
# this run's decide writes its round card only on the paths it decides),
# so this rewrites it to "No decision this round" — only a `pass` card for
# this commit and round with an axis still pending (`card.py closeout`).
# It also rewrites it on `pass` when an axis job this run started did not
# succeed (`axes_ok` false): the caller's decide is documented to skip
# then, because artifact names are run-global and a panel cell running
# beside the axes can claim `axis-<name>` first — the genuine upload then
# fails, and a decide that read the artifact by name would read the forgery.
# `!cancelled()`, not `always()`: a failed panel is the case, but a run a
# newer one superseded must not touch the card that newer run now owns
# (`closeout` also leaves a card another run's link is on alone). The gate
# is the workflow-level `approve_gate` output, computed from `needs` (a
# test pins the two equal). `!= 'skipped'`: the start phase writes its card
# even when its withdrawal failed. Checks out only this repo's assets;
# writes as APPROVER_TOKEN, so GITHUB_TOKEN needs nothing past `contents: read`.
name: Axes alongside the panel (close-out)
needs: [gate, round-cap, approve-start-early, axis-correctness, axis-conformance, post-review, approve-only]
if: >-
${{ !cancelled() && inputs.axes_alongside_panel && needs.approve-start-early.result != 'skipped' &&
needs.round-cap.outputs.capped != 'true' && needs.round-cap.outputs.labelled != 'true' }}
environment: ${{ github.event_name == 'pull_request_target' && inputs.approver_environment || '' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Require a pinned workflows_ref
# workflows_ref has no default on purpose. GitHub does NOT enforce
# `required: true` for workflow_call inputs, so an omitted input arrives
# as '' and actions/checkout would silently fall back to this repo's
# default branch — running MUTABLE scripts under a pin that claims
# otherwise. Fail fast instead. (BE-5546)
env:
WORKFLOWS_REF: ${{ inputs.workflows_ref }}
WORKFLOW_SHA: ${{ job.workflow_sha }}
run: |
# actions/checkout reads `ref` through core.getInput, which TRIMS, so a
# whitespace-only value is an empty ref to IT while sailing past a bare
# -z test here. Compare the stripped form, and echo only that: dropping
# newlines also stops a multi-line value from smuggling a ::workflow
# command:: into the log, and from satisfying the line-oriented grep
# below on one 40-hex line among many.
REF="$(printf '%s' "$WORKFLOWS_REF" | tr -d '[:space:]')"
if [ -z "$REF" ]; then
echo "::error::workflows_ref is required; pin it to the same commit SHA as the uses: line (see header example)"
exit 1
fi
if ! printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::warning::workflows_ref '$REF' is not a full 40-hex commit SHA — branch and tag refs are mutable and can skew between jobs mid-run"
fi
# Equality with the commit the caller's `uses:` line resolved to — the
# same guard public-repo-hygiene.yml runs, and the check that turns
# "workflows_ref must be the same SHA as uses:" from a header comment
# into a fact. `job.workflow_sha` is computed by the RUNNER from the
# `uses:` pin, so a caller cannot set it. Without this, a caller can
# pin `uses:` to one commit and load this workflow's prompts, scripts
# and model list from another. (`job.workflow_sha`, NOT
# `github.job_workflow_sha` — that one is an OIDC token claim, absent
# from the `github` context, and expands to ''.) Both sides are
# lower-cased: hex is case-insensitive, and unlike hygiene's the
# 40-hex test above only WARNS, so an upper-case ref naming the RIGHT
# commit reaches here and must not fail. $REF itself is left alone so
# the messages quote what the caller wrote. (BE-15927)
REF_LC="$(printf '%s' "$REF" | tr 'A-Z' 'a-z')"
SHA="$(printf '%s' "$WORKFLOW_SHA" | tr -d '[:space:]' | tr 'A-Z' 'a-z')"
if [ -z "$SHA" ]; then
# Cannot check, NOT a mismatch. `job.workflow_sha` is the `job`-context
# accessor added in Actions runner v2.334.0, so only an older runner
# gets here. GitHub stops queueing jobs to a self-hosted runner more
# than 30 days behind the latest release, so on any pool — hosted
# `ubuntu-latest`, or the caller's `runs_on` pool the read-only
# model jobs may use — that is a transient window. Warn and continue: a
# property nothing could EVALUATE is not evidence of a violation, and
# failing would take the whole review down on a caller that changed
# nothing. (public-repo-hygiene.yml fails closed in this branch on
# purpose — it is the checker whose own integrity rests on the
# equality. Here the ledger's warn-and-degrade posture is the fit.)
echo "::warning::job.workflow_sha is empty (Actions runner older than v2.334.0?), so workflows_ref could not be cross-checked against the uses: pin. The empty and 40-hex tests above still apply."
elif [ "$REF_LC" != "$SHA" ]; then
echo "::error::workflows_ref ($REF) is not the commit this workflow was called at ($SHA). The uses: pin and workflows_ref MUST name the same commit — otherwise the workflow is pinned but its prompts and scripts are loaded from a different version. Set both to $SHA. (The bump-callers fleet rewrites both together; Dependabot rewrites only uses:, so a caller that lets Dependabot bump this reusable needs a dependabot.yml ignore entry for Comfy-Org/github-workflows.)"
exit 1
fi
- name: Load cursor-review assets
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: Comfy-Org/github-workflows
ref: ${{ inputs.workflows_ref }}
path: _cursor_review_assets
persist-credentials: false
- name: Close out the early card
env:
APPROVER_TOKEN: ${{ secrets.APPROVER_TOKEN }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
COMMIT_SHA: ${{ github.event.pull_request.head.sha }}
ROUND: ${{ needs.round-cap.outputs.next_round }}
MAX_ROUNDS: ${{ needs.round-cap.outputs.max_rounds }}
APPROVE_GATE: ${{ (needs.round-cap.outputs.capped == 'true' || needs.round-cap.outputs.labelled == 'true') && 'capped' || (inputs.approve_max_severity == '' || needs.gate.outputs.approve_author_ok == 'false') && 'off' || needs.approve-only.outputs.go == 'true' && 'pass' || needs.post-review.outputs.approve_gate || 'untrusted' }}
AXES_OK: ${{ contains(fromJSON('["success","skipped"]'), needs.axis-correctness.result) && contains(fromJSON('["success","skipped"]'), needs.axis-conformance.result) }}
AXIS_RESULTS: correctness ${{ needs.axis-correctness.result }}, conformance ${{ needs.axis-conformance.result }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
if [ -z "$APPROVER_TOKEN" ]; then
echo "APPROVER_TOKEN is empty: the start phase wrote no card, so there is none to close out."
exit 0
fi
export GH_TOKEN="$APPROVER_TOKEN"
# Captured, not inlined: a token that cannot read GET /user must not
# pass an empty login, which matches no card.
LOGIN="$(gh api user --jq .login)"
if [ -z "$LOGIN" ]; then
echo "::error::could not resolve the APPROVER_TOKEN identity (GET /user returned no login)"; exit 1
fi
python3 "$CURSOR_REVIEW_ASSETS/../cursor-approve/card.py" closeout --repo "$REPO" \
--pr-number "$PR_NUMBER" --login "$LOGIN" --commit-sha "$COMMIT_SHA" --round "$ROUND" \
--max-rounds "$MAX_ROUNDS" --approve-gate "$APPROVE_GATE" --review-label "$REVIEW_LABEL" \
--run-url "$RUN_URL" --axes-ok "$AXES_OK" --axis-results "$AXIS_RESULTS"