Initial open source GitHub PR review bot
This commit is contained in:
commit
c6bf0346b4
23 files changed
+4577
No files matched your search
@@ -0,0 +1,13 @@
|
|||||||
|
PORT=3000
|
||||||
|
WEBHOOK_SECRET=replace-with-github-webhook-secret
|
||||||
|
GITHUB_APP_ID=123456
|
||||||
|
GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
|
||||||
|
OPENAI_API_KEY=sk-...
|
||||||
|
OPENAI_MODEL=gpt-4.1
|
||||||
|
|
||||||
|
# Optional controls
|
||||||
|
BOT_NAME=ghbot
|
||||||
|
AUTO_MERGE=true
|
||||||
|
MERGE_METHOD=squash
|
||||||
|
REQUIRE_CHECKS=true
|
||||||
|
MAX_PATCH_CHARS=120000
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
typecheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run typecheck
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
.DS_Store
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Contributing
|
||||||
|
|
||||||
|
Thanks for helping improve ghbot.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `.env.example` as the configuration reference. Do not commit `.env`, private keys, webhook secrets, or API keys.
|
||||||
|
|
||||||
|
## Pull request expectations
|
||||||
|
|
||||||
|
- Keep changes focused.
|
||||||
|
- Include clear behavior notes when changing review or merge logic.
|
||||||
|
- Preserve the default-safe posture: auto-merge must stay opt-in.
|
||||||
|
- Run `npm run typecheck` before opening a PR.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
Please do not open public issues for vulnerabilities that expose secrets or allow unintended merges. Open a private security advisory on GitHub or contact the maintainers privately.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 ghbot contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
# ghbot
|
||||||
|
|
||||||
|
GitHub App bot that reviews pull requests with an AI reviewer, leaves inline review comments for problems, approves clean PRs, and can merge them when repository checks are green.
|
||||||
|
|
||||||
|
## Behavior
|
||||||
|
|
||||||
|
- Listens for `pull_request` events: `opened`, `synchronize`, `reopened`, `ready_for_review`.
|
||||||
|
- Fetches changed files and patches from the pull request.
|
||||||
|
- Asks the reviewer for a structured decision:
|
||||||
|
- `safeToMerge=true` only when there are no blocking findings.
|
||||||
|
- `blocking` findings become request-changes reviews.
|
||||||
|
- `suggestion` findings are included as non-blocking suggestions.
|
||||||
|
- Posts inline comments only on valid added diff lines.
|
||||||
|
- Approves clean pull requests.
|
||||||
|
- If `AUTO_MERGE=true`, merges only after:
|
||||||
|
- the AI reviewer says the PR is safe,
|
||||||
|
- GitHub reports the PR as mergeable,
|
||||||
|
- checks/statuses are green when `REQUIRE_CHECKS=true`.
|
||||||
|
|
||||||
|
## GitHub App setup
|
||||||
|
|
||||||
|
Create a GitHub App with these repository permissions:
|
||||||
|
|
||||||
|
- Contents: `Read & write`
|
||||||
|
- Pull requests: `Read & write`
|
||||||
|
- Checks: `Read-only`
|
||||||
|
- Commit statuses: `Read-only`
|
||||||
|
- Metadata: `Read-only`
|
||||||
|
|
||||||
|
Subscribe to this webhook event:
|
||||||
|
|
||||||
|
- Pull request
|
||||||
|
|
||||||
|
Set the webhook URL to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://your-domain.example/webhooks/github
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate a private key for the app, install the app on the target repositories, and copy `.env.example` to `.env`.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Required variables:
|
||||||
|
|
||||||
|
- `WEBHOOK_SECRET`: the GitHub App webhook secret.
|
||||||
|
- `GITHUB_APP_ID`: GitHub App ID.
|
||||||
|
- `GITHUB_PRIVATE_KEY`: GitHub App private key. Use escaped `\n` line breaks in a single-line env var.
|
||||||
|
- `OPENAI_API_KEY`: API key for the reviewer model.
|
||||||
|
|
||||||
|
Important optional variables:
|
||||||
|
|
||||||
|
- `OPENAI_MODEL`: defaults to `gpt-4.1`.
|
||||||
|
- `AUTO_MERGE`: defaults to `false`. Set to `true` only after testing on a non-critical repo.
|
||||||
|
- `MERGE_METHOD`: `merge`, `squash`, or `rebase`. Defaults to `squash`.
|
||||||
|
- `REQUIRE_CHECKS`: defaults to `true`.
|
||||||
|
- `MAX_PATCH_CHARS`: maximum patch payload sent to the reviewer. Defaults to `120000`.
|
||||||
|
|
||||||
|
## Local development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Expose the local server with a tunnel and point the GitHub App webhook to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://your-tunnel.example/webhooks/github
|
||||||
|
```
|
||||||
|
|
||||||
|
Health check:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:3000/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy to Vercel
|
||||||
|
|
||||||
|
This project includes a Vercel Function at `api/github/webhooks.ts` and a rewrite from `/webhooks/github` to `/api/github/webhooks`.
|
||||||
|
|
||||||
|
1. Import this repository into Vercel.
|
||||||
|
2. Add the required environment variables in Vercel Project Settings.
|
||||||
|
3. Deploy.
|
||||||
|
4. Set the GitHub App webhook URL to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://your-project.vercel.app/webhooks/github
|
||||||
|
```
|
||||||
|
|
||||||
|
For local Vercel testing:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev:vercel
|
||||||
|
```
|
||||||
|
|
||||||
|
Vercel serverless functions have execution time limits. For large PRs, keep `MAX_PATCH_CHARS` conservative or upgrade the function duration in `vercel.json`.
|
||||||
|
|
||||||
|
## Self-hosted production
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
Run it behind HTTPS. GitHub webhooks must reach `/webhooks/github`, and the app must keep the private key and webhook secret out of source control.
|
||||||
|
|
||||||
|
## Safety notes
|
||||||
|
|
||||||
|
Start with `AUTO_MERGE=false`. Let the bot comment and approve first, then enable auto-merge after you trust the behavior on your repositories.
|
||||||
|
|
||||||
|
This bot does not execute untrusted PR code. It reviews diffs and checks GitHub check/status results. Keep repository branch protection enabled so required CI and human override rules still apply.
|
||||||
|
|
||||||
|
## Open source release checklist
|
||||||
|
|
||||||
|
- Replace the copyright holder in `LICENSE` if needed.
|
||||||
|
- Create a GitHub repository.
|
||||||
|
- Push this code.
|
||||||
|
- Configure repository secrets only in GitHub/Vercel, never in source control.
|
||||||
|
- Keep branch protection enabled on `main`.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { VercelRequest, VercelResponse } from "@vercel/node";
|
||||||
|
import { waitUntil } from "@vercel/functions";
|
||||||
|
import { createGitHubWebhooks } from "../../src/github/webhookHandler.js";
|
||||||
|
import { logger } from "../../src/logger.js";
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
api: {
|
||||||
|
bodyParser: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const webhooks = createGitHubWebhooks();
|
||||||
|
|
||||||
|
export default async function handler(request: VercelRequest, response: VercelResponse) {
|
||||||
|
if (request.method === "GET") {
|
||||||
|
response.status(200).json({ ok: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.method !== "POST") {
|
||||||
|
response.setHeader("allow", "GET, POST");
|
||||||
|
response.status(405).json({ error: "Method not allowed." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = request.headers["x-github-delivery"];
|
||||||
|
const name = request.headers["x-github-event"];
|
||||||
|
const signature = request.headers["x-hub-signature-256"];
|
||||||
|
|
||||||
|
if (typeof id !== "string" || typeof name !== "string" || typeof signature !== "string") {
|
||||||
|
response.status(400).json({ error: "Missing GitHub webhook headers." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await readRawBody(request);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const verified = await webhooks.verify(payload, signature);
|
||||||
|
if (!verified) {
|
||||||
|
response.status(401).json({ error: "Invalid webhook signature." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
waitUntil(
|
||||||
|
webhooks.receive({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
payload: JSON.parse(payload)
|
||||||
|
} as Parameters<typeof webhooks.receive>[0])
|
||||||
|
);
|
||||||
|
|
||||||
|
response.status(202).json({ ok: true });
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error }, "Failed to handle webhook.");
|
||||||
|
response.status(400).json({ error: "Invalid or failed webhook." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readRawBody(request: VercelRequest): Promise<string> {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
|
||||||
|
for await (const chunk of request) {
|
||||||
|
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Buffer.concat(chunks).toString("utf8");
|
||||||
|
}
|
||||||
Generated
+3639
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "ghbot",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22 <26"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/server.ts",
|
||||||
|
"dev:vercel": "vercel dev",
|
||||||
|
"build": "tsc -p tsconfig.json",
|
||||||
|
"start": "node dist/server.js",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@octokit/auth-app": "^7.0.0",
|
||||||
|
"@octokit/rest": "^21.0.2",
|
||||||
|
"@octokit/webhooks": "^13.3.1",
|
||||||
|
"@vercel/functions": "^2.0.0",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
|
"express": "^4.21.2",
|
||||||
|
"openai": "^4.77.0",
|
||||||
|
"pino": "^9.5.0",
|
||||||
|
"pino-http": "^10.4.0",
|
||||||
|
"zod": "^3.24.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/node": "^22.10.2",
|
||||||
|
"@vercel/node": "^5.3.0",
|
||||||
|
"tsx": "^4.19.2",
|
||||||
|
"typescript": "^5.7.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
});
|
||||||
@@ -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
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import pino from "pino";
|
||||||
|
|
||||||
|
export const logger = pino({
|
||||||
|
level: process.env.LOG_LEVEL ?? "info"
|
||||||
|
});
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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.");
|
||||||
|
});
|
||||||
@@ -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";
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "."
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "api/**/*.ts"]
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"functions": {
|
||||||
|
"api/github/webhooks.ts": {
|
||||||
|
"maxDuration": 60
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rewrites": [
|
||||||
|
{
|
||||||
|
"source": "/webhooks/github",
|
||||||
|
"destination": "/api/github/webhooks"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user