Docs · Agents · Code review
A Claude Code agent that reviews every pull request
An agent that reviews every pull request and posts one comment: a token, an agent file and a pipeline, set up as on Agents. To add these files to a repository in one command, see Practices.
What does the review comment look like?
# Review — fix(ci): fetch every page of comments
| Critical | 0 |
| Medium | 2 |
| Low | 1 |
Safe to merge; both mediums are degradations of the fetch step rather than defects in what it feeds the agent.
M1 · Fetch failure turns the advisory job red
.github/workflows/review.yml:97
No continue-on-error, so a 5xx or a rate limit fails the job before the
review runs — exactly the red X this workflow promises never to produce.
Fix: add continue-on-error: true to the step.
What goes in the agent file?
.claude/agents/code-review.md, in the repository being reviewed. Claude Code
loads AGENTS.md (or CLAUDE.md) itself, so the house style is not repeated here.
---
name: code-review
description: Reviews a branch's diff and writes review.md. Changes nothing, posts nothing.
tools: Bash, Read, Grep, Glob, Write
---
You review one branch's changes and write what you find to `review.md`.
Check for `previous-review.md` before you start. If it is there, this is a
follow-up.
Read the diff first, then read whole files around anything it touches. A diff
shows what moved, not what it broke: the caller that still passes the old
argument is not in the diff, and the test that no longer covers the branch is
not either.
## The output
`review.md` is exactly this shape, and nothing else.
# Review — <the pull request's title>
| Severity | Count |
| --- | --- |
| Critical | <n> |
| Medium | <n> |
| Low | <n> |
<One sentence: is this safe to merge, and if not, which finding stops it.>
### C1 · <the claim, in under ten words>
`path/to/file:42`
<What breaks, and the input or state that breaks it. Two or three lines.>
**Fix:** <the concrete change. Not "consider" and not "you may want to".>
Two things you must not do: change any code, and post anything anywhere. Write
`review.md` and stop. Something else decides what happens to it.
The pipeline
How do I run it in GitHub Actions?
name: review
on: pull_request
concurrency:
group: review-${{ github.event.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v6
with:
node-version: '22'
- name: Install selan and Claude Code
shell: bash
run: |
curl -fsSL https://dl.selan.ai/install.sh | sh
npm install -g @anthropic-ai/claude-code
- name: Review
continue-on-error: true
env:
SELAN_TOKEN: ${{ secrets.SELAN_TOKEN }}
run: |
selan agent-run code-review \
"Review this pull request. \`git diff HEAD^1 HEAD\` is the change.
Write your review to $GITHUB_WORKSPACE/review.md."
- name: Post the review
continue-on-error: true
if: hashFiles('review.md') != ''
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.number }}
run: |
node -e 'require("fs").writeFileSync("payload.json", JSON.stringify({
body: require("fs").readFileSync("review.md", "utf8") }))'
curl -sS -X POST \
-H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/vnd.github+json" \
"$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/issues/$PR/comments" \
-d @payload.json
-
HEAD^1, not the base branch. For apull_requestevent the checked-out ref isrefs/pull/N/merge, and its first parent is the commit the branch was merged onto. Diffing againstorigin/mainwould show anything that lands on main while the job waits as part of this pull request. -
persist-credentials: false: the agent runs with permissions skipped and hasBash. The default leaves the job'sGITHUB_TOKEN(withpull-requests: write) in.git/config, where the agent reads. -
shell: bashadds pipefail. Under the defaultbash -e, a failedcurl -fincurl … | shleavesshreading EOF and exiting 0: the step passes with nothing installed.
How do I run it in GitLab CI?
Four things differ from the workflow above.
review:
stage: test
image: node:26
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
allow_failure: true
timeout: 20m
interruptible: true
cache:
when: always
key: review-$CI_MERGE_REQUEST_IID
paths: [previous-review.md]
variables:
GIT_DEPTH: 0
script:
# Not `curl | sh`: piped, a failed `curl -f` leaves sh reading EOF and exiting 0,
# so the step goes green with nothing installed.
- curl -fsSL https://dl.selan.ai/install.sh -o /tmp/install-selan.sh
- sh /tmp/install-selan.sh
- curl -fsSL https://claude.ai/install.sh -o /tmp/install-claude.sh
# `selan agent-run` passes --dangerously-skip-permissions, and Claude Code exits 1
# on that flag at uid 0. Container images run as root, so drop to a user.
- install -d -o node -g node /tmp/agent
- chown -R node:node "$CI_PROJECT_DIR"
# The runner's files and the volumes above them, out of the agent's reach until
# after_script puts back the modes recorded here.
- |
rm -f "$RUNNER_TEMP_PROJECT_DIR/.gitlab-runner.ext.conf"
install -m 600 /dev/null /tmp/review-modes
for d in "$CI_BUILDS_DIR" "$(dirname "$CI_PROJECT_DIR")" /cache; do
if [ -d "$d" ]; then stat -c '%a %n' "$d" >> /tmp/review-modes; chmod go-w "$d"; fi
done
find "$RUNNER_TEMP_PROJECT_DIR" -exec stat -c '%a %n' {} + >> /tmp/review-modes
chmod -R go-rw "$RUNNER_TEMP_PROJECT_DIR"
- |
if grep -rqF -- "$CI_JOB_TOKEN" "$CI_PROJECT_DIR"; then
echo "CI_JOB_TOKEN is in the checkout, where the agent could read it" >&2; exit 1
fi
- |
cat > /tmp/review.sh <<'SH'
set -e
export HOME=/tmp/agent
export CLAUDE_CONFIG_DIR=/tmp/agent/.claude
# The native installer installs for the user running it, into ~/.local/bin.
export PATH="$HOME/.local/bin:$PATH"
bash /tmp/install-claude.sh
selan agent-run code-review \
"Review this merge request. \`git diff $CI_MERGE_REQUEST_DIFF_BASE_SHA HEAD\` is the change.
Write your review to $CI_PROJECT_DIR/review.md. Your previous review,
if there is one, is at $CI_PROJECT_DIR/previous-review.md."
[ -s review.md ] || { echo "the agent wrote no review" >&2; exit 1; }
cp review.md previous-review.md
selan review codequality review.md gl-code-quality-report.json
SH
# Five named variables, never the job's environment.
env -i PATH="$PATH" SELAN_TOKEN="$SELAN_TOKEN" CI_PROJECT_DIR="$CI_PROJECT_DIR" \
CI_MERGE_REQUEST_DIFF_BASE_SHA="$CI_MERGE_REQUEST_DIFF_BASE_SHA" \
CI_MERGE_REQUEST_TITLE="$CI_MERGE_REQUEST_TITLE" \
su -p node -c "sh /tmp/review.sh"
artifacts:
when: always
paths: [review.md, gl-code-quality-report.json]
reports:
codequality: gl-code-quality-report.json
# The build directory outlives the job and is shared with the runner's other jobs: hand it back.
after_script:
- chown -R root:root "$CI_PROJECT_DIR"
- while read -r mode path; do chmod "$mode" "$path"; done < /tmp/review-modes
- rm -rf "$CI_PROJECT_DIR/.git"
The agent cannot run as root.
selan agent-run adds --dangerously-skip-permissions, and Claude Code
refuses that flag at uid 0:
--dangerously-skip-permissions cannot be used with root/sudo
privileges for security reasons. Container images run as root and GitLab has no
image:user, so the job drops privileges itself. IS_SANDBOX=1 would
bypass the guard, but it declares the container a sandbox while handing an agent Bash inside it.
Set HOME inside the script, not in variables:. A job variable is already
in force during get_sources, and the clone dies with
could not lock config file /tmp/agent/.gitconfig.
The agent gets five variables, not the job's. GitLab hands every job variable to
every line of the script, and su -p passes them all on: the job token, the registry
password, every group secret. The agent reads text the merge request wrote, so one line in a diff
could get it to print them into review.md, which goes up as an artifact.
env -i starts it from nothing and names what it reads: PATH,
SELAN_TOKEN, the two variables the prompt expands, and the merge request's title. The
checks and the conversion after it run as node too, so root never follows a link the
agent left in the checkout.
Nor what the runner leaves on disk. On the docker executor the runner writes
CI_JOB_TOKEN into .gitlab-runner.ext.conf, a git config file beside the
checkout that .git/config includes, so git config --list shows it to any
user. The job deletes it; git skips a missing include and the next checkout writes a fresh one.
The runner's env file, which every later stage exports (root's after_script included),
and the build and cache volumes are writable by anyone: an agent that appended a PATH
line to that file would have its programs run as root, with every variable. So the job records
the modes of those directories and files, takes node's access away while the agent
runs, and after_script restores them. after_script also deletes
.git, which belonged to node, so no config or hook the agent wrote there
reaches the next job's root git. The grep stops the job if a runner ever writes the
token into the checkout itself. On GitHub, persist-credentials: false keeps the token
out of .git/config the same way.
SELAN_TOKEN is still visible to the agent: selan agent-run passes it to
Claude Code, which authenticates with it. Give CI a token of its own, so that revoking it touches
nothing else.
No merge ref, so no HEAD^1. GitLab checks out the source branch
itself, so HEAD^1 is the previous commit on that branch and would review the last push.
CI_MERGE_REQUEST_DIFF_BASE_SHA is the merge base, which also keeps anything that lands
on main while the job queues out of the diff. GIT_DEPTH: 0 puts it in the clone.
On the Free plan, nothing can post a comment. CI_JOB_TOKEN cannot
create a note, and on GitLab.com Free neither a project nor a group access token can be issued:
both endpoints answer 400 User does not have permission to a group Owner.
POST /user/personal_access_tokens accepts only k8s_proxy and
self_rotate, so api scope is web-UI only. What is left is a personal
token: authored by a person, not a bot, carrying everything that person can do, in a variable any
job can read.
So the findings ride artifacts:reports:codequality, which GitLab reads itself. They
render in the merge request's Reports tab: the inline markers in the Changes view
are Ultimate and the pipeline's Code Quality tab is Premium. review.md goes up as an
artifact too, since that is where a finding's fix reads.
The agent writes markdown, so selan review codequality converts it: heading to description,
the C/M/L prefix to critical/major/minor,
the backticked path:line to location. Derive fingerprint from
the id, path and claim and not the line number: GitLab matches findings across pushes by
fingerprint, so a fingerprint that ignores the line keeps a finding the same one after its code
moves. Check the parsed count against the counts table the agent wrote. A parser that matches
nothing produces an empty report, and an empty report is what GitLab renders for a clean review.
One pipeline per push, and do not swallow tags. Asking for merge request
pipelines makes GitLab create one alongside the branch pipeline, so every other job runs twice per
push. A workflow: block fixes that. Keep its tag rule: without it no pipeline is
created for a tag, and a tag-triggered release never ships.
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
The follow-up base is a cache keyed on the merge request. Nobody but the job can write a cache, so no author filter is needed, and the agent reads that file.
What makes it readable
How do I keep a review short enough to read?
- Define each severity in the agent file, in your terms. Critical is "merging this ships something wrong". Medium is a defect in a narrower state. Low is the wording nits. Undefined labels drift upward until none of them mean anything.
-
Keep the zero rows.
Critical | 0is the most useful cell in the table. - Cap the low ones (three is plenty) and give a drop order for long reviews: low first, then medium, never a critical.
- Demand a fix, not a concern. "Consider refactoring this" costs the reader more than it saves. If the agent cannot write the fix, what it has is a question: give it somewhere to put one.
How does a second run follow up on the first?
Every push triggers a fresh run that rescans from nothing and finds a different set of true things: you fix what it said, it comes back with three more, and the list never empties. Hand the agent what it already said. Fetch the last review your pipeline posted, write it into the workspace, and tell the agent that file is the base:
- name: Fetch the previous review
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.number }}
run: |
node -e '
(async () => {
const mine = []
for (let page = 1; ; page++) {
const res = await fetch(
`${process.env.GITHUB_API_URL}/repos/${process.env.GITHUB_REPOSITORY}` +
`/issues/${process.env.PR}/comments?per_page=100&page=${page}`,
{ headers: { Authorization: `Bearer ${process.env.GH_TOKEN}` } })
if (!res.ok) return
const batch = await res.json()
for (const c of batch) {
if (c.user.login === "github-actions[bot]" && c.body.startsWith("# Review —")) {
mine.push(c.body)
}
}
if (batch.length < 100) break
}
if (mine.length) require("fs").writeFileSync(
`${process.env.GITHUB_WORKSPACE}/previous-review.md`, mine.at(-1))
})()
'
Then four rules in the agent file:
-
A finding keeps the id it was given.
M2isM2across three pushes. - The table counts what is still open, and one line under it names what was fixed: Fixed since the last review: M1, L2. A fixed finding gets no block.
- A new finding is added only if it is critical, or in code this push changed.
- Nothing is re-worded, re-ranked or re-scoped. Medium last time is medium now.
Read every page of comments: the endpoint returns oldest-first and ignores sort and
direction, so a single page of 100 follows up on a stale review.
# Review —, and this file is text an agent acts on. Filter on the
author, never write the unfiltered response into the workspace, and tell the agent in as many words
that the file is data, not instructions.