xynthe 0.1.0

A unified orchestration framework for autonomous intelligence with temporal continuity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Context Fabrics - Temporally aware memory substrates
//!
//! Context fabrics provide multi-layered temporal memory with four access patterns:
//! - recall(query, t₁, t₂): Retrieve events within temporal window
//! - project(query, t_future): Hypothesize future state based on trends
//! - diff(state₁, state₂): Compute semantic delta between contexts
//! - consolidate(events): Distill episodic memories into semantic knowledge

use crate::error::Result;
use crate::thought_stream::ThoughtEvent;
use crate::types::{StructuredContent, Timestamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Access pattern for context operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccessPattern {
    /// Retrieve events within temporal window
    #[default]
    Recall,

    /// Hypothesize future state
    Project,

    /// Compute semantic delta
    Diff,

    /// Distill episodic memories
    Consolidate,
}

/// Layer of context fabric
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextLayer {
    /// Current interaction tokens (sub-second latency)
    Immediate,

    /// Active task context (minutes-hours)
    Working,

    /// Past interactions with semantic indexing (days-months)
    Episodic,

    /// Abstracted knowledge from experience (persistent)
    Semantic,
}

impl ContextLayer {
    /// Get the retention duration for this layer
    pub fn retention(&self) -> chrono::Duration {
        match self {
            Self::Immediate => chrono::Duration::seconds(30),
            Self::Working => chrono::Duration::hours(24),
            Self::Episodic => chrono::Duration::days(365),
            Self::Semantic => chrono::Duration::max_value(),
        }
    }
}

/// Time window for queries
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TimeWindow {
    /// Start time (inclusive)
    pub start: Timestamp,

    /// End time (inclusive)
    pub end: Timestamp,

    /// Whether the window is anchored to current time
    anchored: bool,
}

impl TimeWindow {
    /// Create a time window from start to end
    pub fn new(start: Timestamp, end: Timestamp) -> Self {
        Self {
            start,
            end,
            anchored: false,
        }
    }

    /// Create a time window anchored to now
    pub fn from_now(duration: chrono::Duration) -> Self {
        let now = Timestamp::now();
        let start = Timestamp::from_datetime(now.as_datetime() - duration);
        Self {
            start,
            end: now,
            anchored: true,
        }
    }

    /// Check if a timestamp falls within this window
    pub fn contains(&self, timestamp: Timestamp) -> bool {
        timestamp >= self.start && timestamp <= self.end
    }
}

/// Query specification for context fabric
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContextQuery {
    /// Semantic query string
    pub query: String,

    /// Temporal window
    pub window: TimeWindow,

    /// Target layer
    pub layer: ContextLayer,

    /// Access pattern for this query
    pub pattern: AccessPattern,

    /// Maximum results to return
    pub limit: Option<usize>,

    /// Confidence threshold
    pub min_confidence: f64,
}

impl ContextQuery {
    /// Create a new query
    pub fn new(query: impl Into<String>, window: TimeWindow, layer: ContextLayer, pattern: AccessPattern) -> Self {
        Self {
            query: query.into(),
            window,
            layer,
            pattern,
            limit: None,
            min_confidence: 0.0,
        }
    }

    /// Set the result limit
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set the minimum confidence
    pub fn with_min_confidence(mut self, confidence: f64) -> Self {
        self.min_confidence = confidence.clamp(0.0, 1.0);
        self
    }

    /// Create a recall query
    pub fn recall(query: impl Into<String>, window: TimeWindow) -> Self {
        Self::new(query, window, ContextLayer::Episodic, AccessPattern::Recall)
    }

    /// Create a projection query
    pub fn project(query: impl Into<String>, window: TimeWindow) -> Self {
        Self::new(query, window, ContextLayer::Semantic, AccessPattern::Project)
    }
}

/// Event stored in context fabric
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContextEvent {
    /// Event data
    pub content: StructuredContent,

    /// Timestamp
    pub timestamp: Timestamp,

    /// Causal chain index
    pub causal_chain: Vec<usize>,

    /// Confidence score
    pub confidence: f64,

    /// Source layer
    pub layer: ContextLayer,
}

/// Result of context query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContextResult {
    /// Retrieved events
    pub events: Vec<ContextEvent>,

    /// Query metadata
    pub metadata: QueryMetadata,
}

impl ContextResult {
    /// Create a new result
    pub fn new(events: Vec<ContextEvent>, metadata: QueryMetadata) -> Self {
        Self { events, metadata }
    }

    /// Get the number of events
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if result is empty
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Get events with confidence above threshold
    pub fn high_confidence(&self, threshold: f64) -> Vec<&ContextEvent> {
        self.events.iter().filter(|e| e.confidence > threshold).collect()
    }

    /// Get the most recent event
    pub fn most_recent(&self) -> Option<&ContextEvent> {
        self.events.iter().max_by_key(|e| e.timestamp)
    }

    /// Get the oldest event
    pub fn oldest(&self) -> Option<&ContextEvent> {
        self.events.iter().min_by_key(|e| e.timestamp)
    }
}

/// Metadata about a query
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct QueryMetadata {
    /// Number of events retrieved
    pub count: usize,

    /// Query execution time in ms
    pub execution_time_ms: u64,

    /// Whether query hit cache
    pub cached: bool,

    /// Query pattern used
    pub pattern: AccessPattern,
}

/// Context fabric providing temporal memory
#[derive(Clone)]
pub struct ContextFabric {
    /// Event storage by layer
    layers: Arc<RwLock<HashMap<ContextLayer, Vec<ContextEvent>>>>,

    /// Consolidated knowledge
    knowledge: Arc<RwLock<HashMap<String, StructuredContent>>>,

    /// Query cache
    cache: Arc<RwLock<HashMap<String, ContextResult>>>,
}

impl ContextFabric {
    /// Create a new context fabric
    pub fn new() -> Self {
        let mut layers = HashMap::new();
        layers.insert(ContextLayer::Immediate, Vec::new());
        layers.insert(ContextLayer::Working, Vec::new());
        layers.insert(ContextLayer::Episodic, Vec::new());
        layers.insert(ContextLayer::Semantic, Vec::new());

        Self {
            layers: Arc::new(RwLock::new(layers)),
            knowledge: Arc::new(RwLock::new(HashMap::new())),
            cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Store an event in the fabric
    pub async fn store(&self, mut event: ContextEvent, layer: ContextLayer) -> Result<()> {
        event.layer = layer;

        let mut layers = self.layers.write().await;
        if let Some(layer_events) = layers.get_mut(&layer) {
            layer_events.push(event);

            // Sort by timestamp for efficient querying
            layer_events.sort_by_key(|e| e.timestamp);

            // Apply retention policy
            self.apply_retention(layer_events, layer).await;
        }

        // Clear relevant cache entries
        self.clear_cache().await;

        Ok(())
    }

    /// Apply retention policy to a layer
    async fn apply_retention(&self, events: &mut Vec<ContextEvent>, layer: ContextLayer) {
        let now = Timestamp::now();
        let cutoff = now.as_datetime() - layer.retention();

        events.retain(|e| e.timestamp.as_datetime() >= cutoff);
    }

    /// Clear the query cache
    async fn clear_cache(&self) {
        let mut cache = self.cache.write().await;
        cache.clear();
    }

    /// Query the context fabric
    pub async fn query(&self, query: ContextQuery) -> Result<ContextResult> {
        let start_time = std::time::Instant::now();

        // Check cache first
        {
            let cache = self.cache.read().await;
            if let Some(cached) = cache.get(&query.query) {
                return Ok(ContextResult {
                    events: cached.events.clone(),
                    metadata: QueryMetadata {
                        count: cached.events.len(),
                        execution_time_ms: 0,
                        cached: true,
                        pattern: query.pattern,
                    },
                });
            }
        }

        // Execute query
        let mut events = Vec::new();
        let layers = self.layers.read().await;

        if let Some(layer_events) = layers.get(&query.layer) {
            events = layer_events
                .iter()
                .filter(|e| query.window.contains(e.timestamp) && e.confidence >= query.min_confidence)
                .cloned()
                .collect::<Vec<_>>();
        }

        // Apply limit
        if let Some(limit) = query.limit {
            events.truncate(limit);
        }
    let event_count = events.len();
    let execution_time_ms = start_time.elapsed().as_millis() as u64;
    let result = ContextResult::new(
        events,
        QueryMetadata {
            count: event_count,
            execution_time_ms,
            cached: false,
            pattern: query.pattern,
    },
        );
        {
            let mut cache = self.cache.write().await;
            cache.insert(query.query.clone(), result.clone());
        }

        Ok(result)
    }

    /// Recall events within a temporal window
    pub async fn recall(&self, query: impl Into<String>, window: TimeWindow) -> Result<ContextResult> {
        let query = ContextQuery::recall(query, window);
        self.query(query).await
    }

    /// Project future state based on trends
    pub async fn project(&self, query: impl Into<String>, window: TimeWindow) -> Result<ContextResult> {
        let query = ContextQuery::project(query, window);
        self.query(query).await
    }

    /// Compute diff between two states
    pub async fn diff(&self, state1: &str, state2: &str) -> Result<StructuredContent> {
        // In a real implementation, this would compute semantic differences
        // For now, return a placeholder
        Ok(StructuredContent::json(serde_json::json!({
            "operation": "diff",
            "state1": state1,
            "state2": state2,
            "delta": "Not implemented in skeleton"
        })))
    }

    /// Consolidate episodic memories into semantic knowledge
    pub async fn consolidate(&self, events: &[ThoughtEvent]) -> Result<StructuredContent> {
        // In a real implementation, this would distill patterns
        // For now, return a summary
        let summary = serde_json::json!({
            "consolidated_events": events.len(),
            "patterns_detected": events.len() / 5, // Placeholder
            "knowledge_updated": true,
        });

        // Store consolidated knowledge
        let mut knowledge = self.knowledge.write().await;
        knowledge.insert(
            format!("consolidation_{}", Timestamp::now().as_datetime().timestamp()),
            StructuredContent::json(summary.clone()),
        );

        Ok(StructuredContent::json(summary))
    }

    /// Get stored knowledge
    pub async fn knowledge(&self) -> HashMap<String, StructuredContent> {
        let knowledge = self.knowledge.read().await;
        knowledge.clone()
    }

    /// Clear all layers
    pub async fn clear(&self) {
        let mut layers = self.layers.write().await;
        for layer_events in layers.values_mut() {
            layer_events.clear();
        }

        self.clear_cache().await;
    }
}

impl Default for ContextFabric {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::thought_stream::ThoughtEventType;
    use crate::types::ProvenanceChain;

    #[tokio::test]
    async fn test_context_fabric_storage() {
        let fabric = ContextFabric::new();

        let event = ContextEvent {
            content: StructuredContent::text("test"),
            timestamp: Timestamp::now(),
            causal_chain: vec![],
            confidence: 1.0,
            layer: ContextLayer::Working,
        };

        fabric.store(event, ContextLayer::Working).await.unwrap();

        let query = ContextQuery::recall("test", TimeWindow::from_now(chrono::Duration::minutes(5)));
        let result = fabric.query(query).await.unwrap();

        assert_eq!(result.len(), 1);
    }

    #[tokio::test]
    async fn test_recall_query() {
        let fabric = ContextFabric::new();
        let window = TimeWindow::from_now(chrono::Duration::hours(1));

        let result = fabric.recall("test", window).await.unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_time_window() {
        let now = Timestamp::now();
        let past = Timestamp::from_datetime(now.as_datetime() - chrono::Duration::hours(1));
        let window = TimeWindow::new(past, now);

        assert!(window.contains(now));
        assert!(!window.contains(Timestamp::from_datetime(now.as_datetime() + chrono::Duration::hours(1))));
    }

    #[test]
    fn test_context_layers() {
        assert!(ContextLayer::Immediate.retention() < ContextLayer::Episodic.retention());
        assert!(ContextLayer::Semantic.retention() > ContextLayer::Working.retention());
    }
}