mcpField
G
github-code-review

github-code-review

github.com/ruvnet测试与质量80.0k1.3k 次安装今天更新
代码仓库

关于 github-code-review

github-code-review 是一项用于协调多个 AI Agent 审查 GitHub 拉取请求的技能,覆盖安全、性能、架构和代码风格。它利用 PR 上下文,并支持评论、质量检查及 CI 自动化工作流。

主要功能

  1. 01多个专业 Agent 并行审查
  2. 02安全、性能和架构检查
  3. 03基于 PR 配置和分配 swarm
  4. 04生成上下文相关的审查评论
  5. 05质量门禁与 CI 工作流

适用场景

  1. 01审查涉及安全的拉取请求
  2. 02检查性能与设计变更
  3. 03在 CI/CD 中自动执行审查步骤
  4. 04协调相关 PR 的联合审查

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ruvnet/ruflo --skill github-code-review

安装后在 Claude Code 中输入/github-code-review确认已加载。

详细介绍

GitHub 代码审查技能

AI 驱动的代码审查:部署专用审查 Agent,执行全面、智能的代码审查,超越传统静态分析。

🎯 快速入门

简单审查
# Initialize review swarm for PR
gh pr view 123 --json files,diff | npx ruv-swarm github review-init --pr 123

# Post review status
gh pr comment 123 --body "🔍 Multi-agent code review initiated"
完整审查工作流
# Get PR context with gh CLI
PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body)
PR_DIFF=$(gh pr diff 123)

# Initialize comprehensive review
npx ruv-swarm github review-init \
  --pr 123 \
  --pr-data "$PR_DATA" \
  --diff "$PR_DIFF" \
  --agents "security,performance,style,architecture,accessibility" \
  --depth comprehensive

📚 目录

核心功能<$strong><$summary>

<$details>

审查 Agent<$strong><$summary>

<$details>

高级功能<$strong><$summary>

<$details>

集成与自动化<$strong><$summary>

<$details>


🚀 核心功能

多 Agent 审查系统

部署专用 AI Agent,执行全面的代码审查:

# Initialize review swarm with GitHub CLI integration
PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body)
PR_DIFF=$(gh pr diff 123)

# Start multi-agent review
npx ruv-swarm github review-init \
  --pr 123 \
  --pr-data "$PR_DATA" \
  --diff "$PR_DIFF" \
  --agents "security,performance,style,architecture,accessibility" \
  --depth comprehensive

# Post initial review status
gh pr comment 123 --body "🔍 Multi-agent code review initiated"

优势:

  • ✅ 专用 Agent 并行审查
  • ✅ 全面覆盖多个领域
  • ✅ 通过协同分析加快审查周期
  • ✅ 强制执行一致的质量标准

🤖 专用审查 Agent

安全审查 Agent

**重点:**识别安全漏洞并提出修复建议

# Get changed files from PR
CHANGED_FILES=$(gh pr view 123 --json files --jq '.files[].path')

# Run security-focused review
SECURITY_RESULTS=$(npx ruv-swarm github review-security \
  --pr 123 \
  --files "$CHANGED_FILES" \
  --check "owasp,cve,secrets,permissions" \
  --suggest-fixes)

# Post findings based on severity
if echo "$SECURITY_RESULTS" | grep -q "critical"; then
  # Request changes for critical issues
  gh pr review 123 --request-changes --body "$SECURITY_RESULTS"
  gh pr edit 123 --add-label "security-review-required"
else
  # Post as comment for non-critical issues
  gh pr comment 123 --body "$SECURITY_RESULTS"
fi
执行的安全检查<$strong><$summary>
{
  "checks": [
    "SQL injection vulnerabilities",
    "XSS attack vectors",
    "Authentication bypasses",
    "Authorization flaws",
    "Cryptographic weaknesses",
    "Dependency vulnerabilities",
    "Secret exposure",
    "CORS misconfigurations"
  ],
  "actions": [
    "Block PR on critical issues",
    "Suggest secure alternatives",
    "Add security test cases",
    "Update security documentation"
  ]
}

<$details>

评论模板:安全问题<$strong><$summary>
🔒 **Security Issue: [Type]**

**Severity**: 🔴 Critical / 🟡 High / 🟢 Low

**Description**:
[Clear explanation of the security issue]

**Impact**:
[Potential consequences if not addressed]

**Suggested Fix**:
```language
[Code example of the fix]

参考资料:


<$details>

---

### Performance Review Agent

**Focus:** Analyze performance impact and optimization opportunities

```bash
# Run performance analysis
npx ruv-swarm github review-performance \
  --pr 123 \
  --profile "cpu,memory,io" \
  --benchmark-against main \
  --suggest-optimizations
分析的性能指标<$strong><$summary>
{
  "metrics": [
    "Algorithm complexity (Big O analysis)",
    "Database query efficiency",
    "Memory allocation patterns",
    "Cache utilization",
    "Network request optimization",
    "Bundle size impact",
    "Render performance"
  ],
  "benchmarks": [
    "Compare with baseline",
    "Load test simulations",
    "Memory leak detection",
    "Bottleneck identification"
  ]
}

<$details>


架构审查 Agent

**重点:**评估设计模式和架构决策

# Architecture review
npx ruv-swarm github review-architecture \
  --pr 123 \
  --check "patterns,coupling,cohesion,solid" \
  --visualize-impact \
  --suggest-refactoring
架构分析<$strong><$summary>
{
  "patterns": [
    "Design pattern adherence",
    "SOLID principles",
    "DRY violations",
    "Separation of concerns",
    "Dependency injection",
    "Layer violations",
    "Circular dependencies"
  ],
  "metrics": [
    "Coupling metrics",
    "Cohesion scores",
    "Complexity measures",
    "Maintainability index"
  ]
}

<$details>


风格与规范 Agent

**重点:**执行编码标准和最佳实践

# Style enforcement with auto-fix
npx ruv-swarm github review-style \
  --pr 123 \
  --check "formatting,naming,docs,tests" \
  --auto-fix "formatting,imports,whitespace"
风格检查<$strong><$summary>
{
  "checks": [
    "Code formatting",
    "Naming conventions",
    "Documentation standards",
    "Comment quality",
    "Test coverage",
    "Error handling patterns",
    "Logging standards"
  ],
  "auto-fix": [
    "Formatting issues",
    "Import organization",
    "Trailing whitespace",
    "Simple naming issues"
  ]
}

<$details>


🔄 基于 PR 的集群管理

从 PR 创建集群
# Create swarm from PR description using gh CLI
gh pr view 123 --json body,title,labels,files | npx ruv-swarm swarm create-from-pr

# Auto-spawn agents based on PR labels
gh pr view 123 --json labels | npx ruv-swarm swarm auto-spawn

# Create swarm with full PR context
gh pr view 123 --json body,labels,author,assignees | \
  npx ruv-swarm swarm init --from-pr-data
基于标签分配 Agent

将 PR 标签映射到专用 Agent:

{
  "label-mapping": {
    "bug": ["debugger", "tester"],
    "feature": ["architect", "coder", "tester"],
    "refactor": ["analyst", "coder"],
    "docs": ["researcher", "writer"],
    "performance": ["analyst", "optimizer"],
    "security": ["security", "authentication", "audit"]
  }
}
根据 PR 大小选择拓扑
# Automatic topology selection based on PR complexity
# Small PR (< 100 lines): ring topology
# Medium PR (100-500 lines): mesh topology
# Large PR (> 500 lines): hierarchical topology
npx ruv-swarm github pr-topology --pr 123

🎬 PR 评论命令

直接从 PR 评论中执行集群命令:


$swarm init mesh 6
$swarm spawn coder "Implement authentication"
$swarm spawn tester "Write unit tests"
$swarm status
$swarm review --agents security,performance
评论命令的 Webhook 处理程序<$strong><$summary>
// webhook-handler.js
const { createServer } = require('http');
const { execSync } = require('child_process');

createServer((req, res) => {
  if (req.url === '$github-webhook') {
    const event = JSON.parse(body);

    if (event.action === 'opened' && event.pull_request) {
      execSync(`npx ruv-swarm github pr-init ${event.pull_request.number}`);
    }

    if (event.comment && event.comment.body.startsWith('$swarm')) {
      const command = event.comment.body;
      execSync(`npx ruv-swarm github handle-comment --pr ${event.issue.number} --command "${command}"`);
    }

    res.writeHead(200);
    res.end('OK');
  }
}).listen(3000);

<$details>


⚙️ 审查配置

配置文件
# .github$review-swarm.yml
version: 1
review:
  auto-trigger: true
  required-agents:
    - security
    - performance
    - style
  optional-agents:
    - architecture
    - accessibility
    - i18n

  thresholds:
    security: block      # Block merge on security issues
    performance: warn    # Warn on performance issues
    style: suggest       # Suggest style improvements

  rules:
    security:
      - no-eval
      - no-hardcoded-secrets
      - proper-auth-checks
      - validate-input
    performance:
      - no-n-plus-one
      - efficient-queries
      - proper-caching
      - optimize-loops
    architecture:
      - max-coupling: 5
      - min-cohesion: 0.7
      - follow-patterns
      - avoid-circular-deps
自定义审查触发条件
{
  "triggers": {
    "high-risk-files": {
      "paths": ["**$auth/**", "**$payment/**", "**$admin/**"],
      "agents": ["security", "architecture"],
      "depth": "comprehensive",
      "require-approval": true
    },
    "performance-critical": {
      "paths": ["**$api/**", "**$database/**", "**$cache/**"],
      "agents": ["performance", "database"],
      "benchmarks": true,
      "regression-threshold": "5%"
    },
    "ui-changes": {
      "paths": ["**$components/**", "**$styles/**", "**$pages/**"],
      "agents": ["accessibility", "style", "i18n"],
      "visual-tests": true,
      "responsive-check": true
    }
  }
}

🤖 自动化工作流

创建 PR 时自动审查
# .github$workflows$auto-review.yml
name: Automated Code Review
on:
  pull_request:
    types: [opened, synchronize]
  issue_comment:
    types: [created]

jobs:
  swarm-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions$checkout@v3
        with:
          fetch-depth: 0

      - name: Setup GitHub CLI
        run: echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token

      - name: Run Review Swarm
        run: |
          # Get PR context with gh CLI
          PR_NUM=${{ github.event.pull_request.number }}
          PR_DATA=$(gh pr view $PR_NUM --json files,title,body,labels)
          PR_DIFF=$(gh pr diff $PR_NUM)

          # Run swarm review
          REVIEW_OUTPUT=$(npx ruv-swarm github review-all \
            --pr $PR_NUM \
            --pr-data "$PR_DATA" \
            --diff "$PR_DIFF" \
            --agents "security,performance,style,architecture")

          # Post review results
          echo "$REVIEW_OUTPUT" | gh pr review $PR_NUM --comment -F -

          # Update PR status
          if echo "$REVIEW_OUTPUT" | grep -q "approved"; then
            gh pr review $PR_NUM --approve
          elif echo "$REVIEW_OUTPUT" | grep -q "changes-requested"; then
            gh pr review $PR_NUM --request-changes -b "See review comments above"
          fi

      - name: Update Labels
        run: |
          # Add labels based on review results
          if echo "$REVIEW_OUTPUT" | grep -q "security"; then
            gh pr edit $PR_NUM --add-label "security-review"
          fi
          if echo "$REVIEW_OUTPUT" | grep -q "performance"; then
            gh pr edit $PR_NUM --add-label "performance-review"
          fi

💬 智能评论生成

生成上下文相关的审查评论
# Get PR diff with context
PR_DIFF=$(gh pr diff 123 --color never)
PR_FILES=$(gh pr view 123 --json files)

# Generate review comments
COMMENTS=$(npx ruv-swarm github review-comment \
  --pr 123 \
  --diff "$PR_DIFF" \
  --files "$PR_FILES" \
  --style "constructive" \
  --include-examples \
  --suggest-fixes)

# Post comments using gh CLI
echo "$COMMENTS" | jq -c '.[]' | while read -r comment; do
  FILE=$(echo "$comment" | jq -r '.path')
  LINE=$(echo "$comment" | jq -r '.line')
  BODY=$(echo "$comment" | jq -r '.body')
  COMMIT_ID=$(gh pr view 123 --json headRefOid -q .headRefOid)

  # Create inline review comments
  gh api \
    --method POST \
    $repos/:owner/:repo$pulls/123$comments \
    -f path="$FILE" \
    -f line="$LINE" \
    -f body="$BODY" \
    -f commit_id="$COMMIT_ID"
done
批量评论管理
# Manage review comments efficiently
npx ruv-swarm github review-comments \
  --pr 123 \
  --group-by "agent,severity" \
  --summarize \
  --resolve-outdated

🚪 质量门禁与检查

状态检查
# Required status checks in branch protection
protection_rules:
  required_status_checks:
    strict: true
    contexts:
      - "review-swarm$security"
      - "review-swarm$performance"
      - "review-swarm$architecture"
      - "review-swarm$tests"
定义质量门禁
# Set quality gate thresholds
npx ruv-swarm github quality-gates \
  --define '{
    "security": {"threshold": "no-critical"},
    "performance": {"regression": "<5%"},
    "coverage": {"minimum": "80%"},
    "architecture": {"complexity": "<10"},
    "duplication": {"maximum": "5%"}
  }'
跟踪审查指标
# Monitor review effectiveness
npx ruv-swarm github review-metrics \
  --period 30d \
  --metrics "issues-found,false-positives,fix-rate,time-to-review" \
  --export-dashboard \
  --format json

🎓 高级功能

上下文感知审查

结合完整的项目上下文分析 PR:

# Review with comprehensive context
npx ruv-swarm github review-context \
  --pr 123 \
  --load-related-prs \
  --analyze-impact \
  --check-breaking-changes \
  --dependency-analysis
从历史记录中学习

根据代码库模式训练审查 Agent:

# Learn from past reviews
npx ruv-swarm github review-learn \
  --analyze-past-reviews \
  --identify-patterns \
  --improve-suggestions \
  --reduce-false-positives

# Train on your codebase
npx ruv-swarm github review-train \
  --learn-patterns \
  --adapt-to-style \
  --improve-accuracy
跨 PR 分析

协调审查相关的拉取请求:

# Analyze related PRs together
npx ruv-swarm github review-batch \
  --prs "123,124,125" \
  --check-consistency \
  --verify-integration \
  --combined-impact
多 PR 集群协调
# Coordinate swarms across related PRs
npx ruv-swarm github multi-pr \
  --prs "123,124,125" \
  --strategy "parallel" \
  --share-memory

🛠️ 自定义审查 Agent

创建自定义 Agent
// custom-review-agent.js
class CustomReviewAgent {
  constructor(config) {
    this.config = config;
    this.rules = config.rules || [];
  }

  async review(pr) {
    const issues = [];

    // Custom logic: Check for TODO comments in production code
    if (await this.checkTodoComments(pr)) {
      issues.push({
        severity: 'warning',
        file: pr.file,
        line: pr.line,
        message: 'TODO comment found in production code',
        suggestion: 'Resolve TODO or create issue to track it'
      });
    }

    // Custom logic: Verify API versioning
    if (await this.checkApiVersioning(pr)) {
      issues.push({
        severity: 'error',
        file: pr.file,
        line: pr.line,
        message: 'API endpoint missing versioning',
        suggestion: 'Add $v1/, $v2/ prefix to API routes'
      });
    }

    return issues;
  }

  async checkTodoComments(pr) {
    // Implementation
    const todoRegex = /\/\/\s*TODO|\/\*\s*TODO$gi;
    return todoRegex.test(pr.diff);
  }

  async checkApiVersioning(pr) {
    // Implementation
    const apiRegex = $app\.(get|post|put|delete)\(['"]\$api\/(?!v\d+)/;
    return apiRegex.test(pr.diff);
  }
}

module.exports = CustomReviewAgent;
注册自定义 Agent
# Register custom review agent
npx ruv-swarm github register-agent \
  --name "custom-reviewer" \
  --file ".$custom-review-agent.js" \
  --category "standards"

🔧 CI/CD 集成

与构建流水线集成
# .github$workflows$build-and-review.yml
name: Build and Review
on: [pull_request]

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions$checkout@v3
      - run: npm install
      - run: npm test
      - run: npm run build

  swarm-review:
    needs: build-and-test
    runs-on: ubuntu-latest
    steps:
      - name: Run Swarm Review
        run: |
          npx ruv-swarm github review-all \
            --pr ${{ github.event.pull_request.number }} \
            --include-build-results
自动修复 PR
# Auto-fix common issues
npx ruv-swarm github pr-fix 123 \
  --issues "lint,test-failures,formatting" \
  --commit-fixes \
  --push-changes
向 PR 发布进度更新
# Post swarm progress to PR using gh CLI
PROGRESS=$(npx ruv-swarm github pr-progress 123 --format markdown)

gh pr comment 123 --body "$PROGRESS"

# Update PR labels based on progress
if [[ $(echo "$PROGRESS" | grep -o '[0-9]\+%' | sed 's/%//') -gt 90 ]]; then
  gh pr edit 123 --add-label "ready-for-review"
fi

📋 完整工作流示例

示例 1:安全关键型 PR
# Review authentication system changes
npx ruv-swarm github review-init \
  --pr 456 \
  --agents "security,authentication,audit" \
  --depth "maximum" \
  --require-security-approval \
  --penetration-test
示例 2:性能敏感型 PR
# Review database optimization
npx ruv-swarm github review-init \
  --pr 789 \
  --agents "performance,database,caching" \
  --benchmark \
  --profile \
  --load-test
示例 3:UI 组件 PR
# Review new component library
npx ruv-swarm github review-init \
  --pr 321 \
  --agents "accessibility,style,i18n,docs" \
  --visual-regression \
  --component-tests \
  --responsive-check
示例 4:功能开发 PR
# Review new feature implementation
gh pr view 456 --json body,labels,files | \
  npx ruv-swarm github pr-init 456 \
    --topology hierarchical \
    --agents "architect,coder,tester,security" \
    --auto-assign-tasks
示例 5:错误修复 PR
# Review bug fix with debugging focus
npx ruv-swarm github pr-init 789 \
  --topology mesh \
  --agents "debugger,analyst,tester" \
  --priority high \
  --regression-test

📊 监控与分析

审查仪表板
# Launch real-time review dashboard
npx ruv-swarm github review-dashboard \
  --real-time \
  --show "agent-activity,issue-trends,fix-rates,coverage"
生成审查报告
# Create comprehensive review report
npx ruv-swarm github review-report \
  --format "markdown" \
  --include "summary,details,trends,recommendations" \
  --email-stakeholders \
  --export-pdf
PR Swarm 分析
# Generate PR-specific analytics
npx ruv-swarm github pr-report 123 \
  --metrics "completion-time,agent-efficiency,token-usage,issue-density" \
  --format markdown \
  --compare-baseline
导出到 GitHub Insights
# Export metrics to GitHub Insights
npx ruv-swarm github export-metrics \
  --pr 123 \
  --to-insights \
  --dashboard-url

🔐 安全注意事项

最佳实践
  1. 令牌权限:确保 GitHub 令牌仅具有必需的最小权限范围
  2. 命令验证:执行前验证所有 PR 评论
  3. 速率限制:为 PR 操作实施速率限制
  4. 审计跟踪:记录所有 swarm 操作以满足合规要求
  5. 密钥管理:切勿在 PR 评论或日志中暴露 API 密钥
安全检查清单
  • GitHub 令牌的权限范围仅限于仓库
  • 已验证 Webhook 签名
  • 已启用命令注入防护
  • 已配置速率限制
  • 已启用审计日志记录
  • 已启用密钥扫描
  • 已实施分支保护规则

📚 最佳实践

1. 审查配置
  • ✅ 预先定义明确的审查标准
  • ✅ 设置适当的严重级别阈值
  • ✅ 针对你的技术栈配置 Agent 专长
  • ✅ 为紧急情况制定覆盖流程
2. 评论质量
  • ✅ 提供可执行且具体的反馈
  • ✅ 在建议中附上代码示例
  • ✅ 参考文档和最佳实践
  • ✅ 保持尊重、建设性的语气
3. 性能优化
  • ✅ 缓存分析结果,避免重复工作
  • ✅ 对大型 PR 进行增量审查
  • ✅ 启用 Agent 并行执行
  • ✅ 高效地批量处理评论操作
4. PR 模板

## Swarm Configuration
- Topology: [mesh$hierarchical$ring$star]
- Max Agents: [number]
- Auto-spawn: [yes$no]
- Priority: [high$medium$low]

## Tasks for Swarm
- [ ] Task 1 description
- [ ] Task 2 description
- [ ] Task 3 description

## Review Focus Areas
- [ ] Security review
- [ ] Performance analysis
- [ ] Architecture validation
- [ ] Accessibility check
5. 准备就绪后自动合并
# Auto-merge when swarm completes and passes checks
SWARM_STATUS=$(npx ruv-swarm github pr-status 123)

if [[ "$SWARM_STATUS" == "complete" ]]; then
  # Check review requirements
  REVIEWS=$(gh pr view 123 --json reviews --jq '.reviews | length')

  if [[ $REVIEWS -ge 2 ]]; then
    # Enable auto-merge
    gh pr merge 123 --auto --squash
  fi
fi

🔗 与 Claude Code 集成

工作流模式
  1. Claude Code 读取 PR 差异和上下文
  2. Swarm 根据 PR 类型协调审查方式
  3. Agent 并行处理不同的审查方面
  4. 自动向 PR 发布进度更新
  5. 标记为就绪前进行最终审查
示例:完整的 PR 管理
[Single Message - Parallel Execution]:
  // Initialize coordination
  mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 5 }
  mcp__claude-flow__agent_spawn { type: "reviewer", name: "Senior Reviewer" }
  mcp__claude-flow__agent_spawn { type: "tester", name: "QA Engineer" }
  mcp__claude-flow__agent_spawn { type: "coordinator", name: "Merge Coordinator" }

  // Create and manage PR using gh CLI
  Bash("gh pr create --title 'Feature: Add authentication' --base main")
  Bash("gh pr view 54 --json files,diff")
  Bash("gh pr review 54 --approve --body 'LGTM after automated review'")

  // Execute tests and validation
  Bash("npm test")
  Bash("npm run lint")
  Bash("npm run build")

  // Track progress
  TodoWrite { todos: [
    { content: "Complete code review", status: "completed", activeForm: "Completing code review" },
    { content: "Run test suite", status: "completed", activeForm: "Running test suite" },
    { content: "Validate security", status: "completed", activeForm: "Validating security" },
    { content: "Merge when ready", status: "pending", activeForm: "Merging when ready" }
  ]}

🆘 故障排查

常见问题
问题:审查 Agent 未启动<$strong><$summary>

解决方案:

# Check swarm status
npx ruv-swarm swarm-status

# Verify GitHub CLI authentication
gh auth status

# Re-initialize swarm
npx ruv-swarm github review-init --pr 123 --force

<$details>

问题:评论未发布到 PR<$strong><$summary>

解决方案:

# Verify GitHub token permissions
gh auth status

# Check API rate limits
gh api rate_limit

# Use batch comment posting
npx ruv-swarm github review-comments --pr 123 --batch

<$details>

问题:审查耗时过长<$strong><$summary>

解决方案:

# Use incremental review for large PRs
npx ruv-swarm github review-init --pr 123 --incremental

# Reduce agent count
npx ruv-swarm github review-init --pr 123 --agents "security,style" --max-agents 3

# Enable parallel processing
npx ruv-swarm github review-init --pr 123 --parallel --cache-results

<$details>


📖 更多资源

相关技能
  • github-pr-manager - 全面的 PR 生命周期管理
  • github-workflow-automation - 自动化 GitHub 工作流
  • swarm-coordination - 高级 swarm 编排
文档
支持
  • GitHub Issues:报告错误并请求功能
  • 社区:参与讨论并分享经验
  • 示例:浏览示例配置和工作流

📄 许可证

此技能是 Claude Code Flow 项目的一部分,采用 MIT 许可证授权。


最后更新: 2025-10-19 版本: 1.0.0 维护者: Claude Code Flow 团队

评论

支持 Markdown