import type { Octokit } from "@octokit/rest"; import { config } from "../config.js"; import { requiredChecksAreGreen } from "../github/checks.js"; import { postPermissionDeniedComment } from "../github/commandFeedback.js"; import { formatBotSignature, formatRuntimeEnvironmentDetails } from "../github/runtimeInfo.js"; import { formatBotDisplayName } from "../github/botIdentity.js"; import { collectValidNewLines, toDiffPosition } from "../github/diff.js"; import { logger } from "../logger.js"; import { withRetry } from "../retry.js"; import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewMode } from "../types.js"; import { deleteLocalReviewCache, loadPreviousReview, saveReviewCache } from "./cache.js"; import { GooseReviewer } from "./gooseReviewer.js"; import { formatFindingReviewBody, formatReviewBody, type CategorizedFinding } from "./format.js"; import { approvedLoginsForHead, evaluateReviewDecision, formatReviewExternalId, isReviewBranchEnabled, parseReviewExternalId, parseReviewStateMarker } from "./policy.js"; import { compactFilesForReview } from "./prompt.js"; import { loadRepositoryKnowledge } from "../repository/knowledge.js"; import { canAutoResolveConflicts, describeConflictResolutionFailure, resolvePullRequestConflicts } from "./conflictResolver.js"; const reviewer = new GooseReviewer(); const CHECK_RUN_NAME = "ghbot review"; export const RECHECK_COMMENT_COMMAND = "/recheck"; export const CONFLICT_COMMENT_COMMAND = "/conflict"; const REVIEW_PROGRESS_MARKER_PREFIX = "`; } function shortSha(headSha: string): string { return headSha.slice(0, 12); } async function findIssueCommentByMarker( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number }, marker: string ) { const comments = await octokit.paginate(octokit.rest.issues.listComments, { owner: params.owner, repo: params.repo, issue_number: params.pullNumber, per_page: 100 }); return comments.find((comment) => comment.body?.includes(marker)); } async function getLatestBotReviewOutcomeForHead( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number; headSha: string; } ) { const checks = await octokit.rest.checks.listForRef({ owner: params.owner, repo: params.repo, ref: params.headSha, check_name: CHECK_RUN_NAME, per_page: 100 }); const botChecks = checks.data.check_runs .filter((check) => check.name === CHECK_RUN_NAME) .sort((left, right) => { const leftTime = left.started_at ? Date.parse(left.started_at) : 0; const rightTime = right.started_at ? Date.parse(right.started_at) : 0; return rightTime - leftTime; }); for (const check of botChecks) { const outcome = parseReviewExternalId(check.external_id); if (outcome) { return outcome; } } return null; } async function listPullRequestFiles( octokit: Octokit, owner: string, repo: string, pullNumber: number ): Promise { 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; mode: ReviewMode; } ): Promise { const validLines = collectValidNewLines(params.files); const filesByPath = new Map(params.files.map((file) => [file.filename, file])); const disposition = evaluateReviewDecision(params.decision); const currentReviewIds: number[] = []; for (const phase of buildReviewSubmissionPlan(params.decision, disposition)) { const unpostedFindings: CategorizedFinding[] = []; const comments = phase.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.category === "change" ? "Required change" : "Review note"}: ${finding.title}**\n\n${finding.body}` } ]; }); const body = phase.phase === "final" ? formatReviewBody(params.decision, [], params.mode, disposition) : formatFindingReviewBody(params.decision, phase.phase, unpostedFindings, params.mode, disposition); const reviewId = await createGitHubReview(octokit, { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, commitId: params.commitId, event: phase.event, body, comments, logContext: { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, commitId: params.commitId } }); currentReviewIds.push(reviewId); } await supersedePreviousBotReviews(octokit, { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, currentReviewIds, currentCommitId: params.commitId }); } export type ReviewSubmissionPhase = { phase: "change" | "review" | "final"; event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"; findings: CategorizedFinding[]; }; export function buildReviewSubmissionPlan( decision: ReviewDecision, disposition: { event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES" } ): ReviewSubmissionPhase[] { const phases: ReviewSubmissionPhase[] = []; if (decision.change.length > 0) { phases.push({ phase: "change", event: "REQUEST_CHANGES", findings: decision.change.map((finding) => ({ ...finding, category: "change" as const })) }); } if (decision.review.length > 0) { phases.push({ phase: "review", event: "COMMENT", findings: decision.review.map((finding) => ({ ...finding, category: "review" as const })) }); } phases.push({ phase: "final", // Once a dedicated REQUEST_CHANGES review has been submitted, the final // summary must stay a comment so GitHub does not group review notes into // the change-request review. event: decision.change.length > 0 ? "COMMENT" : disposition.event, findings: [] }); return phases; } async function createGitHubReview( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number; commitId: string; event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"; body: string; comments: Array<{ path: string; line: number; side: "LEFT" | "RIGHT"; body: string; }>; logContext: { owner: string; repo: string; pullNumber: number; commitId: string }; } ): Promise { try { const response = await withRetry("github.pulls.createReview", async () => { return octokit.rest.pulls.createReview({ owner: params.owner, repo: params.repo, pull_number: params.pullNumber, commit_id: params.commitId, event: params.event, body: params.body, comments: params.comments }); }); return response.data.id; } catch (error) { if (!shouldFallbackToCommentReview(error, params.event)) { throw error; } logger.warn( { error, ...params.logContext }, "Falling back to COMMENT review because the current token is not allowed to approve pull requests." ); const response = await withRetry("github.pulls.createReview.commentFallback", async () => { return octokit.rest.pulls.createReview({ owner: params.owner, repo: params.repo, pull_number: params.pullNumber, commit_id: params.commitId, event: "COMMENT", body: params.body, comments: params.comments }); }); return response.data.id; } } async function upsertReviewCheckRun( octokit: Octokit, params: { owner: string; repo: string; headSha: string; pullNumber: number; decision: ReviewDecision; mode: ReviewMode; } ): Promise { const disposition = evaluateReviewDecision(params.decision); const conclusion = disposition.blocksMerge || disposition.requiresAdminApproval ? "action_required" : "success"; await withRetry("github.checks.create", async () => { return octokit.rest.checks.create({ owner: params.owner, repo: params.repo, name: CHECK_RUN_NAME, head_sha: params.headSha, status: "completed", conclusion, external_id: formatReviewExternalId(params.mode, disposition), output: { title: params.decision.result.shouldClosePullRequest ? "Malicious code detected" : disposition.requiresAdminApproval ? "Review notes require administrator approval" : `${params.mode === "strict" ? "Strict" : "Normal"} review completed`, summary: params.decision.result.shouldClosePullRequest ? `${params.decision.result.summary}\n\nClose reason: ${params.decision.result.closeReason}` : params.decision.result.summary }, details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}` }); }); } async function markReviewCheckApproved( octokit: Octokit, params: { owner: string; repo: string; headSha: string; pullNumber: number } ): Promise { const checks = await octokit.rest.checks.listForRef({ owner: params.owner, repo: params.repo, ref: params.headSha, check_name: CHECK_RUN_NAME, per_page: 100 }); const check = checks.data.check_runs .filter((item) => item.name === CHECK_RUN_NAME) .sort((left, right) => Date.parse(right.started_at ?? "") - Date.parse(left.started_at ?? ""))[0]; if (!check) { throw new Error(`Could not find ${CHECK_RUN_NAME} check for ${params.headSha}.`); } await withRetry("github.checks.update.adminApproved", async () => { return octokit.rest.checks.update({ owner: params.owner, repo: params.repo, check_run_id: check.id, status: "completed", conclusion: "success", external_id: check.external_id ?? undefined, output: { title: "Repository administrator approved review notes", summary: "The current pull request head has the administrator approval required by REVIEW_POLICY=require_approval." }, details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}` }); }); } export function isRecheckComment(body: string): boolean { return body.trim() === RECHECK_COMMENT_COMMAND; } export function isConflictComment(body: string): boolean { return body.trim() === CONFLICT_COMMENT_COMMAND; } async function closeMaliciousPullRequest( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number; reason: string; } ): Promise { await withRetry("github.issues.createComment.closeMalicious", async () => { return octokit.rest.issues.createComment({ owner: params.owner, repo: params.repo, issue_number: params.pullNumber, body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}` }); }); await withRetry("github.pulls.update.closeMalicious", async () => { return octokit.rest.pulls.update({ owner: params.owner, repo: params.repo, pull_number: params.pullNumber, state: "closed" }); }); } 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; } export async function supersedePreviousBotReviews( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number; currentReviewId?: number; currentReviewIds?: number[]; currentCommitId: string; } ): Promise { const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, { owner: params.owner, repo: params.repo, pull_number: params.pullNumber, per_page: 100 }); const currentReviewIds = new Set([ ...(params.currentReviewIds ?? []), ...(params.currentReviewId ? [params.currentReviewId] : []) ]); for (const review of reviews) { if (review.user?.type !== "Bot" || !parseReviewStateMarker(review.body)) { continue; } if (!review.id || currentReviewIds.has(review.id)) { continue; } const oldCommitId = review.commit_id ?? "unknown"; try { const comments = await octokit.paginate(octokit.rest.pulls.listCommentsForReview, { owner: params.owner, repo: params.repo, pull_number: params.pullNumber, review_id: review.id, per_page: 100 }); const commentsWithNodeIds = comments.filter( (comment): comment is typeof comment & { node_id: string } => Boolean(comment.node_id) ); const commentsToDelete = new Set(comments.filter((comment) => !comment.node_id).map((comment) => comment.id)); if (commentsWithNodeIds.length > 0) { let resolvedCommentNodeIds = new Set(); try { resolvedCommentNodeIds = await withRetry( "github.graphql.resolveReviewThread.superseded", async () => resolveReviewThreadsForComments(octokit, { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, commentNodeIds: commentsWithNodeIds.map((comment) => comment.node_id) }) ); } catch (error) { logger.warn( { error, owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, reviewId: review.id }, "Could not resolve superseded review threads through GraphQL; deleting only the affected inline comments." ); } // A comment not returned from the thread connection cannot be resolved // by its REST id. Delete only that exceptional remainder so one stale // API response does not leave old inline findings permanently active. for (const comment of commentsWithNodeIds) { if (!resolvedCommentNodeIds.has(comment.node_id)) { commentsToDelete.add(comment.id); } } } for (const commentId of commentsToDelete) { await withRetry("github.pulls.deleteReviewComment.superseded", async () => { return octokit.rest.pulls.deleteReviewComment({ owner: params.owner, repo: params.repo, comment_id: commentId }); }); } await withRetry("github.pulls.updateReview.superseded", async () => { return octokit.rest.pulls.updateReview({ owner: params.owner, repo: params.repo, pull_number: params.pullNumber, review_id: review.id, body: formatSupersededReviewBody({ originalMarker: extractReviewStateMarker(review.body), oldCommitId, currentCommitId: params.currentCommitId }) }); }); if (review.state !== "DISMISSED") { await withRetry("github.pulls.dismissReview.superseded", async () => { return octokit.rest.pulls.dismissReview({ owner: params.owner, repo: params.repo, pull_number: params.pullNumber, review_id: review.id, message: `Superseded by the automated review for commit ${shortSha(params.currentCommitId)}.` }); }); } await withRetry("github.graphql.minimizeReview.superseded", async () => { return octokit.graphql( `mutation MinimizeSupersededReview($subjectId: ID!) { minimizeComment(input: { subjectId: $subjectId, classifier: OUTDATED }) { minimizedComment { isMinimized } } }`, { subjectId: review.node_id } ); }); } catch (error) { logger.warn( { error, owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, reviewId: review.id }, "Failed to fully remove a superseded bot review." ); } } } export function formatSupersededReviewBody(params: { originalMarker: string; oldCommitId: string; currentCommitId: string; }): string { return [ params.originalMarker, "## Superseded automated review", "", `The review for commit \`${shortSha(params.oldCommitId)}\` has been replaced by the automated review for commit \`${shortSha(params.currentCommitId)}\`.`, "", "Its previous inline `review` and `change` threads were marked as resolved and hidden. Refer to the latest commit review for the current result." ].join("\n"); } async function resolveReviewThreadsForComments( octokit: Octokit, params: { owner: string; repo: string; pullNumber: number; commentNodeIds: string[] } ): Promise> { type ReviewThreadsResponse = { repository?: { pullRequest?: { reviewThreads?: { nodes?: Array<{ id: string; isResolved: boolean; comments?: { nodes?: Array<{ id: string }> } | null; } | null>; pageInfo: { hasNextPage: boolean; endCursor?: string | null }; } | null; } | null; } | null; }; const targetCommentNodeIds = new Set(params.commentNodeIds); const matchedCommentNodeIds = new Set(); let after: string | null = null; do { const result: ReviewThreadsResponse = await octokit.graphql( `query ReviewThreadsForSupersededReview($owner: String!, $repo: String!, $pullNumber: Int!, $after: String) { repository(owner: $owner, name: $repo) { pullRequest(number: $pullNumber) { reviewThreads(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { id isResolved comments(first: 100) { nodes { id } } } } } } }`, { owner: params.owner, repo: params.repo, pullNumber: params.pullNumber, after } ); const threads = result.repository?.pullRequest?.reviewThreads; if (!threads) { break; } for (const thread of threads.nodes ?? []) { if (!thread) { continue; } const threadCommentNodeIds = (thread.comments?.nodes ?? []) .map((comment) => comment?.id) .filter((commentId): commentId is string => typeof commentId === "string"); const matchingCommentNodeIds = threadCommentNodeIds.filter((commentId) => targetCommentNodeIds.has(commentId)); if (matchingCommentNodeIds.length === 0) { continue; } let threadResolved = thread.isResolved; if (!threadResolved) { try { await withRetry("github.graphql.resolveReviewThread.superseded.item", async () => { return octokit.graphql( `mutation ResolveReviewThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }`, { threadId: thread.id } ); }); threadResolved = true; } catch (error) { logger.warn( { error, threadId: thread.id }, "Could not resolve a superseded review thread." ); } } if (!threadResolved) { continue; } for (const commentNodeId of matchingCommentNodeIds) { matchedCommentNodeIds.add(commentNodeId); try { await withRetry("github.graphql.minimizeResolvedReviewComment.superseded", async () => { return octokit.graphql( `mutation MinimizeSupersededInlineComment($subjectId: ID!) { minimizeComment(input: { subjectId: $subjectId, classifier: RESOLVED }) { minimizedComment { isMinimized } } }`, { subjectId: commentNodeId } ); }); } catch (error) { // Resolution succeeded, so keep the comment rather than deleting it // merely because the optional visual minimization failed. logger.warn( { error, commentNodeId }, "Could not hide a resolved superseded review comment." ); } } } after = threads.pageInfo.hasNextPage ? threads.pageInfo.endCursor ?? null : null; } while (after); return matchedCommentNodeIds; } function extractReviewStateMarker(body: string | null | undefined): string { return body?.match(//)?.[0] ?? ""; } function shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"): boolean { if (event !== "APPROVE") { return false; } if (typeof error !== "object" || error === null || !("status" in error) || error.status !== 422) { return false; } if (!("message" in error) || typeof error.message !== "string") { return false; } return error.message.includes("GitHub Actions is not permitted to approve pull requests."); }