npm package: @sanasai/ai-code-review
Description: Multi-agent AI-powered code review system using Claude
Author: Muthukrishnan
Latest version: 0.6.0

# AI Code Review

Multi-agent AI-powered code review system using Claude. Finds semantic bugs, security vulnerabilities, and logic errors that linters miss.

![core review](review.gif)

## Installation

```bash
npm install -g @sanasai/ai-code-review
```

Or use with npx:

```bash
npx @sanasai/ai-code-review scan
```

## Quick Start

```bash
# Initialize configuration
ai-review init

# Review staged changes
ai-review scan --staged

# Review and fix issues interactively
ai-review scan --staged --fix

# Review commit range
ai-review scan --base main --target feature-branch

# Review a specific file
ai-review scan --file src/app.ts

# Review an entire directory
ai-review scan --dir src/
```

## What It Finds (That Linters Don't)

- **Logic Errors**: Off-by-one errors, incorrect conditionals, missing null checks
- **Security**: SQL injection, XSS, authentication bypasses, hardcoded secrets
- **Concurrency**: Race conditions, missing awaits, deadlocks
- **Performance**: N+1 queries, algorithmic inefficiencies, memory leaks
- **Testing Gaps**: Missing error path tests, flaky tests, untested edge cases
- **API Misuse**: Resource leaks, deprecated APIs, incorrect library usage

## Features

### 6 Specialized AI Agents
- **Security**: Runtime vulnerabilities, auth issues, crypto problems
- **Quality**: Logic errors, race conditions, semantic bugs
- **Testing**: Coverage gaps, flaky tests, edge cases
- **Performance**: Query patterns, complexity issues, memory leaks
- **Accessibility**: WCAG compliance, keyboard navigation
- **Breakage Detection**: API changes, deleted exports, schema modifications, behavioral changes

### Interactive HTML Reports
- AI-generated explanations for each finding
- Copy-to-clipboard for coding agents
- Bad/good code examples
- Real-world security impact examples
- OWASP/CWE references

### Multi-Language Support
JavaScript/TypeScript, Python, Rust, C/C++, C#, Java, Go, Ruby, PHP, Swift, Kotlin, Dart

## Usage

### Basic Commands

```bash
# Staged changes (opens HTML report)
ai-review scan --staged

# Terminal output only
ai-review scan --staged --no-html

# Specific agents
ai-review scan --staged --agents security,testing

# JSON output
ai-review scan --staged --format json --output report.json

# Commit range
ai-review scan --base main --target HEAD

# Scan a single file
ai-review scan --file src/app.ts

# Scan a directory recursively
ai-review scan --dir src/

# Scan multiple files with custom config
ai-review scan --dir src/ -c .ai-review.json --verbose
```

### CLI Options

**Git-based Review:**
- `--staged`: Review staged changes
- `-b, --base <ref>`: Base git reference
- `-t, --target <ref>`: Target git reference

**File/Directory Scanning:**
- `--file <path>`: Scan a specific file
- `--dir <path>`: Scan a directory recursively (respects exclude/include patterns)

**Output Options:**
- `-f, --format <format>`: Output format (terminal, json, html)
- `-o, --output <path>`: Output file path
- `--no-html`: Disable HTML report
- `--no-open`: Don't open browser automatically

**Interactive Fixing:**
- `--fix`: Interactively fix detected issues using Claude CLI (requires Claude CLI to be installed)

**Configuration & Control:**
- `--agents <agents>`: Comma-separated agents to run
- `-c, --config <path>`: Path to config file
- `-v, --verbose`: Verbose output

**Note:** Cannot mix git options (`--staged`, `--base`, `--target`) with file/directory scanning (`--file`, `--dir`)

## Interactive Auto-Fix

Fix detected issues directly with AI assistance using the `--fix` flag. Claude will guide you through fixing issues one at a time with full context and explanation.

### Prerequisites

Install Claude CLI (required for interactive fixing):

```bash
npm install -g @anthropic-ai/claude-cli
# or
brew install anthropics/brew/claude-cli
```

For more installation options, visit: [Claude CLI Repository](https://github.com/anthropics/claude-cli)

### Quick Example

```bash
# Review and fix staged changes
ai-review scan --staged --fix

# Review and fix a directory
ai-review scan --dir src/ --fix

# Review specific agents and fix
ai-review scan --staged --agents security,quality --fix
```

### How It Works

1. **Scan**: AI reviews your code and finds issues
2. **Preview**: See list of all fixable issues
3. **Select**: For each issue, choose to:
   - **Y** - Fix this issue
   - **n** - Skip this issue
   - **s** - Show full context
   - **q** - Quit and stop fixing
4. **Fix**: Claude opens in your terminal and fixes all selected issues
5. **Done**: Type `exit` when finished, and you're back in the CLI

### Workflow Example

```bash
$ ai-review scan --staged --fix

✓ Starting AI code review...
✓ Running code review with 5 agents...

Found 3 issues eligible for fixing

Finding 1 of 3
────────────────────────────────────────────────────
🟠 HIGH - SQL Injection Vulnerability
File: src/api/users.ts:45
Agent: security

Description: User input is directly concatenated into SQL query

Code Snippet:
  const query = `SELECT * FROM users WHERE id = ${userId}`;

Suggestion: Use parameterized queries to prevent SQL injection
────────────────────────────────────────────────────
? Apply fix for this issue? (Y/n/s/q) Y

Issue: SQL Injection Vulnerability
Severity: HIGH
File: src/api/users.ts
Line: 45
Category: database

Description: User input is directly concatenated into SQL query

Current Code:
const query = `SELECT * FROM users WHERE id = ${userId}`;

Suggestion: Use parameterized queries to prevent SQL injection

Please fix this issue by...
[Claude opens interactively - you apply the fix and type 'exit']

[Repeats for remaining issues...]
```

### Use Cases

- **Code Review**: Before committing, review and fix issues immediately
- **PR Preparation**: Clean up issues before submitting pull requests
- **Knowledge**: Learn how to fix issues with Claude's explanations
- **Efficiency**: Batch fix multiple issues in one session
- **Quality**: Ensure code quality without manual searching

### Features

- **Interactive Session**: Claude runs directly in your terminal
- **Full Context**: See complete issue details before deciding
- **Batch Fixes**: Fix multiple issues in one conversation for better context
- **Selective Fixing**: Choose which issues to fix - skip others
- **Learn**: See Claude's fixes and explanations in real-time

### Tips

1. **Start Small**: Use `--fix` on staged changes first to test the workflow
2. **By Agent**: Use `--fix --agents security` to focus on specific issue types
3. **Review Changes**: After fixing, run `git diff` to review what was changed
4. **Test**: Run your test suite after fixes to ensure nothing broke
5. **Claude CLI Settings**: Configure Claude CLI for your preferred model/settings

### Troubleshooting

**"Claude CLI is not installed"**
Install Claude CLI: `npm install -g @anthropic-ai/claude-cli`

**"No findings are eligible for fixing"**
Some issues (like breakage detection) aren't eligible for auto-fix. Only fixable issues are offered.

**"Can't write to file"**
Ensure your files have write permissions and aren't read-only.

**"Changes weren't applied"**
Claude runs interactively - make sure to save your changes in the Claude session and type `exit` to return to the CLI.

## Configuration

### API Key Setup

The tool will prompt for your API key on first use and save it to `~/.ai-review/.ai-review.json`. Alternatively:

```bash
# Set environment variable (highest priority)
export ANTHROPIC_API_KEY="your-api-key"

# Or run init command to configure interactively
ai-review init
```

**API Key Priority:**
1. Environment variable `ANTHROPIC_API_KEY`
2. Global config `~/.ai-review/.ai-review.json`
3. Interactive prompt (saved to global config)

### Project Configuration

Create `.ai-review.json` in your project for custom settings:

```json
{
  "claude": {
    "model": "claude-sonnet-4-20250514",
    "temperature": 0.3
  },
  "agents": {
    "security": { "enabled": true },
    "quality": { "enabled": true },
    "testing": { "enabled": true },
    "performance": { "enabled": false },
    "accessibility": { "enabled": false },
    "breakage": { "enabled": true }
  }
}
```

**Note:** API keys should NOT be stored in project config files. Use the global config or environment variables instead.

## File & Directory Scanning

In addition to git-based reviews, you can scan individual files or entire directories without requiring git changes.

### Use Cases

- **Standalone Code Review**: Review files independently of git history
- **New Codebase**: Audit code before committing to git
- **Bulk Analysis**: Review all files in a directory at once
- **Offline Development**: Code review without git tracking

### Examples

```bash
# Review a single file
ai-review scan --file src/components/App.tsx

# Review an entire directory
ai-review scan --dir src/

# Review with specific agents
ai-review scan --dir src/ --agents security,quality

# Review with custom output
ai-review scan --file src/app.ts --format json --output review.json

# Verbose mode to see scanning progress
ai-review scan --dir src/ --verbose
```

### How It Works

- Scans all matching files based on `includePatterns` and `excludePaths` from config
- Binary files (images, compiled code) are automatically detected and skipped
- Files larger than `maxDiffSize` are skipped with a warning
- Entire files are treated as "added code" for review purposes
- All 6 specialized agents analyze the files as if they were new code

### Configuration

File/directory scanning respects your existing `.ai-review.json` configuration:

```json
{
  "git": {
    "includePatterns": ["**/*.ts", "**/*.js", "**/*.tsx"],
    "excludePaths": ["node_modules/**", "dist/**", "**/*.test.ts"],
    "maxDiffSize": 10000
  }
}
```

- **includePatterns**: Only scan files matching these glob patterns
- **excludePaths**: Skip files matching these patterns
- **maxDiffSize**: Maximum file size in lines (files exceeding this are skipped)

### Performance Tips

- Scanning >50 files triggers a warning about API token consumption
- Use `--agents security,quality` to run only essential agents
- Exclude large generated files and node_modules
- Consider scanning specific directories rather than entire repos

## CI/CD Integration

<details>
<summary><b>📦 Click to expand CI/CD integration examples</b></summary>

### GitHub Actions

Create `.github/workflows/ai-code-review.yml`:

```yaml
ai-code-review:
  stage: code-review
  image: node:${NODE_VERSION}
  needs: []

  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

  before_script:
    - npm install -g @sanasai/ai-code-review
    - git fetch origin ${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}

  script:
    - |
      ai-review scan \
        --base origin/${CI_MERGE_REQUEST_TARGET_BRANCH_NAME} \
        --target ${CI_COMMIT_SHA} \
        --verbose \
        --no-open \
        --agents performance,breakage

  artifacts:
    expose_as: "AI Code Review Report"
    paths:
      - report.html
    when: always
    expire_in: 30 days

  allow_failure: true
```

**Setup:**
1. Add `ANTHROPIC_API_KEY` to repository secrets (Settings → Secrets and variables → Actions)
2. Commit the workflow file
3. Workflow runs automatically on pull requests

---

### GitLab CI

#### Basic Configuration

Create `.gitlab-ci.yml`:

```yaml
ai-code-review:
  stage: test
  image: node:18
  only:
    - merge_requests
  before_script:
    - npm install -g @sanasai/ai-code-review
  script:
    - |
      ai-review scan \
        --base origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME \
        --target $CI_COMMIT_SHA \
        --format json \
        --output review-results.json \
        --no-html
  artifacts:
    when: always
    paths:
      - review-results.json
    expire_in: 30 days
  variables:
    ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
```

#### Advanced: MR Comments on Critical Issues

```yaml
stages:
  - test
  - report

ai-code-review:
  stage: test
  image: node:18
  only:
    - merge_requests
  before_script:
    - npm install -g @sanasai/ai-code-review
  script:
    - |
      ai-review scan \
        --base origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME \
        --target $CI_COMMIT_SHA \
        --format json \
        --output review-results.json \
        --agents security,quality \
        --no-html
  artifacts:
    when: always
    paths:
      - review-results.json
    expire_in: 30 days
  allow_failure: true
  variables:
    ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY

comment-on-mr:
  stage: report
  image: node:18
  only:
    - merge_requests
  dependencies:
    - ai-code-review
  before_script:
    - npm install axios
  script:
    - |
      node -e "
      const fs = require('fs');
      const axios = require('axios');

      const results = JSON.parse(fs.readFileSync('review-results.json', 'utf8'));
      const criticalIssues = results.findings?.filter(f =>
        f.severity === 'critical' || f.severity === 'high'
      ) || [];

      if (criticalIssues.length === 0) {
        console.log('No critical issues found');
        process.exit(0);
      }

      const comment = \`## 🚨 AI Code Review Found \${criticalIssues.length} Critical/High Issues\n\n\` +
        criticalIssues.slice(0, 5).map(issue =>
          \`### \${issue.title} (\${issue.severity})\n\` +
          \`- **File:** \\\`\${issue.file}:\${issue.line}\\\`\n\` +
          \`- **Description:** \${issue.description}\n\`
        ).join('\n');

      axios.post(
        \`\${process.env.CI_API_V4_URL}/projects/\${process.env.CI_PROJECT_ID}/merge_requests/\${process.env.CI_MERGE_REQUEST_IID}/notes\`,
        { body: comment },
        { headers: { 'PRIVATE-TOKEN': process.env.GITLAB_TOKEN } }
      ).then(() => console.log('Comment posted'))
       .catch(err => console.error('Failed:', err.message));
      "
  when: on_failure
  allow_failure: true
```

**Setup:**
1. Go to **Settings → CI/CD → Variables**
2. Add `ANTHROPIC_API_KEY` (mask and protect)
3. For MR comments, add `GITLAB_TOKEN` with `api` scope
4. Commit `.gitlab-ci.yml`

---

### Jenkins

Add to `Jenkinsfile`:

```groovy
pipeline {
    agent any

    environment {
        ANTHROPIC_API_KEY = credentials('anthropic-api-key')
    }

    stages {
        stage('AI Code Review') {
            steps {
                sh 'npm install -g @sanasai/ai-code-review'
                sh """
                    ai-review scan \
                        --base origin/main \
                        --target ${env.GIT_COMMIT} \
                        --format json \
                        --output review-results.json \
                        --no-html
                """
                archiveArtifacts artifacts: 'review-results.json'
            }
        }
    }
}
```

**Setup:**
1. Add `ANTHROPIC_API_KEY` as Jenkins credential
2. Update Jenkinsfile in repository

---

### CircleCI

Create `.circleci/config.yml`:

```yaml
version: 2.1

jobs:
  ai-code-review:
    docker:
      - image: cimg/node:18.0
    steps:
      - checkout
      - run:
          name: Install AI Code Review
          command: npm install -g @sanasai/ai-code-review
      - run:
          name: Run AI Code Review
          command: |
            ai-review scan \
              --base origin/main \
              --target $CIRCLE_SHA1 \
              --format json \
              --output review-results.json \
              --no-html
      - store_artifacts:
          path: review-results.json

workflows:
  version: 2
  review:
    jobs:
      - ai-code-review:
          filters:
            branches:
              ignore: main
```

**Setup:**
1. Add `ANTHROPIC_API_KEY` in CircleCI project settings
2. Commit configuration file

---

### Best Practices

1. **API Key Security**: Always use CI/CD secrets, never commit keys
2. **Target Specific Agents**: Use `--agents security,quality` for critical-only reviews
3. **Exit Codes**: Tool exits non-zero on critical issues
4. **Caching**: Cache npm installations to speed up CI
5. **Conditional Runs**: Only run on PRs/MRs to save API costs
6. **Artifact Storage**: Always store JSON reports as artifacts
7. **Fail on Critical**: Configure CI to fail on critical/high severity

### Optimization Tips

**Cache Dependencies (GitLab)**
```yaml
cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .npm/
```

**Parallel Agent Execution (GitLab)**
```yaml
security-review:
  script: ai-review scan --agents security

quality-review:
  script: ai-review scan --agents quality
```

**Scheduled Full Codebase Reviews**
```yaml
scheduled-review:
  only:
    - schedules
  script:
    - ai-review scan --base HEAD~100 --target HEAD
```

### Troubleshooting

**Issue: Pipeline fails with "ANTHROPIC_API_KEY not set"**
Solution: Ensure the environment variable is added to CI/CD settings and properly masked

**Issue: "git diff returned no changes"**
Solution: Ensure `fetch-depth: 0` (GitHub Actions) or full clone is enabled

**Issue: High API costs**
Solution: Use `--agents security,quality` to run only essential agents in CI

</details>

## Why Use This Instead of Linters?

| Linters | AI Code Review |
|---------|----------------|
| Missing semicolons | SQL injection vulnerabilities |
| Unused variables | Race conditions in async code |
| Formatting issues | Off-by-one errors |
| Import order | N+1 query patterns |
| Naming conventions | Missing null checks |

**Linters find style issues. AI finds bugs.**

## Configuration Commands

```bash
# Show current config
ai-review config show

# Validate config
ai-review config validate

# Show config file path
ai-review config path
```

## License

Apache-2.0

---

**Built with ❤️ by [Sanas AI](https://sanas.ai) Engineering**