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

+30
View File
@@ -0,0 +1,30 @@
import "dotenv/config";
import { z } from "zod";
const configSchema = z.object({
port: z.coerce.number().int().positive().default(3000),
webhookSecret: z.string().min(1),
githubAppId: z.coerce.number().int().positive(),
githubPrivateKey: z.string().min(1).transform((value) => value.replace(/\\n/g, "\n")),
openAiApiKey: z.string().min(1),
openAiModel: z.string().min(1).default("gpt-4.1"),
botName: z.string().min(1).default("ghbot"),
autoMerge: z.coerce.boolean().default(false),
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
requireChecks: z.coerce.boolean().default(true),
maxPatchChars: z.coerce.number().int().positive().default(120_000)
});
export const config = configSchema.parse({
port: process.env.PORT,
webhookSecret: process.env.WEBHOOK_SECRET,
githubAppId: process.env.GITHUB_APP_ID,
githubPrivateKey: process.env.GITHUB_PRIVATE_KEY,
openAiApiKey: process.env.OPENAI_API_KEY,
openAiModel: process.env.OPENAI_MODEL,
botName: process.env.BOT_NAME,
autoMerge: process.env.AUTO_MERGE,
mergeMethod: process.env.MERGE_METHOD,
requireChecks: process.env.REQUIRE_CHECKS,
maxPatchChars: process.env.MAX_PATCH_CHARS
});
+17
View File
@@ -0,0 +1,17 @@
import { createAppAuth } from "@octokit/auth-app";
import { Octokit } from "@octokit/rest";
import { config } from "../config.js";
export async function getInstallationOctokit(installationId: number): Promise<Octokit> {
const auth = createAppAuth({
appId: config.githubAppId,
privateKey: config.githubPrivateKey,
installationId
});
const installationAuthentication = await auth({ type: "installation" });
return new Octokit({
auth: installationAuthentication.token
});
}
+46
View File
@@ -0,0 +1,46 @@
import type { Octokit } from "@octokit/rest";
export async function requiredChecksAreGreen(
octokit: Octokit,
params: {
owner: string;
repo: string;
ref: string;
}
): Promise<{ ok: boolean; reason?: string }> {
const [checks, statuses] = await Promise.all([
octokit.rest.checks.listForRef({
owner: params.owner,
repo: params.repo,
ref: params.ref
}),
octokit.rest.repos.getCombinedStatusForRef({
owner: params.owner,
repo: params.repo,
ref: params.ref
})
]);
const failedCheck = checks.data.check_runs.find((check) => {
return (
check.status !== "completed" ||
!["success", "neutral", "skipped"].includes(check.conclusion ?? "")
);
});
if (failedCheck) {
return {
ok: false,
reason: `Check "${failedCheck.name}" is ${failedCheck.status}/${failedCheck.conclusion ?? "pending"}.`
};
}
if (statuses.data.state !== "success" && statuses.data.statuses.length > 0) {
return {
ok: false,
reason: `Commit status is ${statuses.data.state}.`
};
}
return { ok: true };
}
+50
View File
@@ -0,0 +1,50 @@
import type { DiffPosition, PullRequestFile } from "../types.js";
export function collectValidNewLines(files: PullRequestFile[]): Set<string> {
const validLines = new Set<string>();
for (const file of files) {
if (!file.patch) {
continue;
}
let newLine = 0;
for (const rawLine of file.patch.split("\n")) {
if (rawLine.startsWith("@@")) {
const match = /\+(\d+)(?:,\d+)?/.exec(rawLine);
if (match) {
newLine = Number(match[1]);
}
continue;
}
if (rawLine.startsWith("+") && !rawLine.startsWith("+++")) {
validLines.add(`${file.filename}:${newLine}`);
newLine += 1;
continue;
}
if (!rawLine.startsWith("-")) {
newLine += 1;
}
}
}
return validLines;
}
export function toDiffPosition(
file: PullRequestFile,
line: number,
validLines: Set<string>
): DiffPosition | null {
if (validLines.has(`${file.filename}:${line}`)) {
return {
path: file.filename,
line,
side: "RIGHT"
};
}
return null;
}
+36
View File
@@ -0,0 +1,36 @@
import { Webhooks } from "@octokit/webhooks";
import { config } from "../config.js";
import { getInstallationOctokit } from "./app.js";
import { logger } from "../logger.js";
import { processPullRequest } from "../review/processor.js";
export function createGitHubWebhooks(): Webhooks {
const webhooks = new Webhooks({
secret: config.webhookSecret
});
webhooks.on(
["pull_request.opened", "pull_request.synchronize", "pull_request.reopened", "pull_request.ready_for_review"],
async ({ payload }) => {
const installationId = payload.installation?.id;
if (!installationId) {
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping PR without installation id.");
return;
}
const octokit = await getInstallationOctokit(installationId);
await processPullRequest(octokit, {
owner: payload.repository.owner.login,
repo: payload.repository.name,
pullNumber: payload.pull_request.number,
installationId
});
}
);
webhooks.onError((error) => {
logger.error({ error }, "Webhook handler failed.");
});
return webhooks;
}
+5
View File
@@ -0,0 +1,5 @@
import pino from "pino";
export const logger = pino({
level: process.env.LOG_LEVEL ?? "info"
});
+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
};
});
}
+42
View File
@@ -0,0 +1,42 @@
import express from "express";
import pinoHttpModule from "pino-http";
import { config } from "./config.js";
import { createGitHubWebhooks } from "./github/webhookHandler.js";
import { logger } from "./logger.js";
const app = express();
const webhooks = createGitHubWebhooks();
const pinoHttp = pinoHttpModule.default ?? pinoHttpModule;
app.use(pinoHttp({ logger }));
app.get("/healthz", (_request, response) => {
response.json({ ok: true });
});
app.post("/webhooks/github", express.raw({ type: "application/json" }), async (request, response) => {
const id = request.header("x-github-delivery");
const name = request.header("x-github-event");
const signature = request.header("x-hub-signature-256");
if (!id || !name || !signature) {
response.status(400).json({ error: "Missing GitHub webhook headers." });
return;
}
try {
await webhooks.verifyAndReceive({
id,
name,
signature,
payload: request.body.toString("utf8")
});
response.status(202).json({ ok: true });
} catch (error) {
logger.error({ error }, "Failed to handle webhook.");
response.status(400).json({ error: "Invalid or failed webhook." });
}
});
app.listen(config.port, () => {
logger.info({ port: config.port }, "GitHub bot is listening.");
});
+34
View File
@@ -0,0 +1,34 @@
export type PullRequestRef = {
owner: string;
repo: string;
pullNumber: number;
installationId: number;
};
export type PullRequestFile = {
filename: string;
patch?: string;
status: string;
additions: number;
deletions: number;
};
export type ReviewFinding = {
path: string;
line: number;
severity: "blocking" | "suggestion";
title: string;
body: string;
};
export type ReviewDecision = {
safeToMerge: boolean;
summary: string;
findings: ReviewFinding[];
};
export type DiffPosition = {
path: string;
line: number;
side: "RIGHT";
};