---
name: code-review-automation
description: Automate code review processes including static analysis, security scanning, quality gates, and AI-assisted review comments. Use when setting up automated code review pipelines, configuring quality gates, integrating static analysis tools, enforcing coding standards, automating security scanning in PRs, reducing manual review burden, or establishing code quality metrics. Triggers on phrases like "code review automation", "static analysis", "SAST", "quality gate", "PR checks", "code quality", "SonarQube", "linting automation", "code coverage", "automated review comments", "pull request automation".
---

# Code Review Automation

Automate code quality analysis, security scanning, and review process enforcement to maintain high code standards and reduce manual review effort.

## Workflow

1. Define code quality standards and coding conventions per language/framework (e.g., Java → Google Java Style, Python → PEP 8, JavaScript → Airbnb Style Guide).
2. Integrate static analysis tools into CI/CD pipeline: SonarQube/SonarCloud for code quality, ESLint/Pylint/Checkstyle for linting, SAST tools (Semgrep, Snyk Code, CodeQL) for security.
3. Configure quality gates with minimum thresholds: code coverage ≥ 80%, no critical/blocker issues, duplication < 3%, complexity within limits.
4. Set up automated PR checks: build must pass, all tests must pass, quality gate must pass, security scan must clear, license compliance verified.
5. Deploy AI-assisted review tools (GitHub Copilot Code Review, Codacy, CodeRabbit) to auto-generate review comments on style, bugs, and patterns.
6. Enforce branch protection rules: required reviews (2+ approvers), required status checks, no direct pushes to main, linear history.
7. Track code quality metrics over time: technical debt ratio, code smells per module, test coverage trends, review cycle time.
8. Conduct weekly quality dashboard reviews with engineering leadership.
9. Adjust quality gate thresholds quarterly based on team maturity and product risk.
10. Perform quarterly audit of false positives in automated tools; tune rules.

## Static Analysis Tool Integration

```
STATIC ANALYSIS TOOLCHAIN
===========================

LANGUAGE-SPECIFIC LINTERS:

  Java / Kotlin:
    → Checkstyle: Enforces Google Java Style or custom rules
    → SpotBugs (formerly FindBugs): Detects bug patterns (null dereference, resource leaks)
    → PMD: Code rule violations, unused imports, empty catch blocks
    → Detekt (Kotlin): Idiomatic Kotlin checks, complexity metrics
    → Integration: Maven/Gradle plugins → run on every build

  Python:
    → Flake8: Style enforcement (PEP 8), complexity (McCabe), bugs
    → Pylint: Deep analysis, design recommendations, convention checks
    → Bandit: Security-focused linting (SQL injection, hardcoded secrets)
    → MyPy: Type checking (static analysis for dynamically typed code)
    → Ruff: Fast unified linter (replaces Flake8 + isort + others); 10-100x faster
    → Integration: Pre-commit hooks + CI step

  JavaScript / TypeScript:
    → ESLint: Comprehensive rule set (Airbnb, Standard, custom)
    → Prettier: Code formatting (no-op in CI; error if not formatted)
    → TypeScript strict mode: Catch type errors at compile time
    → TypeScript ESLint: Extended rules for TypeScript-specific patterns
    → Integration: npm scripts → run in CI pipeline

  Go:
    → golangci-lint: Meta-linter aggregating 40+ linters
    → Staticcheck: Deep semantic analysis (SA, QF, QF, QF families)
    → go vet: Built-in Go analysis tool
    → Integration: CI step + pre-commit hook

  C / C++:
    → Clang-Tidy: Modern C++ best practices, bug detection
    → Cppcheck: Memory leaks, undefined behavior, unused variables
    → Coverity (commercial): Deep analysis for safety-critical code
    → Integration: CMake integration; run as build step

CROSS-LANGUAGE TOOLS:

  SonarQube / SonarCloud:
    → 30+ languages supported
    → Three axes: Bugs, Vulnerabilities, Code Smells
    → Security Hotspots: Flag code requiring manual security review
    → Quality Gate: Pass/fail criteria for builds
    → Technical Debt Estimation: Based on code smell remediation effort
    → New Code Period: Track quality of last 30 days / last iteration
    → Pricing: SonarCloud $4/developer/month; SonarQube DevEdition free (10 users)

  Semgrep:
    → Fast SAST for 25+ languages
    → Custom rule writing (YAML-based pattern matching)
    → Community rules: OWASP Top 10, language-specific best practices
    → CI integration: GitHub Actions, GitLab CI, Jenkins
    → Pricing: Semgrep APP free for open source; Pro $25/user/month

  GitHub CodeQL:
    → Semantic code analysis (builds code database for deep queries)
    → Query-based: OWASP, language-specific security queries
    → Code scanning alerts on PRs and commits
    → SARIF upload for GitHub Security tab
    → Included in GitHub Advanced Security ($4/user/month)
```

## Quality Gate Configuration

```
QUALITY GATE THRESHOLDS
=========================

DEFAULT QUALITY GATE (NEW PROJECTS):

  Code Coverage:
    → Line coverage: ≥ 70% (new code), ≥ 60% (overall)
    → Branch coverage: ≥ 60% (new code), ≥ 50% (overall)
    → Action on fail: Build fails; PR cannot merge
    → Exclusions: Generated code, test utilities, configuration files

  Code Duplication:
    → Duplicated blocks: < 3% of codebase
    → Duplicated lines per block: > 5 consecutive lines flagged
    → Action on fail: Warning; requires justification to merge
    → Tracking: Duplication trend must be decreasing quarter-over-quarter

  Complexity:
    → Cognitive complexity: ≤ 15 per function/method
    → Cyclomatic complexity: ≤ 10 per function/method
    → Nested blocks: ≤ 4 levels of nesting
    → Action on fail: Blocker; must refactor before merge

  Security:
    → Critical vulnerabilities: 0 (hard block)
    → High vulnerabilities: 0 (hard block)
    → Medium vulnerabilities: ≤ 5 (warning; must have remediation plan)
    → Low vulnerabilities: tracked; no block
    → Security hotspots: reviewed by security-conscious reviewer

  Code Smells:
    → New code smells per PR: ≤ 10
    → Total code smells: tracked; trend must be flat or decreasing
    → Action on fail: Warning; must document exception

  Reliability:
    → Bugs (confirmed): 0 critical, ≤ 3 major
    → Action on fail: Build fails for critical bugs

STRICT QUALITY GATE (PAYMENT, HEALTHCARE, SECURITY-SENSITIVE):

  Code Coverage:
    → Line coverage: ≥ 85% (new code), ≥ 80% (overall)
    → Branch coverage: ≥ 75% (new code), ≥ 70% (overall)
    → Mutation testing score: ≥ 70% (PITest, Stryker)

  Security:
    → All vulnerabilities: 0 (any severity blocks merge)
    → OWASP Top 10: Zero findings
    → Secrets detection: Zero hardcoded secrets, API keys, credentials
    → Dependency vulnerabilities: Zero high/critical; zero unpatched CVEs

  Test Requirements:
    → Unit tests: Required for all new business logic
    → Integration tests: Required for all API endpoints and database operations
    → Regression tests: Must pass 100% (zero regressions)
    → Performance tests: No regression > 10% on key endpoints

RELAXED QUALITY GATE (PROTOTYPES, INTERNAL TOOLS):

  Code Coverage: ≥ 50% (new code)
  Security: 0 critical/high vulnerabilities
  Code Smells: Warning only (no block)
  Complexity: ≤ 25 per function
  Duplication: < 5%
```

## Automated PR Review Process

```
AUTOMATED PULL REQUEST CHECKLIST
==================================

PRE-MERGE REQUIRED CHECKS (ALL MUST PASS):

  [ ] Build Success
    → Compilation succeeds for all modules
    → Docker image builds successfully (if applicable)
    → No compiler warnings in new code

  [ ] Unit Tests Pass
    → All existing tests pass (no regressions)
    → New tests added for new functionality
    → Test coverage not decreased

  [ ] Integration Tests Pass
    → API endpoint tests pass
    → Database integration tests pass
    → Third-party API mock tests pass

  [ ] Static Analysis
    → Linting passes (ESLint, Pylint, Checkstyle, etc.)
    → Code formatting verified (Prettier, Black, gofmt)
    → SonarQube quality gate passed

  [ ] Security Scan
    → SAST scan: No critical/high vulnerabilities
    → Dependency scan: No vulnerable dependencies (OWASP Dependency-Check, Snyk)
    → Secret scan: No credentials in code (git-secrets, TruffleHog, Gitleaks)
    → License compliance: No prohibited licenses (FOSSA, Snyk License)

  [ ] Documentation
    → README updated if new module/feature
    → API documentation generated (Swagger, JSDoc)
    → CHANGELOG entry added

  [ ] Manual Review
    → Minimum 2 approvals required
    → At least 1 approval from code owner (defined in CODEOWNERS)
    → Conversation resolved (all comments addressed)

AUTOMATED REVIEW COMMENTS (AI-ASSISTED):

  Tools:
    → GitHub Copilot Code Review: Suggests improvements, catches bugs
    → CodeRabbit: Summarizes PR, highlights risks, suggests changes
    → Codacy: Automated review comments on style, complexity, bugs
    → ReviewBot: Learns from team's review patterns; suggests similar comments

  Comment Categories:
    → Style: "Consider using early return to reduce nesting"
    → Bug: "This index could be out of bounds when array is empty"
    → Performance: "N+1 query detected; consider batch loading"
    → Security: "User input used in SQL query; use parameterized query"
    → Testing: "No test added for this new error path"
    → Best Practice: "Consider using 'const' instead of 'let' (not reassigned)"

BRANCH PROTECTION RULES (GITHUB EXAMPLE):

  → Require pull request reviews: 2 approvals minimum
  → Require status checks to pass: All automated checks listed above
  → Require branches to be up to date before merging
  → Include administrators in enforcement
  → Restrict who can push: Only via PR (no direct push to main)
  → Require linear history: Squash merge or rebase only (no merge commits)
  → Require signed commits: GPG/SSH signed commits required
  → Hold checks: Manual approval gate for production-critical changes
```

## Code Quality Metrics Dashboard

```
CODE QUALITY DASHBOARD METRICS
================================

TRACKED METRICS (WEEKLY/MONTHLY):

  Coverage Trends:
    → Overall line coverage: 72.4% (↑ 1.2% from last month)
    → New code coverage: 84.1% (↑ 2.3% from last month)
    → Branch coverage: 61.8% (↓ 0.5% from last month) ⚠️
    → Files with zero coverage: 12 (↓ 3 from last month)

  Technical Debt:
    → Estimated debt ratio: 3.2% (effort to fix / effort to develop from scratch)
    → Total code smells: 1,247 (↓ 45 from last month)
    → Critical smells: 23 (↓ 5 from last month)
    → Estimated fix time: 8.5 developer-days

  Complexity:
    → Average cognitive complexity: 8.4 (target: ≤ 10)
    → Functions exceeding complexity threshold: 34 (↓ 8)
    → Most complex module: payment-processing (avg 18.2)

  Code Review Metrics:
    → Average review time: 4.2 hours (target: ≤ 6 hours)
    → Comments per PR: 7.3 (industry benchmark: 5-10)
    → Review-to-merge ratio: 94% (PRs merged without major rework)
    → Average PR size: 185 lines (target: ≤ 400 lines)

  Security Posture:
    → Open vulnerabilities: 3 medium, 12 low
    → Vulnerabilities introduced last month: 5 (↓ 8 from prior month)
    → Vulnerabilities remediated: 12 (100% remediation rate)
    → Mean time to remediate: 3.2 days (target: ≤ 5 days)
    → Dependency update lag: avg 45 days (target: ≤ 30 days)

  Duplication:
    → Duplicated code: 2.1% (target: < 3%)
    → Largest duplicated block: 240 lines (auth module)
    → Duplication trend: decreasing (↓ 0.4% from last quarter)

DASHBOARD INTEGRATION:
    → SonarQube: Primary quality metrics
    → GitHub/GitLab: PR metrics, review times, check statuses
    → CI/CD platform: Build success rates, test durations
    → JIRA/Linear: Link code quality to tickets and epics
    → Slack/Teams: Weekly quality digest channel
```

## Integration Points

- **GitHub / GitLab / Bitbucket**: Native code scanning, PR checks, branch protection, CODEOWNERS, merge request automation
- **SonarQube / SonarCloud**: Central quality gate, multi-language analysis, technical debt tracking, security hotspot review
- **Snyk Code / Snyk Open Source**: SAST + dependency vulnerability scanning; IDE integration for real-time feedback; fix suggestions
- **Semgrep**: Fast pattern-based SAST; custom rule development; OWASP Top 10 coverage; cloud and self-hosted options
- **GitHub Advanced Security**: CodeQL analysis, dependency review, secret scanning, code scanning alerts; integrated into GitHub UI
- **Pre-commit**: Client-side hooks (linting, formatting, secret scanning) before commits; reduces CI noise
- **JIRA / Linear**: Quality gate failures create tickets; link code issues to backlog items
- **Slack / MS Teams**: Automated alerts for quality gate failures, security findings, coverage drops; weekly digest reports

## Edge Cases

- **Legacy codebases with low coverage**: Gradual improvement strategy; set "new code" gate higher than "overall"; exclude legacy modules from strict gates with documented timeline
- **Open-source dependencies with vulnerabilities**: Dependabot/Renovate auto-PRs for updates; assess update risk; test integration; pin versions with known-good builds
- **Performance impact of analysis tools**: SonarQube on large repos (500K+ LOC) can take 20+ minutes; use incremental analysis; parallelize scanning; cache analysis results
- **False positive management**: Weekly false positive review; suppress with justification; re-evaluate suppressions quarterly; maintain team-specific rule tuning
- **Multi-repo / monorepo analysis**: Monorepo: single SonarQube project with quality gate per module; multi-repo: aggregated dashboard via SonarQube Portfolio View or custom dashboard
- **Language mixing in single project**: Configure per-language rules; set appropriate complexity thresholds per language; ensure all languages covered by at least one tool
- **Contractor / external contributor reviews**: Require additional approval for external PRs; enforce stricter quality gates on external code; require DSA (Developer Certificate of Origin) sign-off
