Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | /** * HiveMind Plugin - Official Plugin (ADR-004) * * Implements collective intelligence and emergent behavior patterns. * Part of the official plugin collection. * * @module v3/shared/plugins/official/hive-mind */ import type { ClaudeFlowPlugin, PluginContext, PluginConfig } from '../types.js'; import { HookEvent, HookPriority, type TaskInfo } from '../../hooks/index.js'; /** * HiveMind configuration */ export interface HiveMindConfig extends PluginConfig { consensusThreshold: number; // Minimum agreement for decisions (0-1) collectiveMemoryEnabled: boolean; emergentBehaviorEnabled: boolean; maxVotingRounds: number; decisionTimeout: number; // ms } /** * Collective decision */ export interface CollectiveDecision { id: string; question: string; votes: Map<string, { agentId: string; vote: string; confidence: number }>; consensus?: string; consensusConfidence: number; timestamp: Date; } /** * Emergent pattern */ export interface EmergentPattern { id: string; type: string; description: string; contributors: string[]; strength: number; discoveredAt: Date; } /** * HiveMind Plugin Implementation */ export class HiveMindPlugin implements ClaudeFlowPlugin { readonly id = 'hive-mind'; readonly name = 'HiveMind Collective Intelligence'; readonly version = '1.0.0'; readonly description = 'Collective intelligence with consensus mechanisms and emergent behavior'; private context?: PluginContext; private config: HiveMindConfig; private decisions: Map<string, CollectiveDecision> = new Map(); private patterns: Map<string, EmergentPattern> = new Map(); private collectiveMemory: Map<string, unknown> = new Map(); constructor(config?: Partial<HiveMindConfig>) { this.config = { enabled: true, consensusThreshold: 0.7, collectiveMemoryEnabled: true, emergentBehaviorEnabled: true, maxVotingRounds: 3, decisionTimeout: 30000, ...config, }; } async initialize(context: PluginContext): Promise<void> { this.context = context; // Register hooks for collective behavior context.hooks?.register( HookEvent.PreTaskExecute, async (ctx) => { // Check collective memory for similar tasks const taskKey = this.generateTaskKey(ctx.task); const previous = this.collectiveMemory.get(taskKey); if (previous && ctx.metadata) { ctx.metadata.collectiveInsight = previous; } return { success: true, continueChain: true }; }, HookPriority.Normal, { name: 'hive-mind-pre-task' } ); context.hooks?.register( HookEvent.PostTaskComplete, async (ctx) => { // Store result in collective memory if (this.config.collectiveMemoryEnabled && ctx.task) { const taskInfo = ctx.task; this.collectiveMemory.set(taskInfo.id, { result: ctx.metadata?.result, timestamp: new Date(), agentId: ctx.agent?.id, }); } // Detect emergent patterns if (this.config.emergentBehaviorEnabled && ctx.task) { this.detectEmergentPatterns(ctx.task); } return { success: true, continueChain: true }; }, HookPriority.Normal, { name: 'hive-mind-post-task' } ); } async shutdown(): Promise<void> { this.decisions.clear(); this.patterns.clear(); this.collectiveMemory.clear(); this.context = undefined; } // ============================================================================ // Collective Decision Making // ============================================================================ /** * Request a collective decision from the swarm */ async requestDecision(question: string, options: string[]): Promise<CollectiveDecision> { const decision: CollectiveDecision = { id: `decision-${Date.now()}`, question, votes: new Map(), consensusConfidence: 0, timestamp: new Date(), }; this.decisions.set(decision.id, decision); // In a real implementation, this would broadcast to agents // For now, simulate with placeholder votes for (let i = 0; i < options.length && i < 3; i++) { decision.votes.set(`agent-${i}`, { agentId: `agent-${i}`, vote: options[i % options.length], confidence: 0.7 + Math.random() * 0.3, }); } // Calculate consensus const voteCounts = new Map<string, number>(); for (const vote of decision.votes.values()) { voteCounts.set(vote.vote, (voteCounts.get(vote.vote) ?? 0) + vote.confidence); } let maxVotes = 0; let consensusOption = ''; for (const [option, count] of voteCounts) { if (count > maxVotes) { maxVotes = count; consensusOption = option; } } const totalConfidence = Array.from(decision.votes.values()).reduce( (sum, v) => sum + v.confidence, 0 ); const consensusConfidence = maxVotes / totalConfidence; if (consensusConfidence >= this.config.consensusThreshold) { decision.consensus = consensusOption; decision.consensusConfidence = consensusConfidence; } return decision; } /** * Submit a vote for a decision */ submitVote(decisionId: string, agentId: string, vote: string, confidence: number): boolean { const decision = this.decisions.get(decisionId); if (!decision) return false; decision.votes.set(agentId, { agentId, vote, confidence }); this.recalculateConsensus(decision); return true; } /** * Get decision result */ getDecision(decisionId: string): CollectiveDecision | undefined { return this.decisions.get(decisionId); } // ============================================================================ // Emergent Behavior Detection // ============================================================================ /** * Detect emergent patterns from agent behavior */ private detectEmergentPatterns(taskData: TaskInfo): void { // Analyze task patterns const type = taskData.description?.split(' ')[0] ?? 'unknown'; const patternKey = `pattern-${type}`; const existing = this.patterns.get(patternKey); if (existing) { existing.strength += 0.1; if (!existing.contributors.includes(String(taskData.agentId))) { existing.contributors.push(String(taskData.agentId)); } } else if (this.collectiveMemory.size > 5) { // Only create patterns after enough collective memory this.patterns.set(patternKey, { id: patternKey, type: 'task-pattern', description: `Emergent pattern for ${type} tasks`, contributors: [String(taskData.agentId)], strength: 0.5, discoveredAt: new Date(), }); } } /** * Get emergent patterns */ getEmergentPatterns(): EmergentPattern[] { return Array.from(this.patterns.values()).filter((p) => p.strength > 0.5); } // ============================================================================ // Collective Memory // ============================================================================ /** * Store in collective memory */ storeCollective(key: string, value: unknown): void { this.collectiveMemory.set(key, { value, timestamp: new Date(), accessCount: 0, }); } /** * Retrieve from collective memory */ retrieveCollective(key: string): unknown { const entry = this.collectiveMemory.get(key) as any; if (entry) { entry.accessCount++; return entry.value; } return undefined; } /** * Get collective memory statistics */ getCollectiveStats(): { totalEntries: number; patterns: number; decisions: number; topPatterns: EmergentPattern[]; } { return { totalEntries: this.collectiveMemory.size, patterns: this.patterns.size, decisions: this.decisions.size, topPatterns: this.getEmergentPatterns().slice(0, 5), }; } // ============================================================================ // Private Helpers // ============================================================================ private generateTaskKey(taskData: TaskInfo | undefined): string { if (!taskData) return 'unknown'; return `${taskData.description || 'task'}-${JSON.stringify(taskData.metadata ?? {})}`.slice(0, 100); } private recalculateConsensus(decision: CollectiveDecision): void { const voteCounts = new Map<string, number>(); let totalConfidence = 0; for (const vote of decision.votes.values()) { voteCounts.set(vote.vote, (voteCounts.get(vote.vote) ?? 0) + vote.confidence); totalConfidence += vote.confidence; } let maxVotes = 0; let consensusOption = ''; for (const [option, count] of voteCounts) { if (count > maxVotes) { maxVotes = count; consensusOption = option; } } const consensusConfidence = totalConfidence > 0 ? maxVotes / totalConfidence : 0; if (consensusConfidence >= this.config.consensusThreshold) { decision.consensus = consensusOption; decision.consensusConfidence = consensusConfidence; } else { decision.consensus = undefined; decision.consensusConfidence = consensusConfidence; } } } /** * Factory function */ export function createHiveMindPlugin(config?: Partial<HiveMindConfig>): HiveMindPlugin { return new HiveMindPlugin(config); } |