ai-code-reviewer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAI Code Reviewer
AI Code Reviewer
Automated AI-powered code review that runs on git hooks with progressive disclosure design. Reviews staged changes against project-specific rules using Claude AI, blocking or warning about violations before commits.
基于AI的自动化代码审查工具,通过Git钩子运行,采用渐进式披露设计。利用Claude AI根据项目专属规则对暂存的变更进行审查,在提交前阻止违规行为或发出警告。
Key Features
核心特性
- Progressive Disclosure: Loads rule metadata first for fast matching, full details only for applicable rules
- Git Hook Integration: Automatically runs on pre-commit or pre-push
- Project-Level Rules: Each project maintains its own review rules in
.ai-reviewer/rules/ - Smart Matching: Matches rules by keywords and file patterns before full AI review
- Flexible Configuration: Block/warn modes, Claude API or CLI backend
- Token Efficient: Minimizes context usage by loading only relevant rules
- 渐进式披露:先加载规则元数据以快速匹配,仅为适用规则加载完整详情
- Git钩子集成:自动在pre-commit或pre-push阶段运行
- 项目级规则:每个项目在目录下维护专属审查规则
.ai-reviewer/rules/ - 智能匹配:在完整AI审查前,通过关键词和文件模式匹配规则
- 灵活配置:支持阻止/警告模式,可选用Claude API或CLI后端
- 高效Token利用:仅加载相关规则,最大限度减少上下文使用量
Quick Start
快速开始
-
Initialize project structure (if not exists):bash
mkdir -p .ai-reviewer/{rules,hooks} cp <skill-path>/assets/config.yaml .ai-reviewer/ cp <skill-path>/assets/rules/*.md .ai-reviewer/rules/ cp <skill-path>/assets/hooks/*.template .ai-reviewer/hooks/ -
Install git hook:bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit -
Configure AI backend in:
.ai-reviewer/config.yaml- Set and provide
ai_backend: claude-api, ORclaude_api_key - Set (requires Claude CLI installed)
ai_backend: claude-cli
- Set
-
Test the review:bash
# Stage some changes git add . # Run review manually to test python3 <skill-path>/scripts/run_review.py --project-root . # If review passes, commit will proceed normally git commit -m "test commit" -
Skip review when needed:bash
git commit --no-verify -m "message"
-
初始化项目结构(若不存在):bash
mkdir -p .ai-reviewer/{rules,hooks} cp <skill-path>/assets/config.yaml .ai-reviewer/ cp <skill-path>/assets/rules/*.md .ai-reviewer/rules/ cp <skill-path>/assets/hooks/*.template .ai-reviewer/hooks/ -
安装Git钩子:bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit -
在中配置AI后端:
.ai-reviewer/config.yaml- 设置并提供
ai_backend: claude-api,或者claude_api_key - 设置(需已安装Claude CLI)
ai_backend: claude-cli
- 设置
-
测试审查功能:bash
# 暂存一些变更 git add . # 手动运行审查进行测试 python3 <skill-path>/scripts/run_review.py --project-root . # 若审查通过,提交将正常进行 git commit -m "test commit" -
必要时跳过审查:bash
git commit --no-verify -m "message"
Workflow Decision Tree
工作流决策树
User wants to:
│
├─ "Set up AI code review"
│ └─ Go to Initial Setup
│
├─ "Add review rules"
│ └─ Go to Creating Rules
│
├─ "Configure review behavior"
│ └─ Go to Configuration
│
├─ "Install/uninstall hooks"
│ └─ Go to Managing Git Hooks
│
├─ "Debug review issues"
│ └─ Go to Troubleshooting
│
└─ "Review staged changes manually"
└─ Run: python3 <skill-path>/scripts/run_review.py --project-root .用户需求:
│
├─ "设置AI代码审查"
│ └─ 进入初始设置
│
├─ "添加审查规则"
│ └─ 进入规则创建
│
├─ "配置审查行为"
│ └─ 进入配置环节
│
├─ "安装/卸载钩子"
│ └─ 进入Git钩子管理
│
├─ "调试审查问题"
│ └─ 进入故障排查
│
└─ "手动审查暂存变更"
└─ 执行:python3 <skill-path>/scripts/run_review.py --project-root .Initial Setup
初始设置
Step 1: Create Project Structure
步骤1:创建项目结构
The reviewer requires this structure:
project-root/
└── .ai-reviewer/
├── config.yaml # Configuration
├── rules/ # Review rules
│ ├── rule1.md
│ └── rule2.md
└── hooks/ # Git hook templates
├── pre-commit.template
└── pre-push.templateCopy from skill assets:
bash
undefined本审查工具需要以下目录结构:
project-root/
└── .ai-reviewer/
├── config.yaml # 配置文件
├── rules/ # 审查规则
│ ├── rule1.md
│ └── rule2.md
└── hooks/ # Git钩子模板
├── pre-commit.template
└── pre-push.template从技能资源中复制文件:
bash
undefinedCreate directories
创建目录
mkdir -p .ai-reviewer/{rules,hooks}
mkdir -p .ai-reviewer/{rules,hooks}
Copy example config
复制示例配置
cp <skill-path>/assets/config.yaml .ai-reviewer/
cp <skill-path>/assets/config.yaml .ai-reviewer/
Copy example rules
复制示例规则
cp <skill-path>/assets/rules/*.md .ai-reviewer/rules/
cp <skill-path>/assets/rules/*.md .ai-reviewer/rules/
Copy hook templates
复制钩子模板
cp <skill-path>/assets/hooks/*.template .ai-reviewer/hooks/
undefinedcp <skill-path>/assets/hooks/*.template .ai-reviewer/hooks/
undefinedStep 2: Configure Reviewer
步骤2:配置审查工具
Edit :
.ai-reviewer/config.yamlFor Claude API (recommended):
yaml
review_mode: block
ai_backend: claude-api
claude_api_key: "sk-ant-api03-..." # Or use ANTHROPIC_API_KEY env var
model: claude-sonnet-4-5-20250929For Claude CLI:
yaml
review_mode: block
ai_backend: claude-cliSee Configuration Reference for all options.
编辑:
.ai-reviewer/config.yaml使用Claude API(推荐):
yaml
review_mode: block
ai_backend: claude-api
claude_api_key: "sk-ant-api03-..." # 或使用ANTHROPIC_API_KEY环境变量
model: claude-sonnet-4-5-20250929使用Claude CLI:
yaml
review_mode: block
ai_backend: claude-cli查看配置参考获取所有选项。
Step 3: Install Git Hooks
步骤3:安装Git钩子
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commitOr for pre-push:
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-pushbash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit或者安装pre-push钩子:
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-pushStep 4: Verify Installation
步骤4:验证安装
bash
undefinedbash
undefinedRun manual review
运行手动审查
python3 <skill-path>/scripts/run_review.py --project-root .
python3 <skill-path>/scripts/run_review.py --project-root .
If successful, try a commit
若成功,尝试提交
git add .
git commit -m "test commit"
undefinedgit add .
git commit -m "test commit"
undefinedCreating Rules
创建规则
Rule File Format
规则文件格式
Rules are Markdown files with YAML frontmatter. See for complete specification.
references/rule_format.mdBasic structure:
yaml
---
id: unique-rule-id
keywords: ["keyword1", "keyword2"]
file_patterns: ["*.py", "src/**/*.js"]
priority: high | medium | low
description: Brief one-line description
---规则为带有YAML前置元数据的Markdown文件。完整规范请参考。
references/rule_format.md基本结构:
yaml
---
id: unique-rule-id
keywords: ["keyword1", "keyword2"]
file_patterns: ["*.py", "src/**/*.js"]
priority: high | medium | low
description: 简短的单行描述
---Rule Title
规则标题
Specification
规范说明
Detailed explanation...
详细解释...
Checklist
检查清单
- Check item 1
- Check item 2
- 检查项1
- 检查项2
Positive Examples
正面示例
python
undefinedpython
undefinedGood code
良好代码
undefinedundefinedNegative Examples
反面示例
python
undefinedpython
undefinedBad code
不良代码
undefinedundefinedRule Matching Logic
规则匹配逻辑
A rule triggers if either condition is met:
- File pattern match: Changed file matches a pattern in
file_patterns - Keyword match: Keyword appears in diff content
Both use OR logic - either triggers the rule.
满足以下任一条件时触发规则:
- 文件模式匹配:变更的文件与中的某一模式匹配
file_patterns - 关键词匹配:关键词出现在差异内容中
两者为或逻辑 - 满足任一条件即触发规则。
Creating a New Rule
创建新规则
- Create
.ai-reviewer/rules/your-rule.md - Add frontmatter with ,
id,keywords,file_patterns,prioritydescription - Add sections: ,
SpecificationChecklist - Optionally add: ,
Positive ExamplesNegative Examples - Test by running review on sample code
Example:
yaml
---
id: no-todo-comments
keywords: ["TODO", "FIXME", "HACK"]
file_patterns: ["*.py", "*.js", "*.ts"]
priority: medium
description: No TODO comments in production code
---- 创建
.ai-reviewer/rules/your-rule.md - 添加包含、
id、keywords、file_patterns、priority的前置元数据description - 添加、
规范说明章节检查清单 - 可选添加、
正面示例章节反面示例 - 通过对示例代码运行审查进行测试
示例:
yaml
---
id: no-todo-comments
keywords: ["TODO", "FIXME", "HACK"]
file_patterns: ["*.py", "*.js", "*.ts"]
priority: medium
description: 生产代码中不允许出现TODO注释
---No TODO Comments
禁止TODO注释
Specification
规范说明
TODO comments should not be committed. Fix the issue or create a ticket.
不应提交TODO注释。请修复问题或创建工单。
Checklist
检查清单
- No TODO comments present
- No FIXME comments present
- No HACK comments present
- 无TODO注释
- 无FIXME注释
- 无HACK注释
Negative Examples
反面示例
python
undefinedpython
undefinedTODO: Refactor this later
TODO: 后续重构此部分
def bad_example():
pass
undefineddef bad_example():
pass
undefinedConfiguration
配置
Review Modes
审查模式
Block mode (strict):
yaml
review_mode: blockBlocks commit if violations found. Use to bypass.
--no-verifyWarn mode (permissive):
yaml
review_mode: warnShows warnings but allows commit.
Advisory mode (informational):
yaml
review_mode: advisoryRuns review but never blocks.
阻止模式(严格):
yaml
review_mode: block若发现违规则阻止提交。使用绕过。
--no-verify警告模式(宽松):
yaml
review_mode: warn显示警告但允许提交。
建议模式(信息性):
yaml
review_mode: advisory运行审查但从不阻止提交。
AI Backend
AI后端
Claude API (recommended, faster):
yaml
ai_backend: claude-api
claude_api_key: "sk-ant-api03-..."
model: claude-sonnet-4-5-20250929
max_tokens: 4096Requires API key. Set via config or env var.
ANTHROPIC_API_KEYClaude CLI (slower, no API key needed):
yaml
ai_backend: claude-cliRequires:
npm install -g @anthropic-ai/claude-cliClaude API(推荐,速度更快):
yaml
ai_backend: claude-api
claude_api_key: "sk-ant-api03-..."
model: claude-sonnet-4-5-20250929
max_tokens: 4096需要API密钥。可通过配置文件或环境变量设置。
ANTHROPIC_API_KEYClaude CLI(速度较慢,无需API密钥):
yaml
ai_backend: claude-cli需先安装:
npm install -g @anthropic-ai/claude-cliSkip Patterns
跳过模式
Exclude generated/vendor files:
yaml
skip_patterns:
- "*.min.js"
- "vendor/**"
- "node_modules/**"
- "*.pb.go"See for complete configuration reference.
references/config_format.md排除生成文件/第三方库文件:
yaml
skip_patterns:
- "*.min.js"
- "vendor/**"
- "node_modules/**"
- "*.pb.go"完整配置参考请见。
references/config_format.mdManaging Git Hooks
管理Git钩子
Install Hook
安装钩子
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commitbash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commitUninstall Hook
卸载钩子
bash
python3 <skill-path>/scripts/install_hook.py uninstall --hook-type pre-commitbash
python3 <skill-path>/scripts/install_hook.py uninstall --hook-type pre-commitList Installed Hooks
列出已安装的钩子
bash
ls -la .git/hooks/bash
ls -la .git/hooks/Hook Location
钩子位置
Hooks are installed to or .
.git/hooks/pre-commit.git/hooks/pre-pushThe hooks automatically find the directory by searching upward from the current directory.
.ai-reviewer钩子安装在或。
.git/hooks/pre-commit.git/hooks/pre-push钩子会自动从当前目录向上搜索目录。
.ai-reviewerRunning Reviews Manually
手动运行审查
Review Staged Changes
审查暂存变更
bash
python3 <skill-path>/scripts/run_review.py --project-root .bash
python3 <skill-path>/scripts/run_review.py --project-root .Test Rule Matching
测试规则匹配
bash
python3 <skill-path>/scripts/load_rules.py .ai-reviewer/rulesLists all rule metadata without running full review.
bash
python3 <skill-path>/scripts/load_rules.py .ai-reviewer/rules列出所有规则元数据,不运行完整审查。
Troubleshooting
故障排查
Review Not Running
审查未运行
Check hook installation:
bash
ls -la .git/hooks/pre-commitCheck hook is executable:
bash
chmod +x .git/hooks/pre-commitCheck .ai-reviewer directory exists:
bash
ls -la .ai-reviewer/检查钩子安装情况:
bash
ls -la .git/hooks/pre-commit检查钩子是否可执行:
bash
chmod +x .git/hooks/pre-commit检查目录是否存在:
.ai-reviewerbash
ls -la .ai-reviewer/API Errors
API错误
Missing API key:
bash
export ANTHROPIC_API_KEY=sk-ant-api03-...Or set in .
config.yamlQuota exceeded: Use instead.
ai_backend: claude-cli缺少API密钥:
bash
export ANTHROPIC_API_KEY=sk-ant-api03-...或在中设置。
config.yaml配额耗尽: 改用。
ai_backend: claude-cliRules Not Matching
规则未匹配
Test metadata loading:
bash
python3 <skill-path>/scripts/load_rules.py .ai-reviewer/rulesCheck keywords and patterns:
- Keywords are case-insensitive
- File patterns use glob syntax (e.g., ,
*.py)src/**/*.js - Empty arrays skip that check
测试元数据加载:
bash
python3 <skill-path>/scripts/load_rules.py .ai-reviewer/rules检查关键词和模式:
- 关键词不区分大小写
- 文件模式使用glob语法(如,
*.py)src/**/*.js - 空数组会跳过对应检查
Large Diffs Skipped
大差异被跳过
If diff exceeds , review is skipped. Increase limit:
max_diff_sizeyaml
max_diff_size: 50000若差异超过,审查会被跳过。可增大限制:
max_diff_sizeyaml
max_diff_size: 50000Silent Failures
静默失败
Enable debug logging:
yaml
log_level: debug
log_file: .ai-reviewer/review.logCheck the log file for detailed error messages.
启用调试日志:
yaml
log_level: debug
log_file: .ai-reviewer/review.log查看日志文件获取详细错误信息。
Progressive Disclosure Design
渐进式披露设计
This skill uses a two-stage loading pattern for token efficiency:
本技能采用两阶段加载模式以提升Token使用效率:
Stage 1: Metadata Loading
阶段1:元数据加载
Loads only frontmatter from all rules:
- ,
id,keywords,file_patterns,prioritydescription - Fast operation, minimal token usage
- Stored in as
load_rules.pyRuleMetadata
仅加载所有规则的前置元数据:
- ,
id,keywords,file_patterns,prioritydescription - 操作快速,Token使用量极少
- 以形式存储在
RuleMetadata中load_rules.py
Stage 2: Rule Matching
阶段2:规则匹配
Matches rules against diff using only metadata:
- Keyword matching against diff content
- File pattern matching against changed files
- Returns only potentially applicable rules
仅使用元数据将规则与差异进行匹配:
- 针对差异内容的关键词匹配
- 针对变更文件的文件模式匹配
- 仅返回可能适用的规则
Stage 3: Full Rule Loading
阶段3:完整规则加载
Loads complete rule details only for matched rules:
- Specification, checklist, examples
- Passed to AI for detailed review
- Minimizes tokens sent to AI
Benefits:
- Scales to hundreds of rules
- Fast initial filtering
- AI receives only relevant context
- Efficient token usage
仅为匹配到的规则加载完整详情:
- 规范说明、检查清单、示例
- 传递给AI进行详细审查
- 最小化发送给AI的Token数量
优势:
- 可扩展至数百条规则
- 快速初始过滤
- AI仅接收相关上下文
- 高效的Token使用
Resources
资源
scripts/
scripts/
-
install_hook.py: Install/uninstall git hooksbash
python3 scripts/install_hook.py install --hook-type pre-commit -
run_review.py: Main review workflowbash
python3 scripts/run_review.py --project-root . -
load_rules.py: Progressive rule loading and matchingpython
from load_rules import RuleLoader, RuleMetadata, FullRule
-
install_hook.py: 安装/卸载Git钩子bash
python3 scripts/install_hook.py install --hook-type pre-commit -
run_review.py: 主审查工作流bash
python3 scripts/run_review.py --project-root . -
load_rules.py: 渐进式规则加载与匹配python
from load_rules import RuleLoader, RuleMetadata, FullRule
references/
references/
-
rule_format.md: Complete rule file specification
- Frontmatter fields
- Body sections
- Matching logic
- Best practices
-
config_format.md: Complete configuration reference
- All config fields
- Review modes
- AI backends
- Environment variables
-
rule_format.md: 完整规则文件规范
- 前置元数据字段
- 正文章节
- 匹配逻辑
- 最佳实践
-
config_format.md: 完整配置参考
- 所有配置字段
- 审查模式
- AI后端
- 环境变量
assets/
assets/
- config.yaml: Configuration file template
- rules/: Example rules
- : Proper exception handling
error-handling.md - : PEP 8 naming conventions
naming-convention.md
- hooks/: Git hook templates
pre-commit.templatepre-push.template
- config.yaml: 配置文件模板
- rules/: 示例规则
- : 正确的异常处理
error-handling.md - : PEP 8命名规范
naming-convention.md
- hooks/: Git钩子模板
pre-commit.templatepre-push.template
Best Practices
最佳实践
- Start Small: Begin with 2-3 core rules, expand gradually
- Specific Keywords: Choose unique keywords that indicate the rule's concern
- Real Examples: Use examples from your actual codebase
- Block Mode: Use for strict enforcement
review_mode: block - Team Adoption: Discuss rules with team, get consensus
- Rule Priority: Mark critical rules as
priority: high - Regular Updates: Review and update rules as codebase evolves
- Token Limits: Monitor AI usage, adjust if needed
max_tokens
- 从小规模开始:先从2-3条核心规则入手,逐步扩展
- 使用特定关键词:选择能明确体现规则关注点的独特关键词
- 使用真实示例:采用代码库中的实际示例
- 使用阻止模式:使用进行严格执行
review_mode: block - 团队共识:与团队讨论规则,达成一致
- 设置规则优先级:将关键规则标记为
priority: high - 定期更新规则:随着代码库演进,审查并更新规则
- 关注Token限制:监控AI使用情况,必要时调整
max_tokens
Advanced Usage
高级用法
Custom Rule Categories
自定义规则分类
Organize rules by category using ID prefixes:
yaml
id: security-001
id: style-001
id: performance-001通过ID前缀按类别组织规则:
yaml
id: security-001
id: style-001
id: performance-001Rule-Specific Prompts
规则专属提示词
Add custom AI instructions in specification:
markdown
undefined在规范说明中添加自定义AI指令:
markdown
undefinedSpecification
规范说明
When reviewing this rule, pay special attention to edge cases involving...
undefined审查此规则时,请特别关注涉及...的边缘情况
undefinedMulti-Language Projects
多语言项目
Use file patterns to target specific languages:
yaml
file_patterns: ["*.py"] # Python only
file_patterns: ["*.js", "*.ts"] # JavaScript/TypeScript
file_patterns: ["*"] # All files使用文件模式针对特定语言:
yaml
file_patterns: ["*.py"] # 仅Python
file_patterns: ["*.js", "*.ts"] # JavaScript/TypeScript
file_patterns: ["*"] # 所有文件CI/CD Integration
CI/CD集成
Add to CI pipeline:
yaml
- name: AI Code Review
run: python3 scripts/run_review.py --project-root .添加到CI流水线:
yaml
- name: AI Code Review
run: python3 scripts/run_review.py --project-root .Limitations
局限性
- Requires Python 3.7+
- Git hooks run in project root context
- Large diffs (>10k chars) are skipped by default
- Claude API has rate limits (use CLI for unlimited reviews)
- Rules use keyword/pattern matching (not AST-based)
- 需要Python 3.7+
- Git钩子在项目根目录上下文运行
- 默认跳过大型差异(>10k字符)
- Claude API有速率限制(使用CLI可进行无限制审查)
- 规则使用关键词/模式匹配(而非基于AST)