selected) {
+ 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;
+ }
+ }
+
+ private void deletePending(String repo, int pull) {
+ host.reviews(repo, pull).stream()
+ .filter(r -> r.state().equals("PENDING") && r.author().equals(settings.botLogin()))
+ .forEach(r -> host.deleteReview(repo, pull, r.id()));
+ }
+
+ private static String summary(int comments, int overBudget, int failed) {
+ StringBuilder sb = new StringBuilder("Automated review: " + comments + " new comment(s). A person still has to review this.");
+ if (overBudget > 0) {
+ sb.append("\n\n").append(overBudget).append(" chunk(s) were not reviewed because of the size limit.");
+ }
+ if (failed > 0) {
+ sb.append("\n\n").append(failed).append(" chunk(s) were not reviewed because the model gave no usable answer.");
+ }
+ return sb.toString();
+ }
+
+ private static long ms(long from, long to) {
+ return (to - from) / 1_000_000;
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewSettings.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewSettings.java
new file mode 100644
index 0000000..ca1b756
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewSettings.java
@@ -0,0 +1,8 @@
+package com.ankurm.prreviewer;
+
+/**
+ * The limits one review runs under. {@code maxComments} counts per pull request, not per run: a per-run
+ * cap would let every redelivered event post the next batch.
+ */
+public record ReviewSettings(String botLogin, int maxChunkChars, int maxChunks, int maxComments, Severity minSeverity) {
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerApplication.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerApplication.java
new file mode 100644
index 0000000..b4af1f3
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerApplication.java
@@ -0,0 +1,15 @@
+package com.ankurm.prreviewer;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+
+/** Entry point. Configuration lives in {@code application.properties}, wiring in {@link ReviewerConfig}. */
+@SpringBootApplication
+@EnableConfigurationProperties(ReviewerProperties.class)
+public class ReviewerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ReviewerApplication.class, args);
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerConfig.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerConfig.java
new file mode 100644
index 0000000..49eecf4
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerConfig.java
@@ -0,0 +1,31 @@
+package com.ankurm.prreviewer;
+
+import org.springframework.ai.chat.client.ChatClient;
+import org.springframework.ai.chat.model.ChatModel;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/** Wires the pipeline. The only model-specific thing here is the {@link ChatModel} bean Spring AI provides. */
+@Configuration
+class ReviewerConfig {
+
+ @Bean
+ GitHost gitHost(ReviewerProperties p) {
+ return new GiteaClient(p.giteaUrl(), p.giteaToken());
+ }
+
+ @Bean
+ ModelReviewer modelReviewer(ChatModel model) {
+ return new ModelReviewer(ChatClient.create(model));
+ }
+
+ @Bean
+ ReviewService reviewService(ModelReviewer reviewer, GitHost host, ReviewerProperties p) {
+ return new ReviewService(reviewer, host, p.settings());
+ }
+
+ @Bean(destroyMethod = "close")
+ ReviewQueue reviewQueue() {
+ return new ReviewQueue();
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerProperties.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerProperties.java
new file mode 100644
index 0000000..987c4a2
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/ReviewerProperties.java
@@ -0,0 +1,26 @@
+package com.ankurm.prreviewer;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.context.properties.bind.DefaultValue;
+
+/**
+ * @param giteaUrl base URL of the Gitea server, without {@code /api/v1}
+ * @param giteaToken access token of the bot user
+ * @param botLogin login of that user; only its own comments are trusted for de-duplication
+ * @param webhookSecret the secret configured on the Gitea webhook
+ */
+@ConfigurationProperties("reviewer")
+public record ReviewerProperties(
+ String giteaUrl,
+ String giteaToken,
+ String botLogin,
+ String webhookSecret,
+ @DefaultValue("6000") int maxChunkChars,
+ @DefaultValue("20") int maxChunks,
+ @DefaultValue("10") int maxComments,
+ @DefaultValue("MINOR") Severity minSeverity) {
+
+ ReviewSettings settings() {
+ return new ReviewSettings(botLogin, maxChunkChars, maxChunks, maxComments, minSeverity);
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/Severity.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/Severity.java
new file mode 100644
index 0000000..7884c58
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/Severity.java
@@ -0,0 +1,6 @@
+package com.ankurm.prreviewer;
+
+/** Declared worst first, so the natural enum order is the posting order. */
+public enum Severity {
+ CRITICAL, MAJOR, MINOR, NIT
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/Signatures.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/Signatures.java
new file mode 100644
index 0000000..01d2fcf
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/Signatures.java
@@ -0,0 +1,31 @@
+package com.ankurm.prreviewer;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.util.HexFormat;
+
+/** Gitea's {@code X-Gitea-Signature}: the lowercase hex HMAC-SHA256 of the raw request body. */
+public final class Signatures {
+
+ private Signatures() {}
+
+ public static String hmacSha256Hex(String secret, byte[] body) {
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
+ return HexFormat.of().formatHex(mac.doFinal(body));
+ } catch (GeneralSecurityException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** {@link MessageDigest#isEqual} does not stop at the first wrong byte, so timing reveals nothing. */
+ public static boolean matches(String secret, byte[] body, String header) {
+ return header != null && MessageDigest.isEqual(
+ hmacSha256Hex(secret, body).getBytes(StandardCharsets.US_ASCII),
+ header.getBytes(StandardCharsets.US_ASCII));
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/UnifiedDiff.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/UnifiedDiff.java
new file mode 100644
index 0000000..1e10922
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/UnifiedDiff.java
@@ -0,0 +1,104 @@
+package com.ankurm.prreviewer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A small parser for the unified diff Gitea serves at {@code /pulls/{n}.diff}.
+ *
+ * The one rule that matters: inside a hunk, count lines using the numbers in the {@code @@} header.
+ * Do not recognise file headers by their text, because an added line {@code ++i;} appears in the diff
+ * as {@code +++i;} and a removed SQL comment {@code -- note} appears as {@code --- note}.
+ */
+public final class UnifiedDiff {
+
+ public enum Type { ADDED, REMOVED, CONTEXT }
+
+ /** {@code newLine} is 0 for removed lines, {@code oldLine} is 0 for added lines. */
+ public record Line(Type type, int oldLine, int newLine, String text) {}
+
+ public record Hunk(String header, List lines) {}
+
+ public record FileDiff(String path, boolean deleted, boolean binary, List hunks) {}
+
+ private static final Pattern HUNK = Pattern.compile("^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@.*");
+
+ private UnifiedDiff() {}
+
+ public static List parse(String diff) {
+ List files = new ArrayList<>();
+ String path = null;
+ boolean deleted = false;
+ boolean binary = false;
+ List hunks = new ArrayList<>();
+ List current = null;
+ int oldNo = 0, newNo = 0, oldLeft = 0, newLeft = 0;
+
+ for (String raw : diff.split("\n", -1)) {
+ if (oldLeft > 0 || newLeft > 0) {
+ if (raw.startsWith("\\")) {
+ continue; // "\ No newline at end of file"
+ }
+ 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;
+ }
+ if (raw.startsWith("diff --git ")) {
+ if (path != null) {
+ files.add(new FileDiff(path, deleted, binary, hunks));
+ }
+ path = pathFromGitHeader(raw);
+ deleted = false;
+ binary = false;
+ hunks = new ArrayList<>();
+ } else if (raw.startsWith("+++ ") && !raw.equals("+++ /dev/null")) {
+ path = clean(raw.substring(4));
+ } else if (raw.startsWith("rename to ")) {
+ path = clean("b/" + raw.substring(10));
+ } else if (raw.startsWith("deleted file mode")) {
+ deleted = true;
+ } else if (raw.startsWith("Binary files ") || raw.startsWith("GIT binary patch")) {
+ binary = true;
+ } else {
+ Matcher m = HUNK.matcher(raw);
+ if (m.matches()) {
+ oldNo = Integer.parseInt(m.group(1));
+ oldLeft = m.group(2) == null ? 1 : Integer.parseInt(m.group(2));
+ newNo = Integer.parseInt(m.group(3));
+ newLeft = m.group(4) == null ? 1 : Integer.parseInt(m.group(4));
+ current = new ArrayList<>();
+ hunks.add(new Hunk(raw, current));
+ }
+ }
+ }
+ if (path != null) {
+ files.add(new FileDiff(path, deleted, binary, hunks));
+ }
+ return files;
+ }
+
+ private static String pathFromGitHeader(String header) {
+ int b = header.lastIndexOf(" b/");
+ return b >= 0 ? clean(header.substring(b + 1)) : header.substring("diff --git ".length());
+ }
+
+ /** Strips the {@code b/} prefix and the tab git appends after a path that contains spaces. */
+ private static String clean(String p) {
+ int tab = p.indexOf('\t');
+ if (tab >= 0) {
+ p = p.substring(0, tab);
+ }
+ if (p.length() > 1 && p.startsWith("\"") && p.endsWith("\"")) {
+ p = p.substring(1, p.length() - 1);
+ }
+ return p.startsWith("b/") ? p.substring(2) : p;
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/UsageMeter.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/UsageMeter.java
new file mode 100644
index 0000000..a9e2c90
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/UsageMeter.java
@@ -0,0 +1,47 @@
+package com.ankurm.prreviewer;
+
+import org.springframework.ai.chat.client.ChatClientRequest;
+import org.springframework.ai.chat.client.ChatClientResponse;
+import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
+import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
+import org.springframework.core.Ordered;
+
+/**
+ * Sits next to the model, inside the validation advisor, so it sees every request that is really sent,
+ * retries included. Reading usage from the final response would hide the cost of the retries.
+ */
+final class UsageMeter implements CallAdvisor {
+
+ int calls;
+ long inputTokens;
+ long outputTokens;
+ long nanos;
+
+ @Override
+ public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
+ long start = System.nanoTime();
+ calls++;
+ try {
+ ChatClientResponse response = chain.nextCall(request);
+ var chat = response.chatResponse();
+ if (chat != null && chat.getMetadata().getUsage() != null) {
+ var usage = chat.getMetadata().getUsage();
+ inputTokens += usage.getPromptTokens() == null ? 0 : usage.getPromptTokens();
+ outputTokens += usage.getCompletionTokens() == null ? 0 : usage.getCompletionTokens();
+ }
+ return response;
+ } finally {
+ nanos += System.nanoTime() - start;
+ }
+ }
+
+ @Override
+ public String getName() {
+ return "usage-meter";
+ }
+
+ @Override
+ public int getOrder() {
+ return Ordered.LOWEST_PRECEDENCE - 100;
+ }
+}
diff --git a/pr-reviewer/src/main/java/com/ankurm/prreviewer/WebhookController.java b/pr-reviewer/src/main/java/com/ankurm/prreviewer/WebhookController.java
new file mode 100644
index 0000000..905da0e
--- /dev/null
+++ b/pr-reviewer/src/main/java/com/ankurm/prreviewer/WebhookController.java
@@ -0,0 +1,62 @@
+package com.ankurm.prreviewer;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Set;
+
+/**
+ * Receives Gitea webhooks. The body arrives as bytes because the signature covers exactly those bytes.
+ * The answer goes back at once: Gitea gave up on a delivery after about five seconds in our run and
+ * did not send it again.
+ */
+@RestController
+public class WebhookController {
+
+ private static final Logger log = LoggerFactory.getLogger(WebhookController.class);
+
+ /** A push to an open pull request arrives as event {@code pull_request}, action {@code synchronized}. */
+ private static final Set ACTIONS = Set.of("opened", "reopened", "synchronized");
+
+ private final JsonMapper json = JsonMapper.builder().build();
+ private final ReviewerProperties properties;
+ private final ReviewService service;
+ private final ReviewQueue queue;
+
+ public WebhookController(ReviewerProperties properties, ReviewService service, ReviewQueue queue) {
+ this.properties = properties;
+ this.service = service;
+ this.queue = queue;
+ }
+
+ @PostMapping("/webhook/gitea")
+ public ResponseEntity receive(@RequestHeader(value = "X-Gitea-Signature", required = false) String signature,
+ @RequestHeader(value = "X-Gitea-Event", required = false) String event,
+ @RequestBody byte[] body) {
+ 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);
+ }
+ String repo = root.path("repository").path("full_name").asString();
+ int number = root.path("pull_request").path("number").asInt();
+ String sha = root.path("pull_request").path("head").path("sha").asString();
+ queue.submit(repo + "#" + number, () -> {
+ ReviewReport report = service.review(repo, number, sha);
+ log.info("reviewed {}#{} at {}: {}", repo, number, sha.substring(0, Math.min(8, sha.length())), report);
+ });
+ return ResponseEntity.accepted().body("queued " + repo + "#" + number);
+ }
+}
diff --git a/pr-reviewer/src/main/resources/application.properties b/pr-reviewer/src/main/resources/application.properties
new file mode 100644
index 0000000..be49f7c
--- /dev/null
+++ b/pr-reviewer/src/main/resources/application.properties
@@ -0,0 +1,10 @@
+# Gitea
+reviewer.gitea-url=${GITEA_URL:http://localhost:3000}
+reviewer.gitea-token=${GITEA_TOKEN:}
+reviewer.bot-login=${GITEA_BOT_LOGIN:reviewbot}
+reviewer.webhook-secret=${GITEA_WEBHOOK_SECRET}
+
+# Model: OpenAI, or any OpenAI-compatible server. For Ollama use OPENAI_BASE_URL=http://localhost:11434/v1
+spring.ai.openai.api-key=${OPENAI_API_KEY:unused}
+spring.ai.openai.base-url=${OPENAI_BASE_URL:https://api.openai.com/v1}
+spring.ai.openai.chat.model=${OPENAI_MODEL:gpt-5.4-mini}
diff --git a/pr-reviewer/src/test/java/com/ankurm/prreviewer/CostTest.java b/pr-reviewer/src/test/java/com/ankurm/prreviewer/CostTest.java
new file mode 100644
index 0000000..54467c6
--- /dev/null
+++ b/pr-reviewer/src/test/java/com/ankurm/prreviewer/CostTest.java
@@ -0,0 +1,83 @@
+package com.ankurm.prreviewer;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.ai.chat.client.ChatClient;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * COMPUTED ESTIMATES, not bills. Token counts come from running the real prompts through JTokkit
+ * (cl100k_base); no vendor's model was called. Output length is an assumption.
+ */
+class CostTest {
+
+ /** Assumed output tokens per model call: about three findings. */
+ static final int OUTPUT_PER_CALL = 300;
+
+ /** USD per million tokens, read from the vendors' pricing pages on 2026-12-03. */
+ record Price(String model, double input, double output) {
+ double usd(long in, long out) {
+ return (in * input + out * output) / 1_000_000;
+ }
+ }
+
+ static final List PRICES = List.of(
+ new Price("Claude Haiku 5.5 (<=100k prompt)", 0.10, 0.50),
+ new Price("gpt-5-mini", 0.25, 2.00),
+ new Price("gpt-5.4-mini", 0.75, 4.50),
+ new Price("Claude Sonnet 5.5", 2.00, 10.00),
+ new Price("Claude Opus 5.5", 4.00, 20.00));
+
+ @Test
+ void estimates() throws IOException {
+ // A real change: the Java sources one commit added to this repository (20 files).
+ String large = Files.readString(Path.of("src/test/resources/sample-large.diff"));
+ var model = new ScriptedChatModel(p -> "{\"findings\":[]}");
+ var reviewer = new ModelReviewer(ChatClient.create(model));
+ var host = new FakeHost(large);
+ var service = new ReviewService(reviewer, host, new ReviewSettings("reviewbot", 6000, 100, 10, Severity.MINOR));
+
+ var first = service.review("o/r", 1, "sha-1");
+ int mark = large.indexOf("\n+", large.indexOf("\n@@")) + 1;
+ host.diff = large.substring(0, mark) + large.substring(mark).replaceFirst("\\+", "+ "); // touch one line
+ var push = service.review("o/r", 1, "sha-1");
+
+ var empty = new Chunker.Chunk("A.java", List.of(new UnifiedDiff.Line(UnifiedDiff.Type.ADDED, 0, 1, "")));
+ long overhead = reviewer.review(empty).inputTokens();
+ var small = new FakeHost(Samples.PULL_DIFF);
+ var tiny = new ReviewService(reviewer, small, ReviewServiceTest.SETTINGS).review("o/r", 1, "sha-1");
+
+ var t = new Transcript("17-cost-estimate.txt");
+ t.line("COMPUTED ESTIMATE: tokens counted with JTokkit cl100k_base on the real prompts, no paid model called.");
+ t.line("Assumed output: %d tokens per call. Prices per million tokens as read on 2026-12-03.", OUTPUT_PER_CALL);
+ t.line("");
+ t.line("fixed overhead of every call (instructions + JSON schema, empty diff): %d input tokens", overhead);
+ t.line("%-40s %6s %12s %14s", "pull request", "calls", "input tokens", "of it overhead");
+ row(t, "sample (1 file, 22 added lines)", tiny, overhead);
+ row(t, "real commit (20 files, 1004 added lines)", first, overhead);
+ row(t, "same PR, push that edits one line", push, overhead);
+ t.line("");
+ t.line("%-34s %12s %12s %16s %18s", "model", "sample PR", "20-file PR", "one-line re-push", "1000 x 20-file PR");
+ for (Price p : PRICES) {
+ t.line("%-34s %12s %12s %16s %18s", p.model(), usd(p, tiny), usd(p, first), usd(p, push),
+ "$%.2f".formatted(1000 * p.usd(first.inputTokens(), (long) first.modelCalls() * OUTPUT_PER_CALL)));
+ }
+ t.write();
+
+ assertThat(push.modelCalls()).isEqualTo(1);
+ assertThat(push.cacheHits()).isEqualTo(first.chunks() - 1);
+ }
+
+ private static void row(Transcript t, String what, ReviewReport r, long overhead) {
+ t.line("%-40s %6d %12d %13.0f%%", what, r.modelCalls(), r.inputTokens(), 100.0 * overhead * r.modelCalls() / r.inputTokens());
+ }
+
+ private static String usd(Price p, ReviewReport r) {
+ return "$%.4f".formatted(p.usd(r.inputTokens(), (long) r.modelCalls() * OUTPUT_PER_CALL));
+ }
+}
diff --git a/pr-reviewer/src/test/java/com/ankurm/prreviewer/DiffTest.java b/pr-reviewer/src/test/java/com/ankurm/prreviewer/DiffTest.java
new file mode 100644
index 0000000..0e3052d
--- /dev/null
+++ b/pr-reviewer/src/test/java/com/ankurm/prreviewer/DiffTest.java
@@ -0,0 +1,93 @@
+package com.ankurm.prreviewer;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class DiffTest {
+
+ /** Shapes taken from a real Gitea 1.27.3 diff, plus the two content lines that look like headers. */
+ static final String TRICKY = """
+ diff --git a/README.md b/README.md
+ deleted file mode 100644
+ index e5a8d0d..0000000
+ --- a/README.md
+ +++ /dev/null
+ @@ -1,2 +0,0 @@
+ -# shop
+ -
+ diff --git a/docs/my file.txt b/docs/my file.txt
+ new file mode 100644
+ index 0000000..0a207c0
+ --- /dev/null
+ +++ b/docs/my file.txt\t
+ @@ -0,0 +1,2 @@
+ +a
+ +b
+ \\ No newline at end of file
+ diff --git a/img.png b/img.png
+ new file mode 100644
+ index 0000000..c866266
+ Binary files /dev/null and b/img.png differ
+ diff --git a/q.sql b/q.sql
+ index 1111111..2222222 100644
+ --- a/q.sql
+ +++ b/q.sql
+ @@ -1,3 +1,4 @@
+ select 1;
+ --- old comment
+ +++i;
+ +select 2;
+ select 3;
+ """;
+
+ @Test
+ void parsesByHunkCounts() {
+ var files = UnifiedDiff.parse(TRICKY);
+ var t = new Transcript("01-diff-parsing.txt");
+ for (var f : files) {
+ t.line("%s deleted=%s binary=%s hunks=%d", f.path(), f.deleted(), f.binary(), f.hunks().size());
+ }
+ var sql = files.getLast();
+ t.line("");
+ t.line("lines of q.sql (old, new, type, text):");
+ sql.hunks().getFirst().lines().forEach(l -> t.line(" %3s %3s %-7s %s",
+ l.oldLine() == 0 ? "-" : l.oldLine(), l.newLine() == 0 ? "-" : l.newLine(), l.type(), l.text()));
+ var chunked = new Chunker(6000).chunk(files);
+ t.line("");
+ t.line("skipped files: %s", chunked.skippedFiles());
+ t.line("chunks sent : %s", chunked.chunks().stream().map(Chunker.Chunk::file).toList());
+ t.write();
+
+ assertThat(files).extracting(UnifiedDiff.FileDiff::path)
+ .containsExactly("README.md", "docs/my file.txt", "img.png", "q.sql");
+ assertThat(chunked.chunks().getLast().addedLines()).containsExactly(
+ java.util.Map.entry(2, "++i;"), java.util.Map.entry(3, "select 2;"));
+ assertThat(chunked.skippedFiles()).containsExactly("README.md", "img.png");
+ }
+
+ @Test
+ void splitsALargeHunkWithoutShiftingNumbers() {
+ StringBuilder body = new StringBuilder();
+ for (int i = 1; i <= 40; i++) {
+ body.append("int field").append(i).append(" = ").append(i).append(";\n");
+ }
+ var chunks = new Chunker(300).chunk(UnifiedDiff.parse(Samples.addedFile("Big.java", body.toString()))).chunks();
+ var t = new Transcript("02-chunking.txt");
+ t.line("40 added lines, limit 300 characters per chunk -> %d chunks", chunks.size());
+ for (var c : chunks) {
+ var lines = List.copyOf(c.addedLines().keySet());
+ t.line(" new-file lines %2d..%2d rendered %3d chars", lines.getFirst(), lines.getLast(), c.render().length());
+ }
+ t.line("");
+ t.line("second chunk exactly as the model sees it:");
+ t.block(chunks.get(1).render());
+ t.write();
+
+ assertThat(chunks.stream().flatMap(c -> c.addedLines().entrySet().stream()))
+ .hasSize(40).allSatisfy(e -> assertThat(e.getValue()).startsWith("int field" + e.getKey() + " "));
+ assertThat(chunks).allSatisfy(c -> assertThat(c.render().length()).isLessThanOrEqualTo(300));
+ }
+}
diff --git a/pr-reviewer/src/test/java/com/ankurm/prreviewer/FakeHost.java b/pr-reviewer/src/test/java/com/ankurm/prreviewer/FakeHost.java
new file mode 100644
index 0000000..3dd6d26
--- /dev/null
+++ b/pr-reviewer/src/test/java/com/ankurm/prreviewer/FakeHost.java
@@ -0,0 +1,56 @@
+package com.ankurm.prreviewer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** An in-memory pull request, for the tests that do not need a server. */
+class FakeHost implements GitHost {
+
+ String head = "sha-1";
+ String diff;
+ final List reviews = new ArrayList<>();
+ final List> comments = new ArrayList<>();
+ final List> posted = new ArrayList<>();
+
+ FakeHost(String diff) {
+ this.diff = diff;
+ }
+
+ @Override
+ public String headSha(String repo, int pull) {
+ return head;
+ }
+
+ @Override
+ public String diff(String repo, int pull) {
+ return diff;
+ }
+
+ @Override
+ public List reviews(String repo, int pull) {
+ return List.copyOf(reviews);
+ }
+
+ @Override
+ public List comments(String repo, int pull, long reviewId) {
+ return comments.get((int) reviewId);
+ }
+
+ @Override
+ public void deleteReview(String repo, int pull, long reviewId) {
+ reviews.removeIf(r -> r.id() == reviewId);
+ }
+
+ @Override
+ public long createReview(String repo, int pull, String sha, String body, List inline) {
+ posted.add(inline);
+ return add("reviewbot", "COMMENT", inline.stream().map(c -> new Comment("reviewbot", c.body())).toList());
+ }
+
+ long add(String author, String state, List content) {
+ long id = comments.size();
+ comments.add(content);
+ reviews.add(new Review(id, state, author));
+ return id;
+ }
+}
diff --git a/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaAdmin.java b/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaAdmin.java
new file mode 100644
index 0000000..cba8674
--- /dev/null
+++ b/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaAdmin.java
@@ -0,0 +1,137 @@
+package com.ankurm.prreviewer;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+import java.io.IOException;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+
+/** Test-side helper that plays the humans: creates repositories, pushes commits, opens pull requests. */
+class GiteaAdmin {
+
+ static final String URL = System.getenv("GITEA_URL");
+ static final String DEV = System.getenv("GITEA_DEV_TOKEN");
+ static final String BOT = System.getenv("GITEA_BOT_TOKEN");
+
+ record Answer(int status, JsonNode json, String text) {}
+
+ private final JsonMapper mapper = JsonMapper.builder().build();
+ private final HttpClient http = HttpClient.newBuilder().proxy(ProxySelector.of(null)).build();
+
+ GiteaAdmin() {
+ if (URL == null || !(URL.contains("localhost") || URL.contains("127.0.0.1"))) {
+ throw new IllegalStateException("these tests create repositories; point GITEA_URL at a local throwaway Gitea");
+ }
+ }
+
+ Answer call(String token, String method, String path, Object body) {
+ try {
+ var req = HttpRequest.newBuilder(URI.create(URL + "/api/v1" + path))
+ .header("Authorization", "token " + token).header("Content-Type", "application/json")
+ .method(method, body == null ? HttpRequest.BodyPublishers.noBody()
+ : HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body)))
+ .build();
+ var res = http.send(req, HttpResponse.BodyHandlers.ofString());
+ String text = res.body();
+ JsonNode node = text.startsWith("{") || text.startsWith("[") ? mapper.readTree(text) : null;
+ return new Answer(res.statusCode(), node, text);
+ } catch (IOException | InterruptedException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private Answer ok(String method, String path, Object body) {
+ Answer a = call(DEV, method, path, body);
+ if (a.status() >= 300) {
+ throw new IllegalStateException(method + " " + path + " -> " + a.status() + " " + a.text());
+ }
+ return a;
+ }
+
+ /** A new public repository (public so the test can read the web pages) with the bot as collaborator. */
+ String repo(String prefix) {
+ String name = prefix + "-" + System.nanoTime() % 1_000_000;
+ ok("POST", "/user/repos", Map.of("name", name, "auto_init", true, "default_branch", "main"));
+ ok("PUT", "/repos/dev/" + name + "/collaborators/reviewbot", Map.of("permission", "write"));
+ return "dev/" + name;
+ }
+
+ void create(String repo, String path, String content, String branch, String newBranch) {
+ ok("POST", "/repos/" + repo + "/contents/" + path, newBranch == null
+ ? Map.of("content", b64(content), "branch", branch, "message", "add " + path)
+ : Map.of("content", b64(content), "branch", branch, "new_branch", newBranch, "message", "add " + path));
+ }
+
+ void update(String repo, String path, String content, String branch, String newBranch) {
+ String sha = ok("GET", "/repos/" + repo + "/contents/" + path + "?ref=" + branch, null).json().path("sha").asString();
+ ok("PUT", "/repos/" + repo + "/contents/" + path, newBranch == null
+ ? Map.of("content", b64(content), "sha", sha, "branch", branch, "message", "change " + path)
+ : Map.of("content", b64(content), "sha", sha, "branch", branch, "new_branch", newBranch, "message", "change " + path));
+ }
+
+ int openPull(String repo, String head) {
+ return ok("POST", "/repos/" + repo + "/pulls", Map.of("head", head, "base", "main", "title", "Change " + head))
+ .json().path("number").asInt();
+ }
+
+ String headSha(String repo, int pull) {
+ return ok("GET", "/repos/" + repo + "/pulls/" + pull, null).json().path("head").path("sha").asString();
+ }
+
+ String diff(String repo, int pull) {
+ return ok("GET", "/repos/" + repo + "/pulls/" + pull + ".diff", null).text();
+ }
+
+ void hook(String repo, String url, String secret) {
+ ok("POST", "/repos/" + repo + "/hooks", Map.of("type", "gitea", "active", true,
+ "events", List.of("pull_request"),
+ "config", Map.of("url", url, "content_type", "json", "secret", secret)));
+ }
+
+ List reviews(String repo, int pull, String token) {
+ return call(token, "GET", "/repos/" + repo + "/pulls/" + pull + "/reviews?limit=50", null).json().valueStream().toList();
+ }
+
+ List comments(String repo, int pull, long review, String token) {
+ return call(token, "GET", "/repos/" + repo + "/pulls/" + pull + "/reviews/" + review + "/comments", null)
+ .json().valueStream().toList();
+ }
+
+ String webPage(String path) {
+ try {
+ return http.send(HttpRequest.newBuilder(URI.create(URL + path)).build(), HttpResponse.BodyHandlers.ofString()).body();
+ } catch (IOException | InterruptedException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ static int count(String haystack, String needle) {
+ return haystack.split(java.util.regex.Pattern.quote(needle), -1).length - 1;
+ }
+
+ private static String b64(String s) {
+ return Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
+ }
+
+ /** package shop; class Cart with thirty fields, a file long enough to have lines outside any hunk. */
+ static String cart(List inserts) {
+ StringBuilder sb = new StringBuilder("package shop;\n\npublic class Cart {\n");
+ for (int i = 1; i <= 30; i++) {
+ sb.append(" int field").append(i).append(";\n");
+ }
+ List lines = new java.util.ArrayList<>(sb.append("}\n").toString().lines().toList());
+ for (String insert : inserts) { // "7:code" inserts code so that it becomes line 7
+ int colon = insert.indexOf(':');
+ lines.add(Integer.parseInt(insert.substring(0, colon)) - 1, insert.substring(colon + 1));
+ }
+ return String.join("\n", lines) + "\n";
+ }
+}
diff --git a/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaLiveTest.java b/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaLiveTest.java
new file mode 100644
index 0000000..d8eed35
--- /dev/null
+++ b/pr-reviewer/src/test/java/com/ankurm/prreviewer/GiteaLiveTest.java
@@ -0,0 +1,321 @@
+package com.ankurm.prreviewer;
+
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
+import org.springframework.ai.chat.model.ChatModel;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.context.ApplicationContextInitializer;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import org.slf4j.LoggerFactory;
+
+import com.sun.net.httpserver.HttpServer;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+
+import static com.ankurm.prreviewer.GiteaAdmin.*;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Runs against a real, local, throwaway Gitea started by {@code scripts/gitea-up.sh}. */
+@EnabledIfEnvironmentVariable(named = "GITEA_URL", matches = "http://(localhost|127\\.0\\.0\\.1).*")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class GiteaLiveTest {
+
+ private final GiteaAdmin gitea = new GiteaAdmin();
+
+ /** Cart.java with two added lines, at 7 and 26, on branch "feature". */
+ private String cartPull(String repo) {
+ gitea.create(repo, "src/Cart.java", cart(List.of()), "main", null);
+ gitea.update(repo, "src/Cart.java",
+ cart(List.of("7: String password = \"hunter2\";", "26: void pay() { System.out.println(\"pay\"); }")),
+ "main", "feature");
+ gitea.openPull(repo, "feature");
+ return repo;
+ }
+
+ private GiteaAdmin.Answer review(String repo, String sha, Object... lineAndBody) {
+ List