关于 Pair Programming
Pair Programming 是 Ruflo CLI 的 AI 编程协作技能,适合希望以结构化方式结对开发的开发者。它支持角色模式、验证、测试、代码审查和会话持久化。
主要功能
- 01驾驶员与导航员角色管理
- 02七种协作模式
- 03质量评分与失败回滚
- 04测试生成与覆盖率跟踪
- 05会话保存与恢复
适用场景
- 01以 TDD 方式实现功能
- 02审查变更中的安全与性能问题
- 03通过引导式分析调试故障
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ruvnet/ ruflo --skill pair-programming安装后在 Claude Code 中输入/pair-programming确认已加载。
详细介绍
结对编程
通过智能角色管理、实时质量监控和全面的开发工作流,实现 AI 协作结对编程。
此技能的功能
此技能提供专业的结对编程能力,并借助 AI 助手,支持多种协作模式、持续验证和集成测试。它管理 driver$navigator 角色、执行实时代码审查、跟踪质量指标,并通过 truth-score 验证确保高标准。
主要功能:
- 多种模式:Driver、Navigator、Switch、TDD、Review、Mentor、Debug
- 实时验证:自动质量评分,失败时回滚
- 角色管理:在 driver$navigator 角色之间无缝切换
- 测试集成:自动生成测试、跟踪覆盖率、持续测试
- 代码审查:安全扫描、性能分析、最佳实践检查
- 会话持久化:自动保存、恢复、导出和共享
Claude Code 如何使用此技能
CLI 保存会话状态;Claude Code 读取该状态。这里没有可供输入的 REPL。
- 每轮开始时运行
ruflo pair status --json。如果active为false,则此技能处于休眠状态。 - 遵循
mode和aiRole。作为 driver 时,你编写代码,由人类进行审查。作为 navigator 时,你负责审查并提出建议,除非收到请求,否则不进行编辑。tdd、review、mentor和debug会按下文所述进一步调整此行为。 - 当
switchDue为true时,运行ruflo pair switch,宣布角色互换,然后以新角色继续。 - 使用
ruflo pair mode <mode>在会话中途更改模式。人类也可以在自己的 shell 中运行相同的命令。
状态保存在 .claude-flow/sessions/pair/current.json 中。ruflo pair end 会将其归档到同一目录下的 history.jsonl。
前提条件
必需:
- 已安装 Ruflo CLI(
npm install -g ruflo),该工具提供ruflo pair命令 - Git 仓库(可选,但建议使用)
建议:
- 测试框架(Jest、pytest 等)
- 已配置的 Linter(ESLint、pylint 等)
- 代码格式化工具(Prettier、Black 等)
快速开始
基本会话
# Start simple pair programming
ruflo pair start
TDD 会话
# Test-driven development
ruflo pair start \
--mode tdd \
--test-first \
--coverage 90
完整指南
会话控制命令
开始会话
# Basic start
ruflo pair start
# Expert refactoring session
ruflo pair start \
--agent senior-dev \
--focus refactor \
--verify \
--threshold 0.98
# Debugging session
ruflo pair start \
--agent debugger-expert \
--focus debug \
--review
# Learning session
ruflo pair start \
--mode mentor \
--pace slow \
--examples
会话管理
# Check status
ruflo pair status
# View history
ruflo pair history
# Pause session
$pause [--reason <reason>]
# Resume session
$resume
# End session
ruflo pair end [--save] [--report]
可用模式
Driver 模式
你编写代码,AI 提供指导。
ruflo pair start --mode driver
你的职责:
- 编写实际代码
- 实现解决方案
- 立即做出决策
- 处理语法和结构
AI Navigator:
- 提供战略指导
- 发现潜在问题
- 提出改进建议
- 实时审查
- 跟踪整体方向
适用于:
- 学习新模式
- 实现熟悉的功能
- 快速迭代
- 动手调试
命令:
$suggest - Get implementation suggestions
$review - Request code review
$explain - Ask for explanations
$optimize - Request optimization ideas
$patterns - Get pattern recommendations
Navigator 模式
AI 编写代码,你提供方向。
ruflo pair start --mode navigator
你的职责:
- 提供高层次指导
- 审查生成的代码
- 做出架构决策
- 确保满足业务需求
AI Driver:
- 编写实现代码
- 处理语法细节
- 落实你的指导
- 管理样板代码
- 执行重构
适用于:
- 快速原型设计
- 生成样板代码
- 学习 AI 的模式
- 探索解决方案
命令:
$implement - Direct implementation
$refactor - Request refactoring
$test - Generate tests
$document - Add documentation
$alternate - See alternative approaches
Switch 模式
按指定间隔自动交替角色。
# Default 10-minute intervals
ruflo pair start --mode switch
# 5-minute intervals (rapid)
ruflo pair start --mode switch --interval 5m
# 15-minute intervals (deep focus)
ruflo pair start --mode switch --interval 15m
交接流程:
- 切换前 30 秒发出提醒
- 当前 driver 完成当前思路
- 生成上下文摘要
- 平稳交换角色
- 新 driver 继续工作
适用于:
- 均衡协作
- 知识共享
- 复杂功能
- 长时间会话
专项模式
TDD 模式 - 测试驱动开发:
ruflo pair start \
--mode tdd \
--test-first \
--coverage 100
工作流:编写失败的测试 → 实现 → 重构 → 重复
Review 模式 - 持续代码审查:
ruflo pair start \
--mode review \
--strict \
--security
功能:实时反馈、安全扫描、性能分析
Mentor 模式 - 以学习为重点:
ruflo pair start \
--mode mentor \
--explain-all \
--pace slow
功能:详细讲解、分步指导、模式教学
Debug 模式 - 问题解决:
ruflo 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
ruflo pair config set defaultMode switch
ruflo pair config set verification.threshold 0.98
# Get configuration
ruflo pair config get
ruflo pair config get defaultMode
# Export/Import
ruflo pair config export > config.json
ruflo pair config import config.json
# Reset
ruflo pair config reset
配置文件管理
创建可重复使用的配置文件:
# Create profile
ruflo pair profile create refactoring \
--mode driver \
--verify true \
--threshold 0.98 \
--focus refactor
# Use profile
ruflo pair start --profile refactoring
# List profiles
ruflo 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
ruflo 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:修复 Bug
调试 Node.js 中的内存泄漏:
# Session setup
ruflo 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
ruflo 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
ruflo 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
ruflo 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
ruflo 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
ruflo pair --template refactor
# Focus: Code improvement
# Verification: High (0.98)
# Testing: After each change
# Review: Continuous
# Feature template
ruflo pair --template feature
# Focus: Implementation
# Verification: Standard (0.95)
# Testing: On completion
# Review: Pre-commit
# Debug template
ruflo pair --template debug
# Focus: Problem solving
# Verification: Moderate (0.90)
# Testing: Regression tests
# Review: Root cause
# Learning template
ruflo pair --template learn
# Mode: Mentor
# Pace: Slow
# Explanations: Detailed
# Examples: Many
会话管理
会话状态
ruflo 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
会话历史记录
ruflo 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
ruflo pair --save [--name <name>]
# Load session
ruflo pair --load <session-id>
# Export session
ruflo pair --export <session-id> [--format json|md]
# Generate report
ruflo pair --report <session-id>
后台会话
# Start in background
ruflo pair start --background
# Monitor background session
ruflo pair --monitor
# Attach to background session
ruflo pair --attach <session-id>
# End background session
ruflo 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
ruflo pair start --record
# Replay session
ruflo pair --replay <session-id>
# Session analytics
ruflo pair --analytics <session-id>
集成选项
与 Git 集成:
ruflo pair start --git --auto-commit
与 CI/CD 集成:
ruflo pair start --ci --non-interactive
与 IDE 集成:
ruflo pair start --ide vscode
最佳实践
会话实践
- 明确目标 - 预先定义会话目标
- 选择合适的模式 - 根据任务类型选择
- 启用验证 - 用于关键代码路径
- 定期测试 - 持续保持质量
- 会话笔记 - 记录重要决策
- 定期休息 - 每 45-60 分钟休息一次
代码实践
- 尽早测试 - 每次更改后运行测试
- 提交前验证 - 检查真实性评分
- 审查安全性 - 敏感代码务必审查
- 分析性能 - 使用
$perf进行优化 - 保存会话 - 适用于复杂工作
- 向 AI 学习 - 经常提问
模式选择
- Driver 模式:学习时使用,控制实现过程
- Navigator 模式:用于快速原型设计和生成
- Switch 模式:适用于长时间会话,平衡协作
- TDD 模式:通过测试构建
- Review 模式:侧重质量
- Mentor 模式:优先学习
- Debug 模式:修复问题
故障排除
会话无法启动
- 检查 Agent 是否可用
- 验证配置文件语法
- 确保工作区干净
- 查看日志文件
会话断开连接
- 使用
--recover恢复 - 检查网络连接
- 验证后台进程
- 查看自动保存文件
性能不佳
- 降低验证阈值
- 禁用持续测试
- 检查系统资源
- 使用更轻量的 AI 模型
配置问题
- 验证 JSON 语法
- 检查文件权限
- 查看优先级顺序(CLI > env > project > user > global)
- 运行
ruflo 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"
}
}
相关命令
ruflo pair --help- 显示帮助ruflo pair config- 管理配置ruflo pair profile- 管理配置文件ruflo pair templates- 列出模板ruflo pair agents- 列出可用的 Agent