Use Codex CLI for PR reviews
This commit is contained in:
1 parent
fd9479590a
commit
341a6ce69b
9 files changed
+269
-604
No files matched your search
+9
-15
@@ -5,10 +5,6 @@ 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;
|
||||
@@ -33,14 +29,12 @@ const envBoolean = z.preprocess((value) => {
|
||||
const configSchema = z.object({
|
||||
port: z.coerce.number().int().positive().default(3000),
|
||||
githubToken: z.string().min(1),
|
||||
openAiApiKey: z.string().min(1),
|
||||
openAiBaseUrl: optionalString.pipe(z.string().url().optional()),
|
||||
openAiModel: optionalNonEmptyString.default("gpt-4.1"),
|
||||
openAiReasoningEffort: z.preprocess((value) => {
|
||||
codexModel: optionalString.default("gpt-5.4"),
|
||||
codexReasoningEffort: z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.enum(["default", "low", "medium", "high"]).optional()).transform((value) => {
|
||||
return value === "default" ? undefined : value;
|
||||
}),
|
||||
}, z.enum(["minimal", "low", "medium", "high", "xhigh"]).optional()),
|
||||
codexBaseUrl: optionalString,
|
||||
codexApiKey: z.string().min(1),
|
||||
botName: z.string().min(1).default("ghbot"),
|
||||
lenientApprovalUser: z.string().min(1).default("lezi-fun"),
|
||||
autoMerge: envBoolean.default(false),
|
||||
@@ -53,10 +47,10 @@ const configSchema = z.object({
|
||||
export const config = configSchema.parse({
|
||||
port: process.env.PORT,
|
||||
githubToken: process.env.GITHUB_TOKEN,
|
||||
openAiApiKey: process.env.OPENAI_API_KEY,
|
||||
openAiBaseUrl: process.env.OPENAI_BASE_URL,
|
||||
openAiModel: process.env.OPENAI_MODEL,
|
||||
openAiReasoningEffort: process.env.OPENAI_REASONING_EFFORT,
|
||||
codexModel: process.env.CODEX_MODEL,
|
||||
codexReasoningEffort: process.env.CODEX_REASONING_EFFORT,
|
||||
codexBaseUrl: process.env.CODEX_BASE_URL,
|
||||
codexApiKey: process.env.CODEX_API_KEY,
|
||||
botName: process.env.BOT_NAME,
|
||||
lenientApprovalUser: process.env.LENIENT_APPROVAL_USER,
|
||||
autoMerge: process.env.AUTO_MERGE,
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { config } from "../config.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const reviewDecisionSchema = z.object({
|
||||
safeToMerge: z.boolean(),
|
||||
shouldClosePullRequest: z.boolean(),
|
||||
closeReason: z.string(),
|
||||
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 CodexCliReviewer {
|
||||
async review(input: {
|
||||
title: string;
|
||||
body: string | null;
|
||||
files: PullRequestFile[];
|
||||
mode: ReviewMode;
|
||||
}): Promise<ReviewDecision> {
|
||||
return withRetry("codex.exec.review", async () => {
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ghbot-codex-"));
|
||||
const schemaPath = path.join(tempDir, "review-schema.json");
|
||||
const outputPath = path.join(tempDir, "review-output.json");
|
||||
const codexHome = path.join(tempDir, "codex-home");
|
||||
|
||||
try {
|
||||
await fs.mkdir(codexHome, { recursive: true });
|
||||
await fs.writeFile(path.join(codexHome, "config.toml"), buildCodexConfig(), "utf8");
|
||||
await fs.writeFile(schemaPath, JSON.stringify(buildSchema(), null, 2), "utf8");
|
||||
|
||||
const prompt = buildPrompt(input);
|
||||
const args = [
|
||||
"exec",
|
||||
"--skip-git-repo-check",
|
||||
"--sandbox",
|
||||
"workspace-write",
|
||||
"--ask-for-approval",
|
||||
"never",
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
"-C",
|
||||
process.cwd(),
|
||||
"--ephemeral"
|
||||
];
|
||||
|
||||
args.push(prompt);
|
||||
|
||||
logger.info(
|
||||
{
|
||||
mode: input.mode,
|
||||
fileCount: input.files.length,
|
||||
model: config.codexModel,
|
||||
reasoningEffort: config.codexReasoningEffort,
|
||||
baseUrl: normalizeBaseUrl(config.codexBaseUrl)
|
||||
},
|
||||
"Running Codex CLI review."
|
||||
);
|
||||
|
||||
try {
|
||||
await execFileAsync("codex", args, {
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
...process.env,
|
||||
CODEX_HOME: codexHome,
|
||||
CODEX_API_KEY: config.codexApiKey
|
||||
},
|
||||
maxBuffer: 10 * 1024 * 1024
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
{
|
||||
error,
|
||||
mode: input.mode,
|
||||
fileCount: input.files.length,
|
||||
model: config.codexModel,
|
||||
reasoningEffort: config.codexReasoningEffort,
|
||||
baseUrl: normalizeBaseUrl(config.codexBaseUrl)
|
||||
},
|
||||
"Codex CLI review command failed."
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const raw = await fs.readFile(outputPath, "utf8");
|
||||
return reviewDecisionSchema.parse(JSON.parse(raw));
|
||||
} finally {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function buildCodexConfig(): string {
|
||||
const lines = [
|
||||
`model = ${toTomlString(config.codexModel)}`,
|
||||
'model_provider = "ghbot"',
|
||||
'approval_policy = "never"',
|
||||
'sandbox_mode = "workspace-write"'
|
||||
];
|
||||
|
||||
if (config.codexReasoningEffort) {
|
||||
lines.push(`model_reasoning_effort = ${toTomlString(config.codexReasoningEffort)}`);
|
||||
}
|
||||
|
||||
lines.push("", "[model_providers.ghbot]");
|
||||
lines.push('name = "ghbot"');
|
||||
lines.push(`base_url = ${toTomlString(normalizeBaseUrl(config.codexBaseUrl))}`);
|
||||
lines.push('env_key = "CODEX_API_KEY"');
|
||||
lines.push('wire_api = "responses"');
|
||||
lines.push("requires_openai_auth = false");
|
||||
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(value: string | undefined): string {
|
||||
const baseUrl = value?.trim();
|
||||
if (!baseUrl) {
|
||||
return "https://api.openai.com/v1";
|
||||
}
|
||||
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function toTomlString(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function buildSchema() {
|
||||
return {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"],
|
||||
properties: {
|
||||
safeToMerge: { type: "boolean" },
|
||||
shouldClosePullRequest: { type: "boolean" },
|
||||
closeReason: { type: "string" },
|
||||
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" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildPrompt(input: {
|
||||
title: string;
|
||||
body: string | null;
|
||||
files: PullRequestFile[];
|
||||
mode: ReviewMode;
|
||||
}): string {
|
||||
return [
|
||||
buildSystemPrompt(input.mode),
|
||||
"",
|
||||
"Pull request payload:",
|
||||
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 ?? ""
|
||||
}))
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildSystemPrompt(mode: ReviewMode): string {
|
||||
const commonRules = [
|
||||
"You are a senior software engineer reviewing a GitHub pull request.",
|
||||
"Return JSON that exactly matches the provided schema.",
|
||||
"Only set safeToMerge=true when there are no blocking findings.",
|
||||
"Set shouldClosePullRequest=true only for clearly malicious code: backdoors, credential theft, token exfiltration, destructive commands, malware, hidden persistence, privilege escalation, supply-chain compromise, or intentionally abusive behavior.",
|
||||
"Do not set shouldClosePullRequest=true for ordinary bugs, crashes, failing tests, incomplete code, suspicious-but-unproven code, or low-quality changes.",
|
||||
"When shouldClosePullRequest=true, explain the evidence in closeReason. Otherwise closeReason must be an empty string.",
|
||||
"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 flow.",
|
||||
"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(" ");
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import { OpenAI } from "openai";
|
||||
import { z } from "zod";
|
||||
import { config } from "../config.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js";
|
||||
|
||||
const reviewDecisionSchema = z.object({
|
||||
safeToMerge: z.boolean(),
|
||||
shouldClosePullRequest: z.boolean(),
|
||||
closeReason: z.string(),
|
||||
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,
|
||||
baseURL: config.openAiBaseUrl
|
||||
});
|
||||
|
||||
async review(input: {
|
||||
title: string;
|
||||
body: string | null;
|
||||
files: PullRequestFile[];
|
||||
mode: ReviewMode;
|
||||
}): Promise<ReviewDecision> {
|
||||
const response = await withRetry("openai.responses.create", async () => {
|
||||
return this.client.responses.create({
|
||||
model: config.openAiModel,
|
||||
temperature: 0.1,
|
||||
...(config.openAiReasoningEffort ? { reasoning: { effort: config.openAiReasoningEffort } } : {}),
|
||||
text: {
|
||||
format: {
|
||||
name: "pull_request_review",
|
||||
type: "json_schema",
|
||||
strict: true,
|
||||
schema: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"],
|
||||
properties: {
|
||||
safeToMerge: { type: "boolean" },
|
||||
shouldClosePullRequest: { type: "boolean" },
|
||||
closeReason: { type: "string" },
|
||||
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" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
instructions: buildSystemPrompt(input.mode),
|
||||
input: [
|
||||
{
|
||||
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.output_text;
|
||||
if (!raw) {
|
||||
throw new Error("OpenAI returned an empty review response.");
|
||||
}
|
||||
|
||||
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.",
|
||||
"Set shouldClosePullRequest=true only for clearly malicious code: backdoors, credential theft, token exfiltration, destructive commands, malware, hidden persistence, privilege escalation, supply-chain compromise, or intentionally abusive behavior.",
|
||||
"Do not set shouldClosePullRequest=true for ordinary bugs, crashes, failing tests, incomplete code, suspicious-but-unproven code, or low-quality changes.",
|
||||
"When shouldClosePullRequest=true, explain the evidence in closeReason. Otherwise closeReason must be an empty string.",
|
||||
"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(" ");
|
||||
}
|
||||
@@ -5,11 +5,11 @@ import { collectValidNewLines, toDiffPosition } from "../github/diff.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding, ReviewMode } from "../types.js";
|
||||
import { CodexCliReviewer } from "./codexCliReviewer.js";
|
||||
import { formatReviewBody } from "./format.js";
|
||||
import { OpenAiReviewer } from "./openaiReviewer.js";
|
||||
import { compactFilesForReview } from "./prompt.js";
|
||||
|
||||
const reviewer = new OpenAiReviewer();
|
||||
const reviewer = new CodexCliReviewer();
|
||||
const CHECK_RUN_NAME = "ghbot review";
|
||||
export const LENIENT_COMMENT_COMMAND = "/lenient-check";
|
||||
const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
Reference in new issue
Block a user