Add lenient review check action

This commit is contained in:
lezi-fun committed 2026-05-12 21:32:04 +08:00
1 parent 63eba2db87
commit 5cca2e8564
6 files changed
+153 -21

No files matched your search

+4 -1
View File
@@ -10,6 +10,8 @@ GitHub App bot that reviews pull requests with an AI reviewer, leaves inline rev
- `safeToMerge=true` only when there are no blocking findings. - `safeToMerge=true` only when there are no blocking findings.
- `blocking` findings become request-changes reviews. - `blocking` findings become request-changes reviews.
- `suggestion` findings are included as non-blocking suggestions. - `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.
- Posts inline comments only on valid added diff lines. - Posts inline comments only on valid added diff lines.
- Approves clean pull requests. - Approves clean pull requests.
- If `AUTO_MERGE=true`, merges only after: - If `AUTO_MERGE=true`, merges only after:
@@ -23,13 +25,14 @@ Create a GitHub App with these repository permissions:
- Contents: `Read & write` - Contents: `Read & write`
- Pull requests: `Read & write` - Pull requests: `Read & write`
- Checks: `Read-only` - Checks: `Read & write`
- Commit statuses: `Read-only` - Commit statuses: `Read-only`
- Metadata: `Read-only` - Metadata: `Read-only`
Subscribe to this webhook event: Subscribe to this webhook event:
- Pull request - Pull request
- Check run
Set the webhook URL to: Set the webhook URL to:
+22 -3
View File
@@ -2,7 +2,7 @@ import { Webhooks } from "@octokit/webhooks";
import { config } from "../config.js"; import { config } from "../config.js";
import { getInstallationOctokit } from "./app.js"; import { getInstallationOctokit } from "./app.js";
import { logger } from "../logger.js"; import { logger } from "../logger.js";
import { processPullRequest } from "../review/processor.js"; import { isLenientCheckAction, processLenientCheckRunAction, processPullRequest } from "../review/processor.js";
export function createGitHubWebhooks(): Webhooks { export function createGitHubWebhooks(): Webhooks {
const webhooks = new Webhooks({ const webhooks = new Webhooks({
@@ -22,12 +22,31 @@ export function createGitHubWebhooks(): Webhooks {
await processPullRequest(octokit, { await processPullRequest(octokit, {
owner: payload.repository.owner.login, owner: payload.repository.owner.login,
repo: payload.repository.name, repo: payload.repository.name,
pullNumber: payload.pull_request.number, pullNumber: payload.pull_request.number
installationId
}); });
} }
); );
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.onError((error) => { webhooks.onError((error) => {
logger.error({ error }, "Webhook handler failed."); logger.error({ error }, "Webhook handler failed.");
}); });
+4 -2
View File
@@ -1,9 +1,11 @@
import type { ReviewDecision, ReviewFinding } from "../types.js"; import type { ReviewDecision, ReviewFinding, ReviewMode } from "../types.js";
export function formatReviewBody(decision: ReviewDecision, unpostedFindings: ReviewFinding[]): string { export function formatReviewBody(decision: ReviewDecision, unpostedFindings: ReviewFinding[], mode: ReviewMode): string {
const lines = [ const lines = [
`## Automated review`, `## Automated review`,
"", "",
`Mode: ${mode === "lenient" ? "lenient" : "strict"}`,
"",
decision.summary, decision.summary,
"", "",
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}` `Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
+29 -9
View File
@@ -1,7 +1,7 @@
import OpenAI from "openai"; import OpenAI from "openai";
import { z } from "zod"; import { z } from "zod";
import { config } from "../config.js"; import { config } from "../config.js";
import type { PullRequestFile, ReviewDecision } from "../types.js"; import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js";
const reviewDecisionSchema = z.object({ const reviewDecisionSchema = z.object({
safeToMerge: z.boolean(), safeToMerge: z.boolean(),
@@ -24,6 +24,7 @@ export class OpenAiReviewer {
title: string; title: string;
body: string | null; body: string | null;
files: PullRequestFile[]; files: PullRequestFile[];
mode: ReviewMode;
}): Promise<ReviewDecision> { }): Promise<ReviewDecision> {
const response = await this.client.chat.completions.create({ const response = await this.client.chat.completions.create({
model: config.openAiModel, model: config.openAiModel,
@@ -62,14 +63,7 @@ export class OpenAiReviewer {
messages: [ messages: [
{ {
role: "system", role: "system",
content: [ content: buildSystemPrompt(input.mode)
"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", role: "user",
@@ -98,3 +92,29 @@ export class OpenAiReviewer {
return reviewDecisionSchema.parse(JSON.parse(raw)); return reviewDecisionSchema.parse(JSON.parse(raw));
} }
} }
function buildSystemPrompt(mode: ReviewMode): string {
const commonRules = [
"You are a senior software engineer reviewing a GitHub pull request.",
"Only set safeToMerge=true when there are no blocking findings.",
"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."
];
if (mode === "lenient") {
return [
...commonRules,
"This is a lenient review requested by the pull request author.",
"Only report issues that are dangerous, affect runtime behavior, can cause errors, can crash, can break builds/tests, can lose data, or create clear security problems.",
"Do not block on style, naming, subjective maintainability, small refactors, missing comments, formatting, or non-dangerous best-practice preferences.",
"Use suggestion severity only when the issue is still runtime-relevant but not necessarily blocking."
].join(" ");
}
return [
...commonRules,
"This is a strict review.",
"Find correctness bugs, security issues, data-loss risks, broken tests, bad error handling, and maintainability problems.",
"Use suggestion severity for non-blocking style or clarity improvements."
].join(" ");
}
+92 -5
View File
@@ -3,14 +3,16 @@ import { config } from "../config.js";
import { requiredChecksAreGreen } from "../github/checks.js"; import { requiredChecksAreGreen } from "../github/checks.js";
import { collectValidNewLines, toDiffPosition } from "../github/diff.js"; import { collectValidNewLines, toDiffPosition } from "../github/diff.js";
import { logger } from "../logger.js"; import { logger } from "../logger.js";
import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding } from "../types.js"; import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding, ReviewMode } from "../types.js";
import { formatReviewBody } from "./format.js"; import { formatReviewBody } from "./format.js";
import { OpenAiReviewer } from "./openaiReviewer.js"; import { OpenAiReviewer } from "./openaiReviewer.js";
import { compactFilesForReview } from "./prompt.js"; import { compactFilesForReview } from "./prompt.js";
const reviewer = new OpenAiReviewer(); const reviewer = new OpenAiReviewer();
const LENIENT_ACTION_IDENTIFIER = "lenient_check";
const CHECK_RUN_NAME = "ghbot review";
export async function processPullRequest(octokit: Octokit, ref: PullRequestRef): Promise<void> { export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise<void> {
const { owner, repo, pullNumber } = ref; const { owner, repo, pullNumber } = ref;
const { data: pullRequest } = await octokit.rest.pulls.get({ const { data: pullRequest } = await octokit.rest.pulls.get({
@@ -34,7 +36,8 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef):
const decision = await reviewer.review({ const decision = await reviewer.review({
title: pullRequest.title, title: pullRequest.title,
body: pullRequest.body, body: pullRequest.body,
files: compactFiles files: compactFiles,
mode
}); });
await submitReview(octokit, { await submitReview(octokit, {
@@ -43,7 +46,17 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef):
pullNumber, pullNumber,
commitId: pullRequest.head.sha, commitId: pullRequest.head.sha,
files, files,
decision decision,
mode
});
await upsertReviewCheckRun(octokit, {
owner,
repo,
headSha: pullRequest.head.sha,
pullNumber,
decision,
mode
}); });
if (!decision.safeToMerge) { if (!decision.safeToMerge) {
@@ -93,6 +106,37 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef):
}); });
} }
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( async function listPullRequestFiles(
octokit: Octokit, octokit: Octokit,
owner: string, owner: string,
@@ -124,6 +168,7 @@ async function submitReview(
commitId: string; commitId: string;
files: PullRequestFile[]; files: PullRequestFile[];
decision: ReviewDecision; decision: ReviewDecision;
mode: ReviewMode;
} }
): Promise<void> { ): Promise<void> {
const validLines = collectValidNewLines(params.files); const validLines = collectValidNewLines(params.files);
@@ -163,11 +208,53 @@ async function submitReview(
pull_number: params.pullNumber, pull_number: params.pullNumber,
commit_id: params.commitId, commit_id: params.commitId,
event, event,
body: formatReviewBody(params.decision, unpostedFindings), body: formatReviewBody(params.decision, unpostedFindings, params.mode),
comments comments
}); });
} }
async function upsertReviewCheckRun(
octokit: Octokit,
params: {
owner: string;
repo: string;
headSha: string;
pullNumber: number;
decision: ReviewDecision;
mode: ReviewMode;
}
): Promise<void> {
const hasBlockingFinding = params.decision.findings.some((finding) => finding.severity === "blocking");
const conclusion = params.decision.safeToMerge && !hasBlockingFinding ? "success" : "action_required";
await octokit.rest.checks.create({
owner: params.owner,
repo: params.repo,
name: CHECK_RUN_NAME,
head_sha: params.headSha,
status: "completed",
conclusion,
output: {
title: params.mode === "lenient" ? "Lenient review completed" : "Strict review completed",
summary: params.decision.summary
},
actions:
params.mode === "strict" && conclusion === "action_required"
? [
{
label: "Lenient check",
description: "Run only critical runtime checks.",
identifier: LENIENT_ACTION_IDENTIFIER
}
]
: undefined
});
}
export function isLenientCheckAction(identifier: string): boolean {
return identifier === LENIENT_ACTION_IDENTIFIER;
}
async function waitForMergeable( async function waitForMergeable(
octokit: Octokit, octokit: Octokit,
owner: string, owner: string,
+2 -1
View File
@@ -2,7 +2,6 @@ export type PullRequestRef = {
owner: string; owner: string;
repo: string; repo: string;
pullNumber: number; pullNumber: number;
installationId: number;
}; };
export type PullRequestFile = { export type PullRequestFile = {
@@ -27,6 +26,8 @@ export type ReviewDecision = {
findings: ReviewFinding[]; findings: ReviewFinding[];
}; };
export type ReviewMode = "strict" | "lenient";
export type DiffPosition = { export type DiffPosition = {
path: string; path: string;
line: number; line: number;