1pub 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
69pub 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
75pub 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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct StrangeLoopConfig {
113 pub max_depth: usize,
115 pub meta_levels: usize,
117 pub update_rate: f64,
119 pub mirror_depth: usize,
121 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#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct SelfReferentialSymbol {
140 pub id: String,
142 pub content: Vec<f64>,
144 pub references: Vec<String>,
146 pub level: usize,
148 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 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 pub fn references_self(&self) -> bool {
173 self.is_self_ref
174 }
175}
176
177pub struct StrangeLoopEngine {
179 config: StrangeLoopConfig,
180 self_model: SelfModel,
182 meta_cognition: MetaCognition,
184 loops: Vec<StrangeLoop>,
186 mirror: RecursiveMirror,
188 symbols: HashMap<String, SelfReferentialSymbol>,
190 current_depth: usize,
192 history: Vec<ProcessingEvent>,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct ProcessingEvent {
199 pub event_type: String,
201 pub depth: usize,
203 pub meta_level: usize,
205 pub timestamp: u64,
207 pub data: serde_json::Value,
209}
210
211impl StrangeLoopEngine {
212 pub fn new() -> Self {
214 Self::with_config(StrangeLoopConfig::default())
215 }
216
217 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 pub fn process(&mut self, input: &[f64]) -> Result<Vec<f64>> {
233 self.current_depth = 0;
234 self.process_recursive(input)
235 }
236
237 fn process_recursive(&mut self, input: &[f64]) -> Result<Vec<f64>> {
239 self.current_depth += 1;
240
241 if self.current_depth > self.config.max_depth {
243 self.current_depth -= 1;
244 return Err(StrangeLoopError::InfiniteRecursion(self.current_depth));
245 }
246
247 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 self.self_model.observe(input);
259
260 let meta_output = self.meta_cognition.process(input)?;
262
263 let reflection = self.mirror.reflect(input);
265
266 let loop_contribution = self.detect_loops(input, &reflection);
268
269 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 self.self_model.update(&output);
281
282 self.current_depth -= 1;
283 Ok(output)
284 }
285
286 fn detect_loops(&mut self, input: &[f64], reflection: &[f64]) -> Vec<f64> {
288 let similarity = self.cosine_similarity(input, reflection);
290
291 if similarity > 0.8 {
293 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 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 #[inline]
312 fn cosine_similarity(&self, a: &[f64], b: &[f64]) -> f64 {
313 simd_ops::cosine_similarity_f64(a, b)
314 }
315
316 pub fn meta_think(&mut self, thought: &[f64]) -> Result<ThoughtAboutThought> {
318 self.meta_cognition.think_about(thought)
319 }
320
321 pub fn self_state(&self) -> SelfState {
323 self.self_model.current_state()
324 }
325
326 pub fn get_reflection(&mut self, input: &[f64]) -> Vec<f64> {
328 self.mirror.reflect(input)
329 }
330
331 pub fn add_symbol(&mut self, symbol: SelfReferentialSymbol) {
333 self.symbols.insert(symbol.id.clone(), symbol);
334 }
335
336 pub fn get_symbol(&self, id: &str) -> Option<&SelfReferentialSymbol> {
338 self.symbols.get(id)
339 }
340
341 pub fn loop_count(&self) -> usize {
343 self.loops.len()
344 }
345
346 pub fn current_depth(&self) -> usize {
348 self.current_depth
349 }
350
351 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 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#[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 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}