omega_strange_loops/
lib.rs

1//! Omega Strange Loops
2//!
3//! Self-referential structures inspired by Hofstadter's "I Am a Strange Loop":
4//! - Strange loops: Self-referential feedback systems
5//! - Self-models: Internal representations of self
6//! - Meta-cognition: Thinking about thinking
7//! - Recursive self-improvement: Learning to learn better
8//! - Mirror structures: Representations that represent themselves
9//! - Gödelian self-reference: The limits of self-knowledge
10//! - Consciousness emergence: Detecting awareness of awareness
11//! - The "I": The unified sense of self
12//! - Infinite recursion: Self-models to arbitrary depth
13//!
14//! These structures enable self-awareness and consciousness-like properties.
15//!
16//! # Architecture
17//!
18//! The system is built on several interconnected layers:
19//!
20//! ```text
21//!                    ┌─────────────────────┐
22//!                    │      The "I"        │  ← Unified sense of self
23//!                    │   (self_awareness)  │
24//!                    └──────────┬──────────┘
25//!                               │
26//!         ┌─────────────────────┼─────────────────────┐
27//!         │                     │                     │
28//!         ▼                     ▼                     ▼
29//! ┌───────────────┐   ┌─────────────────┐   ┌─────────────────┐
30//! │   Gödelian    │   │  Consciousness  │   │  Infinite Self  │
31//! │ Self-Reference│   │   Emergence     │   │    (Recursion)  │
32//! └───────┬───────┘   └────────┬────────┘   └────────┬────────┘
33//!         │                    │                     │
34//!         └────────────────────┼─────────────────────┘
35//!                              │
36//!         ┌────────────────────┼────────────────────┐
37//!         │                    │                    │
38//!         ▼                    ▼                    ▼
39//! ┌───────────────┐   ┌───────────────┐   ┌───────────────┐
40//! │ Strange Loops │   │ Meta-Cognition│   │    Mirrors    │
41//! └───────────────┘   └───────────────┘   └───────────────┘
42//!                              │
43//!                              ▼
44//!                    ┌─────────────────┐
45//!                    │   Self-Model    │
46//!                    └─────────────────┘
47//! ```
48//!
49//! # Key Concepts
50//!
51//! - **Strange Loops**: Level-crossing feedback loops where "going up" eventually
52//!   brings you back to where you started
53//! - **Gödelian Self-Reference**: Using Gödel's insights to understand limits
54//!   of self-knowledge
55//! - **Consciousness Emergence**: Detecting signatures of awareness emerging
56//! - **The "I"**: The subjective sense of unified selfhood
57//! - **Infinite Recursion**: Self-models that can recurse to arbitrary depth
58
59pub mod consciousness;
60pub mod godelian;
61pub mod infinite_self;
62pub mod meta_cognition;
63pub mod mirror;
64pub mod self_awareness;
65pub mod self_model;
66pub mod simd_ops;
67pub mod strange_loop;
68
69// Core exports
70pub use meta_cognition::{MetaCognition, MetaLevel, ThoughtAboutThought};
71pub use mirror::{Mirror, MirrorReflection, RecursiveMirror};
72pub use self_model::{SelfModel, SelfModelUpdate, SelfState};
73pub use strange_loop::{LoopLevel, StrangeLoop, TangledHierarchy};
74
75// Advanced self-awareness exports
76pub use consciousness::{
77    ConsciousnessDetector, ConsciousnessSignature, ConsciousnessStream, ExperienceMoment,
78};
79pub use godelian::{GodelianEngine, GodelianInsight, GodelianStats, InsightType, ProofStatus};
80pub use infinite_self::{InfiniteSelf, RecursiveObservation, SelfLevel, WhoIsAskingResult};
81pub use self_awareness::{IBuilder, IComponents, IProcessResult, NarrativeSelf, SelfConcept, TheI};
82pub use simd_ops::{
83    cosine_similarity_f64, cosine_distance_f64, dot_product_f64, l2_distance_f64,
84    consciousness_delta, loop_strength, batch_loop_detection, SimdLevel,
85    evolve_states, weighted_combine, batch_cosine_similarity_f64,
86};
87
88use serde::{Deserialize, Serialize};
89use std::collections::HashMap;
90use thiserror::Error;
91
92/// Errors in strange loop processing
93#[derive(Debug, Error)]
94pub enum StrangeLoopError {
95    #[error("Infinite recursion detected at depth {0}")]
96    InfiniteRecursion(usize),
97
98    #[error("Self-reference paradox: {0}")]
99    Paradox(String),
100
101    #[error("Level mismatch: expected {expected}, got {got}")]
102    LevelMismatch { expected: usize, got: usize },
103
104    #[error("Model update failed: {0}")]
105    ModelUpdateFailed(String),
106}
107
108pub type Result<T> = std::result::Result<T, StrangeLoopError>;
109
110/// Configuration for strange loop system
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct StrangeLoopConfig {
113    /// Maximum recursion depth
114    pub max_depth: usize,
115    /// Number of meta-levels
116    pub meta_levels: usize,
117    /// Self-model update rate
118    pub update_rate: f64,
119    /// Mirror reflection depth
120    pub mirror_depth: usize,
121    /// Enable paradox detection
122    pub detect_paradoxes: bool,
123}
124
125impl Default for StrangeLoopConfig {
126    fn default() -> Self {
127        Self {
128            max_depth: 7,
129            meta_levels: 5,
130            update_rate: 0.1,
131            mirror_depth: 3,
132            detect_paradoxes: true,
133        }
134    }
135}
136
137/// A self-referential symbol
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct SelfReferentialSymbol {
140    /// Symbol ID
141    pub id: String,
142    /// Symbol content
143    pub content: Vec<f64>,
144    /// References to other symbols (including self)
145    pub references: Vec<String>,
146    /// Level in hierarchy
147    pub level: usize,
148    /// Is self-referential
149    pub is_self_ref: bool,
150}
151
152impl SelfReferentialSymbol {
153    pub fn new(id: String, content: Vec<f64>, level: usize) -> Self {
154        Self {
155            id,
156            content,
157            references: Vec::new(),
158            level,
159            is_self_ref: false,
160        }
161    }
162
163    /// Add a reference (potentially self-referential)
164    pub fn add_reference(&mut self, ref_id: String) {
165        if ref_id == self.id {
166            self.is_self_ref = true;
167        }
168        self.references.push(ref_id);
169    }
170
171    /// Check if references itself
172    pub fn references_self(&self) -> bool {
173        self.is_self_ref
174    }
175}
176
177/// The main strange loop engine
178pub struct StrangeLoopEngine {
179    config: StrangeLoopConfig,
180    /// Self-model
181    self_model: SelfModel,
182    /// Meta-cognition system
183    meta_cognition: MetaCognition,
184    /// Strange loops
185    loops: Vec<StrangeLoop>,
186    /// Recursive mirror
187    mirror: RecursiveMirror,
188    /// Symbol table
189    symbols: HashMap<String, SelfReferentialSymbol>,
190    /// Current recursion depth
191    current_depth: usize,
192    /// Processing history
193    history: Vec<ProcessingEvent>,
194}
195
196/// A processing event
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct ProcessingEvent {
199    /// Event type
200    pub event_type: String,
201    /// Recursion depth
202    pub depth: usize,
203    /// Meta-level
204    pub meta_level: usize,
205    /// Timestamp
206    pub timestamp: u64,
207    /// Data
208    pub data: serde_json::Value,
209}
210
211impl StrangeLoopEngine {
212    /// Create new engine
213    pub fn new() -> Self {
214        Self::with_config(StrangeLoopConfig::default())
215    }
216
217    /// Create with custom config
218    pub fn with_config(config: StrangeLoopConfig) -> Self {
219        Self {
220            config: config.clone(),
221            self_model: SelfModel::new(config.meta_levels),
222            meta_cognition: MetaCognition::new(config.meta_levels),
223            loops: Vec::new(),
224            mirror: RecursiveMirror::new(config.mirror_depth),
225            symbols: HashMap::new(),
226            current_depth: 0,
227            history: Vec::new(),
228        }
229    }
230
231    /// Process input through strange loop
232    pub fn process(&mut self, input: &[f64]) -> Result<Vec<f64>> {
233        self.current_depth = 0;
234        self.process_recursive(input)
235    }
236
237    /// Recursive processing with self-reference
238    fn process_recursive(&mut self, input: &[f64]) -> Result<Vec<f64>> {
239        self.current_depth += 1;
240
241        // Check for infinite recursion
242        if self.current_depth > self.config.max_depth {
243            self.current_depth -= 1;
244            return Err(StrangeLoopError::InfiniteRecursion(self.current_depth));
245        }
246
247        // Create processing event
248        let event = ProcessingEvent {
249            event_type: "process".to_string(),
250            depth: self.current_depth,
251            meta_level: self.meta_cognition.current_level(),
252            timestamp: self.now(),
253            data: serde_json::json!({"input_len": input.len()}),
254        };
255        self.history.push(event);
256
257        // 1. Update self-model with input
258        self.self_model.observe(input);
259
260        // 2. Meta-cognitive processing
261        let meta_output = self.meta_cognition.process(input)?;
262
263        // 3. Mirror reflection (see ourselves seeing)
264        let reflection = self.mirror.reflect(input);
265
266        // 4. Check for strange loops (self-reference)
267        let loop_contribution = self.detect_loops(input, &reflection);
268
269        // 5. Combine outputs
270        let mut output = Vec::with_capacity(input.len());
271        for (i, &input_val) in input.iter().enumerate() {
272            let meta = meta_output.get(i).copied().unwrap_or(0.0);
273            let refl = reflection.get(i).copied().unwrap_or(0.0);
274            let loop_val = loop_contribution.get(i).copied().unwrap_or(0.0);
275
276            output.push(input_val * 0.4 + meta * 0.3 + refl * 0.2 + loop_val * 0.1);
277        }
278
279        // 6. Self-reference: feed output back to self-model
280        self.self_model.update(&output);
281
282        self.current_depth -= 1;
283        Ok(output)
284    }
285
286    /// Detect strange loops in processing
287    fn detect_loops(&mut self, input: &[f64], reflection: &[f64]) -> Vec<f64> {
288        // Compute similarity between input and reflection
289        let similarity = self.cosine_similarity(input, reflection);
290
291        // High similarity = strong self-reference = strange loop
292        if similarity > 0.8 {
293            // Create or strengthen loop
294            let loop_id = format!("loop_{}", self.loops.len());
295            let new_loop = StrangeLoop::new(loop_id, self.current_depth, similarity);
296            self.loops.push(new_loop);
297        }
298
299        // Loop contribution based on active loops
300        let loop_strength: f64 = self
301            .loops
302            .iter()
303            .map(|l| l.strength * (1.0 / (1.0 + l.level as f64)))
304            .sum::<f64>()
305            / self.loops.len().max(1) as f64;
306
307        input.iter().map(|&x| x * loop_strength).collect()
308    }
309
310    /// Cosine similarity (SIMD-accelerated)
311    #[inline]
312    fn cosine_similarity(&self, a: &[f64], b: &[f64]) -> f64 {
313        simd_ops::cosine_similarity_f64(a, b)
314    }
315
316    /// Think about own thinking
317    pub fn meta_think(&mut self, thought: &[f64]) -> Result<ThoughtAboutThought> {
318        self.meta_cognition.think_about(thought)
319    }
320
321    /// Get self-model state
322    pub fn self_state(&self) -> SelfState {
323        self.self_model.current_state()
324    }
325
326    /// Get mirror reflection
327    pub fn get_reflection(&mut self, input: &[f64]) -> Vec<f64> {
328        self.mirror.reflect(input)
329    }
330
331    /// Add self-referential symbol
332    pub fn add_symbol(&mut self, symbol: SelfReferentialSymbol) {
333        self.symbols.insert(symbol.id.clone(), symbol);
334    }
335
336    /// Get symbol by ID
337    pub fn get_symbol(&self, id: &str) -> Option<&SelfReferentialSymbol> {
338        self.symbols.get(id)
339    }
340
341    /// Count strange loops
342    pub fn loop_count(&self) -> usize {
343        self.loops.len()
344    }
345
346    /// Get current recursion depth
347    pub fn current_depth(&self) -> usize {
348        self.current_depth
349    }
350
351    /// Get statistics
352    pub fn stats(&self) -> StrangeLoopStats {
353        StrangeLoopStats {
354            loop_count: self.loops.len(),
355            symbol_count: self.symbols.len(),
356            meta_level: self.meta_cognition.current_level(),
357            self_reference_strength: self.self_model.self_reference_strength(),
358            history_size: self.history.len(),
359        }
360    }
361
362    fn now(&self) -> u64 {
363        std::time::SystemTime::now()
364            .duration_since(std::time::UNIX_EPOCH)
365            .unwrap_or_default()
366            .as_millis() as u64
367    }
368
369    /// Reset engine
370    pub fn reset(&mut self) {
371        self.self_model = SelfModel::new(self.config.meta_levels);
372        self.meta_cognition = MetaCognition::new(self.config.meta_levels);
373        self.loops.clear();
374        self.mirror = RecursiveMirror::new(self.config.mirror_depth);
375        self.symbols.clear();
376        self.current_depth = 0;
377        self.history.clear();
378    }
379}
380
381impl Default for StrangeLoopEngine {
382    fn default() -> Self {
383        Self::new()
384    }
385}
386
387/// Statistics about strange loop engine
388#[derive(Debug, Clone, Serialize, Deserialize)]
389pub struct StrangeLoopStats {
390    pub loop_count: usize,
391    pub symbol_count: usize,
392    pub meta_level: usize,
393    pub self_reference_strength: f64,
394    pub history_size: usize,
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn test_engine_creation() {
403        let engine = StrangeLoopEngine::new();
404        assert_eq!(engine.loop_count(), 0);
405        assert_eq!(engine.current_depth(), 0);
406    }
407
408    #[test]
409    fn test_process() {
410        let mut engine = StrangeLoopEngine::new();
411        let input = vec![0.5; 10];
412
413        let output = engine.process(&input).unwrap();
414        assert_eq!(output.len(), 10);
415    }
416
417    #[test]
418    fn test_self_referential_symbol() {
419        let mut symbol = SelfReferentialSymbol::new("sym1".to_string(), vec![1.0; 5], 0);
420
421        assert!(!symbol.references_self());
422
423        symbol.add_reference("sym1".to_string());
424        assert!(symbol.references_self());
425    }
426
427    #[test]
428    fn test_max_depth() {
429        let mut engine = StrangeLoopEngine::with_config(StrangeLoopConfig {
430            max_depth: 2,
431            ..Default::default()
432        });
433
434        // Should work within limits
435        let result = engine.process(&vec![0.5; 5]);
436        assert!(result.is_ok());
437    }
438
439    #[test]
440    fn test_stats() {
441        let engine = StrangeLoopEngine::new();
442        let stats = engine.stats();
443
444        assert_eq!(stats.loop_count, 0);
445        assert_eq!(stats.symbol_count, 0);
446    }
447}