Add pr-reviewer module: Gitea webhooks, Spring AI structured output, quote-checked inline comments, de-duplication across pushes and live tests against Gitea 1.27.3 on Spring AI 2.1.0

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
This commit is contained in:
Claude
2026-12-04 07:49:36 +05:30
parent 38c9ca8452
commit 8fa3c5d682
74 changed files with 4794 additions and 0 deletions
@@ -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<Price> 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));
}
}
@@ -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));
}
}
@@ -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<Review> reviews = new ArrayList<>();
final List<List<Comment>> comments = new ArrayList<>();
final List<List<InlineComment>> 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<Review> reviews(String repo, int pull) {
return List.copyOf(reviews);
}
@Override
public List<Comment> 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<InlineComment> 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<Comment> content) {
long id = comments.size();
comments.add(content);
reviews.add(new Review(id, state, author));
return id;
}
}
@@ -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<JsonNode> reviews(String repo, int pull, String token) {
return call(token, "GET", "/repos/" + repo + "/pulls/" + pull + "/reviews?limit=50", null).json().valueStream().toList();
}
List<JsonNode> 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<String> 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<String> 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";
}
}
@@ -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<Map<String, Object>> comments = new ArrayList<>();
for (int i = 0; i < lineAndBody.length; i += 3) {
comments.add(Map.of("path", lineAndBody[i], "new_position", lineAndBody[i + 1], "body", lineAndBody[i + 2]));
}
return gitea.call(BOT, "POST", "/repos/" + repo + "/pulls/1/reviews",
Map.of("commit_id", sha, "event", "COMMENT", "body", "probe", "comments", comments));
}
@Test
@Order(1)
void whatGiteaAcceptsAsACommentPosition() {
String repo = cartPull(gitea.repo("accept"));
String sha = gitea.headSha(repo, 1);
var t = new Transcript("11-gitea-accepts.txt");
t.line("the diff:");
t.block(gitea.diff(repo, 1));
t.line("");
t.line("one review per row, one inline comment each (Gitea %s)",
gitea.call(DEV, "GET", "/version", null).json().path("version").asString());
record Row(String what, String path, int line, String marker) {}
var rows = List.of(
new Row("an added line", "src/Cart.java", 7, "probe-added"),
new Row("a context line", "src/Cart.java", 8, "probe-context"),
new Row("a line outside every hunk", "src/Cart.java", 15, "probe-outside"),
new Row("a file that does not exist", "src/Nope.java", 3, "probe-nofile"),
new Row("line 0", "src/Cart.java", 0, "probe-zero"),
new Row("a line past the end of the file", "src/Cart.java", 9999, "probe-past"));
List<Integer> status = new ArrayList<>();
for (Row r : rows) {
status.add(review(repo, sha, r.path(), r.line(), r.marker()).status());
}
String conversation = gitea.webPage("/" + repo + "/pulls/1");
String files = gitea.webPage("/" + repo + "/pulls/1/files");
t.line("%-33s %5s %4s %-18s %s", "comment on", "line", "HTTP", "shown: conversation", "shown: files changed");
for (int i = 0; i < rows.size(); i++) {
String p = "<p dir=\"auto\">" + rows.get(i).marker() + "</p>";
t.line("%-33s %5d %4d %-18s %s", rows.get(i).what(), rows.get(i).line(), status.get(i),
count(conversation, p) > 0 ? "yes" : "no", count(files, p) > 0 ? "yes" : "no");
}
var pending = gitea.reviews(repo, 1, BOT).stream().filter(r -> r.path("state").asString().equals("PENDING")).count();
t.line("PENDING reviews left behind by those calls: %d", pending);
t.write();
assertThat(status).containsExactly(200, 200, 200, 200, 200, 500);
}
private void dump(Transcript t, String repo) {
for (var r : gitea.reviews(repo, 1, BOT)) {
t.line(" review %-8s body=%-8s comments: %s", r.path("state").asString(),
'"' + r.path("body").asString() + '"',
gitea.comments(repo, 1, r.path("id").asLong(), BOT).stream()
.map(c -> c.path("body").asString() + "@" + c.path("position").asInt()).toList());
}
}
@Test
@Order(2)
void oneBadLineLeavesAPendingReviewBehind() {
String repo = cartPull(gitea.repo("pending"));
String sha = gitea.headSha(repo, 1);
var t = new Transcript("12-gitea-pending-review.txt");
Object[] batch = {"src/Cart.java", 7, "good-A", "src/Cart.java", 9999, "ghost", "src/Cart.java", 26, "good-B"};
for (int i = 1; i <= 3; i++) {
t.line("POST review [good-A@7, ghost@9999, good-B@26], attempt %d -> HTTP %d", i, review(repo, sha, batch).status());
}
t.line("reviews as the bot sees them now:");
dump(t, repo);
var next = review(repo, sha, "src/Cart.java", 26, "unrelated");
t.line("");
t.line("POST review [unrelated@26] -> HTTP %d", next.status());
t.line("reviews now:");
dump(t, repo);
var published = gitea.comments(repo, 1, next.json().path("id").asLong(), BOT);
assertThat(published).extracting(c -> c.path("body").asString())
.containsExactlyInAnyOrder("good-A", "good-A", "good-A", "unrelated");
// The same leftover, but the next writer is our service: it clears pending reviews first.
String repo2 = cartPull(gitea.repo("cleanup"));
review(repo2, gitea.headSha(repo2, 1), batch);
t.line("");
t.line("second repository, same failed batch once, then ReviewService.review():");
var service = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(ScriptedChatModel.ruleBased())),
new GiteaClient(URL, BOT), ReviewServiceTest.SETTINGS);
service.review(repo2, 1, gitea.headSha(repo2, 1));
for (var r : gitea.reviews(repo2, 1, BOT)) {
var bodies = gitea.comments(repo2, 1, r.path("id").asLong(), BOT).stream()
.map(c -> c.path("body").asString().lines().findFirst().orElse("") + " @" + c.path("position").asInt()).toList();
t.line(" review %s", r.path("state").asString());
bodies.forEach(b -> t.line(" %s", b));
assertThat(bodies).noneMatch(b -> b.startsWith("good-A"));
}
t.write();
}
@Test
@Order(3)
void anOldCommitIdDoesNotPinTheLine() {
String repo = cartPull(gitea.repo("stale"));
String old = gitea.headSha(repo, 1);
gitea.update(repo, "src/Cart.java", cart(List.of("4: // one", "5: // two", "6: // three", "7: // four",
"11: String password = \"hunter2\";", "30: void pay() { System.out.println(\"pay\"); }")), "feature", null);
var t = new Transcript("13-gitea-stale-commit.txt");
t.line("commit A adds the password on line 7. commit B then inserts four comment lines above it.");
var answer = review(repo, old, "src/Cart.java", 7, "about the password");
t.line("POST review with commit_id=A, new_position=7 -> HTTP %d, review stale=%s", answer.status(),
answer.json().path("stale").asBoolean());
var c = gitea.comments(repo, 1, answer.json().path("id").asLong(), BOT).getFirst();
t.line("diff_hunk Gitea attached to the comment:");
t.block(c.path("diff_hunk").asString());
t.write();
assertThat(c.path("diff_hunk").asString()).contains("// four").doesNotContain("password");
}
@Test
@Order(4)
void endToEndThroughARealWebhook() throws Exception {
var model = ScriptedChatModel.ruleBased();
ApplicationContextInitializer<GenericApplicationContext> scripted =
ctx -> ctx.registerBean(ChatModel.class, () -> model);
var logs = new ListAppender<ILoggingEvent>();
try (ConfigurableApplicationContext app = new SpringApplicationBuilder(ReviewerApplication.class)
.initializers(scripted)
.run("--server.port=0", "--spring.ai.model.chat=none", "--reviewer.gitea-url=" + URL,
"--reviewer.gitea-token=" + BOT, "--reviewer.webhook-secret=s3cret")) {
logs.start();
((Logger) LoggerFactory.getLogger(WebhookController.class)).addAppender(logs);
int port = app.getEnvironment().getProperty("local.server.port", Integer.class);
String repo = gitea.repo("e2e");
gitea.create(repo, "src/UserDao.java", Samples.BASE, "main", null);
gitea.hook(repo, "http://" + System.getenv("WEBHOOK_HOST") + ":" + port + "/webhook/gitea", "s3cret");
var t = new Transcript("14-end-to-end.txt");
gitea.update(repo, "src/UserDao.java", Samples.FEATURE, "main", "feature");
gitea.openPull(repo, "feature");
t.line("1. pull request opened -> %s", outcome(logs, 1));
String shifted = "// Copyright\n// All rights reserved\n" + Samples.FEATURE;
gitea.update(repo, "src/UserDao.java", shifted, "feature", null);
t.line("2. push: two lines on top -> %s", outcome(logs, 2));
gitea.update(repo, "src/UserDao.java", shifted.replace(" return role == \"admin\";",
" System.out.println(role);\n return role == \"admin\";"), "feature", null);
t.line("3. push: one new problem -> %s", outcome(logs, 3));
t.line("");
t.line("inline comments on the pull request, read back from Gitea:");
List<String> bodies = new ArrayList<>();
for (var r : gitea.reviews(repo, 1, DEV)) {
t.line(" review by %s, state %s, stale=%s", r.path("user").path("login").asString(),
r.path("state").asString(), r.path("stale").asBoolean());
for (var c : gitea.comments(repo, 1, r.path("id").asLong(), DEV)) {
bodies.add(c.path("body").asString());
t.line(" %s:%d %s", c.path("path").asString(), c.path("position").asInt(),
c.path("body").asString().lines().findFirst().orElse(""));
}
}
t.line("");
t.line("first comment body as stored:");
t.block(bodies.getFirst());
String page = gitea.webPage("/" + repo + "/pulls/1");
t.line("");
// Gitea keeps the raw markdown of every comment in a hidden div for its edit box.
String visible = page.replaceAll("(?s)<div id=\"issuecomment-\\d+-raw\" class=\"raw-content tw-hidden\">.*?</div>", "");
t.line("conversation page: marker in the hidden raw-markdown blocks %d time(s), in the rendered comments %d time(s)",
count(page, "&lt;!-- pr-reviewer:") - count(visible, "&lt;!-- pr-reviewer:"),
count(visible, "pr-reviewer:"));
t.write();
assertThat(bodies).hasSize(3);
} finally {
((Logger) LoggerFactory.getLogger(WebhookController.class)).detachAppender(logs);
}
}
/** Waits for the n-th "reviewed ..." log line and summarises its report. */
private static String outcome(ListAppender<ILoggingEvent> logs, int n) throws InterruptedException {
for (int i = 0; i < 300; i++) {
var done = new ArrayList<>(logs.list).stream().filter(e -> e.getMessage().startsWith("reviewed")).toList();
if (done.size() >= n) {
ReviewReport r = (ReviewReport) done.get(n - 1).getArgumentArray()[3];
return "%-11s posted %d, already there %d".formatted(r.status(), r.posted().size(),
r.dropped().stream().filter(d -> d.reason().equals("ALREADY_POSTED")).count());
}
Thread.sleep(100);
}
throw new AssertionError("no review " + n);
}
@Test
@Order(5)
void failedAndSlowDeliveriesAreNotRetried() throws IOException, InterruptedException {
List<String> seen = new CopyOnWriteArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 0), 0);
long start = System.nanoTime();
server.createContext("/", exchange -> {
exchange.getRequestBody().readAllBytes();
String path = exchange.getRequestURI().getPath();
seen.add(path);
if (path.equals("/slow")) {
try {
Thread.sleep(8_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
try {
exchange.sendResponseHeaders(path.equals("/fail") ? 500 : 202, -1);
} catch (IOException ignored) {
// Gitea has hung up by now
}
exchange.close();
});
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
try {
String repo = gitea.repo("delivery");
String base = "http://" + System.getenv("WEBHOOK_HOST") + ":" + server.getAddress().getPort();
gitea.hook(repo, base + "/fail", "s");
gitea.hook(repo, base + "/slow", "s");
cartPull(repo);
Thread.sleep(60_000);
var t = new Transcript("15-delivery-not-retried.txt");
t.line("one pull request opened, two webhooks, 60 seconds of waiting");
t.line("receiver that answers 500 : %d request(s) received", seen.stream().filter("/fail"::equals).count());
t.line("receiver that answers after 8 seconds: %d request(s) received", seen.stream().filter("/slow"::equals).count());
t.write();
assertThat(seen).containsExactlyInAnyOrder("/fail", "/slow");
} finally {
server.stop(0);
}
}
@Test
@Order(6)
void whereTheTimeGoes() {
String repo = gitea.repo("latency");
StringBuilder file = new StringBuilder("class C%d {\n");
for (int i = 0; i < 100; i++) {
file.append(i % 25 == 0 ? " void f" + i + "() { System.out.println(" + i + "); }\n" : " int field" + i + " = " + i + ";\n");
}
file.append("}\n");
gitea.create(repo, "README2.md", "x\n", "main", "feature");
for (int i = 0; i < 8; i++) {
gitea.create(repo, "src/C" + i + ".java", file.toString().formatted(i), "feature", null);
}
gitea.openPull(repo, "feature");
var settings = new ReviewSettings("reviewbot", 6000, 20, 100, Severity.MINOR);
var model = ScriptedChatModel.ruleBased();
var t = new Transcript("16-pipeline-latency.txt");
t.line("8 new files, 102 lines each; local Gitea; the model is scripted and answers instantly");
t.line("%-34s %6s %6s %6s %6s %6s %6s", "run", "chunks", "posted", "fetch", "model", "dedup", "post");
String sha = gitea.headSha(repo, 1);
for (int run = 1; run <= 5; run++) {
var r = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(model)),
new GiteaClient(URL, BOT), settings).review(repo, 1, sha);
t.line("%-34s %6d %6d %4dms %4dms %4dms %4dms", "run " + run + (run == 1 ? " (cold JVM paths)" : ""),
r.chunks(), r.posted().size(), r.timings().fetch(), r.timings().model(), r.timings().dedup(), r.timings().post());
}
// De-duplication reads every earlier review with one request each.
for (int i = 0; i < 60; i++) {
review(repo, sha, "src/C0.java", 2, "older review " + i);
}
var client = new GiteaClient(URL, BOT);
var service = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(model)), client, settings);
long reviews = client.reviews(repo, 1).size();
service.review(repo, 1, sha);
var r = service.review(repo, 1, sha);
assertThat(reviews).isGreaterThan(50); // more than one page
assertThat(r.posted()).isEmpty();
t.line("");
t.line("after %d reviews on the pull request: dedup phase %d ms (one request per review)", reviews, r.timings().dedup());
t.write();
}
}
@@ -0,0 +1,39 @@
package com.ankurm.prreviewer;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.ankurm.prreviewer.LineGuard.Outcome.*;
import static org.assertj.core.api.Assertions.assertThat;
class LineGuardTest {
private record Case(String what, int line, String quote, LineGuard.Outcome expected, int expectedLine) {}
@Test
void numberAndQuoteMustAgree() {
var chunk = new Chunker(6000).chunk(UnifiedDiff.parse(Samples.PULL_DIFF)).chunks().getFirst();
String pw = "String password = \"hunter2\";";
var cases = List.of(
new Case("right line, right quote", 7, pw, ACCEPTED, 7),
new Case("right line, partial quote", 14, "role == \"admin\"", ACCEPTED, 14),
new Case("off by two, quote is real", 9, pw, RELOCATED, 7),
new Case("line past the end of the file", 9999, pw, RELOCATED, 7),
new Case("line past the end, invented code", 9999, "new ObjectInputStream(in)", NOT_AN_ADDED_LINE, 9999),
new Case("context line", 6, "private final Connection db;", NOT_AN_ADDED_LINE, 6),
new Case("real line number, invented code", 7, "Runtime.getRuntime().exec(cmd);", QUOTE_NOT_FOUND, 7),
new Case("wrong line, quote on several lines", 99, "public int average(int[] scores) {".substring(0, 0) + "}", AMBIGUOUS_QUOTE, 99),
new Case("too short to be a partial quote", 14, "role", QUOTE_NOT_FOUND, 14),
new Case("no quote at all", 7, "", NO_QUOTE, 7));
var t = new Transcript("05-line-guard.txt");
t.line("%-36s %5s %-18s %s", "case", "model", "verdict", "posted on");
for (var c : cases) {
var v = LineGuard.check(new Finding(c.line, c.quote, Severity.MAJOR, Category.BUG, "t", "c", ""), chunk);
t.line("%-36s %5d %-18s %s", c.what, c.line, v.outcome(), v.postable() ? "line " + v.line() : "nowhere");
assertThat(v.outcome()).as(c.what).isEqualTo(c.expected);
assertThat(v.line()).as(c.what).isEqualTo(c.expectedLine);
}
t.write();
}
}
@@ -0,0 +1,59 @@
package com.ankurm.prreviewer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
/**
* The same pipeline in front of a real model behind an OpenAI-compatible endpoint. A model's answers
* differ from run to run, so this test records and asserts nothing about them.
*/
@EnabledIfEnvironmentVariable(named = "LLM_URL", matches = "http.*")
class LlmLiveTest {
@Test
void realModelOnTheSamplePullRequest() {
String model = System.getenv("LLM_MODEL");
try (var app = new SpringApplicationBuilder(ReviewerApplication.class).web(WebApplicationType.NONE)
.run("--spring.ai.openai.base-url=" + System.getenv("LLM_URL"),
"--spring.ai.openai.chat.model=" + model,
"--spring.ai.openai.chat.temperature=0.2",
"--spring.ai.openai.timeout=600s",
"--reviewer.webhook-secret=unused")) {
var reviewer = app.getBean(ModelReviewer.class);
var chunk = new Chunker(6000).chunk(UnifiedDiff.parse(Samples.PULL_DIFF)).chunks().getFirst();
var t = new Transcript("18-real-model-" + model.replaceAll("[^a-z0-9.]+", "-") + ".txt");
t.line("model %s on a local CPU (2 vCPU), temperature 0.2, the sample pull request, 5 independent runs", model);
int findings = 0, accepted = 0, relocated = 0, wrongNumber = 0;
for (int run = 1; run <= 5; run++) {
ModelReviewer.Reply reply;
try {
reply = reviewer.review(chunk);
} catch (ModelReviewer.ModelFailure e) {
t.line("");
t.line("run %d: NO USABLE ANSWER after %d call(s), %.0f s: %s", run, e.spent.modelCalls(),
e.spent.nanos() / 1e9, e.getMessage().lines().findFirst().orElse(""));
continue;
}
t.line("");
t.line("run %d: %d call(s), %d input + %d output tokens, %.0f s", run, reply.modelCalls(),
reply.inputTokens(), reply.outputTokens(), reply.nanos() / 1e9);
for (Finding f : reply.findings()) {
var v = LineGuard.check(f, chunk);
findings++;
if (v.outcome() == LineGuard.Outcome.ACCEPTED) accepted++;
if (v.outcome() == LineGuard.Outcome.RELOCATED) relocated++;
if (v.line() != f.line() || !chunk.addedLines().containsKey(f.line())) wrongNumber++;
t.line(" model line %3d %-18s -> %s %s %s", f.line(), v.outcome(),
v.postable() ? "post on " + v.line() : "dropped", f.severity(), f.title());
t.line(" quote: %s", String.valueOf(f.quote()).replace("\n", "\\n"));
}
}
t.line("");
t.line("totals: %d findings, %d accepted as claimed, %d moved to another line, %d dropped",
findings, accepted, relocated, findings - accepted - relocated);
t.write();
}
}
}
@@ -0,0 +1,154 @@
package com.ankurm.prreviewer;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class ReviewServiceTest {
static final ReviewSettings SETTINGS = new ReviewSettings("reviewbot", 6000, 20, 10, Severity.MINOR);
static ReviewService service(ScriptedChatModel model, FakeHost host, ReviewSettings s) {
return new ReviewService(new ModelReviewer(ChatClient.create(model)), host, s);
}
static String diff(String... added) {
return Samples.addedFile("src/A.java", String.join("\n", added) + "\n");
}
static void print(Transcript t, String label, ReviewReport r) {
t.line("%-44s %-11s modelCalls=%d cacheHits=%d posted=%s dropped=%s", label, r.status(), r.modelCalls(), r.cacheHits(),
r.posted().stream().map(p -> "line " + p.line()).toList(),
r.dropped().stream().map(d -> "line " + d.line() + " " + d.reason()).toList());
}
@Test
void doesNotRepeatItselfAfterAPush() {
var host = new FakeHost(diff("class A {", " String password = \"hunter2\";", "}"));
var model = ScriptedChatModel.ruleBased();
var service = service(model, host, SETTINGS);
var t = new Transcript("06-dedup.txt");
var first = service.review("o/r", 1, "sha-1");
print(t, "first push", first);
var redelivered = service.review("o/r", 1, "sha-1");
print(t, "same event delivered again", redelivered);
host.head = "sha-2";
host.diff = diff("// licence header", "// more header", "class A {", " String password = \"hunter2\";", "}");
var shifted = service.review("o/r", 1, "sha-2");
print(t, "push moves the line from 2 to 4", shifted);
var restarted = service(model, host, SETTINGS).review("o/r", 1, "sha-2");
print(t, "bot restarted, empty cache", restarted);
host.head = "sha-3";
host.diff = diff("class A {", " String password = \"hunter2\";",
" void f() { System.out.println(1); }", "}");
var added = service.review("o/r", 1, "sha-3");
print(t, "push adds a second problem", added);
t.write();
assertThat(first.posted()).hasSize(1);
assertThat(redelivered.posted()).isEmpty();
assertThat(shifted.posted()).isEmpty();
assertThat(restarted.posted()).isEmpty();
assertThat(added.posted()).singleElement().extracting(ReviewReport.Posted::line).isEqualTo(3);
assertThat(host.posted).hasSize(2);
}
@Test
void identicalLinesAreSeparateAndMovedChunksAreReused() {
var t = new Transcript("07-cache-and-copies.txt");
var host = new FakeHost(diff("System.out.println(\"x\");", "int a;", "System.out.println(\"x\");"));
var model = ScriptedChatModel.ruleBased();
var service = service(model, host, SETTINGS);
var first = service.review("o/r", 1, "sha-1");
print(t, "two identical added lines", first);
// Same code, every line five further down: a different diff, the same content.
host.diff = host.diff.replace("@@ -0,0 +1,3 @@", "@@ -0,0 +6,3 @@");
var moved = service.review("o/r", 1, "sha-1");
print(t, "identical code, shifted by five lines", moved);
t.write();
assertThat(first.posted()).extracting(ReviewReport.Posted::line).containsExactly(1, 3);
assertThat(moved.cacheHits()).isEqualTo(1);
assertThat(moved.modelCalls()).isZero();
assertThat(moved.dropped()).extracting(ReviewReport.Dropped::line).containsExactly(6, 8);
assertThat(moved.dropped()).extracting(ReviewReport.Dropped::reason).containsOnly("ALREADY_POSTED");
}
@Test
void limitsAndFailures() {
var t = new Transcript("08-limits-and-failures.txt");
String two = diff("String password = \"a1\";", "System.out.println(1);", "System.out.println(2);")
+ Samples.addedFile("src/B.java", "System.out.println(3);\n");
var cappedService = service(ScriptedChatModel.ruleBased(), new FakeHost(two),
new ReviewSettings("reviewbot", 6000, 20, 2, Severity.MINOR));
var capped = cappedService.review("o/r", 1, "sha-1");
print(t, "comment cap 2, worst first", capped);
var again = cappedService.review("o/r", 1, "sha-1");
print(t, "same event again, cap already used up", again);
var strict = service(ScriptedChatModel.ruleBased(), new FakeHost(two),
new ReviewSettings("reviewbot", 6000, 20, 10, Severity.MAJOR)).review("o/r", 1, "sha-1");
print(t, "minimum severity MAJOR", strict);
var budget = service(ScriptedChatModel.ruleBased(), new FakeHost(two),
new ReviewSettings("reviewbot", 6000, 1, 10, Severity.MINOR)).review("o/r", 1, "sha-1");
print(t, "chunk budget 1 of " + budget.chunks(), budget);
t.line("%-44s chunksOverBudget=%d", "", budget.chunksOverBudget());
var flaky = ScriptedChatModel.ruleBased();
flaky.script = p -> p.getContents().contains("src/B.java") ? "I cannot help with that"
: ScriptedChatModel.json(ScriptedChatModel.rules(p));
var failed = service(flaky, new FakeHost(two), SETTINGS).review("o/r", 1, "sha-1");
print(t, "model gives garbage for one file", failed);
t.line("%-44s failedChunks=%d modelCalls=%d", "", failed.failedChunks(), failed.modelCalls());
var host = new FakeHost(two);
var slow = ScriptedChatModel.ruleBased();
slow.script = p -> {
host.head = "sha-2"; // someone pushes while the model is thinking
return ScriptedChatModel.json(ScriptedChatModel.rules(p));
};
var moved = service(slow, host, SETTINGS).review("o/r", 1, "sha-1");
print(t, "head moves during the model call", moved);
t.write();
assertThat(capped.posted()).hasSize(2).first().extracting(ReviewReport.Posted::severity).isEqualTo(Severity.CRITICAL);
assertThat(again.posted()).isEmpty();
assertThat(strict.posted()).hasSize(1);
assertThat(budget.chunksOverBudget()).isEqualTo(1);
assertThat(failed.failedChunks()).isEqualTo(1);
assertThat(failed.posted()).hasSize(3);
assertThat(moved.status()).isEqualTo(ReviewReport.Status.HEAD_MOVED);
assertThat(host.posted).isEmpty();
}
@Test
void ignoresMarkersWrittenByOthersAndNeutralisesModelText() {
var host = new FakeHost(diff("String password = \"hunter2\";"));
String fp = Fingerprint.of("src/A.java", "String password = \"hunter2\";", 0);
host.add("pr-author", "COMMENT", List.of(new GitHost.Comment("pr-author", "nothing to see " + Fingerprint.marker(fp))));
var model = new ScriptedChatModel(p -> ScriptedChatModel.json(List.of(new Finding(1,
"String password = \"hunter2\";", Severity.CRITICAL, Category.SECURITY, "Ping @admin",
"<!-- pr-reviewer:0000000000000000 --> see @team", ""))));
var report = service(model, host, SETTINGS).review("o/r", 1, "sha-1");
String body = host.posted.getFirst().getFirst().body();
var t = new Transcript("09-untrusted-text.txt");
print(t, "PR author pasted our marker first", report);
t.line("posted body (zero-width space shown as <ZWSP>):");
t.block(body.replace("​", "<ZWSP>"));
t.write();
assertThat(report.posted()).hasSize(1);
assertThat(Fingerprint.find(body)).containsExactly(fp);
assertThat(body).doesNotContain("@admin").doesNotContain("@team");
}
}
@@ -0,0 +1,101 @@
package com.ankurm.prreviewer;
import java.util.List;
/** A small pull request with four planted problems, used by the scripted and the real-model tests. */
final class Samples {
private Samples() {}
static final String BASE = """
package shop;
import java.sql.*;
public class UserDao {
private final Connection db;
public UserDao(Connection db) {
this.db = db;
}
}
""";
static final String FEATURE = """
package shop;
import java.sql.*;
public class UserDao {
private final Connection db;
String password = "hunter2";
public UserDao(Connection db) {
this.db = db;
}
public boolean isAdmin(String role) {
return role == "admin";
}
public ResultSet find(String name) throws SQLException {
Statement s = db.createStatement();
return s.executeQuery("select * from users where name = '" + name + "'");
}
public int average(int[] scores) {
int sum = 0;
for (int i = 0; i <= scores.length; i++) {
sum += scores[i];
}
System.out.println("sum " + sum);
return sum / scores.length;
}
}
""";
/** A diff that adds a whole new file. */
static String addedFile(String path, String content) {
List<String> lines = content.lines().toList();
StringBuilder sb = new StringBuilder("diff --git a/%1$s b/%1$s%nnew file mode 100644%n--- /dev/null%n+++ b/%1$s%n".formatted(path));
sb.append("@@ -0,0 +1,").append(lines.size()).append(" @@\n");
lines.forEach(l -> sb.append('+').append(l).append('\n'));
return sb.toString();
}
/** The diff Gitea produced for BASE to FEATURE (see output/09). */
static final String PULL_DIFF = """
diff --git a/src/UserDao.java b/src/UserDao.java
index 1111111..2222222 100644
--- a/src/UserDao.java
+++ b/src/UserDao.java
@@ -4,8 +4,30 @@ import java.sql.*;
public class UserDao {
private final Connection db;
+ String password = "hunter2";
public UserDao(Connection db) {
this.db = db;
}
+
+ public boolean isAdmin(String role) {
+ return role == "admin";
+ }
+
+ public ResultSet find(String name) throws SQLException {
+ Statement s = db.createStatement();
+ return s.executeQuery("select * from users where name = '" + name + "'");
+ }
+
+ public int average(int[] scores) {
+ int sum = 0;
+ for (int i = 0; i <= scores.length; i++) {
+ sum += scores[i];
+ }
+ System.out.println("sum " + sum);
+ return sum / scores.length;
+ }
}
""";
}
@@ -0,0 +1,75 @@
package com.ankurm.prreviewer;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.metadata.ChatResponseMetadata;
import org.springframework.ai.chat.metadata.DefaultUsage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.tokenizer.JTokkitTokenCountEstimator;
import tools.jackson.databind.json.JsonMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Not a language model: a stand-in that reads the numbered diff out of the prompt and answers with
* JSON. Token usage is counted from the real prompt text with JTokkit (cl100k_base).
*/
class ScriptedChatModel implements ChatModel {
static final JsonMapper JSON = JsonMapper.builder().build();
static final JTokkitTokenCountEstimator TOKENS = new JTokkitTokenCountEstimator();
private static final Pattern ADDED = Pattern.compile("(?m)^\\s*(\\d+) \\+ (.*)$");
final List<Prompt> prompts = new CopyOnWriteArrayList<>();
volatile Function<Prompt, String> script;
ScriptedChatModel(Function<Prompt, String> script) {
this.script = script;
}
/** Flags a handful of patterns, on the line where they really are. */
static ScriptedChatModel ruleBased() {
return new ScriptedChatModel(prompt -> json(rules(prompt)));
}
static List<Finding> rules(Prompt prompt) {
List<Finding> found = new ArrayList<>();
Matcher m = ADDED.matcher(prompt.getContents());
while (m.find()) {
int line = Integer.parseInt(m.group(1));
String code = m.group(2).strip();
if (code.contains("password = \"")) {
found.add(new Finding(line, code, Severity.CRITICAL, Category.SECURITY, "Hard-coded password",
"A credential in source control is readable by everyone with the repository.",
"String password = System.getenv(\"DB_PASSWORD\");"));
} else if (code.contains("' + ")) {
found.add(new Finding(line, code, Severity.CRITICAL, Category.SECURITY, "SQL built by concatenation",
"User input becomes part of the statement.", "Use a PreparedStatement with a ? parameter."));
} else if (code.contains("System.out.println")) {
found.add(new Finding(line, code, Severity.MINOR, Category.MAINTAINABILITY, "Console output",
"Use the logger so the message has a level and can be switched off.", ""));
}
}
return found;
}
static String json(List<Finding> findings) {
return JSON.writeValueAsString(new ReviewResult(findings));
}
@Override
public ChatResponse call(Prompt prompt) {
prompts.add(prompt);
String text = script.apply(prompt);
var usage = new DefaultUsage(TOKENS.estimate(prompt.getContents()), TOKENS.estimate(text));
return new ChatResponse(List.of(new Generation(new AssistantMessage(text))),
ChatResponseMetadata.builder().usage(usage).build());
}
}
@@ -0,0 +1,83 @@
package com.ankurm.prreviewer;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import java.util.ArrayDeque;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class StructuredOutputTest {
static Chunker.Chunk chunk() {
return new Chunker(6000).chunk(UnifiedDiff.parse(
Samples.addedFile("A.java", "class A {\n String password = \"hunter2\";\n}\n"))).chunks().getFirst();
}
static ModelReviewer reviewer(ScriptedChatModel model) {
return new ModelReviewer(ChatClient.create(model));
}
@Test
void showsExactlyWhatIsSent() {
var model = ScriptedChatModel.ruleBased();
var reply = reviewer(model).review(chunk());
var t = new Transcript("03-prompt-and-schema.txt");
model.prompts.getFirst().getInstructions().forEach(m -> {
t.line("=== %s message", m.getMessageType());
t.block(m.getText());
});
t.line("=== parsed back into records");
reply.findings().forEach(f -> t.line("%s", f));
t.write();
// Braces in the code survive: the diff is not treated as a prompt template.
assertThat(model.prompts.getFirst().getContents()).contains("class A {").contains("\"findings\"");
assertThat(reply.findings()).singleElement().extracting(Finding::line).isEqualTo(2);
}
@Test
void retriesInvalidJsonAndCountsTheRetry() {
var t = new Transcript("04-bad-replies.txt");
String good = ScriptedChatModel.json(List.of(new Finding(2, "String password = \"hunter2\";",
Severity.CRITICAL, Category.SECURITY, "Hard-coded password", "Readable by anyone.", "")));
var fenced = new ScriptedChatModel(p -> "```json\n" + good + "\n```");
var client = ChatClient.create(fenced);
var plain = client.prompt().user("review").call().entity(ReviewResult.class);
t.line("fenced reply, plain entity() : %d finding(s), %d model call(s)", plain.findings().size(), fenced.prompts.size());
fenced.prompts.clear();
var validated = client.prompt().user("review").call().entity(ReviewResult.class, spec -> spec.validateSchema());
int wasted = fenced.prompts.size();
t.line("fenced reply, entity() + validateSchema(): %d finding(s), %d model call(s)", validated.findings().size(), wasted);
var r1 = reviewer(fenced).review(chunk());
t.line("fenced reply, with FenceStripper : %d finding(s), %d model call(s)", r1.findings().size(), r1.modelCalls());
var replies = new ArrayDeque<>(List.of(good.replace("\"CRITICAL\"", "\"HIGH\""), good));
var once = new ScriptedChatModel(p -> replies.removeFirst());
var r2 = reviewer(once).review(chunk());
t.line("severity \"HIGH\", then valid : %d finding(s), %d model call(s), %d input tokens (single call: %d)",
r2.findings().size(), r2.modelCalls(), r2.inputTokens(), r1.inputTokens());
String retryPrompt = once.prompts.get(1).getContents();
t.line("line added to the retried request:");
retryPrompt.lines().filter(l -> l.startsWith("Output JSON validation failed")).forEach(l -> t.line(" %s", l));
t.line("copies of the schema in the retried request: %d", retryPrompt.split("JSON Schema instance", -1).length - 1);
var never = new ScriptedChatModel(p -> "Looks good to me!");
try {
reviewer(never).review(chunk());
t.line("prose forever : returned normally");
} catch (ModelReviewer.ModelFailure e) {
t.line("prose forever : ModelFailure after %d model calls, %d input tokens spent",
e.spent.modelCalls(), e.spent.inputTokens());
}
t.write();
assertThat(wasted).isEqualTo(4);
assertThat(r1.modelCalls()).isEqualTo(1);
assertThat(r2.modelCalls()).isEqualTo(2);
assertThatThrownBy(() -> reviewer(never).review(chunk())).isInstanceOf(ModelReviewer.ModelFailure.class);
}
}
@@ -0,0 +1,36 @@
package com.ankurm.prreviewer;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes them to output/NN-name.txt, so the test IS the transcript. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file) {
this.file = file;
}
void line(String format, Object... args) {
lines.add((args.length == 0 ? format : format.formatted(args)).stripTrailing());
}
void block(String text) {
text.stripTrailing().lines().forEach(l -> lines.add(l.stripTrailing()));
}
void write() {
try {
Files.createDirectories(Path.of("output"));
Files.write(Path.of("output", file), lines);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,62 @@
package com.ankurm.prreviewer;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/** Uses one delivery captured from a real Gitea 1.27.3, signed by Gitea itself with the secret "s3cret". */
class WebhookTest {
@Test
void verifiesARealDelivery() throws IOException {
byte[] body = Files.readAllBytes(Path.of("src/test/resources/gitea-1.27.3-synchronized.json"));
Map<String, String> h = new HashMap<>();
var headerLines = Files.readAllLines(Path.of("src/test/resources/gitea-1.27.3-synchronized.headers"));
headerLines.forEach(l -> h.put(l.substring(0, l.indexOf(':')), l.substring(l.indexOf(':') + 2)));
var host = new FakeHost("");
host.head = "moved-on";
var properties = new ReviewerProperties("http://unused", "t", "reviewbot", "s3cret", 6000, 20, 10, Severity.MINOR);
var t = new Transcript("10-webhook.txt");
t.line("headers Gitea 1.27.3 sent for a push to an open pull request:");
headerLines.forEach(l -> t.line(" %s", l));
t.line("");
try (var queue = new ReviewQueue()) {
var controller = new WebhookController(properties,
ReviewServiceTest.service(ScriptedChatModel.ruleBased(), host, properties.settings()), queue);
String sig = h.get("X-Gitea-Signature");
byte[] reformatted = ScriptedChatModel.JSON.writeValueAsString(ScriptedChatModel.JSON.readTree(body))
.getBytes(StandardCharsets.UTF_8);
var real = row(t, "the captured delivery", controller.receive(sig, "pull_request", body));
var none = row(t, "no signature header", controller.receive(null, "pull_request", body));
var prefixed = row(t, "X-Hub-Signature-256 value (has sha256=)",
controller.receive(h.get("X-Hub-Signature-256"), "pull_request", body));
var parsed = row(t, "same JSON, parsed and re-serialised", controller.receive(sig, "pull_request", reformatted));
byte[] comment = "{\"action\":\"reviewed\"}".getBytes(StandardCharsets.UTF_8);
var own = row(t, "the event our own review triggers",
controller.receive(Signatures.hmacSha256Hex("s3cret", comment), "pull_request_comment", comment));
t.line("original body: %d bytes, re-serialised: %d bytes", body.length, reformatted.length);
assertThat(real.getStatusCode().value()).isEqualTo(202);
assertThat(none.getStatusCode().value()).isEqualTo(401);
assertThat(prefixed.getStatusCode().value()).isEqualTo(401);
assertThat(own.getBody()).startsWith("ignored");
assertThat(parsed.getStatusCode().value()).isEqualTo(java.util.Arrays.equals(body, reformatted) ? 202 : 401);
}
t.write();
}
private static ResponseEntity<String> row(Transcript t, String what, ResponseEntity<String> r) {
t.line("%-42s -> %d %s", what, r.getStatusCode().value(), r.getBody());
return r;
}
}