1use std::sync::{Arc, RwLock};
14use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
15
16use crate::architecture_simulator::ArchitectureSimulator;
17use crate::heuristic_decision::HeuristicDecisionMaker;
18use crate::knowledge_base::KnowledgeBase;
19
20#[derive(Debug, Clone)]
24pub struct VagusTone {
25 pub current: f64,
26 pub baseline: f64,
27 pub trend: f64, pub volatility: f64, pub last_update: u64,
30}
31
32#[derive(Debug, Clone)]
34pub struct SystemPulse {
35 pub timestamp: u64,
36 pub cpu_pressure: f64, pub memory_pressure: f64, pub io_pressure: f64, pub network_pressure: f64, pub request_rate: f64, pub error_rate: f64, pub hrv: f64,
43}
44
45#[derive(Debug, Clone)]
47pub struct GutFeeling {
48 pub id: String,
49 pub source: String, pub raw_signal: f64, pub anomaly_score: f64, pub timestamp: u64,
53 pub processed: bool, }
55
56#[derive(Debug, Clone, PartialEq)]
58pub enum CognitiveInflammation {
59 MemoryLeak { module: String, leak_rate: f64 },
61 Deadlock { thread: String, wait_time_ms: u64 },
63 InfiniteLoop { location: String, iterations: u64 },
65 DoSAttack { source: String, request_count: u64 },
67 ResourceExhaustion { resource: String, usage: f64 },
69 CascadeFailure {
71 origin: String,
72 affected: Vec<String>,
73 },
74 Custom(String),
76}
77
78#[derive(Debug, Clone)]
80pub struct AntiInflammatoryResponse {
81 pub inflammation_type: CognitiveInflammation,
82 pub action: String, pub target: String, pub success: bool, pub recovery_time_ms: u64, pub side_effects: Vec<String>, pub timestamp: u64,
88}
89
90#[derive(Debug, Clone)]
92pub struct VagusState {
93 pub tone: VagusTone,
94 pub pulse: SystemPulse,
95 pub gut_feelings: Vec<GutFeeling>,
96 pub active_inflammations: Vec<CognitiveInflammation>,
97 pub response_history: Vec<AntiInflammatoryResponse>,
98 pub parasympathetic_mode: bool, pub freeze_initiated: bool, }
101
102#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
104pub enum AlertLevel {
105 Relaxed = 0,
106 Vigilant = 1,
107 Stressed = 2,
108 Critical = 3,
109 Emergency = 4,
110}
111
112pub struct VagusNerve {
115 state: Arc<RwLock<VagusState>>,
116 #[allow(dead_code)]
118 simulator: Arc<ArchitectureSimulator>,
119 decision_maker: Arc<RwLock<Option<HeuristicDecisionMaker>>>,
121 knowledge_base: Arc<KnowledgeBase>,
123 last_pulse: Arc<RwLock<Instant>>,
125 heartbeat_interval_ms: u64,
127 inflammation_threshold: f64,
129 parasympathetic_threshold: f64,
131}
132
133impl VagusNerve {
134 pub fn new(simulator: Arc<ArchitectureSimulator>, knowledge_base: Arc<KnowledgeBase>) -> Self {
135 let now = SystemTime::now()
136 .duration_since(UNIX_EPOCH)
137 .unwrap()
138 .as_secs();
139
140 Self {
141 state: Arc::new(RwLock::new(VagusState {
142 tone: VagusTone {
143 current: 0.8, baseline: 0.8,
145 trend: 0.0,
146 volatility: 0.1,
147 last_update: now,
148 },
149 pulse: SystemPulse {
150 timestamp: now,
151 cpu_pressure: 0.0,
152 memory_pressure: 0.0,
153 io_pressure: 0.0,
154 network_pressure: 0.0,
155 request_rate: 0.0,
156 error_rate: 0.0,
157 hrv: 0.8, },
159 gut_feelings: Vec::new(),
160 active_inflammations: Vec::new(),
161 response_history: Vec::new(),
162 parasympathetic_mode: false,
163 freeze_initiated: false,
164 })),
165 simulator,
166 decision_maker: Arc::new(RwLock::new(None)),
167 knowledge_base,
168 last_pulse: Arc::new(RwLock::new(Instant::now())),
169 heartbeat_interval_ms: 1000,
170 inflammation_threshold: 0.7,
171 parasympathetic_threshold: 0.85,
172 }
173 }
174
175 pub fn set_decision_maker(&self, dm: HeuristicDecisionMaker) {
177 *crate::sync_guard::write_lock(&self.decision_maker) = Some(dm);
178 }
179
180 pub fn measure_pulse(&self, metrics: &SystemMetrics) -> SystemPulse {
182 let now = SystemTime::now()
183 .duration_since(UNIX_EPOCH)
184 .unwrap()
185 .as_secs();
186
187 let prev_pulse = crate::sync_guard::read_lock(&self.state).pulse.clone();
189 let response_delta = (metrics.request_rate - prev_pulse.request_rate).abs();
190 let hrv = 1.0 - (response_delta / 100.0).min(1.0);
191
192 let pulse = SystemPulse {
193 timestamp: now,
194 cpu_pressure: metrics.cpu_usage,
195 memory_pressure: metrics.memory_usage,
196 io_pressure: metrics.io_usage,
197 network_pressure: metrics.network_usage,
198 request_rate: metrics.request_rate,
199 error_rate: metrics.error_rate,
200 hrv,
201 };
202
203 {
205 let mut state = crate::sync_guard::write_lock(&self.state);
206 state.pulse = pulse.clone();
207 }
208
209 *crate::sync_guard::write_lock(&self.last_pulse) = Instant::now();
210 pulse
211 }
212
213 pub fn update_tone(&self) {
215 let mut state = crate::sync_guard::write_lock(&self.state);
216 let pulse = &state.pulse;
217
218 let avg_pressure = (pulse.cpu_pressure
220 + pulse.memory_pressure
221 + pulse.io_pressure
222 + pulse.network_pressure)
223 / 4.0;
224
225 let target_tone = 1.0 - avg_pressure;
227
228 let alpha = 0.1;
230 let new_tone = state.tone.current * (1.0 - alpha) + target_tone * alpha;
231
232 let trend = new_tone - state.tone.current;
234
235 let vol_change = (new_tone - state.tone.current).abs();
237 let new_volatility = state.tone.volatility * 0.95 + vol_change * 0.05;
238
239 let now = SystemTime::now()
240 .duration_since(UNIX_EPOCH)
241 .unwrap()
242 .as_secs();
243
244 state.tone = VagusTone {
245 current: new_tone,
246 baseline: state.tone.baseline,
247 trend,
248 volatility: new_volatility,
249 last_update: now,
250 };
251 }
252
253 pub fn receive_gut_feeling(&self, source: &str, raw_signal: f64) -> String {
255 let now = SystemTime::now()
256 .duration_since(UNIX_EPOCH)
257 .unwrap()
258 .as_secs();
259
260 let baseline = 0.5; let anomaly_score = ((raw_signal - baseline).abs() / baseline).min(1.0);
263
264 let feeling = GutFeeling {
265 id: format!("gf_{}", rand::random::<u32>()),
266 source: source.to_string(),
267 raw_signal,
268 anomaly_score,
269 timestamp: now,
270 processed: false,
271 };
272
273 let id = feeling.id.clone();
274
275 {
276 let mut state = crate::sync_guard::write_lock(&self.state);
277 state.gut_feelings.push(feeling);
278
279 if state.gut_feelings.len() > 1000 {
281 state.gut_feelings.drain(0..500);
282 }
283 }
284
285 id
286 }
287
288 pub fn detect_inflammation(&self) -> Vec<CognitiveInflammation> {
290 let state = crate::sync_guard::read_lock(&self.state);
291 let pulse = &state.pulse;
292 let tone = &state.tone;
293
294 let mut inflammations = Vec::new();
295
296 if pulse.memory_pressure > self.inflammation_threshold && tone.trend < -0.1 {
298 inflammations.push(CognitiveInflammation::MemoryLeak {
300 module: "unknown".to_string(),
301 leak_rate: pulse.memory_pressure - self.inflammation_threshold,
302 });
303 }
304
305 if pulse.error_rate > 0.1 && pulse.request_rate > 100.0 {
307 inflammations.push(CognitiveInflammation::DoSAttack {
308 source: "unknown".to_string(),
309 request_count: (pulse.request_rate * pulse.error_rate) as u64,
310 });
311 }
312
313 if pulse.cpu_pressure > 0.95 || pulse.memory_pressure > 0.95 {
315 inflammations.push(CognitiveInflammation::ResourceExhaustion {
316 resource: if pulse.cpu_pressure > 0.95 {
317 "cpu".to_string()
318 } else {
319 "memory".to_string()
320 },
321 usage: pulse.cpu_pressure.max(pulse.memory_pressure),
322 });
323 }
324
325 if pulse.hrv < 0.3 {
327 inflammations.push(CognitiveInflammation::Custom(
328 "system_paralysis".to_string(),
329 ));
330 }
331
332 drop(state);
334 let mut state = crate::sync_guard::write_lock(&self.state);
335 state.active_inflammations = inflammations.clone();
336
337 inflammations
338 }
339
340 pub fn trigger_anti_inflammatory_response(
342 &self,
343 inflammation: &CognitiveInflammation,
344 ) -> AntiInflammatoryResponse {
345 let now = SystemTime::now()
346 .duration_since(UNIX_EPOCH)
347 .unwrap()
348 .as_secs();
349
350 let start = Instant::now();
351
352 let (action, target, success, side_effects) = match inflammation {
353 CognitiveInflammation::MemoryLeak { module, .. } => {
354 (
356 "force_memory_flush".to_string(),
357 module.clone(),
358 true,
359 vec![
360 "cache_cleared".to_string(),
361 "recent_activations_preserved".to_string(),
362 ],
363 )
364 }
365 CognitiveInflammation::DoSAttack { source, .. } => {
366 (
368 "activate_rate_limiting".to_string(),
369 source.clone(),
370 true,
371 vec![
372 "throttle_applied".to_string(),
373 "legitimate_requests_delayed".to_string(),
374 ],
375 )
376 }
377 CognitiveInflammation::ResourceExhaustion { resource, .. } => {
378 (
380 "isolate_resource".to_string(),
381 resource.clone(),
382 true,
383 vec!["resource_quota_enforced".to_string()],
384 )
385 }
386 CognitiveInflammation::Deadlock { thread, .. } => {
387 (
389 "force_thread_interrupt".to_string(),
390 thread.clone(),
391 true,
392 vec!["potential_data_loss".to_string()],
393 )
394 }
395 CognitiveInflammation::InfiniteLoop { location, .. } => {
396 (
398 "break_loop".to_string(),
399 location.clone(),
400 true,
401 vec!["partial_computation_lost".to_string()],
402 )
403 }
404 _ => (
405 "general_pause".to_string(),
406 "system".to_string(),
407 true,
408 vec!["all_operations_slowed".to_string()],
409 ),
410 };
411
412 let recovery_time = start.elapsed().as_millis() as u64;
413
414 let response = AntiInflammatoryResponse {
415 inflammation_type: inflammation.clone(),
416 action: action.clone(),
417 target: target.clone(),
418 success,
419 recovery_time_ms: recovery_time,
420 side_effects: side_effects.clone(),
421 timestamp: now,
422 };
423
424 {
426 let mut state = crate::sync_guard::write_lock(&self.state);
427 state.response_history.push(response.clone());
428
429 if state.response_history.len() > 100 {
431 state.response_history.drain(0..50);
432 }
433 }
434
435 self.knowledge_base.add_pitfall(
437 &format!("Inflammation detected: {:?}", inflammation),
438 &format!(
439 "Action taken: {}, Recovery time: {}ms",
440 action, recovery_time
441 ),
442 "system_defense",
443 vec![
444 "vagus_response".to_string(),
445 "anti_inflammatory".to_string(),
446 ],
447 );
448
449 response
450 }
451
452 pub fn activate_parasympathetic(&self) -> bool {
454 let mut state = crate::sync_guard::write_lock(&self.state);
455
456 let tone = state.tone.current;
457 let pulse = &state.pulse;
458 let avg_pressure = (pulse.cpu_pressure
459 + pulse.memory_pressure
460 + pulse.io_pressure
461 + pulse.network_pressure)
462 / 4.0;
463
464 if avg_pressure > self.parasympathetic_threshold && tone < 0.3 {
466 state.parasympathetic_mode = true;
467 state.freeze_initiated = true;
468
469 self.knowledge_base.add_insight(
471 "Parasympathetic Mode Activated",
472 &format!(
473 "System entering rest mode. Avg pressure: {:.2}, Tone: {:.2}",
474 avg_pressure, tone
475 ),
476 vec!["vagus".to_string(), "homeostasis".to_string()],
477 "vagus_system",
478 );
479
480 true
481 } else {
482 false
483 }
484 }
485
486 pub fn deactivate_parasympathetic(&self) -> bool {
488 let state = crate::sync_guard::read_lock(&self.state);
489
490 let tone = state.tone.current;
491 let pulse = &state.pulse;
492 let avg_pressure = (pulse.cpu_pressure
493 + pulse.memory_pressure
494 + pulse.io_pressure
495 + pulse.network_pressure)
496 / 4.0;
497
498 drop(state);
499
500 if avg_pressure < 0.4 && tone > 0.6 {
502 let mut state = crate::sync_guard::write_lock(&self.state);
503 if state.parasympathetic_mode {
504 state.parasympathetic_mode = false;
505 state.freeze_initiated = false;
506
507 self.knowledge_base.add_insight(
508 "Parasympathetic Mode Deactivated",
509 &format!(
510 "System returning to active mode. Avg pressure: {:.2}, Tone: {:.2}",
511 avg_pressure, tone
512 ),
513 vec!["vagus".to_string(), "recovery".to_string()],
514 "vagus_system",
515 );
516
517 return true;
518 }
519 }
520
521 false
522 }
523
524 pub fn get_alert_level(&self) -> AlertLevel {
526 let state = crate::sync_guard::read_lock(&self.state);
527
528 let pulse = &state.pulse;
529 let tone = state.tone.current;
530 let avg_pressure = (pulse.cpu_pressure
531 + pulse.memory_pressure
532 + pulse.io_pressure
533 + pulse.network_pressure)
534 / 4.0;
535
536 if avg_pressure > 0.95 && pulse.hrv < 0.2 {
538 return AlertLevel::Emergency;
539 }
540
541 if avg_pressure > 0.85 {
543 return AlertLevel::Critical;
544 }
545
546 if avg_pressure > 0.7 && tone < 0.4 {
548 return AlertLevel::Stressed;
549 }
550
551 if avg_pressure > 0.5 {
553 return AlertLevel::Vigilant;
554 }
555
556 AlertLevel::Relaxed
558 }
559
560 pub fn get_state(&self) -> VagusState {
562 crate::sync_guard::read_lock(&self.state).clone()
563 }
564
565 pub fn get_tone(&self) -> VagusTone {
567 crate::sync_guard::read_lock(&self.state).tone.clone()
568 }
569
570 pub fn get_unprocessed_gut_feelings(&self) -> Vec<GutFeeling> {
572 let state = crate::sync_guard::read_lock(&self.state);
573 state
574 .gut_feelings
575 .iter()
576 .filter(|f| !f.processed)
577 .cloned()
578 .collect()
579 }
580
581 pub fn mark_gut_feeling_processed(&self, id: &str) {
583 let mut state = crate::sync_guard::write_lock(&self.state);
584 if let Some(feeling) = state.gut_feelings.iter_mut().find(|f| f.id == id) {
585 feeling.processed = true;
586 }
587 }
588
589 pub fn automatic_cycle(&self) -> VagusStatus {
591 let mut status = VagusStatus {
592 pulse_measured: false,
593 tone_updated: false,
594 inflammation_detected: false,
595 response_triggered: false,
596 parasympathetic_activated: false,
597 alert_level: AlertLevel::Relaxed,
598 };
599
600 if crate::sync_guard::read_lock(&self.last_pulse).elapsed()
602 > Duration::from_millis(self.heartbeat_interval_ms)
603 {
604 status.pulse_measured = true;
606 }
607
608 self.update_tone();
610 status.tone_updated = true;
611
612 let inflammations = self.detect_inflammation();
614 status.inflammation_detected = !inflammations.is_empty();
615
616 for inf in &inflammations {
618 self.trigger_anti_inflammatory_response(inf);
619 status.response_triggered = true;
620 }
621
622 let activated = self.activate_parasympathetic();
624 if activated {
625 status.parasympathetic_activated = true;
626 } else {
627 self.deactivate_parasympathetic();
628 }
629
630 status.alert_level = self.get_alert_level();
632
633 status
634 }
635
636 pub fn get_statistics(&self) -> VagusStatistics {
638 let state = crate::sync_guard::read_lock(&self.state);
639
640 VagusStatistics {
641 current_tone: state.tone.current,
642 tone_trend: state.tone.trend,
643 tone_volatility: state.tone.volatility,
644 hrv: state.pulse.hrv,
645 avg_pressure: (state.pulse.cpu_pressure
646 + state.pulse.memory_pressure
647 + state.pulse.io_pressure
648 + state.pulse.network_pressure)
649 / 4.0,
650 gut_feelings_count: state.gut_feelings.len(),
651 unprocessed_gut_feelings: state.gut_feelings.iter().filter(|f| !f.processed).count(),
652 active_inflammations: state.active_inflammations.len(),
653 response_count: state.response_history.len(),
654 parasympathetic_mode: state.parasympathetic_mode,
655 freeze_initiated: state.freeze_initiated,
656 alert_level: self.get_alert_level(),
657 }
658 }
659}
660
661pub struct SystemMetrics {
663 pub cpu_usage: f64,
664 pub memory_usage: f64,
665 pub io_usage: f64,
666 pub network_usage: f64,
667 pub request_rate: f64,
668 pub error_rate: f64,
669}
670
671impl Default for SystemMetrics {
672 fn default() -> Self {
673 Self {
674 cpu_usage: 0.0,
675 memory_usage: 0.0,
676 io_usage: 0.0,
677 network_usage: 0.0,
678 request_rate: 0.0,
679 error_rate: 0.0,
680 }
681 }
682}
683
684#[derive(Debug, Clone)]
686pub struct VagusStatus {
687 pub pulse_measured: bool,
688 pub tone_updated: bool,
689 pub inflammation_detected: bool,
690 pub response_triggered: bool,
691 pub parasympathetic_activated: bool,
692 pub alert_level: AlertLevel,
693}
694
695#[derive(Debug, Clone)]
697pub struct VagusStatistics {
698 pub current_tone: f64,
699 pub tone_trend: f64,
700 pub tone_volatility: f64,
701 pub hrv: f64,
702 pub avg_pressure: f64,
703 pub gut_feelings_count: usize,
704 pub unprocessed_gut_feelings: usize,
705 pub active_inflammations: usize,
706 pub response_count: usize,
707 pub parasympathetic_mode: bool,
708 pub freeze_initiated: bool,
709 pub alert_level: AlertLevel,
710}
711
712impl std::fmt::Display for AlertLevel {
715 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716 match self {
717 AlertLevel::Relaxed => write!(f, "RELAXED"),
718 AlertLevel::Vigilant => write!(f, "VIGILANT"),
719 AlertLevel::Stressed => write!(f, "STRESSED"),
720 AlertLevel::Critical => write!(f, "CRITICAL"),
721 AlertLevel::Emergency => write!(f, "EMERGENCY"),
722 }
723 }
724}
725
726impl std::fmt::Display for VagusStatistics {
727 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
728 writeln!(f, "{}", "═".repeat(40))?;
729 writeln!(f, " VAGUS NERVE STATUS")?;
730 writeln!(f, "{}", "═".repeat(40))?;
731 writeln!(
732 f,
733 " Tone: {:.2} (trend: {:.3}, vol: {:.3})",
734 self.current_tone, self.tone_trend, self.tone_volatility
735 )?;
736 writeln!(f, " HRV: {:.2}", self.hrv)?;
737 writeln!(f, " Avg Pressure: {:.1}%", self.avg_pressure * 100.0)?;
738 writeln!(
739 f,
740 " Gut Feelings: {} / {} pending",
741 self.gut_feelings_count - self.unprocessed_gut_feelings,
742 self.unprocessed_gut_feelings
743 )?;
744 writeln!(f, " Active Inflammations: {}", self.active_inflammations)?;
745 writeln!(f, " Response History: {}", self.response_count)?;
746 writeln!(
747 f,
748 " Parasympathetic: {} | Freeze: {}",
749 if self.parasympathetic_mode {
750 "ACTIVE"
751 } else {
752 "OFF"
753 },
754 if self.freeze_initiated {
755 "ACTIVE"
756 } else {
757 "OFF"
758 }
759 )?;
760 writeln!(f, " Alert Level: {}", self.alert_level)?;
761 writeln!(f, "{}", "═".repeat(40))
762 }
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768
769 fn create_test_vagus() -> VagusNerve {
770 let kb = Arc::new(KnowledgeBase::new());
771 let sim = Arc::new(ArchitectureSimulator::new());
772 VagusNerve::new(sim, kb)
773 }
774
775 #[test]
776 fn test_gut_feeling() {
777 let vagus = create_test_vagus();
778
779 let id = vagus.receive_gut_feeling("test_source", 0.9);
780 assert!(!id.is_empty());
781
782 let feelings = vagus.get_unprocessed_gut_feelings();
783 assert!(!feelings.is_empty());
784
785 vagus.mark_gut_feeling_processed(&id);
786 let feelings = vagus.get_unprocessed_gut_feelings();
787 assert!(feelings.is_empty());
788 }
789
790 #[test]
791 fn test_tone_update() {
792 let vagus = create_test_vagus();
793
794 let metrics = SystemMetrics {
796 cpu_usage: 0.5,
797 memory_usage: 0.3,
798 io_usage: 0.2,
799 network_usage: 0.1,
800 request_rate: 100.0,
801 error_rate: 0.01,
802 };
803 vagus.measure_pulse(&metrics);
804
805 vagus.update_tone();
806 let tone = vagus.get_tone();
807
808 assert!(tone.current >= 0.0 && tone.current <= 1.0);
809 }
810
811 #[test]
812 fn test_alert_level() {
813 let vagus = create_test_vagus();
814
815 let level = vagus.get_alert_level();
817 assert_eq!(level, AlertLevel::Relaxed);
818
819 let metrics = SystemMetrics {
821 cpu_usage: 0.9,
822 memory_usage: 0.9,
823 io_usage: 0.9,
824 network_usage: 0.9,
825 request_rate: 1000.0,
826 error_rate: 0.5,
827 };
828 vagus.measure_pulse(&metrics);
829 vagus.update_tone();
830
831 let level = vagus.get_alert_level();
832 assert!(level >= AlertLevel::Stressed);
833 }
834
835 #[test]
836 fn test_inflammation_detection() {
837 let vagus = create_test_vagus();
838
839 let metrics = SystemMetrics {
841 cpu_usage: 0.5,
842 memory_usage: 0.5,
843 io_usage: 0.5,
844 network_usage: 0.5,
845 request_rate: 500.0,
846 error_rate: 0.2, };
848 vagus.measure_pulse(&metrics);
849 vagus.update_tone();
850
851 let inflammations = vagus.detect_inflammation();
852 assert!(!inflammations.is_empty());
853 }
854}