1use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11#[derive(Debug, Clone)]
13pub struct CollectiveIntelligence {
14 pub groups: HashMap<String, OrganismGroup>,
16 pub active_decisions: Vec<CollectiveDecision>,
18 pub swarm_behaviors: Vec<SwarmBehavior>,
20 pub collective_memory: CollectiveMemory,
22 pub intelligence_metrics: IntelligenceMetrics,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct OrganismGroup {
29 pub group_id: String,
31 pub members: Vec<String>,
33 pub purpose: String,
35 pub intelligence_level: f64,
37 pub cohesion: f64,
39 pub created_at: u64,
41 pub performance_history: Vec<GroupPerformance>,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct CollectiveDecision {
48 pub decision_id: String,
50 pub question: String,
52 pub participants: Vec<String>,
54 pub options: Vec<DecisionOption>,
56 pub algorithm: DecisionAlgorithm,
58 pub status: DecisionStatus,
60 pub result: Option<String>,
62 pub confidence: f64,
64 pub timestamp: u64,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct DecisionOption {
71 pub option_id: String,
73 pub description: String,
75 pub votes: Vec<Vote>,
77 pub weight: f64,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Vote {
84 pub organism_id: String,
86 pub strength: f64,
88 pub confidence: f64,
90 pub timestamp: u64,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum DecisionAlgorithm {
97 Majority,
99 WeightedByFitness,
101 Consensus,
103 SwarmIntelligence,
105 NeuralNetwork,
107}
108
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub enum DecisionStatus {
112 Proposed,
114 Voting,
116 Decided,
118 Cancelled,
120 Executing,
122 Complete,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct SwarmBehavior {
129 pub behavior_id: String,
131 pub name: String,
133 pub behavior_type: SwarmBehaviorType,
135 pub participants: Vec<String>,
137 pub parameters: HashMap<String, f64>,
139 pub effectiveness: f64,
141 pub created_at: u64,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
147pub enum SwarmBehaviorType {
148 Flocking,
150 Foraging,
152 ProblemSolving,
154 InformationSharing,
156 CoordinatedEvolution,
158 Defense,
160 Exploration,
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct CollectiveMemory {
167 pub knowledge_base: HashMap<String, SharedKnowledge>,
169 pub experiences: Vec<CollectiveExperience>,
171 pub wisdom: Vec<CollectiveWisdom>,
173 pub consolidation_rules: Vec<ConsolidationRule>,
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct SharedKnowledge {
180 pub knowledge_id: String,
182 pub content: String,
184 pub contributors: Vec<String>,
186 pub reliability: f64,
188 pub age: u64,
190 pub access_count: u64,
192}
193
194#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct CollectiveExperience {
197 pub experience_id: String,
199 pub description: String,
201 pub participants: Vec<String>,
203 pub outcome: ExperienceOutcome,
205 pub lessons: Vec<String>,
207 pub timestamp: u64,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
213pub enum ExperienceOutcome {
214 Success,
215 Failure,
216 Partial,
217 Learning,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct CollectiveWisdom {
223 pub statement: String,
225 pub supporting_experiences: Vec<String>,
227 pub confidence: f64,
229 pub age: u64,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct ConsolidationRule {
236 pub name: String,
238 pub condition: String,
240 pub action: String,
242 pub priority: u32,
244}
245
246#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct GroupPerformance {
249 pub timestamp: u64,
251 pub task_completion_rate: f64,
253 pub decision_accuracy: f64,
255 pub coordination_efficiency: f64,
257 pub innovation_rate: f64,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct IntelligenceMetrics {
264 pub total_groups: usize,
266 pub active_decisions: usize,
268 pub successful_decisions: u64,
270 pub failed_decisions: u64,
272 pub avg_decision_time: f64,
274 pub collective_iq: f64,
276}
277
278impl CollectiveIntelligence {
279 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 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 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 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 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 Err(CollectiveError::AlgorithmNotImplemented)
423 }
424 }
425 } else {
426 Err(CollectiveError::DecisionNotFound(decision_id.to_string()))
427 }
428 }
429
430 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#[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 ci.active_decisions[0].status = DecisionStatus::Voting;
539 let option_id = ci.active_decisions[0].options[0].option_id.clone();
540
541 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 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}