github-code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitHub Code Review Skill

GitHub代码评审Skill

AI-Powered Code Review: Deploy specialized review agents to perform comprehensive, intelligent code reviews that go beyond traditional static analysis.
AI驱动的代码评审:部署专业的评审Agent,执行超越传统静态分析的全面智能代码评审。

🎯 Quick Start

🎯 快速开始

Simple Review

简单评审

bash
undefined
bash
undefined

Initialize review swarm for PR

Initialize review swarm for PR

gh pr view 123 --json files,diff | npx ruv-swarm github review-init --pr 123
gh pr view 123 --json files,diff | npx ruv-swarm github review-init --pr 123

Post review status

Post review status

gh pr comment 123 --body "🔍 Multi-agent code review initiated"
undefined
gh pr comment 123 --body "🔍 Multi-agent code review initiated"
undefined

Complete Review Workflow

完整评审工作流

bash
undefined
bash
undefined

Get PR context with gh CLI

Get PR context with gh CLI

PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body) PR_DIFF=$(gh pr diff 123)
PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body) PR_DIFF=$(gh pr diff 123)

Initialize comprehensive review

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

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

---

📚 Table of Contents

📚 目录

<details> <summary><strong>Core Features</strong></summary> </details> <details> <summary><strong>Review Agents</strong></summary> </details> <details> <summary><strong>Advanced Features</strong></summary> </details> <details> <summary><strong>Integration & Automation</strong></summary> </details>
<details> <summary><strong>核心功能</strong></summary> </details> <details> <summary><strong>评审Agent</strong></summary> </details> <details> <summary><strong>高级功能</strong></summary> </details> <details> <summary><strong>集成与自动化</strong></summary> </details>

🚀 Core Features

🚀 核心功能

Multi-Agent Review System

多Agent评审系统

Deploy specialized AI agents for comprehensive code review:
bash
undefined
部署专业AI Agent执行全面代码评审:
bash
undefined

Initialize review swarm with GitHub CLI integration

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)
PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body) PR_DIFF=$(gh pr diff 123)

Start multi-agent review

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

Post initial review status

gh pr comment 123 --body "🔍 Multi-agent code review initiated"

**Benefits:**
- ✅ Parallel review by specialized agents
- ✅ Comprehensive coverage across multiple domains
- ✅ Faster review cycles with coordinated analysis
- ✅ Consistent quality standards enforcement

---
gh pr comment 123 --body "🔍 Multi-agent code review initiated"

**优势:**
- ✅ 由专业Agent并行评审
- ✅ 覆盖多个领域的全面检查
- ✅ 协作分析缩短评审周期
- ✅ 执行一致的质量标准

---

🤖 Specialized Review Agents

🤖 专业评审Agent

Security Review Agent

安全评审Agent

Focus: Identify security vulnerabilities and suggest fixes
bash
undefined
重点: 识别安全漏洞并建议修复方案
bash
undefined

Get changed files from PR

Get changed files from PR

CHANGED_FILES=$(gh pr view 123 --json files --jq '.files[].path')
CHANGED_FILES=$(gh pr view 123 --json files --jq '.files[].path')

Run security-focused review

Run security-focused review

SECURITY_RESULTS=$(npx ruv-swarm github review-security
--pr 123
--files "$CHANGED_FILES"
--check "owasp,cve,secrets,permissions"
--suggest-fixes)
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

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

<details>
<summary><strong>Security Checks Performed</strong></summary>

```javascript
{
  "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> <details> <summary><strong>Comment Template: Security Issue</strong></summary>
markdown
🔒 **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]
References:
  • OWASP Guide
  • Security Best Practices

</details>

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

<details>
<summary><strong>执行的安全检查</strong></summary>

```javascript
{
  "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> <details> <summary><strong>评论模板:安全问题</strong></summary>
markdown
🔒 **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]
References:
  • OWASP Guide
  • Security Best Practices

</details>

---

Performance Review Agent

性能评审Agent

Focus: Analyze performance impact and optimization opportunities
bash
undefined
重点: 分析性能影响与优化机会
bash
undefined

Run performance analysis

Run performance analysis

npx ruv-swarm github review-performance
--pr 123
--profile "cpu,memory,io"
--benchmark-against main
--suggest-optimizations

<details>
<summary><strong>Performance Metrics Analyzed</strong></summary>

```javascript
{
  "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>
npx ruv-swarm github review-performance
--pr 123
--profile "cpu,memory,io"
--benchmark-against main
--suggest-optimizations

<details>
<summary><strong>分析的性能指标</strong></summary>

```javascript
{
  "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>

Architecture Review Agent

架构评审Agent

Focus: Evaluate design patterns and architectural decisions
bash
undefined
重点: 评估设计模式与架构决策
bash
undefined

Architecture review

Architecture review

npx ruv-swarm github review-architecture
--pr 123
--check "patterns,coupling,cohesion,solid"
--visualize-impact
--suggest-refactoring

<details>
<summary><strong>Architecture Analysis</strong></summary>

```javascript
{
  "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>
npx ruv-swarm github review-architecture
--pr 123
--check "patterns,coupling,cohesion,solid"
--visualize-impact
--suggest-refactoring

<details>
<summary><strong>架构分析内容</strong></summary>

```javascript
{
  "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>

Style & Convention Agent

风格与规范Agent

Focus: Enforce coding standards and best practices
bash
undefined
重点: 执行编码标准与最佳实践
bash
undefined

Style enforcement with auto-fix

Style enforcement with auto-fix

npx ruv-swarm github review-style
--pr 123
--check "formatting,naming,docs,tests"
--auto-fix "formatting,imports,whitespace"

<details>
<summary><strong>Style Checks</strong></summary>

```javascript
{
  "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>
npx ruv-swarm github review-style
--pr 123
--check "formatting,naming,docs,tests"
--auto-fix "formatting,imports,whitespace"

<details>
<summary><strong>风格检查内容</strong></summary>

```javascript
{
  "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-Based Swarm Management

🔄 基于PR的Swarm管理

Create Swarm from PR

从PR创建Swarm

bash
undefined
bash
undefined

Create swarm from PR description using gh CLI

Create swarm from PR description using gh CLI

gh pr view 123 --json body,title,labels,files | npx ruv-swarm swarm create-from-pr
gh pr view 123 --json body,title,labels,files | npx ruv-swarm swarm create-from-pr

Auto-spawn agents based on PR labels

Auto-spawn agents based on PR labels

gh pr view 123 --json labels | npx ruv-swarm swarm auto-spawn
gh pr view 123 --json labels | npx ruv-swarm swarm auto-spawn

Create swarm with full PR context

Create swarm with full PR context

gh pr view 123 --json body,labels,author,assignees |
npx ruv-swarm swarm init --from-pr-data
undefined
gh pr view 123 --json body,labels,author,assignees |
npx ruv-swarm swarm init --from-pr-data
undefined

Label-Based Agent Assignment

基于标签的Agent分配

Map PR labels to specialized agents:
json
{
  "label-mapping": {
    "bug": ["debugger", "tester"],
    "feature": ["architect", "coder", "tester"],
    "refactor": ["analyst", "coder"],
    "docs": ["researcher", "writer"],
    "performance": ["analyst", "optimizer"],
    "security": ["security", "authentication", "audit"]
  }
}
将PR标签映射到专业Agent:
json
{
  "label-mapping": {
    "bug": ["debugger", "tester"],
    "feature": ["architect", "coder", "tester"],
    "refactor": ["analyst", "coder"],
    "docs": ["researcher", "writer"],
    "performance": ["analyst", "optimizer"],
    "security": ["security", "authentication", "audit"]
  }
}

Topology Selection by PR Size

按PR大小选择拓扑结构

bash
undefined
bash
undefined

Automatic topology selection based on PR complexity

Automatic topology selection based on PR complexity

Small PR (< 100 lines): ring topology

Small PR (< 100 lines): ring topology

Medium PR (100-500 lines): mesh topology

Medium PR (100-500 lines): mesh topology

Large PR (> 500 lines): hierarchical topology

Large PR (> 500 lines): hierarchical topology

npx ruv-swarm github pr-topology --pr 123

---
npx ruv-swarm github pr-topology --pr 123

---

🎬 PR Comment Commands

🎬 PR评论命令

Execute swarm commands directly from PR comments:
markdown
<!-- In PR comment -->
/swarm init mesh 6
/swarm spawn coder "Implement authentication"
/swarm spawn tester "Write unit tests"
/swarm status
/swarm review --agents security,performance
<details> <summary><strong>Webhook Handler for Comment Commands</strong></summary>
javascript
// 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>
直接从PR评论中执行Swarm命令:
markdown
<!-- In PR comment -->
/swarm init mesh 6
/swarm spawn coder "Implement authentication"
/swarm spawn tester "Write unit tests"
/swarm status
/swarm review --agents security,performance
<details> <summary><strong>评论命令的Webhook处理器</strong></summary>
javascript
// 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>

⚙️ Review Configuration

⚙️ 评审配置

Configuration File

配置文件

yaml
undefined
yaml
undefined

.github/review-swarm.yml

.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
undefined
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
undefined

Custom Review Triggers

自定义评审触发器

javascript
{
  "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
    }
  }
}

javascript
{
  "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
    }
  }
}

🤖 Automated Workflows

🤖 自动化工作流

Auto-Review on PR Creation

PR创建时自动评审

yaml
undefined
yaml
undefined

.github/workflows/auto-review.yml

.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

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

---

💬 Intelligent Comment Generation

💬 智能评论生成

Generate Contextual Review Comments

生成上下文相关的评审评论

bash
undefined
bash
undefined

Get PR diff with context

Get PR diff with context

PR_DIFF=$(gh pr diff 123 --color never) PR_FILES=$(gh pr view 123 --json files)
PR_DIFF=$(gh pr diff 123 --color never) PR_FILES=$(gh pr view 123 --json files)

Generate review comments

Generate review comments

COMMENTS=$(npx ruv-swarm github review-comment
--pr 123
--diff "$PR_DIFF"
--files "$PR_FILES"
--style "constructive"
--include-examples
--suggest-fixes)
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

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
undefined
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
undefined

Batch Comment Management

批量评论管理

bash
undefined
bash
undefined

Manage review comments efficiently

Manage review comments efficiently

npx ruv-swarm github review-comments
--pr 123
--group-by "agent,severity"
--summarize
--resolve-outdated

---
npx ruv-swarm github review-comments
--pr 123
--group-by "agent,severity"
--summarize
--resolve-outdated

---

🚪 Quality Gates & Checks

🚪 质量门禁与检查

Status Checks

状态检查

yaml
undefined
yaml
undefined

Required status checks in branch protection

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"
undefined
protection_rules: required_status_checks: strict: true contexts: - "review-swarm/security" - "review-swarm/performance" - "review-swarm/architecture" - "review-swarm/tests"
undefined

Define Quality Gates

定义质量门禁

bash
undefined
bash
undefined

Set quality gate thresholds

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%"} }'
undefined
npx ruv-swarm github quality-gates
--define '{ "security": {"threshold": "no-critical"}, "performance": {"regression": "<5%"}, "coverage": {"minimum": "80%"}, "architecture": {"complexity": "<10"}, "duplication": {"maximum": "5%"} }'
undefined

Track Review Metrics

跟踪评审指标

bash
undefined
bash
undefined

Monitor review effectiveness

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

---
npx ruv-swarm github review-metrics
--period 30d
--metrics "issues-found,false-positives,fix-rate,time-to-review"
--export-dashboard
--format json

---

🎓 Advanced Features

🎓 高级功能

Context-Aware Reviews

上下文感知评审

Analyze PRs with full project context:
bash
undefined
结合完整项目上下文分析PR:
bash
undefined

Review with comprehensive context

Review with comprehensive context

npx ruv-swarm github review-context
--pr 123
--load-related-prs
--analyze-impact
--check-breaking-changes
--dependency-analysis
undefined
npx ruv-swarm github review-context
--pr 123
--load-related-prs
--analyze-impact
--check-breaking-changes
--dependency-analysis
undefined

Learning from History

从历史中学习

Train review agents on your codebase patterns:
bash
undefined
在代码库模式上训练评审Agent:
bash
undefined

Learn from past reviews

Learn from past reviews

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

Train on your codebase

Train on your codebase

npx ruv-swarm github review-train
--learn-patterns
--adapt-to-style
--improve-accuracy
undefined
npx ruv-swarm github review-train
--learn-patterns
--adapt-to-style
--improve-accuracy
undefined

Cross-PR Analysis

跨PR分析

Coordinate reviews across related pull requests:
bash
undefined
协调相关拉取请求的评审工作:
bash
undefined

Analyze related PRs together

Analyze related PRs together

npx ruv-swarm github review-batch
--prs "123,124,125"
--check-consistency
--verify-integration
--combined-impact
undefined
npx ruv-swarm github review-batch
--prs "123,124,125"
--check-consistency
--verify-integration
--combined-impact
undefined

Multi-PR Swarm Coordination

多PR Swarm协作

bash
undefined
bash
undefined

Coordinate swarms across related PRs

Coordinate swarms across related PRs

npx ruv-swarm github multi-pr
--prs "123,124,125"
--strategy "parallel"
--share-memory

---
npx ruv-swarm github multi-pr
--prs "123,124,125"
--strategy "parallel"
--share-memory

---

🛠️ Custom Review Agents

🛠️ 自定义评审Agent

Create Custom Agent

创建自定义Agent

javascript
// 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;
javascript
// 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;

Register Custom Agent

注册自定义Agent

bash
undefined
bash
undefined

Register custom review agent

Register custom review agent

npx ruv-swarm github register-agent
--name "custom-reviewer"
--file "./custom-review-agent.js"
--category "standards"

---
npx ruv-swarm github register-agent
--name "custom-reviewer"
--file "./custom-review-agent.js"
--category "standards"

---

🔧 CI/CD Integration

🔧 CI/CD集成

Integration with Build Pipeline

与构建流水线集成

yaml
undefined
yaml
undefined

.github/workflows/build-and-review.yml

.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
undefined
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
undefined

Automated PR Fixes

自动PR修复

bash
undefined
bash
undefined

Auto-fix common issues

Auto-fix common issues

npx ruv-swarm github pr-fix 123
--issues "lint,test-failures,formatting"
--commit-fixes
--push-changes
undefined
npx ruv-swarm github pr-fix 123
--issues "lint,test-failures,formatting"
--commit-fixes
--push-changes
undefined

Progress Updates to PR

向PR更新进度

bash
undefined
bash
undefined

Post swarm progress to PR using gh CLI

Post swarm progress to PR using gh CLI

PROGRESS=$(npx ruv-swarm github pr-progress 123 --format markdown)
gh pr comment 123 --body "$PROGRESS"
PROGRESS=$(npx ruv-swarm github pr-progress 123 --format markdown)
gh pr comment 123 --body "$PROGRESS"

Update PR labels based on 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

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

---

📋 Complete Workflow Examples

📋 完整工作流示例

Example 1: Security-Critical PR

示例1:安全关键PR

bash
undefined
bash
undefined

Review authentication system changes

Review authentication system changes

npx ruv-swarm github review-init
--pr 456
--agents "security,authentication,audit"
--depth "maximum"
--require-security-approval
--penetration-test
undefined
npx ruv-swarm github review-init
--pr 456
--agents "security,authentication,audit"
--depth "maximum"
--require-security-approval
--penetration-test
undefined

Example 2: Performance-Sensitive PR

示例2:性能敏感PR

bash
undefined
bash
undefined

Review database optimization

Review database optimization

npx ruv-swarm github review-init
--pr 789
--agents "performance,database,caching"
--benchmark
--profile
--load-test
undefined
npx ruv-swarm github review-init
--pr 789
--agents "performance,database,caching"
--benchmark
--profile
--load-test
undefined

Example 3: UI Component PR

示例3:UI组件PR

bash
undefined
bash
undefined

Review new component library

Review new component library

npx ruv-swarm github review-init
--pr 321
--agents "accessibility,style,i18n,docs"
--visual-regression
--component-tests
--responsive-check
undefined
npx ruv-swarm github review-init
--pr 321
--agents "accessibility,style,i18n,docs"
--visual-regression
--component-tests
--responsive-check
undefined

Example 4: Feature Development PR

示例4:功能开发PR

bash
undefined
bash
undefined

Review new feature implementation

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
undefined
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
undefined

Example 5: Bug Fix PR

示例5:Bug修复PR

bash
undefined
bash
undefined

Review bug fix with debugging focus

Review bug fix with debugging focus

npx ruv-swarm github pr-init 789
--topology mesh
--agents "debugger,analyst,tester"
--priority high
--regression-test

---
npx ruv-swarm github pr-init 789
--topology mesh
--agents "debugger,analyst,tester"
--priority high
--regression-test

---

📊 Monitoring & Analytics

📊 监控与分析

Review Dashboard

评审仪表盘

bash
undefined
bash
undefined

Launch real-time review dashboard

Launch real-time review dashboard

npx ruv-swarm github review-dashboard
--real-time
--show "agent-activity,issue-trends,fix-rates,coverage"
undefined
npx ruv-swarm github review-dashboard
--real-time
--show "agent-activity,issue-trends,fix-rates,coverage"
undefined

Generate Review Reports

生成评审报告

bash
undefined
bash
undefined

Create comprehensive review report

Create comprehensive review report

npx ruv-swarm github review-report
--format "markdown"
--include "summary,details,trends,recommendations"
--email-stakeholders
--export-pdf
undefined
npx ruv-swarm github review-report
--format "markdown"
--include "summary,details,trends,recommendations"
--email-stakeholders
--export-pdf
undefined

PR Swarm Analytics

PR Swarm分析

bash
undefined
bash
undefined

Generate PR-specific analytics

Generate PR-specific analytics

npx ruv-swarm github pr-report 123
--metrics "completion-time,agent-efficiency,token-usage,issue-density"
--format markdown
--compare-baseline
undefined
npx ruv-swarm github pr-report 123
--metrics "completion-time,agent-efficiency,token-usage,issue-density"
--format markdown
--compare-baseline
undefined

Export to GitHub Insights

导出到GitHub Insights

bash
undefined
bash
undefined

Export metrics to GitHub Insights

Export metrics to GitHub Insights

npx ruv-swarm github export-metrics
--pr 123
--to-insights
--dashboard-url

---
npx ruv-swarm github export-metrics
--pr 123
--to-insights
--dashboard-url

---

🔐 Security Considerations

🔐 安全注意事项

Best Practices

最佳实践

  1. Token Permissions: Ensure GitHub tokens have minimal required scopes
  2. Command Validation: Validate all PR comments before execution
  3. Rate Limiting: Implement rate limits for PR operations
  4. Audit Trail: Log all swarm operations for compliance
  5. Secret Management: Never expose API keys in PR comments or logs
  1. Token权限:确保GitHub Token仅拥有最小必要权限
  2. 命令验证:执行前验证所有PR评论中的命令
  3. 速率限制:为PR操作实现速率限制
  4. 审计跟踪:记录所有Swarm操作以符合合规要求
  5. 密钥管理:切勿在PR评论或日志中暴露API密钥

Security Checklist

安全检查清单

  • GitHub token scoped to repository only
  • Webhook signatures verified
  • Command injection protection enabled
  • Rate limiting configured
  • Audit logging enabled
  • Secrets scanning active
  • Branch protection rules enforced

  • GitHub Token仅限定仓库范围
  • Webhook签名已验证
  • 已启用命令注入防护
  • 已配置速率限制
  • 已启用审计日志
  • 密钥扫描已激活
  • 分支保护规则已执行

📚 Best Practices

📚 最佳实践

1. Review Configuration

1. 评审配置

  • ✅ Define clear review criteria upfront
  • ✅ Set appropriate severity thresholds
  • ✅ Configure agent specializations for your stack
  • ✅ Establish override procedures for emergencies
  • ✅ 提前定义清晰的评审标准
  • ✅ 设置适当的严重程度阈值
  • ✅ 针对你的技术栈配置Agent专业方向
  • ✅ 建立紧急情况的覆盖流程

2. Comment Quality

2. 评论质量

  • ✅ Provide actionable, specific feedback
  • ✅ Include code examples with suggestions
  • ✅ Reference documentation and best practices
  • ✅ Maintain respectful, constructive tone
  • ✅ 提供可操作的具体反馈
  • ✅ 包含带建议的代码示例
  • ✅ 参考文档与最佳实践
  • ✅ 保持尊重、建设性的语气

3. Performance Optimization

3. 性能优化

  • ✅ Cache analysis results to avoid redundant work
  • ✅ Use incremental reviews for large PRs
  • ✅ Enable parallel agent execution
  • ✅ Batch comment operations efficiently
  • ✅ 缓存分析结果以避免重复工作
  • ✅ 对大型PR使用增量评审
  • ✅ 启用Agent并行执行
  • ✅ 高效批量处理评论操作

4. PR Templates

4. PR模板

markdown
<!-- .github/pull_request_template.md -->
markdown
<!-- .github/pull_request_template.md -->

Swarm Configuration

Swarm配置

  • Topology: [mesh/hierarchical/ring/star]
  • Max Agents: [number]
  • Auto-spawn: [yes/no]
  • Priority: [high/medium/low]
  • Topology: [mesh/hierarchical/ring/star]
  • Max Agents: [number]
  • Auto-spawn: [yes/no]
  • Priority: [high/medium/low]

Tasks for Swarm

Swarm任务

  • Task 1 description
  • Task 2 description
  • Task 3 description
  • 任务1描述
  • 任务2描述
  • 任务3描述

Review Focus Areas

评审重点领域

  • Security review
  • Performance analysis
  • Architecture validation
  • Accessibility check
undefined
  • 安全评审
  • 性能分析
  • 架构验证
  • 无障碍性检查
undefined

5. Auto-Merge When Ready

5. 就绪时自动合并

bash
undefined
bash
undefined

Auto-merge when swarm completes and passes checks

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

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

---

🔗 Integration with Claude Code

🔗 与Claude Code集成

Workflow Pattern

工作流模式

  1. Claude Code reads PR diff and context
  2. Swarm coordinates review approach based on PR type
  3. Agents work in parallel on different review aspects
  4. Progress updates posted to PR automatically
  5. Final review performed before marking ready
  1. Claude Code 读取PR差异与上下文
  2. Swarm 根据PR类型协调评审方法
  3. Agent 并行处理不同评审维度
  4. 进度 自动更新到PR中
  5. 最终评审 在标记就绪前执行

Example: Complete PR Management

示例:完整PR管理

javascript
[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" }
  ]}

javascript
[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" }
  ]}

🆘 Troubleshooting

🆘 故障排除

Common Issues

常见问题

<details> <summary><strong>Issue: Review agents not spawning</strong></summary>
Solution:
bash
undefined
<details> <summary><strong>问题:评审Agent未启动</strong></summary>
解决方案:
bash
undefined

Check swarm status

Check swarm status

npx ruv-swarm swarm-status
npx ruv-swarm swarm-status

Verify GitHub CLI authentication

Verify GitHub CLI authentication

gh auth status
gh auth status

Re-initialize swarm

Re-initialize swarm

npx ruv-swarm github review-init --pr 123 --force

</details>

<details>
<summary><strong>Issue: Comments not posting to PR</strong></summary>

**Solution:**
```bash
npx ruv-swarm github review-init --pr 123 --force

</details>

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

**解决方案:**
```bash

Verify GitHub token permissions

Verify GitHub token permissions

gh auth status
gh auth status

Check API rate limits

Check API rate limits

gh api rate_limit
gh api rate_limit

Use batch comment posting

Use batch comment posting

npx ruv-swarm github review-comments --pr 123 --batch

</details>

<details>
<summary><strong>Issue: Review taking too long</strong></summary>

**Solution:**
```bash
npx ruv-swarm github review-comments --pr 123 --batch

</details>

<details>
<summary><strong>问题:评审耗时过长</strong></summary>

**解决方案:**
```bash

Use incremental review for large PRs

Use incremental review for large PRs

npx ruv-swarm github review-init --pr 123 --incremental
npx ruv-swarm github review-init --pr 123 --incremental

Reduce agent count

Reduce agent count

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

Enable parallel processing

Enable parallel processing

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

</details>

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

</details>

---

📖 Additional Resources

📖 附加资源

Related Skills

相关技能

  • github-pr-manager
    - Comprehensive PR lifecycle management
  • github-workflow-automation
    - Automate GitHub workflows
  • swarm-coordination
    - Advanced swarm orchestration
  • github-pr-manager
    - 全面PR生命周期管理
  • github-workflow-automation
    - 自动化GitHub工作流
  • swarm-coordination
    - 高级Swarm编排

Documentation

文档

Support

支持

  • GitHub Issues: Report bugs and request features
  • Community: Join discussions and share experiences
  • Examples: Browse example configurations and workflows

  • GitHub Issues:报告Bug并请求功能
  • 社区:加入讨论并分享经验
  • 示例:浏览示例配置与工作流

📄 License

📄 许可证

This skill is part of the Claude Code Flow project and is licensed under the MIT License.

Last Updated: 2025-10-19 Version: 1.0.0 Maintainer: Claude Code Flow Team
本Skill是Claude Code Flow项目的一部分,采用MIT许可证授权。

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