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";
2
3const result = await relay
4 .workflow("code-review")
5
6 // Step 1: Analyze code quality and style
7 .step("quality-analysis")
8 .with("openai:gpt-4o")
9 .prompt(`Review this code for quality and best practices:
10
11Language: {{language}}
12File: {{filePath}}
13
14```{{language}}
15{{codeChanges}}
16```
17
18Check for:
19- Code complexity (cyclomatic complexity)
20- Function length (>50 lines is a smell)
21- Naming conventions
22- Code duplication
23- Missing error handling
24- Lack of input validation
25- Poor separation of concerns
26- Magic numbers or hardcoded values
27
28Rate severity: critical, major, minor, suggestion
29Provide specific line numbers and fixes.`)
30
31 // Step 2: Security vulnerability scan
32 .step("security-scan")
33 .with("anthropic:claude-3.5-sonnet")
34 .depends("quality-analysis")
35 .prompt(`Scan for security vulnerabilities:
36
37Code:
38```{{language}}
39{{codeChanges}}
40```
41
42Context: {{fileContext}}
43
44Check OWASP Top 10:
45- SQL injection risks
46- XSS vulnerabilities
47- Authentication/authorization issues
48- Sensitive data exposure
49- Insecure deserialization
50- Insufficient logging
51- SSRF potential
52- Command injection
53- Path traversal
54
55For each finding:
56- Vulnerability type
57- Severity (critical/high/medium/low)
58- Affected code snippet
59- Exploitation scenario
60- Remediation steps`)
61
62 // Step 3: Performance analysis
63 .step("performance-review")
64 .with("openai:gpt-4o")
65 .depends("quality-analysis")
66 .prompt(`Analyze performance implications:
67
68Code:
69```{{language}}
70{{codeChanges}}
71```
72
73Identify:
74- N+1 query problems
75- Inefficient algorithms (time/space complexity)
76- Unnecessary loops or iterations
77- Missing indexes (database queries)
78- Memory leaks potential
79- Blocking operations in async code
80- Missing caching opportunities
81
82Estimate performance impact: high/medium/low
83Suggest optimizations with code examples.`)
84
85 // Step 4: Architecture and design review
86 .step("architecture-review")
87 .with("anthropic:claude-3.5-sonnet")
88 .depends("quality-analysis", "security-scan", "performance-review")
89 .prompt(`Review architectural decisions:
90
91Code: {{codeChanges}}
92File: {{filePath}}
93Project Context: {{projectContext}}
94
95Evaluate:
96- Separation of concerns
97- Dependency injection vs tight coupling
98- SOLID principles adherence
99- Design patterns appropriateness
100- Testability
101- API design (if applicable)
102- Error handling strategy
103- Logging and observability
104
105Suggest improvements aligned with project architecture.`)
106
107 // Step 5: Generate review summary
108 .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:
112
113Quality: {{quality-analysis.output}}
114Security: {{security-scan.output}}
115Performance: {{performance-review.output}}
116Architecture: {{architecture-review.output}}
117
118Format as GitHub PR comment:
119
120## ๐Ÿค– AI Code Review
121
122### โœ… Looks Good
123- Positive aspects (2-3 items)
124
125### โš ๏ธ Issues Found
126- Critical/High issues (block merge)
127- Medium issues (should fix)
128- Minor/Suggestions (nice-to-have)
129
130### ๐Ÿ”’ Security Concerns
131- Vulnerabilities found (or "None detected")
132
133### โšก Performance Notes
134- Optimization opportunities
135
136### ๐Ÿ’ก Recommendations
137- Top 3-5 actionable improvements
138
139Tone: Constructive, specific, helpful
140Use code snippets and line numbers.`)
141
142 .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 });
149
150// Post review to GitHub
151await 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 Review
2
3on:
4 pull_request:
5 types: [opened, synchronize]
6
7jobs:
8 ai-review:
9 runs-on: ubuntu-latest
10 steps:
11 - uses: actions/checkout@v3
12
13 - name: Get PR diff
14 id: diff
15 run: |
16 gh pr diff ${{ github.event.pull_request.number }} > pr.diff
17 env:
18 GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
19
20 - name: Run AI Review
21 run: |
22 curl -X POST https://api.relayplane.com/webhooks/code-review \
23 -H "Authorization: Bearer $RELAYPLANE_KEY" \
24 -d @pr.diff
25 env:
26 RELAYPLANE_KEY: ${{ secrets.RELAYPLANE_KEY }}

Sample Output

1## ๐Ÿค– AI Code Review
2
3### โœ… Looks Good
4- Good use of TypeScript types for API contracts
5- Proper async/await error handling in most places
6- Clear function naming and structure
7
8### โš ๏ธ Issues Found
9
10**CRITICAL**
11- ๐Ÿ”’ **SQL Injection Risk (line 45)**: User input directly interpolated into query
12 ```typescript
13 // โŒ Current
14 const query = \`SELECT * FROM users WHERE email = '${email}'\`;
15
16 // โœ… Fixed
17 const query = 'SELECT * FROM users WHERE email = $1';
18 await db.query(query, [email]);
19 ```
20
21**HIGH**
22- โšก **N+1 Query (line 67)**: Fetching user details in loop
23 - Consider using JOIN or batching with \`WHERE id IN (...)\`
24
25**MEDIUM**
26- ๐Ÿงน **Error Handling (line 82)**: Catching error but not logging
27 - Add structured logging for debugging production issues
28
29### ๐Ÿ”’ Security Concerns
30- Missing rate limiting on authentication endpoint
31- Passwords should use bcrypt with cost factor >=12
32
33### โšก Performance Notes
34- Consider caching user profile data (high read volume)
35- Add database index on \`users.email\` for faster lookups
36
37### ๐Ÿ’ก Recommendations
381. Add input validation with zod/joi before database operations
392. Extract database queries to repository layer
403. Add unit tests for authentication logic
414. Consider using prepared statements globally
425. Add request ID for distributed tracing

Customization

  • 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.