genesis_protocol/
collective.rs

1//! 🌐 Collective Intelligence System
2//!
3//! This module implements collective intelligence capabilities that enable
4//! groups of TRON organisms to exhibit emergent swarm behavior and make
5//! collective decisions that surpass individual intelligence.
6
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11/// Collective intelligence coordinator
12#[derive(Debug, Clone)]
13pub struct CollectiveIntelligence {
14    /// Registered organism groups
15    pub groups: HashMap<String, OrganismGroup>,
16    /// Active collective decisions
17    pub active_decisions: Vec<CollectiveDecision>,
18    /// Swarm behaviors
19    pub swarm_behaviors: Vec<SwarmBehavior>,
20    /// Collective memory
21    pub collective_memory: CollectiveMemory,
22    /// Intelligence metrics
23    pub intelligence_metrics: IntelligenceMetrics,
24}
25
26/// Group of organisms working together
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct OrganismGroup {
29    /// Group identifier
30    pub group_id: String,
31    /// Group members
32    pub members: Vec<String>,
33    /// Group purpose/goal
34    pub purpose: String,
35    /// Group intelligence level
36    pub intelligence_level: f64,
37    /// Group cohesion strength
38    pub cohesion: f64,
39    /// Group creation time
40    pub created_at: u64,
41    /// Group performance history
42    pub performance_history: Vec<GroupPerformance>,
43}
44
45/// Collective decision making
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct CollectiveDecision {
48    /// Decision ID
49    pub decision_id: String,
50    /// Decision question/problem
51    pub question: String,
52    /// Participating organisms
53    pub participants: Vec<String>,
54    /// Voting options
55    pub options: Vec<DecisionOption>,
56    /// Decision algorithm used
57    pub algorithm: DecisionAlgorithm,
58    /// Decision status
59    pub status: DecisionStatus,
60    /// Final result
61    pub result: Option<String>,
62    /// Confidence in decision
63    pub confidence: f64,
64    /// Decision timestamp
65    pub timestamp: u64,
66}
67
68/// Decision option
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct DecisionOption {
71    /// Option ID
72    pub option_id: String,
73    /// Option description
74    pub description: String,
75    /// Votes for this option
76    pub votes: Vec<Vote>,
77    /// Option weight/score
78    pub weight: f64,
79}
80
81/// Individual vote
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Vote {
84    /// Voting organism
85    pub organism_id: String,
86    /// Vote strength (0.0-1.0)
87    pub strength: f64,
88    /// Confidence in vote
89    pub confidence: f64,
90    /// Vote timestamp
91    pub timestamp: u64,
92}
93
94/// Decision algorithms
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum DecisionAlgorithm {
97    /// Simple majority voting
98    Majority,
99    /// Weighted voting by fitness
100    WeightedByFitness,
101    /// Consensus building
102    Consensus,
103    /// Swarm intelligence
104    SwarmIntelligence,
105    /// Artificial neural network
106    NeuralNetwork,
107}
108
109/// Decision status
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub enum DecisionStatus {
112    /// Decision is being proposed
113    Proposed,
114    /// Voting is in progress
115    Voting,
116    /// Decision has been made
117    Decided,
118    /// Decision was cancelled
119    Cancelled,
120    /// Decision is being executed
121    Executing,
122    /// Decision execution complete
123    Complete,
124}
125
126/// Swarm behavior patterns
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct SwarmBehavior {
129    /// Behavior ID
130    pub behavior_id: String,
131    /// Behavior name
132    pub name: String,
133    /// Behavior type
134    pub behavior_type: SwarmBehaviorType,
135    /// Participating organisms
136    pub participants: Vec<String>,
137    /// Behavior parameters
138    pub parameters: HashMap<String, f64>,
139    /// Behavior effectiveness
140    pub effectiveness: f64,
141    /// Behavior creation time
142    pub created_at: u64,
143}
144
145/// Types of swarm behaviors
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub enum SwarmBehaviorType {
148    /// Flocking/herding behavior
149    Flocking,
150    /// Foraging for resources
151    Foraging,
152    /// Collective problem solving
153    ProblemSolving,
154    /// Information sharing
155    InformationSharing,
156    /// Coordinated evolution
157    CoordinatedEvolution,
158    /// Defensive behavior
159    Defense,
160    /// Exploration behavior
161    Exploration,
162}
163
164/// Collective memory system
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct CollectiveMemory {
167    /// Shared knowledge base
168    pub knowledge_base: HashMap<String, SharedKnowledge>,
169    /// Collective experiences
170    pub experiences: Vec<CollectiveExperience>,
171    /// Wisdom accumulated over time
172    pub wisdom: Vec<CollectiveWisdom>,
173    /// Memory consolidation rules
174    pub consolidation_rules: Vec<ConsolidationRule>,
175}
176
177/// Shared knowledge entry
178#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct SharedKnowledge {
180    /// Knowledge ID
181    pub knowledge_id: String,
182    /// Knowledge content
183    pub content: String,
184    /// Contributing organisms
185    pub contributors: Vec<String>,
186    /// Knowledge reliability
187    pub reliability: f64,
188    /// Knowledge age
189    pub age: u64,
190    /// Times knowledge was accessed
191    pub access_count: u64,
192}
193
194/// Collective experience
195#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct CollectiveExperience {
197    /// Experience ID
198    pub experience_id: String,
199    /// Experience description
200    pub description: String,
201    /// Participants
202    pub participants: Vec<String>,
203    /// Experience outcome
204    pub outcome: ExperienceOutcome,
205    /// Lessons learned
206    pub lessons: Vec<String>,
207    /// Experience timestamp
208    pub timestamp: u64,
209}
210
211/// Experience outcome
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub enum ExperienceOutcome {
214    Success,
215    Failure,
216    Partial,
217    Learning,
218}
219
220/// Collective wisdom
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct CollectiveWisdom {
223    /// Wisdom statement
224    pub statement: String,
225    /// Supporting experiences
226    pub supporting_experiences: Vec<String>,
227    /// Wisdom confidence
228    pub confidence: f64,
229    /// Wisdom age
230    pub age: u64,
231}
232
233/// Memory consolidation rules
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct ConsolidationRule {
236    /// Rule name
237    pub name: String,
238    /// Rule condition
239    pub condition: String,
240    /// Rule action
241    pub action: String,
242    /// Rule priority
243    pub priority: u32,
244}
245
246/// Group performance metrics
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct GroupPerformance {
249    /// Performance measurement time
250    pub timestamp: u64,
251    /// Task completion rate
252    pub task_completion_rate: f64,
253    /// Decision accuracy
254    pub decision_accuracy: f64,
255    /// Coordination efficiency
256    pub coordination_efficiency: f64,
257    /// Innovation rate
258    pub innovation_rate: f64,
259}
260
261/// Intelligence metrics
262#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct IntelligenceMetrics {
264    /// Total groups managed
265    pub total_groups: usize,
266    /// Active decisions
267    pub active_decisions: usize,
268    /// Successful decisions
269    pub successful_decisions: u64,
270    /// Failed decisions
271    pub failed_decisions: u64,
272    /// Average decision time
273    pub avg_decision_time: f64,
274    /// Collective intelligence score
275    pub collective_iq: f64,
276}
277
278impl CollectiveIntelligence {
279    /// Create new collective intelligence system
280    pub fn new() -> Result<Self, CollectiveError> {
281        Ok(CollectiveIntelligence {
282            groups: HashMap::new(),
283            active_decisions: Vec::new(),
284            swarm_behaviors: Vec::new(),
285            collective_memory: CollectiveMemory::new(),
286            intelligence_metrics: IntelligenceMetrics::new(),
287        })
288    }
289
290    /// Create new organism group
291    pub fn create_group(&mut self, members: Vec<String>, purpose: String) -> Result<String, CollectiveError> {
292        let group_id = format!("group_{}", uuid::Uuid::new_v4());
293        
294        let group = OrganismGroup {
295            group_id: group_id.clone(),
296            members,
297            purpose,
298            intelligence_level: 0.5,
299            cohesion: 0.6,
300            created_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
301            performance_history: Vec::new(),
302        };
303        
304        self.groups.insert(group_id.clone(), group);
305        self.intelligence_metrics.total_groups += 1;
306        
307        Ok(group_id)
308    }
309
310    /// Initiate collective decision
311    pub fn initiate_decision(
312        &mut self,
313        question: String,
314        participants: Vec<String>,
315        options: Vec<String>,
316        algorithm: DecisionAlgorithm,
317    ) -> Result<String, CollectiveError> {
318        let decision_id = format!("decision_{}", uuid::Uuid::new_v4());
319        
320        let decision_options: Vec<DecisionOption> = options
321            .into_iter()
322            .map(|desc| DecisionOption {
323                option_id: uuid::Uuid::new_v4().to_string(),
324                description: desc,
325                votes: Vec::new(),
326                weight: 0.0,
327            })
328            .collect();
329        
330        let decision = CollectiveDecision {
331            decision_id: decision_id.clone(),
332            question,
333            participants,
334            options: decision_options,
335            algorithm,
336            status: DecisionStatus::Proposed,
337            result: None,
338            confidence: 0.0,
339            timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
340        };
341        
342        self.active_decisions.push(decision);
343        self.intelligence_metrics.active_decisions += 1;
344        
345        Ok(decision_id)
346    }
347
348    /// Cast vote in collective decision
349    pub fn cast_vote(
350        &mut self,
351        decision_id: &str,
352        organism_id: &str,
353        option_id: &str,
354        strength: f64,
355        confidence: f64,
356    ) -> Result<(), CollectiveError> {
357        if let Some(decision) = self.active_decisions.iter_mut().find(|d| d.decision_id == decision_id) {
358            if decision.status != DecisionStatus::Voting {
359                return Err(CollectiveError::DecisionNotVoting);
360            }
361            
362            if let Some(option) = decision.options.iter_mut().find(|o| o.option_id == option_id) {
363                let vote = Vote {
364                    organism_id: organism_id.to_string(),
365                    strength,
366                    confidence,
367                    timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
368                };
369                
370                option.votes.push(vote);
371                option.weight += strength * confidence;
372                
373                Ok(())
374            } else {
375                Err(CollectiveError::OptionNotFound(option_id.to_string()))
376            }
377        } else {
378            Err(CollectiveError::DecisionNotFound(decision_id.to_string()))
379        }
380    }
381
382    /// Finalize collective decision
383    pub fn finalize_decision(&mut self, decision_id: &str) -> Result<String, CollectiveError> {
384        if let Some(decision) = self.active_decisions.iter_mut().find(|d| d.decision_id == decision_id) {
385            match decision.algorithm {
386                DecisionAlgorithm::Majority => {
387                    let best_option = decision.options.iter()
388                        .max_by(|a, b| a.votes.len().cmp(&b.votes.len()));
389                    
390                    if let Some(option) = best_option {
391                        decision.result = Some(option.description.clone());
392                        decision.status = DecisionStatus::Decided;
393                        decision.confidence = option.votes.len() as f64 / decision.participants.len() as f64;
394                        
395                        self.intelligence_metrics.successful_decisions += 1;
396                        self.intelligence_metrics.active_decisions -= 1;
397                        
398                        Ok(option.description.clone())
399                    } else {
400                        Err(CollectiveError::NoVotesCast)
401                    }
402                },
403                DecisionAlgorithm::WeightedByFitness => {
404                    let best_option = decision.options.iter()
405                        .max_by(|a, b| a.weight.partial_cmp(&b.weight).unwrap());
406                    
407                    if let Some(option) = best_option {
408                        decision.result = Some(option.description.clone());
409                        decision.status = DecisionStatus::Decided;
410                        decision.confidence = option.weight / decision.options.len() as f64;
411                        
412                        self.intelligence_metrics.successful_decisions += 1;
413                        self.intelligence_metrics.active_decisions -= 1;
414                        
415                        Ok(option.description.clone())
416                    } else {
417                        Err(CollectiveError::NoVotesCast)
418                    }
419                },
420                _ => {
421                    // Other algorithms can be implemented as needed
422                    Err(CollectiveError::AlgorithmNotImplemented)
423                }
424            }
425        } else {
426            Err(CollectiveError::DecisionNotFound(decision_id.to_string()))
427        }
428    }
429
430    /// Get collective intelligence metrics
431    pub fn get_metrics(&self) -> IntelligenceMetrics {
432        self.intelligence_metrics.clone()
433    }
434}
435
436impl CollectiveMemory {
437    pub fn new() -> Self {
438        CollectiveMemory {
439            knowledge_base: HashMap::new(),
440            experiences: Vec::new(),
441            wisdom: Vec::new(),
442            consolidation_rules: Vec::new(),
443        }
444    }
445}
446
447impl IntelligenceMetrics {
448    pub fn new() -> Self {
449        IntelligenceMetrics {
450            total_groups: 0,
451            active_decisions: 0,
452            successful_decisions: 0,
453            failed_decisions: 0,
454            avg_decision_time: 0.0,
455            collective_iq: 100.0,
456        }
457    }
458}
459
460/// Collective intelligence errors
461#[derive(Debug, thiserror::Error)]
462pub enum CollectiveError {
463    #[error("Group not found: {0}")]
464    GroupNotFound(String),
465    #[error("Decision not found: {0}")]
466    DecisionNotFound(String),
467    #[error("Option not found: {0}")]
468    OptionNotFound(String),
469    #[error("Decision is not in voting state")]
470    DecisionNotVoting,
471    #[error("No votes cast")]
472    NoVotesCast,
473    #[error("Algorithm not implemented")]
474    AlgorithmNotImplemented,
475    #[error("Insufficient participants")]
476    InsufficientParticipants,
477    #[error("Group capacity exceeded")]
478    GroupCapacityExceeded,
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    #[test]
486    fn test_collective_intelligence_creation() {
487        let ci = CollectiveIntelligence::new().unwrap();
488        assert_eq!(ci.groups.len(), 0);
489        assert_eq!(ci.active_decisions.len(), 0);
490    }
491
492    #[test]
493    fn test_group_creation() {
494        let mut ci = CollectiveIntelligence::new().unwrap();
495        
496        let members = vec!["tron_1".to_string(), "tron_2".to_string()];
497        let group_id = ci.create_group(members.clone(), "Test Group".to_string()).unwrap();
498        
499        assert!(!group_id.is_empty());
500        assert!(ci.groups.contains_key(&group_id));
501        assert_eq!(ci.groups[&group_id].members, members);
502    }
503
504    #[test]
505    fn test_decision_initiation() {
506        let mut ci = CollectiveIntelligence::new().unwrap();
507        
508        let participants = vec!["tron_1".to_string(), "tron_2".to_string()];
509        let options = vec!["Option A".to_string(), "Option B".to_string()];
510        
511        let decision_id = ci.initiate_decision(
512            "Test Question".to_string(),
513            participants,
514            options,
515            DecisionAlgorithm::Majority,
516        ).unwrap();
517        
518        assert!(!decision_id.is_empty());
519        assert_eq!(ci.active_decisions.len(), 1);
520        assert_eq!(ci.active_decisions[0].options.len(), 2);
521    }
522
523    #[test]
524    fn test_voting_and_decision() {
525        let mut ci = CollectiveIntelligence::new().unwrap();
526        
527        let participants = vec!["tron_1".to_string(), "tron_2".to_string()];
528        let options = vec!["Option A".to_string(), "Option B".to_string()];
529        
530        let decision_id = ci.initiate_decision(
531            "Test Question".to_string(),
532            participants,
533            options,
534            DecisionAlgorithm::Majority,
535        ).unwrap();
536        
537        // Change status to voting
538        ci.active_decisions[0].status = DecisionStatus::Voting;
539        let option_id = ci.active_decisions[0].options[0].option_id.clone();
540        
541        // Cast votes
542        ci.cast_vote(&decision_id, "tron_1", &option_id, 1.0, 0.8).unwrap();
543        ci.cast_vote(&decision_id, "tron_2", &option_id, 0.8, 0.9).unwrap();
544        
545        // Finalize decision
546        let result = ci.finalize_decision(&decision_id).unwrap();
547        assert_eq!(result, "Option A");
548        
549        assert_eq!(ci.active_decisions[0].status, DecisionStatus::Decided);
550        assert!(ci.active_decisions[0].confidence > 0.0);
551    }
552}