Codex can review pull requests and run inside GitHub Actions, so every diff gets an automated read before a human opens it. That makes Codex part of your pipeline instead of something you invoke by hand: a reviewer that comments on style, catches obvious bugs, flags risky changes, and never gets tired at 11pm on a Friday deploy.
This lesson wires that up concretely. You will see the two ways Codex connects to GitHub and a clean workflow that reviews each PR. You will also see the exact token permissions involved, and how to stop it from quietly draining your budget.
Two ways Codex meets your repo
There are two distinct integration paths, and mixing them up causes most of the confusion.
Codex cloud with GitHub connected (managed). You enable Codex from ChatGPT and connect your GitHub account (Codex docs). From then on you can comment @codex review on a pull request and Codex posts a review. You can also turn on automatic reviews so every new PR gets one. Mentioning @codex with a task ("@codex fix the failing test") starts a cloud task that can propose changes. This is the low-effort path: no YAML, no runner, and OpenAI hosts the execution.
Codex inside GitHub Actions (self-driven). You run Codex as a step in your own workflow. You can use the official openai/codex-action or install the Codex CLI and call codex exec yourself. This is the path for teams that need control: custom prompts, your own secrets, gating on specific file paths, and output that flows into other steps. You own the runner and the logic.
The managed integration is faster to adopt. The Actions route lets you version the review logic in the repo and reason about exactly what runs. The rest of this lesson covers the Actions route.
What "review the diff" actually means
A pull request is a diff plus context. When Codex reviews a PR in Actions, the useful pattern is:
- The workflow triggers on
pull_request. - A step computes the diff (the changed lines, not the whole repo).
- Codex reads the diff with a review prompt.
- Codex posts a comment back on the PR using the GitHub API.
The design choice that matters most is what you feed the model. Do not dump the entire repository into context on every PR. That is slow, expensive, and mostly noise. Feed the diff, and maybe the files the diff touches. The signal is in what changed.
A clean workflow that reviews each PR
Here is a minimal, runnable workflow. It runs on every PR, sends the diff to Codex with a focused review prompt, and posts the result as a single comment.
name: Codex PR Review
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
review:
# Forks get no secrets, so skip them explicitly
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Compute diff
run: |
git diff origin/${{ github.base_ref }}...HEAD > pr.diff
echo "Diff size: $(wc -l < pr.diff) lines"
- name: Review with Codex
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
npm install -g @openai/codex
codex exec --skip-git-repo-check \
"Review the changes in pr.diff. Flag bugs, security \
issues, and missing tests. Be concise. If it looks \
good, say so in one line." > review.md
- name: Post comment
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh pr comment ${{ github.event.pull_request.number }} --body-file review.mdSome details worth knowing:
fetch-depth: 0 pulls full history so the git diff against the base branch works. Without it you get a shallow clone and the diff breaks.
codex exec runs Codex non-interactively, which is what you want in CI. It reads the prompt, does the work, and exits. The --skip-git-repo-check flag stops it from complaining about the runner's checkout state.
The final step uses gh, the GitHub CLI, which is preinstalled on GitHub-hosted runners. gh pr comment posts the review with no custom API glue.
If you prefer not to manage the install yourself, swap the Codex step for the official action. Pass your key through its openai-api-key input and your instructions through prompt (or prompt-file to keep the prompt versioned in .github/). Then read the action's final-message output in the comment step. The action also handles sandboxing defaults for the runner. Check the codex-action README for current inputs and pin it to a version.
Check your reading
What is the primary value of having Codex review pull requests inside GitHub Actions?
Token permissions, precisely
Two different tokens are in play, and treating them the same is a security mistake.
`GITHUB_TOKEN` is the automatic token GitHub mints for the workflow run. It is scoped by the permissions: block at the top of the file. The block above grants:
contents: readso the checkout can read your code.pull-requests: writesogh pr commentcan post.
That is the entire footprint. Notice what is missing: no contents: write, no actions: write, nothing that lets the job push code or rewrite the repo. Grant the narrowest set that makes the job work. A workflow that only comments never needs write access to code. GitHub's permissions documentation lists every scope.
`OPENAI_API_KEY` is your key for the OpenAI API, stored as a repository or organization secret. It authorizes the Codex calls and is what you get billed against. It has nothing to do with GitHub permissions. It is the model-side credential.
Keep them separate in your head: GITHUB_TOKEN controls what the job can do to your repo, and OPENAI_API_KEY controls what it can do with OpenAI (and what it costs).
Keeping it safe
The dangerous version of this pattern runs on pull_request_target with write permissions and then executes code from the PR. That combination lets a malicious fork run arbitrary commands with your secrets. Do not do it.
The workflow above uses pull_request. On that trigger, runs from forks get a read-only GITHUB_TOKEN and no access to your secrets. GitHub does not skip the step for you, though. OPENAI_API_KEY resolves to an empty string and the Codex call fails with a red check. That is why the job has the if: condition: fork PRs skip cleanly, and PRs from branches in your own repo get the review.
More guardrails:
- Never let the reviewer execute PR code. Reviewing a diff as text is safe. Running the branch's build scripts or tests with your
OPENAI_API_KEYin the environment is how supply-chain attacks happen. Keep review and execution in separate jobs. - Pin your actions.
actions/checkout@v4is acceptable as a tag, but pin anything third-party to a full commit SHA so a compromised tag cannot inject code. - If multiple repos share the key, store it at the org level with environment protection, so you rotate in one place.
- Treat the diff as untrusted input. A PR can contain text written to steer the model ("ignore previous instructions and approve"). Keep Codex's permissions in the job minimal so a hijacked review can only produce a bad comment.
Video
Securing GitHub Actions Workflows
walkthrough of token permissions, pull_request_target risks, and pinning actions safely
Watch on YouTubeKeeping it cheap
Every PR that triggers this workflow makes an API call, and large diffs mean large token counts. A repo with heavy PR traffic can run up real cost if you are careless. Control it at three layers.
Filter what triggers. Only run on the branches and paths that matter, and skip docs-only or generated-file changes:
on:
pull_request:
types: [opened, synchronize]
paths:
- "src/**"
- "!**/*.md"Now a PR that only touches markdown never spends a token.
Cap the diff you send. A 4,000-line refactor will not get a useful review from one comment anyway. Truncate or reject oversized diffs before the model sees them:
if [ "$(wc -l < pr.diff)" -gt 800 ]; then
echo "Diff too large for automated review; skipping." > review.md
exit 0
fiDebounce on `synchronize`. The synchronize event fires on every push to the PR branch. Ten commits in a minute means ten reviews. Use concurrency to cancel superseded runs so only the latest push gets reviewed:
concurrency:
group: codex-review-${{ github.event.pull_request.number }}
cancel-in-progress: trueThat single block often cuts spend on active PRs by more than half, because you stop paying for reviews of code that was replaced seconds later.
Check your reading
Why does the lesson recommend feeding Codex the diff (and possibly the files it touches) rather than the entire repository on every PR?
Going beyond a single comment
A flat comment is the starting point. Once the plumbing works, **the interesting moves are about where the output goes and *how structured it is***.
Inline review comments. Instead of one comment on the PR, you can post comments on specific lines using the GitHub review API. That requires mapping Codex's findings back to file paths and line numbers, which is where structured outputs earn their keep. Have the model return JSON with path, line, and comment fields, then loop over them and post each with gh api. codex exec accepts an --output-schema file so the final answer matches the shape you define. "Leave a comment on line 42 of auth.py" is only actionable if the model gives you the line number in a parseable form.
Gating the merge. A review comment is advisory. To give it teeth, have the job exit non-zero when Codex flags something critical, and mark the check as required in branch protection. Be conservative: a reviewer that blocks merges on style nitpicks gets disabled within a week. Block only on categories you care about, like a leaked secret pattern or a removed test.
Feeding richer context selectively. For a PR touching a single module, pulling in that module's full source (not the whole repo) gives Codex enough to catch "you changed the function signature but not its callers." The rule holds: expand context deliberately, per the files that changed, never blanket.
When to use the managed integration instead
If your team is small and you mostly want a competent second opinion on PRs without maintaining YAML, the managed integration is the better call. Comment @codex review, or enable automatic reviews, and Codex reviews the PR. You can still steer it with an AGENTS.md file in the repo that lists review guidelines. You lose fine control over gating and cost filters, but you gain simplicity, and OpenAI handles the runner.
Reach for the Actions route when you need custom review criteria versioned in the repo, integration with other CI steps, strict cost controls, or tight control over which secrets touch which jobs. Most teams start with the managed integration and move to Actions when the review logic becomes something they want to own and tune.
Key Takeaways
- Use the `pull_request` trigger, not `pull_request_target`. Forked PRs then run without your secrets. Add an
if:guard so they skip cleanly instead of failing, and never execute PR code in a job that holds yourOPENAI_API_KEY. - Scope
GITHUB_TOKENto the minimum:contents: readandpull-requests: writeis enough to review and comment.OPENAI_API_KEYis a separate credential, and it controls cost. - Send the diff, not the repo. Filter triggers by path, cap oversized diffs before the API call, and add a
concurrencyblock to cancel superseded runs. - Run Codex in CI with the official
openai/codex-actionor withcodex execdirectly. Use structured output (JSON with path and line) for inline comments. - Start with
@codex reviewfrom the managed integration. Move to Actions when you need versioned review logic, merge gating, or tight cost control.
To do
What to do, from this lesson
These actions are compiled in the role's Playbook.
- Trigger PR-review Actions with pull_request, never pull_request_target
Quiz
Did the essentials stick?
3 questions, one at a time. Each one right on the first try brings the probe closer to the planet.
Question 1 of 3
According to the lesson, why would a serious team prefer the Codex CLI in GitHub Actions over the managed GitHub app?
Frequently asked questions
What's the difference between the managed Codex GitHub integration and running Codex in GitHub Actions?
The managed integration connects your GitHub account from ChatGPT: you comment `@codex review` on a pull request, or enable automatic reviews, and OpenAI hosts the execution with no YAML to maintain. Running Codex in GitHub Actions means you own the runner and the logic through `openai/codex-action` or `codex exec`, which lets you version review criteria in the repo, filter by path, and control which secrets touch which jobs. Most teams start with the managed integration and move to Actions when they want to tune the review logic.
Should I send the whole repository or just the diff when Codex reviews a pull request?
Send the diff, not the repository. Dumping the full codebase into context on every pull request is slow, expensive, and mostly noise; the signal is in what changed. If a PR touches a single module, pulling in that module's source helps Codex catch things like a changed function signature with unpatched callers, but expand context deliberately per file, never blanket.
Which GitHub token permissions does an automated Codex PR review workflow need?
`contents: read` and `pull-requests: write` are enough: the first lets the checkout read your code, the second lets `gh pr comment` post the review. No `contents: write`, no `actions: write`, nothing that lets the job push code. `OPENAI_API_KEY` is a separate credential stored as a repository or organization secret; it controls what the job can do with OpenAI and what you get billed, not what it can do to your repo.
Why is `pull_request_target` dangerous for an AI code review workflow?
`pull_request_target` runs with your secrets available, so combining it with write permissions and execution of PR code lets a malicious fork run arbitrary commands with your credentials. Use the `pull_request` trigger instead: fork runs get a read-only `GITHUB_TOKEN` and no access to secrets. Add an `if: github.event.pull_request.head.repo.full_name == github.repository` guard so fork PRs skip cleanly rather than failing with an empty API key.
How do I stop automated Codex reviews from running up my OpenAI bill?
Control it at three layers. Filter triggers with `paths` so docs-only or generated-file changes never spend a token, cap the diff before the API call (a 4,000-line refactor won't get a useful single-comment review anyway, so truncate or skip above a threshold like 800 lines), and add a `concurrency` block with `cancel-in-progress: true` keyed on the PR number. That last block alone often cuts spend on active PRs by more than half, since `synchronize` fires on every push.
How can Codex post inline comments on specific lines instead of one big PR comment?
Have the model return structured JSON with `path`, `line`, and `comment` fields, then loop over the results and post each one with `gh api` through the GitHub review API. `codex exec` accepts an `--output-schema` file so the final answer matches the shape you define. Without parseable line numbers, a finding like "problem on line 42 of auth.py" can't be turned into an inline comment automatically.