omega_brain/
self_awareness.rs

1//! Self-Awareness System - Self-contained strange loops and meta-cognition
2
3use crate::{BrainConfig, Result};
4use serde::{Deserialize, Serialize};
5
6/// Strange loop config
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct StrangeLoopConfig {
9    pub max_depth: usize,
10    pub meta_levels: usize,
11    pub update_rate: f64,
12    pub mirror_depth: usize,
13    pub detect_paradoxes: bool,
14}
15
16/// Self state
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct SelfState {
19    pub state: Vec<f64>,
20}
21
22/// Thought about thought
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ThoughtAboutThought {
25    pub meta: Vec<f64>,
26}
27
28/// Self model
29#[derive(Debug, Clone)]
30pub struct SelfModel {
31    state: Vec<f64>,
32    observations: Vec<Vec<f64>>,
33    confidence: f64,
34    self_ref_strength: f64,
35}
36
37impl SelfModel {
38    pub fn new(dim: usize) -> Self {
39        Self { state: vec![0.0; dim], observations: Vec::new(), confidence: 0.5, self_ref_strength: 0.0 }
40    }
41    pub fn observe(&mut self, input: &[f64]) {
42        self.observations.push(input.to_vec());
43        if self.observations.len() > 100 { self.observations.remove(0); }
44    }
45    pub fn update(&mut self, output: &[f64]) {
46        for (i, &v) in output.iter().enumerate() {
47            if i < self.state.len() { self.state[i] = 0.9 * self.state[i] + 0.1 * v; }
48        }
49        if !self.observations.is_empty() {
50            let last = &self.observations[self.observations.len() - 1];
51            let sim = self.cosine_similarity(&self.state, last);
52            self.self_ref_strength = 0.9 * self.self_ref_strength + 0.1 * sim;
53            self.confidence = 0.9 * self.confidence + 0.1 * sim.abs();
54        }
55    }
56    pub fn current_state(&self) -> SelfState { SelfState { state: self.state.clone() } }
57    pub fn self_reference_strength(&self) -> f64 { self.self_ref_strength }
58    pub fn confidence(&self) -> f64 { self.confidence }
59    pub fn reset(&mut self) {
60        self.state.fill(0.0);
61        self.observations.clear();
62        self.confidence = 0.5;
63        self.self_ref_strength = 0.0;
64    }
65    fn cosine_similarity(&self, a: &[f64], b: &[f64]) -> f64 {
66        let mut dot = 0.0; let mut na = 0.0; let mut nb = 0.0;
67        for (&x, &y) in a.iter().zip(b.iter()) { dot += x * y; na += x * x; nb += y * y; }
68        let denom = (na * nb).sqrt();
69        if denom > 0.0 { dot / denom } else { 0.0 }
70    }
71}
72
73/// Meta-cognition
74#[derive(Debug, Clone)]
75pub struct MetaCognition {
76    levels: usize,
77    current_level: usize,
78    quality: f64,
79}
80
81impl MetaCognition {
82    pub fn new(levels: usize) -> Self { Self { levels, current_level: 0, quality: 0.5 } }
83    pub fn think_about(&mut self, thought: &[f64]) -> std::result::Result<ThoughtAboutThought, String> {
84        self.current_level = (self.current_level + 1) % self.levels;
85        let decay = 1.0 / (self.current_level + 1) as f64;
86        let meta: Vec<f64> = thought.iter().map(|&x| x * decay).collect();
87        self.quality = meta.iter().map(|x| x.abs()).sum::<f64>() / meta.len().max(1) as f64;
88        Ok(ThoughtAboutThought { meta })
89    }
90    pub fn cognitive_quality(&self) -> f64 { self.quality }
91    pub fn current_level(&self) -> usize { self.current_level }
92    pub fn reset(&mut self) { self.current_level = 0; self.quality = 0.5; }
93}
94
95/// Strange loop engine
96#[derive(Debug, Clone)]
97pub struct StrangeLoopEngine {
98    config: StrangeLoopConfig,
99    loop_count: usize,
100    dim: usize,
101}
102
103impl StrangeLoopEngine {
104    pub fn with_config(config: StrangeLoopConfig) -> Self {
105        Self { dim: 64, loop_count: 0, config }
106    }
107    pub fn process(&mut self, input: &[f64]) -> std::result::Result<Vec<f64>, String> {
108        self.loop_count += 1;
109        // Use dim to limit output size if needed
110        let output: Vec<f64> = input.iter().take(self.dim).enumerate()
111            .map(|(i, &x)| x * (1.0 / (1 + i % self.config.max_depth) as f64))
112            .collect();
113        Ok(output)
114    }
115    pub fn loop_count(&self) -> usize { self.loop_count }
116    pub fn dim(&self) -> usize { self.dim }
117    pub fn reset(&mut self) { self.loop_count = 0; }
118}
119
120/// Self-awareness system
121pub struct SelfAwarenessSystem {
122    engine: StrangeLoopEngine,
123    self_model: SelfModel,
124    meta_cognition: MetaCognition,
125    loop_count: usize,
126    self_ref_strength: f64,
127    dim: usize,
128}
129
130impl SelfAwarenessSystem {
131    pub fn new(config: &BrainConfig) -> Self {
132        let sl_config = StrangeLoopConfig {
133            max_depth: config.max_recursion,
134            meta_levels: config.meta_levels,
135            update_rate: config.self_update_rate,
136            mirror_depth: config.mirror_depth,
137            detect_paradoxes: true,
138        };
139        Self {
140            engine: StrangeLoopEngine::with_config(sl_config),
141            self_model: SelfModel::new(config.attention_dim),
142            meta_cognition: MetaCognition::new(config.meta_levels),
143            loop_count: 0,
144            self_ref_strength: 0.0,
145            dim: config.attention_dim,
146        }
147    }
148    pub fn reflect(&mut self, input: &[f64]) -> Result<Vec<f64>> {
149        let normalized: Vec<f64> = (0..self.dim).map(|i| input.get(i).copied().unwrap_or(0.0)).collect();
150        let output = self.engine.process(&normalized).map_err(crate::BrainError::SelfModelError)?;
151        self.self_model.observe(&normalized);
152        self.self_model.update(&output);
153        self.self_ref_strength = self.self_model.self_reference_strength();
154        self.loop_count = self.engine.loop_count();
155        Ok(output)
156    }
157    pub fn think_about(&mut self, thought: &[f64]) -> Result<Vec<f64>> {
158        let normalized: Vec<f64> = (0..self.dim).map(|i| thought.get(i).copied().unwrap_or(0.0)).collect();
159        let tat = self.meta_cognition.think_about(&normalized).map_err(crate::BrainError::SelfModelError)?;
160        let output = self.engine.process(&tat.meta).map_err(crate::BrainError::SelfModelError)?;
161        Ok(output)
162    }
163    pub fn current_self_state(&self) -> Vec<f64> { self.self_model.current_state().state }
164    pub fn self_reference_strength(&self) -> f64 { self.self_ref_strength }
165    pub fn loop_count(&self) -> usize { self.loop_count }
166    pub fn confidence(&self) -> f64 { self.self_model.confidence() }
167    pub fn cognitive_quality(&self) -> f64 { self.meta_cognition.cognitive_quality() }
168    pub fn has_paradox(&self) -> bool { self.self_ref_strength > 0.95 && self.loop_count > 10 }
169    pub fn meta_level_count(&self) -> usize { self.meta_cognition.current_level() }
170    pub fn reset(&mut self) {
171        self.engine.reset();
172        self.self_model.reset();
173        self.meta_cognition.reset();
174        self.loop_count = 0;
175        self.self_ref_strength = 0.0;
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    #[test]
183    fn test_self_model() {
184        let mut sm = SelfModel::new(8);
185        sm.observe(&vec![0.5; 8]);
186        sm.update(&vec![0.3; 8]);
187        assert!(sm.confidence() >= 0.0);
188    }
189}