-
Notifications
You must be signed in to change notification settings - Fork 264
feat(web): multi-phase review agent with per-file parallel LLM calls #1164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fatmcgav
wants to merge
3
commits into
sourcebot-dev:main
Choose a base branch
from
fatmcgav:feat-improve-agent-llm-efficiency
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
packages/web/src/features/agents/review-agent/nodes/generateMrSummary.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import { sourcebot_context, sourcebot_pr_payload } from "@/features/agents/review-agent/types"; | ||
| import { getAISDKLanguageModelAndOptions, getConfiguredLanguageModels } from "@/features/chat/utils.server"; | ||
| import { validateLogPath } from "@/features/agents/review-agent/nodes/invokeDiffReviewLlm"; | ||
| import { env } from "@sourcebot/shared"; | ||
| import { generateText } from "ai"; | ||
| import { createLogger } from "@sourcebot/shared"; | ||
| import fs from "fs"; | ||
|
|
||
| const logger = createLogger('generate-mr-summary'); | ||
|
|
||
| /** | ||
| * Makes a single LLM call over the entire MR diff to identify cross-file | ||
| * semantic changes (renames, signature changes, removed exports, etc.) that | ||
| * individual per-file reviewers should be aware of. Returns null when there | ||
| * are no notable cross-file concerns or if the call fails — the per-file | ||
| * review pipeline always continues regardless. | ||
| */ | ||
| export const generateMrSummary = async ( | ||
| pr_payload: sourcebot_pr_payload, | ||
| reviewAgentLogPath: string | undefined, | ||
| ): Promise<sourcebot_context | null> => { | ||
| logger.debug("Executing generate_mr_summary"); | ||
|
|
||
| const models = await getConfiguredLanguageModels(); | ||
| if (models.length === 0) { | ||
| logger.warn("No language models configured, skipping MR summary"); | ||
| return null; | ||
| } | ||
|
|
||
| let selectedModel = models[0]; | ||
| if (env.REVIEW_AGENT_MODEL) { | ||
| const match = models.find((m) => m.displayName === modelName); | ||
| if (match) { | ||
| selectedModel = match; | ||
| } else { | ||
| logger.warn(`REVIEW_AGENT_MODEL="${env.REVIEW_AGENT_MODEL}" did not match any configured model displayName. Falling back to the first configured model.`); | ||
| } | ||
| } | ||
|
|
||
| const { model, providerOptions, temperature } = await getAISDKLanguageModelAndOptions(selectedModel); | ||
|
|
||
| const diffSummary = pr_payload.file_diffs.map((fileDiff) => { | ||
| const header = fileDiff.from !== fileDiff.to | ||
| ? `File: ${fileDiff.to} (renamed from ${fileDiff.from})` | ||
| : `File: ${fileDiff.to}`; | ||
| const hunks = fileDiff.diffs.map((d, i) => | ||
| `Hunk ${i + 1}:\n--- Old\n${d.oldSnippet}\n+++ New\n${d.newSnippet}` | ||
| ).join('\n\n'); | ||
| return `${header}\n${hunks}`; | ||
| }).join('\n\n---\n\n'); | ||
|
|
||
| const prompt = `You are reviewing a pull request titled "${pr_payload.title}". | ||
|
|
||
| Below are all the changed files and their diffs. Identify and summarise semantic changes that reviewers of individual files should be aware of — such as renamed functions or types, changed signatures or interfaces, removed exports, or behaviour changes with cross-file implications. | ||
|
|
||
| If there are no noteworthy cross-file semantic concerns, respond with an empty string. | ||
|
|
||
| # Changed Files | ||
|
|
||
| ${diffSummary}`; | ||
|
|
||
| if (reviewAgentLogPath) { | ||
| validateLogPath(reviewAgentLogPath); | ||
| fs.appendFileSync(reviewAgentLogPath, `\n\nMR Summary Prompt:\n${prompt}`); | ||
| } | ||
|
|
||
| try { | ||
| const result = await generateText({ | ||
| model, | ||
| system: "You are a code review assistant. Provide a concise plain-text summary of cross-file semantic changes in a pull request. Respond with an empty string if there are none.", | ||
| prompt, | ||
| providerOptions, | ||
| temperature, | ||
| }); | ||
|
|
||
| const summary = result.text.trim(); | ||
|
|
||
| if (reviewAgentLogPath) { | ||
| validateLogPath(reviewAgentLogPath); | ||
| fs.appendFileSync(reviewAgentLogPath, `\n\nMR Summary Response:\n${summary}`); | ||
| } | ||
| if (!summary) { | ||
| logger.debug("No cross-file semantic changes detected, skipping summary context"); | ||
| return null; | ||
| } | ||
|
|
||
| logger.debug("Completed generate_mr_summary"); | ||
| return { | ||
| type: "pr_summary", | ||
| description: "A summary of cross-file semantic changes in this pull request", | ||
| context: summary, | ||
| }; | ||
| } catch (error) { | ||
| logger.error("Error generating MR summary, proceeding without it:", error); | ||
| return null; | ||
| } | ||
| }; | ||
117 changes: 83 additions & 34 deletions
117
packages/web/src/features/agents/review-agent/nodes/generatePrReview.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,52 +1,101 @@ | ||
| import { sourcebot_pr_payload, sourcebot_diff_review, sourcebot_file_diff_review, sourcebot_context } from "@/features/agents/review-agent/types"; | ||
| import { sourcebot_pr_payload, sourcebot_file_diff_review, sourcebot_context } from "@/features/agents/review-agent/types"; | ||
| import { generateDiffReviewPrompt } from "@/features/agents/review-agent/nodes/generateDiffReviewPrompt"; | ||
| import { invokeDiffReviewLlm } from "@/features/agents/review-agent/nodes/invokeDiffReviewLlm"; | ||
| import { fetchFileContent } from "@/features/agents/review-agent/nodes/fetchFileContent"; | ||
| import { generateMrSummary } from "@/features/agents/review-agent/nodes/generateMrSummary"; | ||
| import { createLogger } from "@sourcebot/shared"; | ||
|
|
||
| const logger = createLogger('generate-pr-review'); | ||
|
|
||
| export const generatePrReviews = async (reviewAgentLogFileName: string | undefined, pr_payload: sourcebot_pr_payload, rules: string[]): Promise<sourcebot_file_diff_review[]> => { | ||
| logger.debug("Executing generate_pr_reviews"); | ||
| const MAX_CONCURRENT_FILE_REVIEWS = 5; | ||
|
|
||
| const file_diff_reviews: sourcebot_file_diff_review[] = []; | ||
| for (const file_diff of pr_payload.file_diffs) { | ||
| const reviews: sourcebot_diff_review[] = []; | ||
| /** | ||
| * Runs tasks with a bounded concurrency limit, returning results in the same | ||
| * order as the input array and using the same PromiseSettledResult shape as | ||
| * Promise.allSettled. | ||
| */ | ||
| async function withConcurrencyLimit<T>( | ||
| tasks: Array<() => Promise<T>>, | ||
| limit: number, | ||
| ): Promise<PromiseSettledResult<T>[]> { | ||
| const results: PromiseSettledResult<T>[] = new Array(tasks.length); | ||
| let nextIndex = 0; | ||
|
|
||
| for (const diff of file_diff.diffs) { | ||
| async function worker() { | ||
| while (nextIndex < tasks.length) { | ||
| const index = nextIndex++; | ||
| try { | ||
| const fileContentContext = await fetchFileContent(pr_payload, file_diff.to); | ||
| const context: sourcebot_context[] = [ | ||
| { | ||
| type: "pr_title", | ||
| description: "The title of the pull request", | ||
| context: pr_payload.title, | ||
| }, | ||
| { | ||
| type: "pr_description", | ||
| description: "The description of the pull request", | ||
| context: pr_payload.description, | ||
| }, | ||
| fileContentContext, | ||
| ]; | ||
|
|
||
| const prompt = await generateDiffReviewPrompt(diff, context, rules); | ||
|
|
||
| const diffReview = await invokeDiffReviewLlm(reviewAgentLogFileName, prompt); | ||
| reviews.push(...diffReview.reviews); | ||
| } catch (error) { | ||
| logger.error(`Error generating review for ${file_diff.to}: ${error}`); | ||
| results[index] = { status: 'fulfilled', value: await tasks[index]() }; | ||
| } catch (reason) { | ||
| results[index] = { status: 'rejected', reason }; | ||
| } | ||
| } | ||
|
|
||
| if (reviews.length > 0) { | ||
| file_diff_reviews.push({ | ||
| } | ||
|
|
||
| await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker)); | ||
| return results; | ||
| } | ||
|
|
||
| export const generatePrReviews = async (reviewAgentLogFileName: string | undefined, pr_payload: sourcebot_pr_payload, rules: string[]): Promise<sourcebot_file_diff_review[]> => { | ||
| logger.debug("Executing generate_pr_reviews"); | ||
|
|
||
| // Run MR summary upfront to detect cross-file semantic changes. | ||
| const mrSummaryResult = await Promise.allSettled([ | ||
| generateMrSummary(pr_payload, reviewAgentLogFileName), | ||
| ]); | ||
|
|
||
| const mrSummaryContext: sourcebot_context[] = []; | ||
| if (mrSummaryResult[0].status === 'fulfilled' && mrSummaryResult[0].value !== null) { | ||
| mrSummaryContext.push(mrSummaryResult[0].value); | ||
| } else if (mrSummaryResult[0].status === 'rejected') { | ||
| logger.warn(`MR summary generation failed: ${mrSummaryResult[0].reason}`); | ||
| } | ||
|
|
||
| // Per-file review — one LLM call per file, parallelised with a concurrency cap. | ||
| logger.debug(`Reviewing ${pr_payload.file_diffs.length} file(s)`); | ||
| const fileResults = await withConcurrencyLimit( | ||
| pr_payload.file_diffs.map((file_diff) => async () => { | ||
| const fileContentContext = await fetchFileContent(pr_payload, file_diff.to); | ||
| const context: sourcebot_context[] = [ | ||
| { | ||
| type: "pr_title", | ||
| description: "The title of the pull request", | ||
| context: pr_payload.title, | ||
| }, | ||
| { | ||
| type: "pr_description", | ||
| description: "The description of the pull request", | ||
| context: pr_payload.description, | ||
| }, | ||
| fileContentContext, | ||
| ...mrSummaryContext, | ||
| ]; | ||
|
|
||
| const prompt = await generateDiffReviewPrompt(file_diff.diffs, context, rules); | ||
| const diffReview = await invokeDiffReviewLlm(reviewAgentLogFileName, prompt); | ||
|
|
||
| if (diffReview.reviews.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| return { | ||
| filename: file_diff.to, | ||
| reviews: reviews, | ||
| }); | ||
| oldFilename: file_diff.from, | ||
| reviews: diffReview.reviews, | ||
| } satisfies sourcebot_file_diff_review; | ||
| }), | ||
| MAX_CONCURRENT_FILE_REVIEWS, | ||
| ); | ||
|
|
||
| const file_diff_reviews: sourcebot_file_diff_review[] = []; | ||
| for (const result of fileResults) { | ||
| if (result.status === 'rejected') { | ||
| logger.error(`Error generating review: ${result.reason}`); | ||
| } else if (result.value !== null) { | ||
| file_diff_reviews.push(result.value); | ||
| } | ||
| } | ||
|
|
||
| logger.debug("Completed generate_pr_reviews"); | ||
| return file_diff_reviews; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.