AI-Assisted Code Review
Automated PR review, diff summarization, security scanning, and quality gates using AI coding tools
title: "AI-Assisted Code Review" description: "Automated PR review, diff summarization, security scanning, and quality gates using AI coding tools" section: "Workflows" readTime: "14 min"
AI-Assisted Code Review
AI tools can act as a first-pass reviewer that catches bugs, security issues, and style problems before a human ever opens the PR. This doesn't replace human review — it raises the baseline quality so human reviewers can focus on architecture and intent rather than typos and null checks.
What AI Review Can Catch
| Category | Examples |
|---|---|
| Security | Hardcoded secrets, SQL injection, missing input validation, IDOR vulnerabilities |
| Bugs | Null pointer dereferences, off-by-one errors, unhandled promise rejections |
| Performance | N+1 queries, missing indexes, sync operations in async context |
| Style | Inconsistent naming, dead code, overly complex functions |
| Test coverage | Missing edge cases, missing error path tests |
| Documentation | Public API functions without JSDoc |
Claude Code: Built-in Review Commands
Before writing your own prompts, try the review commands that ship with Claude Code:
| Command | What it does |
|---|---|
/code-review [effort] [target] | Reviews your branch's commits ahead of upstream plus uncommitted changes for correctness bugs. Runs as a background subagent with its own context. Pass a file path, PR number, branch, or range like main...my-feature to review something else |
/review | Alias of /code-review |
/code-review ultra | Deep multi-agent review in a cloud sandbox (ultrareview); /ultrareview is an alias. Requires a claude.ai account |
/security-review | Checks the diff between your branch and origin's default branch for vulnerabilities (injection, auth issues, data exposure). Needs an origin remote |
/simplify [target] | Cleanup-only review (reuse, simplification, efficiency, abstraction level) that applies fixes. Does not hunt for bugs |
Useful /code-review flags:
--fix— apply the findings to your working tree after the review--comment— post findings as inline comments on a GitHub PR (or a note on a GitLab MR)--max-findings <n>/all/default— change how many findings are reported
# Interactive
/code-review high 1234 # review PR #1234 at high effort
/code-review --fix # review current branch and apply fixes
# Non-interactive (waits for the review and prints findings)
claude -p "/code-review"
claude ultrareview 1234 --json # cloud review from a script or CI jobThe effort level trades coverage for confidence: low reports only the most confident findings, medium through max broaden coverage. If you don't type a level, the review reuses the last one you typed.
/code-review follows your CLAUDE.md but does not read REVIEW.md (that file is for the managed Code Review service below). A background review's --fix edits happen outside your session's checkpoints, so /rewind won't undo them — use git.
Claude Code: Pre-commit Review Hook
Setup
Create a shell script that runs Claude on staged changes:
# .git/hooks/pre-commit (or use via husky)
#!/bin/bash
DIFF=$(git diff --cached)
if [ -z "$DIFF" ]; then
exit 0
fi
echo "$DIFF" | claude -p "Review this git diff for:
1. Security vulnerabilities (OWASP Top 10)
2. Obvious bugs or null reference risks
3. Missing error handling
Respond with: PASS if no critical issues, or BLOCK: <reason> if there is a critical issue.
Only flag genuine problems — do not nitpick style."
# Check exit code / parse outputFull PR Diff Review
# Review a PR's full diff against main
git diff main...HEAD | claude -p "You are a senior code reviewer.
Review this diff for bugs, security issues, and missing tests.
Format your response as:
## Critical (must fix)
## Important (should fix)
## Suggestions (optional)
Be concise — one line per issue with the file and line reference."Security-Focused Scan
claude "Perform a security audit of the files I've changed in this PR.
Run: git diff main...HEAD --name-only
Then read each changed file and look for:
- Hardcoded credentials or API keys
- SQL/NoSQL injection vectors
- Missing authentication checks on API routes
- Unvalidated user input passed to shell commands or eval
Report findings with file name, line number, and severity (Critical/High/Medium)."Writer/Reviewer Pattern
A fresh context reviews better because it isn't biased toward code it just wrote. Have one session (or a subagent) implement and another review:
Use a subagent to review the rate limiter diff against PLAN.md. Check that
every requirement is implemented, the listed edge cases have tests, and
nothing outside the task's scope changed. Report gaps, not style preferences.
Tell the reviewer to flag only gaps that affect correctness or stated requirements — a reviewer asked to find problems will usually report some, and chasing every one leads to over-engineering.
Claude Code Review (Managed PR Reviews)
Code Review is a managed service (research preview, Team and Enterprise plans) that reviews GitHub PRs with a fleet of agents on Anthropic infrastructure, verifies candidate findings against actual code behavior, and posts inline comments. It is not available with Zero Data Retention or the HIPAA configuration.
Setup: an Owner opens claude.ai/admin-settings/claude-code, clicks Setup, installs the Claude GitHub App, selects repositories, and picks a Review Behavior per repo: Once after PR creation, After every push, or Manual.
| Marker | Severity | Meaning |
|---|---|---|
| 🔴 | Important | A bug that should be fixed before merging |
| 🟡 | Nit | Minor issue, not blocking |
| 🟣 | Pre-existing | A bug already in the codebase, not introduced by this PR |
| PR comment | Effect |
|---|---|
@claude review | One-off review, no subscription to future pushes |
@claude review always | Review now and on every subsequent push |
@claude review once | Same as @claude review |
Post the command as a top-level PR comment; you need write access. The Claude Code Review check run always completes neutral, so it never blocks merges on its own — parse its output in your own CI if you want a gate.
Customize with REVIEW.md at the repo root: redefine what counts as Important, cap nit volume, list paths to skip (generated code, lockfiles), and add repo-specific checks. CLAUDE.md is also read, and new violations of it are flagged as nits.
# Review instructions
## What Important means here
Reserve Important for findings that would break behavior, leak data,
or block a rollback. Style and naming are Nit at most.
## Do not report
- Anything CI already enforces: lint, formatting, type errors
- Generated files under `src/gen/` and any `*.lock` file
## Always check
- New API routes have an integration test
- Database queries are scoped to the caller's tenantCost: billed on token usage, averaging $15–25 per review, through usage credits separate from plan usage. After every push costs the most.
GitHub Copilot Code Review
Review in VS Code
- Open the Source Control view (
Ctrl+Shift+G) - Hover over the CHANGES heading and click Copilot Code Review - Uncommitted Changes
- Copilot's comments appear inline in your files and in the Problems tab
To review just part of a file, select the code, right-click, and choose Generate Code > Review; comments appear inline and in the Comments panel.
On GitHub.com, request Copilot as a reviewer from a pull request's Reviewers menu.
Review Comments
In Copilot Chat with the PR diff in context:
Review these changes. For each issue found, suggest a concrete fix
rather than just describing the problem.
Summarize what this PR does in 3 sentences, then list any concerns
about the implementation approach.
Auto-Review on PR Open
Automatic Copilot code review is available on Copilot Pro, Pro+ and Max plans and with a Copilot Business or Enterprise license. Turn it on in any of these places (each is evaluated separately, and Copilot still posts a single review):
- Personal: Copilot settings → Code review → Automatic Copilot code review (optionally also Review new pushes and Review draft pull requests)
- Repository: Settings → Rulesets → new branch ruleset set to Active → branch rule Automatically request Copilot code review
- Organization: Settings → Repository → Rulesets → new branch ruleset targeting repositories by pattern, with the same branch rule
Steer what it focuses on with repository custom instructions in .github/copilot-instructions.md, and add path-specific rules in .github/instructions/*.instructions.md with an applyTo glob:
<!-- .github/copilot-instructions.md -->
When reviewing pull requests, focus on security and performance.<!-- .github/instructions/api.instructions.md -->
---
applyTo: "src/api/**/*.ts"
---
Every route handler must validate its request body and check authentication.Add excludeAgent: "code-review" to an instruction file's frontmatter to keep code review from using it. Instructions scope what Copilot checks; they aren't a documented way to exclude files from review.
Cursor Code Review
In Cursor's Agent chat, attach your changes with @Commit (Diff of Working State) for uncommitted changes or @Branch (Diff with Main) for the whole branch:
@Branch Review these changes for security vulnerabilities and edge cases I might have missed.
Or reference specific files:
Compare @src/api/users.ts with the interface defined in @types/api.ts —
are there any mismatches or missing validations?
Automated Review Pipeline (CI)
Official GitHub Action
The simplest route is Claude Code GitHub Actions. Run /install-github-app in Claude Code to install the GitHub App, store the secret (ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN), and open a PR with the workflow files. Or add a review workflow yourself:
# .github/workflows/claude-review.yml
name: Code Review
on:
pull_request:
types: [opened, synchronize, ready_for_review, reopened]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
plugin_marketplaces: "https://github.com/anthropics/claude-code.git"
plugins: "code-review@claude-code-plugins"
prompt: "/code-review:code-review --comment ${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
claude_args: '--allowedTools "mcp__github_inline_comment__create_inline_comment"'--comment makes Claude post inline comments on the PR; the claude_args line is required so the action starts the inline-comment MCP server. Add --max-turns to claude_args and a workflow timeout to cap cost. For an @claude-mention workflow instead, omit prompt.
Custom Script Step
For full control, call the CLI directly in a CI step:
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
ai-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get PR diff
run: git diff origin/${{ github.base_ref }}...HEAD > /tmp/pr.diff
- name: AI Security Scan
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
cat /tmp/pr.diff | npx -y @anthropic-ai/claude-code -p --max-turns 3 \
"Scan for OWASP Top 10 vulnerabilities only.
Output ONLY raw JSON, no prose: [{file, line, severity, description}] or []" \
> /tmp/security-findings.json
# Fail if critical issues found
if jq -e '[.[] | select(.severity == "Critical")] | length > 0' /tmp/security-findings.json; then
echo "Critical security issues found:"
cat /tmp/security-findings.json
exit 1
fiReview Prompt Templates
Quick Review
Review this diff. Flag only: bugs that will cause runtime errors,
security vulnerabilities, and unhandled edge cases. One line per finding.
Thorough Review
You are a senior engineer reviewing a PR. Evaluate:
1. Correctness — will this code work as intended?
2. Security — any attack vectors introduced?
3. Performance — any O(n²) or missing caching?
4. Maintainability — is this readable in 6 months?
5. Tests — are the right cases covered?
Be specific: include file names and line numbers.
Focused Review
This PR adds payment processing. Focus exclusively on:
- PCI-DSS compliance (no card data in logs)
- Idempotency of payment mutations
- Error handling for partial charges
- Webhook signature verification