ai-code-reviewer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI 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

快速开始

  1. 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/
  2. Install git hook:
    bash
    python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit
  3. Configure AI backend in
    .ai-reviewer/config.yaml
    :
    • Set
      ai_backend: claude-api
      and provide
      claude_api_key
      , OR
    • Set
      ai_backend: claude-cli
      (requires Claude CLI installed)
  4. 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"
  5. Skip review when needed:
    bash
    git commit --no-verify -m "message"
  1. 初始化项目结构(若不存在):
    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/
  2. 安装Git钩子
    bash
    python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit
  3. .ai-reviewer/config.yaml
    中配置AI后端
    • 设置
      ai_backend: claude-api
      并提供
      claude_api_key
      ,或者
    • 设置
      ai_backend: claude-cli
      (需已安装Claude CLI)
  4. 测试审查功能
    bash
    # 暂存一些变更
    git add .
    
    # 手动运行审查进行测试
    python3 <skill-path>/scripts/run_review.py --project-root .
    
    # 若审查通过,提交将正常进行
    git commit -m "test commit"
  5. 必要时跳过审查
    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.template
Copy 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
undefined

Create 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/
undefined
cp <skill-path>/assets/hooks/*.template .ai-reviewer/hooks/
undefined

Step 2: Configure Reviewer

步骤2:配置审查工具

Edit
.ai-reviewer/config.yaml
:
For 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-20250929
For Claude CLI:
yaml
review_mode: block
ai_backend: claude-cli
See 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-commit
Or for pre-push:
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-push
bash
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-push

Step 4: Verify Installation

步骤4:验证安装

bash
undefined
bash
undefined

Run 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"
undefined
git add . git commit -m "test commit"
undefined

Creating Rules

创建规则

Rule File Format

规则文件格式

Rules are Markdown files with YAML frontmatter. See
references/rule_format.md
for complete specification.
Basic 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
undefined
python
undefined

Good code

良好代码

undefined
undefined

Negative Examples

反面示例

python
undefined
python
undefined

Bad code

不良代码

undefined
undefined

Rule Matching Logic

规则匹配逻辑

A rule triggers if either condition is met:
  1. File pattern match: Changed file matches a pattern in
    file_patterns
  2. Keyword match: Keyword appears in diff content
Both use OR logic - either triggers the rule.
满足以下任一条件时触发规则:
  1. 文件模式匹配:变更的文件与
    file_patterns
    中的某一模式匹配
  2. 关键词匹配:关键词出现在差异内容中
两者为或逻辑 - 满足任一条件即触发规则。

Creating a New Rule

创建新规则

  1. Create
    .ai-reviewer/rules/your-rule.md
  2. Add frontmatter with
    id
    ,
    keywords
    ,
    file_patterns
    ,
    priority
    ,
    description
  3. Add sections:
    Specification
    ,
    Checklist
  4. Optionally add:
    Positive Examples
    ,
    Negative Examples
  5. 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
---
  1. 创建
    .ai-reviewer/rules/your-rule.md
  2. 添加包含
    id
    keywords
    file_patterns
    priority
    description
    的前置元数据
  3. 添加
    规范说明
    检查清单
    章节
  4. 可选添加
    正面示例
    反面示例
    章节
  5. 通过对示例代码运行审查进行测试
示例:
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
undefined
python
undefined

TODO: Refactor this later

TODO: 后续重构此部分

def bad_example(): pass
undefined
def bad_example(): pass
undefined

Configuration

配置

Review Modes

审查模式

Block mode (strict):
yaml
review_mode: block
Blocks commit if violations found. Use
--no-verify
to bypass.
Warn mode (permissive):
yaml
review_mode: warn
Shows warnings but allows commit.
Advisory mode (informational):
yaml
review_mode: advisory
Runs 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: 4096
Requires API key. Set via config or
ANTHROPIC_API_KEY
env var.
Claude CLI (slower, no API key needed):
yaml
ai_backend: claude-cli
Requires:
npm install -g @anthropic-ai/claude-cli
Claude API(推荐,速度更快):
yaml
ai_backend: claude-api
claude_api_key: "sk-ant-api03-..."
model: claude-sonnet-4-5-20250929
max_tokens: 4096
需要API密钥。可通过配置文件或
ANTHROPIC_API_KEY
环境变量设置。
Claude CLI(速度较慢,无需API密钥):
yaml
ai_backend: claude-cli
需先安装:
npm install -g @anthropic-ai/claude-cli

Skip Patterns

跳过模式

Exclude generated/vendor files:
yaml
skip_patterns:
  - "*.min.js"
  - "vendor/**"
  - "node_modules/**"
  - "*.pb.go"
See
references/config_format.md
for complete configuration reference.
排除生成文件/第三方库文件:
yaml
skip_patterns:
  - "*.min.js"
  - "vendor/**"
  - "node_modules/**"
  - "*.pb.go"
完整配置参考请见
references/config_format.md

Managing Git Hooks

管理Git钩子

Install Hook

安装钩子

bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit
bash
python3 <skill-path>/scripts/install_hook.py install --hook-type pre-commit

Uninstall Hook

卸载钩子

bash
python3 <skill-path>/scripts/install_hook.py uninstall --hook-type pre-commit
bash
python3 <skill-path>/scripts/install_hook.py uninstall --hook-type pre-commit

List Installed Hooks

列出已安装的钩子

bash
ls -la .git/hooks/
bash
ls -la .git/hooks/

Hook Location

钩子位置

Hooks are installed to
.git/hooks/pre-commit
or
.git/hooks/pre-push
.
The hooks automatically find the
.ai-reviewer
directory by searching upward from the current directory.
钩子安装在
.git/hooks/pre-commit
.git/hooks/pre-push
钩子会自动从当前目录向上搜索
.ai-reviewer
目录。

Running 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/rules
Lists 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-commit
Check hook is executable:
bash
chmod +x .git/hooks/pre-commit
Check .ai-reviewer directory exists:
bash
ls -la .ai-reviewer/
检查钩子安装情况:
bash
ls -la .git/hooks/pre-commit
检查钩子是否可执行:
bash
chmod +x .git/hooks/pre-commit
检查
.ai-reviewer
目录是否存在:
bash
ls -la .ai-reviewer/

API Errors

API错误

Missing API key:
bash
export ANTHROPIC_API_KEY=sk-ant-api03-...
Or set in
config.yaml
.
Quota exceeded: Use
ai_backend: claude-cli
instead.
缺少API密钥:
bash
export ANTHROPIC_API_KEY=sk-ant-api03-...
或在
config.yaml
中设置。
配额耗尽: 改用
ai_backend: claude-cli

Rules Not Matching

规则未匹配

Test metadata loading:
bash
python3 <skill-path>/scripts/load_rules.py .ai-reviewer/rules
Check 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
max_diff_size
, review is skipped. Increase limit:
yaml
max_diff_size: 50000
若差异超过
max_diff_size
,审查会被跳过。可增大限制:
yaml
max_diff_size: 50000

Silent Failures

静默失败

Enable debug logging:
yaml
log_level: debug
log_file: .ai-reviewer/review.log
Check 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
    ,
    priority
    ,
    description
  • Fast operation, minimal token usage
  • Stored in
    load_rules.py
    as
    RuleMetadata
仅加载所有规则的前置元数据:
  • id
    ,
    keywords
    ,
    file_patterns
    ,
    priority
    ,
    description
  • 操作快速,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 hooks
    bash
    python3 scripts/install_hook.py install --hook-type pre-commit
  • run_review.py: Main review workflow
    bash
    python3 scripts/run_review.py --project-root .
  • load_rules.py: Progressive rule loading and matching
    python
    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
    • error-handling.md
      : Proper exception handling
    • naming-convention.md
      : PEP 8 naming conventions
  • hooks/: Git hook templates
    • pre-commit.template
    • pre-push.template
  • config.yaml: 配置文件模板
  • rules/: 示例规则
    • error-handling.md
      : 正确的异常处理
    • naming-convention.md
      : PEP 8命名规范
  • hooks/: Git钩子模板
    • pre-commit.template
    • pre-push.template

Best Practices

最佳实践

  1. Start Small: Begin with 2-3 core rules, expand gradually
  2. Specific Keywords: Choose unique keywords that indicate the rule's concern
  3. Real Examples: Use examples from your actual codebase
  4. Block Mode: Use
    review_mode: block
    for strict enforcement
  5. Team Adoption: Discuss rules with team, get consensus
  6. Rule Priority: Mark critical rules as
    priority: high
  7. Regular Updates: Review and update rules as codebase evolves
  8. Token Limits: Monitor AI usage, adjust
    max_tokens
    if needed
  1. 从小规模开始:先从2-3条核心规则入手,逐步扩展
  2. 使用特定关键词:选择能明确体现规则关注点的独特关键词
  3. 使用真实示例:采用代码库中的实际示例
  4. 使用阻止模式:使用
    review_mode: block
    进行严格执行
  5. 团队共识:与团队讨论规则,达成一致
  6. 设置规则优先级:将关键规则标记为
    priority: high
  7. 定期更新规则:随着代码库演进,审查并更新规则
  8. 关注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-001

Rule-Specific Prompts

规则专属提示词

Add custom AI instructions in specification:
markdown
undefined
在规范说明中添加自定义AI指令:
markdown
undefined

Specification

规范说明

When reviewing this rule, pay special attention to edge cases involving...
undefined
审查此规则时,请特别关注涉及...的边缘情况
undefined

Multi-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)