AI pull-request reviewer
When a pull request opens or changes, a short Go task reads its diff from GitHub, asks Claude for a review, and posts the review as a comment. It starts in mock mode, so you can run it before you have any keys.
What this tutorial proves
- A task reads two secrets by name (
ctx.Secrets). The values are never in the code, the config or the command line. - A task reaches only the hosts you allow: here exactly two,
api.github.comandapi.anthropic.com. - GitHub starts a run through a signed webhook, with the repository and the pull request number in the body.
- A repeated webhook delivery returns the same run, so one commit on a pull request gets one review.
- A task can post AI output back to the system that called it: the review lands as a comment on the pull request.
What you build
A reviewer that comments on every new pull request and on every new commit pushed to one.
- A GitHub Actions workflow calls the task's webhook with
{"repo":"owner/name","pr":123}. - The task reads the pull request's diff from the GitHub API.
- It sends the diff to Claude and gets back a verdict, a summary and a few line comments, as JSON.
- It posts the review as one comment on the pull request, and returns a short result.
pull request opened ──▶ GitHub Actions ──signed POST──▶ api.ignitify.dev/hooks/trigger/<hook-id>
│ starts a run
▼
VM: pr-reviewer ──HTTPS──▶ api.github.com (read the diff)
──HTTPS──▶ api.anthropic.com (ask for a review)
──HTTPS──▶ api.github.com (post the comment)The task's nature
| Setting | Value | Why |
|---|---|---|
runtime | go | The platform compiles the module to one static binary. You need no Go toolchain to deploy. |
secrets | [GITHUB_TOKEN, ANTHROPIC_API_KEY] | The names the task reads. A run fails if a name has no value yet. |
network.type | egress | Outbound only. Nothing can connect to the task. |
egress_allow | [api.github.com, api.anthropic.com] | The only two hosts the task may reach. |
duration | short | One diff, one review, one comment. |
preset | std.micro | 128 MiB is enough for three HTTP calls. The smallest size costs the least. |
timeout_sec | 300 | A real review of a large diff can take a minute or two. |
Before you start
- A plan with webhooks. This tutorial uses Starter. Free allows the secrets, but not the outbound calls or
hook:create. - The CLI, installed and signed in. See Install.
- For mock mode, nothing else. To go live: a GitHub token that can read pull requests and write comments on the repository, and an Anthropic API key.
$ ignitify loginCreate the task
Register the name and get a Go task folder with starter files. You replace main.go and task.yaml, and add review.go, in the next step.
$ ignitify task:create pr-reviewer --lang gotasks/pr-reviewer/
├── task.yaml the secret names, the two allowed hosts, run defaults
├── main.go the shell: run(), the real GitHub and Claude calls
├── review.go the parts with no network: payload, mock rule, prompt, comment, sample data
├── go.mod the module (written by task:create; keep it)
├── go.sum empty: the task uses only the standard library
├── ignitify/ the runtime client (written by task:create; do not edit it)
└── README.md how to run itThe code
main.go picks the clients and runs the flow. review.go holds everything that makes no network call, so you can read and test it alone. Both files are in package main, and the platform builds them together into one binary.
GitHub and Claude sit behind two small interfaces, GitHub and Reviewer. In mock mode the task uses the mocks in review.go. Otherwise it uses githubAPI and claudeAPI in main.go, which call the real APIs.
// pr-reviewer: a GitHub webhook starts a run with {"repo":"owner/name","pr":123}. The task reads the
// pull request's diff, asks Claude for a short review, and posts the review as a PR comment.
//
// While a secret holds its sample value (review.go), the run is a mock: no GitHub or Claude call.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
ignitify "ignitify.local/runtime"
)
func main() {
ignitify.Start(run)
}
func run(payload json.RawMessage, ctx *ignitify.Ctx) (any, error) {
p, err := parsePayload(payload)
if err != nil {
return nil, err
}
mock := isMock(ctx.Secrets)
var gh GitHub = mockGitHub{}
var ai Reviewer = mockClaude{}
if mock {
log.Printf("mock mode: sample data, no GitHub or Claude call")
} else {
gh = githubAPI{token: ctx.Secrets["GITHUB_TOKEN"]}
ai = claudeAPI{key: ctx.Secrets["ANTHROPIC_API_KEY"]}
}
res, err := reviewPR(p, gh, ai, mock)
if err != nil {
return nil, err
}
ctx.Metric("reviews_posted", 1, "", map[string]any{"verdict": res.Verdict})
return res, nil
}
var client = &http.Client{Timeout: 90 * time.Second}
// send does one request and returns the body. A status that is not 2xx is an error.
func send(req *http.Request) ([]byte, error) {
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode/100 != 2 {
return nil, fmt.Errorf("%s %s: %d %s", req.Method, req.URL.Host, res.StatusCode, cut(string(body), 300))
}
return body, nil
}
// ── GitHub REST API ─────────────────────────────────────────────────────────
type githubAPI struct{ token string }
func (g githubAPI) request(method, path, accept string, body []byte) (*http.Request, error) {
req, err := http.NewRequest(method, "https://api.github.com"+path, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+g.token)
req.Header.Set("Accept", accept)
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
return req, nil
}
func (g githubAPI) Diff(repo string, pr int) (string, error) {
req, err := g.request("GET", fmt.Sprintf("/repos/%s/pulls/%d", repo, pr), "application/vnd.github.diff", nil)
if err != nil {
return "", err
}
body, err := send(req)
return string(body), err
}
func (g githubAPI) Comment(repo string, pr int, text string) error {
body, _ := json.Marshal(map[string]string{"body": text})
req, err := g.request("POST", fmt.Sprintf("/repos/%s/issues/%d/comments", repo, pr), "application/vnd.github+json", body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
_, err = send(req)
return err
}
// ── Anthropic Messages API ──────────────────────────────────────────────────
type claudeAPI struct{ key string }
// reviewSchema makes Claude answer with JSON in the shape of Review.
var reviewSchema = map[string]any{
"type": "object",
"properties": map[string]any{
"verdict": map[string]any{"type": "string", "enum": []string{"approve", "comment", "request_changes"}},
"summary": map[string]any{"type": "string"},
"comments": map[string]any{"type": "array", "items": map[string]any{
"type": "object",
"properties": map[string]any{
"file": map[string]any{"type": "string"},
"line": map[string]any{"type": "integer"},
"body": map[string]any{"type": "string"},
},
"required": []string{"file", "line", "body"},
"additionalProperties": false,
}},
},
"required": []string{"verdict", "summary", "comments"},
"additionalProperties": false,
}
func (c claudeAPI) Review(repo string, pr int, diff string) (Review, error) {
body, _ := json.Marshal(map[string]any{
"model": "claude-opus-5-5",
"max_tokens": 16000,
"system": "You are a careful senior engineer who reviews pull requests. Be short and concrete.",
"messages": []map[string]string{{"role": "user", "content": prompt(repo, pr, diff)}},
"output_config": map[string]any{
"effort": "low",
"format": map[string]any{"type": "json_schema", "schema": reviewSchema},
},
"fallbacks": "default", // a declined request is run again on a fallback model
})
req, err := http.NewRequest("POST", "https://api.anthropic.com/v1/messages", bytes.NewReader(body))
if err != nil {
return Review{}, err
}
req.Header.Set("x-api-key", c.key)
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("anthropic-beta", "server-side-fallback-2026-07-01")
req.Header.Set("Content-Type", "application/json")
raw, err := send(req)
if err != nil {
return Review{}, err
}
var msg struct {
StopReason string `json:"stop_reason"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}
if err := json.Unmarshal(raw, &msg); err != nil {
return Review{}, err
}
if msg.StopReason == "refusal" {
return Review{}, fmt.Errorf("Claude declined to review this pull request")
}
for _, block := range msg.Content {
if block.Type == "text" {
var r Review
err := json.Unmarshal([]byte(block.Text), &r)
return r, err
}
}
return Review{}, fmt.Errorf("Claude sent no text (stop_reason %s)", msg.StopReason)
}package main
// The parts with no network: the payload, the mock rule, the review flow, the prompt, the comment
// text, and the sample data that the mocks return.
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
)
// The sample secret values. While either secret holds its sample value, the run is a mock: it makes
// no GitHub call and no Claude call.
const (
sampleGitHubToken = "mock-github-token"
sampleAnthropicKey = "mock-anthropic-key"
)
const (
maxDiffBytes = 100_000 // the part of the diff that Claude reads
maxSummaryBytes = 2_000 // keeps the result far below the 10 KiB limit
)
var repoPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
type Payload struct {
Repo string `json:"repo"`
PR int `json:"pr"`
}
type LineComment struct {
File string `json:"file"`
Line int `json:"line"`
Body string `json:"body"`
}
type Review struct {
Verdict string `json:"verdict"` // approve | comment | request_changes
Summary string `json:"summary"`
Comments []LineComment `json:"comments"`
}
type Result struct {
Repo string `json:"repo"`
PR int `json:"pr"`
Verdict string `json:"verdict"`
Summary string `json:"summary"`
CommentsPosted int `json:"comments_posted"`
Mock bool `json:"mock"`
}
// GitHub and Reviewer are the seams: main.go has the real clients, this file has the mocks.
type GitHub interface {
Diff(repo string, pr int) (string, error)
Comment(repo string, pr int, body string) error
}
type Reviewer interface {
Review(repo string, pr int, diff string) (Review, error)
}
func parsePayload(raw json.RawMessage) (Payload, error) {
var p Payload
if err := json.Unmarshal(raw, &p); err != nil {
return p, fmt.Errorf(`the payload must be {"repo":"owner/name","pr":123}: %w`, err)
}
if !repoPattern.MatchString(p.Repo) {
return p, errors.New(`"repo" must be "owner/name"`)
}
if p.PR < 1 {
return p, errors.New(`"pr" must be a pull request number`)
}
return p, nil
}
// isMock is the one mock rule: either secret still holds its sample value.
func isMock(secrets map[string]string) bool {
return secrets["GITHUB_TOKEN"] == sampleGitHubToken || secrets["ANTHROPIC_API_KEY"] == sampleAnthropicKey
}
// reviewPR is the whole flow: read the diff, ask for a review, post it as one PR comment.
func reviewPR(p Payload, gh GitHub, ai Reviewer, mock bool) (Result, error) {
diff, err := gh.Diff(p.Repo, p.PR)
if err != nil {
return Result{}, err
}
r, err := ai.Review(p.Repo, p.PR, trimDiff(diff))
if err != nil {
return Result{}, err
}
if err := gh.Comment(p.Repo, p.PR, commentBody(r)); err != nil {
return Result{}, err
}
return Result{Repo: p.Repo, PR: p.PR, Verdict: r.Verdict, Summary: cut(r.Summary, maxSummaryBytes), CommentsPosted: 1, Mock: mock}, nil
}
// trimDiff keeps the first maxDiffBytes of the diff, cut at a line end.
func trimDiff(diff string) string {
if len(diff) <= maxDiffBytes {
return diff
}
head := diff[:maxDiffBytes]
if i := strings.LastIndexByte(head, '\n'); i > 0 {
head = head[:i+1]
}
return head + "\n[the diff was cut here]\n"
}
func cut(s string, n int) string {
if len(s) <= n {
return s
}
return strings.ToValidUTF8(s[:n], "") + "…"
}
func prompt(repo string, pr int, diff string) string {
return fmt.Sprintf(`Review pull request #%d in %s. Look for bugs, security problems and missing error handling.
Ignore style. Give at most 5 line comments, on lines that the diff adds.
<diff>
%s
</diff>`, pr, repo, diff)
}
func commentBody(r Review) string {
var b strings.Builder
fmt.Fprintf(&b, "### AI review: %s\n\n%s\n", r.Verdict, r.Summary)
for _, c := range r.Comments {
fmt.Fprintf(&b, "\n- `%s:%d`: %s", c.File, c.Line, c.Body)
}
b.WriteString("\n\n<sub>Posted by the pr-reviewer task on Ignitify.</sub>\n")
return b.String()
}
// ── Mocks: sample data, no network ──────────────────────────────────────────
type mockGitHub struct{}
func (mockGitHub) Diff(string, int) (string, error) { return sampleDiff, nil }
func (mockGitHub) Comment(string, int, string) error { return nil }
type mockClaude struct{}
func (mockClaude) Review(string, int, string) (Review, error) { return sampleReview, nil }
const sampleDiff = `diff --git a/cache/cache.go b/cache/cache.go
index 3f2a1c9..8b7d4e0 100644
--- a/cache/cache.go
+++ b/cache/cache.go
@@ -12,6 +12,18 @@ type Cache struct {
items map[string]entry
}
+// Reload reads every entry from the file again.
+func (c *Cache) Reload(path string) {
+ data, _ := os.ReadFile(path)
+ var fresh map[string]entry
+ json.Unmarshal(data, &fresh)
+ c.items = fresh
+}
+
+func (c *Cache) Get(key string) entry {
+ return c.items[key]
+}
+
func (c *Cache) Len() int {
return len(c.items)
}
`
var sampleReview = Review{
Verdict: "request_changes",
Summary: "Reload ignores two errors. A missing or broken file empties the cache, and no caller can see why.",
Comments: []LineComment{
{File: "cache/cache.go", Line: 17, Body: "The error from os.ReadFile is dropped. Return it, and keep the old entries."},
{File: "cache/cache.go", Line: 19, Body: "json.Unmarshal can fail. On a failure, fresh is nil and the cache becomes empty."},
{File: "cache/cache.go", Line: 20, Body: "Reload replaces c.items with no lock. A Get at the same time is a data race."},
},
}schema_version: 1
slug: pr-reviewer # must match this directory's name
runtime: go
# Secret NAMES the task reads from ctx.Secrets. Set each value with `ignitify secret:set NAME --stdin`.
# A run fails if a declared name has no value. The sample values mock-github-token and
# mock-anthropic-key turn on mock mode: no GitHub or Claude call.
secrets: [GITHUB_TOKEN, ANTHROPIC_API_KEY]
execution:
duration: short # one diff, one review, one comment
network:
type: egress # outbound only: nothing can connect to this task
egress_allow: [api.github.com, api.anthropic.com] # the only two hosts the task may reach
run:
payload:
repo: octo-org/widgets
pr: 42
preset: std.micro # 128 MiB is enough: three HTTP calls and some JSON
timeout_sec: 300 # a real review can take a minute or two# pr-reviewer
An AI pull-request reviewer. A GitHub Actions workflow calls the task's webhook when a pull request opens or changes. The task reads the pull request's diff, asks Claude for a short review, and posts the review as a comment on the pull request.
## Files
- `task.yaml`: slug, runtime, the two secret names, outbound access to `api.github.com` and `api.anthropic.com` only, and run defaults.
- `main.go`: the shell: `run()`, and the real GitHub and Claude calls.
- `review.go`: the parts with no network: payload rules, the mock rule, the review flow, the prompt, the comment text and the sample data.
- `go.mod`, `go.sum`: the module. Standard library only, so `go.sum` is empty.
- `ignitify/`: the runtime client, written by `task:create`. Do not edit it.
## Mock mode
While `GITHUB_TOKEN` is `mock-github-token` or `ANTHROPIC_API_KEY` is `mock-anthropic-key`, the run is a mock. It returns a sample review and makes no GitHub or Claude call. Set both real keys to go live.
## Payload
| Field | Default | Meaning |
| :-- | :-- | :-- |
| `repo` | `octo-org/widgets` (in task.yaml) | The repository, as `owner/name` |
| `pr` | 42 | The pull request number |
## Result
`{ repo, pr, verdict, summary, comments_posted, mock }`. `verdict` is `approve`, `comment` or `request_changes`.
## Lifecycle
```bash
ignitify login
ignitify task:create pr-reviewer --lang go
printf %s mock-github-token | ignitify secret:set GITHUB_TOKEN --stdin
printf %s mock-anthropic-key | ignitify secret:set ANTHROPIC_API_KEY --stdin
ignitify task:validate pr-reviewer
ignitify task:deploy pr-reviewer
ignitify task:run pr-reviewer --wait
```
Connect GitHub: create a webhook with `ignitify hook:create pr-reviewer`, and call it from the workflow in `pr-review.yml`.The mock rule is one line in review.go: the run is a mock while GITHUB_TOKEN is mock-github-token or ANTHROPIC_API_KEY is mock-anthropic-key. So a run never posts a fake review with a real token.
Store the two secrets
For mock mode, store the sample values. Read each value from a pipe or a file, so it stays out of your shell history. A value on the command line is refused.
$ printf %s mock-github-token | ignitify secret:set GITHUB_TOKEN --stdin✓ secret GITHUB_TOKEN stored
$ printf %s mock-anthropic-key | ignitify secret:set ANTHROPIC_API_KEY --stdin✓ secret ANTHROPIC_API_KEY stored
$ ignitify secret:listValidate and deploy
Check task.yaml on your machine, and list the files that a deploy would upload. Nothing is sent and nothing is built.
$ ignitify task:validate pr-reviewer✓ task config valid
$ ignitify task:pack pr-reviewerUpload the source. The platform compiles the Go module and builds the image.
$ ignitify task:deploy pr-reviewer✓ Image built · <build time>✓ Deployment Createddeployment_id <deployment-id>
Run it once in mock mode
The default payload in task.yaml reviews pull request 42 of octo-org/widgets. In mock mode that repository is never called. --wait follows the run and prints it with its result.
$ ignitify task:run pr-reviewer --wait$ ignitify task:run pr-reviewer --wait --payload '{"repo":"your-org/your-repo","pr":7}'Read the result
$ ignitify run:get <run-id> --json | jq .result{
"repo": "octo-org/widgets",
"pr": 42,
"verdict": "request_changes",
"summary": "Reload ignores two errors. A missing or broken file empties the cache, and no caller can see why.",
"comments_posted": 1,
"mock": true
}mock: true says that no GitHub or Claude call was made. With real keys, this is the comment the task posts on the pull request:
### AI review: request_changes
Reload ignores two errors. A missing or broken file empties the cache, and no caller can see why.
- `cache/cache.go:17`: The error from os.ReadFile is dropped. Return it, and keep the old entries.
- `cache/cache.go:19`: json.Unmarshal can fail. On a failure, fresh is nil and the cache becomes empty.
- `cache/cache.go:20`: Reload replaces c.items with no lock. A Get at the same time is a data race.A bad payload fails the run with the reason, for example "repo" must be "owner/name". Read it with run:get <run-id>.
Connect GitHub
Create a webhook for the task. The reply shows the secret once, so store it now. A new deploy of the task keeps the same URL and secret.
$ ignitify hook:create pr-reviewer⚠️ The `secret` below is shown ONCE and cannot be read back — `hook:list` never returns it.✓ Webhook Createdurl https://api.ignitify.dev/hooks/trigger/<hook-id>secret <hook-secret> (shown ONCE)
Put the URL and the secret in your repository's Actions secrets as IGNITIFY_HOOK_URL and IGNITIFY_HOOK_SECRET, and add this workflow. It sends only the repository and the pull request number, signed with HMAC-SHA256. The delivery id holds the commit, so a re-run job returns the same run instead of a second review.
# .github/workflows/pr-review.yml — starts one review run when a pull request opens or gets new commits.
# Repository secrets: IGNITIFY_HOOK_URL and IGNITIFY_HOOK_SECRET (from `ignitify hook:create`).
name: pr-review
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
trigger:
runs-on: ubuntu-latest
steps:
- name: Start the review run
env:
HOOK_URL: ${{ secrets.IGNITIFY_HOOK_URL }}
HOOK_SECRET: ${{ secrets.IGNITIFY_HOOK_SECRET }}
REPO: ${{ github.repository }}
PR: ${{ github.event.pull_request.number }}
SHA: ${{ github.event.pull_request.head.sha }}
run: |
BODY=$(printf '{"repo":"%s","pr":%s}' "$REPO" "$PR")
SIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "$HOOK_SECRET" -hex | sed 's/^.* //')
# One delivery id per pull request and commit: a re-run job returns the same run,
# so a commit gets one review.
curl -fsS -X POST "$HOOK_URL" \
-H "content-type: application/json" \
-H "x-ignitify-signature: sha256=$SIG" \
-H "x-ignitify-delivery: pr-review-$REPO-$PR-$SHA" \
-d "$BODY"A good call answers 202 with the new run id. A wrong signature answers 401.
Going live
Replace the two sample values with real ones. The platform reads secrets when a run starts, so the next run uses them. You change no code.
$ ignitify secret:set GITHUB_TOKEN --stdin < github-token.txt$ ignitify secret:set ANTHROPIC_API_KEY --stdin < anthropic-key.txt- GitHub token: a fine-grained token for the repository with the Pull requests: Read and write permission. It reads the diff and posts the comment.
- Anthropic key: from the Claude Console. The task calls the Messages API with
claude-opus-5-5ateffort: low, and asks for JSON in the shape ofReview. - Check it first: run once with
--payloadon a test pull request, and readmock: falsein the result.
Things you may want to change in the code:
prompt()inreview.go: what Claude looks for, and how many line comments it may give.maxDiffBytes: how much of a large diff Claude reads. The rest is cut, with a note.githubAPI.Comment: post line comments on the diff instead of one comment, with GitHub's pull request review API.
Clean up
$ ignitify hook:list pr-reviewer$ ignitify hook:delete <hook-resource-id> -y$ ignitify secret:delete GITHUB_TOKEN -y$ ignitify secret:delete ANTHROPIC_API_KEY -y$ ignitify task:delete pr-reviewer --yesNext steps
- Skip small changes: in the workflow, call the webhook only when the pull request has a label, such as
ai-review. - Get told when a review fails: set a callback with
notify:set, as in the nightly report tutorial. - Read more: Use secrets, Trigger from a webhook, Network access.