Skip to main content

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