exo_core/
lib.rs

1//! Core trait definitions and types for EXO-AI cognitive substrate
2//!
3//! This crate provides the foundational abstractions that all other EXO-AI
4//! crates build upon, including backend traits, pattern representations,
5//! and core error types.
6//!
7//! # Theoretical Framework Modules
8//!
9//! - [`consciousness`]: Integrated Information Theory (IIT 4.0) implementation
10//!   for computing Φ (phi) - the measure of integrated information
11//! - [`thermodynamics`]: Landauer's Principle tracking for measuring
12//!   computational efficiency relative to fundamental physics limits
13
14pub mod consciousness;
15pub mod thermodynamics;
16
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::fmt;
20use uuid::Uuid;
21
22/// Pattern representation in substrate
23#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct Pattern {
25    /// Unique identifier
26    pub id: PatternId,
27    /// Vector embedding
28    pub embedding: Vec<f32>,
29    /// Metadata
30    pub metadata: Metadata,
31    /// Temporal origin
32    pub timestamp: SubstrateTime,
33    /// Causal antecedents
34    pub antecedents: Vec<PatternId>,
35    /// Salience score (importance)
36    pub salience: f32,
37}
38
39/// Pattern identifier
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
41pub struct PatternId(pub Uuid);
42
43impl PatternId {
44    pub fn new() -> Self {
45        Self(Uuid::new_v4())
46    }
47}
48
49impl Default for PatternId {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55impl fmt::Display for PatternId {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{}", self.0)
58    }
59}
60
61/// Substrate time representation (nanoseconds since epoch)
62#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
63pub struct SubstrateTime(pub i64);
64
65impl SubstrateTime {
66    pub const MIN: Self = Self(i64::MIN);
67    pub const MAX: Self = Self(i64::MAX);
68
69    pub fn now() -> Self {
70        use std::time::{SystemTime, UNIX_EPOCH};
71        let duration = SystemTime::now()
72            .duration_since(UNIX_EPOCH)
73            .expect("Time went backwards");
74        Self(duration.as_nanos() as i64)
75    }
76
77    pub fn abs(&self) -> Self {
78        Self(self.0.abs())
79    }
80}
81
82impl std::ops::Sub for SubstrateTime {
83    type Output = Self;
84    fn sub(self, rhs: Self) -> Self::Output {
85        Self(self.0 - rhs.0)
86    }
87}
88
89/// Metadata for patterns
90#[derive(Clone, Debug, Default, Serialize, Deserialize)]
91pub struct Metadata {
92    pub fields: HashMap<String, MetadataValue>,
93}
94
95impl Metadata {
96    /// Create empty metadata
97    pub fn new() -> Self {
98        Self::default()
99    }
100
101    /// Create metadata with a single field
102    pub fn with_field(key: impl Into<String>, value: MetadataValue) -> Self {
103        let mut fields = HashMap::new();
104        fields.insert(key.into(), value);
105        Self { fields }
106    }
107
108    /// Add a field
109    pub fn insert(&mut self, key: impl Into<String>, value: MetadataValue) -> &mut Self {
110        self.fields.insert(key.into(), value);
111        self
112    }
113}
114
115#[derive(Clone, Debug, Serialize, Deserialize)]
116pub enum MetadataValue {
117    String(String),
118    Number(f64),
119    Boolean(bool),
120    Array(Vec<MetadataValue>),
121}
122
123/// Search result
124#[derive(Clone, Debug)]
125pub struct SearchResult {
126    pub pattern: Pattern,
127    pub score: f32,
128    pub distance: f32,
129}
130
131/// Filter for search operations
132#[derive(Clone, Debug, Serialize, Deserialize)]
133pub struct Filter {
134    pub conditions: Vec<FilterCondition>,
135}
136
137#[derive(Clone, Debug, Serialize, Deserialize)]
138pub struct FilterCondition {
139    pub field: String,
140    pub operator: FilterOperator,
141    pub value: MetadataValue,
142}
143
144#[derive(Clone, Debug, Serialize, Deserialize)]
145pub enum FilterOperator {
146    Equal,
147    NotEqual,
148    GreaterThan,
149    LessThan,
150    Contains,
151}
152
153/// Manifold delta result from deformation
154#[derive(Clone, Debug)]
155pub enum ManifoldDelta {
156    /// Continuous deformation applied
157    ContinuousDeform {
158        embedding: Vec<f32>,
159        salience: f32,
160        loss: f32,
161    },
162    /// Classical discrete insert (for classical backend)
163    DiscreteInsert { id: PatternId },
164}
165
166/// Entity identifier (for hypergraph)
167#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
168pub struct EntityId(pub Uuid);
169
170impl EntityId {
171    pub fn new() -> Self {
172        Self(Uuid::new_v4())
173    }
174}
175
176impl Default for EntityId {
177    fn default() -> Self {
178        Self::new()
179    }
180}
181
182impl fmt::Display for EntityId {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        write!(f, "{}", self.0)
185    }
186}
187
188/// Hyperedge identifier
189#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
190pub struct HyperedgeId(pub Uuid);
191
192impl HyperedgeId {
193    pub fn new() -> Self {
194        Self(Uuid::new_v4())
195    }
196}
197
198impl Default for HyperedgeId {
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204/// Section identifier (for sheaf structures)
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
206pub struct SectionId(pub Uuid);
207
208impl SectionId {
209    pub fn new() -> Self {
210        Self(Uuid::new_v4())
211    }
212}
213
214impl Default for SectionId {
215    fn default() -> Self {
216        Self::new()
217    }
218}
219
220/// Relation type for hyperedges
221#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
222pub struct RelationType(pub String);
223
224impl RelationType {
225    pub fn new(s: impl Into<String>) -> Self {
226        Self(s.into())
227    }
228}
229
230/// Relation between entities in hyperedge
231#[derive(Clone, Debug, Serialize, Deserialize)]
232pub struct Relation {
233    pub relation_type: RelationType,
234    pub properties: serde_json::Value,
235}
236
237/// Topological query specification
238#[derive(Clone, Debug, Serialize, Deserialize)]
239pub enum TopologicalQuery {
240    /// Find persistent homology features
241    PersistentHomology {
242        dimension: usize,
243        epsilon_range: (f32, f32),
244    },
245    /// Find Betti numbers
246    BettiNumbers { max_dimension: usize },
247    /// Sheaf consistency check
248    SheafConsistency { local_sections: Vec<SectionId> },
249}
250
251/// Result from hyperedge query
252#[derive(Clone, Debug, Serialize, Deserialize)]
253pub enum HyperedgeResult {
254    PersistenceDiagram(Vec<(f32, f32)>),
255    BettiNumbers(Vec<usize>),
256    SheafConsistency(SheafConsistencyResult),
257    NotSupported,
258}
259
260/// Sheaf consistency result
261#[derive(Clone, Debug, Serialize, Deserialize)]
262pub enum SheafConsistencyResult {
263    Consistent,
264    Inconsistent(Vec<String>),
265    NotConfigured,
266}
267
268/// Error types
269#[derive(Debug, thiserror::Error)]
270pub enum Error {
271    #[error("Pattern not found: {0}")]
272    PatternNotFound(PatternId),
273
274    #[error("Invalid embedding dimension: expected {expected}, got {got}")]
275    InvalidDimension { expected: usize, got: usize },
276
277    #[error("Backend error: {0}")]
278    Backend(String),
279
280    #[error("Convergence failed")]
281    ConvergenceFailed,
282
283    #[error("Invalid configuration: {0}")]
284    InvalidConfig(String),
285
286    #[error("Not found: {0}")]
287    NotFound(String),
288}
289
290pub type Result<T> = std::result::Result<T, Error>;
291
292/// Backend trait for substrate compute operations
293pub trait SubstrateBackend: Send + Sync {
294    /// Execute similarity search on substrate
295    fn similarity_search(
296        &self,
297        query: &[f32],
298        k: usize,
299        filter: Option<&Filter>,
300    ) -> Result<Vec<SearchResult>>;
301
302    /// Deform manifold to incorporate new pattern
303    fn manifold_deform(
304        &self,
305        pattern: &Pattern,
306        learning_rate: f32,
307    ) -> Result<ManifoldDelta>;
308
309    /// Get embedding dimension
310    fn dimension(&self) -> usize;
311}
312
313/// Configuration for manifold operations
314#[derive(Clone, Debug, Serialize, Deserialize)]
315pub struct ManifoldConfig {
316    /// Embedding dimension
317    pub dimension: usize,
318    /// Maximum gradient descent steps
319    pub max_descent_steps: usize,
320    /// Learning rate for gradient descent
321    pub learning_rate: f32,
322    /// Convergence threshold for gradient norm
323    pub convergence_threshold: f32,
324    /// Number of hidden layers
325    pub hidden_layers: usize,
326    /// Hidden dimension size
327    pub hidden_dim: usize,
328    /// Omega_0 for SIREN (frequency parameter)
329    pub omega_0: f32,
330}
331
332impl Default for ManifoldConfig {
333    fn default() -> Self {
334        Self {
335            dimension: 768,
336            max_descent_steps: 100,
337            learning_rate: 0.01,
338            convergence_threshold: 1e-4,
339            hidden_layers: 3,
340            hidden_dim: 256,
341            omega_0: 30.0,
342        }
343    }
344}