1pub mod consciousness;
15pub mod thermodynamics;
16
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::fmt;
20use uuid::Uuid;
21
22#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct Pattern {
25 pub id: PatternId,
27 pub embedding: Vec<f32>,
29 pub metadata: Metadata,
31 pub timestamp: SubstrateTime,
33 pub antecedents: Vec<PatternId>,
35 pub salience: f32,
37}
38
39#[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#[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#[derive(Clone, Debug, Default, Serialize, Deserialize)]
91pub struct Metadata {
92 pub fields: HashMap<String, MetadataValue>,
93}
94
95impl Metadata {
96 pub fn new() -> Self {
98 Self::default()
99 }
100
101 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 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#[derive(Clone, Debug)]
125pub struct SearchResult {
126 pub pattern: Pattern,
127 pub score: f32,
128 pub distance: f32,
129}
130
131#[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#[derive(Clone, Debug)]
155pub enum ManifoldDelta {
156 ContinuousDeform {
158 embedding: Vec<f32>,
159 salience: f32,
160 loss: f32,
161 },
162 DiscreteInsert { id: PatternId },
164}
165
166#[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#[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#[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#[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#[derive(Clone, Debug, Serialize, Deserialize)]
232pub struct Relation {
233 pub relation_type: RelationType,
234 pub properties: serde_json::Value,
235}
236
237#[derive(Clone, Debug, Serialize, Deserialize)]
239pub enum TopologicalQuery {
240 PersistentHomology {
242 dimension: usize,
243 epsilon_range: (f32, f32),
244 },
245 BettiNumbers { max_dimension: usize },
247 SheafConsistency { local_sections: Vec<SectionId> },
249}
250
251#[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#[derive(Clone, Debug, Serialize, Deserialize)]
262pub enum SheafConsistencyResult {
263 Consistent,
264 Inconsistent(Vec<String>),
265 NotConfigured,
266}
267
268#[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
292pub trait SubstrateBackend: Send + Sync {
294 fn similarity_search(
296 &self,
297 query: &[f32],
298 k: usize,
299 filter: Option<&Filter>,
300 ) -> Result<Vec<SearchResult>>;
301
302 fn manifold_deform(
304 &self,
305 pattern: &Pattern,
306 learning_rate: f32,
307 ) -> Result<ManifoldDelta>;
308
309 fn dimension(&self) -> usize;
311}
312
313#[derive(Clone, Debug, Serialize, Deserialize)]
315pub struct ManifoldConfig {
316 pub dimension: usize,
318 pub max_descent_steps: usize,
320 pub learning_rate: f32,
322 pub convergence_threshold: f32,
324 pub hidden_layers: usize,
326 pub hidden_dim: usize,
328 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}