Skip to main content

Build an AI Pull Request Reviewer in Java: Spring AI, Gitea Webhooks and Inline Comments

Build an AI pull request reviewer in Java with Spring AI structured output and Gitea webhooks: a guard for wrong line numbers, no repeat comments after a push, and the Gitea behaviours found by testing a real server, including the pending review a failed call leaves behind. Cost figures are computed estimates.

Asking a model to review some code takes ten lines of Java. Getting its answer onto the right line of a pull request, only once, even after five more pushes, is the real work. In the runs below a small local model quoted a hard-coded password perfectly and gave the wrong line number five times out of five, and Gitea 1.27.3 accepted comments on a file that does not exist.

This post builds an AI pull request reviewer with Spring Boot, Spring AI structured output and Gitea webhooks, and tests it against a real Gitea running in Docker. It is the stricter follow-up to the smaller AI code-review bot, which never talked to a live server. Doing that showed two things the earlier version gets wrong, both covered below.

Versions tested (December 2026). JDK 25 (Temurin 25.0.5.1), Spring Boot 4.2.0, Spring AI 2.1.0, JUnit 6.1.3, Gitea 1.27.3 in Docker. Code: the pr-reviewer module of java-ai-agents.
What is real and what is not. Gitea, the webhooks, the REST calls and the application are real. Most tests use a scripted ChatModel that follows fixed rules. One section uses real but very small local models (qwen2.5-coder 1.5b and 3b through Ollama). No paid model was called, so every dollar figure is a computed estimate.

An AI pull request review is mostly not the model

The flow is short. Gitea sends a webhook when a pull request opens or gets a push. The service fetches the diff, cuts it into chunks, asks a model about each chunk, checks the answers, removes what it has already said, and posts one review with inline comments. A few words used below: the head is the newest commit of the branch under review, a hunk is one @@ block of a diff, and an inline comment is attached to a file and line.

Webhookverify, answer 202Fetch diffcheck headChunknumber the linesModelclaims findingsLine guardquote must matchDe-duplicatefingerprintsPost one reviewCOMMENT onlyGrey and blue prepare the input. Red and green decide what may be published.

The picture shows where trust changes. Only one box is the model. Everything to its left decides what it sees, and everything to its right treats what it says as an unverified claim.

Verify the webhook, then answer at once

A webhook endpoint is a public URL that spends your money. Gitea signs the raw request body with HMAC-SHA256 and a shared secret, and sends the hex digest in X-Gitea-Signature. Take the body as byte[]: parsing and re-serialising it changes the bytes. The next lines come from WebhookController.java.

if (!Signatures.matches(properties.webhookSecret(), body, signature)) {
    return ResponseEntity.status(401).body("bad signature");
}
JsonNode root = json.readTree(new String(body, StandardCharsets.UTF_8));
String action = root.path("action").asString("");
// Our own review also fires webhooks (event pull_request_comment). Ignoring them prevents a loop.
if (!"pull_request".equals(event) || !ACTIONS.contains(action)) {
    return ResponseEntity.ok("ignored: " + event + "/" + action);
}

The test replays a delivery captured from the real server, signed by Gitea itself. The output is from output/10-webhook.txt.

headers Gitea 1.27.3 sent for a push to an open pull request:
  User-Agent: Go-http-client/1.1
  Content-Type: application/json
  X-Gitea-Event: pull_request
  X-Gitea-Event-Type: pull_request_sync
  X-Gitea-Signature: 492a12ee8b49f54f0ab4e30df1d5b463856c9798b99cff79beb067a52bda2b91
  X-Hub-Signature-256: sha256=492a12ee8b49f54f0ab4e30df1d5b463856c9798b99cff79beb067a52bda2b91

the captured delivery                      -> 202 queued dev/shop#1
no signature header                        -> 401 bad signature
X-Hub-Signature-256 value (has sha256=)    -> 401 bad signature
same JSON, parsed and re-serialised        -> 401 bad signature
the event our own review triggers          -> 200 ignored: pull_request_comment/reviewed
original body: 13213 bytes, re-serialised: 9568 bytes
A push does not arrive as event pull_request_sync in X-Gitea-Event. That header says pull_request; pull_request_sync is in X-Gitea-Event-Type, and the action is synchronized. My earlier bot required X-Gitea-Event: pull_request_sync, so on this server it would ignore every push. Its tests passed because I had written the request by hand.

Answer 202 before doing any work. Reviews take seconds, and in a 60-second test a delivery that failed or timed out was not sent again (output/15).

one pull request opened, two webhooks, 60 seconds of waiting
receiver that answers 500            : 1 request(s) received
receiver that answers after 8 seconds: 1 request(s) received
Going deeper: webhook setup traps

A Gitea with default settings refuses to call a private address at all. The hook saves without complaint, and the only sign in this run was a server log line, quoted from output/19.

Unable to deliver webhook task[1]: unable to deliver webhook task[1] in http://172.17.0.1:8118/webhook/gitea due to error in http client: Post "http://172.17.0.1:8118/webhook/gitea": dial tcp 172.17.0.1:8118: webhook can only call allowed HTTP servers (check your security.ALLOWED_HOST_LIST setting), deny '172.17.0.1(172.17.0.1:8118)'

Set [security] ALLOWED_HOST_LIST to what you need, for example private on a closed network. Two more points:

  • Your own review fires webhooks too (event pull_request_comment). Filter by event or the bot can talk to itself.
  • ReviewQueue.java runs one review at a time per pull request, so two quick pushes cannot both post. It is in memory, so run one replica.
  • Gitea webhook documentation.

Parse the diff by counting, not by guessing

A comment needs a line number in the new file. The diff gives you a starting number in each hunk header, and you count from there. The trap is recognising file headers by their text: an added line ++i; appears in a diff as +++i;, which looks like a header. The chunker in my earlier module skips such lines, and every number after it shifts. This is its real output, produced by a script and saved in output/21.

new file content is: select 1; / ++i; / select 2; / select 3;  (added: lines 2 and 3)
code-review-bot DiffChunker says:
1|  select 1;
2| +select 2;
3|  select 3;
added lines: [2]

select 2; is really on line 3. The new parser reads the line counts from the @@ header and treats everything inside the hunk as content. From UnifiedDiff.java:

char marker = raw.isEmpty() ? ' ' : raw.charAt(0);
String text = raw.isEmpty() ? "" : raw.substring(1);
switch (marker) {
    case '+' -> { current.add(new Line(Type.ADDED, 0, newNo++, text)); newLeft--; }
    case '-' -> { current.add(new Line(Type.REMOVED, oldNo++, 0, text)); oldLeft--; }
    case ' ' -> { current.add(new Line(Type.CONTEXT, oldNo++, newNo++, text)); oldLeft--; newLeft--; }
    default -> throw new IllegalArgumentException("unexpected line inside a hunk: " + raw);
}
continue;
Going deeper: chunking

Chunker.java keeps a chunk inside one file, keeps hunks whole when they fit, and splits a large hunk between lines. Deleted, binary, lock, minified and generated files are never sent. Gitea also appends a tab to a +++ path that contains spaces, which the parser strips.

  • output/01: deleted, binary, spaced-path and look-alike lines.
  • output/02: a 40-line hunk split into four chunks with correct numbers.
  • A model sees one chunk at a time, so it cannot find a bug that spans two files.

Ask Spring AI for records, not prose

Spring AI can turn a Java record into a JSON schema, add it to the prompt, and map the reply back. Each finding carries a line, a quote of the code on that line, severity, category, title, comment and suggestion. From ModelReviewer.java:

ReviewResult result = chat.prompt()
        .advisors(new FenceStripper(), meter)
        .system(SYSTEM)
        .user(userMessage(chunk))
        .call()
        .entity(ReviewResult.class, spec -> spec.validateSchema());

validateSchema() adds an advisor that checks the reply and asks again, up to four calls in total in these runs. That has a catch. A reply wrapped in a Markdown fence is common, plain entity() accepts it, and the validation advisor in 2.1.0 does not. See output/04-bad-replies.txt.

fenced reply, plain entity()         : 1 finding(s), 1 model call(s)
fenced reply, entity() + validateSchema(): 1 finding(s), 4 model call(s)
fenced reply, with FenceStripper     : 1 finding(s), 1 model call(s)
The same answer, four times the bill. The result is correct, so nothing looks broken. The fix here is FenceStripper, a small advisor that sits between the validator and the model and removes the fence first.
Going deeper: retries, failures and the real prompt

A retry costs a full call. UsageMeter sits next to the model so retried tokens are counted. A reply that never validates ends in an exception for that chunk only, and the review summary says a chunk was skipped.

severity "HIGH", then valid          : 1 finding(s), 2 model call(s), 1291 input tokens (single call: 630)
line added to the retried request:
  Output JSON validation failed because of: does not have a value in the enumeration ["CRITICAL", "MAJOR", "MINOR", "NIT"]
copies of the schema in the retried request: 1
prose forever                        : ModelFailure after 4 model calls, 2637 input tokens spent

Never trust the line number on its own

The model is asked for two things that must agree: a number and a copy of the code. If they agree on an added line, post. If the quote matches exactly one added line elsewhere in the chunk, move the comment there. Otherwise drop it.

Findingline number + quoteAgree on added linepost as claimedQuote matches one linemove, then postNo match or severaldropnumber is rightnumber is wrong, code is realinvented or ambiguous

The diagram has one path to an unchanged comment, one to a moved comment, and drops everything else. The code is in LineGuard.java.

String claimed = added.get(f.line());
if (claimed != null && matches(normalize(claimed), quote)) {
    return new Verdict(Outcome.ACCEPTED, f.line());
}
List<Integer> candidates = added.entrySet().stream()
        .filter(e -> matches(normalize(e.getValue()), quote))
        .map(Map.Entry::getKey).toList();
if (candidates.size() == 1) {
    return new Verdict(Outcome.RELOCATED, candidates.getFirst());
}
if (candidates.size() > 1) {
    return new Verdict(Outcome.AMBIGUOUS_QUOTE, f.line());
}
return new Verdict(claimed == null ? Outcome.NOT_AN_ADDED_LINE : Outcome.QUOTE_NOT_FOUND, f.line());

Invented and shifted numbers fed into it give this table, from output/05.

case                                 model  verdict            posted on
right line, right quote                  7  ACCEPTED           line 7
right line, partial quote               14  ACCEPTED           line 14
off by two, quote is real                9  RELOCATED          line 7
line past the end of the file         9999  RELOCATED          line 7
line past the end, invented code      9999  NOT_AN_ADDED_LINE  nowhere
context line                             6  NOT_AN_ADDED_LINE  nowhere
real line number, invented code          7  QUOTE_NOT_FOUND    nowhere
wrong line, quote on several lines      99  AMBIGUOUS_QUOTE    nowhere
too short to be a partial quote         14  QUOTE_NOT_FOUND    nowhere
no quote at all                          7  NO_QUOTE           nowhere

This is not only a theory about scripted mistakes. qwen2.5-coder:1.5b, run five times on a small pull request with planted bugs, reported the password on line 8 every time. It is on line 7. From output/18 (1.5b):

model qwen2.5-coder:1.5b on a local CPU (2 vCPU), temperature 0.2, the sample pull request, 5 independent runs

run 1: 1 call(s), 908 input + 104 output tokens, 49 s
  model line   8  RELOCATED          -> post on 7  CRITICAL Hard-coded Password
      quote: String password = "hunter2";
...
totals: 5 findings, 0 accepted as claimed, 5 moved to another line, 0 dropped
Do not read this as a benchmark. It is one tiny model and one file. It also reported only the password and missed the string comparison with ==, the concatenated SQL and the off-by-one loop. The 3b model returned no findings in all five runs (output/18, 3b). The guard fixes positions. It cannot add the findings a model did not make, or tell you a well-placed finding is true.

Gitea will accept almost any comment position

You might expect the server to reject a bad position. I posted one review per case to a real Gitea 1.27.3 and then looked at both web tabs. From output/11-gitea-accepts.txt:

one review per row, one inline comment each (Gitea 1.27.3)
comment on                         line  HTTP  shown: conversation shown: files changed
an added line                         7   200  yes                yes
a context line                        8   200  yes                yes
a line outside every hunk            15   200  yes                no
a file that does not exist            3   200  yes                no
line 0                                0   200  yes                yes
a line past the end of the file    9999   500  no                 no
PENDING reviews left behind by those calls: 1

A comment outside every hunk, or on a missing file, returns 200 and then does not appear in the “Files changed” tab. A line past the end of the file returns 500, and that failure is not clean.

Batch of 3good, bad, goodHTTP 500at the bad linePENDING reviewkeeps the first goodNext good reviewany later POSTPublished togetherold leftovers includedThe comment after the bad one was never stored.

As the figure shows, the comments processed before the bad one stay behind in a PENDING review. Each retry adds another copy, and the next successful review from the same user publishes all of them. From output/12:

POST review [good-A@7, ghost@9999, good-B@26], attempt 1 -> HTTP 500
POST review [good-A@7, ghost@9999, good-B@26], attempt 2 -> HTTP 500
POST review [good-A@7, ghost@9999, good-B@26], attempt 3 -> HTTP 500
reviews as the bot sees them now:
    review PENDING  body=""       comments: [good-A@7, good-A@7, good-A@7]

POST review [unrelated@26] -> HTTP 200
reviews now:
    review COMMENT  body="probe"  comments: [good-A@7, good-A@7, good-A@7, unrelated@26]

So the service deletes its own pending reviews before posting and again after a failure. From ReviewService.java:

deletePending(repo, pull);
var comments = selected.stream().map(c -> new GitHost.InlineComment(
        c.path(), c.line(), CommentFormat.body(c.finding(), c.fingerprint()))).toList();
try {
    host.createReview(repo, pull, sha, body, comments);
} catch (RuntimeException e) {
    deletePending(repo, pull);
    throw e;
}
Going deeper: an old commit_id does not pin the line

If someone pushes while the model is thinking, sending the old commit_id does not save you. The call succeeds, and the code Gitea attaches to the comment comes from the newer head. From output/13:

commit A adds the password on line 7. commit B then inserts four comment lines above it.
POST review with commit_id=A, new_position=7 -> HTTP 200, review stale=false
diff_hunk Gitea attached to the comment:
@@ -4,0 +4,4 @@
+    // one
+    // two
+    // three
+    // four

The service therefore reads the head after fetching the diff and again just before posting, and posts nothing if it moved. A push in the last few milliseconds can still slip through.

Say each thing once, however often the branch moves

A line number is a bad identity, because adding two lines at the top moves everything. The model’s wording is worse, because it changes between runs. The identity used here is the file path, the code on the line, and which copy of that code it is. It is hidden inside the comment as an HTML comment, so the pull request is the database and a restarted bot forgets nothing.

First push: line 7fingerprint 1: path + code + copyLater push: line 9same path, code, copySame fingerprintalready posted, skipThe line number is not part of the identity.

The drawing shows the line moving from 7 to 9 while its fingerprint stays the same, so nothing new is posted. From Fingerprint.java:

public static String of(String path, String code, int occurrence) {
    return Hashes.sha256(path + "\n" + LineGuard.normalize(code) + "\n" + occurrence).substring(0, 16);
}

Through real webhooks, opening a pull request, pushing two lines on top and then pushing one new problem gave this (output/14):

1. pull request opened      -> REVIEWED    posted 2, already there 0
2. push: two lines on top   -> NOTHING_NEW posted 0, already there 2
3. push: one new problem    -> REVIEWED    posted 1, already there 2

inline comments on the pull request, read back from Gitea:
  review by reviewbot, state COMMENT, stale=true
    src/UserDao.java:27  **MINOR** (maintainability): Console output
    src/UserDao.java:7  **CRITICAL** (security): Hard-coded password
  review by reviewbot, state COMMENT, stale=false
    src/UserDao.java:16  **MINOR** (maintainability): Console output

Gitea marked the first review stale and left its stored line numbers as they were. The marker did not show in the rendered comments.

Going deeper: limits, forged markers and noise

Only markers in comments written by the bot user count, otherwise an author could paste one to silence a finding. Model text is also defused: @name cannot ping anyone and it cannot forge a marker (output/09).

The comment cap counts per pull request. My first version counted per run, and the timing test showed that each redelivery then posted the next batch.

comment cap 2, worst first                   REVIEWED    modelCalls=2 cacheHits=0 posted=[line 1, line 2] dropped=[line 3 OVER_COMMENT_CAP, line 1 OVER_COMMENT_CAP]
same event again, cap already used up        NOTHING_NEW modelCalls=0 cacheHits=2 posted=[] dropped=[line 1 ALREADY_POSTED, line 2 ALREADY_POSTED, line 3 OVER_COMMENT_CAP, line 1 OVER_COMMENT_CAP]
  • output/06 and output/07: redelivery, moved lines, restart, identical lines.
  • A renamed file, or an edited line, gets a new fingerprint and can be commented again.
  • Once the cap is used up, even a later serious finding is held back. Raise the cap or exempt CRITICAL if that matters.

What a review costs and how long it takes

Chunks are cached by their content without line numbers, so a push that edits one line pays for one chunk. The cost table is a computed estimate: tokens were counted with the JTokkit cl100k_base tokenizer on the real prompts, output was assumed to be 300 tokens per call, and list prices were read on 3 December 2026 from Anthropic and OpenAI. From output/17:

COMPUTED ESTIMATE: tokens counted with JTokkit cl100k_base on the real prompts, no paid model called.
Assumed output: 300 tokens per call. Prices per million tokens as read on 2026-12-03.

fixed overhead of every call (instructions + JSON schema, empty diff): 611 input tokens
pull request                              calls input tokens of it overhead
sample (1 file, 22 added lines)               1          866            71%
real commit (20 files, 1004 added lines)     23        30450            46%
same PR, push that edits one line             1         1284            48%

model                                 sample PR   20-file PR one-line re-push  1000 x 20-file PR
Claude Haiku 5.5 (<=100k prompt)        $0.0002      $0.0065          $0.0003              $6.50
gpt-5-mini                              $0.0008      $0.0214          $0.0009             $21.41
gpt-5.4-mini                            $0.0020      $0.0539          $0.0023             $53.89
Claude Sonnet 5.5                       $0.0047      $0.1299          $0.0056            $129.90
Claude Opus 5.5                         $0.0095      $0.2598          $0.0111            $259.80

Nearly half of the input on the 20-file change is the fixed instructions and schema, repeated on every call. Real bills will differ: other tokenizers count differently (Anthropic says its newer models produce about 30% more tokens than its earlier ones), and retries add calls.

Time is dominated by the model. With the packaged jar, local Gitea and the 1.5b model on two shared vCPUs, one small pull request took 20 seconds end to end, of which the model phase was about 17 (output/20). Across the five runs above, one call took between 10 and 49 seconds. Without a model, the rest of the pipeline looks like this (output/16):

8 new files, 102 lines each; local Gitea; the model is scripted and answers instantly
run                                chunks posted  fetch  model  dedup   post
run 1 (cold JVM paths)                  9     32   77ms  169ms   12ms  606ms
run 2                                   9      0   51ms  143ms   80ms    0ms
run 3                                   9      0   92ms  158ms   68ms    0ms
run 4                                   9      0   55ms  279ms   76ms    0ms
run 5                                   9      0  114ms  153ms  307ms    0ms

after 61 reviews on the pull request: dedup phase 1725 ms (one request per review)
Going deeper: tuning cost and speed

The “model” column here is Spring AI plus the scripted stand-in, not inference. De-duplication makes one request per earlier review, so it grows with the life of a pull request. These timings come from a shared machine and move a lot between runs.

Run it, and decide whether you should

The offline tests need only JDK 25. The full set starts a throwaway Gitea in Docker, and refuses to run against anything that is not localhost. The script is run-all.sh.

export JAVA_HOME=/path/to/jdk-25
mvn test -pl pr-reviewer -am          # offline: no Docker, no API key
pr-reviewer/scripts/run-all.sh        # throwaway Gitea in Docker, rewrites output/

To deploy, set the Gitea URL, a token for a dedicated bot user, the webhook secret and an OpenAI-compatible endpoint, as listed in the module README and application.properties. The hosted OpenAI API was not called while building this, and Claude would need the Anthropic starter, which I did not try. GitHub is not supported.

Should you build this? If you want to learn the mechanics or must keep code on your own Gitea, yes. Treat it as a second pair of eyes that posts COMMENT reviews, never approvals. Before relying on it, measure how many findings your chosen model gets right on your own past pull requests. Compilers, tests and static analysis are cheaper for everything they can catch.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.