import { spawnSync } from "node:child_process"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { chinese, english } from "./pr-review-language.mjs"; const FILES_PER_PAGE = 100; const MAX_FILES = 300; const MAX_DIFF_LENGTH = 400_000; const MAX_FILE_LENGTH = 36_000; const CI_WAIT_MS = 240_000; const CI_APPEAR_WAIT_MS = 60_000; const MAX_FINDINGS = 3; const MAX_PENDING_CHECKS = 3; const MAX_PREVIOUS_COMMENTS = 8; const MARKER_PREFIX = "\r?\n?/, "").trim(); const result = { commit: latest.commit_id || null, summary: shortText(body, 1200), inlineFindings: reviewComments.slice(0, MAX_PREVIOUS_COMMENTS).map((comment) => ({ path: comment.path, side: comment.side ?? "RIGHT", line: comment.line ?? comment.original_line ?? null, body: shortText(comment.body ?? "", 160), })), }; if (Array.isArray(changedFilesSince)) { result.changedFilesSincePreviousReview = changedFilesSince.slice(0, 60); } return result; } async function fetchReviewHistory(github, repoPath, path, headSha, marker) { const botReviews = []; let reviewed = false; for (let page = 1; ; page++) { const { data, link } = await github(path + "/reviews?per_page=100&page=" + page); for (const review of data) { if (review.user?.login !== "github-actions[bot]" || review.state !== "COMMENTED") continue; if (review.body?.startsWith(marker + "\n")) reviewed = true; if (review.body?.startsWith(MARKER_PREFIX)) botReviews.push(review); } if (reviewed || !link?.includes('rel="next"')) break; } if (reviewed) return { alreadyReviewed: true, previousReview: null }; const latest = botReviews.at(-1); if (!latest) return { alreadyReviewed: false, previousReview: null }; let comments = []; try { ({ data: comments } = await github(path + "/reviews/" + latest.id + "/comments?per_page=100")); } catch { comments = []; } let changedSince = null; if (latest.commit_id && latest.commit_id !== headSha) { try { const { data: comparison } = await github(repoPath + "/compare/" + latest.commit_id + "..." + headSha + "?per_page=1"); changedSince = (comparison.files ?? []).map((file) => file.filename); } catch { changedSince = null; } } return { alreadyReviewed: false, previousReview: extractPreviousReview(botReviews, comments, changedSince), }; } async function fetchHeadCommitMessage(github, repoPath, sha) { try { const { data } = await github(repoPath + "/commits/" + sha); return data?.commit?.message ?? ""; } catch { return ""; } } function snapshot(pull) { return [pull.head.sha, pull.base.sha]; } async function listChangedFiles(github, path) { const files = []; for (let page = 1; files.length < MAX_FILES; page++) { const { data, link } = await github(path + "/files?per_page=" + FILES_PER_PAGE + "&page=" + page); files.push(...data); if (!link?.includes('rel="next"') || !data.length) break; } return files.slice(0, MAX_FILES); } export async function waitForCI(github, repoPath, pull, number, { skipCI = false, wait = true } = {}) { if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" }; const startedAt = Date.now(); const deadline = startedAt + CI_WAIT_MS; const appearDeadline = startedAt + CI_APPEAR_WAIT_MS; const path = repoPath + "/actions/workflows/ci.yml/runs?event=pull_request&per_page=20&head_sha=" + pull.head.sha; for (;;) { const { data } = await github(path); const run = data.workflow_runs.find((run) => run.head_sha === pull.head.sha && run.head_repository?.full_name === pull.head.repo.full_name && run.head_branch === pull.head.ref && (!run.pull_requests.length || run.pull_requests.some((pr) => pr.number === Number(number)))); if (run?.status === "completed") { const { data: jobs } = await github(repoPath + "/actions/runs/" + run.id + "/attempts/" + run.run_attempt + "/jobs"); const verify = jobs.jobs.find((job) => job.name === "verify"); const steps = verify?.steps.filter((step) => /^(CI tests|Frontend test|Go test|Bundle frontend|Build reims-go|WebView2)/.test(step.name)); return { status: "completed", id: run.id, attempt: run.run_attempt, url: run.html_url, conclusion: verify?.conclusion ?? run.conclusion, steps: (steps ?? []).map(({ name, conclusion }) => ({ name, conclusion })), }; } const now = Date.now(); const remaining = deadline - now; if (!wait || remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) { return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url }; } await delay(Math.min(20_000, remaining)); } } function reviewMarker(revision, mainSha, ci) { return MARKER_PREFIX + [revision, mainSha, ci.id ?? "none", ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->"; } async function mainlineContext(github, repoPath, pull, files) { const branch = pull.base.repo.default_branch; const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch); const { data: ref } = await github(refPath); const sha = ref.object.sha; let comparison; try { ({ data: comparison } = await github(repoPath + "/compare/" + pull.head.sha + "..." + sha + "?per_page=1")); } catch (error) { if (![404, 409, 422].includes(error.status)) throw error; console.log("GitHub could not compare the PR head to the default branch"); return { refPath, branch, sha, comparisonUnavailable: true }; } const paths = new Set(files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean))); const mainFiles = comparison.files ?? []; const overlap = mainFiles.filter((file) => paths.has(file.filename) || paths.has(file.previous_filename)); const { diffs, partial } = selectDiffs(overlap, 45_000); return { refPath, branch, sha, mergeBase: comparison.merge_base_commit.sha, mainlineCommitsSinceBranching: comparison.ahead_by, comparedFiles: mainFiles.length, recentPaths: mainFiles.slice(0, 120).map((file) => file.filename), fileListMayBeTruncated: mainFiles.length >= MAX_FILES, overlappingFiles: overlap.length, partialOverlaps: partial, overlappingDiffs: diffs, }; } export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, hasFindings, locations }) { const lines = []; for (const key of REVIEW_SECTIONS) { if (!assessment[key].trim()) continue; lines.push("- **" + copy[key] + "** " + plainMarkdown(shortText(assessment[key], 75))); } const ciPassed = ci.status === "completed" && ci.conclusion === "success"; const ciFailed = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion); const ciNeedsAction = ci.conclusion === "action_required" || ci.status === "action_required"; let ciStatus = ci.id ? copy.ciPending : copy.ciMissing; if (ciNeedsAction) ciStatus = copy.ciActionRequired; else if (ciPassed) ciStatus = copy.ciPassed; else if (ci.status === "completed") ciStatus = (ciFailed ? copy.ciFailed : copy.ciNoPass) + " (`" + ci.conclusion + "`)"; lines.push("\n**" + copy.tests + "** " + ciStatus + (ci.url ? " · [" + copy.ciRun + "](" + ci.url + ")" : "")); for (const step of ci.steps ?? []) { lines.push("- " + plainMarkdown(step.name) + " · " + plainMarkdown(step.conclusion ?? "—")); } const pending = assessment.pending_checks.filter((check) => MANUAL_IMPACTS.has(check?.impact) && typeof check.scenario === "string" && check.scenario.trim() && typeof check.consequence === "string" && check.consequence.trim() && hasChangedEvidence(locations.get(check.path), check.evidence)).slice(0, MAX_PENDING_CHECKS); if (pending.length) { lines.push("\n**" + copy.pending + "**"); for (const check of pending) { lines.push("- " + plainMarkdown(shortText(check.scenario, 75)) + " · " + plainMarkdown(shortText(check.consequence, 60))); } } let decision = "merge"; let reason = copy.noFindings; if (mergeable === false) { decision = "changes"; reason = copy.conflict; } else if (ciFailed) { decision = "changes"; reason = copy.fixCI; } else if (hasFindings) { decision = "changes"; reason = copy.fixFindings; } else if (assessment.decision === "decline") { decision = "decline"; reason = plainMarkdown(shortText(assessment.reason, 110)); } else if (pending.length) { decision = "verify"; reason = copy.pendingRequired; } else if (incomplete) { decision = "inspect"; reason = copy.incomplete; } else if (!ciPassed) { decision = "awaitCI"; reason = copy.ciRequired; } lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason); return lines.join("\n"); } export async function run() { if (!process.env.PR_REVIEW_LLM_KEY?.trim()) { console.log("PR review skipped: set the PR_REVIEW_LLM_KEY repository secret"); return; } const event = JSON.parse(await readFile(required("GITHUB_EVENT_PATH"), "utf8")); const number = event.pull_request?.number ?? event.inputs?.pull_number; if (!/^[1-9]\d*$/.test(String(number))) throw new Error("Missing or invalid PR number"); const repo = required("GITHUB_REPOSITORY"); const api = required("GITHUB_API_URL"); const token = required("GITHUB_TOKEN"); const github = (route, body) => githubRequest(api + route, token, body); const repoPath = "/repos/" + repo; const path = repoPath + "/pulls/" + number; const { data: pull } = await github(path); if (pull.state !== "open" || (event.pull_request && event.pull_request.head.sha !== pull.head.sha)) { console.log("PR is closed or the event is outdated"); return; } const isManual = !event.pull_request; const headCommitMessage = !isManual && pull.draft ? "" : await fetchHeadCommitMessage(github, repoPath, pull.head.sha); const skipReason = shouldSkipAutoReview({ isManual, draft: Boolean(pull.draft), commitMessage: headCommitMessage }); if (skipReason) { console.log("PR review skipped: " + skipReason); return; } const revision = snapshot(pull).join(":"); const [files, ci] = await Promise.all([ listChangedFiles(github, path), waitForCI(github, repoPath, pull, number, { skipCI: hasSkipCIToken(headCommitMessage) }), ]); const mainline = await mainlineContext(github, repoPath, pull, files); const marker = reviewMarker(revision, mainline.sha, ci); const history = await fetchReviewHistory(github, repoPath, path, pull.head.sha, marker); if (history.alreadyReviewed) { console.log("This PR revision has already been reviewed"); return; } const { diffs, locations, partial } = selectDiffs(files); async function currentPR() { const { data: current } = await github(path); return current.state === "open" && snapshot(current).join(":") === revision ? current : null; } if (!(await currentPR())) { console.log("PR changed while reading the diff"); return; } const { refPath, ...comparison } = mainline; const reviewInput = { title: pull.title.slice(0, 300), description: (pull.body ?? "").slice(0, 3500), head: pull.head.sha, base: { branch: pull.base.ref, reportedSha: pull.base.sha, mergeable: pull.mergeable }, mainline: comparison, goVersion: (await readFile("go.mod", "utf8")).match(/^go (\S+)/m)?.[1], coverage: { reviewedFiles: diffs.length, changedFiles: pull.changed_files, partialFiles: partial }, ci: { ...ci, changesCIWorkflow: files.some((file) => file.filename === ".github/workflows/ci.yml") }, diffs, }; if (history.previousReview) reviewInput.previousReview = history.previousReview; const assessment = await reviewDiffs( reviewInput, files.some((file) => file.filename.startsWith("frontend/") || file.previous_filename?.startsWith("frontend/")), ); const { findings } = assessment; const copy = localizedCopy(assessment); const comments = inlineComments(findings, locations); const coverage = copy.scope + " " + diffs.length + "/" + pull.changed_files + (partial ? " (" + partial + " " + copy.partial + ")" : ""); const result = comments.length ? copy.inline + " · " + comments.length : diffs.length ? "" : copy.noDiff; let finalCI = ci; if (ci.conclusion !== "success") { try { finalCI = await waitForCI(github, repoPath, pull, number, { wait: false }); } catch (error) { console.warn("Could not refresh CI: " + error.message); } } const finalMarker = reviewMarker(revision, mainline.sha, finalCI); if (finalMarker !== marker) { const { alreadyReviewed } = await fetchReviewHistory(github, repoPath, path, pull.head.sha, finalMarker); if (alreadyReviewed) { console.log("This PR revision has already been reviewed with the latest CI result"); return; } } const latestPR = await currentPR(); if (!latestPR) { console.log("PR changed while the model was reviewing it"); return; } const { data: latestMain } = await github(refPath); const mainMoved = latestMain.object.sha !== mainline.sha; const mainCoverage = mainline.comparisonUnavailable ? copy.comparisonUnavailable : mainline.overlappingFiles > mainline.overlappingDiffs.length || mainline.partialOverlaps || mainline.fileListMayBeTruncated ? copy.comparisonPartial : ""; const scopeNotes = [mainCoverage, mainMoved ? copy.mainMoved : ""].filter(Boolean); const assessmentSummary = reviewSummary(copy, assessment, finalCI, { incomplete: !diffs.length || diffs.length < pull.changed_files || partial > 0, mergeable: latestPR.mergeable, hasFindings: comments.length > 0, locations, }); const summary = finalMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage + (scopeNotes.length ? " · " + scopeNotes.join(" ") : "") + "\n\n" + assessmentSummary; const review = { event: "COMMENT", commit_id: pull.head.sha, body: result ? summary + "\n\n" + result : summary, }; if (comments.length) review.comments = comments; try { await github(path + "/reviews", review); } catch (error) { if (error.status !== 422 || !comments.length || !(await currentPR())) throw error; const details = comments.map(({ path, line, side, body }) => "- " + plainMarkdown(path) + " " + side + ":" + line + " · " + body); delete review.comments; review.body = summary + "\n\n" + copy.inlineFallback + "\n\n" + details.join("\n"); await github(path + "/reviews", review); } console.log("Review submitted"); } if (process.argv[1]?.endsWith("pr-review.mjs")) { run().catch((error) => { console.error(error.message); process.exitCode = 1; }); }