关于 hive-mind-advanced
hive-mind-advanced 是 Claude Flow 多 Agent 协作系统的进阶技能,采用 Queen 主导架构、集体记忆和共识机制来分配任务并协调决策。
主要功能
- 01Queen 与专职 Worker 分层协作
- 02支持多数、加权和拜占庭共识
- 03跨 Agent 集体记忆与搜索
- 04自动分配任务并支持扩缩容
- 05会话检查点、暂停与恢复
适用场景
- 01协调多个 Agent 完成软件开发任务
- 02通过共识选择架构或实施方案
- 03在多个 Hive 间共享集体记忆
- 04暂停并恢复长期协作会话
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ruvnet/ ruflo --skill hive-mind-advanced安装后在 Claude Code 中输入/hive-mind-advanced确认已加载。
详细介绍
Hive Mind 高级技能
掌握先进的 Hive Mind 集体智能系统,运用 Queen 主导架构、拜占庭共识和集体记忆,实现复杂的多 Agent 协调。
概述
Hive Mind 系统代表了 Claude Flow 中多 Agent 协调的最高水平。它采用 Queen 主导的分层架构,由战略 Queen 协调器通过集体决策和共享记忆来指挥专业 Worker Agent。
核心概念
架构模式
Queen 主导的协调
- 战略 Queen Agent 负责统筹高级目标
- 战术 Queen 负责管理中级执行
- 自适应 Queen 根据性能动态调整策略
Worker 专业分工
- Researcher Agent:分析与调查
- Coder Agent:实现与开发
- Analyst Agent:数据处理与指标分析
- Tester Agent:质量保证与验证
- Architect Agent:系统设计与规划
- Reviewer Agent:代码审查与改进
- Optimizer Agent:性能提升
- Documenter Agent:生成文档
集体记忆系统
- 所有 Agent 共享的知识库
- 具备内存压力处理能力的 LRU 缓存
- 使用 WAL 模式进行 SQLite 持久化
- 记忆整合与关联
- 访问模式跟踪与优化
共识机制
多数共识 采用简单投票,票数最多的选项获胜。
加权共识 Queen 的投票权重为 3 倍,提供战略指导。
拜占庭容错 决策通过需要 2/3 多数,确保即使存在故障 Agent 也能达成稳健共识。
入门
1. 初始化 Hive Mind
# Basic initialization
npx claude-flow hive-mind init
# Force reinitialize
npx claude-flow hive-mind init --force
# Custom configuration
npx claude-flow hive-mind init --config hive-config.json
2. 启动一个 Swarm
# Basic spawn with objective
npx claude-flow hive-mind spawn "Build microservices architecture"
# Strategic queen type
npx claude-flow hive-mind spawn "Research AI patterns" --queen-type strategic
# Tactical queen with max workers
npx claude-flow hive-mind spawn "Implement API" --queen-type tactical --max-workers 12
# Adaptive queen with consensus
npx claude-flow hive-mind spawn "Optimize system" --queen-type adaptive --consensus byzantine
# Generate Claude Code commands
npx claude-flow hive-mind spawn "Build full-stack app" --claude
3. 监控状态
# Check hive mind status
npx claude-flow hive-mind status
# Get detailed metrics
npx claude-flow hive-mind metrics
# Monitor collective memory
npx claude-flow hive-mind memory
高级工作流
会话管理
创建和管理会话
# List active sessions
npx claude-flow hive-mind sessions
# Pause a session
npx claude-flow hive-mind pause <session-id>
# Resume a paused session
npx claude-flow hive-mind resume <session-id>
# Stop a running session
npx claude-flow hive-mind stop <session-id>
会话功能
- 自动创建检查点
- 跟踪进度并显示完成百分比
- 父子进程管理
- 记录事件的会话日志
- 导出$导入功能
建立共识
Hive Mind 通过结构化投票建立共识:
// Programmatic consensus building
const decision = await hiveMind.buildConsensus(
'Architecture pattern selection',
['microservices', 'monolith', 'serverless']
);
// Result includes:
// - decision: Winning option
// - confidence: Vote percentage
// - votes: Individual agent votes
共识算法
- 多数 - 简单的民主投票
- 加权 - Queen 拥有 3 倍投票权
- 拜占庭 - 需要 2/3 的绝对多数
集体记忆
存储知识
// Store in collective memory
await memory.store('api-patterns', {
rest: { pros: [...], cons: [...] },
graphql: { pros: [...], cons: [...] }
}, 'knowledge', { confidence: 0.95 });
记忆类型
knowledge:永久见解(无 TTL)context:会话上下文(TTL 为 1 小时)task:任务专用数据(TTL 为 30 分钟)result:执行结果(永久保存,经过压缩)error:错误日志(TTL 为 24 小时)metric:性能指标(TTL 为 1 小时)consensus:决策记录(永久保存)system:系统配置(永久保存)
搜索与检索
// Search memory by pattern
const results = await memory.search('api*', {
type: 'knowledge',
minConfidence: 0.8,
limit: 50
});
// Get related memories
const related = await memory.getRelated('api-patterns', 10);
// Build associations
await memory.associate('rest-api', 'authentication', 0.9);
任务分配
自动分配 Worker
系统会根据以下因素智能分配任务:
- 与 Agent 专业领域的关键词匹配
- 历史性能指标
- Worker 可用性和负载
- 任务复杂度分析
// Create task (auto-assigned)
const task = await hiveMind.createTask(
'Implement user authentication',
priority: 8,
{ estimatedDuration: 30000 }
);
自动扩缩容
// Configure auto-scaling
const config = {
autoScale: true,
maxWorkers: 12,
scaleUpThreshold: 2, // Pending tasks per idle worker
scaleDownThreshold: 2 // Idle workers above pending tasks
};
集成模式
与 Claude Code 集成
直接生成 Claude Code 启动命令:
npx claude-flow hive-mind spawn "Build REST API" --claude
输出:
Task("Queen Coordinator", "Orchestrate REST API development...", "coordinator")
Task("Backend Developer", "Implement Express routes...", "backend-dev")
Task("Database Architect", "Design PostgreSQL schema...", "code-analyzer")
Task("Test Engineer", "Create Jest test suite...", "tester")
与 SPARC 方法论集成
# Use hive mind for SPARC workflow
npx claude-flow sparc tdd "User authentication" --hive-mind
# Spawns:
# - Specification agent
# - Architecture agent
# - Coder agents
# - Tester agents
# - Reviewer agents
与 GitHub 集成
# Repository analysis with hive mind
npx claude-flow hive-mind spawn "Analyze repo quality" --objective "owner$repo"
# PR review coordination
npx claude-flow hive-mind spawn "Review PR #123" --queen-type tactical
性能优化
记忆优化
集体记忆系统包含高级优化功能:
LRU 缓存
- 可配置的缓存大小(默认:1000 个条目)
- 内存压力处理(默认:50MB)
- 自动淘汰最少使用的条目
数据库优化
- WAL(预写式日志)模式
- 64MB 缓存大小
- 256MB 内存映射
- 为常见查询使用预处理语句
- 自动执行 ANALYZE 和 OPTIMIZE
对象池化
- 查询结果池化
- 内存条目池化
- 降低垃圾回收压力
性能指标
// Get performance insights
const insights = hiveMind.getPerformanceInsights();
// Includes:
// - asyncQueue utilization
// - Batch processing stats
// - Success rates
// - Average processing times
// - Memory efficiency
任务执行
并行处理
- 批量生成 Agent(每批 5 个)
- 并发任务编排
- 异步操作优化
- 非阻塞任务分配
基准测试
- 批量生成速度提升 10-20 倍
- 整体速度提升 2.8-4.4 倍
- Token 用量减少 32.3%
- SWE-Bench 解决率达 84.8%
配置
Hive Mind 配置
{
"objective": "Build microservices",
"name": "my-hive",
"queenType": "strategic", // strategic | tactical | adaptive
"maxWorkers": 8,
"consensusAlgorithm": "byzantine", // majority | weighted | byzantine
"autoScale": true,
"memorySize": 100, // MB
"taskTimeout": 60, // minutes
"encryption": false
}
记忆配置
{
"maxSize": 100, // MB
"compressionThreshold": 1024, // bytes
"gcInterval": 300000, // 5 minutes
"cacheSize": 1000,
"cacheMemoryMB": 50,
"enablePooling": true,
"enableAsyncOperations": true
}
Hooks 集成
Hive Mind 与 Claude Flow hooks 集成,实现自动化:
任务前 Hooks
- 根据文件类型自动分配 Agent
- 验证目标复杂度
- 优化拓扑选择
- 缓存搜索模式
任务后 Hooks
- 自动格式化交付内容
- 训练神经模式
- 更新集体记忆
- 分析性能瓶颈
会话 Hooks
- 生成会话摘要
- 持久化检查点数据
- 跟踪全面的指标
- 恢复执行上下文
最佳实践
1. 选择合适的 Queen 类型
战略型 Queen——用于研究、规划和分析
npx claude-flow hive-mind spawn "Research ML frameworks" --queen-type strategic
战术型 Queen——用于实现和执行
npx claude-flow hive-mind spawn "Build authentication" --queen-type tactical
自适应型 Queen——用于优化和动态任务
npx claude-flow hive-mind spawn "Optimize performance" --queen-type adaptive
2. 利用共识机制
对关键决策使用共识机制:
- 架构模式选择
- 技术栈选择
- 实施方案
- 代码审查批准
- 发布就绪情况
3. 利用集体记忆
存储经验
// After successful pattern implementation
await memory.store('auth-pattern', {
approach: 'JWT with refresh tokens',
pros: ['Stateless', 'Scalable'],
cons: ['Token size', 'Revocation complexity'],
implementation: {...}
}, 'knowledge', { confidence: 0.95 });
构建关联
// Link related concepts
await memory.associate('jwt-auth', 'refresh-tokens', 0.9);
await memory.associate('jwt-auth', 'oauth2', 0.7);
4. 监控性能
# Regular status checks
npx claude-flow hive-mind status
# Track metrics
npx claude-flow hive-mind metrics
# Analyze memory usage
npx claude-flow hive-mind memory
5. 会话管理
频繁创建检查点
// Create checkpoints at key milestones
await sessionManager.saveCheckpoint(
sessionId,
'api-routes-complete',
{ completedRoutes: [...], remaining: [...] }
);
恢复会话
# Resume from any previous state
npx claude-flow hive-mind resume <session-id>
故障排除
记忆问题
内存使用率高
# Run garbage collection
npx claude-flow hive-mind memory --gc
# Optimize database
npx claude-flow hive-mind memory --optimize
# Export and clear
npx claude-flow hive-mind memory --export --clear
缓存命中率低
// Increase cache size in config
{
"cacheSize": 2000,
"cacheMemoryMB": 100
}
性能问题
任务分配缓慢
// Enable worker type caching
// The system caches best worker matches for 5 minutes
// Automatic - no configuration needed
队列利用率高
// Increase async queue concurrency
{
"asyncQueueConcurrency": 20 // Default: min(maxWorkers * 2, 20)
}
共识失败
未能达成共识(拜占庭故障)
# Switch to weighted consensus for more decisive results
npx claude-flow hive-mind spawn "..." --consensus weighted
# Or use simple majority
npx claude-flow hive-mind spawn "..." --consensus majority
高级主题
自定义工作者类型
在 .claude.agents/ 中定义专用工作者:
name: security-auditor
type: specialist
capabilities:
- vulnerability-scanning
- security-review
- penetration-testing
- compliance-checking
priority: high
神经模式训练
系统会基于成功模式进行训练:
// Automatic pattern learning
// Happens after successful task completion
// Stores in collective memory
// Improves future task matching
多 Hive 协调
同时运行多个 hive mind:
# Frontend hive
npx claude-flow hive-mind spawn "Build UI" --name frontend-hive
# Backend hive
npx claude-flow hive-mind spawn "Build API" --name backend-hive
# They share collective memory for coordination
导出/导入会话
# Export session for backup
npx claude-flow hive-mind export <session-id> --output backup.json
# Import session
npx claude-flow hive-mind import backup.json
API 参考
HiveMindCore
const hiveMind = new HiveMindCore({
objective: 'Build system',
queenType: 'strategic',
maxWorkers: 8,
consensusAlgorithm: 'byzantine'
});
await hiveMind.initialize();
await hiveMind.spawnQueen(queenData);
await hiveMind.spawnWorkers(['coder', 'tester']);
await hiveMind.createTask('Implement feature', 7);
const decision = await hiveMind.buildConsensus('topic', options);
const status = hiveMind.getStatus();
await hiveMind.shutdown();
CollectiveMemory
const memory = new CollectiveMemory({
swarmId: 'hive-123',
maxSize: 100,
cacheSize: 1000
});
await memory.store(key, value, type, metadata);
const data = await memory.retrieve(key);
const results = await memory.search(pattern, options);
const related = await memory.getRelated(key, limit);
await memory.associate(key1, key2, strength);
const stats = memory.getStatistics();
const analytics = memory.getAnalytics();
const health = await memory.healthCheck();
HiveMindSessionManager
const sessionManager = new HiveMindSessionManager();
const sessionId = await sessionManager.createSession(
swarmId, swarmName, objective, metadata
);
await sessionManager.saveCheckpoint(sessionId, name, data);
const sessions = await sessionManager.getActiveSessions();
const session = await sessionManager.getSession(sessionId);
await sessionManager.pauseSession(sessionId);
await sessionManager.resumeSession(sessionId);
await sessionManager.stopSession(sessionId);
await sessionManager.completeSession(sessionId);
示例
全栈开发
# Initialize hive mind
npx claude-flow hive-mind init
# Spawn full-stack hive
npx claude-flow hive-mind spawn "Build e-commerce platform" \
--queen-type strategic \
--max-workers 10 \
--consensus weighted \
--claude
# Output generates Claude Code commands:
# - Queen coordinator
# - Frontend developers (React)
# - Backend developers (Node.js)
# - Database architects
# - DevOps engineers
# - Security auditors
# - Test engineers
# - Documentation specialists
研究与分析
# Spawn research hive
npx claude-flow hive-mind spawn "Research GraphQL vs REST" \
--queen-type adaptive \
--consensus byzantine
# Researchers gather data
# Analysts process findings
# Queen builds consensus on recommendation
# Results stored in collective memory
代码审查
# Review coordination
npx claude-flow hive-mind spawn "Review PR #456" \
--queen-type tactical \
--max-workers 6
# Spawns:
# - Code analyzers
# - Security reviewers
# - Performance reviewers
# - Test coverage analyzers
# - Documentation reviewers
# - Consensus on approval$changes
技能进阶
初级
- 初始化 hive mind
- 生成基础群组
- 监控状态
- 使用多数共识
中级
- 配置 Queen 类型
- 实施会话管理
- 使用加权共识
- 访问集体记忆
- 启用自动扩缩容
高级
- 拜占庭容错
- 记忆优化
- 自定义工作者类型
- 多 Hive 协调
- 神经模式训练
- 会话导出$导入
- 性能调优
相关技能
swarm-orchestration:基础群组协调consensus-mechanisms:分布式决策memory-systems:高级记忆管理sparc-methodology:结构化开发工作流github-integration:仓库协调
参考资料
技能版本:1.0.0 最后更新:2025-10-19 维护者:Claude Flow 团队 许可证:MIT