pre-commit-ai-review
v1.1.0
Published
AI-powered code review as a pre-commit hook with configurable rules, severity categorization, and interactive override support
Downloads
191
Maintainers
Readme
pre-commit-ai-review
AI-powered code review as a pre-commit hook. Integrates with OpenAI, Anthropic, or Google Gemini to review your staged changes before every commit, with configurable rules, severity-based categorization, and interactive override support.
Think of it as having a senior engineer review every diff before it lands — automatically, on every commit, across your entire team.
Source & Issues: github.com/vineetbarshikar/pre-commit-ai-review
Features
- Multi-provider support — OpenAI (GPT-4o), Anthropic (Claude), Google Gemini
- 8 review dimensions — bugs, security, complexity, maintainability, readability, best practices, performance, and testability
- Configurable severity — issues categorized as
error,warning, orinfo - Blocking by severity — configure which severity levels block the commit
- Interactive overrides — override individual blocking issues with a reason
- Custom rules — define plain-English project-specific rules (folder structure, coding standards, etc.)
- Optional review — disable globally or skip per-commit with an env var
- Husky + native hook support — works with both Husky and raw git hooks
- Path filtering — ignore files matching glob patterns
What Gets Reviewed
Every commit is evaluated across 8 dimensions by the AI model. This goes well beyond simple linting — the AI understands intent, context, and engineering trade-offs.
1. Correctness & Bugs
Catches logic errors that static analysis misses — incorrect conditionals, off-by-one mistakes, unhandled edge cases, null/undefined dereferences, and misuse of async/await.
✖ ERROR src/cart.ts (line 18) [bug]
Discount is applied before checking if the cart is empty, resulting in negative totals.
→ Move the empty-cart guard above the discount calculation on line 12.2. Security
Flags injection vulnerabilities, hardcoded secrets, insecure data handling, missing input validation, and improper auth checks before they ever reach your repo.
✖ ERROR src/db.ts (line 34) [security]
String interpolation used in SQL query — vulnerable to SQL injection.
→ Use parameterized queries: db.query('SELECT * FROM users WHERE id = ?', [id])3. Code Complexity & Maintainability
Identifies functions that are doing too much, deeply nested logic that increases cognitive load, high cyclomatic complexity, duplicated logic, and magic numbers that should be named constants.
⚠ WARNING src/checkout.ts (line 5) [complexity]
Function processOrder is 87 lines long and handles validation, pricing, inventory,
and email — violates Single Responsibility Principle.
→ Split into processOrder, validateOrder, calculateTotal, and notifyUser.4. Readability
Flags unclear variable or function names, missing comments on non-obvious logic, inconsistent style, and dense expressions that make the code hard to scan.
ℹ INFO src/utils.ts (line 22) [readability]
Variable 'd' does not express intent.
→ Rename to 'deliveryDeadline' to clarify its purpose.5. Best Practices & Design
Catches violations of SOLID principles, inappropriate coupling between modules, use of deprecated APIs, and patterns that are discouraged for the language or framework in use.
⚠ WARNING src/components/UserProfile.tsx (line 10) [best-practices]
Component directly imports and calls the API client — bypasses the service layer.
→ Route the call through src/services/userService.ts to keep components decoupled.6. Error Handling & Resilience
Finds unhandled promise rejections, empty catch blocks that swallow errors, missing fallback values, and operations that can fail silently.
✖ ERROR src/api.ts (line 56) [error-handling]
fetch() call has no .catch() and is not inside a try/catch — unhandled rejection
will crash the process in Node.js.
→ Wrap in try/catch or add .catch(err => logger.error(err)).7. Performance
Spots unnecessary re-computation inside loops, missing memoization opportunities, inefficient data structures, and patterns that cause excessive memory allocation.
⚠ WARNING src/search.ts (line 14) [performance]
JSON.parse(JSON.stringify(obj)) used for deep clone inside a loop — expensive on
every iteration.
→ Use structuredClone(obj) (Node 17+) or move the clone outside the loop.8. Testability
Highlights code that will be hard to unit test — tightly coupled logic, mixed I/O and business logic, functions with too many responsibilities to mock effectively.
ℹ INFO src/mailer.ts (line 8) [testability]
sendWelcomeEmail() directly instantiates the SMTP transport — cannot be mocked in tests.
→ Accept the transport as a parameter or inject it via a service container.Installation
npm install --save-dev pre-commit-ai-reviewThen install the pre-commit hook:
# Auto-detect (uses Husky if found, otherwise native)
npx pre-commit-ai-review install
# Explicitly use Husky
npx pre-commit-ai-review install --husky
# Explicitly use native .git/hooks/pre-commit
npx pre-commit-ai-review install --nativeThis creates the hook and generates a default .aireviewrc.json config file.
API Key Setup
Set the environment variable for your chosen provider:
# OpenAI
export OPENAI_API_KEY=sk-...
# Anthropic
export ANTHROPIC_API_KEY=sk-ant-...
# Google Gemini
export GEMINI_API_KEY=AIza...For persistent setup, add to your shell profile (.zshrc, .bashrc, etc.) or use a .env file (do not commit it).
Configuration
All configuration lives in .aireviewrc.json (or .aireviewrc, .aireviewrc.yaml, aireview.config.js) in your project root.
Full Configuration Reference
{
"enabled": true,
"provider": "openai",
"model": "gpt-5.4",
"blockOn": ["error"],
"rules": [
"Use constants instead of magic numbers",
"Follow the src/features/<feature-name>/ folder structure",
"Always handle promise rejections with try/catch or .catch()",
"Use TypeScript strict types — avoid 'any'"
],
"ignorePaths": [
"node_modules/**",
"dist/**",
"build/**",
"*.lock",
"*.min.js",
"*.min.css",
"coverage/**"
],
"maxFilesPerCommit": 20,
"maxDiffLinesPerFile": 500,
"includeFullFile": false,
"systemPromptExtra": "This is a React + TypeScript project."
}Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | boolean | true | Enable or disable the review. When false, the hook exits immediately. |
| provider | "openai" \| "anthropic" \| "gemini" | "openai" | AI provider to use. |
| model | string | Auto per provider | Model name. Defaults: gpt-4o, claude-3-5-sonnet-20241022, gemini-2.0-flash. |
| apiKey | string | From env var | API key. Prefer setting via environment variable. |
| blockOn | Severity[] | ["error"] | Which severity levels block the commit. |
| rules | string[] | [] | Plain-English project rules to enforce. |
| ignorePaths | string[] | See defaults | Glob patterns for files to skip. |
| maxFilesPerCommit | number | 20 | Max files to review per commit (to control token usage). |
| maxDiffLinesPerFile | number | 500 | Max diff lines per file before truncation. |
| includeFullFile | boolean | false | Send full file content alongside diff. |
| systemPromptExtra | string | — | Additional instructions injected into the system prompt. |
Provider Models
OpenAI
| Model | API String | Notes |
|-------|-----------|-------|
| GPT-5.4 ⭐ | gpt-5.4 | Latest flagship, 1M context, native computer-use |
| GPT-5.4 Pro | gpt-5.4-pro | Maximum performance |
| GPT-5.3 Codex | gpt-5.3-codex | Optimized for code generation + reasoning |
| o3 | o3 | Best reasoning model for complex problems |
| o4-mini | o4-mini | Fast, cost-efficient reasoning |
| GPT-4o | gpt-4o | Widely available, good fallback |
Anthropic
| Model | API String | Notes |
|-------|-----------|-------|
| Claude Sonnet 4.6 ⭐ | claude-sonnet-4-6 | Best speed/intelligence balance, default on claude.ai |
| Claude Opus 4.6 | claude-opus-4-6 | Most intelligent, best for complex agentic tasks |
| Claude Haiku 4.5 | claude-haiku-4-5 | Fastest and most affordable |
Google Gemini
| Model | API String | Notes |
|-------|-----------|-------|
| Gemini 2.5 Flash ⭐ | gemini-2.5-flash | Best price/performance, stable |
| Gemini 2.5 Pro | gemini-2.5-pro | Most capable stable model |
| Gemini 3.1 Pro Preview | gemini-3.1-pro-preview | Latest, enterprise reasoning |
| Gemini 3.1 Flash Preview | gemini-3.1-flash-preview | Latest fast model |
| Gemini 3.1 Flash Lite Preview | gemini-3.1-flash-lite-preview | Fastest and cheapest |
Note: Models marked ⭐ are the defaults used when no
modelis specified in config. Preview models may require allowlist access. Always check your provider's billing tier if you get a 404 or 403 error.
Usage
Normal Commit
git add .
git commit -m "my changes"The hook runs automatically and:
- Gets staged file diffs
- Sends each file to the configured AI provider
- Displays results grouped by file and severity
- Prompts you to override or abort for blocking issues
Skip Review for One Commit
SKIP_AI_REVIEW=1 git commit -m "emergency fix"Disable Review Globally
Set "enabled": false in .aireviewrc.json.
Severity Levels
| Level | Icon | Description | Blocking (default) |
|-------|------|-------------|-------------------|
| error | ✖ | Bugs, security vulnerabilities, runtime failures, data loss risks | Yes |
| warning | ⚠ | High complexity, maintainability problems, performance issues, missing error handling | No |
| info | ℹ | Readability improvements, best practice suggestions, optional refactors | No |
Issues are also tagged with a category so you can see at a glance what kind of problem was found:
bug · security · complexity · maintainability · readability · naming · best-practices · performance · error-handling · types · duplication · structure · testability · documentation · style
To also block on warnings:
{
"blockOn": ["error", "warning"]
}Interactive Override Flow
When blocking issues are found, you are prompted for each one:
✖ ERROR in src/auth.ts (line 42): [security]
Using hardcoded credentials in source code
→ Move credentials to environment variables
? What would you like to do?
❯ Override — commit anyway (requires reason)
Abort — cancel the commit
? Enter your override reason: Will fix in follow-up ticket AI-123
✓ Override recorded.Overrides are saved to .aireview-overrides.json (gitignored) with a timestamp and reason for auditability.
Custom Rules Examples
{
"rules": [
"Follow the src/features/<name>/index.ts entry-point pattern for new features",
"Use named exports only — no default exports",
"All API calls must go through the src/api/ layer, not called directly in components",
"Use the logger utility from src/utils/logger.ts instead of console.log",
"Database queries must use parameterized statements to prevent SQL injection",
"React components must have explicit return types",
"Error boundaries must wrap route-level components"
]
}Uninstalling
npx pre-commit-ai-review uninstallProgrammatic Usage
You can also use the package programmatically:
import {
loadConfig,
getStagedChanges,
createProvider,
reviewStagedFiles,
runInteractiveReview,
} from "pre-commit-ai-review";
const config = await loadConfig();
const staged = await getStagedChanges(process.cwd(), config.ignorePaths, config.maxFilesPerCommit, config.maxDiffLinesPerFile);
const provider = createProvider(config.provider);
const review = await reviewStagedFiles(staged.files, provider, config);
const result = await runInteractiveReview(review, config.blockOn, process.cwd());
if (!result.proceed) {
process.exit(1);
}How It Works
git commit
│
▼
pre-commit hook
│
▼
Load .aireviewrc.json
│
▼
Get staged file diffs (git diff --cached)
│
▼
Filter by ignorePaths + maxFilesPerCommit
│
▼
Send each diff to AI provider with:
- System prompt (reviewer role + output format)
- Custom rules from config
- File diff as user message
│
▼
Parse structured JSON response
│
▼
Categorize by severity (error / warning / info)
│
▼
Display results in terminal
│
▼
If blocking issues found:
→ Prompt: Override (with reason) or Abort
→ Save overrides to .aireview-overrides.json
│
▼
Commit proceeds or is blockedRequirements
- Node.js >= 18
- Git repository
- API key for at least one supported provider
Contributing
Contributions, bug reports, and feature requests are welcome!
- GitHub repository: github.com/vineetbarshikar/pre-commit-ai-review
- Report a bug: github.com/vineetbarshikar/pre-commit-ai-review/issues
- npm package: npmjs.com/package/pre-commit-ai-review
License
MIT — see LICENSE on GitHub.
