mcpField
P
Pair Programming

Pair Programming

github.com/ruvnet开发101.6k42 次安装今天更新
代码仓库

关于 Pair Programming

Pair Programming 是面向 Claude Flow CLI 的协作开发技能,通过角色模式与 AI 搭档共同编程,并结合测试、代码审查、质量验证和会话持久化。

主要功能

  1. 01Driver、navigator 和角色切换模式
  2. 02TDD、审查、导师和调试模式
  3. 03测试生成与覆盖率跟踪
  4. 04代码审查与安全分析
  5. 05质量验证及失败回滚
  6. 06会话保存、恢复和导出

适用场景

  1. 01通过 driver 或 navigator 协作开发功能
  2. 02使用 TDD 工作流构建并验证更改
  3. 03通过调试和跟踪排查错误
  4. 04审查或重构代码并跟踪质量

安装

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

$npx skills add https://github.com/ruvnet/ruview --skill pair-programming

安装后在 Claude Code 中输入/pair-programming确认已加载。

详细介绍

结对编程

借助智能角色管理、实时质量监控和全面的开发工作流,开展协作式 AI 结对编程。

此技能的作用

此技能提供专业的 AI 辅助结对编程能力,支持多种协作模式、持续验证和集成测试。它负责管理驾驶员/领航员角色、执行实时代码审查、跟踪质量指标,并通过 truth-score 验证确保高标准。

主要能力:

  • 多种模式:驾驶员、领航员、切换、TDD、审查、导师、调试
  • 实时验证:自动进行质量评分,失败时回滚
  • 角色管理:在驾驶员/领航员角色之间无缝切换
  • 测试集成:自动生成测试、跟踪覆盖率、持续测试
  • 代码审查:安全扫描、性能分析、最佳实践检查
  • 会话持久化:自动保存、恢复、导出和分享

前置条件

必需:

  • 已安装 Claude Flow CLI(npm install -g claude-flow@alpha)
  • Git 仓库(可选,但推荐)

推荐:

  • 测试框架(Jest、pytest 等)
  • 已配置代码检查工具(ESLint、pylint 等)
  • 代码格式化工具(Prettier、Black 等)

快速入门

基本会话
# Start simple pair programming
claude-flow pair --start
TDD 会话
# Test-driven development
claude-flow pair --start \
  --mode tdd \
  --test-first \
  --coverage 90

完整指南

会话控制命令
启动会话
# Basic start
claude-flow pair --start

# Expert refactoring session
claude-flow pair --start \
  --agent senior-dev \
  --focus refactor \
  --verify \
  --threshold 0.98

# Debugging session
claude-flow pair --start \
  --agent debugger-expert \
  --focus debug \
  --review

# Learning session
claude-flow pair --start \
  --mode mentor \
  --pace slow \
  --examples
会话管理
# Check status
claude-flow pair --status

# View history
claude-flow pair --history

# Pause session
/pause [--reason <reason>]

# Resume session
/resume

# End session
claude-flow pair --end [--save] [--report]
可用模式
驾驶员模式

你编写代码,AI 提供指导。

claude-flow pair --start --mode driver

你的职责:

  • 编写实际代码
  • 实现解决方案
  • 立即做出决策
  • 处理语法和结构

AI 领航员:

  • 提供战略指导
  • 发现潜在问题
  • 提出改进建议
  • 实时审查
  • 跟踪整体方向

适用场景:

  • 学习新模式
  • 实现熟悉的功能
  • 快速迭代
  • 动手调试

命令:

/suggest     - Get implementation suggestions
/review      - Request code review
/explain     - Ask for explanations
/optimize    - Request optimization ideas
/patterns    - Get pattern recommendations
领航员模式

AI 编写代码,你提供方向。

claude-flow pair --start --mode navigator

你的职责:

  • 提供高层次方向
  • 审查生成的代码
  • 做出架构决策
  • 确保符合业务需求

AI 驾驶员:

  • 编写实现代码
  • 处理语法细节
  • 落实你的指导
  • 管理样板代码
  • 执行重构

适用场景:

  • 快速原型设计
  • 生成样板代码
  • 学习 AI 的模式
  • 探索解决方案

命令:

/implement   - Direct implementation
/refactor    - Request refactoring
/test        - Generate tests
/document    - Add documentation
/alternate   - See alternative approaches
切换模式

按固定间隔自动交替角色。

# Default 10-minute intervals
claude-flow pair --start --mode switch

# 5-minute intervals (rapid)
claude-flow pair --start --mode switch --interval 5m

# 15-minute intervals (deep focus)
claude-flow pair --start --mode switch --interval 15m

交接流程:

  1. 切换前 30 秒发出提醒
  2. 当前驾驶员完成当前思路
  3. 生成上下文摘要
  4. 平稳交换角色
  5. 新驾驶员继续工作

适用场景:

  • 平衡协作
  • 知识共享
  • 复杂功能
  • 长时间会话
专项模式

TDD 模式 - 测试驱动开发:

claude-flow pair --start \
  --mode tdd \
  --test-first \
  --coverage 100

工作流:编写失败的测试 → 实现 → 重构 → 重复

审查模式 - 持续代码审查:

claude-flow pair --start \
  --mode review \
  --strict \
  --security

功能:实时反馈、安全扫描、性能分析

导师模式 - 侧重学习:

claude-flow pair --start \
  --mode mentor \
  --explain-all \
  --pace slow

功能:详细说明、分步指导、模式讲解

调试模式 - 问题解决:

claude-flow pair --start \
  --mode debug \
  --verbose \
  --trace

功能:识别问题、分析根本原因、提出修复建议

会话内命令
代码命令
/explain [--level basic|detailed|expert]
  Explain the current code or selection

/suggest [--type refactor|optimize|security|style]
  Get improvement suggestions

/implement <description>
  Request implementation (navigator mode)

/refactor [--pattern <pattern>] [--scope function|file|module]
  Refactor selected code

/optimize [--target speed|memory|both]
  Optimize code for performance

/document [--format jsdoc|markdown|inline]
  Add documentation to code

/comment [--verbose]
  Add inline comments

/pattern <pattern-name> [--example]
  Apply a design pattern
测试命令
/test [--watch] [--coverage] [--only <pattern>]
  Run test suite

/test-gen [--type unit|integration|e2e]
  Generate tests for current code

/coverage [--report html|json|terminal]
  Check test coverage

/mock <target> [--realistic]
  Generate mock data or functions

/test-watch [--on-save]
  Enable test watching

/snapshot [--update]
  Create test snapshots
审查命令
/review [--scope current|file|changes] [--strict]
  Perform code review

/security [--deep] [--fix]
  Security analysis

/perf [--profile] [--suggestions]
  Performance analysis

/quality [--detailed]
  Check code quality metrics

/lint [--fix] [--config <config>]
  Run linters

/complexity [--threshold <value>]
  Analyze code complexity
导航命令
/goto <file>[:line[:column]]
  Navigate to file or location

/find <pattern> [--regex] [--case-sensitive]
  Search in project

/recent [--limit <n>]
  Show recent files

/bookmark [add|list|goto|remove] [<name>]
  Manage bookmarks

/history [--limit <n>] [--filter <pattern>]
  Show command history

/tree [--depth <n>] [--filter <pattern>]
  Show project structure
Git 命令
/diff [--staged] [--file <file>]
  Show git diff

/commit [--message <msg>] [--amend]
  Commit with verification

/branch [create|switch|delete|list] [<name>]
  Branch operations

/stash [save|pop|list|apply] [<message>]
  Stash operations

/log [--oneline] [--limit <n>]
  View git log

/blame [<file>]
  Show git blame
AI 伙伴命令
/agent [switch|info|config] [<agent-name>]
  Manage AI agent

/teach <preference>
  Teach the AI your preferences

/feedback [positive|negative] <message>
  Provide feedback to AI

/personality [professional|friendly|concise|verbose]
  Adjust AI personality

/expertise [add|remove|list] [<domain>]
  Set AI expertise focus
指标命令
/metrics [--period today|session|week|all]
  Show session metrics

/score [--breakdown]
  Show quality scores

/productivity [--chart]
  Show productivity metrics

/leaderboard [--personal|team]
  Show improvement leaderboard
角色与模式命令
/switch [--immediate]
  Switch driver/navigator roles

/mode <type>
  Change mode (driver|navigator|switch|tdd|review|mentor|debug)

/role
  Show current role

/handoff
  Prepare role handoff
命令快捷方式
别名完整命令
/s/suggest
/e/explain
/t/test
/r/review
/c/commit
/g/goto
/f/find
/h/help
/sw/switch
/st/status
配置
基本配置

创建 .claude-flow/pair-config.json:

{
  "pair": {
    "enabled": true,
    "defaultMode": "switch",
    "defaultAgent": "auto",
    "autoStart": false,
    "theme": "professional"
  }
}
完整配置
{
  "pair": {
    "general": {
      "enabled": true,
      "defaultMode": "switch",
      "defaultAgent": "senior-dev",
      "language": "javascript",
      "timezone": "UTC"
    },

    "modes": {
      "driver": {
        "enabled": true,
        "suggestions": true,
        "realTimeReview": true,
        "autoComplete": false
      },
      "navigator": {
        "enabled": true,
        "codeGeneration": true,
        "explanations": true,
        "alternatives": true
      },
      "switch": {
        "enabled": true,
        "interval": "10m",
        "warning": "30s",
        "autoSwitch": true,
        "pauseOnIdle": true
      }
    },

    "verification": {
      "enabled": true,
      "threshold": 0.95,
      "autoRollback": true,
      "preCommitCheck": true,
      "continuousMonitoring": true,
      "blockOnFailure": true
    },

    "testing": {
      "enabled": true,
      "autoRun": true,
      "framework": "jest",
      "onSave": true,
      "coverage": {
        "enabled": true,
        "minimum": 80,
        "enforce": true,
        "reportFormat": "html"
      }
    },

    "review": {
      "enabled": true,
      "continuous": true,
      "preCommit": true,
      "security": true,
      "performance": true,
      "style": true,
      "complexity": {
        "maxComplexity": 10,
        "maxDepth": 4,
        "maxLines": 100
      }
    },

    "git": {
      "enabled": true,
      "autoCommit": false,
      "commitTemplate": "feat: {message}",
      "signCommits": false,
      "pushOnEnd": false,
      "branchProtection": true
    },

    "session": {
      "autoSave": true,
      "saveInterval": "5m",
      "maxDuration": "4h",
      "idleTimeout": "15m",
      "breakReminder": "45m",
      "metricsInterval": "1m"
    },

    "ai": {
      "model": "advanced",
      "temperature": 0.7,
      "maxTokens": 4000,
      "personality": "professional",
      "expertise": ["backend", "testing", "security"],
      "learningEnabled": true
    }
  }
}
内置 Agent
{
  "agents": {
    "senior-dev": {
      "expertise": ["architecture", "patterns", "optimization"],
      "style": "thorough",
      "reviewLevel": "strict"
    },
    "tdd-specialist": {
      "expertise": ["testing", "mocks", "coverage"],
      "style": "test-first",
      "reviewLevel": "comprehensive"
    },
    "debugger-expert": {
      "expertise": ["debugging", "profiling", "tracing"],
      "style": "analytical",
      "reviewLevel": "focused"
    },
    "junior-dev": {
      "expertise": ["learning", "basics", "documentation"],
      "style": "questioning",
      "reviewLevel": "educational"
    }
  }
}
CLI 配置
# Set configuration
claude-flow pair config set defaultMode switch
claude-flow pair config set verification.threshold 0.98

# Get configuration
claude-flow pair config get
claude-flow pair config get defaultMode

# Export/Import
claude-flow pair config export > config.json
claude-flow pair config import config.json

# Reset
claude-flow pair config reset
配置文件管理

创建可重复使用的配置文件:

# Create profile
claude-flow pair profile create refactoring \
  --mode driver \
  --verify true \
  --threshold 0.98 \
  --focus refactor

# Use profile
claude-flow pair --start --profile refactoring

# List profiles
claude-flow pair profile list

配置文件设置:

{
  "profiles": {
    "refactoring": {
      "mode": "driver",
      "verification": {
        "enabled": true,
        "threshold": 0.98
      },
      "focus": "refactor"
    },
    "debugging": {
      "mode": "navigator",
      "agent": "debugger-expert",
      "trace": true,
      "verbose": true
    },
    "learning": {
      "mode": "mentor",
      "pace": "slow",
      "explanations": "detailed",
      "examples": true
    }
  }
}
实际示例
示例 1:功能实现

使用 JWT 令牌实现用户身份验证:

# Session setup
claude-flow pair --start \
  --mode switch \
  --agent senior-dev \
  --focus implement \
  --verify \
  --test

会话流程:

👥 Starting pair programming for authentication feature...

[DRIVER: You - 10 minutes]
/explain JWT authentication flow
> AI explains JWT concepts and best practices

/suggest implementation approach
> AI suggests using middleware pattern with refresh tokens

# You write the basic auth middleware structure

[SWITCH TO NAVIGATOR]

[NAVIGATOR: AI - 10 minutes]
/implement JWT token generation with refresh tokens
> AI generates secure token implementation

/test-gen
> AI creates comprehensive test suite

[SWITCH TO DRIVER]

[DRIVER: You - 10 minutes]
# You refine the implementation
/review --security
> AI performs security review, suggests improvements

/commit --message "feat: JWT authentication with refresh tokens"
✅ Truth Score: 0.98 - Committed successfully
示例 2:修复错误

调试 Node.js 中的内存泄漏:

# Session setup
claude-flow pair --start \
  --mode navigator \
  --agent debugger-expert \
  --focus debug \
  --trace

会话流程:

👥 Starting debugging session...

/status
> Analyzing application for memory issues...

/perf --profile
> Memory usage growing: 150MB → 450MB over 10 minutes

/find "new EventEmitter" --regex
> Found 3 instances of EventEmitter creation

/inspect eventEmitters --deep
> Discovering listeners not being removed

/suggest fix for memory leak
> AI suggests: "Add removeListener in cleanup functions"

/implement cleanup functions for all event emitters
> AI generates proper cleanup code

/test
> Memory stable at 150MB ✅

/commit --message "fix: memory leak in event emitters"
示例 3:TDD 会话

使用测试驱动开发构建购物车:

# Session setup
claude-flow pair --start \
  --mode tdd \
  --agent tdd-specialist \
  --test-first

会话流程:

👥 TDD Session: Shopping Cart Feature

[RED PHASE]
/test-gen "add item to cart"
> AI writes failing test:
  ✗ should add item to cart
  ✗ should update quantity for existing item
  ✗ should calculate total price

[GREEN PHASE]
/implement minimal cart functionality
> You write just enough code to pass tests

/test
> Tests passing: 3/3 ✅

[REFACTOR PHASE]
/refactor --pattern repository
> AI refactors to repository pattern

/test
> Tests still passing: 3/3 ✅

[NEXT CYCLE]
/test-gen "remove item from cart"
> AI writes new failing tests...
示例 4:代码重构

现代化旧版代码:

# Session setup
claude-flow pair --start \
  --mode driver \
  --focus refactor \
  --verify \
  --threshold 0.98

会话流程:

👥 Refactoring Session: Modernizing UserService

/analyze UserService.js
> AI identifies:
  - Callback hell (5 levels deep)
  - No error handling
  - Tight coupling
  - No tests

/suggest refactoring plan
> AI suggests:
  1. Convert callbacks to async/await
  2. Add error boundaries
  3. Extract dependencies
  4. Add unit tests

/test-gen --before-refactor
> AI generates tests for current behavior

/refactor callbacks to async/await
# You refactor with AI guidance

/test
> All tests passing ✅

/review --compare
> AI shows before/after comparison
> Code complexity: 35 → 12
> Truth score: 0.99 ✅

/commit --message "refactor: modernize UserService with async/await"
示例 5:性能优化

优化运行缓慢的 React 应用:

# Session setup
claude-flow pair --start \
  --mode switch \
  --agent performance-expert \
  --focus optimize \
  --profile

会话流程:

👥 Performance Optimization Session

/perf --profile
> React DevTools Profiler Results:
  - ProductList: 450ms render
  - CartSummary: 200ms render
  - Unnecessary re-renders: 15

/suggest optimizations for ProductList
> AI suggests:
  1. Add React.memo
  2. Use useMemo for expensive calculations
  3. Implement virtualization for long lists

/implement React.memo and useMemo
# You implement with AI guidance

/perf --profile
> ProductList: 45ms render (90% improvement!) ✅

/implement virtualization with react-window
> AI implements virtual scrolling

/perf --profile
> ProductList: 12ms render (97% improvement!) ✅
> FPS: 60 stable ✅

/commit --message "perf: optimize ProductList with memoization and virtualization"
示例 6:API 开发

使用 Express 构建 RESTful API:

# Session setup
claude-flow pair --start \
  --mode navigator \
  --agent backend-expert \
  --focus implement \
  --test

会话流程:

👥 API Development Session

/design REST API for blog platform
> AI designs endpoints:
  POST   /api/posts
  GET    /api/posts
  GET    /api/posts/:id
  PUT    /api/posts/:id
  DELETE /api/posts/:id

/implement CRUD endpoints with validation
> AI implements with Express + Joi validation

/test-gen --integration
> AI generates integration tests

/security --api
> AI adds:
  - Rate limiting
  - Input sanitization
  - JWT authentication
  - CORS configuration

/document --openapi
> AI generates OpenAPI documentation

/test --integration
> All endpoints tested: 15/15 ✅
会话模板
快速入门模板
# Refactoring template
claude-flow pair --template refactor
# Focus: Code improvement
# Verification: High (0.98)
# Testing: After each change
# Review: Continuous

# Feature template
claude-flow pair --template feature
# Focus: Implementation
# Verification: Standard (0.95)
# Testing: On completion
# Review: Pre-commit

# Debug template
claude-flow pair --template debug
# Focus: Problem solving
# Verification: Moderate (0.90)
# Testing: Regression tests
# Review: Root cause

# Learning template
claude-flow pair --template learn
# Mode: Mentor
# Pace: Slow
# Explanations: Detailed
# Examples: Many
会话管理
会话状态
claude-flow pair --status

输出:

👥 Pair Programming Session
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Session ID: pair_1755021234567
Duration: 45 minutes
Status: Active

Partner: senior-dev
Current Role: DRIVER (you)
Mode: Switch (10m intervals)
Next Switch: in 3 minutes

📊 Metrics:
├── Truth Score: 0.982 ✅
├── Lines Changed: 234
├── Files Modified: 5
├── Tests Added: 12
├── Coverage: 87% ↑3%
└── Commits: 3

🎯 Focus: Implementation
📝 Current File: src/auth/login.js
会话历史记录
claude-flow pair --history

输出:

📚 Session History
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. 2024-01-15 14:30 - 16:45 (2h 15m)
   Partner: expert-coder
   Focus: Refactoring
   Truth Score: 0.975
   Changes: +340 -125 lines

2. 2024-01-14 10:00 - 11:30 (1h 30m)
   Partner: tdd-specialist
   Focus: Testing
   Truth Score: 0.991
   Tests Added: 24

3. 2024-01-13 15:00 - 17:00 (2h)
   Partner: debugger-expert
   Focus: Bug Fixing
   Truth Score: 0.968
   Issues Fixed: 5
会话持久化
# Save session
claude-flow pair --save [--name <name>]

# Load session
claude-flow pair --load <session-id>

# Export session
claude-flow pair --export <session-id> [--format json|md]

# Generate report
claude-flow pair --report <session-id>
后台会话
# Start in background
claude-flow pair --start --background

# Monitor background session
claude-flow pair --monitor

# Attach to background session
claude-flow pair --attach <session-id>

# End background session
claude-flow pair --end <session-id>
高级功能
自定义命令

在配置中定义:

{
  "customCommands": {
    "tdd": "/test-gen && /test --watch",
    "full-review": "/lint --fix && /test && /review --strict",
    "quick-fix": "/suggest --type fix && /implement && /test"
  }
}

使用自定义命令:

/custom tdd
/custom full-review
命令串联
/test && /commit && /push
/lint --fix && /test && /review --strict
会话录制
# Start with recording
claude-flow pair --start --record

# Replay session
claude-flow pair --replay <session-id>

# Session analytics
claude-flow pair --analytics <session-id>
集成选项

与 Git 集成:

claude-flow pair --start --git --auto-commit

与 CI/CD 集成:

claude-flow pair --start --ci --non-interactive

与 IDE 集成:

claude-flow pair --start --ide vscode
最佳实践
会话实践
  1. 明确目标 - 预先定义会话目标
  2. 选择合适模式 - 根据任务类型选择
  3. 启用验证 - 用于关键代码路径
  4. 定期测试 - 持续保持质量
  5. 会话笔记 - 记录重要决策
  6. 定期休息 - 每 45-60 分钟休息一次
代码实践
  1. 尽早测试 - 每次更改后运行测试
  2. 提交前验证 - 检查真实性分数
  3. 审查安全性 - 敏感代码务必审查
  4. 分析性能 - 使用 /perf 进行优化
  5. 保存会话 - 适用于复杂工作
  6. 向 AI 学习 - 经常提问
模式选择
  • Driver 模式:学习或控制实现时
  • Navigator 模式:快速原型开发或生成时
  • Switch 模式:长会话、平衡协作时
  • TDD 模式:通过测试构建时
  • Review 模式:注重质量时
  • Mentor 模式:优先学习时
  • Debug 模式:修复问题时
故障排除
会话无法启动
  • 检查 Agent 是否可用
  • 验证配置文件语法
  • 确保工作区干净
  • 检查日志文件
会话断开
  • 使用 --recover 恢复
  • 检查网络连接
  • 验证后台进程
  • 检查自动保存文件
性能不佳
  • 降低验证阈值
  • 禁用持续测试
  • 检查系统资源
  • 使用更轻量的 AI 模型
配置问题
  • 验证 JSON 语法
  • 检查文件权限
  • 检查优先级顺序(CLI > env > project > user > global)
  • 运行 claude-flow pair config validate
质量指标
真实性分数阈值
Error:   < 0.90 ❌
Warning: 0.90 - 0.95 ⚠️
Good:    0.95 - 0.98 ✅
Excellent: > 0.98 🌟
覆盖率阈值
Error:   < 70% ❌
Warning: 70% - 80% ⚠️
Good:    80% - 90% ✅
Excellent: > 90% 🌟
复杂度阈值
Error:   > 15 ❌
Warning: 10 - 15 ⚠️
Good:    5 - 10 ✅
Excellent: < 5 🌟
环境变量

通过环境变量覆盖配置:

export CLAUDE_PAIR_MODE=driver
export CLAUDE_PAIR_VERIFY=true
export CLAUDE_PAIR_THRESHOLD=0.98
export CLAUDE_PAIR_AGENT=senior-dev
export CLAUDE_PAIR_AUTO_TEST=true
命令历史记录

浏览历史记录:

  • ↑/↓ - 浏览命令历史记录
  • Ctrl+R - 搜索命令历史记录
  • !! - 重复上一条命令
  • !<n> - 运行历史记录中的第 n 条命令
键盘快捷键(可配置)

默认快捷键:

{
  "shortcuts": {
    "switch": "ctrl+shift+s",
    "suggest": "ctrl+space",
    "review": "ctrl+r",
    "test": "ctrl+t"
  }
}
相关命令
  • claude-flow pair --help - 显示帮助
  • claude-flow pair config - 管理配置
  • claude-flow pair profile - 管理配置文件
  • claude-flow pair templates - 列出模板
  • claude-flow pair agents - 列出可用 Agent

评论

支持 Markdown