@sanasai/ai-code-review
v0.6.0
Published
Multi-agent AI-powered code review system using Claude
Maintainers
Readme
AI Code Review
Multi-agent AI-powered code review system using Claude. Finds semantic bugs, security vulnerabilities, and logic errors that linters miss.

Installation
npm install -g @sanasai/ai-code-reviewOr use with npx:
npx @sanasai/ai-code-review scanQuick Start
# 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
# 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 --verboseCLI 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):
npm install -g @anthropic-ai/claude-cli
# or
brew install anthropics/brew/claude-cliFor more installation options, visit: Claude CLI Repository
Quick Example
# 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 --fixHow It Works
- Scan: AI reviews your code and finds issues
- Preview: See list of all fixable issues
- Select: For each issue, choose to:
- Y - Fix this issue
- n - Skip this issue
- s - Show full context
- q - Quit and stop fixing
- Fix: Claude opens in your terminal and fixes all selected issues
- Done: Type
exitwhen finished, and you're back in the CLI
Workflow Example
$ 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
- Start Small: Use
--fixon staged changes first to test the workflow - By Agent: Use
--fix --agents securityto focus on specific issue types - Review Changes: After fixing, run
git diffto review what was changed - Test: Run your test suite after fixes to ensure nothing broke
- 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:
# Set environment variable (highest priority)
export ANTHROPIC_API_KEY="your-api-key"
# Or run init command to configure interactively
ai-review initAPI Key Priority:
- Environment variable
ANTHROPIC_API_KEY - Global config
~/.ai-review/.ai-review.json - Interactive prompt (saved to global config)
Project Configuration
Create .ai-review.json in your project for custom settings:
{
"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
# 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/ --verboseHow It Works
- Scans all matching files based on
includePatternsandexcludePathsfrom config - Binary files (images, compiled code) are automatically detected and skipped
- Files larger than
maxDiffSizeare 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:
{
"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,qualityto run only essential agents - Exclude large generated files and node_modules
- Consider scanning specific directories rather than entire repos
CI/CD Integration
GitHub Actions
Create .github/workflows/ai-code-review.yml:
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: trueSetup:
- Add
ANTHROPIC_API_KEYto repository secrets (Settings → Secrets and variables → Actions) - Commit the workflow file
- Workflow runs automatically on pull requests
GitLab CI
Basic Configuration
Create .gitlab-ci.yml:
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_KEYAdvanced: MR Comments on Critical Issues
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: trueSetup:
- Go to Settings → CI/CD → Variables
- Add
ANTHROPIC_API_KEY(mask and protect) - For MR comments, add
GITLAB_TOKENwithapiscope - Commit
.gitlab-ci.yml
Jenkins
Add to Jenkinsfile:
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:
- Add
ANTHROPIC_API_KEYas Jenkins credential - Update Jenkinsfile in repository
CircleCI
Create .circleci/config.yml:
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: mainSetup:
- Add
ANTHROPIC_API_KEYin CircleCI project settings - Commit configuration file
Best Practices
- API Key Security: Always use CI/CD secrets, never commit keys
- Target Specific Agents: Use
--agents security,qualityfor critical-only reviews - Exit Codes: Tool exits non-zero on critical issues
- Caching: Cache npm installations to speed up CI
- Conditional Runs: Only run on PRs/MRs to save API costs
- Artifact Storage: Always store JSON reports as artifacts
- Fail on Critical: Configure CI to fail on critical/high severity
Optimization Tips
Cache Dependencies (GitLab)
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- .npm/Parallel Agent Execution (GitLab)
security-review:
script: ai-review scan --agents security
quality-review:
script: ai-review scan --agents qualityScheduled Full Codebase Reviews
scheduled-review:
only:
- schedules
script:
- ai-review scan --base HEAD~100 --target HEADTroubleshooting
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
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
# Show current config
ai-review config show
# Validate config
ai-review config validate
# Show config file path
ai-review config pathLicense
Apache-2.0
Built with ❤️ by Sanas AI Engineering
