omega_brain/
lib.rs

1//! Omega Brain
2//!
3//! Unified brain-like cognitive architecture that integrates all Omega components
4//! into a coherent cognitive system resembling biological brain function:
5//!
6//! - **Neural Substrate** (omega-snn): Spiking neurons with STDP learning
7//! - **Attention System** (omega-attention): 39 attention mechanisms
8//! - **Consciousness Core** (omega-consciousness): IIT, GWT, Free Energy
9//! - **Memory System** (omega-hippocampus): Pattern separation/completion, replay
10//! - **Sleep System** (omega-sleep): Consolidation during SWS/REM
11//! - **Self-Awareness** (omega-strange-loops): Meta-cognition, self-model
12//! - **Runtime Adaptation** (ruvector-sona inspired): LoRA, EWC++, ReasoningBank
13//!
14//! The cognitive cycle follows: Perception → Attention → Processing → Memory → Action
15
16pub mod attention_system;
17pub mod cognitive_cycle;
18pub mod config;
19pub mod consciousness_core;
20pub mod memory_system;
21pub mod neural_substrate;
22pub mod runtime_adaptation;
23pub mod self_awareness;
24pub mod sleep_system;
25
26pub use attention_system::AttentionSystem;
27pub use cognitive_cycle::{CognitiveCycle, CognitiveState, ProcessingResult};
28pub use config::{BrainConfig, BrainMode};
29pub use consciousness_core::ConsciousnessCore;
30pub use memory_system::MemorySystem;
31pub use neural_substrate::NeuralSubstrate;
32pub use runtime_adaptation::{
33    AdaptationStats, EWCPlusPlus, LoRAAdapter, LoRAConfig, LoRARank,
34    ReasoningBank, ReasoningPattern, RuntimeAdaptation,
35};
36pub use self_awareness::SelfAwarenessSystem;
37pub use sleep_system::SleepSystem;
38
39use parking_lot::RwLock;
40use serde::{Deserialize, Serialize};
41use std::sync::Arc;
42use thiserror::Error;
43
44/// Errors in brain processing
45#[derive(Debug, Error)]
46pub enum BrainError {
47    #[error("Neural processing failed: {0}")]
48    NeuralError(String),
49
50    #[error("Attention allocation failed: {0}")]
51    AttentionError(String),
52
53    #[error("Consciousness integration failed: {0}")]
54    ConsciousnessError(String),
55
56    #[error("Memory operation failed: {0}")]
57    MemoryError(String),
58
59    #[error("Sleep cycle interrupted: {0}")]
60    SleepError(String),
61
62    #[error("Self-model inconsistency: {0}")]
63    SelfModelError(String),
64
65    #[error("Configuration error: {0}")]
66    ConfigError(String),
67}
68
69pub type Result<T> = std::result::Result<T, BrainError>;
70
71/// Brain state snapshot
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct BrainState {
74    /// Current cognitive state
75    pub cognitive_state: CognitiveStateSnapshot,
76    /// Consciousness level (0-1)
77    pub consciousness_level: f64,
78    /// Attention focus
79    pub attention_focus: Vec<f64>,
80    /// Self-reference strength
81    pub self_reference: f64,
82    /// Current sleep stage (if sleeping)
83    pub sleep_stage: Option<String>,
84    /// Processing cycle count
85    pub cycle_count: u64,
86    /// Timestamp
87    pub timestamp: u64,
88}
89
90/// Simplified cognitive state for serialization
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct CognitiveStateSnapshot {
93    pub mode: String,
94    pub activity_level: f64,
95    pub integration: f64,
96}
97
98/// Brain metrics
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct BrainMetrics {
101    /// Total processing cycles
102    pub cycles: u64,
103    /// Average processing time (ms)
104    pub avg_processing_time: f64,
105    /// IIT Phi value
106    pub phi: f64,
107    /// Free energy
108    pub free_energy: f64,
109    /// Memory consolidation ratio
110    pub consolidation_ratio: f64,
111    /// Strange loop count
112    pub strange_loop_count: usize,
113    /// Neural spike rate
114    pub spike_rate: f64,
115}
116
117/// The unified Omega Brain
118///
119/// Integrates all cognitive components into a single coherent system
120/// that processes information in a brain-like manner.
121pub struct OmegaBrain {
122    /// Configuration
123    config: BrainConfig,
124    /// Neural substrate (spiking networks)
125    neural: Arc<RwLock<NeuralSubstrate>>,
126    /// Attention system
127    attention: Arc<RwLock<AttentionSystem>>,
128    /// Consciousness core (IIT, GWT, FEP)
129    consciousness: Arc<RwLock<ConsciousnessCore>>,
130    /// Memory system (hippocampus)
131    memory: Arc<RwLock<MemorySystem>>,
132    /// Sleep system
133    sleep: Arc<RwLock<SleepSystem>>,
134    /// Self-awareness (strange loops)
135    self_awareness: Arc<RwLock<SelfAwarenessSystem>>,
136    /// Cognitive cycle manager
137    cognitive_cycle: Arc<RwLock<CognitiveCycle>>,
138    /// Processing cycle count
139    cycle_count: Arc<RwLock<u64>>,
140    /// Is brain active
141    is_active: Arc<RwLock<bool>>,
142}
143
144impl OmegaBrain {
145    /// Create a new Omega Brain with default configuration
146    pub fn new() -> Self {
147        Self::with_config(BrainConfig::default())
148    }
149
150    /// Create with custom configuration
151    pub fn with_config(config: BrainConfig) -> Self {
152        let neural = Arc::new(RwLock::new(NeuralSubstrate::new(&config)));
153        let attention = Arc::new(RwLock::new(AttentionSystem::new(&config)));
154        let consciousness = Arc::new(RwLock::new(ConsciousnessCore::new(&config)));
155        let memory = Arc::new(RwLock::new(MemorySystem::new(&config)));
156        let sleep = Arc::new(RwLock::new(SleepSystem::new(&config)));
157        let self_awareness = Arc::new(RwLock::new(SelfAwarenessSystem::new(&config)));
158        let cognitive_cycle = Arc::new(RwLock::new(CognitiveCycle::new(&config)));
159
160        Self {
161            config,
162            neural,
163            attention,
164            consciousness,
165            memory,
166            sleep,
167            self_awareness,
168            cognitive_cycle,
169            cycle_count: Arc::new(RwLock::new(0)),
170            is_active: Arc::new(RwLock::new(true)),
171        }
172    }
173
174    /// Process input through the brain
175    ///
176    /// This is the main entry point for cognitive processing.
177    /// Input flows through: Neural → Attention → Consciousness → Memory → Output
178    pub fn process(&self, input: &[f64]) -> Result<ProcessingResult> {
179        if !*self.is_active.read() {
180            return Err(BrainError::NeuralError("Brain is not active".to_string()));
181        }
182
183        // Check if we should be sleeping
184        {
185            let sleep = self.sleep.read();
186            if sleep.should_sleep() {
187                // Reduced processing during sleep
188                return self.process_during_sleep(input);
189            }
190        }
191
192        // Full cognitive cycle
193        self.run_cognitive_cycle(input)
194    }
195
196    /// Run a full cognitive cycle
197    fn run_cognitive_cycle(&self, input: &[f64]) -> Result<ProcessingResult> {
198        // 1. Neural processing (spiking network)
199        let neural_output = {
200            let mut neural = self.neural.write();
201            neural.process(input)?
202        };
203
204        // 2. Attention allocation
205        let attended = {
206            let mut attention = self.attention.write();
207            attention.attend(&neural_output)?
208        };
209
210        // 3. Consciousness integration (IIT + GWT + FEP)
211        let conscious_content = {
212            let mut consciousness = self.consciousness.write();
213            consciousness.integrate(&attended)?
214        };
215
216        // 4. Memory encoding/retrieval
217        let memory_output = {
218            let mut memory = self.memory.write();
219            memory.process(&conscious_content)?
220        };
221
222        // 5. Self-awareness update
223        let self_aware_output = {
224            let mut self_awareness = self.self_awareness.write();
225            self_awareness.reflect(&memory_output)?
226        };
227
228        // 6. Update cognitive cycle state
229        let result = {
230            let mut cycle = self.cognitive_cycle.write();
231            cycle.complete_cycle(
232                input,
233                &neural_output,
234                &attended,
235                &conscious_content,
236                &memory_output,
237                &self_aware_output,
238            )?
239        };
240
241        // Increment cycle counter
242        {
243            let mut count = self.cycle_count.write();
244            *count += 1;
245        }
246
247        Ok(result)
248    }
249
250    /// Process during sleep (reduced/modified processing)
251    fn process_during_sleep(&self, input: &[f64]) -> Result<ProcessingResult> {
252        // During sleep, run consolidation instead of full processing
253        let mut sleep = self.sleep.write();
254        let mut memory = self.memory.write();
255
256        // Run sleep stage processing
257        let sleep_output = sleep.process_cycle()?;
258
259        // Consolidate memories based on sleep stage
260        if sleep_output.is_sws {
261            memory.consolidate_slow_wave(&sleep_output)?;
262        } else if sleep_output.is_rem {
263            memory.consolidate_rem(&sleep_output)?;
264        }
265
266        // Return minimal processing result
267        Ok(ProcessingResult {
268            output: input.to_vec(),
269            consciousness_level: 0.1, // Low during sleep
270            attention_strength: 0.0,
271            memory_encoded: false,
272            strange_loop_detected: false,
273            processing_time_ms: 0,
274        })
275    }
276
277    /// Get current brain state
278    pub fn state(&self) -> BrainState {
279        let consciousness = self.consciousness.read();
280        let attention = self.attention.read();
281        let self_awareness = self.self_awareness.read();
282        let sleep = self.sleep.read();
283        let cycle = self.cognitive_cycle.read();
284
285        BrainState {
286            cognitive_state: CognitiveStateSnapshot {
287                mode: cycle.current_mode().to_string(),
288                activity_level: cycle.activity_level(),
289                integration: consciousness.integration_level(),
290            },
291            consciousness_level: consciousness.consciousness_level(),
292            attention_focus: attention.current_focus(),
293            self_reference: self_awareness.self_reference_strength(),
294            sleep_stage: sleep.current_stage_name(),
295            cycle_count: *self.cycle_count.read(),
296            timestamp: self.now(),
297        }
298    }
299
300    /// Get brain metrics
301    pub fn metrics(&self) -> BrainMetrics {
302        let consciousness = self.consciousness.read();
303        let memory = self.memory.read();
304        let self_awareness = self.self_awareness.read();
305        let neural = self.neural.read();
306        let cycle = self.cognitive_cycle.read();
307
308        BrainMetrics {
309            cycles: *self.cycle_count.read(),
310            avg_processing_time: cycle.avg_processing_time(),
311            phi: consciousness.phi(),
312            free_energy: consciousness.free_energy(),
313            consolidation_ratio: memory.consolidation_ratio(),
314            strange_loop_count: self_awareness.loop_count(),
315            spike_rate: neural.spike_rate(),
316        }
317    }
318
319    /// Enter sleep mode
320    pub fn sleep(&self) -> Result<()> {
321        let mut sleep = self.sleep.write();
322        sleep.initiate_sleep()?;
323        Ok(())
324    }
325
326    /// Wake up from sleep
327    pub fn wake(&self) -> Result<()> {
328        let mut sleep = self.sleep.write();
329        sleep.wake_up()?;
330        Ok(())
331    }
332
333    /// Force memory consolidation
334    pub fn consolidate_memories(&self) -> Result<usize> {
335        let mut memory = self.memory.write();
336        memory.force_consolidation()
337    }
338
339    /// Think about a specific topic (directed cognition)
340    pub fn think_about(&self, topic: &[f64]) -> Result<Vec<f64>> {
341        // Direct attention to topic
342        {
343            let mut attention = self.attention.write();
344            attention.focus_on(topic)?;
345        }
346
347        // Process through consciousness
348        let conscious = {
349            let mut consciousness = self.consciousness.write();
350            consciousness.deliberate(topic)?
351        };
352
353        // Meta-cognitive reflection
354        let reflected = {
355            let mut self_awareness = self.self_awareness.write();
356            self_awareness.think_about(&conscious)?
357        };
358
359        Ok(reflected)
360    }
361
362    /// Recall a memory
363    pub fn recall(&self, cue: &[f64]) -> Result<Option<Vec<f64>>> {
364        let memory = self.memory.read();
365        memory.retrieve(cue)
366    }
367
368    /// Store a memory
369    pub fn remember(&self, content: &[f64], importance: f64) -> Result<()> {
370        let mut memory = self.memory.write();
371        memory.encode(content, importance)
372    }
373
374    /// Get current consciousness level
375    pub fn consciousness_level(&self) -> f64 {
376        let consciousness = self.consciousness.read();
377        consciousness.consciousness_level()
378    }
379
380    /// Get IIT Phi value
381    pub fn phi(&self) -> f64 {
382        let consciousness = self.consciousness.read();
383        consciousness.phi()
384    }
385
386    /// Check if brain is dreaming
387    pub fn is_dreaming(&self) -> bool {
388        let sleep = self.sleep.read();
389        sleep.is_rem()
390    }
391
392    /// Get self-model state
393    pub fn self_state(&self) -> Vec<f64> {
394        let self_awareness = self.self_awareness.read();
395        self_awareness.current_self_state()
396    }
397
398    /// Activate the brain
399    pub fn activate(&self) {
400        let mut is_active = self.is_active.write();
401        *is_active = true;
402    }
403
404    /// Deactivate the brain
405    pub fn deactivate(&self) {
406        let mut is_active = self.is_active.write();
407        *is_active = false;
408    }
409
410    /// Check if brain is active
411    pub fn is_active(&self) -> bool {
412        *self.is_active.read()
413    }
414
415    /// Get brain configuration
416    pub fn config(&self) -> &BrainConfig {
417        &self.config
418    }
419
420    /// Reset the brain to initial state
421    pub fn reset(&self) {
422        {
423            let mut neural = self.neural.write();
424            neural.reset();
425        }
426        {
427            let mut attention = self.attention.write();
428            attention.reset();
429        }
430        {
431            let mut consciousness = self.consciousness.write();
432            consciousness.reset();
433        }
434        {
435            let mut memory = self.memory.write();
436            memory.reset();
437        }
438        {
439            let mut sleep = self.sleep.write();
440            sleep.reset();
441        }
442        {
443            let mut self_awareness = self.self_awareness.write();
444            self_awareness.reset();
445        }
446        {
447            let mut cycle = self.cognitive_cycle.write();
448            cycle.reset();
449        }
450        {
451            let mut count = self.cycle_count.write();
452            *count = 0;
453        }
454    }
455
456    fn now(&self) -> u64 {
457        std::time::SystemTime::now()
458            .duration_since(std::time::UNIX_EPOCH)
459            .unwrap_or_default()
460            .as_millis() as u64
461    }
462}
463
464impl Default for OmegaBrain {
465    fn default() -> Self {
466        Self::new()
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn test_brain_creation() {
476        let brain = OmegaBrain::new();
477        assert!(brain.is_active());
478        assert_eq!(*brain.cycle_count.read(), 0);
479    }
480
481    #[test]
482    fn test_brain_processing() {
483        let brain = OmegaBrain::new();
484        let input = vec![0.5; 32];
485
486        let result = brain.process(&input);
487        assert!(result.is_ok());
488
489        let metrics = brain.metrics();
490        assert_eq!(metrics.cycles, 1);
491    }
492
493    #[test]
494    fn test_brain_state() {
495        let brain = OmegaBrain::new();
496        let state = brain.state();
497
498        assert!(state.consciousness_level >= 0.0 && state.consciousness_level <= 1.0);
499    }
500
501    #[test]
502    fn test_brain_reset() {
503        let brain = OmegaBrain::new();
504
505        // Process some input
506        let input = vec![0.5; 32];
507        brain.process(&input).unwrap();
508
509        // Reset
510        brain.reset();
511
512        let metrics = brain.metrics();
513        assert_eq!(metrics.cycles, 0);
514    }
515}