jcergolj/ai-pair-review

AI-powered pre-commit code review using Claude Code CLI. Reviews for SOLID principles, design patterns, and code quality.

Installs: 24

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Language:Shell

pkg:composer/jcergolj/ai-pair-review

v0.5 2025-10-21 10:47 UTC

This package is auto-updated.

Last update: 2025-10-21 10:48:15 UTC


README

🤖 AI-powered pre-commit code review for Laravel projects using Claude Code CLI.

Automatically reviews your code for SOLID principles, design patterns, and code quality on every commit.

Features

  • 🎯 SOLID Principles - Detects violations of Single Responsibility, Open/Closed, etc.
  • 🏗️ Design Patterns - Suggests Strategy, Factory, Repository, Observer patterns
  • 🔧 Code Quality - Identifies code smells and refactoring opportunities
  • ✅ Laravel Best Practices - N+1 queries, proper Eloquent usage, security
  • 📝 Actionable - Saves editable markdown file with improvement checklist
  • ⚡ Non-blocking - Commit now, fix later from the review file

Quick Start

1. Install via Composer

composer require --dev jcergolj/ai-pair-review

2. Install the hooks

php artisan ai-review:install

3. Commit as usual

git commit -m "Add feature"

AI reviews your code automatically!

How It Works

  1. You run git commit
  2. AI reviews only your staged PHP files
  3. Review is saved to code-reviews/code-review-TIMESTAMP.md
  4. File opens in VS Code automatically
  5. You choose to:
    • Commit now and fix issues later, or
    • Abort and fix issues now

Code Review Storage

All AI-generated code reviews are automatically stored in the code-reviews/ folder in your project root. Each review is saved as a markdown file with a timestamp:

code-reviews/
├── code-review-20251021_143022.md
├── code-review-20251021_151204.md
└── code-review-20251022_094515.md

This folder is automatically created on the first review and contains:

  • Timestamped files - Each review gets a unique filename
  • Editable markdown - Remove items you don't want to fix
  • Actionable checklists - Ready to submit to Claude Code for implementation

After Committing

# Review the generated file
cat code-reviews/code-review-20251021_143022.md

# Edit it to keep only what you want to fix

# Submit to Claude Code for automatic implementation
claude "Implement the improvements in code-reviews/code-review-20251021_143022.md"

Example Review

## Issues Found

### High Priority
- [ ] Single Responsibility Violation (UserService.php:21)
  - Problem: Class handles creation, emails, logging, subscriptions
  - Fix: Extract to CreateUserAction, UserRegistered event, SubscriptionStrategy

- [ ] Missing Type Declarations (UserService.php:21)
  - Problem: No return type, array instead of DTO
  - Fix: Add `: User` return type, create `RegisterUserData` DTO

### Medium Priority
- [ ] Strategy Pattern Opportunity (UserService.php:40)
  - Suggestion: Replace conditionals with SubscriptionStrategy interface

### Low Priority
- [ ] Use Eloquent Mass Assignment
  - Suggestion: Replace manual properties with User::create()

What Gets Reviewed

🎯 SOLID Principles

  • Single Responsibility - One class, one reason to change
  • Open/Closed - Open for extension, closed for modification
  • Liskov Substitution - Proper use of abstractions
  • Interface Segregation - Focused, cohesive interfaces
  • Dependency Inversion - Depend on abstractions, not concretions

🏗️ Architecture & Patterns

  • Design pattern usage (Strategy, Factory, Repository, Observer, etc.)
  • Dependency injection
  • Domain-Driven Design principles
  • God objects and procedural code

🔧 Code Quality

  • Code smells (long methods, feature envy, data clumps)
  • Duplicated code
  • Complex conditionals → polymorphism
  • Better use of collections

✅ Laravel Best Practices

  • Eloquent relationships and query optimization
  • N+1 query detection
  • Service providers and facades
  • Security (authorization, validation, mass assignment)
  • Proper use of Form Requests, Events, Jobs

📝 Type Safety

  • Missing type declarations
  • Interface opportunities
  • Value objects instead of primitives

Configuration

Edit .pre-commit-config in your project root:

# Enable/disable AI review
AI_REVIEW=true

Large Changes & Token Limits

Claude has token limits (~200k tokens, roughly 800k characters). The hook automatically handles large changes:

  • ⚠️ Warning at 300KB - Shows size and suggests splitting commits
  • 🛑 Block at 500KB - Offers options:
    • Skip AI review and commit normally
    • Truncate diff for partial review
    • Abort to split changes
  • 🚨 Token errors - Clear error messages with suggestions

Best practices for large changes:

# Instead of committing everything at once
git add .
git commit -m "Large refactor"

# Split into focused commits
git add app/Services/UserService.php
git commit -m "Extract user registration logic"

git add app/Events/UserRegistered.php
git commit -m "Add user registration event"

git add app/Listeners/SendWelcomeEmail.php
git commit -m "Add welcome email listener"

Disable for one commit

AI_REVIEW=false git commit -m "Quick fix"

Skip hook entirely (emergency)

git commit --no-verify -m "Hotfix"

Commands

Install

php artisan ai-review:install

Installs the pre-commit hooks.

Options:

  • --force - Overwrite existing hooks

Uninstall

php artisan ai-review:uninstall

Removes the pre-commit hooks.

Requirements

  • PHP 8.4+
  • Laravel 12+
  • Git repository
  • Claude Code CLI installed and in PATH (default)

Note: Currently uses Claude Code CLI, but can be easily modified to use other AI providers (OpenAI, Gemini, Ollama, etc.). See EXTEND_TO_OTHER_AI.md for instructions.

Install Claude Code from https://claude.ai/code

Team Setup

Option 1: Commit config to repository

git add .pre-commit-config
git commit -m "Add AI review config"

Team members run:

composer install
php artisan ai-review:install

Option 2: Auto-install on composer install

Add to your project's composer.json:

{
  "scripts": {
    "post-install-cmd": [
      "@php artisan ai-review:install --quiet || true"
    ]
  }
}

Non-Laravel Projects

The hooks work with any PHP project! To install manually:

# From vendor directory
cp vendor/jcergolj/ai-pair-review/stubs/pre-commit .git/hooks/
cp vendor/jcergolj/ai-pair-review/stubs/ai-reviewer.sh .git/hooks/
cp vendor/jcergolj/ai-pair-review/stubs/.pre-commit-config .
'chmod +x .git/hooks/*

Support Other Languages

Edit .git/hooks/ai-reviewer.sh line 17:

# For Python
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$' || true)

# For JavaScript/TypeScript
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|jsx|ts|tsx)$' || true)

# For all languages
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM || true)

Troubleshooting

"Claude CLI not found"

Install Claude Code from https://claude.ai/code

The hook will skip gracefully if Claude is not installed.

Hook not running

# Check hooks are installed
ls -la .git/hooks/

# Reinstall
php artisan ai-review:install --force

Review file not opening

Install VS Code CLI or the review is still saved to code-reviews/code-review-*.md

Slow reviews

For large commits (10+ files), reviews may take 20-30 seconds. Consider:

  • Smaller, more focused commits
  • Temporarily disable: AI_REVIEW=false git commit

Examples

Before Review

class UserService {
    public function register(array $data) {
        $user = User::create($data);
        Mail::to($user)->send(new WelcomeEmail());
        Log::info("Registered: {$user->email}");
        return $user;
    }
}

After AI Suggestions

// Single Responsibility - one action
class RegisterUserAction {
    public function execute(RegisterUserData $data): User {
        $user = User::create($data->toArray());
        event(new UserRegistered($user));
        return $user;
    }
}

// Event for cross-cutting concerns
class SendWelcomeEmail {
    public function handle(UserRegistered $event): void {
        $event->user->notify(new WelcomeNotification());
    }
}

// Value object for type safety
class RegisterUserData {
    public function __construct(
        public readonly string $name,
        public readonly Email $email,
        public readonly HashedPassword $password,
    ) {}
}

Why Use This?

📚 Educational

Learn SOLID principles by seeing them applied to your actual code

🔍 Quality

Catch architectural issues before code review

⚡ Fast

Get instant expert feedback on every commit

🎯 Actionable

Edit the review to keep what matters, submit to Claude for automatic fixes

Publishing to Packagist

To share this package publicly:

1. Create GitHub repository

cd ai-pair-review
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/jcergolj/ai-pair-review.git
git push -u origin main

2. Tag a release

git tag -a v1.0.0 -m "First release"
git push origin v1.0.0

3. Submit to Packagist

  1. Go to https://packagist.org/packages/submit
  2. Enter your GitHub URL: https://github.com/jcergolj/ai-pair-review
  3. Click Submit

4. Install in any project

composer require --dev jcergolj/ai-pair-review
php artisan ai-review:install

Customization

Customize What Gets Reviewed

The AI review prompt is fully customizable! See CUSTOMIZE_PROMPT.md for the complete guide with examples.

Quick start:

# Open the reviewer script
code .git/hooks/ai-reviewer.sh

# Edit the REVIEW_PROMPT variable (starts at line 33)

Popular customizations:

  • Security Focus - Prioritize vulnerabilities and security issues
  • Performance Focus - Catch N+1 queries, caching opportunities
  • Team Standards - Enforce your company's specific coding rules
  • Educational Mode - Get detailed explanations for learning
  • Strict Mode - Catch every small issue
  • Lenient Mode - Only report critical problems

See CUSTOMIZE_PROMPT.md for copy-paste templates and examples.

Save Reviews to Custom Location

Edit .git/hooks/ai-reviewer.sh line 130:

# Save to .reviews/ directory
mkdir -p "$PROJECT_ROOT/.reviews"
REVIEW_FILE="$PROJECT_ROOT/.reviews/code-review-$TIMESTAMP.md"

Extending to Other AI Providers

While this package uses Claude Code CLI by default, it's built on standard Git hooks and can be easily modified to use:

  • OpenAI GPT-4 (via API)
  • Google Gemini (via API)
  • Ollama (local, offline)
  • GitHub Copilot CLI
  • Any other AI service

The pre-commit hook is just a bash script - modify .git/hooks/ai-reviewer.sh to call your preferred AI provider.

Full guide with examples: EXTEND_TO_OTHER_AI.md

Quick example for OpenAI:

# Replace line 118 in .git/hooks/ai-reviewer.sh
REVIEW_OUTPUT=$(curl -s https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model":"gpt-4","messages":[...]}' | jq -r '.choices[0].message.content')

Contributing

Contributions welcome!

Especially wanted:

  • Support for additional AI providers
  • Improved prompts
  • Bug fixes
  • Documentation improvements
  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

License

MIT License - see LICENSE file

Credits

Built with Claude Code CLI by Anthropic

Support