1pub 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#[derive(Clone, Debug, Serialize, Deserialize)]
39pub struct Pattern {
40 pub id: PatternId,
42 pub embedding: Vec<f32>,
44 pub metadata: Metadata,
46 pub timestamp: SubstrateTime,
48 pub antecedents: Vec<PatternId>,
50 pub salience: f32,
52}
53
54#[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#[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#[derive(Clone, Debug, Default, Serialize, Deserialize)]
106pub struct Metadata {
107 pub fields: HashMap<String, MetadataValue>,
108}
109
110impl Metadata {
111 pub fn new() -> Self {
113 Self::default()
114 }
115
116 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 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#[derive(Clone, Debug)]
140pub struct SearchResult {
141 pub pattern: Pattern,
142 pub score: f32,
143 pub distance: f32,
144}
145
146#[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#[derive(Clone, Debug)]
170pub enum ManifoldDelta {
171 ContinuousDeform {
173 embedding: Vec<f32>,
174 salience: f32,
175 loss: f32,
176 },
177 DiscreteInsert { id: PatternId },
179}
180
181#[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#[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#[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#[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#[derive(Clone, Debug, Serialize, Deserialize)]
247pub struct Relation {
248 pub relation_type: RelationType,
249 pub properties: serde_json::Value,
250}
251
252#[derive(Clone, Debug, Serialize, Deserialize)]
254pub enum TopologicalQuery {
255 PersistentHomology {
257 dimension: usize,
258 epsilon_range: (f32, f32),
259 },
260 BettiNumbers { max_dimension: usize },
262 SheafConsistency { local_sections: Vec<SectionId> },
264}
265
266#[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#[derive(Clone, Debug, Serialize, Deserialize)]
277pub enum SheafConsistencyResult {
278 Consistent,
279 Inconsistent(Vec<String>),
280 NotConfigured,
281}
282
283#[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
307pub trait SubstrateBackend: Send + Sync {
309 fn similarity_search(
311 &self,
312 query: &[f32],
313 k: usize,
314 filter: Option<&Filter>,
315 ) -> Result<Vec<SearchResult>>;
316
317 fn manifold_deform(&self, pattern: &Pattern, learning_rate: f32) -> Result<ManifoldDelta>;
319
320 fn dimension(&self) -> usize;
322}
323
324#[derive(Clone, Debug, Serialize, Deserialize)]
326pub struct ManifoldConfig {
327 pub dimension: usize,
329 pub max_descent_steps: usize,
331 pub learning_rate: f32,
333 pub convergence_threshold: f32,
335 pub hidden_layers: usize,
337 pub hidden_dim: usize,
339 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}