# AI code review

Two small workflow files give your repository an AI reviewer. The first reviews each pull request and posts the findings as inline comments from `codebahn-bot`. The second commits fixes for those findings when someone comments `/fix`. Both run on Codebahn's hosted runners, so nothing runs on your machine.

The agent is your choice. The examples use [Claude Code](https://code.claude.com/docs); any agent with a headless mode can take its place (see [Adjust it](#adjust-it)).

## Prerequisites

- A repository on Codebahn with CI set up ([Set up CI](/docs/set-up-ci/))
- An API key for your agent's provider. Give it a spend limit, so a busy week can't run up a surprise bill.

:::note[Where your code goes]
The review sends the pull request diff, and any files the agent reads for context, to your agent's provider under your own account and terms. That provider is not a Codebahn sub-processor; this is a choice you make for your repository. Hosted runners reach the API over HTTPS like any other download.
:::

## Add the API key

In your repository, open **Settings > Actions > Secrets** and add the key as a secret. The examples read `ANTHROPIC_API_KEY`.

That is the only credential you create. Codebahn gives every CI job a short-lived `CODEBAHN_BOT_TOKEN` for the `codebahn-bot` user, scoped to the repository and expiring when the job ends. The workflows use it to read the pull request, post the review and push fixes. See [CI tokens](/docs/ci-runners/#ci-tokens).

## Review every pull request

Create `.codebahn/workflows/ai-review.yml`:

```yaml
# Claude reviews each pull request and posts its findings as codebahn-bot.
# Comment "/review" on a pull request to run it again.

name: AI review

on:
  pull_request:            # delete to review only on "/review"
    types: [opened, synchronize, ready_for_review]
  issue_comment:
    types: [created]

env:
  MODEL: claude-haiku-5-5  # or claude-sonnet-5-5 for deeper reviews
  CODEBAHN_TOKEN: ${{ secrets.CODEBAHN_BOT_TOKEN }}

jobs:
  review:
    # Never review the bot's own pushes: that is what keeps /fix from looping.
    if: >
      github.actor != 'codebahn-bot' && (
        (github.event_name == 'pull_request' && !github.event.pull_request.draft) ||
        (github.event.issue.pull_request && startsWith(github.event.comment.body, '/review')))
    runs-on: codebahn-small
    timeout-minutes: 10
    env:
      PR: ${{ github.event.pull_request.number || github.event.issue.number }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: refs/pull/${{ env.PR }}/head
          fetch-depth: 0
          persist-credentials: false

      - name: Install tools
        run: |
          curl -fsSL https://releases.codebahn.net/cli/install.sh | INSTALL_DIR=/usr/local/bin sh
          npm install -g --silent @anthropic-ai/claude-code

      - name: Review with Claude
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          BASE=$(codebahn pr get --index "$PR" --json | jq -r .base.ref)
          git diff "origin/$BASE...HEAD" > /tmp/pr.diff
          CODEBAHN_TOKEN= claude -p --model "$MODEL" --max-turns 15 --add-dir /tmp \
            --allowedTools "Read,Grep,Glob,Write" -- "
          Review the pull request diff in /tmp/pr.diff, reading the repo for context.
          Report only bugs, crashes, security issues and wrong behaviour. No style nits.
          Write /tmp/review.json with this shape and nothing else:
          {\"body\": \"one short paragraph\",
           \"comments\": [{\"path\": \"file\", \"new_position\": <line in the new file>, \"body\": \"problem and fix\"}]}
          Comment only on lines the diff adds. Leave comments empty if nothing is wrong."

      - name: Post review
        run: |
          codebahn pr create-review --index "$PR" --state COMMENT \
            --body "$(jq -r .body /tmp/review.json)" \
            --comments "$(jq -c .comments /tmp/review.json)"
```

Open a pull request and a review from `codebahn-bot` appears within a few minutes: a summary, plus a comment on each line it has a finding for. Comment `/review` to run it again. Draft pull requests are skipped until they are marked ready.

What the file does, and why:

- **The agent never holds a Codebahn token.** The review step clears `CODEBAHN_TOKEN` before it starts the agent, and the agent's only tools are reading files and writing `/tmp/review.json`. Text in a pull request that tries to steer the model can produce a bad comment, but not a push or a merge. The [Codebahn CLI](/docs/cli/) posts the review afterwards, in a step with no model in it.
- **The review is a comment, never an approval.** It does not count toward required approvals and does not block a merge.
- **Two limits bound each run.** `timeout-minutes` caps CI time and `--max-turns` caps how many steps the agent takes.

## Fix on request

Create `.codebahn/workflows/ai-fix.yml`:

```yaml
# Comment "/fix" on a pull request and Claude commits fixes for the latest
# AI review to the pull request branch. Add a note to steer it: "/fix keep the API".

name: AI fix

on:
  issue_comment:
    types: [created]
  # pull_request_review_comment:   # uncomment to fix automatically after every AI review
  #   types: [created]

env:
  MODEL: claude-haiku-5-5
  CODEBAHN_TOKEN: ${{ secrets.CODEBAHN_BOT_TOKEN }}

jobs:
  fix:
    if: >
      (github.event.issue.pull_request && startsWith(github.event.comment.body, '/fix')) ||
      (github.event_name == 'pull_request_review_comment' && github.actor == 'codebahn-bot')
    runs-on: codebahn-small
    timeout-minutes: 10
    env:
      PR: ${{ github.event.issue.number || github.event.pull_request.number }}
      NOTE: ${{ github.event.comment.body }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: refs/pull/${{ env.PR }}/head
          persist-credentials: false

      - name: Install tools
        run: |
          curl -fsSL https://releases.codebahn.net/cli/install.sh | INSTALL_DIR=/usr/local/bin sh
          npm install -g --silent @anthropic-ai/claude-code

      - name: Fix with Claude
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          REVIEW=$(codebahn pr reviews --index "$PR" --json | jq '[.[] | select(.user.login == "codebahn-bot")] | last | .id')
          codebahn pr review-comments --index "$PR" --id "$REVIEW" --json \
            | jq '[.[] | {path, line: .position, body}]' > /tmp/findings.json
          jq -e 'length > 0' /tmp/findings.json || { echo "Nothing to fix"; exit 0; }
          printf '%s\n' "${NOTE#/fix}" > /tmp/note.txt
          CODEBAHN_TOKEN= claude -p --model "$MODEL" --max-turns 20 --add-dir /tmp \
            --allowedTools "Read,Grep,Glob,Edit,Write" -- "
          Fix each finding in /tmp/findings.json (a file, a line and the problem).
          Follow any extra instructions in /tmp/note.txt.
          Make the smallest correct change. Do not edit CI workflow files."

      - name: Push the fix as codebahn-bot
        run: |
          git add -A
          git diff --cached --quiet && { echo "No changes"; exit 0; }
          git -c user.name=codebahn-bot -c user.email=codebahn-bot@noreply.codebahn.net \
            commit -m "fix: apply AI review feedback"
          BRANCH=$(codebahn pr get --index "$PR" --json | jq -r .head.ref)
          AUTH=$(printf 'codebahn-bot:%s' "$CODEBAHN_TOKEN" | base64 -w0)
          git -c http.extraheader="AUTHORIZATION: basic $AUTH" push origin "HEAD:refs/heads/$BRANCH"
```

Comment `/fix` on a pull request that has an AI review. The agent reads the findings, edits the code, and `codebahn-bot` pushes one commit to the pull request branch. Anything after `/fix` is passed to the agent as an extra instruction, for example `/fix return None for empty lists`.

The fix is an ordinary commit. Read it, revert it, or push your own change on top.

## Fix automatically

Uncomment the `pull_request_review_comment` trigger in `ai-fix.yml`. From then on, every AI review is followed by a fix commit.

On Codebahn, a review posted as a comment fires `pull_request_review_comment`, not `pull_request_review`, which fires only for approvals and change requests. That is why the trigger names the comment event.

## What each push triggers

`codebahn-bot` acts as a real user, so its fix commit starts CI like any push: your tests run on the fixed code. The AI review skips that push, because the review job ignores commits from `codebahn-bot`. One push from a person therefore causes at most one review and one fix:

| Event | Actor | What runs |
| --- | --- | --- |
| You push, or comment `/review` | you | One AI review |
| The AI review is posted | `codebahn-bot` | One fix, if automatic fixes are on |
| The fix is pushed | `codebahn-bot` | Your other workflows. The AI review skips. |

If the fix leaves something unresolved, nothing retries on its own. You decide whether to comment `/review` or `/fix` again.

:::caution[Keep the actor check]
Removing `github.actor != 'codebahn-bot'` from `ai-review.yml` makes every fix trigger a new review, and with automatic fixes on, every review a new fix. The two would alternate until a run fails or your spend limit stops them.
:::

## Adjust it

- **Agent and model.** `MODEL` picks the model; the example uses the cheapest current Claude model, and a larger one costs more per review. To use another agent, change the install line, the `claude` command and the API key secret in both files. Keep two things: clear `CODEBAHN_TOKEN` before the agent runs, and have the review write `/tmp/review.json` in the same shape, since the posting step reads that file.
- **Review only on request.** Delete the `pull_request` trigger from `ai-review.yml`. Reviews then run only on `/review`.
- **What to look for.** Edit the `Report only ...` line in the prompt, for example to add your team's conventions or a checklist.
- **Who can trigger it.** Anyone who can comment on the pull request can run `/review` and `/fix`, which means anyone with access to the repository.

Each run uses CI minutes like any job (see [Billing](/docs/billing/)), plus the Anthropic usage on your own key.

## Troubleshooting

- **`error: not logged in`.** The CLI found no token. CI tokens are secrets, not environment variables: keep the `CODEBAHN_TOKEN: ${{ secrets.CODEBAHN_BOT_TOKEN }}` line in `env`.
- **The review job shows as skipped.** Expected for pushes by `codebahn-bot`, for draft pull requests, and for comments that start with anything other than `/review`.
- **`/fix` says "Nothing to fix".** The latest AI review had no inline findings. Comment `/review` first.
- **Comments on forked pull requests.** Codebahn does not inject `CODEBAHN_BOT_TOKEN` into jobs for pull requests from forks, so neither workflow can post or push there.
