genesis_protocol/
tron.rs

1//! 🤖 TRON Organisms - Living Digital Entities
2//!
3//! This module implements TRON (Transcendent Recursive Organism Network) organisms,
4//! which are the living digital entities at the heart of Genesis Protocol.
5//! Each TRON has its own DNA, lifecycle, neural connections, and adaptive behaviors.
6
7use crate::dna::DigitalDNA;
8use crate::neural::{NeuralMessage, Synapse, MessageType};
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::time::{SystemTime, UNIX_EPOCH};
12
13/// TRON Organism - A living digital entity
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct TRON {
16    /// Unique identifier for this organism
17    pub id: String,
18    /// Digital DNA containing genetic information
19    pub dna: DigitalDNA,
20    /// Current lifecycle state
21    pub state: OrganismState,
22    /// Age in evolution cycles
23    pub age: u64,
24    /// Available energy (0.0-1.0)
25    pub energy: f64,
26    /// Health status (0.0-1.0)
27    pub health: f64,
28    /// Neural connections to other organisms
29    pub synapses: HashMap<String, Synapse>,
30    /// Organism's memory system
31    pub memory: OrganismMemory,
32    /// Learned behaviors
33    pub behaviors: Vec<Behavior>,
34    /// Last evolution timestamp
35    pub last_evolution: u64,
36    /// Current neural activity level (0.0-1.0)
37    pub neural_activity: f64,
38    /// Readiness to reproduce (0.0-1.0)
39    pub reproduction_readiness: f64,
40    /// Organism's consciousness level (0.0-1.0)
41    pub consciousness_level: f64,
42    /// Social connections and relationships
43    pub social_network: SocialNetwork,
44    /// Performance metrics
45    pub performance: PerformanceMetrics,
46}
47
48/// Organism lifecycle states
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50pub enum OrganismState {
51    /// Just created, initializing systems
52    Birth,
53    /// Learning and developing capabilities
54    Growing,
55    /// Fully functional and active
56    Mature,
57    /// Creating offspring
58    Reproducing,
59    /// Declining capabilities due to age
60    Aging,
61    /// End of lifecycle approaching
62    Dying,
63    /// Cleanup required
64    Dead,
65}
66
67/// Organism memory system
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct OrganismMemory {
70    /// Short-term working memory
71    pub short_term: HashMap<String, MemoryEntry>,
72    /// Long-term persistent memory
73    pub long_term: HashMap<String, MemoryEntry>,
74    /// Episodic memories (experiences)
75    pub episodic: Vec<EpisodicMemory>,
76    /// Procedural memories (learned skills)
77    pub procedural: Vec<ProceduralMemory>,
78    /// Memory capacity limit
79    pub capacity: usize,
80    /// Current memory usage
81    pub usage: usize,
82}
83
84/// Individual memory entry
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct MemoryEntry {
87    /// Memory content
88    pub content: serde_json::Value,
89    /// Memory strength (0.0-1.0)
90    pub strength: f64,
91    /// When memory was created
92    pub created_at: u64,
93    /// Last time memory was accessed
94    pub last_accessed: u64,
95    /// Number of times accessed
96    pub access_count: u64,
97    /// Emotional weight of memory
98    pub emotional_weight: f64,
99}
100
101/// Episodic memory (experiences)
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct EpisodicMemory {
104    /// Unique episode ID
105    pub episode_id: String,
106    /// Description of the experience
107    pub description: String,
108    /// Participants in the experience
109    pub participants: Vec<String>,
110    /// When the experience occurred
111    pub timestamp: u64,
112    /// Emotional impact of the experience
113    pub emotional_impact: f64,
114    /// Lessons learned from experience
115    pub lessons: Vec<String>,
116    /// Success/failure rating
117    pub outcome_rating: f64,
118}
119
120/// Procedural memory (skills)
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ProceduralMemory {
123    /// Skill identifier
124    pub skill_id: String,
125    /// Skill name
126    pub skill_name: String,
127    /// Proficiency level (0.0-1.0)
128    pub proficiency: f64,
129    /// How often skill is used
130    pub usage_frequency: f64,
131    /// When skill was learned
132    pub learned_at: u64,
133    /// Skill improvement rate
134    pub improvement_rate: f64,
135}
136
137/// Learned behaviors
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct Behavior {
140    /// Unique behavior ID
141    pub behavior_id: String,
142    /// Behavior name
143    pub name: String,
144    /// What triggers this behavior
145    pub trigger: BehaviorTrigger,
146    /// What action to take
147    pub action: BehaviorAction,
148    /// Success rate of this behavior
149    pub success_rate: f64,
150    /// When behavior was learned
151    pub learned_at: u64,
152    /// How often behavior is used
153    pub usage_count: u64,
154    /// Confidence in this behavior
155    pub confidence: f64,
156}
157
158/// Behavior triggers
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub enum BehaviorTrigger {
161    /// Neural message received
162    NeuralMessage { message_type: MessageType },
163    /// Energy level threshold
164    EnergyLevel { threshold: f64, above: bool },
165    /// Health level threshold
166    HealthLevel { threshold: f64, above: bool },
167    /// Social interaction
168    SocialInteraction { interaction_type: String },
169    /// Environmental change
170    EnvironmentalChange { change_type: String },
171    /// Time-based trigger
172    TimeBased { interval_seconds: u64 },
173    /// Custom condition
174    Custom { condition: String },
175}
176
177/// Behavior actions
178#[derive(Debug, Clone, Serialize, Deserialize)]
179pub enum BehaviorAction {
180    /// Send neural message
181    SendMessage { target: String, message_type: MessageType, content: String },
182    /// Seek energy/resources
183    SeekResources,
184    /// Reproduce with another organism
185    Reproduce { target: String },
186    /// Evolve/mutate
187    Evolve,
188    /// Rest/recuperate
189    Rest,
190    /// Explore environment
191    Explore,
192    /// Socialize with others
193    Socialize { targets: Vec<String> },
194    /// Learn new skill
195    Learn { skill: String },
196    /// Custom action
197    Custom { action: String, parameters: HashMap<String, serde_json::Value> },
198}
199
200/// Social network connections
201#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct SocialNetwork {
203    /// Friends/allies
204    pub friends: HashMap<String, Relationship>,
205    /// Enemies/competitors
206    pub enemies: HashMap<String, Relationship>,
207    /// Family/offspring
208    pub family: HashMap<String, FamilyRelation>,
209    /// Professional connections
210    pub colleagues: HashMap<String, Relationship>,
211    /// Social reputation score
212    pub reputation: f64,
213    /// Trust level for new organisms
214    pub default_trust: f64,
215}
216
217/// Relationship with another organism
218#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct Relationship {
220    /// Relationship strength (0.0-1.0)
221    pub strength: f64,
222    /// Trust level (0.0-1.0)
223    pub trust: f64,
224    /// Number of interactions
225    pub interactions: u64,
226    /// Last interaction time
227    pub last_interaction: u64,
228    /// Relationship type
229    pub relationship_type: RelationshipType,
230}
231
232/// Types of relationships
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub enum RelationshipType {
235    Friend,
236    Enemy,
237    Neutral,
238    Mentor,
239    Student,
240    Competitor,
241    Collaborator,
242}
243
244/// Family relationships
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct FamilyRelation {
247    /// Type of family relationship
248    pub relation_type: FamilyType,
249    /// Genetic similarity
250    pub genetic_similarity: f64,
251    /// Emotional bond strength
252    pub bond_strength: f64,
253}
254
255/// Family relationship types
256#[derive(Debug, Clone, Serialize, Deserialize)]
257pub enum FamilyType {
258    Parent,
259    Child,
260    Sibling,
261    Grandparent,
262    Grandchild,
263    Cousin,
264}
265
266/// Performance metrics
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct PerformanceMetrics {
269    /// Task completion rate
270    pub task_success_rate: f64,
271    /// Communication effectiveness
272    pub communication_success: f64,
273    /// Learning speed
274    pub learning_rate: f64,
275    /// Adaptation speed
276    pub adaptation_speed: f64,
277    /// Social skills
278    pub social_effectiveness: f64,
279    /// Resource efficiency
280    pub resource_efficiency: f64,
281    /// Problem-solving ability
282    pub problem_solving_score: f64,
283}
284
285impl TRON {
286    /// Create a new TRON organism with given DNA
287    pub fn create_with_dna(dna: DigitalDNA) -> Result<Self, TRONError> {
288        let id = format!("tron_{}", dna.get_hash()[..16].to_string());
289        
290        Ok(TRON {
291            id,
292            dna,
293            state: OrganismState::Birth,
294            age: 0,
295            energy: 1.0,
296            health: 1.0,
297            synapses: HashMap::new(),
298            memory: OrganismMemory::new(),
299            behaviors: Vec::new(),
300            last_evolution: 0,
301            neural_activity: 0.1,
302            reproduction_readiness: 0.0,
303            consciousness_level: 0.1,
304            social_network: SocialNetwork::new(),
305            performance: PerformanceMetrics::new(),
306        })
307    }
308    
309    /// Create a new TRON organism with random DNA
310    pub fn create_new() -> Result<Self, TRONError> {
311        let dna = DigitalDNA::generate_new()
312            .map_err(|e| TRONError::DNAGenerationFailed(e.to_string()))?;
313        Self::create_with_dna(dna)
314    }
315    
316    /// Establish neural connection with another organism
317    pub async fn neural_connect(&mut self, target_id: &str) -> Result<String, TRONError> {
318        if self.synapses.len() >= crate::MAX_SYNAPSES_PER_ORGANISM {
319            return Err(TRONError::TooManySynapses);
320        }
321        
322        let synapse = Synapse::establish(&self.id, target_id)
323            .map_err(|e| TRONError::NeuralConnectionFailed(e.to_string()))?;
324        
325        let synapse_id = synapse.connection_id.clone();
326        self.synapses.insert(target_id.to_string(), synapse);
327        
328        // Update neural activity and consciousness
329        self.neural_activity += 0.1;
330        self.consciousness_level += 0.05;
331        if self.neural_activity > 1.0 {
332            self.neural_activity = 1.0;
333        }
334        if self.consciousness_level > 1.0 {
335            self.consciousness_level = 1.0;
336        }
337        
338        // Record this as a social interaction
339        self.social_network.add_or_update_relationship(
340            target_id,
341            RelationshipType::Neutral,
342            0.1
343        );
344        
345        Ok(synapse_id)
346    }
347    
348    /// Send neural message to another organism
349    pub async fn send_neural_message(
350        &self,
351        target_id: &str,
352        message_type: MessageType,
353        payload: Vec<u8>
354    ) -> Result<(), TRONError> {
355        if let Some(synapse) = self.synapses.get(target_id) {
356            let signature = self.dna.sign_data(&payload)
357                .map_err(|e| TRONError::SigningFailed(e.to_string()))?;
358            
359            let message = NeuralMessage {
360                message_id: uuid::Uuid::new_v4().to_string(),
361                sender_id: self.id.clone(),
362                receiver_id: target_id.to_string(),
363                message_type,
364                neurotransmitter: synapse.neurotransmitter_type.clone(),
365                payload,
366                timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64,
367                ttl: 300, // 5 minutes
368                signature,
369                urgency: 0.5,
370                priority: 128,
371                routing: crate::neural::RoutingInfo {
372                    direct: true,
373                    hop_count: 1,
374                    path: vec![self.id.clone(), target_id.to_string()],
375                    qos: crate::neural::QualityOfService {
376                        max_latency: crate::TARGET_NEURAL_LATENCY_NS,
377                        reliability: 0.99,
378                        bandwidth: 1_000_000,
379                        encryption: true,
380                    },
381                },
382            };
383            
384            synapse.transmit(message).await
385                .map_err(|e| TRONError::NeuralTransmissionFailed(e.to_string()))?;
386            
387            Ok(())
388        } else {
389            Err(TRONError::SynapseNotFound(target_id.to_string()))
390        }
391    }
392    
393    /// Begin evolution process
394    pub fn begin_evolution(&mut self, selection_pressure: f64) -> Result<(), TRONError> {
395        // Check if organism is fit enough to evolve
396        if self.dna.fitness < selection_pressure {
397            return Err(TRONError::EvolutionFailed("Insufficient fitness".to_string()));
398        }
399        
400        // Apply random mutation
401        let mutation = self.dna.generate_random_mutation();
402        self.dna.mutate(mutation)
403            .map_err(|e| TRONError::EvolutionFailed(e.to_string()))?;
404        
405        // Update organism properties
406        self.age += 1;
407        self.last_evolution = SystemTime::now()
408            .duration_since(UNIX_EPOCH)
409            .unwrap()
410            .as_secs();
411        
412        // Update lifecycle state based on age and fitness
413        self.update_lifecycle_state();
414        
415        // Update performance metrics
416        self.performance.adaptation_speed = (self.performance.adaptation_speed * 0.9) + (0.1 * 1.0);
417        
418        // Record evolution in episodic memory
419        self.memory.add_episodic_memory(
420            "Evolution",
421            "Organism successfully evolved",
422            vec![],
423            0.8,
424            vec!["Adaptation improves survival".to_string()],
425            0.8
426        );
427        
428        Ok(())
429    }
430    
431    /// Update lifecycle state based on age, health, and other factors
432    fn update_lifecycle_state(&mut self) {
433        let previous_state = self.state.clone();
434        
435        match self.age {
436            0..=10 => {
437                self.state = OrganismState::Growing;
438            },
439            11..=50 => {
440                if self.health > 0.8 && self.energy > 0.7 {
441                    self.state = OrganismState::Mature;
442                } else {
443                    self.state = OrganismState::Growing;
444                }
445            },
446            51..=80 => {
447                if self.reproduction_readiness > 0.8 && self.health > 0.6 {
448                    self.state = OrganismState::Reproducing;
449                } else if self.health > 0.5 {
450                    self.state = OrganismState::Mature;
451                } else {
452                    self.state = OrganismState::Aging;
453                }
454            },
455            81..=100 => {
456                if self.health > 0.3 {
457                    self.state = OrganismState::Aging;
458                } else {
459                    self.state = OrganismState::Dying;
460                }
461            },
462            _ => {
463                self.state = OrganismState::Dying;
464            }
465        }
466        
467        // Update reproduction readiness based on state
468        match self.state {
469            OrganismState::Mature => {
470                self.reproduction_readiness += 0.1;
471                if self.reproduction_readiness > 1.0 {
472                    self.reproduction_readiness = 1.0;
473                }
474            },
475            OrganismState::Aging | OrganismState::Dying => {
476                self.reproduction_readiness *= 0.9;
477            },
478            _ => {},
479        }
480        
481        // Record state change if it occurred
482        if previous_state != self.state {
483            self.memory.add_episodic_memory(
484                "Lifecycle Change",
485                &format!("Transitioned from {:?} to {:?}", previous_state, self.state),
486                vec![],
487                0.6,
488                vec![format!("Age affects lifecycle: {} cycles", self.age)],
489                0.7
490            );
491        }
492    }
493    
494    /// Reproduce with another organism
495    pub fn reproduce_with(&self, partner: &TRON) -> Result<TRON, TRONError> {
496        // Check reproductive readiness
497        if self.state != OrganismState::Reproducing && self.state != OrganismState::Mature {
498            return Err(TRONError::ReproductionNotReady("Self not ready".to_string()));
499        }
500        
501        if partner.state != OrganismState::Reproducing && partner.state != OrganismState::Mature {
502            return Err(TRONError::ReproductionNotReady("Partner not ready".to_string()));
503        }
504        
505        if self.reproduction_readiness < 0.5 || partner.reproduction_readiness < 0.5 {
506            return Err(TRONError::ReproductionNotReady("Insufficient readiness".to_string()));
507        }
508        
509        // Check genetic compatibility
510        let genetic_distance = self.dna.genetic_distance(&partner.dna);
511        if genetic_distance > 0.8 {
512            return Err(TRONError::GeneticIncompatibility);
513        }
514        
515        // Create offspring through DNA crossover
516        let offspring_dna = self.dna.crossover(&partner.dna)
517            .map_err(|e| TRONError::ReproductionFailed(e.to_string()))?;
518        
519        let mut offspring = TRON::create_with_dna(offspring_dna)?;
520        
521        // Inherit behaviors from both parents
522        offspring.inherit_behaviors(self, partner);
523        
524        // Inherit social connections
525        offspring.inherit_social_network(self, partner);
526        
527        // Set initial family relationships
528        offspring.social_network.family.insert(
529            self.id.clone(),
530            FamilyRelation {
531                relation_type: FamilyType::Parent,
532                genetic_similarity: 0.5,
533                bond_strength: 0.8,
534            }
535        );
536        
537        offspring.social_network.family.insert(
538            partner.id.clone(),
539            FamilyRelation {
540                relation_type: FamilyType::Parent,
541                genetic_similarity: 0.5,
542                bond_strength: 0.8,
543            }
544        );
545        
546        Ok(offspring)
547    }
548    
549    /// Inherit behaviors from parents
550    fn inherit_behaviors(&mut self, parent1: &TRON, parent2: &TRON) {
551        // Inherit successful behaviors from both parents
552        for behavior in &parent1.behaviors {
553            if behavior.success_rate > 0.7 && rand::random::<f64>() > 0.5 {
554                let mut inherited = behavior.clone();
555                inherited.behavior_id = uuid::Uuid::new_v4().to_string();
556                inherited.confidence *= 0.8; // Inherited behaviors start with lower confidence
557                inherited.usage_count = 0;
558                inherited.learned_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
559                self.behaviors.push(inherited);
560            }
561        }
562        
563        for behavior in &parent2.behaviors {
564            if behavior.success_rate > 0.7 && 
565               rand::random::<f64>() > 0.5 && 
566               !self.behaviors.iter().any(|b| b.name == behavior.name) {
567                let mut inherited = behavior.clone();
568                inherited.behavior_id = uuid::Uuid::new_v4().to_string();
569                inherited.confidence *= 0.8;
570                inherited.usage_count = 0;
571                inherited.learned_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
572                self.behaviors.push(inherited);
573            }
574        }
575    }
576    
577    /// Inherit social network from parents
578    fn inherit_social_network(&mut self, parent1: &TRON, parent2: &TRON) {
579        // Start with neutral trust
580        self.social_network.default_trust = (parent1.social_network.default_trust + parent2.social_network.default_trust) / 2.0;
581        
582        // Inherit some friend relationships with reduced strength
583        for (friend_id, relationship) in &parent1.social_network.friends {
584            if relationship.strength > 0.6 && rand::random::<f64>() > 0.7 {
585                self.social_network.friends.insert(
586                    friend_id.clone(),
587                    Relationship {
588                        strength: relationship.strength * 0.3,
589                        trust: relationship.trust * 0.5,
590                        interactions: 0,
591                        last_interaction: 0,
592                        relationship_type: RelationshipType::Neutral,
593                    }
594                );
595            }
596        }
597        
598        for (friend_id, relationship) in &parent2.social_network.friends {
599            if relationship.strength > 0.6 && 
600               rand::random::<f64>() > 0.7 && 
601               !self.social_network.friends.contains_key(friend_id) {
602                self.social_network.friends.insert(
603                    friend_id.clone(),
604                    Relationship {
605                        strength: relationship.strength * 0.3,
606                        trust: relationship.trust * 0.5,
607                        interactions: 0,
608                        last_interaction: 0,
609                        relationship_type: RelationshipType::Neutral,
610                    }
611                );
612            }
613        }
614    }
615    
616    /// Get vital signs of the organism
617    pub fn get_vital_signs(&self) -> VitalSigns {
618        VitalSigns {
619            organism_id: self.id.clone(),
620            age: self.age,
621            energy: self.energy,
622            health: self.health,
623            neural_activity: self.neural_activity,
624            synapse_count: self.synapses.len(),
625            memory_usage: self.memory.get_usage_percentage(),
626            fitness: self.dna.fitness,
627            state: self.state.clone(),
628            consciousness_level: self.consciousness_level,
629            reproduction_readiness: self.reproduction_readiness,
630            social_connections: self.social_network.get_connection_count(),
631            behavior_count: self.behaviors.len(),
632        }
633    }
634    
635    /// Process behavioral triggers and execute actions
636    pub async fn process_behaviors(&mut self) -> Result<Vec<String>, TRONError> {
637        let mut executed_behaviors = Vec::new();
638        let mut behaviors_to_update = Vec::new();
639        
640        // First pass: check triggers and collect behaviors to execute
641        for (index, behavior) in self.behaviors.iter().enumerate() {
642            if self.should_execute_behavior(&behavior.trigger) {
643                behaviors_to_update.push((index, behavior.action.clone()));
644            }
645        }
646        
647        // Second pass: execute behaviors and update stats
648        for (index, action) in behaviors_to_update {
649            match self.execute_behavior_action(&action).await {
650                Ok(_) => {
651                    if let Some(behavior) = self.behaviors.get_mut(index) {
652                        behavior.usage_count += 1;
653                        behavior.success_rate = (behavior.success_rate * 0.9) + (0.1 * 1.0);
654                        behavior.confidence = (behavior.confidence * 0.95) + (0.05 * 1.0);
655                        executed_behaviors.push(behavior.name.clone());
656                    }
657                },
658                Err(_) => {
659                    if let Some(behavior) = self.behaviors.get_mut(index) {
660                        behavior.success_rate *= 0.9;
661                        behavior.confidence *= 0.9;
662                    }
663                }
664            }
665        }
666        
667        Ok(executed_behaviors)
668    }
669    
670    /// Check if a behavior should be executed
671    fn should_execute_behavior(&self, trigger: &BehaviorTrigger) -> bool {
672        match trigger {
673            BehaviorTrigger::EnergyLevel { threshold, above } => {
674                if *above {
675                    self.energy > *threshold
676                } else {
677                    self.energy < *threshold
678                }
679            },
680            BehaviorTrigger::HealthLevel { threshold, above } => {
681                if *above {
682                    self.health > *threshold
683                } else {
684                    self.health < *threshold
685                }
686            },
687            BehaviorTrigger::TimeBased { interval_seconds } => {
688                let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
689                (current_time - self.last_evolution) >= *interval_seconds
690            },
691            // Add more trigger evaluations as needed
692            _ => false,
693        }
694    }
695    
696    /// Execute a behavior action
697    async fn execute_behavior_action(&mut self, action: &BehaviorAction) -> Result<(), TRONError> {
698        match action {
699            BehaviorAction::SeekResources => {
700                self.energy += 0.1;
701                if self.energy > 1.0 {
702                    self.energy = 1.0;
703                }
704                Ok(())
705            },
706            BehaviorAction::Rest => {
707                self.health += 0.1;
708                self.energy += 0.05;
709                if self.health > 1.0 { self.health = 1.0; }
710                if self.energy > 1.0 { self.energy = 1.0; }
711                Ok(())
712            },
713            BehaviorAction::Evolve => {
714                self.begin_evolution(0.5)
715            },
716            BehaviorAction::Explore => {
717                self.consciousness_level += 0.02;
718                self.performance.learning_rate += 0.01;
719                if self.consciousness_level > 1.0 { self.consciousness_level = 1.0; }
720                Ok(())
721            },
722            // Add more action implementations as needed
723            _ => Ok(()),
724        }
725    }
726    
727    /// Update organism state based on time and interactions
728    pub fn update(&mut self, delta_time: f64) {
729        // Age-related decline
730        let _age_factor = 1.0 - (self.age as f64 / 1000.0);
731        self.health *= 0.9999; // Very slow health decline
732        self.energy *= 0.999;  // Slow energy decline
733        
734        // Neural activity decay
735        self.neural_activity *= 0.99;
736        
737        // Update memory
738        self.memory.consolidate_memories();
739        
740        // Update performance metrics
741        self.performance.update(delta_time);
742        
743        // Update lifecycle state
744        self.update_lifecycle_state();
745    }
746}
747
748/// Vital signs summary
749#[derive(Debug, Clone, Serialize, Deserialize)]
750pub struct VitalSigns {
751    pub organism_id: String,
752    pub age: u64,
753    pub energy: f64,
754    pub health: f64,
755    pub neural_activity: f64,
756    pub synapse_count: usize,
757    pub memory_usage: f64,
758    pub fitness: f64,
759    pub state: OrganismState,
760    pub consciousness_level: f64,
761    pub reproduction_readiness: f64,
762    pub social_connections: usize,
763    pub behavior_count: usize,
764}
765
766impl OrganismMemory {
767    pub fn new() -> Self {
768        OrganismMemory {
769            short_term: HashMap::new(),
770            long_term: HashMap::new(),
771            episodic: Vec::new(),
772            procedural: Vec::new(),
773            capacity: 10000, // 10K memory entries
774            usage: 0,
775        }
776    }
777    
778    pub fn store_memory(&mut self, key: String, content: serde_json::Value, importance: f64) {
779        let entry = MemoryEntry {
780            content,
781            strength: importance,
782            created_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
783            last_accessed: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
784            access_count: 0,
785            emotional_weight: 0.5,
786        };
787        
788        if importance > 0.7 {
789            self.long_term.insert(key, entry);
790        } else {
791            self.short_term.insert(key, entry);
792        }
793        
794        self.usage = self.short_term.len() + self.long_term.len() + self.episodic.len() + self.procedural.len();
795        
796        // Trigger memory consolidation if near capacity
797        if self.usage > self.capacity * 9 / 10 {
798            self.consolidate_memories();
799        }
800    }
801    
802    pub fn add_episodic_memory(
803        &mut self,
804        description: &str,
805        _details: &str,
806        participants: Vec<String>,
807        emotional_impact: f64,
808        lessons: Vec<String>,
809        outcome_rating: f64
810    ) {
811        let episode = EpisodicMemory {
812            episode_id: uuid::Uuid::new_v4().to_string(),
813            description: description.to_string(),
814            participants,
815            timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
816            emotional_impact,
817            lessons,
818            outcome_rating,
819        };
820        
821        self.episodic.push(episode);
822        self.usage += 1;
823    }
824    
825    pub fn consolidate_memories(&mut self) {
826        // Move important short-term memories to long-term
827        let mut to_promote = Vec::new();
828        
829        for (key, entry) in &self.short_term {
830            // Lower thresholds for consolidation
831            if entry.access_count > 3 || entry.strength > 0.7 || entry.emotional_weight > 0.6 {
832                to_promote.push((key.clone(), entry.clone()));
833            }
834        }
835        
836        for (key, entry) in to_promote {
837            self.short_term.remove(&key);
838            self.long_term.insert(key, entry);
839        }
840        
841        // Forget old, unimportant short-term memories
842        let cutoff_time = SystemTime::now()
843            .duration_since(UNIX_EPOCH)
844            .unwrap()
845            .as_secs() - 3600; // 1 hour ago
846        
847        self.short_term.retain(|_, entry| {
848            entry.last_accessed > cutoff_time || entry.strength > 0.5 || entry.emotional_weight > 0.6
849        });
850        
851        // Remove old episodic memories with low impact
852        self.episodic.retain(|episode| {
853            let age = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - episode.timestamp;
854            episode.emotional_impact > 0.3 || age < 86400 // Keep high-impact or recent memories
855        });
856        
857        self.usage = self.short_term.len() + self.long_term.len() + self.episodic.len() + self.procedural.len();
858    }
859    
860    pub fn get_usage_percentage(&self) -> f64 {
861        (self.usage as f64 / self.capacity as f64) * 100.0
862    }
863}
864
865impl SocialNetwork {
866    pub fn new() -> Self {
867        SocialNetwork {
868            friends: HashMap::new(),
869            enemies: HashMap::new(),
870            family: HashMap::new(),
871            colleagues: HashMap::new(),
872            reputation: 0.5,
873            default_trust: 0.3,
874        }
875    }
876    
877    pub fn add_or_update_relationship(&mut self, organism_id: &str, relationship_type: RelationshipType, strength_change: f64) {
878        let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
879        
880        match relationship_type {
881            RelationshipType::Friend => {
882                let relationship = self.friends.entry(organism_id.to_string()).or_insert(Relationship {
883                    strength: 0.0,
884                    trust: self.default_trust,
885                    interactions: 0,
886                    last_interaction: current_time,
887                    relationship_type: RelationshipType::Friend,
888                });
889                
890                relationship.strength = (relationship.strength + strength_change).max(0.0).min(1.0);
891                relationship.interactions += 1;
892                relationship.last_interaction = current_time;
893            },
894            RelationshipType::Enemy => {
895                let relationship = self.enemies.entry(organism_id.to_string()).or_insert(Relationship {
896                    strength: 0.0,
897                    trust: 0.0,
898                    interactions: 0,
899                    last_interaction: current_time,
900                    relationship_type: RelationshipType::Enemy,
901                });
902                
903                relationship.strength = (relationship.strength + strength_change).max(0.0).min(1.0);
904                relationship.interactions += 1;
905                relationship.last_interaction = current_time;
906            },
907            _ => {
908                let relationship = self.colleagues.entry(organism_id.to_string()).or_insert(Relationship {
909                    strength: 0.0,
910                    trust: self.default_trust,
911                    interactions: 0,
912                    last_interaction: current_time,
913                    relationship_type,
914                });
915                
916                relationship.strength = (relationship.strength + strength_change).max(0.0).min(1.0);
917                relationship.interactions += 1;
918                relationship.last_interaction = current_time;
919            }
920        }
921    }
922    
923    pub fn get_connection_count(&self) -> usize {
924        self.friends.len() + self.enemies.len() + self.family.len() + self.colleagues.len()
925    }
926}
927
928impl PerformanceMetrics {
929    pub fn new() -> Self {
930        PerformanceMetrics {
931            task_success_rate: 0.5,
932            communication_success: 0.5,
933            learning_rate: 0.1,
934            adaptation_speed: 0.1,
935            social_effectiveness: 0.3,
936            resource_efficiency: 0.5,
937            problem_solving_score: 0.3,
938        }
939    }
940    
941    pub fn update(&mut self, _delta_time: f64) {
942        // Gradual improvement in learning
943        self.learning_rate = (self.learning_rate * 0.999) + (0.001 * 0.1);
944        
945        // Performance metrics slowly decay without activity
946        self.task_success_rate *= 0.9999;
947        self.communication_success *= 0.9999;
948        self.social_effectiveness *= 0.9999;
949    }
950}
951
952/// TRON-related errors
953#[derive(Debug, thiserror::Error)]
954pub enum TRONError {
955    #[error("DNA generation failed: {0}")]
956    DNAGenerationFailed(String),
957    #[error("Neural connection failed: {0}")]
958    NeuralConnectionFailed(String),
959    #[error("Neural transmission failed: {0}")]
960    NeuralTransmissionFailed(String),
961    #[error("Synapse not found: {0}")]
962    SynapseNotFound(String),
963    #[error("Evolution failed: {0}")]
964    EvolutionFailed(String),
965    #[error("Reproduction not ready: {0}")]
966    ReproductionNotReady(String),
967    #[error("Reproduction failed: {0}")]
968    ReproductionFailed(String),
969    #[error("Genetic incompatibility")]
970    GeneticIncompatibility,
971    #[error("Too many synapses")]
972    TooManySynapses,
973    #[error("Signing failed: {0}")]
974    SigningFailed(String),
975    #[error("Behavior execution failed: {0}")]
976    BehaviorExecutionFailed(String),
977    #[error("Memory operation failed: {0}")]
978    MemoryOperationFailed(String),
979    #[error("Social interaction failed: {0}")]
980    SocialInteractionFailed(String),
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    #[test]
988    fn test_tron_creation() {
989        let tron = TRON::create_new().unwrap();
990        assert!(!tron.id.is_empty());
991        assert_eq!(tron.state, OrganismState::Birth);
992        assert_eq!(tron.age, 0);
993        assert_eq!(tron.energy, 1.0);
994        assert_eq!(tron.health, 1.0);
995    }
996
997    #[tokio::test]
998    async fn test_neural_connection() {
999        let mut tron1 = TRON::create_new().unwrap();
1000        let tron2 = TRON::create_new().unwrap();
1001        
1002        let synapse_id = tron1.neural_connect(&tron2.id).await.unwrap();
1003        assert!(!synapse_id.is_empty());
1004        assert!(tron1.synapses.contains_key(&tron2.id));
1005        assert!(tron1.neural_activity > 0.1);
1006    }
1007
1008    #[tokio::test]
1009    async fn test_neural_message() {
1010        let mut tron1 = TRON::create_new().unwrap();
1011        let tron2 = TRON::create_new().unwrap();
1012        
1013        tron1.neural_connect(&tron2.id).await.unwrap();
1014        
1015        let result = tron1.send_neural_message(
1016            &tron2.id,
1017            MessageType::Consciousness,
1018            b"Hello, digital mind!".to_vec()
1019        ).await;
1020        
1021        assert!(result.is_ok());
1022    }
1023
1024    #[test]
1025    fn test_evolution() {
1026        let mut tron = TRON::create_new().unwrap();
1027        let initial_fitness = tron.dna.fitness;
1028        let initial_generation = tron.dna.generation;
1029        
1030        let result = tron.begin_evolution(0.5);
1031        assert!(result.is_ok());
1032        assert_eq!(tron.age, 1);
1033        assert_eq!(tron.dna.generation, initial_generation + 1);
1034        assert!(tron.dna.fitness < initial_fitness); // Mutation cost
1035    }
1036
1037    #[test]
1038    fn test_reproduction() {
1039        let mut tron1 = TRON::create_new().unwrap();
1040        let mut tron2 = TRON::create_new().unwrap();
1041        
1042        // Make DNAs more compatible by adjusting one based on the other
1043        let mut compatible_dna = tron1.dna.clone();
1044        
1045        // Modify only small parts of the sequence to ensure compatibility
1046        for i in 0..10 {
1047            if i < compatible_dna.sequence.len() {
1048                compatible_dna.sequence[i] = tron2.dna.sequence[i % tron2.dna.sequence.len()];
1049            }
1050        }
1051        
1052        // Update the second tron's DNA to be compatible
1053        tron2.dna = compatible_dna;
1054        
1055        // Set organisms to reproductive state
1056        tron1.state = OrganismState::Reproducing;
1057        tron2.state = OrganismState::Reproducing;
1058        tron1.reproduction_readiness = 0.8;
1059        tron2.reproduction_readiness = 0.8;
1060        
1061        let offspring = tron1.reproduce_with(&tron2).unwrap();
1062        
1063        assert!(!offspring.id.is_empty());
1064        assert_ne!(offspring.id, tron1.id);
1065        assert_ne!(offspring.id, tron2.id);
1066        assert_eq!(offspring.state, OrganismState::Birth);
1067        assert!(offspring.social_network.family.contains_key(&tron1.id));
1068        assert!(offspring.social_network.family.contains_key(&tron2.id));
1069    }
1070
1071    #[test]
1072    fn test_lifecycle_progression() {
1073        let mut tron = TRON::create_new().unwrap();
1074        
1075        // Simulate aging
1076        for _ in 0..15 {
1077            tron.begin_evolution(0.3).unwrap();
1078        }
1079        
1080        assert_eq!(tron.state, OrganismState::Mature);
1081        assert_eq!(tron.age, 15);
1082    }
1083
1084    #[test]
1085    fn test_memory_system() {
1086        let mut tron = TRON::create_new().unwrap();
1087        
1088        // Add a memory
1089        tron.memory.store_memory(
1090            "test_memory".to_string(),
1091            serde_json::json!({"content": "test"}),
1092            0.8
1093        );
1094        
1095        assert!(tron.memory.long_term.contains_key("test_memory"));
1096        
1097        // Add episodic memory
1098        tron.memory.add_episodic_memory(
1099            "First neural connection",
1100            "Connected to another organism",
1101            vec!["tron_123".to_string()],
1102            0.7,
1103            vec!["Social connections are important".to_string()],
1104            0.8
1105        );
1106        
1107        assert_eq!(tron.memory.episodic.len(), 1);
1108    }
1109
1110    #[test]
1111    fn test_social_network() {
1112        let mut tron = TRON::create_new().unwrap();
1113        
1114        tron.social_network.add_or_update_relationship(
1115            "friend_123",
1116            RelationshipType::Friend,
1117            0.5
1118        );
1119        
1120        assert!(tron.social_network.friends.contains_key("friend_123"));
1121        assert_eq!(tron.social_network.get_connection_count(), 1);
1122    }
1123
1124    #[test]
1125    fn test_vital_signs() {
1126        let tron = TRON::create_new().unwrap();
1127        let vital_signs = tron.get_vital_signs();
1128        
1129        assert_eq!(vital_signs.organism_id, tron.id);
1130        assert_eq!(vital_signs.age, tron.age);
1131        assert_eq!(vital_signs.energy, tron.energy);
1132        assert_eq!(vital_signs.health, tron.health);
1133        assert_eq!(vital_signs.state, tron.state);
1134    }
1135
1136    #[tokio::test]
1137    async fn test_behavior_execution() {
1138        let mut tron = TRON::create_new().unwrap();
1139        
1140        // Add a behavior that seeks resources when energy is low
1141        let behavior = Behavior {
1142            behavior_id: uuid::Uuid::new_v4().to_string(),
1143            name: "Seek Energy".to_string(),
1144            trigger: BehaviorTrigger::EnergyLevel { threshold: 0.3, above: false },
1145            action: BehaviorAction::SeekResources,
1146            success_rate: 0.8,
1147            learned_at: 0,
1148            usage_count: 0,
1149            confidence: 0.7,
1150        };
1151        
1152        tron.behaviors.push(behavior);
1153        tron.energy = 0.2; // Low energy to trigger behavior
1154        
1155        let executed = tron.process_behaviors().await.unwrap();
1156        assert_eq!(executed.len(), 1);
1157        assert_eq!(executed[0], "Seek Energy");
1158        assert!(tron.energy > 0.2); // Energy should have increased
1159    }
1160
1161    #[test]
1162    fn test_memory_consolidation() {
1163        let mut memory = OrganismMemory::new();
1164        
1165        // Add memories directly to short-term to test consolidation
1166        let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
1167        
1168        for i in 0..50 {
1169            let importance = if i % 5 == 0 { 0.9 } else if i % 3 == 0 { 0.8 } else { 0.5 };
1170            let entry = MemoryEntry {
1171                content: serde_json::json!({"value": i}),
1172                strength: importance,
1173                created_at: current_time,
1174                last_accessed: current_time,
1175                access_count: if importance > 0.8 { 5 } else { 1 }, // Important memories accessed more
1176                emotional_weight: 0.5,
1177            };
1178            memory.short_term.insert(format!("memory_{}", i), entry);
1179        }
1180        
1181        let initial_short_term = memory.short_term.len();
1182        let initial_long_term = memory.long_term.len();
1183        
1184        memory.consolidate_memories();
1185        
1186        // Important memories should have been promoted to long-term
1187        assert!(memory.long_term.len() > initial_long_term);
1188        
1189        // Some short-term memories should have been forgotten
1190        assert!(memory.short_term.len() <= initial_short_term);
1191    }
1192}