Skip to content

CLI-based AI code review system that performs comprehensive reviews at commit time

License

Notifications You must be signed in to change notification settings

martinkl164/AI-Code-Review-CLI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ AI Code Review CLI

Catch Security, Bugs & Quality Issues Before They Ship

A portable, CLI-based AI code review system that performs comprehensive reviews at commit timeβ€”powered by GitHub Copilot.

License: MIT Platform GitHub Copilot

AI Code Review CLI


Quick Start β€’ Features β€’ Workflows β€’ Configuration β€’ Troubleshooting



πŸ’‘ The Problem

You're about to commit code with a hardcoded password. Or a SQL injection vulnerability. Or an empty catch block. Or naming convention violations.

Traditional code reviews catch these issuesβ€”days later. By then, they're already in your codebase, possibly in production.

βœ… The Solution

This tool intercepts your commits before they happen, analyzes your staged changes with AI, and blocks commits that contain critical security, correctness, or quality issues.

AI Code Review Output Example

Fix the issue. Commit again. Ship secure code.


πŸ” What Gets Reviewed

This isn't just a security toolβ€”it's a comprehensive AI code reviewer using a multi-agent architecture where specialized agents work in parallel to analyze different aspects of your code:

Multi-Agent System:

  • πŸ”’ Security Agent: Focuses on vulnerabilities, secrets, and security patterns
  • πŸ“ Naming Agent: Checks Java naming conventions and code style
  • βœ… Quality Agent: Reviews correctness, performance, and best practices
  • πŸ€– Summarizer Agent: Aggregates results and eliminates duplicates

Review Categories:

Category Severity Examples
πŸ”’ Security BLOCK Hardcoded secrets, SQL injection, unsafe deserialization
πŸ› Correctness BLOCK Null pointer risks, thread safety issues
⚑ Performance WARN Inefficient collections, O(n) when O(1) available
πŸ“ Code Quality WARN Empty catch blocks, poor exception handling
🎯 Best Practices INFO Naming conventions, Java code standards

Severity Levels:

  • BLOCK: Commit rejected (security & critical bugs)
  • WARN: Commit allowed with warnings (quality issues)
  • INFO: Commit allowed with suggestions (style & conventions)

🎯 Features

Feature Description
πŸ”’ Comprehensive Reviews Checks security, correctness, performance, quality, and best practices
πŸ€– Multi-Agent Architecture Specialized agents (Security, Naming, Quality) run in parallel for faster reviews
🎯 Java-Focused Checklist YAML-driven rules covering OWASP security + code quality standards
⚑ Reviews Only Changes Analyzes staged diffs, not entire filesβ€”fast and focused
🧠 AI-Powered Analysis Leverages GitHub Copilot for intelligent code understanding
🚫 Smart Blocking Only blocks BLOCK-severity issues (security/bugs), allows WARN/INFO
πŸ“‹ Structured Markdown Output Human-readable results parsed with native tools (no jq required)
πŸ–₯️ Cross-Platform Native PowerShell for Windows, bash for macOS/Linux
πŸ”§ IDE-Compatible Works with IntelliJ IDEA, VS Code, PyCharm, WebStorm, and any git client
✏️ Fully Customizable Extend the YAML checklist with your own rules

πŸš€ Quick Start

Prerequisites

1. Install GitHub Copilot CLI

All platforms (requires Node.js):

npm install -g @githubnext/github-copilot-cli

Then authenticate:

copilot auth

This will open a browser window to authenticate with your GitHub account (requires GitHub Copilot subscription).

Installation

Windows (PowerShell) - Recommended:

.\install.ps1

macOS/Linux (bash):

./install.sh

The script checks dependencies, installs the pre-commit hook, and verifies everything works.

Manual Installation:

# Windows - copy the hook wrapper
Copy-Item pre-commit.ps1 -Destination . -Force
# The installer creates a bash wrapper in .git/hooks/pre-commit that calls the PowerShell script
# macOS/Linux
cp pre-commit.sh .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

That's It!

Now every git commit triggers an automatic AI review:

git add src/main/java/MyClass.java
git commit -m "Add new feature"
# AI review runs automatically ✨

πŸ’» Platform Support

Platform Script Notes
Windows pre-commit.ps1 Native PowerShell, runs parallel jobs
macOS pre-commit.sh Native bash, runs background jobs
Linux pre-commit.sh Native bash, runs background jobs

Windows Users

The tool runs natively in PowerShell with full feature support:

  • βœ… Parallel agent execution using PowerShell jobs
  • βœ… Full emoji and Unicode support
  • βœ… No WSL required
  • βœ… Works with any IDE (IntelliJ, VS Code, etc.)
  • βœ… Works from PowerShell, CMD, or Git Bash

Using with IDEs

IntelliJ IDEA / PyCharm / WebStorm:

  1. Commit via IDE dialog (Ctrl+K) as normal
  2. The pre-commit hook runs automatically
  3. Review output appears in the IDE's console

VS Code:

  1. Commit via Source Control panel as normal
  2. The pre-commit hook runs automatically
  3. Review output appears in the terminal

Any Git Client: The hook works with any tool that uses gitβ€”GitHub Desktop, GitKraken, Tower, etc.


πŸ” Security & Privacy

⚠️ Critical: This tool sends your code to AI services. For proprietary/corporate code, you MUST use GitHub Copilot Business/Enterprise, Azure OpenAI, or local LLMs (Ollama). Do NOT use free/consumer AI tiers for confidential code.

flowchart LR
    A[Your Code] --> B[git diff]
    B --> C[Pre-commit Hook]
    C --> D[GitHub Copilot API]
    D --> E[AI Analysis]
    E --> F[Markdown Response]
    F --> G[Block/Allow Decision]
Loading

Enterprise vs. Consumer AI Plans

Aspect Enterprise/Business Plans Individual/Free Plans
Data Retention βœ… Prompts discarded immediately after response ⚠️ May be retained for service improvement
Training Usage βœ… Your code is NOT used for AI training ⚠️ May be used to train/improve models
Contractual Protection βœ… Data Processing Agreement (DPA), GDPR compliance ⚠️ Standard consumer terms only
IP Indemnification βœ… Often includes IP infringement protection ❌ Typically not included

βœ… Required for Proprietary Code: Secure AI Options

For corporate/proprietary codebases, use ONLY these options:

  1. GitHub Copilot Business/Enterprise

    • βœ… Code is discarded immediately after generating response
    • βœ… Never used to train AI models
    • βœ… Contractual data processing agreement (DPA)
    • βœ… GDPR compliant
  2. Azure OpenAI Service

    • βœ… Enterprise SLA (99.9% uptime)
    • βœ… Data residency options
    • βœ… Your data never leaves your Azure tenant
    • βœ… Full RBAC and compliance controls
  3. Local LLMs (Ollama + CodeLlama)

    • βœ… Data never leaves your machine
    • βœ… No internet connection required
    • βœ… Complete privacy
    • βœ… No subscription costs

❌ NEVER Use for Proprietary Code: Consumer AI Tiers

Do NOT use free/individual AI plans for corporate code:

  • ❌ GitHub Copilot Individual - May retain prompts, different terms than Business/Enterprise
  • ❌ Free ChatGPT, Claude, etc. - Code may be used for model training
  • ❌ Free API trials - Limited data protection guarantees

Bottom line: If you're working on proprietary code, you MUST use GitHub Copilot Business/Enterprise, Azure OpenAI, or local models (Ollama). Consumer/free tiers are NOT suitable for confidential code.

What NOT to Send (Any AI Service)

Regardless of which tier you use, never send:

  • ❌ Hardcoded secrets, API keys, or passwords
  • ❌ Proprietary algorithms or trade secrets
  • ❌ Customer PII or HIPAA/GDPR protected data
  • ❌ Internal infrastructure details (IPs, hostnames, internal URLs)

Mitigation Strategies

  1. Use Enterprise AI for corporate/proprietary codebases
  2. Use .gitignore to exclude sensitive files
  3. Use environment variables for all secrets
  4. Review staged files before committing: git diff --cached
  5. Consider local LLMs (Ollama, CodeLlama) for highly sensitive codebases
  6. Set AI_REVIEW_ENABLED=false for sensitive commits

πŸ“– Full Security Guide β†’


πŸ“– Workflows

Workflow 1: The Standard Loop

Commit β†’ Review β†’ Fix β†’ Commit

See full workflow

Step 1: Attempt Commit

git add src/main/java/UserService.java
git commit -m "Add user authentication"

Step 2: Review Blocked

╔═══════════════════════════════════════════════════════════╗
β•‘  AI REVIEW: COMMIT BLOCKED                                β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

  ❌ [BLOCK] src/main/java/UserService.java:23
     Hardcoded database password detected.

Step 3: Get AI-Assisted Fix

In your IDE (VS Code, IntelliJ):

  • Open the file, select the problematic code
  • Ask Copilot: "Fix this hardcoded password using environment variables"

Or via CLI:

gh copilot suggest "How do I fix hardcoded passwords in Java using environment variables?"

Step 4: Apply the Fix

// ❌ Before (BLOCKED):
private static final String DB_PASSWORD = "admin123";

// βœ… After (GOOD):
private static final String DB_PASSWORD = System.getenv("DB_PASSWORD");

Step 5: Commit Again

git add src/main/java/UserService.java
git commit -m "Add user authentication with secure password handling"
# βœ… Review passes!

Workflow 2: Review Past Results

# View full review
Get-Content .ai/last_review.json

# View individual agent reports
Get-Content .ai/agents/security/review.md
Get-Content .ai/agents/naming/review.md
Get-Content .ai/agents/quality/review.md

# Search for BLOCK issues
Select-String -Path .ai/last_review.json -Pattern "\[BLOCK\]"

On macOS/Linux:

cat .ai/last_review.json
grep -A 2 '\[BLOCK\]' .ai/last_review.json

Workflow 3: Emergency Bypass

When you absolutely must commit immediately:

git commit --no-verify -m "Emergency hotfix for production"

⚠️ Use sparingly! Always track bypassed security debt:

Add-Content -Path SECURITY_DEBT.md -Value "TODO: Fix issues from $(git rev-parse HEAD)"

Workflow 4: CI/CD Integration

# .github/workflows/pr-check.yml
- name: Run AI Code Review
  shell: pwsh
  run: |
    if (-not (.\pre-commit.ps1)) {
      Write-Host "Code review failed"
      Get-Content .ai/last_review.json
      exit 1
    }

βš™οΈ Configuration

Disable Review

# Single commit
git commit --no-verify -m "Skip review for this commit"

# Permanently (session)
$env:AI_REVIEW_ENABLED = 'false'

# Remove hook entirely
Remove-Item .git/hooks/pre-commit

Uninstall / Remove the Hook

Windows (PowerShell):

Remove-Item .git\hooks\pre-commit

macOS/Linux:

rm .git/hooks/pre-commit

Customize Checklist

Edit .ai/java_code_review_checklist.yaml:

rules:
  - id: custom-rule-001
    description: "Check for deprecated API usage"
    severity: WARN  # BLOCK | WARN | INFO

Severity Levels

Severity Effect Example Issues
BLOCK ❌ Prevents commit Hardcoded secrets, SQL injection, null pointer risks
WARN ⚠️ Allows commit, shows warning Poor exception handling, performance issues
INFO ℹ️ Allows commit, shows info Naming convention violations

Environment Variables

Variable Default Description
AI_REVIEW_MODEL gpt-4.1 AI model for code review (see models below)
AI_REVIEW_ENABLED true Set to false to skip AI review
SKIP_SENSITIVE_CHECK false Skip sensitive data warning prompt
FORCE_COLOR false Force colored output (bash only)

Available models: gpt-4.1, gpt-5, gpt-5-mini, gpt-5.1, gpt-5.1-codex, gpt-5.2, claude-sonnet-4, claude-sonnet-4.5, claude-haiku-4.5, claude-opus-4.5, gemini-3-pro-preview

# Use a different model
$env:AI_REVIEW_MODEL = 'claude-sonnet-4.5'
git commit -m "message"

πŸ“ Project Structure

.
β”œβ”€β”€ pre-commit.ps1                         # PowerShell pre-commit hook (Windows)
β”œβ”€β”€ pre-commit.sh                          # Bash pre-commit hook (macOS/Linux)
β”œβ”€β”€ install.ps1                            # PowerShell installation script
β”œβ”€β”€ install.sh                             # Bash installation script
β”œβ”€β”€ LICENSE                                # MIT License
β”œβ”€β”€ .ai/
β”‚   β”œβ”€β”€ agents/                           # Multi-agent system
β”‚   β”‚   β”œβ”€β”€ security/                     # Security agent
β”‚   β”‚   β”œβ”€β”€ naming/                       # Naming conventions agent
β”‚   β”‚   β”œβ”€β”€ quality/                      # Code quality agent
β”‚   β”‚   └── summarizer/                   # Results aggregator
β”‚   β”œβ”€β”€ java_code_review_checklist.yaml   # Review rules (YAML)
β”‚   β”œβ”€β”€ java_review_prompt.txt            # AI prompt template
β”‚   └── last_review.json                  # Last review results
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ ARCHITECTURE.md                   # System design
β”‚   β”œβ”€β”€ SECURITY.md                       # Security guide
β”‚   └── linked_image.png                  # Project image
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ BadClass.java                     # Example with intentional issues
β”‚   β”œβ”€β”€ a.java                            # Simple example file
β”‚   └── README.md                         # Examples documentation
└── README.md

πŸ” Troubleshooting

"GitHub CLI (gh) not found"

Install GitHub CLI for your platform:

# Windows
winget install --id GitHub.cli

# Or with Chocolatey
choco install gh

# Or with Scoop
scoop install gh
# macOS
brew install gh

# Linux
# See https://github.com/cli/cli/blob/trunk/docs/install_linux.md
"GitHub Copilot CLI extension not installed"
gh extension install github/gh-copilot
"Could not connect to GitHub Copilot"
  1. Ensure you're authenticated: gh auth login
  2. Check your GitHub Copilot subscription
  3. Verify extension: gh extension list
Hook not running

Windows:

# Check if hook exists
Test-Path .git/hooks/pre-commit

# Re-run installer
.\install.ps1

macOS/Linux:

# Check if executable
ls -la .git/hooks/pre-commit

# Make executable
chmod +x .git/hooks/pre-commit
Review takes too long
  • Large diffs (>20KB) are automatically truncated
  • Consider smaller, focused commits
  • Bypass for large refactors: git commit --no-verify
PowerShell execution policy error
# Allow script execution for current user
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
"Too many arguments" or argument length errors (Windows)

Windows has a command-line argument length limit of ~8,191 characters. The PowerShell script automatically handles this by:

  1. Checking prompt length before invocation
  2. Using stdin piping (copilot -p -) for large prompts
  3. Writing prompts to temp files when needed

If you still encounter issues:

# Reduce diff size by committing smaller changes
git add -p  # Stage partial changes

# Or increase MAX_DIFF_SIZE in pre-commit.ps1 if your prompts are within limits
# Default: $MAX_DIFF_SIZE = 20000  (bytes)
# Default: $MAX_ARG_LENGTH = 7000  (characters)

πŸ“„ License

MIT License - See LICENSE for details.


About

CLI-based AI code review system that performs comprehensive reviews at commit time

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published