AI Code Reviewer
Automated code review with security scanning, best practices, and performance analysis.
This workflow analyzes pull requests for code quality, security vulnerabilities, and architectural issues.
Implementation
1import { relay } from "@relayplane/workflows";23const result = await relay4 .workflow("code-review")56 // Step 1: Analyze code quality and style7 .step("quality-analysis")8 .with("openai:gpt-4o")9 .prompt(`Review this code for quality and best practices:1011Language: {{language}}12File: {{filePath}}1314```{{language}}15{{codeChanges}}16```1718Check for:19- Code complexity (cyclomatic complexity)20- Function length (>50 lines is a smell)21- Naming conventions22- Code duplication23- Missing error handling24- Lack of input validation25- Poor separation of concerns26- Magic numbers or hardcoded values2728Rate severity: critical, major, minor, suggestion29Provide specific line numbers and fixes.`)3031 // Step 2: Security vulnerability scan32 .step("security-scan")33 .with("anthropic:claude-3.5-sonnet")34 .depends("quality-analysis")35 .prompt(`Scan for security vulnerabilities:3637Code:38```{{language}}39{{codeChanges}}40```4142Context: {{fileContext}}4344Check OWASP Top 10:45- SQL injection risks46- XSS vulnerabilities47- Authentication/authorization issues48- Sensitive data exposure49- Insecure deserialization50- Insufficient logging51- SSRF potential52- Command injection53- Path traversal5455For each finding:56- Vulnerability type57- Severity (critical/high/medium/low)58- Affected code snippet59- Exploitation scenario60- Remediation steps`)6162 // Step 3: Performance analysis63 .step("performance-review")64 .with("openai:gpt-4o")65 .depends("quality-analysis")66 .prompt(`Analyze performance implications:6768Code:69```{{language}}70{{codeChanges}}71```7273Identify:74- N+1 query problems75- Inefficient algorithms (time/space complexity)76- Unnecessary loops or iterations77- Missing indexes (database queries)78- Memory leaks potential79- Blocking operations in async code80- Missing caching opportunities8182Estimate performance impact: high/medium/low83Suggest optimizations with code examples.`)8485 // Step 4: Architecture and design review86 .step("architecture-review")87 .with("anthropic:claude-3.5-sonnet")88 .depends("quality-analysis", "security-scan", "performance-review")89 .prompt(`Review architectural decisions:9091Code: {{codeChanges}}92File: {{filePath}}93Project Context: {{projectContext}}9495Evaluate:96- Separation of concerns97- Dependency injection vs tight coupling98- SOLID principles adherence99- Design patterns appropriateness100- Testability101- API design (if applicable)102- Error handling strategy103- Logging and observability104105Suggest improvements aligned with project architecture.`)106107 // Step 5: Generate review summary108 .step("review-summary")109 .with("anthropic:claude-3.5-sonnet")110 .depends("quality-analysis", "security-scan", "performance-review", "architecture-review")111 .prompt(`Create pull request review summary:112113Quality: {{quality-analysis.output}}114Security: {{security-scan.output}}115Performance: {{performance-review.output}}116Architecture: {{architecture-review.output}}117118Format as GitHub PR comment:119120## ๐ค AI Code Review121122### โ
Looks Good123- Positive aspects (2-3 items)124125### โ ๏ธ Issues Found126- Critical/High issues (block merge)127- Medium issues (should fix)128- Minor/Suggestions (nice-to-have)129130### ๐ Security Concerns131- Vulnerabilities found (or "None detected")132133### โก Performance Notes134- Optimization opportunities135136### ๐ก Recommendations137- Top 3-5 actionable improvements138139Tone: Constructive, specific, helpful140Use code snippets and line numbers.`)141142 .run({143 language: "typescript",144 filePath: "src/api/users/handler.ts",145 codeChanges: prDiff,146 fileContext: "REST API endpoint for user management",147 projectContext: "Node.js Express API with PostgreSQL",148 });149150// Post review to GitHub151await github.pulls.createReview({152 owner: repo.owner,153 repo: repo.name,154 pull_number: pr.number,155 body: result.steps["review-summary"].output,156 event: hasBlockingIssues ? "REQUEST_CHANGES" : "COMMENT",157});GitHub Actions Integration
1name: AI Code Review23on:4 pull_request:5 types: [opened, synchronize]67jobs:8 ai-review:9 runs-on: ubuntu-latest10 steps:11 - uses: actions/checkout@v31213 - name: Get PR diff14 id: diff15 run: |16 gh pr diff ${{ github.event.pull_request.number }} > pr.diff17 env:18 GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}1920 - name: Run AI Review21 run: |22 curl -X POST https://api.relayplane.com/webhooks/code-review \23 -H "Authorization: Bearer $RELAYPLANE_KEY" \24 -d @pr.diff25 env:26 RELAYPLANE_KEY: ${{ secrets.RELAYPLANE_KEY }}Sample Output
1## ๐ค AI Code Review23### โ
Looks Good4- Good use of TypeScript types for API contracts5- Proper async/await error handling in most places6- Clear function naming and structure78### โ ๏ธ Issues Found910**CRITICAL**11- ๐ **SQL Injection Risk (line 45)**: User input directly interpolated into query12 ```typescript13 // โ Current14 const query = \`SELECT * FROM users WHERE email = '${email}'\`;1516 // โ
Fixed17 const query = 'SELECT * FROM users WHERE email = $1';18 await db.query(query, [email]);19 ```2021**HIGH**22- โก **N+1 Query (line 67)**: Fetching user details in loop23 - Consider using JOIN or batching with \`WHERE id IN (...)\`2425**MEDIUM**26- ๐งน **Error Handling (line 82)**: Catching error but not logging27 - Add structured logging for debugging production issues2829### ๐ Security Concerns30- Missing rate limiting on authentication endpoint31- Passwords should use bcrypt with cost factor >=123233### โก Performance Notes34- Consider caching user profile data (high read volume)35- Add database index on \`users.email\` for faster lookups3637### ๐ก Recommendations381. Add input validation with zod/joi before database operations392. Extract database queries to repository layer403. Add unit tests for authentication logic414. Consider using prepared statements globally425. Add request ID for distributed tracingCustomization
- Integrate with SonarQube or CodeClimate for metrics
- Add language-specific linters (ESLint, Pylint, etc.)
- Custom rules based on your team's standards
- Auto-fix simple issues (formatting, imports)
- Benchmark against similar projects
Human Review Still Required: AI code review is a supplement, not replacement, for human reviewers. Use it to catch common issues and free up humans for architectural decisions.