npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

pre-commit-ai-review

npm version GitHub License: MIT Node.js >= 18

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, or info
  • 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-review

Then 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 --native

This 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 model is 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:

  1. Gets staged file diffs
  2. Sends each file to the configured AI provider
  3. Displays results grouped by file and severity
  4. 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 uninstall

Programmatic 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 blocked

Requirements

  • Node.js >= 18
  • Git repository
  • API key for at least one supported provider

Contributing

Contributions, bug reports, and feature requests are welcome!

License

MIT — see LICENSE on GitHub.