Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Code Review & Security Agent

A production-ready AI agent for automated code review, security vulnerability detection, and code quality analysis using static analysis, LLMs, and security scanning tools.

Features

  • 🔍 Automated Code Review - AI-powered PR reviews with inline comments
  • 🛡️ Security Scanning - OWASP Top 10, CVE detection
  • 🐛 Bug Detection - Logic errors, race conditions, memory leaks
  • 📊 Code Quality Metrics - Complexity, maintainability, test coverage
  • 🚀 Performance Analysis - Identify bottlenecks and optimizations
  • 🔄 CI/CD Integration - GitHub Actions, GitLab CI, Jenkins

Tech Stack

  • Ollama / CodeLlama - Code understanding and generation
  • Semgrep - Static analysis and pattern matching
  • Bandit - Python security linting
  • ESLint - JavaScript/TypeScript linting
  • SonarQube - Code quality platform (optional)
  • Trivy - Dependency vulnerability scanning
  • FastAPI - REST API
  • PostgreSQL - Review history storage
  • Redis - Caching and queuing

Architecture

code-review-agent/
├── src/
│   ├── agent/
│   │   ├── code_reviewer.py        # Core review logic
│   │   ├── security_scanner.py     # Security vulnerability detection
│   │   ├── quality_analyzer.py     # Code quality metrics
│   │   ├── performance_analyzer.py # Performance analysis
│   │   └── llm_reviewer.py         # LLM-based review
│   ├── analyzers/
│   │   ├── semgrep_analyzer.py     # Semgrep integration
│   │   ├── static_analyzer.py      # AST-based analysis
│   │   └── dependency_scanner.py   # Dependency vulnerability check
│   ├── api/
│   │   ├── main.py                 # FastAPI application
│   │   └── webhooks.py             # GitHub/GitLab webhooks
│   ├── integrations/
│   │   ├── github.py               # GitHub API integration
│   │   ├── gitlab.py               # GitLab API integration
│   │   └── ci_cd.py                # CI/CD integration
│   └── models/
│       ├── database.py             # Review storage
│       └── schemas.py              # Pydantic schemas
├── rules/
│   ├── semgrep/                    # Custom Semgrep rules
│   ├── security/                   # Security check rules
│   └── quality/                    # Quality standards
├── tests/
├── requirements.txt
└── docker-compose.yml

Installation

Prerequisites

Setup

cd code-review-agent

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Install Semgrep
pip install semgrep

# Pull Ollama model
ollama pull codellama:13b

# Setup database
createdb code_review_agent
alembic upgrade head

# Configure environment
cp .env.example .env
# Add GitHub/GitLab tokens

# Start services
docker-compose up -d

# Run API server
uvicorn src.api.main:app --reload

Usage

CLI Usage

# Review a single file
python -m code_review_agent review path/to/file.py

# Review entire PR/commit
python -m code_review_agent review-pr --pr 123 --repo owner/repo

# Security scan only
python -m code_review_agent security-scan src/

# Quality analysis
python -m code_review_agent quality-check src/

# Full analysis with report
python -m code_review_agent analyze --output report.html

API Endpoints

Review Pull Request

POST /api/v1/review/pr
{
  "repo": "owner/repo",
  "pr_number": 123,
  "comment_inline": true,
  "severity_threshold": "medium"
}

Review Code Snippet

POST /api/v1/review/code
{
  "code": "def unsafe_query(user_input):\n    query = f\"SELECT * FROM users WHERE id = {user_input}\"\n    return db.execute(query)",
  "language": "python",
  "context": "database query function"
}

Security Scan

POST /api/v1/security/scan
{
  "repo": "owner/repo",
  "branch": "main",
  "scan_dependencies": true
}

Python SDK

from code_review_agent import CodeReviewer

# Initialize reviewer
reviewer = CodeReviewer(
    model="codellama:13b",
    rules=["security", "best-practices", "performance"]
)

# Review code
with open("my_code.py") as f:
    code = f.read()

result = reviewer.review(
    code=code,
    language="python",
    context="API endpoint handler"
)

# Print findings
for finding in result.findings:
    print(f"\n{finding.severity.upper()}: {finding.title}")
    print(f"Line {finding.line_number}: {finding.description}")
    print(f"Suggestion: {finding.suggestion}")
    if finding.code_snippet:
        print(f"\nFixed code:\n{finding.code_snippet}")

# Review metrics
print(f"\nReview Score: {result.score}/100")
print(f"Security Issues: {result.security_issues_count}")
print(f"Quality Issues: {result.quality_issues_count}")

GitHub Integration

from code_review_agent import GitHubReviewer

# Initialize GitHub reviewer
gh_reviewer = GitHubReviewer(token="ghp_xxx")

# Review PR with inline comments
review = gh_reviewer.review_pr(
    repo="owner/repo",
    pr_number=123,
    post_comments=True,
    auto_approve_if_clean=True
)

# Summary
print(f"Review Status: {review.status}")
print(f"Issues Found: {review.issues_count}")
print(f"Comments Posted: {review.comments_posted}")

CI/CD Integration

GitHub Actions

name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: AI Code Review
        uses: agenticai/code-review-action@v1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          severity-threshold: medium
          post-comments: true
          fail-on-high: true

GitLab CI

code_review:
  stage: test
  image: agenticai/code-review-agent:latest
  script:
    - code-review-agent review-mr --mr $CI_MERGE_REQUEST_IID
  only:
    - merge_requests

Features in Detail

Security Vulnerability Detection

Detects:

  • SQL Injection - Unsafe database queries
  • XSS (Cross-Site Scripting) - Unsafe HTML rendering
  • CSRF - Missing CSRF protection
  • Command Injection - Unsafe shell command execution
  • Path Traversal - Unsafe file operations
  • Hardcoded Secrets - API keys, passwords in code
  • Weak Cryptography - Insecure algorithms (MD5, DES)
  • Authentication Issues - Weak auth, missing checks
  • Authorization Issues - Missing access controls
  • Insecure Deserialization
  • Known CVEs - In dependencies

Code Quality Analysis

Analyzes:

  • Complexity - Cyclomatic complexity, cognitive complexity
  • Maintainability - Code smells, duplication
  • Test Coverage - Unit test coverage gaps
  • Code Style - PEP 8, ESLint, etc.
  • Documentation - Missing docstrings, comments
  • Best Practices - Language-specific patterns
  • Error Handling - Missing try-catch, error cases
  • Type Safety - Type hints, null checks

Performance Analysis

Identifies:

  • N+1 Queries - Database query optimization
  • Memory Leaks - Unclosed resources, circular references
  • Inefficient Algorithms - O(n²) where O(n log n) possible
  • Unnecessary Computation - Redundant calculations
  • Resource Contention - Race conditions, deadlocks
  • Blocking Operations - Sync calls in async code

AI-Powered Review

LLM reviews for:

  • Logic Errors - Bugs in business logic
  • Edge Cases - Unhandled scenarios
  • API Design - RESTful best practices
  • Naming - Variable and function naming
  • Architecture - Design patterns, SOLID principles
  • Readability - Code clarity and structure

Review Rules

Built-in Rule Sets

  • security-critical: OWASP Top 10, CWE Top 25
  • security-standard: Common security issues
  • quality-high: Strict quality standards
  • quality-standard: Balanced quality checks
  • performance: Performance optimizations
  • best-practices: Language-specific best practices

Custom Rules

Create custom Semgrep rules:

# rules/custom/no-eval.yaml
rules:
  - id: no-eval-usage
    pattern: eval(...)
    message: "Avoid using eval() - security risk"
    severity: ERROR
    languages: [python, javascript]
    metadata:
      category: security
      cwe: "CWE-95: Improper Neutralization of Directives"

Apply custom rules:

reviewer = CodeReviewer(
    custom_rules_dir="./rules/custom"
)

Configuration

Edit .env:

# Ollama
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=codellama:13b

# GitHub Integration
GITHUB_TOKEN=ghp_xxx
GITHUB_WEBHOOK_SECRET=your_secret

# GitLab Integration
GITLAB_TOKEN=glpat-xxx
GITLAB_WEBHOOK_SECRET=your_secret

# Database
DATABASE_URL=postgresql://user:pass@localhost/code_review

# Redis
REDIS_URL=redis://localhost:6379/0

# Review Settings
SEVERITY_THRESHOLD=medium
MAX_FINDINGS_PER_REVIEW=50
AUTO_FIX_ENABLED=false
POST_INLINE_COMMENTS=true

# Security Scanning
ENABLE_DEPENDENCY_SCAN=true
ENABLE_SECRET_SCAN=true
TRIVY_ENABLED=true

# SonarQube (optional)
SONAR_HOST=http://localhost:9000
SONAR_TOKEN=your_token

Review Output Formats

JSON Report

{
  "summary": {
    "total_findings": 12,
    "critical": 2,
    "high": 3,
    "medium": 5,
    "low": 2,
    "score": 68
  },
  "findings": [
    {
      "id": "sql-injection-001",
      "severity": "critical",
      "category": "security",
      "title": "SQL Injection Vulnerability",
      "description": "Unsafe SQL query with user input",
      "file": "api/users.py",
      "line": 45,
      "code": "query = f\"SELECT * FROM users WHERE id = {user_id}\"",
      "suggestion": "Use parameterized queries",
      "fixed_code": "query = \"SELECT * FROM users WHERE id = %s\"\ndb.execute(query, (user_id,))",
      "references": ["CWE-89", "OWASP A03:2021"]
    }
  ]
}

HTML Report

Beautiful HTML reports with:

  • Executive summary
  • Findings by severity
  • Code snippets with highlights
  • Fix suggestions
  • Trend charts

Markdown Report

GitHub-flavored markdown for PR comments.

Performance

  • Single file review: 2-5 seconds
  • PR review (10 files): 15-30 seconds
  • Full repository scan: 2-10 minutes (depends on size)
  • Security scan: 30-60 seconds
  • Dependency scan: 10-20 seconds

Advanced Features

Auto-fix

Automatically fix certain issues:

reviewer = CodeReviewer(auto_fix=True)

result = reviewer.review_and_fix(
    code=code,
    fix_categories=["formatting", "imports", "simple-security"]
)

# Get fixed code
fixed_code = result.fixed_code

Diff-only Review

Review only changed lines (faster for PRs):

result = reviewer.review_diff(
    base_commit="abc123",
    head_commit="def456",
    repo_path="."
)

Learning from Feedback

Train the agent on your team's preferences:

# Mark false positive
reviewer.mark_false_positive(finding_id="fp-001")

# Mark as accepted pattern
reviewer.accept_pattern(
    pattern="using_specific_library",
    reason="Company standard"
)

Testing

# Run all tests
pytest tests/

# Test specific analyzer
pytest tests/test_security_scanner.py

# Test with sample code
pytest tests/ --code-samples=samples/

Roadmap

  • Support more languages (Rust, Go, Kotlin)
  • Machine learning model training on codebase
  • IDE plugins (VS Code, IntelliJ)
  • Team analytics dashboard
  • Custom rule marketplace
  • Auto-refactoring suggestions

Contributing

See CONTRIBUTING.md

License

MIT License - see LICENSE

Support


Built with ❤️ by the AgenticAI team

About

Automated code review and security scanning with AI

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages