Initial open source GitHub PR review bot

This commit is contained in:
lezi-fun committed 2026-05-12 21:23:43 +08:00
commit c6bf0346b4
23 files changed
+4577

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
import type { ReviewDecision, ReviewFinding } from "../types.js";
export function formatReviewBody(decision: ReviewDecision, unpostedFindings: ReviewFinding[]): string {
const lines = [
`## Automated review`,
"",
decision.summary,
"",
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
];
if (unpostedFindings.length > 0) {
lines.push("", "Findings that could not be attached inline:");
for (const finding of unpostedFindings) {
lines.push(
"",
`- ${finding.path}:${finding.line} [${finding.severity}] ${finding.title}`,
` ${finding.body}`
);
}
}
return lines.join("\n");
}
+100
View File
@@ -0,0 +1,100 @@
import OpenAI from "openai";
import { z } from "zod";
import { config } from "../config.js";
import type { PullRequestFile, ReviewDecision } from "../types.js";
const reviewDecisionSchema = z.object({
safeToMerge: z.boolean(),
summary: z.string(),
findings: z.array(
z.object({
path: z.string(),
line: z.number().int().positive(),
severity: z.enum(["blocking", "suggestion"]),
title: z.string(),
body: z.string()
})
)
});
export class OpenAiReviewer {
private readonly client = new OpenAI({ apiKey: config.openAiApiKey });
async review(input: {
title: string;
body: string | null;
files: PullRequestFile[];
}): Promise<ReviewDecision> {
const response = await this.client.chat.completions.create({
model: config.openAiModel,
temperature: 0.1,
response_format: {
type: "json_schema",
json_schema: {
name: "pull_request_review",
strict: true,
schema: {
type: "object",
additionalProperties: false,
required: ["safeToMerge", "summary", "findings"],
properties: {
safeToMerge: { type: "boolean" },
summary: { type: "string" },
findings: {
type: "array",
items: {
type: "object",
additionalProperties: false,
required: ["path", "line", "severity", "title", "body"],
properties: {
path: { type: "string" },
line: { type: "integer", minimum: 1 },
severity: { type: "string", enum: ["blocking", "suggestion"] },
title: { type: "string" },
body: { type: "string" }
}
}
}
}
}
}
},
messages: [
{
role: "system",
content: [
"You are a strict senior software engineer reviewing a GitHub pull request.",
"Find correctness bugs, security issues, data-loss risks, broken tests, bad error handling, and maintainability problems.",
"Only set safeToMerge=true when there are no blocking findings.",
"Use suggestion severity for non-blocking style or clarity improvements.",
"For each finding, choose a line number that exists on an added line in the supplied patch whenever possible.",
"Do not invent files, line numbers, test results, or runtime behavior."
].join(" ")
},
{
role: "user",
content: JSON.stringify({
pullRequest: {
title: input.title,
body: input.body ?? ""
},
files: input.files.map((file) => ({
path: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
patch: file.patch ?? ""
}))
})
}
]
});
const raw = response.choices[0]?.message.content;
if (!raw) {
throw new Error("OpenAI returned an empty review response.");
}
return reviewDecisionSchema.parse(JSON.parse(raw));
}
}
+197
View File
@@ -0,0 +1,197 @@
import type { Octokit } from "@octokit/rest";
import { config } from "../config.js";
import { requiredChecksAreGreen } from "../github/checks.js";
import { collectValidNewLines, toDiffPosition } from "../github/diff.js";
import { logger } from "../logger.js";
import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding } from "../types.js";
import { formatReviewBody } from "./format.js";
import { OpenAiReviewer } from "./openaiReviewer.js";
import { compactFilesForReview } from "./prompt.js";
const reviewer = new OpenAiReviewer();
export async function processPullRequest(octokit: Octokit, ref: PullRequestRef): Promise<void> {
const { owner, repo, pullNumber } = ref;
const { data: pullRequest } = await octokit.rest.pulls.get({
owner,
repo,
pull_number: pullNumber
});
if (pullRequest.draft) {
logger.info({ owner, repo, pullNumber }, "Skipping draft pull request.");
return;
}
if (pullRequest.state !== "open") {
logger.info({ owner, repo, pullNumber, state: pullRequest.state }, "Skipping non-open pull request.");
return;
}
const files = await listPullRequestFiles(octokit, owner, repo, pullNumber);
const compactFiles = compactFilesForReview(files, config.maxPatchChars);
const decision = await reviewer.review({
title: pullRequest.title,
body: pullRequest.body,
files: compactFiles
});
await submitReview(octokit, {
owner,
repo,
pullNumber,
commitId: pullRequest.head.sha,
files,
decision
});
if (!decision.safeToMerge) {
logger.info({ owner, repo, pullNumber }, "Review requested changes; not merging.");
return;
}
if (!config.autoMerge) {
logger.info({ owner, repo, pullNumber }, "AUTO_MERGE is disabled; approved only.");
return;
}
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.`
});
return;
}
if (config.requireChecks) {
const checks = await requiredChecksAreGreen(octokit, {
owner,
repo,
ref: pullRequest.head.sha
});
if (!checks.ok) {
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim()
});
return;
}
}
await octokit.rest.pulls.merge({
owner,
repo,
pull_number: pullNumber,
merge_method: config.mergeMethod,
commit_title: `${pullRequest.title} (#${pullNumber})`
});
}
async function listPullRequestFiles(
octokit: Octokit,
owner: string,
repo: string,
pullNumber: number
): Promise<PullRequestFile[]> {
const files = await octokit.paginate(octokit.rest.pulls.listFiles, {
owner,
repo,
pull_number: pullNumber,
per_page: 100
});
return files.map((file) => ({
filename: file.filename,
patch: file.patch,
status: file.status,
additions: file.additions,
deletions: file.deletions
}));
}
async function submitReview(
octokit: Octokit,
params: {
owner: string;
repo: string;
pullNumber: number;
commitId: string;
files: PullRequestFile[];
decision: ReviewDecision;
}
): Promise<void> {
const validLines = collectValidNewLines(params.files);
const filesByPath = new Map(params.files.map((file) => [file.filename, file]));
const unpostedFindings: ReviewFinding[] = [];
const comments = params.decision.findings.flatMap((finding) => {
const file = filesByPath.get(finding.path);
if (!file) {
unpostedFindings.push(finding);
return [];
}
const position = toDiffPosition(file, finding.line, validLines);
if (!position) {
unpostedFindings.push(finding);
return [];
}
return [
{
path: position.path,
line: position.line,
side: position.side,
body: `**${finding.title}**\n\n${finding.body}`
}
];
});
const hasBlockingFinding = params.decision.findings.some((finding) => finding.severity === "blocking");
const event: "APPROVE" | "REQUEST_CHANGES" =
params.decision.safeToMerge && !hasBlockingFinding ? "APPROVE" : "REQUEST_CHANGES";
await octokit.rest.pulls.createReview({
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber,
commit_id: params.commitId,
event,
body: formatReviewBody(params.decision, unpostedFindings),
comments
});
}
async function waitForMergeable(
octokit: Octokit,
owner: string,
repo: string,
pullNumber: number
) {
for (let attempt = 0; attempt < 5; attempt += 1) {
const { data } = await octokit.rest.pulls.get({
owner,
repo,
pull_number: pullNumber
});
if (data.mergeable !== null) {
return data;
}
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
const { data } = await octokit.rest.pulls.get({
owner,
repo,
pull_number: pullNumber
});
return data;
}
+19
View File
@@ -0,0 +1,19 @@
import type { PullRequestFile } from "../types.js";
export function compactFilesForReview(files: PullRequestFile[], maxPatchChars: number): PullRequestFile[] {
let remaining = maxPatchChars;
return files.map((file) => {
if (!file.patch || remaining <= 0) {
return { ...file, patch: undefined };
}
const patch = file.patch.slice(0, remaining);
remaining -= patch.length;
return {
...file,
patch: patch.length < file.patch.length ? `${patch}\n[patch truncated]` : patch
};
});
}