首页
/ ruflo 多智能体代码审查蜂群:agent-code-review-swarm 技能的完整配置与实现解析

ruflo 多智能体代码审查蜂群:agent-code-review-swarm 技能的完整配置与实现解析

2026-09-06 11:45:22作者:郜逊炳

本文围绕 ruflo 仓库中的技能文件 .agents/skills/agent-code-review-swarm/SKILL.md 展开,系统讲解如何用多个专职 AI Agent(安全、性能、架构、风格等)协同完成超越传统静态分析的智能代码审查。读完后你将掌握:该技能包的前置/后置钩子与工具声明机制、从 PR 获取上下文到发起蜂群审查的完整命令流程、审查配置文件与阈值门禁的写法、GitHub Actions 自动化集成方案,以及技能所声明的 swarm_init / agent_spawn 等 MCP 工具在仓库 v3 MCP Server 源码中的真实定义与 V2 兼容映射关系。

技能定位与文件结构

agent-code-review-swarm 是 ruflo 提供的一个 Agent 技能(Skill),目标如文档概述所言:部署专职 AI Agent 执行综合性、智能化的代码审查,超越传统静态分析。技能文件位于 .agents/skills/agent-code-review-swarm/SKILL.md,通过 $agent-code-review-swarm 触发调用。它与仓库中 swarm-init 等技能同属 .agents/skills/ 目录体系,配套源码支撑包括:

技能包解剖:双重 Frontmatter 与工具声明

SKILL.md 的头部包含两段 YAML frontmatter,这是理解其运行机制的关键:

外层 frontmatter(技能注册信息):

---
name: agent-code-review-swarm
description: Agent skill for code-review-swarm - invoke with $agent-code-review-swarm
---

内层 frontmatter(技能能力定义):

---
name: code-review-swarm
description: Deploy specialized AI agents to perform comprehensive, intelligent code reviews that go beyond traditional static analysis
tools: mcp__claude-flow__swarm_init, mcp__claude-flow__agent_spawn, mcp__claude-flow__task_orchestrate, Bash, Read, Write, TodoWrite
color: blue
type: development
capabilities:
  - Automated multi-agent code review
  - Security vulnerability analysis
  - Performance bottleneck detection
  - Architecture pattern validation
  - Style and convention enforcement
priority: high
hooks:
  pre: |
    echo "Starting code-review-swarm..."
    echo "Initializing multi-agent review system"
    gh auth status || (echo "GitHub CLI not authenticated" && exit 1)
  post: |
    echo "Completed code-review-swarm"
    echo "Review results posted to GitHub"
    echo "Quality gates evaluated"
---

几个要点:

  1. tools 声明:技能显式声明依赖 mcp__claude-flow__swarm_init(初始化蜂群)、mcp__claude-flow__agent_spawn(派生 Agent)、mcp__claude-flow__task_orchestrate(任务编排)三个 MCP 工具,外加 BashReadWriteTodoWrite 四个本地工具。前缀 mcp__claude-flow__ 表明这些工具来自 claude-flow MCP Server。
  2. pre 钩子:在技能执行前校验 gh auth status,未认证则直接 exit 1 中止——这是典型的"快速失败"防护,因为整个审查流程都依赖 GitHub CLI。
  3. post 钩子:宣告结果已回贴 GitHub、质量门禁已评估。

从源码看这三个 MCP 工具的真实定义

技能声明的三个工具在仓库 v3 MCP 工具层中都有对应实现,且 v2 兼容工具文件 给出了完整的参数 schema 与新旧命名映射(swarm_init -> swarm/initagent_spawn -> agent/spawn):

swarm_init(V2 兼容版) 的输入 schema(见 v2-compat-tools.ts):

参数 类型 / 取值 说明
topology mesh / hierarchical / ring / star / adaptive / collective / hierarchical-mesh 蜂群拓扑类型(必填)
maxAgents 数字,1–100,默认 5 最大 Agent 数
strategy balanced / specialized / adaptive,默认 balanced 任务分发策略

其 handler 会将 V2 入参转换为 V3 调用后转发给 initSwarmToolstrategy=balanced 映射为 loadBalancing: truestrategy=adaptive 映射为 autoScaling: true——从源码结构看,V2 的"策略"被拆解成了 V3 配置中的两个独立开关。

agent_spawn 的 schema 包含 type(Agent 类型)、name(自定义名称)、capabilities(能力字符串数组)等字段,与技能中"按专职角色派生审查 Agent"的用法直接对应。

V3 原生 swarm/init 的 schema 定义在 swarm-tools.ts,能力上限更高:

  • topology 支持 hierarchical / mesh / adaptive / collective / hierarchical-mesh,默认 hierarchical-mesh
  • maxAgents 上限从 V2 的 100 提升至 1000,默认 15;
  • config 中可指定 communicationProtocoldirect / message-bus / pubsub)、consensusMechanismmajority / unanimous / weighted / none)、failureHandlingretry / failover / ignore)等。

这意味着:技能 frontmatter 中面向 V2 命名空间声明的工具,在实际运行时会落到同一套 V3 处理器上;做安全、性能、架构多 Agent 并行审查时,可以按 swarm/init 的 schema 选择合适的拓扑与共识机制。

核心功能一:多 Agent 审查系统(review-init)

技能的第一个核心场景是基于 gh CLI 发起多 Agent 审查。完整流程(PR 编号以 123 为例):

# 获取 PR 详情
PR_DATA=$(gh pr view 123 --json files,additions,deletions,title,body)
PR_DIFF=$(gh pr diff 123)

# 携带 PR 上下文初始化审查蜂群
npx ruv-swarm github review-init \
  --pr 123 \
  --pr-data "$PR_DATA" \
  --diff "$PR_DIFF" \
  --agents "security,performance,style,architecture,accessibility" \
  --depth comprehensive

# 发布初始审查状态
gh pr comment 123 --body "🔍 Multi-agent code review initiated"

参数说明:

  • --agents:指定参与审查的专职 Agent 列表,accessibility(可访问性)在此处作为附加项出现;
  • --depth comprehensive:审查深度,文档后续示例还使用了 maximum(安全关键场景);
  • 前置条件:与 pre 钩子一致,gh 必须已认证;PR_DATAPR_DIFF 作为上下文整体注入,Agent 才能"带着完整语境"做审查,而不是只拿到一个裸 diff。

四个专职审查 Agent 及其检查清单

1. 安全 Agent(review-security)

# 获取变更文件列表
CHANGED_FILES=$(gh pr view 123 --json files --jq '.files[].path')

# 执行安全审查
SECURITY_RESULTS=$(npx ruv-swarm github review-security \
  --pr 123 \
  --files "$CHANGED_FILES" \
  --check "owasp,cve,secrets,permissions" \
  --suggest-fixes)

# 按严重程度分流处理
if echo "$SECURITY_RESULTS" | grep -q "critical"; then
  gh pr review 123 --request-changes --body "$SECURITY_RESULTS"
  gh pr edit 123 --add-label "security-review-required"
else
  gh pr comment 123 --body "$SECURITY_RESULTS"
fi

--check 参数支持 owasp(OWASP 类风险)、cve(已知漏洞组件)、secrets(密钥泄漏)、permissions(权限模型)四类检查。结果处理策略是典型的"严重度分流":命中 criticalrequest-changes 并打上 security-review-required 标签阻塞合并,否则仅以评论形式提示。

安全 Agent 的完整检查项与动作清单(文档原文):

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

2. 性能 Agent(review-performance)

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

--profile 指定剖析维度(CPU / 内存 / IO),--benchmark-against main 表示以 main 分支作为基线做对比。其度量项与基准能力:

{
  "metrics": [
    "Algorithm complexity",
    "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"
  ]
}

3. 架构 Agent(review-architecture)

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

检查维度覆盖设计模式遵循、SOLID、DRY 违背、关注点分离、依赖注入、层级违规与循环依赖;度量指标包括耦合度、内聚度、复杂度与可维护性指数:

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

4. 风格与规范 Agent

风格 Agent 负责格式化、命名约定、文档标准、注释质量、测试覆盖、错误处理与日志规范七项检查,并对其中四类问题提供自动修复:

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

"auto-fix 仅覆盖可机械修复的问题"是这类工具设计的关键边界——它避免 Agent 对语义层问题做激进改动。

审查配置文件:阈值、规则与门禁语义

在仓库的 .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
    performance: warn
    style: suggest

  rules:
    security:
      - no-eval
      - no-hardcoded-secrets
      - proper-auth-checks
    performance:
      - no-n-plus-one
      - efficient-queries
      - proper-caching
    architecture:
      - max-coupling: 5
      - min-cohesion: 0.7
      - follow-patterns

配置要点解析:

  • required-agents vs optional-agents:前者的 Agent 每次审查都必须参与,后者按需启用;
  • thresholds 的三级门禁语义block(阻断合并)、warn(警告但不阻断)、suggest(仅建议)。这里安全设为最高级别 block,性能 warn,风格 suggest,体现了"风险越高、门禁越硬"的分层策略;
  • rules:每类 Agent 挂接具体规则。安全规则是布尔型检查(禁 eval、禁硬编码密钥、鉴权必须到位);架构规则带有数值阈值(max-coupling: 5min-cohesion: 0.7),与架构 Agent 输出的耦合/内聚指标直接对应。

高级审查特性

上下文感知审查(review-context)

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

--load-related-prs 会拉取相关 PR 一起分析,--check-breaking-changes 关注破坏性变更——适合大型重构分支的审查。

历史学习(review-learn)

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

对历史审查记录做模式挖掘,持续改进建议质量并降低误报率。这一特性与 ruflo 整体的"自适应记忆、自学习"定位一致:审查系统会随团队反馈进化。

跨 PR 批量分析(review-batch)

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

针对相互关联的多个 PR(例如同一功能拆成多批提交),检查跨 PR 一致性、集成正确性与合并后的综合影响。

GitHub Actions 自动化集成

技能文档给出了完整的 CI 工作流(.github/workflows/auto-review.yml),在 openedsynchronize 事件上自动触发蜂群审查:

name: Automated Code Review
on:
  pull_request:
    types: [opened, synchronize]

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: |
          PR_NUM=${{ github.event.pull_request.number }}
          PR_DATA=$(gh pr view $PR_NUM --json files,title,body,labels)

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

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

          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

实现细节值得注意:

  1. fetch-depth: 0 拉取完整历史,保证 review-context 类的基线对比可用;
  2. GITHUB_TOKEN 免交互登录 gh CLI,对应 pre 钩子的认证检查;
  3. review-all 一次性跑完全部 Agent,输出先以评论形式回贴,再按输出中的 approved / changes-requested 标记执行对应的 gh pr review 动作——把"AI 结论"落成 GitHub 原生的审批语义。

自定义审查触发器

除全局触发外,还可以按路径模式配置差异化触发(原文以 $ 分隔通配路径):

{
  "triggers": {
    "high-risk-files": {
      "paths": ["**/auth/**", "**/payment/**"],
      "agents": ["security", "architecture"],
      "depth": "comprehensive"
    },
    "performance-critical": {
      "paths": ["**/api/**", "**/database/**"],
      "agents": ["performance", "database"],
      "benchmarks": true
    },
    "ui-changes": {
      "paths": ["**/components/**", "**/styles/**"],
      "agents": ["accessibility", "style", "i18n"],
      "visual-tests": true
    }
  }
}

即:动到 auth/payment/ 目录自动升级为安全 + 架构的 comprehensive 深度审查;api/database/ 目录追加基准测试;components/styles/ 目录触发可访问性与视觉测试。这是"基于风险的审查分配"的落地方式。

智能审查评论生成

生成结构化行内评论并逐条通过 GitHub API 发布的完整脚本:

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

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

# 逐条创建行内评论
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')

  gh api \
    --method POST \
    "repos/:owner/:repo/pulls/123/comments" \
    -f path="$FILE" \
    -f line="$LINE" \
    -f body="$BODY" \
    -f commit_id="$(gh pr view 123 --json headRefOid -q .headRefOid)"
done

要点:--style constructive 控制评论语气;--include-examples 要求附示例代码;评论输出为 JSON 数组(jq -c '.[]' 逐行解析),每条含 pathlinebody 三个字段;commit_id 取 PR 的 headRefOid,确保行内评论锚定到正确的提交上。

文档同时给出了安全问题的评论模板骨架(含 Severity 三级色标 🔴 Critical / 🟡 High / 🟢 Low、Description、Impact、Suggested Fix 与 References 段落),以及批量评论管理命令:

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

按 Agent 与严重度分组、汇总摘要、并自动清理过时的评论——避免 PR 页面被陈旧的 AI 评论淹没。

CI/CD 集成:状态检查、质量门禁与度量

强制状态检查

将各 Agent 的结果注册为分支保护所需的 status check($ 处为文档内的命名分隔写法,实际上下文名以部署配置为准):

protection_rules:
  required_status_checks:
    contexts:
      - "review-swarm/security"
      - "review-swarm/performance"
      - "review-swarm/architecture"

质量门禁定义

npx ruv-swarm github quality-gates \
  --define '{
    "security": {"threshold": "no-critical"},
    "performance": {"regression": "<5%"},
    "coverage": {"minimum": "80%"},
    "architecture": {"complexity": "<10"}
  }'

四条门禁分别量化了:安全零 critical、性能回退小于 5%、测试覆盖不低于 80%、复杂度低于 10。它们与配置文件中 thresholdsblock/warn/suggest 语义配合,构成完整的准入策略。

审查有效性度量

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

统计 30 天窗口内的发现问题数、误报数与修复率——这直接呼应 review-learn 的"降低误报"目标:先度量,再改进。

实战示例与高级特性

文档给出了三类典型 PR 的审查启动示例:

安全关键 PR(如认证系统变更):

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

性能敏感 PR(如数据库优化):

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

UI 组件 PR(如新组件库):

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

AI 学习与自定义审查 Agent

# 针对自有代码库训练
npx ruv-swarm github review-train \
  --learn-patterns \
  --adapt-to-style \
  --improve-accuracy

自定义 Agent 只需实现 review(pr) 接口并返回结构化问题列表:

class CustomReviewAgent {
  async review(pr) {
    const issues = [];
    if (await this.checkCustomRule(pr)) {
      issues.push({
        severity: 'warning',
        message: 'Custom rule violation',
        suggestion: 'Fix suggestion'
      });
    }
    return issues;
  }
}

风险导向的编排则交给 review-orchestrate

npx ruv-swarm github review-orchestrate \
  --strategy "risk-based" \
  --allocate-time-budget \
  --prioritize-critical

监控与分析

# 实时审查仪表盘
npx ruv-swarm github review-dashboard \
  --real-time \
  --show "agent-activity,issue-trends,fix-rates"

# 生成审查报告
npx ruv-swarm github review-report \
  --format "markdown" \
  --include "summary,details,trends" \
  --email-stakeholders

最佳实践清单

文档总结的三组最佳实践,可直接作为团队落地检查表:

  1. 审查配置:定义清晰的审查标准;设置合理的阈值;配置 Agent 专业化分工;建立人工覆盖(override)流程——AI 门禁必须留出人工通道。
  2. 评论质量:反馈必须可执行(actionable);附代码示例;引用相关文档;保持尊重语气。
  3. 性能:缓存分析结果;大 PR 做增量审查;Agent 并行执行;评论智能批量合并——这与 swarm/init 支持的 message-bus 通信协议和 swarm/scale 弹性扩缩(见 swarm-tools.tsscaleSwarmSchemagradual / immediate / adaptive 三种扩缩策略)在实现层面是相通的。

小结

agent-code-review-swarm 技能把"代码审查"从单点静态检查升级为一条完整的智能流水线:gh CLI 提供 PR 上下文 → swarm_init / agent_spawn 按角色派生专职 Agent → 各 Agent 依配置阈值产出 block/warn/suggest 三级结论 → 行内评论与 request-changes / approve 落回 GitHub 原生审批流 → 通过 metrics 与 learn 循环持续降低误报。技能所依赖的 MCP 工具在仓库 v2 兼容工具v3 蜂群工具 中均有真实 schema 定义(拓扑、并发上限、通信协议、共识机制),蜂群运行时位于 v3/@claude-flow/swarm。适用前提:本地或 CI 环境已安装 gh 并完成认证,且可通过 npx 拉取 ruv-swarm 运行时;配置中的 PR 编号、Agent 列表与阈值均应按团队实际情况调整。

登录后查看全文
热门项目推荐
相关项目推荐