Code Review Patterns

Comprehensive patterns for implementing AI-powered code review workflows with Claude Code, including automated reviews, quality checks, and collaborative review processes.

📚 Available Patterns

Core Patterns

  • AI-Powered Workflows - Automated code review with AI assistance
  • Quality Gate Automation - Automated quality checks and standards enforcement
  • Review Process Optimization - Streamlining the review workflow
  • Collaborative Review - Multi-reviewer and AI-human collaboration patterns

🎯 Key Review Areas

1. Automated Code Analysis

  • Style and formatting checks
  • Security vulnerability detection
  • Performance issue identification
  • Best practice validation

2. AI-Assisted Reviews

  • Intelligent suggestions
  • Pattern recognition
  • Context-aware feedback
  • Learning from past reviews

3. Quality Assurance

  • Test coverage analysis
  • Documentation completeness
  • API contract validation
  • Dependency security

4. Process Optimization

  • Review automation
  • Batch processing
  • Priority-based reviews
  • Feedback aggregation

🔧 Code Review Strategies

AI Review Framework

interface CodeReviewStrategy {
  // Analyze code changes
  analyze(changes: CodeChanges): Promise<ReviewReport>
  
  // Generate suggestions
  suggest(issues: Issue[]): Promise<Suggestion[]>
  
  // Validate against standards
  validate(code: string, standards: Standards): ValidationResult
  
  // Learn from feedback
  learn(feedback: ReviewFeedback): void
}

Review Automation Pipeline

name: Claude Code AI-Assisted Review
on:
  pull_request:
    types: [opened, synchronize, reopened]
 
jobs:
  automated_review:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history for better analysis
 
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
 
      - name: Run Linter & Static Analysis
        run: |
          npm ci
          npm run lint:check
          npm run typecheck
        continue-on-error: true  # Capture errors for AI review
 
      - name: Run Unit & Integration Tests
        run: |
          npm test -- --coverage --json --outputFile=test-results.json
        continue-on-error: true
 
      - name: Security Scan with CodeQL
        uses: github/codeql-action/analyze@v3
        with:
          languages: javascript, typescript
 
      - name: Generate AI Review Summary
        env:
          CLAUDE_API_KEY: ${{ secrets.CLAUDE_API_KEY }}
        run: |
          # Get PR diff
          git diff ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > changes.diff
          
          # Combine all analysis results
          echo "## Automated Review Results" > review_input.md
          echo "### Lint Results" >> review_input.md
          npm run lint:check --silent 2>&1 | tail -n 50 >> review_input.md || true
          echo "### Test Results" >> review_input.md
          cat test-results.json | jq '.numFailedTests, .numPassedTests' >> review_input.md || true
          echo "### Code Changes" >> review_input.md
          head -n 1000 changes.diff >> review_input.md
          
          # Use Claude to analyze and generate review
          claude -p "Review this PR for:
            1. Code quality issues
            2. Security vulnerabilities  
            3. Performance concerns
            4. Best practice violations
            5. Test coverage gaps
            
            Provide specific, actionable feedback with code examples.
            Format as a GitHub PR review comment." < review_input.md > review_summary.md
    
      - name: Post AI Review as PR Comment
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const fs = require('fs');
            const reviewContent = fs.readFileSync('review_summary.md', 'utf8');
            
            // Add header to distinguish AI review
            const comment = `## 🤖 Claude Code Review
            
            ${reviewContent}
            
            ---
            *This is an automated review. Human review is still required for merge approval.*`;
            
            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });
 
      - name: Quality Gate Check
        run: |
          # Check if critical issues were found
          if grep -q "CRITICAL\|HIGH" review_summary.md; then
            echo "❌ Quality gate failed: Critical issues found"
            exit 1
          fi
          
          # Check test coverage
          COVERAGE=$(cat coverage/coverage-summary.json | jq '.total.lines.pct')
          if (( $(echo "$COVERAGE < 80" | bc -l) )); then
            echo "❌ Quality gate failed: Coverage below 80%"
            exit 1
          fi
          
          echo "✅ Quality gates passed"

💡 Best Practices

1. Comprehensive Analysis

  • Review code holistically
  • Check for side effects
  • Validate assumptions
  • Consider edge cases

2. Constructive Feedback

  • Provide specific suggestions
  • Explain the “why”
  • Offer alternatives
  • Recognize good patterns

3. Efficient Workflow

  • Automate repetitive checks
  • Focus human review on complex issues
  • Use AI for initial pass
  • Batch similar reviews

4. Continuous Improvement

  • Track review metrics
  • Learn from patterns
  • Update standards
  • Refine processes

🚀 Advanced Techniques

Smart Review Prioritization

class ReviewPrioritizer {
  prioritize(pullRequests: PullRequest[]): PrioritizedList {
    return pullRequests
      .map(pr => ({
        pr,
        score: this.calculateScore(pr)
      }))
      .sort((a, b) => b.score - a.score)
  }
  
  private calculateScore(pr: PullRequest): number {
    const factors = {
      criticalPath: pr.affectsCriticalPath ? 10 : 0,
      securityImpact: pr.securityChanges ? 8 : 0,
      size: Math.max(0, 5 - pr.filesChanged / 10),
      author: pr.author.isNewContributor ? 3 : 0
    }
    
    return Object.values(factors).reduce((a, b) => a + b, 0)
  }
}

Pattern-Based Review

class PatternReviewer {
  private patterns = new Map<string, ReviewPattern>()
  
  async reviewCode(code: string): Promise<ReviewResult> {
    const detectedPatterns = await this.detectPatterns(code)
    const suggestions = []
    
    for (const pattern of detectedPatterns) {
      if (this.patterns.has(pattern.type)) {
        const reviewer = this.patterns.get(pattern.type)!
        suggestions.push(...await reviewer.review(pattern))
      }
    }
    
    return { suggestions, patterns: detectedPatterns }
  }
}

📋 Implementation Patterns

1. Automated First Pass

AI reviews before human review:

async function automatedReview(pr: PullRequest) {
  // Run automated checks
  const results = await Promise.all([
    runLinting(pr),
    runSecurityScan(pr),
    runTests(pr),
    analyzeComplexity(pr)
  ])
  
  // Generate AI review with specific focus areas
  const aiReview = await generateAIReview(pr, {
    results,
    focusAreas: [
      'security vulnerabilities',
      'performance bottlenecks',
      'test coverage gaps',
      'code duplication',
      'API contract violations'
    ],
    contextFiles: ['CLAUDE.md', 'ARCHITECTURE.md']
  })
  
  // Post categorized feedback
  await postReviewComments(pr, {
    critical: aiReview.securityIssues,
    suggestions: aiReview.improvements,
    praise: aiReview.goodPatterns
  })
}

2. Incremental Reviews

Review as code is written:

class IncrementalReviewer {
  async reviewChange(change: CodeChange) {
    // Review immediately
    const feedback = await this.analyze(change)
    
    // Provide real-time suggestions
    if (feedback.hasIssues()) {
      await this.notifyDeveloper(feedback)
    }
  }
}

3. Learning System

Improve reviews over time:

class LearningReviewer {
  async learn(review: CompletedReview) {
    // Extract patterns from accepted suggestions
    const patterns = this.extractPatterns(review)
    
    // Update review model
    await this.model.train(patterns)
    
    // Adjust future reviews
    this.updateStrategies(patterns)
  }
}

📖 Common Review Scenarios

Pull Request Reviews

  • Automated initial analysis
  • Focus area identification
  • Change impact assessment
  • Merge conflict detection

Security Reviews

  • Vulnerability scanning
  • Dependency checking
  • Secret detection
  • Permission validation

Performance Reviews

  • Complexity analysis
  • Resource usage checks
  • Optimization suggestions
  • Benchmark comparisons

Architecture Reviews

  • Pattern compliance
  • Dependency analysis
  • API design validation
  • Documentation completeness

🏆 Review Best Practices

  1. Automate First - Let AI handle routine checks

    • Format/lint issues caught automatically
    • Security vulnerabilities flagged immediately
    • Test coverage validated before human review
  2. Focus Human Effort - Review complex logic manually

    • Architecture decisions
    • Business logic correctness
    • Performance trade-offs
  3. Provide Context - Explain why changes are needed

    • Link to issue/ticket
    • Include design decisions
    • Document assumptions
  4. Be Constructive - Suggest improvements

    • Provide code examples
    • Offer alternative approaches
    • Recognize good patterns
  5. Learn Continuously - Improve the review process

    • Track review metrics (time, iterations, defect escape rate)
    • Update automation rules based on patterns
    • Refine AI prompts for better suggestions

📊 Key Metrics for Success

  • Review Time Reduction: Target 40-60% decrease with automation
  • Defect Detection Rate: AI catches 70%+ of common issues
  • Developer Satisfaction: Measure via surveys and feedback
  • Code Quality Metrics: Track maintainability index improvements
  • Time to Merge: Reduce from days to hours for standard changes

🧭 Quick Navigation

← Back to Patterns | Home | AI Workflows | Testing