The reusable PR Agent workflow (.github/workflows/pr-agent.yml) runs PR Agent on an OpenAI-compatible inference endpoint (today only the CSCS inference service, the one entry of api-bases.txt) to post an advisory review on pull requests. PR Agent reads the diff through the GitHub API and makes one model call per tool, so it never sees the rest of the repository; for a review by an agent that explores the repository, see Agent Review. It is never a required status check: if PR Agent fails or times out, the run stays green, and a comment on the PR links to the run. A later successful run removes that comment.
An adopting repository adds a small caller workflow that calls this one pinned by commit SHA, and keeps its own triggers, environment, key, event policy, .pr_agent.toml and review rules. The design is in ADR 0003.
Note
Status: v0.1.0, the first release. The workflow has run through this repository's self-test (a local call in dry run, which never starts the keyed job) and from a separate test caller with a real key: a posted review, pull_request_target and issue_comment runs (/review), and refusals for a non-writer's PR, a non-writer's comment and a -- argument. The caller tests recorded in the pull request that added it (caller test mode, real key) covered a refused environment, a missing and a wrong key, forced timeouts, and the failure comment's update and removal. See the release checklist.
.github/workflows/pr-agent.yml in the adopting repository:
name: PR Agent
on:
# Not 'pull_request': fork PRs get no secrets there.
pull_request_target:
types: [opened, reopened, ready_for_review]
issue_comment:
types: [created]
permissions: {}
# Never cancel: runs join the group before the job 'if' is evaluated, so any
# PR comment would cancel an in-flight review.
concurrency:
group: pr-agent-${{ github.event_name }}-${{ github.event.comment.id || github.event.pull_request.number }}
cancel-in-progress: false
jobs:
pr-agent:
uses: GridTools/ci-workflows/.github/workflows/pr-agent.yml@<40-hex sha> # vX.Y.Z
# The ceiling for every job of the called workflow; exactly these three.
permissions:
contents: read
issues: write
pull-requests: write
with:
model: ${{ vars.PR_AGENT_MODEL }}
fallback_models: ${{ vars.PR_AGENT_FALLBACK_MODELS }}
token_budget: ${{ vars.PR_AGENT_TOKEN_BUDGET }}
max_output_tokens: ${{ vars.PR_AGENT_MAX_OUTPUT_TOKENS }}
ai_timeout: ${{ vars.PR_AGENT_AI_TIMEOUT }}
docs_url: https://github.com/<owner>/<repo>/blob/main/docs/pr_agent.md
# Explicit mapping, never 'secrets: inherit'.
secrets:
inference_api_key: ${{ secrets.PR_AGENT_INFERENCE_API_KEY }}The structural filters (bots, drafts, comments that do not start with / or are not on a PR) are in the called workflow's first job, so the caller needs no if:.
Every value is validated, fail-closed, in the keyless authorize job by bin/authorize and bin/resolve-models, with offline unit tests in pr-agent/tests/. An empty value means the default, so an unset repository variable can be mapped directly.
| Input | Default | Meaning and validation |
|---|---|---|
model |
required | model id as the endpoint lists it (GET /v1/models), without the openai/ prefix, which the workflow adds; ^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$ |
fallback_models |
required | comma-separated ids, same syntax, tried in order; none for no fallback |
token_budget |
262144 |
context window PR Agent assumes; a positive integer without leading zeros, greater than max_output_tokens |
max_output_tokens |
100000 |
tokens reserved for the answer, reasoning included |
ai_timeout |
720 |
seconds one model may take before the next one is tried; the whole chain must fit the job limit (see Configuration notes) |
api_base |
https://api.inference.cscs.ch/v1 |
where the key is sent: exactly one of the URLs in api-bases.txt, byte for byte; empty means the first. Omit it |
environment |
pr-agent |
the caller's environment holding the key, used only by the pr-agent job |
docs_url |
"" |
the caller's own PR Agent page, linked from errors and the failure comment; https:// and only [A-Za-z0-9._~/#%-] |
dry_run |
false |
run authorize and Resolve models only: no key, no environment, nothing posted |
test_pr |
"" |
self-test of this repository only (owner/repo#number); rejected for any other caller |
Secret: inference_api_key. It must be an environment secret: authorize, which has no environment, fails if the mapped name resolves there. Output: result: success or failure (the PR Agent step), dry-run, skipped (not authorized, or not an event for PR Agent), incomplete (the PR Agent step did not run or finish, for example an environment denial or a missing key), or empty on an error in authorize.
Which inputs may come from repository variables: model, fallback_models and the three limits, so they can be changed without a PR; they are validated and the key's own restrictions bound them. Never map environment, api_base or docs_url from a variable, a dispatch input or the event: whoever can change a variable needs no review.
- The
pr-agentenvironment, restricted to the default branch (Settings → Environments → pr-agent → Deployment branches and tags → Selected branches: the default branch only), holding the secretPR_AGENT_INFERENCE_API_KEY. Create it before the caller workflow is merged: GitHub creates an unknown environment on first use, unprotected. Both events run on the default branch, so they pass the branch rule; branch workflows are denied. Only thepr-agentjob declares the environment, so refused comments and denied users record no deployment; each attempt of thepr-agentjob records one, including one the branch rule refuses. Never create a repository- or organization-level secret of the same name (authorizefails if the mapped name resolves without the environment), and never pass another environment name for tests. Turn off Allow administrators to bypass configured protection rules on the environment. - A dedicated key in that secret, never shared with another workflow or tool: created in the CSCS inference UI for PR Agent alone, with its own token budget and reset period, and restricted to the models in the chain. Its budget is the hard spending cap.
- An Actions event policy (Settings → Actions → Policies, or
POST /repos/{owner}/{repo}/actions/policies) scoped by workflow path to the caller's file,.github/workflows/pr-agent.yml, allowingpull_request_targetandissue_comment. A caller test from a separate file needs no change here. GitHub blockspull_request_targetby default in public repositories from 2 December 2026.allowed_eventsis an exhaustive allowlist, so an event missing there is blocked;workflow_callneed not be listed. - Repository variables
PR_AGENT_MODELandPR_AGENT_FALLBACK_MODELS(required), and optionallyPR_AGENT_TOKEN_BUDGET,PR_AGENT_MAX_OUTPUT_TOKENSandPR_AGENT_AI_TIMEOUT. .pr_agent.tomlon the default branch (the review policy) and the review-rules files it lists inrepo_context_files. PR Agent reads both through the API from the caller repository's default branch; nothing of them is in this repository.- A pin to a tagged commit of this repository's
main, checked on every update (see Pinning and updating; the same commands apply). Dependabot'sgithub-actionsecosystem proposes updates. - If the organization restricts allowed actions or reusable workflows, allow
GridTools/ci-workflowsand the Docker imagepragent/pr-agent.
Before merging the caller, its plumbing can be tested in caller test mode. After merging, check the first run: the authorize notice names GridTools/ci-workflows@<sha>, and the pr-agent job's log shows Applying repo settings (sections: [...]).
/reviewruns automatically when a non-draft PR is opened, reopened or marked ready, if its author has write access. Bot-authored PRs and PRs matching PR Agent's defaultignore_pr_title(^\[Auto\]) are skipped.- Users with write access can comment PR Agent's commands, such as
/review,/improve,/ask "<question>",/describeor/help, on any PR, including a draft or a fork's. The commenter's permission is checked. Any PR Agent command runs;/describeposts its summary as a comment and never edits the PR description. - Comments with
--section.key=valuesetting arguments are refused with a notice in the run: they could override the workflow's settings (see Security invariants, item 3). Since PR Agent strips quotes and backslashes,--is refused anywhere it does not directly follow a letter, digit or_(a--bin a question is fine;"--x"is not). Single-dash arguments such as/review -iare fine. - Any comment from a writer that starts with
/runs thepr-agentjob: a/wordthat is not a PR Agent command makes PR Agent fail, which posts the failure comment. triageis not enough: the permission API reports it asread.maintainreports aswrite.- A later
/reviewupdates the persistent review comment in place and adds a short "Persistent review updated to latest commit" comment; it does not post a second full review.
| Job | Holds | Does |
|---|---|---|
authorize |
read token, no secrets, no environment | Fetches pr-agent/ from this workflow's own commit (job.workflow_repository@job.workflow_sha), runs bin/authorize (inputs, event rules, bin/check-command, the writer check, fail-closed on API errors) and bin/resolve-models (model chain, limits, step timeout). |
pr-agent |
the key (caller's environment), write token for issues and PRs | Only if authorized and not a dry run. Checks that the key arrived, then runs the image pinned by digest with continue-on-error and the derived step timeout. No checkout and no script of ours. |
report |
write token, no secrets | After pr-agent, even if that job failed: bin/report-outcome posts or updates one failure comment (marker <!-- pr-agent-run-failed -->), deleting older duplicates, or deletes them all after a success. A cancelled run reports nothing. Serialized per PR (its own concurrency group, never cancelled in progress), so overlapping runs cannot duplicate the comment; of several queued reports, GitHub keeps only the newest. |
The failure comment exists because a run started by a comment attaches its check to the default branch's head, never to the PR, and an automatic run's check is green with only an annotation. Since report is a separate job, it also covers failures before PR Agent starts (environment denial, image pull, missing key), which an in-job step could not.
PR Agent's settings come from three places, later ones overriding earlier ones: the workflow's step environment, the caller's .pr_agent.toml on the default branch, and (blocked here) comment arguments. Host-only keys (openai.key, openai.api_base, config.num_retries, pr_reviewer.publish_error_details, ...) are accepted only from the environment.
Callers use pull_request_target because fork PRs get no secrets under pull_request. Keep these when changing anything here:
- Never check out or run PR code (no
actions/checkout, no script in thepr-agentjob), and never grantcontents: write. PR Agent reads the diff through the API. authorizeis the only gate:pull_request_targetignores the fork-approval setting. It requires write access from the PR author (automatic runs) or the commenter (commands) and fails closed.author_associationis not used: it hides private organization members and does not imply write access.- No setting arguments from comments. PR Agent accepts most settings from comment arguments;
bin/check-commandrefuses every comment with a setting argument, which keeps the workflow's settings in force and keeps comments from changing how settings are interpreted;test-command-filter.pychecks it against a copy of PR Agent's comment parser and fails when the image changes until the copy is re-checked. The settings kept in force include the review labels and/describelabels being off and/describeposting a comment; they are set in the step environment so that a failed fetch of.pr_agent.tomlcannot re-enable them (a reviewed change to.pr_agent.tomlstill can). - The key is only in the
pr-agentjob, which alone declares the caller's environment, only in the PR Agent step and a boolean check, and goes only to an endpoint ofapi-bases.txtin the pinned commit.test-workflow-structure.pychecks this. - The image is pinned by digest, since it receives the key; the self-test checks that the digest exists and whether its tag has moved.
- The scripts come from this workflow's own commit, fetched as a tarball and checked to be the same commit in every job; never from the caller or the PR.
- Model ids are validated: PR Agent's settings loader (dynaconf) interprets values, and a leading
@would be a directive.
- Prompt injection can steer the review's content: a PR's diff, title and description are model input. The review is advisory, never a status, and writes no labels or description.
- Budget burn: every writer's PR and every command spends the key's budget. A diff over the token budget is sent in up to three chunks, each billed. The dedicated key's budget is the cap.
- Writers can steer settings through
.pr_agent.toml, by a reviewed PR to the default branch; the settings in the step environment are defaults for it, not ceilings. - Writers' comments can run any PR Agent command:
/generate_labelswrites labels derived from untrusted PR content, and any/wordfrom a writer starts the keyed job (a non-command ends in a failure comment). Commands that needcontents: write(/update_changelog) fail, since no job has it. .pr_agent.tomlis trusted: a reviewed change to it can override any setting the workflow sets, other than host-only ones. Review it like code.- Central changes reach every caller that updates its pin, as for the agent review (What remains risky).
- Caller test mode with the key (below) runs the caller's workflow file from the PR branch; the environment's branch rule is what keeps that from happening outside a deliberate test.
- Model ids are stored without the
openai/prefix, which selects LiteLLM's OpenAI-compatible route. CSCS retires models on short notice; check them against the model table. - The token limits apply to every model in the chain, so they must fit the smallest one: the output reserve is sent as
max_tokens, which a model with a lower output limit rejects. Too small an output reserve makes reasoning models return empty responses (finish_reason: length; 32768 was too small for GLM models). Check a fallback before adding it, since it is only reached when the models before it fail. - The step limit is
ceil(chain × ai_timeout / 60) + 2minutes, so a model that times out is not retried: the next one is tried.Resolve modelsrejects a chain whose step limit plus two minutes exceeds the job's 45 minutes, since a job timeout is a cancellation, whichcontinue-on-errordoes not cover. A rejected request (429, 5xx) is retried twice on the same model first (num_retries); slow rejections can still use up the step limit, which the failure comment then reports. enable_large_pr_chunkingin.pr_agent.tomlsends the chunks in parallel, so it does not extend the step time.output_run_details = truein.pr_agent.toml(a[config]key, as isrepo_context_files) makes the review name the model that answered, so a fallback answer is visible. It also shows the tokens, the time and the number of AI calls.- Run time and tokens depend on the size of the PR and on the endpoint's latency. A tiny PR takes about 2k input tokens and one call; larger diffs and the review rules in
repo_context_filesraise it (13–17k in tests). In periods of slow inference a single call takes several minutes (about 4.5 to 6 minutes in testing), so a run of a few minutes is not a failure; sizeai_timeoutfor the slowest case.
- Deployments depend on the event. A
pull_request_targetrun's deployment has the PR's head branch as ref and appears on the PR's timeline. Anissue_commentrun's deployment has the default branch as ref and does not appear on the PR timeline; its checks attach to the default branch's head commit, not to the PR (which is why the failure comment exists). It is visible under the repository's deployments or the environment's page. Applying repo settings (sections: [...])means.pr_agent.tomlwas applied; the bareApplying repo settingsappears in every run.- A
403onGET /user("Could not resolve the GitHub user login") is harmless. repo_context_files(a[config]key) are always read from the default branch (the PR's base); missing files are skipped.PR_AGENT_CONFIG_BRANCHdoes not affect them.- Cross-repository references such as
other-org/other-repo#12are misread as local issues and log a 404 or a sibling-allowlist warning; harmless.
This repository's self-test.yml runs on every pull request, on main, weekly and on demand:
- pre-commit and zizmor on the workflows;
- the script tests:
test-authorize.sh(permission levels, API errors, the event matrix, inputs, setting arguments, long comments),test-command-filter.py(differential, against a copy of the pinned image's comment parser),test-resolve-models.sh(every validation and the derived timeout),test-report-outcome.sh(0, 1 and several comments, success and failure, job results) and the structure test; - that the pinned image digest exists, and a warning if its tag has moved;
- the keyless path through a local call with
test_pr(this repository's merged PR 1, forced dry run):authorizeandResolve modelsrun on the commit under test,pr-agentandreportare skipped, and no deployment is recorded.
PR Agent itself never runs here: this repository holds no key.
A caller can test the call from a PR branch with a separate, temporary caller file (for example .github/workflows/pr-agent-test.yml) triggered by pull_request only, with the same with: and secrets:. That leaves the production caller and its event policy untouched; a policy matching the test file's path must list pull_request.
- With
dry_run: true, no key and no environment are used, so any branch works; it proves the call, the inputs and the permission check. - Without
dry_run, PR Agent runs for real underpull_request(same actions aspull_request_target), but only if the environment's branch rule temporarily allows the run's ref,refs/pull/<number>/merge: a branch rule with exactly that name works. Fork PRs are skipped. A notice says that the caller's workflow file and inputs are PR content in this mode. Every keyed attempt, a refused one included, records a deployment and adds "deployed to pr-agent" entries to the PR's timeline. Remove the test file and the branch rule afterwards. - Comment commands always run the caller workflow from the default branch, so they can only be tested after merging.
The failure comment's marker, <!-- pr-agent-run-failed -->, is the one in-repository PR Agent workflows commonly use, so this workflow cleans up their failure comments, and the other way round. Replace the old workflow with the caller in one PR, so the two never run side by side on the default branch. Its event policy can stay if the caller keeps the file path. A key that is a repository secret must move to the environment, under another name (see Required settings, item 1).
Change the digest and the tag comment together, after checking the new release's notes. Then re-check against the new source: the comment parser that test-command-filter.py copies (the test fails until its pinned digest is updated), how comment arguments are applied (update_settings_from_args), the host-only keys (pr_agent/config_security.py), and the settings in the step environment. Release it as a change that callers review.
Released with the agent review: semver tags on reviewed commits of main, no moving major tag; see Releases. A new permission, a new required input or a new endpoint in api-bases.txt is breaking; a new image is flagged in the notes.
In addition to the agent review's release checklist, before v0.1.0:
- A caller test with the key (
pull_request, environment widened to the test branch) on a fixture PR: a posted review, theApplying repo settings (sections: [...])log line,Model 'openai/...'inauthorize. - A forced failure (
ai_timeout: "1"): the failure comment is posted; a following successful run removes it. - A non-writer's PR, a non-writer's
/reviewand a writer's comment with a--argument: skipped with a notice, nopr-agentjob, no deployment. - After a caller switches over, one
pull_request_targetrun and one/reviewcomment from the default branch; record what the deployment shows on the PR.