xynthe 0.1.0

A unified orchestration framework for autonomous intelligence with temporal continuity
Documentation
//! Context Fabric and Memory System example - demonstrates multi-layered memory
//!
//! Run with: cargo run --example memory_system

use xynthe::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    println!("=== Xynthe Memory System Example ===\n");

    // 1. Initialize context fabric with multiple layers
    println!("1. Creating context fabric with temporal layers...");
    let context_fabric = Arc::new(ContextFabric::new());
    println!("   ✓ Context fabric initialized with 4 layers:");
    println!("     - Immediate (30s retention)");
    println!("     - Working (24h retention)");
    println!("     - Episodic (365d retention)");
    println!("     - Semantic (persistent)\n");

    // 2. Store events in different memory layers
    println!("2. Storing events across different memory layers...");

    let now = Timestamp::now();

    // Store in Immediate layer (high-frequency sensor data)
    let immediate_event = ContextEvent {
        content: StructuredContent::text("Recent user interaction"),
        timestamp: now,
        causal_chain: vec![],
        confidence: 0.95,
        layer: ContextLayer::Immediate,
    };
    context_fabric.store(immediate_event.clone(), ContextLayer::Immediate).await?;
    println!("   ✓ Stored event in Immediate layer");

    // Store in Working layer (current task context)
    let working_event = ContextEvent {
        content: StructuredContent::json(serde_json::json!({
            "task": "Process weather request",
            "status": "in_progress"
        })),
        timestamp: now,
        causal_chain: vec![],
        confidence: 0.9,
        layer: ContextLayer::Working,
    };
    context_fabric.store(working_event.clone(), ContextLayer::Working).await?;
    println!("   ✓ Stored event in Working layer");

    // Store in Episodic layer (historical interactions)
    let episodic_event = ContextEvent {
        content: StructuredContent::text("User frequently checks weather in SF"),
        timestamp: Timestamp::from_datetime(now.as_datetime() - chrono::Duration::days(7)),
        causal_chain: vec![],
        confidence: 0.85,
        layer: ContextLayer::Episodic,
    };
    context_fabric.store(episodic_event.clone(), ContextLayer::Episodic).await?;
    println!("   ✓ Stored event in Episodic layer\n");

    // 3. Query recent events (recall pattern)
    println!("3. Querying recent events (recall pattern)...");
    let recall_window = TimeWindow::from_now(chrono::Duration::hours(1));
    let recall_query = ContextQuery::recall("weather OR user", recall_window)
        .with_limit(5)
        .with_min_confidence(0.8);

    let recall_results = context_fabric.query(recall_query).await?;
    println!("   Retrieved: {} events in {} ms",
        recall_results.events.len(),
        recall_results.metadata.execution_time_ms
    );
    println!("   Cache hit: {}\n", recall_results.metadata.cached);

    // 4. Query for trends (projection pattern)
    println!("4. Querying for future trends (projection pattern)...");
    let project_window = TimeWindow::from_now(chrono::Duration::weeks(1));
    let project_query = ContextQuery::project("weather requests", project_window);

    let project_results = context_fabric.query(project_query).await?;
    println!("   Projection window: Next 7 days");
    println!("   Historical basis: {} events\n", project_results.events.len());

    // 5. Demonstrate semantic consolidation
    println!("5. Consolidating episodic memories to semantic knowledge...");

    // Create some thought events for consolidation
    let thought_stream = ThoughtStream::new("consolidation_test");
    let thoughts = vec![
        ThoughtEvent::observation(
            StructuredContent::text("User checks weather every morning"),
            ProvenanceChain::new(),
        ),
        ThoughtEvent::reflection(
            StructuredContent::text("Pattern: 8am-9am timezone"),
            ProvenanceChain::new(),
        ),
    ];

    for thought in thoughts {
        thought_stream.emit(thought)?;
    }

    let consolidated = context_fabric.consolidate(&thoughts).await?;
    println!("   Consolidated knowledge: {:?}\n", consolidated.as_json());

    // 6. Get stored knowledge
    println!("6. Retrieving consolidated knowledge...");
    let knowledge = context_fabric.knowledge().await;
    println!("   Knowledge entries: {}\n", knowledge.len());

    // 7. Demonstrate memory layer properties
    println!("7. Memory layer properties:");
    println!("   Immediate: {} seconds", ContextLayer::Immediate.retention().num_seconds());
    println!("   Working: {} hours", ContextLayer::Working.retention().num_hours());
    println!("   Episodic: {} days", ContextLayer::Episodic.retention().num_days());
    println!("   Semantic: Persistent\n");

    println!("=== Memory System Example Completed ===\n");
    println("Memory patterns demonstrated:");
    println!("  ✓ Temporal storage across 4 layers");
    println!("  ✓ Recall queries with time windows");
    println!("  ✓ Project queries for trend analysis");
    println!("  ✓ Semantic consolidation of episodic memory");
    println!("  ✓ Retention policies per layer");

    Ok(())
}