Setup and context — Why Automate PR Reviews with AI?
One of the biggest bottlenecks in team development is waiting for Pull Request (PR) code reviews. Work stalls while PRs sit in the review queue, stretching lead times and slowing down the entire delivery pipeline. It's a pain point nearly every development team has experienced.
By combining Antigravity's AI agents with GitHub, you can automatically check code quality, detect security risks, and generate improvement suggestions the moment a PR is created. Human reviewers then focus on the AI's findings rather than combing through every line, dramatically reducing review turnaround time.
This guide walks you through building an automated PR review workflow with Antigravity and GitHub, from environment setup to practical implementation. Whether you're new to AI-powered code reviews or looking to level up your existing workflow, you'll find actionable steps to get started right away.
Prerequisites and Setup
Before diving into AI-powered PR review automation, make sure you have the following in place:
- Antigravity IDE (latest version recommended)
- GitHub account with write access to your repository
- Node.js 18+ for running scripts
- Git installed locally
Start by connecting Antigravity to GitHub. Open the terminal in Antigravity and run:
# Verify GitHub CLI installation
gh --version
# gh version 2.x.x
# Authenticate with GitHub (first time only)
gh auth login
# A browser window will open for GitHub authenticationOnce authenticated, Antigravity's agents can directly access PR information from your GitHub repositories.
Analyzing PR Diffs with Antigravity Agents
Antigravity's greatest strength is that its AI agents understand your entire repository context when reviewing code. Unlike simple static analysis tools, they can consider your project's architectural decisions and check for consistency with existing patterns.
Basic PR Review Flow
In Antigravity's agent chat, make a request like this:
Please review PR #42 in this repository.
Focus on the following areas:
1. Type safety issues
2. Error handling adequacy
3. Performance impact of changes
The agent will execute gh pr diff 42 to fetch the diff, read through each changed file, and generate review comments with specific feedback.
Script for Extracting Diffs and Generating Review Prompts
Here's a reusable script that works for both manual and automated review workflows:
// scripts/ai-pr-review.ts
// Antigravity × GitHub PR review automation script
import { execSync } from "child_process";
interface ReviewComment {
file: string;
line: number;
severity: "error" | "warning" | "info";
message: string;
}
function getPRDiff(prNumber: number): string {
// Fetch the PR diff
const diff = execSync(`gh pr diff ${prNumber}`, {
encoding: "utf-8",
});
return diff;
}
function parseDiffFiles(diff: string): string[] {
// Extract changed file names from the diff
const files = diff
.split("\n")
.filter((line) => line.startsWith("diff --git"))
.map((line) => {
const match = line.match(/b\/(.+)$/);
return match ? match[1] : "";
})
.filter(Boolean);
return files;
}
function generateReviewPrompt(
diff: string,
files: string[]
): string {
return `
Please review the following PR diff.
## Review Criteria
- Type safety (potential TypeScript type errors)
- Error handling (unhandled exceptions, edge cases)
- Security (injection vulnerabilities, auth gaps)
- Performance (unnecessary re-renders, N+1 queries)
- Code quality (naming conventions, separation of concerns)
## Changed Files
${files.map((f) => `- ${f}`).join("\n")}
## Diff
\`\`\`diff
${diff}
\`\`\`
For each file, provide specific line numbers and improvement suggestions.
If no issues are found, mark the file as "LGTM".
`.trim();
}
// Main execution
const prNumber = parseInt(process.argv[2] || "0");
if (!prNumber) {
console.error("Usage: npx tsx scripts/ai-pr-review.ts <PR_NUMBER>");
process.exit(1);
}
const diff = getPRDiff(prNumber);
const files = parseDiffFiles(diff);
const prompt = generateReviewPrompt(diff, files);
console.log("📝 Files to review:");
files.forEach((f) => console.log(` - ${f}`));
console.log("\n🤖 Pass this prompt to the Antigravity agent:\n");
console.log(prompt);
// Expected output:
// 📝 Files to review:
// - src/components/UserProfile.tsx
// - src/lib/api.ts
//
// 🤖 Pass this prompt to the Antigravity agent:
// (Review prompt is displayed)Run this script with npx tsx scripts/ai-pr-review.ts 42 to automatically generate the diff and a review prompt ready for the Antigravity agent.
Triggering Automatic Reviews with GitHub Actions
Beyond manual reviews, you can set up automatic reviews that fire every time a PR is created or updated. GitHub Actions makes it straightforward to integrate code review into your CI/CD pipeline.
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
ai-review:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get changed files
id: changed
run: |
FILES=$(gh pr diff ${{ github.event.pull_request.number }} --name-only)
echo "files<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run lint and type check
run: |
npm ci
npm run lint -- --format json > lint-results.json || true
npx tsc --noEmit 2> type-errors.txt || true
- name: Post review summary
if: always()
run: |
LINT_ERRORS=$(cat lint-results.json | jq '[.[] | .messages | length] | add // 0')
TYPE_ERRORS=$(wc -l < type-errors.txt | tr -d ' ')
BODY="## 🤖 AI Code Review Summary\n\n"
BODY+="| Check | Result |\n"
BODY+="| --- | --- |\n"
BODY+="| Lint Errors | ${LINT_ERRORS} |\n"
BODY+="| Type Errors | ${TYPE_ERRORS} |\n\n"
if [ "$LINT_ERRORS" -gt 0 ] || [ "$TYPE_ERRORS" -gt 0 ]; then
BODY+="⚠️ Issues detected by automated checks. See step logs for details."
else
BODY+="✅ All automated checks passed."
fi
gh pr comment ${{ github.event.pull_request.number }} --body "$(echo -e "$BODY")"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}This workflow automatically runs lint and type checks whenever a PR is created or updated, then posts a summary comment directly on the PR.
For a deeper dive into advanced CI/CD pipelines with matrix builds and security scanning, check out Antigravity × GitHub Actions: Advanced CI/CD Pipeline Guide, which covers production-grade configurations in detail.
Customizing Review Standards with AGENTS.md
To ensure your Antigravity agents follow consistent review standards, define your review policy in an AGENTS.md file at the root of your repository.
# AGENTS.md — PR Review Policy
## Code Review Standards
### Must-Check Items (Blockers)
- Unhandled Promise / async-await errors
- Missing user input validation
- Hardcoded secrets (API keys, tokens)
- Inappropriate type assertions (as any)
### Recommendations (Suggestions)
- Suggest splitting functions longer than 50 lines
- Extract magic numbers into named constants
- Encourage comments that explain "why", not "what"
### Out of Scope
- Formatting (handled by Prettier)
- Import ordering (enforced by ESLint rules)When this file sits in your repository root, Antigravity's agents automatically reference it during reviews, generating comments that align with your team's specific standards and conventions.
Posting Review Results as GitHub Comments
Manually copying review results is tedious. Let's build a script that posts review comments directly to GitHub PRs via the GitHub API.
// scripts/post-review-comment.ts
// Post review results as a GitHub PR comment
import { execSync } from "child_process";
interface ReviewResult {
summary: string;
issues: Array<{
file: string;
line: number;
message: string;
}>;
approved: boolean;
}
function postReviewComment(
prNumber: number,
review: ReviewResult
): void {
const body = formatReviewBody(review);
// Post PR comment using gh CLI
execSync(
`gh pr comment ${prNumber} --body '${body.replace(/'/g, "'\\''")}'`,
{ stdio: "inherit" }
);
console.log(`✅ Review comment posted to PR #${prNumber}`);
}
function formatReviewBody(review: ReviewResult): string {
let body = "## 🤖 Antigravity AI Review\n\n";
body += `**Verdict**: ${review.approved ? "✅ LGTM" : "⚠️ Changes Requested"}\n\n`;
body += `### Summary\n${review.summary}\n\n`;
if (review.issues.length > 0) {
body += "### Issues Found\n\n";
for (const issue of review.issues) {
body += `- **${issue.file}:${issue.line}** — ${issue.message}\n`;
}
}
return body;
}
// Usage example
const sampleReview: ReviewResult = {
summary:
"Overall code quality is good. One error handling improvement identified.",
issues: [
{
file: "src/lib/api.ts",
line: 45,
message:
"Missing error handling for fetch. Add a try-catch block to handle network errors gracefully.",
},
],
approved: false,
};
const prNumber = parseInt(process.argv[2] || "0");
if (prNumber) {
postReviewComment(prNumber, sampleReview);
}
// Expected output:
// ✅ Review comment posted to PR #42Practical Workflow Design Tips
To get the most out of AI-powered PR reviews, here are some practical tips for designing your review workflow.
Layer Your Reviews
Rather than relying entirely on AI, structure your reviews in stages for the best results:
- Stage 1 (Fully Automated): Lint checks, type checking, security scanning
- Stage 2 (AI-Assisted): Code design review, performance impact analysis
- Stage 3 (Human): Business logic correctness, UX implications
Improve Review Quality with Context
Providing the Antigravity agent with specific context yields far more useful feedback:
Please review PR #42.
This PR migrates user authentication from session-based to JWT-based auth.
Focus especially on token handling and security implications.
When you include background information about the PR's purpose, the agent understands the intent behind changes and provides targeted, actionable feedback.
GitHub Integration Basics
For foundational guidance on connecting Antigravity with GitHub, see Antigravity × GitHub Integration Setup Guide. You might also find Streamlining Your Git Workflow with Antigravity helpful for day-to-day Git operations.
Summary
Automating GitHub PR reviews with Antigravity is a practical approach that can significantly boost your development team's productivity. Here's a recap of what we covered:
- Use Antigravity's AI agents to automatically analyze PR diffs for type safety, security, and performance issues
- Integrate with GitHub Actions to trigger automated quality checks on every PR
- Define project-specific review standards in
AGENTS.mdfor consistent code quality - Design a layered review workflow that clearly separates AI and human responsibilities
Start with a small project, iterate on your review criteria, and grow the automation as your team becomes comfortable with it. If you're interested in extending this to security auditing, Antigravity × AI-Driven Security Audit Automation Guide covers building a complete vulnerability detection and auto-fix pipeline.