Review Code para Claude Code
haacked/review-code
Revisão de código paralela com agentes especializados por domínio
Ver no GitHubSistema abrangente de revisão de código que utiliza agentes IA especializados para analisar segurança, performance, correção, manutenibilidade, testes, compatibilidade e arquitetura. Executa múltiplos revisores em paralelo, otimizando tokens e velocidade de análise.
Instalação
npx convez-ai haacked/review-code1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Validar segurança e vulnerabilidades OWASP antes de deploy
- Otimizar performance e detectar padrões como queries N+1
- Revisar arquitetura e padrões de design de sistema
- Validar compatibilidade e breaking changes
- Analisar cobertura e qualidade de testes
Veredito

Ferramenta madura e bem arquitetada para automação de revisão de código. A abordagem com agentes paralelos especializados resolve limitações reais de single-agent reviews, oferecendo análise profunda com eficiência de tokens. Requer bash 4.0+ e é ideal para equipes que buscam padronizar qualidade sem overhead manual.
README
A tradução para o português deste README ainda está na fila.
Review-Code for Claude Code
A comprehensive code review system for Claude Code that uses specialized AI agents to review your code for security, performance, correctness, maintainability, testing, compatibility, and architecture concerns.
⚠️ macOS Users: This tool requires bash 4.0+. macOS ships with bash 3.2 by default. Install bash 4.0+ with
brew install bashbefore proceeding.
Goals
This system was built with three core objectives:
1. Comprehensive Code Reviews
Specialized agents each focus on a distinct aspect of code quality, ensuring nothing falls through the cracks:
Core Review Agents (Always Run):
- Security: Vulnerabilities, OWASP Top 10, secret management
- Performance: Database optimization, N+1 queries, algorithmic complexity
- Correctness: Intent verification, integration boundaries, functional correctness
- Maintainability: Code clarity, simplicity, technical debt
- Testing: Coverage, quality, edge cases
- Compatibility: Breaking changes, backward compatibility
- Architecture: System design, patterns, necessity
Domain-Specific Agents (Conditional):
- Frontend: React, Kea state management, accessibility, hooks (runs only when
.tsx/.jsxfiles are detected) - Infra-Config: Helm values, Kubernetes manifests, Terraform, ArgoCD, CI/CD pipelines (runs only when matching files are detected)
Supporting Agents:
- Context Explorer: Pre-review pass that gathers architectural context for the specialized reviewers
- Finding Validator: Adversarial pass that attempts to disprove blocking findings before they ship
- Voice: Final pass that rewrites comment bodies in a plain, conversational voice while preserving citations and code
Each review agent runs independently and in parallel, providing deep expertise in its domain rather than a superficial scan across all concerns.
Why Multiple Specialized Agents?
This architecture solves real problems encountered with single-agent reviews:
Problem with Single Agent Approach:
- Required multiple review passes, manually asking to focus on different aspects each time
- Sequential execution through a long checklist meant slow reviews (12-18s)
- Context window filled up by the time later checklist items were reached, degrading quality
- Superficial coverage across all concerns since one agent can't be expert in everything
Benefits of Multiple Specialized Agents:
- Parallel Execution: Core agents run concurrently (4-6x faster than sequential)
- Fresh Context Windows: Each agent gets full context budget, maintaining quality across all areas
- Deep Expertise: Security agent knows OWASP Top 10, performance agent knows N+1 patterns
- Token Efficiency: Each agent loads only relevant context (security doesn't need performance guidelines)
- Focused Findings: Specialized agents provide more actionable, detailed recommendations
This isn't premature abstraction - it's solving proven problems with a domain-appropriate architecture.
2. Token Efficiency
Review-code achieves 40-60% token savings through multiple optimization strategies:
- Diff Compression: Minimal context lines (1 vs 3) - agents can read full files when needed
- Smart Context Loading: Only loads guidelines for detected languages/frameworks
- Architectural Context Caching: Caches context exploration results for 24 hours
- Incremental Diff Tracking: Only reviews files changed since last review
- Bash Scripts for Heavy Lifting: Uses shell scripts for diff generation, file detection, and context preparation instead of consuming tokens
This means you get thorough reviews without burning through your token budget.
3. Continuous Improvement via Feedback Loop
The system learns and improves over time through a structured feedback mechanism:
- Structured Context Files: Language, framework, org, and repo-specific guidelines live in
context/directories - Review Artifacts: Every review is saved with confidence scores and detailed findings
- Iterative Refinement: Insights from reviews can be fed back into context files to improve future reviews
- Agent Specialization: Findings help refine each agent's focus areas and detection patterns
- Knowledge Accumulation: Org and repo contexts capture institutional knowledge about patterns, antipatterns, and conventions
This creates a virtuous cycle where reviews get better as you identify new patterns to detect or guidelines to enforce.
Features
- Specialized Review Agents: Each agent focuses on a specific aspect of code quality
- Core Agents (7): Security, Performance, Correctness, Maintainability, Testing, Compatibility, Architecture
- Conditional Agents (2): Frontend (React/TypeScript files), Infra-Config (Helm/Terraform/K8s/CI-CD files)
- Supporting Agents: Context Explorer (pre-review), Finding Validator (adversarial pass), Voice (final rewrite)
- Hierarchical Context Loading: Automatically loads language, framework, org, and repo-specific guidelines
- PR and Local Review Modes: Review pull requests, branches, commits, ranges, or uncommitted changes
- Stack-Aware Branch Reviews: Detects Graphite parents (or
branch.<name>.parentin git config) so stacked branches review against the right base - Draft GitHub Reviews:
--draftposts inline comments as a pending review, with automatic comment-drift detection when new commits land between generation and submission - Copilot Integration: Cross-checks findings against GitHub Copilot's review for corroboration
- Learning Loop:
learnsubcommand analyzes PR outcomes and folds patterns back into context files - Token Optimizations: Diff filtering (excludes lock files, snapshots, generated code), context caching (40-60% savings)
- Confidence Scoring: Every finding includes confidence level (20-100%) to help prioritize
Quick Start
Prerequisites
Before installing, ensure you have:
- bash 4.0+:
bash --version- macOS users MUST install bash 4.0+:
brew install bash(system bash 3.2 will NOT work) - Why: The system uses bash 4.0+ features (associative arrays, case conversion operators)
- Verify: Run
bash --version- should show 4.0 or higher
- macOS users MUST install bash 4.0+:
- git:
git --version(install from git-scm.com) - gh (GitHub CLI):
gh --version(install from cli.github.com) - jq:
jq --version(brew install jq) - Claude Code: The
~/.claudedirectory should exist
Installation
Option 1: Quick Install (Recommended)
Install with a single command:
curl -fsSL https://raw.githubusercontent.com/haacked/review-code/main/install.sh | bash
This will:
- Download review-code temporarily
- Install files to
~/.claude/and your chosen review directory - Clean up the download automatically
- No repository kept around after installation
Option 2: Local Development Install
For developers working on review-code:
- Clone this repository:
git clone https://github.com/haacked/review-code ~/dev/haacked/review-code
- Run the setup script:
cd ~/dev/haacked/review-code
bin/setup
- Run tests to verify everything works:
bin/test
- Make changes and re-run setup to test:
# Edit agents, scripts, or context files
vim agents/code-reviewer-security.md
# Run tests to ensure changes work
bin/test
# Re-install to test changes
bin/setup
Both methods will:
- Copy skill files to
~/.claude/skills/review-code/(SKILL.md, handlers, scripts, context) - Copy agent definitions to
~/.claude/agents/ - Install the uninstaller at
~/.claude/bin/uninstall-review-code.sh - Smart-merge context files so user learnings are preserved across updates
- Prompt you to choose where to save code reviews (default:
~/dev/ai/reviews) - Show permissions guide for Claude Code
Usage
Review Local Changes
/review-code
Smart mode that prompts you to choose:
- If on main/master: Reviews uncommitted changes only
- If on feature branch with uncommitted changes: Prompts to review uncommitted, branch, or both
- If on feature branch with no uncommitted changes: Reviews entire branch vs base
Review Pull Requests
Review any GitHub pull request by URL - works from anywhere (inside or outside a git repository):
/review-code https://github.com/org/repo/pull/456 # Review any PR by URL
How it works:
- Outside git repo: Fetches all context via
ghCLI from GitHub - Inside git repo (different branch): Uses
ghCLI to fetch PR context - Inside git repo (on PR's branch): Uses local git for faster diff generation
This means you can review PRs for any repository without needing to clone it locally.
Speeding up cross-repo PR reviews with repos.conf
When reviewing a PR from outside its repository, the skill can provision a short-lived worktree off a local clone you already have, giving agents native Read/Grep/Glob access to the PR source instead of falling back to a diff-only review. Opt in by creating ~/.claude/skills/review-code/repos.conf:
# Format: <org>/<repo> <absolute-or-tilde-path>
posthog/posthog ~/dev/posthog/posthog
someorg/somerepo ~/dev/someorg/somerepo
$REVIEW_CODE_CONFIG_DIR/repos.conf overrides the default location (used by tests and advanced setups).
Without a mapping for the PR's repo, the review falls back to diff-only (with a warning).
Review Git History
/review-code 356ded2 # Review that specific commit
/review-code feature-branch # Review entire branch vs main
/review-code abc123..HEAD # Review changes from abc123 to HEAD
/review-code v1.0.0..v2.0.0 # Review changes between two tags
Run Specific Review Type (on uncommitted changes)
/review-code security # Security review only
/review-code performance # Performance review only
/review-code correctness # Correctness review only
/review-code maintainability # Maintainability review only
/review-code testing # Testing review only
/review-code compatibility # Compatibility review only
/review-code architecture # Architecture review only
/review-code frontend # Frontend review only (React/TypeScript)
/review-code infra-config # Infrastructure config review only (Helm/Terraform/K8s/CI-CD)
Find Existing Reviews
/review-code find # Find review for current branch/PR
/review-code find 123 # Find review for PR #123
/review-code find feature-branch # Find review for a specific branch
Learn from Past Reviews
The learn subcommand analyzes outcomes of past PR reviews (what was acted on, what was dismissed) and folds insights back into the context files.
/review-code learn 123 # Analyze outcomes of a specific PR
/review-code learn # Batch-analyze all unanalyzed PRs with existing reviews
/review-code learn --apply # Apply accumulated learnings to context files
Flags
--draft/-d— Post a pending GitHub review with inline comments (PR mode only). Auto-detects and adjusts for comment drift when new commits land between review generation and submission.--self— Allow draft reviews on your own PR (for testing).--parent <ref>— Override the base branch for branch/current-branch reviews. By default, branches with a recorded stack parent (Graphite orbranch.<name>.parent) review against that parent.--force/-f— Skip the pre-flight context clear prompt.--overwrite— Replace an existing review file without prompting.--append— Append to an existing review file without prompting.--fix— After the review, apply fixes for findings the agent can resolve cleanly. Edits the working tree directly; the Fix Summary section in the saved review lists anything skipped and any judgment calls made. Not compatible withlearnorfind.
Filter by File Pattern
Add a file pattern as the second argument to review only matching files:
/review-code "*.sh" # Review only shell scripts (uncommitted)
/review-code 356ded2..HEAD "*.py" # Review only Python files in range
/review-code feature-branch "src/**/*.ts" # Review only TypeScript in src/
/review-code https://github.com/org/repo/pull/123 "lib/*.rs" # Review only Rust files in PR
/review-code security "*.go" # Security review only Go files (uncommitted)
File patterns support:
- Wildcards:
*.js,*.{ts,tsx} - Directories:
src/**/*.py - Specific paths:
lib/auth.rs
How Review Determines What to Review
When you run /review-code, the system:
-
Shows you a summary of what will be reviewed before starting:
📋 Review Summary Repository: posthog/posthog Branch: feature-branch (vs master) Location: /path/to/worktree Comparison: master..feature-branch Changes: - Commits: 3 - Files: 12 - Added: +450 lines - Removed: -123 lines -
Asks for confirmation before running the review agents
-
Determines the base branch using smart detection:
- Gets default branch name from
git symbolic-ref refs/remotes/origin/HEAD(e.g., "master" or "main") - Prefers local branch: If
masterexists locally, compares against localmaster - Falls back to remote: If local doesn't exist, uses
origin/master - Fallback chain: Tries
main→origin/main→master→origin/masterif origin/HEAD doesn't exist
This means:
- Fresh clones work: Even if you haven't checked out main/master locally
- Clearer comparisons: Summary shows whether comparing against local or remote branch
- Accurate commit counts: Shows exactly how many commits will be reviewed
- Gets default branch name from
-
Counts commits in the range: For branch reviews, shows commit count from base to HEAD
This eliminates confusion about what's being reviewed and lets you cancel if the wrong files or range were detected.
Review Agents
The system includes seven core agents (always run), two conditional agents (run when matching files are detected), and three supporting agents (context exploration, finding validation, and voice).
Core Agents
Security (code-reviewer-security)
Focuses on:
- Authentication and authorization vulnerabilities
- Input validation and sanitization
- SQL injection, XSS, CSRF protection
- Secret management
- API security
- OWASP Top 10 compliance
Performance (code-reviewer-performance)
Focuses on:
- Database query optimization
- N+1 query detection
- Caching opportunities
- Algorithmic complexity
- Memory leaks
- Resource usage
Correctness (code-reviewer-correctness)
Focuses on:
- Functional correctness against the PR's stated intent
- Integration boundaries (cache, queue, API, database)
- Preservation of existing behavior
- Edge cases and failure modes
Maintainability (code-reviewer-maintainability)
Focuses on:
- Code clarity and readability
- Function/class complexity
- Naming conventions
- Code duplication
- Technical debt
- Simplicity (YAGNI, KISS)
Testing (code-reviewer-testing)
Focuses on:
- Test coverage adequacy
- Test quality and clarity
- Missing edge cases
- Test maintainability
- Flaky tests
- Test naming
Compatibility (code-reviewer-compatibility)
Focuses on:
- Breaking API changes
- Database migration safety
- Backward compatibility
- Versioning concerns
- Deprecation handling
Architecture (code-reviewer-architecture)
Focuses on:
- System design appropriateness
- Component boundaries
- Coupling and cohesion
- Abstraction levels
- Pattern misuse
- Over-engineering
- Necessity (YAGNI)
- Code reuse opportunities
Conditional Agents
Frontend (code-reviewer-frontend)
Runs only when: .tsx, .jsx, or frontend-related files are detected in the diff
Focuses on:
- React component design and patterns
- Kea/Redux state management
- Hooks usage and dependencies
- Accessibility (a11y) compliance
- React performance (re-renders, memoization)
- TypeScript type safety for components
- Component lifecycle and side effects
Why conditional? Frontend expertise is only needed for React/TypeScript changes. Running it unconditionally wastes tokens on backend-only changes.
Infra-Config (code-reviewer-infra-config)
Runs only when: Infrastructure config files are detected in the diff (Helm values.yaml, Chart.yaml, .tf/.tfvars, Kubernetes manifests, ArgoCD configs, Dockerfile, GitHub Actions workflows, kustomization.yaml, etc.)
Focuses on:
- Cross-environment consistency (dev/staging/prod)
- Route, service, and ingress correctness
- Operational safety (resource limits, probes, rollout strategy)
- Config validation and drift
- Secret handling and reference correctness
Supporting Agents
Context Explorer (code-review-context-explorer)
Runs before the specialized reviewers to gather architectural context — established patterns, related modules, and call sites — so each agent can review the diff against the surrounding codebase rather than in isolation.
Finding Validator (finding-validator)
Adversarial pass that takes blocking findings and attempts to disprove them, surfacing the strongest counter-argument so theoretical or false-positive findings are filtered out before they reach the author.
Voice (code-reviewer-voice)
Final pass that rewrites comment bodies in a plain, conversational voice. Preserves every citation, file path, line number, identifier, number, and code block exactly — only the phrasing changes.
Context System
Review-code automatically loads context based on your code:
Language Context
Detects languages in your changes and loads language-specific guidelines:
- Python, TypeScript, Rust, SQL, Bash, Go, Ruby, Elixir, C#, Java, PHP, Swift, Kotlin, Dart
Framework Context
Detects frameworks and loads framework-specific patterns:
- Django, React, Kea, Node.js, ASP.NET Core, Flutter, React Native, iOS, Android
Organization Context
If your repo belongs to a known organization, loads org-specific patterns. You can add your own organization context in context/orgs/{org-name}/org.md.
See Customization Guide for details.
Repository Context
Loads repo-specific workflows and requirements. Add your own in context/orgs/{org-name}/repos/{repo-name}.md.
Configuration
Review Output Path
Reviews are saved to a configurable location. The default is ~/dev/ai/reviews/{org}/{repo}/{pr-number-or-branch}.md.
To change the path, edit ~/.claude/skills/review-code/.env:
REVIEW_ROOT_PATH="$HOME/my-custom-path/reviews"
The directory structure will be created automatically:
~/my-custom-path/reviews/
├── org-name/
│ ├── repo-name/
│ │ ├── pr-123.md
│ │ ├── pr-456.md
│ │ └── feature-branch.md
Testing
The review-code shell scripts have automated test coverage using BATS.
Run all tests:
bin/test
Run specific test file:
bats tests/unit/test-pre-review-context.bats
Current test coverage: Over 40 unit test files plus an end-to-end integration suite cover the shell scripts that power the skill — diff generation and filtering, language/framework detection, PR context fetching, worktree provisioning, draft-review submission, comment-drift detection, the learning loop, and more.
See tests/README.md for detailed testing documentation.
Token Optimizations
The review system includes several optimizations to reduce token usage by 40-60%:
- Diff Compression: Uses minimal context lines (1 instead of 3) - agents can read full files if needed
- Smart Context Loading: Only loads context for detected languages/frameworks
- Bash Heavy Lifting: Shell scripts handle diff generation, parsing, and context gathering
Environment Variables:
DIFF_CONTEXT_LINES- Override diff context lines (default: 1)
Output Format
Reviews are saved as structured Markdown with:
- Summary of findings by severity
- Confidence scores for each finding (20-100%)
- Detailed findings with file locations
- Code snippets showing issues
- Specific recommendations
- Links to relevant documentation
Example:
# Code Review: PR #123
## Summary
🔴 **2 Critical Issues**
🟡 **5 Moderate Issues**
🟢 **3 Minor Improvements**
## Security Review
### 🔴 Critical: SQL Injection Vulnerability [95% confidence]
**Location**: auth.py:45
**Issue**: User input directly interpolated into SQL query
...
Uninstallation
To remove review-code:
~/.claude/bin/uninstall-review-code.sh
Or if you have the repo cloned:
cd ~/dev/haacked/review-code
./uninstall.sh
This removes:
- Command and agent files from
~/.claude/ - Helper scripts from
~/.claude/bin/ - Optionally removes context files and config (you'll be asked)
- Optionally removes old
~/.review-code/directory if found
Your review files are preserved unless you explicitly choose to remove the context directory.
Troubleshooting
"Command not found" errors
- Ensure gh CLI is installed:
brew install gh - Ensure jq is installed:
brew install jq - Run the installer again to verify setup
"Missing helper scripts" error
- Ensure you've cloned the full repository
- Check that
bin/directory contains the helper scripts
Reviews not loading org-specific context
- Check that org name matches directory:
context/orgs/{org-name}/ - Org names are case-insensitive and normalized to lowercase
Config file not being read
- Check file exists:
ls -la ~/.claude/skills/review-code/.env - Check syntax:
cat ~/.claude/skills/review-code/.env - Ensure
REVIEW_ROOT_PATHis set correctly
Documentation
- Customization Guide - Add your own org/repo context
- Standalone Installation Guide - Detailed installation instructions
- DEBUG Mode Guide - Debug and verify review processing
Contributing
Contributions are welcome! Please feel free to submit issues or pull requests.
Adding Context
The most valuable contributions are adding language, framework, and organization-specific context:
- Language context:
context/languages/{language}.md - Framework context:
context/frameworks/{framework}.md - Organization context:
context/orgs/{org-name}/org.md
See the Customization Guide for details.
License
MIT License - see LICENSE.md for details.
Author
Phil Haack (@haacked)