Convert reviewer to GitHub Actions workflow
This commit is contained in:
1 parent
9d40d7850f
commit
50d0ae5be9
18 files changed
+541
-2641
No files matched your search
+4
-5
@@ -1,16 +1,15 @@
|
||||
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-----"
|
||||
GITHUB_TOKEN=ghp_your_token_here
|
||||
OPENAI_API_KEY=sk-...
|
||||
OPENAI_BASE_URL=https://api.openai.com/v1
|
||||
OPENAI_MODEL=gpt-4.1
|
||||
OPENAI_REASONING_EFFORT=medium
|
||||
|
||||
# Optional controls
|
||||
BOT_NAME=ghbot
|
||||
BOT_NAME=github-actions[bot]
|
||||
LENIENT_APPROVAL_USER=lezi-fun
|
||||
AUTO_MERGE=true
|
||||
AUTO_MERGE=false
|
||||
MERGE_METHOD=squash
|
||||
REQUIRE_CHECKS=true
|
||||
MAX_PATCH_CHARS=120000
|
||||
LOG_LEVEL=info
|
||||
@@ -1,19 +0,0 @@
|
||||
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,53 @@
|
||||
name: PR Review Bot
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
issue_comment:
|
||||
types:
|
||||
- created
|
||||
pull_request_review:
|
||||
types:
|
||||
- submitted
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
checks: write
|
||||
statuses: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
review:
|
||||
name: bot-review
|
||||
if: |
|
||||
github.event_name == 'pull_request_target' ||
|
||||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
|
||||
github.event_name == 'pull_request_review'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: node dist/src/actions/runReview.js
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
OPENAI_BASE_URL: ${{ secrets.OPENAI_BASE_URL }}
|
||||
OPENAI_MODEL: ${{ secrets.OPENAI_MODEL }}
|
||||
OPENAI_REASONING_EFFORT: ${{ secrets.OPENAI_REASONING_EFFORT }}
|
||||
BOT_NAME: github-actions[bot]
|
||||
LENIENT_APPROVAL_USER: lezi-fun
|
||||
AUTO_MERGE: ${{ vars.AUTO_MERGE || 'false' }}
|
||||
MERGE_METHOD: ${{ vars.MERGE_METHOD || 'squash' }}
|
||||
REQUIRE_CHECKS: ${{ vars.REQUIRE_CHECKS || 'true' }}
|
||||
MAX_PATCH_CHARS: ${{ vars.MAX_PATCH_CHARS || '120000' }}
|
||||
LOG_LEVEL: info
|
||||
@@ -1,18 +1,20 @@
|
||||
# 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.
|
||||
GitHub Actions 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`.
|
||||
- Triggers on `pull_request_target`: `opened`, `synchronize`, `reopened`, `ready_for_review`.
|
||||
- When a new PR is opened, posts an immediate comment that review has started.
|
||||
- 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.
|
||||
- Creates a GitHub check run with a `Lenient check` button when strict review requests changes.
|
||||
- When `Lenient check` is clicked, reviews again and only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks.
|
||||
- A PR that passes `Lenient check` is not auto-merged until `@lezi-fun` approves the current head commit.
|
||||
- Supports a lenient pass when a repository administrator comments `/lenient-check`.
|
||||
- If no repository administrator has commented or reviewed within the last 24 hours, the lenient trigger automatically broadens to users with `write`, `maintain`, or `admin` permission.
|
||||
- In lenient mode, only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks.
|
||||
- A PR that passes lenient mode is not auto-merged until `@lezi-fun` approves the current head commit.
|
||||
- If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request.
|
||||
- Posts inline comments only on valid added diff lines.
|
||||
- Approves clean pull requests.
|
||||
@@ -21,115 +23,90 @@ GitHub App bot that reviews pull requests with an AI reviewer, leaves inline rev
|
||||
- GitHub reports the PR as mergeable,
|
||||
- checks/statuses are green when `REQUIRE_CHECKS=true`.
|
||||
|
||||
## GitHub App setup
|
||||
## GitHub Actions setup
|
||||
|
||||
Create a GitHub App with these repository permissions:
|
||||
Add these repository secrets:
|
||||
|
||||
- Contents: `Read & write`
|
||||
- Pull requests: `Read & write`
|
||||
- Checks: `Read & write`
|
||||
- Commit statuses: `Read-only`
|
||||
- Metadata: `Read-only`
|
||||
- `OPENAI_API_KEY`
|
||||
- `OPENAI_BASE_URL`
|
||||
- `OPENAI_MODEL`
|
||||
- `OPENAI_REASONING_EFFORT`
|
||||
|
||||
Subscribe to this webhook event:
|
||||
Optional repository variables:
|
||||
|
||||
- Pull request
|
||||
- Check run
|
||||
- `AUTO_MERGE`: defaults to `false`
|
||||
- `MERGE_METHOD`: `merge`, `squash`, or `rebase`, defaults to `squash`
|
||||
- `REQUIRE_CHECKS`: defaults to `true`
|
||||
- `MAX_PATCH_CHARS`: defaults to `120000`
|
||||
|
||||
Set the webhook URL to:
|
||||
The workflow uses the repository `GITHUB_TOKEN`, so you do not need a GitHub App, webhook endpoint, Vercel deployment, or a self-hosted listener.
|
||||
|
||||
## Required workflow permissions
|
||||
|
||||
Repository Actions permissions must allow the workflow token to:
|
||||
|
||||
- `contents: write`
|
||||
- `pull-requests: write`
|
||||
- `checks: write`
|
||||
- `issues: write`
|
||||
- `statuses: read`
|
||||
|
||||
These permissions are declared in [.github/workflows/review.yml](/Users/home/Projects/ghbot/.github/workflows/review.yml:1).
|
||||
|
||||
## Lenient check
|
||||
|
||||
If a strict review leaves findings that are not practical to change, a repository administrator can comment this on the PR:
|
||||
|
||||
```text
|
||||
https://your-domain.example/webhooks/github
|
||||
/lenient-check
|
||||
```
|
||||
|
||||
Generate a private key for the app, install the app on the target repositories, and copy `.env.example` to `.env`.
|
||||
That reruns the AI in lenient mode.
|
||||
|
||||
## Configuration
|
||||
If no administrator has commented or reviewed within the last 24 hours on that PR, the command is also accepted from users with `write` or `maintain` permission.
|
||||
|
||||
```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.
|
||||
- `OPENAI_BASE_URL`: optional OpenAI-compatible API base URL.
|
||||
|
||||
Important optional variables:
|
||||
|
||||
- `OPENAI_MODEL`: defaults to `gpt-4.1`.
|
||||
- `OPENAI_REASONING_EFFORT`: optional reasoning effort, one of `low`, `medium`, or `high`. Use `default` or leave unset to omit the parameter.
|
||||
- `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`.
|
||||
- `LENIENT_APPROVAL_USER`: defaults to `lezi-fun`.
|
||||
- `MAX_PATCH_CHARS`: maximum patch payload sent to the reviewer. Defaults to `120000`.
|
||||
If lenient mode passes, the bot still requires `@lezi-fun` to approve the current head commit before merge.
|
||||
|
||||
## 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
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
`npm start` runs `node dist/src/server.js`.
|
||||
To simulate the workflow locally, export the same env vars that the GitHub Action uses and run:
|
||||
|
||||
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.
|
||||
```bash
|
||||
node dist/src/actions/runReview.js
|
||||
```
|
||||
|
||||
You must also provide:
|
||||
|
||||
- `GITHUB_EVENT_NAME`
|
||||
- `GITHUB_EVENT_PATH`
|
||||
- `GITHUB_TOKEN`
|
||||
|
||||
## Configuration
|
||||
|
||||
See [.env.example](/Users/home/Projects/ghbot/.env.example:1) for local testing values.
|
||||
|
||||
Important variables:
|
||||
|
||||
- `GITHUB_TOKEN`: GitHub token used by the workflow or local simulation
|
||||
- `OPENAI_API_KEY`: API key for the reviewer model
|
||||
- `OPENAI_BASE_URL`: optional OpenAI-compatible API base URL
|
||||
- `OPENAI_MODEL`: defaults to `gpt-4.1`
|
||||
- `OPENAI_REASONING_EFFORT`: optional reasoning effort, one of `low`, `medium`, or `high`
|
||||
- `BOT_NAME`: defaults to `ghbot`, but the workflow sets it to `github-actions[bot]`
|
||||
- `LENIENT_APPROVAL_USER`: defaults to `lezi-fun`
|
||||
- `AUTO_MERGE`: defaults to `false`
|
||||
- `MERGE_METHOD`: defaults to `squash`
|
||||
- `REQUIRE_CHECKS`: defaults to `true`
|
||||
- `MAX_PATCH_CHARS`: defaults to `120000`
|
||||
|
||||
## 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`.
|
||||
@@ -1,66 +0,0 @@
|
||||
import type { VercelRequest, VercelResponse } from "@vercel/node";
|
||||
import { waitUntil } from "@vercel/functions";
|
||||
import { logger } from "../../src/logger.js";
|
||||
|
||||
export const config = {
|
||||
api: {
|
||||
bodyParser: false
|
||||
}
|
||||
};
|
||||
|
||||
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 { createGitHubWebhooks } = await import("../../src/github/webhookHandler.js");
|
||||
const webhooks = createGitHubWebhooks();
|
||||
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
-2248
File diff suppressed because it is too large.
Load diff
@@ -7,28 +7,18 @@
|
||||
"node": ">=22 <26"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"dev:vercel": "vercel dev",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/src/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,138 @@
|
||||
import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
import { createGitHubClient } from "../github/client.js";
|
||||
import { logger } from "../logger.js";
|
||||
import {
|
||||
processLenientCheckComment,
|
||||
processPullRequest,
|
||||
processPullRequestReviewApproval
|
||||
} from "../review/processor.js";
|
||||
|
||||
type GitHubRepository = {
|
||||
name: string;
|
||||
owner: {
|
||||
login: string;
|
||||
};
|
||||
full_name: string;
|
||||
};
|
||||
|
||||
type PullRequestPayload = {
|
||||
action: string;
|
||||
pull_request: {
|
||||
number: number;
|
||||
draft: boolean;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type IssueCommentPayload = {
|
||||
action: string;
|
||||
issue: {
|
||||
number: number;
|
||||
pull_request?: {
|
||||
url: string;
|
||||
};
|
||||
};
|
||||
comment: {
|
||||
body: string;
|
||||
user: {
|
||||
login: string;
|
||||
};
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type PullRequestReviewPayload = {
|
||||
action: string;
|
||||
review: {
|
||||
state: string;
|
||||
commit_id: string;
|
||||
user?: {
|
||||
login?: string;
|
||||
};
|
||||
};
|
||||
pull_request: {
|
||||
number: number;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const eventName = process.env.GITHUB_EVENT_NAME;
|
||||
const eventPath = process.env.GITHUB_EVENT_PATH;
|
||||
|
||||
if (!eventName || !eventPath) {
|
||||
throw new Error("GITHUB_EVENT_NAME and GITHUB_EVENT_PATH are required.");
|
||||
}
|
||||
|
||||
const payload = JSON.parse(fs.readFileSync(eventPath, "utf8")) as PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload;
|
||||
const octokit = createGitHubClient();
|
||||
|
||||
logger.info({ eventName }, "Handling GitHub Actions review event.");
|
||||
|
||||
if (eventName === "pull_request_target") {
|
||||
const prPayload = payload as PullRequestPayload;
|
||||
if (prPayload.action === "opened") {
|
||||
await octokit.rest.issues.createComment({
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
issue_number: prPayload.pull_request.number,
|
||||
body: "Automated review has started. I am checking this pull request now."
|
||||
});
|
||||
}
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
pullNumber: prPayload.pull_request.number
|
||||
},
|
||||
"strict"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventName === "issue_comment") {
|
||||
const commentPayload = payload as IssueCommentPayload;
|
||||
if (!commentPayload.issue.pull_request) {
|
||||
logger.info({ issueNumber: commentPayload.issue.number }, "Skipping issue comment because it is not on a pull request.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processLenientCheckComment(octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventName === "pull_request_review") {
|
||||
const reviewPayload = payload as PullRequestReviewPayload;
|
||||
const reviewerLogin = reviewPayload.review.user?.login;
|
||||
if (!reviewerLogin) {
|
||||
logger.warn({ pullNumber: reviewPayload.pull_request.number }, "Skipping review event without reviewer login.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processPullRequestReviewApproval(octokit, {
|
||||
owner: reviewPayload.repository.owner.login,
|
||||
repo: reviewPayload.repository.name,
|
||||
pullNumber: reviewPayload.pull_request.number,
|
||||
reviewerLogin,
|
||||
state: reviewPayload.review.state,
|
||||
commitId: reviewPayload.review.commit_id
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warn({ eventName }, "Unhandled GitHub Actions event.");
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
logger.error({ error, botName: config.botName }, "GitHub Actions review run failed.");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+42
-13
@@ -1,30 +1,58 @@
|
||||
import "dotenv/config";
|
||||
import { z } from "zod";
|
||||
|
||||
const optionalString = z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.string().optional());
|
||||
|
||||
const optionalNonEmptyString = z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.string().min(1).optional());
|
||||
|
||||
const envBoolean = z.preprocess((value) => {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
|
||||
switch (value.toLowerCase()) {
|
||||
case "true":
|
||||
case "1":
|
||||
case "yes":
|
||||
case "on":
|
||||
return true;
|
||||
case "false":
|
||||
case "0":
|
||||
case "no":
|
||||
case "off":
|
||||
return false;
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}, z.boolean());
|
||||
|
||||
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")),
|
||||
githubToken: z.string().min(1),
|
||||
openAiApiKey: z.string().min(1),
|
||||
openAiBaseUrl: z.string().url().optional(),
|
||||
openAiModel: z.string().min(1).default("gpt-4.1"),
|
||||
openAiReasoningEffort: z.enum(["default", "low", "medium", "high"]).optional().transform((value) => {
|
||||
openAiBaseUrl: optionalString.pipe(z.string().url().optional()),
|
||||
openAiModel: optionalNonEmptyString.default("gpt-4.1"),
|
||||
openAiReasoningEffort: z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.enum(["default", "low", "medium", "high"]).optional()).transform((value) => {
|
||||
return value === "default" ? undefined : value;
|
||||
}),
|
||||
botName: z.string().min(1).default("ghbot"),
|
||||
lenientApprovalUser: z.string().min(1).default("lezi-fun"),
|
||||
autoMerge: z.coerce.boolean().default(false),
|
||||
autoMerge: envBoolean.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)
|
||||
requireChecks: envBoolean.default(true),
|
||||
maxPatchChars: z.coerce.number().int().positive().default(120_000),
|
||||
logLevel: z.string().min(1).default("info")
|
||||
});
|
||||
|
||||
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,
|
||||
githubToken: process.env.GITHUB_TOKEN,
|
||||
openAiApiKey: process.env.OPENAI_API_KEY,
|
||||
openAiBaseUrl: process.env.OPENAI_BASE_URL,
|
||||
openAiModel: process.env.OPENAI_MODEL,
|
||||
@@ -34,5 +62,6 @@ export const config = configSchema.parse({
|
||||
autoMerge: process.env.AUTO_MERGE,
|
||||
mergeMethod: process.env.MERGE_METHOD,
|
||||
requireChecks: process.env.REQUIRE_CHECKS,
|
||||
maxPatchChars: process.env.MAX_PATCH_CHARS
|
||||
maxPatchChars: process.env.MAX_PATCH_CHARS,
|
||||
logLevel: process.env.LOG_LEVEL
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
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
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
|
||||
const IGNORED_CHECK_RUN_NAMES = new Set(["ghbot review", "bot-review"]);
|
||||
|
||||
export async function requiredChecksAreGreen(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
@@ -22,6 +24,10 @@ export async function requiredChecksAreGreen(
|
||||
]);
|
||||
|
||||
const failedCheck = checks.data.check_runs.find((check) => {
|
||||
if (IGNORED_CHECK_RUN_NAMES.has(check.name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
check.status !== "completed" ||
|
||||
!["success", "neutral", "skipped"].includes(check.conclusion ?? "")
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { config } from "../config.js";
|
||||
|
||||
export function createGitHubClient(): Octokit {
|
||||
return new Octokit({
|
||||
auth: config.githubToken
|
||||
});
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Webhooks } from "@octokit/webhooks";
|
||||
import { config } from "../config.js";
|
||||
import { getInstallationOctokit } from "./app.js";
|
||||
import { logger } from "../logger.js";
|
||||
import {
|
||||
isLenientCheckAction,
|
||||
processLenientCheckRunAction,
|
||||
processPullRequest,
|
||||
processPullRequestReviewApproval
|
||||
} 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
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
webhooks.on("check_run.requested_action", async ({ payload }) => {
|
||||
const actionIdentifier = payload.requested_action?.identifier;
|
||||
if (!actionIdentifier || !isLenientCheckAction(actionIdentifier)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const installationId = payload.installation?.id;
|
||||
if (!installationId) {
|
||||
logger.warn({ repository: payload.repository.full_name, checkRun: payload.check_run.id }, "Skipping check action without installation id.");
|
||||
return;
|
||||
}
|
||||
|
||||
const octokit = await getInstallationOctokit(installationId);
|
||||
await processLenientCheckRunAction(octokit, {
|
||||
owner: payload.repository.owner.login,
|
||||
repo: payload.repository.name,
|
||||
headSha: payload.check_run.head_sha
|
||||
});
|
||||
});
|
||||
|
||||
webhooks.on("pull_request_review.submitted", async ({ payload }) => {
|
||||
const reviewerLogin = payload.review.user?.login;
|
||||
if (!reviewerLogin) {
|
||||
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without reviewer login.");
|
||||
return;
|
||||
}
|
||||
|
||||
const installationId = payload.installation?.id;
|
||||
if (!installationId) {
|
||||
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without installation id.");
|
||||
return;
|
||||
}
|
||||
|
||||
const octokit = await getInstallationOctokit(installationId);
|
||||
await processPullRequestReviewApproval(octokit, {
|
||||
owner: payload.repository.owner.login,
|
||||
repo: payload.repository.name,
|
||||
pullNumber: payload.pull_request.number,
|
||||
reviewerLogin,
|
||||
state: payload.review.state,
|
||||
commitId: payload.review.commit_id
|
||||
});
|
||||
});
|
||||
|
||||
webhooks.onError((error) => {
|
||||
logger.error({ error }, "Webhook handler failed.");
|
||||
});
|
||||
|
||||
return webhooks;
|
||||
}
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
import pino from "pino";
|
||||
import { config } from "./config.js";
|
||||
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL ?? "info"
|
||||
level: config.logLevel
|
||||
});
|
||||
@@ -14,6 +14,10 @@ export function formatReviewBody(decision: ReviewDecision, unpostedFindings: Rev
|
||||
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
|
||||
];
|
||||
|
||||
if (mode === "strict" && !decision.safeToMerge && !decision.shouldClosePullRequest) {
|
||||
lines.push("", "Need a narrower pass? Comment `/lenient-check` on this PR.");
|
||||
}
|
||||
|
||||
if (unpostedFindings.length > 0) {
|
||||
lines.push("", "Findings that could not be attached inline:");
|
||||
for (const finding of unpostedFindings) {
|
||||
|
||||
+214
-44
@@ -9,8 +9,9 @@ import { OpenAiReviewer } from "./openaiReviewer.js";
|
||||
import { compactFilesForReview } from "./prompt.js";
|
||||
|
||||
const reviewer = new OpenAiReviewer();
|
||||
const LENIENT_ACTION_IDENTIFIER = "lenient_check";
|
||||
const CHECK_RUN_NAME = "ghbot review";
|
||||
export const LENIENT_COMMENT_COMMAND = "/lenient-check";
|
||||
const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise<void> {
|
||||
const { owner, repo, pullNumber } = ref;
|
||||
@@ -130,6 +131,81 @@ export async function processPullRequestReviewApproval(
|
||||
});
|
||||
}
|
||||
|
||||
export async function processLenientCheckComment(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
commenterLogin: string;
|
||||
commentBody: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
if (!isLenientCheckComment(params.commentBody)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const adminRecentlyResponded = await hasRecentAdminResponse(octokit, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber
|
||||
});
|
||||
|
||||
const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
username: params.commenterLogin
|
||||
});
|
||||
|
||||
const allowedPermissions = adminRecentlyResponded
|
||||
? new Set(["admin"])
|
||||
: new Set(["admin", "maintain", "write"]);
|
||||
|
||||
if (!allowedPermissions.has(permission.permission)) {
|
||||
logger.info(
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commenterLogin: params.commenterLogin,
|
||||
permission: permission.permission,
|
||||
adminRecentlyResponded
|
||||
},
|
||||
"Ignoring lenient check comment because commenter does not meet the current permission threshold."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commenterLogin: params.commenterLogin,
|
||||
adminRecentlyResponded,
|
||||
permission: permission.permission
|
||||
},
|
||||
"Processing lenient check comment command."
|
||||
);
|
||||
|
||||
await octokit.rest.issues.createComment({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
issue_number: params.pullNumber,
|
||||
body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.`
|
||||
});
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber
|
||||
},
|
||||
"lenient"
|
||||
);
|
||||
}
|
||||
|
||||
async function maybeMergePullRequest(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
@@ -232,37 +308,6 @@ async function hasCurrentHeadApprovalFrom(
|
||||
});
|
||||
}
|
||||
|
||||
export async function processLenientCheckRunAction(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
headSha: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const pulls = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
commit_sha: params.headSha
|
||||
});
|
||||
|
||||
const pullRequest = pulls.data.find((pull) => pull.state === "open");
|
||||
if (!pullRequest) {
|
||||
logger.warn(params, "No open pull request found for lenient check action.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: pullRequest.number
|
||||
},
|
||||
"lenient"
|
||||
);
|
||||
}
|
||||
|
||||
async function listPullRequestFiles(
|
||||
octokit: Octokit,
|
||||
owner: string,
|
||||
@@ -297,6 +342,13 @@ async function submitReview(
|
||||
mode: ReviewMode;
|
||||
}
|
||||
): Promise<void> {
|
||||
await dismissExistingBotReviews(octokit, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commitId: params.commitId
|
||||
});
|
||||
|
||||
const validLines = collectValidNewLines(params.files);
|
||||
const filesByPath = new Map(params.files.map((file) => [file.filename, file]));
|
||||
const unpostedFindings: ReviewFinding[] = [];
|
||||
@@ -371,21 +423,12 @@ async function upsertReviewCheckRun(
|
||||
? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}`
|
||||
: params.decision.summary
|
||||
},
|
||||
actions:
|
||||
params.mode === "strict" && conclusion === "action_required"
|
||||
? [
|
||||
{
|
||||
label: "Lenient check",
|
||||
description: "Run only critical runtime checks.",
|
||||
identifier: LENIENT_ACTION_IDENTIFIER
|
||||
}
|
||||
]
|
||||
: undefined
|
||||
details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}`
|
||||
});
|
||||
}
|
||||
|
||||
export function isLenientCheckAction(identifier: string): boolean {
|
||||
return identifier === LENIENT_ACTION_IDENTIFIER;
|
||||
export function isLenientCheckComment(body: string): boolean {
|
||||
return body.trim().startsWith(LENIENT_COMMENT_COMMAND);
|
||||
}
|
||||
|
||||
async function closeMaliciousPullRequest(
|
||||
@@ -439,3 +482,130 @@ async function waitForMergeable(
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
async function dismissExistingBotReviews(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
commitId: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
for (const review of reviews) {
|
||||
if (review.user?.login !== config.botName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (review.commit_id !== params.commitId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!review.id || review.state === "DISMISSED") {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await octokit.rest.pulls.dismissReview({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
review_id: review.id,
|
||||
message: "Superseded by a newer automated review run."
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
reviewId: review.id
|
||||
},
|
||||
"Failed to dismiss existing bot review."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function hasRecentAdminResponse(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
const threshold = Date.now() - ADMIN_RESPONSE_WINDOW_MS;
|
||||
|
||||
const [comments, reviews] = await Promise.all([
|
||||
octokit.paginate(octokit.rest.issues.listComments, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
issue_number: params.pullNumber,
|
||||
per_page: 100
|
||||
}),
|
||||
octokit.paginate(octokit.rest.pulls.listReviews, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
per_page: 100
|
||||
})
|
||||
]);
|
||||
|
||||
const actors = new Map<string, number>();
|
||||
|
||||
for (const comment of comments) {
|
||||
const login = comment.user?.login;
|
||||
const createdAt = comment.created_at ? Date.parse(comment.created_at) : NaN;
|
||||
if (!login || Number.isNaN(createdAt) || createdAt < threshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
actors.set(login, Math.max(actors.get(login) ?? 0, createdAt));
|
||||
}
|
||||
|
||||
for (const review of reviews) {
|
||||
const login = review.user?.login;
|
||||
const submittedAt = review.submitted_at ? Date.parse(review.submitted_at) : NaN;
|
||||
if (!login || Number.isNaN(submittedAt) || submittedAt < threshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
actors.set(login, Math.max(actors.get(login) ?? 0, submittedAt));
|
||||
}
|
||||
|
||||
for (const login of actors.keys()) {
|
||||
try {
|
||||
const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
username: login
|
||||
});
|
||||
|
||||
if (permission.permission === "admin") {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
login
|
||||
},
|
||||
"Failed to resolve collaborator permission while checking for recent admin response."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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.");
|
||||
});
|
||||
+2
-1
@@ -10,5 +10,6 @@
|
||||
"outDir": "dist",
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": ["src/**/*.ts", "api/**/*.ts"]
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/server.ts", "src/github/app.ts", "src/github/webhookHandler.ts", "api/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user