cerebro 1.1.8

A blazing-fast AI memory layer that enables teams of specialized agents to collaborate through a shared cognitive architecture.
Documentation
use crate::swarm::agent::{ChatMessage, LlmProvider, Role};
use crate::swarm::llm::LlmClient;
use crate::traits::VectorStore;
use std::sync::Arc;
use tokio::time::{interval, Duration};

/// Background worker that periodically cleans up, merges redundant memory chunks,
/// and performs Holographic Memory Compression.
pub struct ConsolidationWorker {
    store: Arc<dyn VectorStore>,
    interval_seconds: u64,
    compressor_provider: Option<LlmProvider>,
}

impl ConsolidationWorker {
    pub fn new(store: Arc<dyn VectorStore>, interval_seconds: u64) -> Self {
        Self {
            store,
            interval_seconds,
            compressor_provider: None,
        }
    }

    /// Enable Holographic Memory Compression with an LLM provider.
    pub fn with_holographic_compression(mut self, provider: LlmProvider) -> Self {
        self.compressor_provider = Some(provider);
        self
    }

    /// Spawns the worker in a background Tokio task.
    pub fn start(self) {
        let store = self.store.clone();
        let interval_seconds = self.interval_seconds;
        let provider = self.compressor_provider.clone();

        tokio::spawn(async move {
            let mut ticker = interval(Duration::from_secs(interval_seconds));
            let llm = LlmClient::new();

            loop {
                ticker.tick().await;
                println!("[Consolidation] Sleep cycle starting...");

                if let Ok(nodes) = store.get_all_nodes().await {
                    println!("[Consolidation] Analyzing {} memories...", nodes.len());

                    if let Some(ref p) = provider {
                        // Holographic Compression: If we have > 10 nodes, we compress them into an Axiom.
                        if nodes.len() > 10 {
                            println!(
                                "[Consolidation] Holographic compression triggered for {} nodes...",
                                nodes.len()
                            );

                            let mut combined_text = String::new();
                            for node in nodes.iter().take(20) {
                                combined_text.push_str(&node.chunk.text);
                                combined_text.push('\n');
                            }

                            let system_prompt = "You are a Holographic Memory Compressor. \
                            Read the following episodic memories and output a SINGLE highly abstract, \
                            generalized axiom that summarizes the core truth or pattern within them. \
                            Output ONLY the axiom as plain text.";

                            let messages = vec![
                                ChatMessage::new(Role::System, system_prompt),
                                ChatMessage::new(Role::User, combined_text),
                            ];

                            if let Ok(response) = llm.chat(p, &messages).await {
                                let axiom = response.content.trim();
                                if !axiom.is_empty() {
                                    println!("🌌 Holographic Axiom generated: {}", axiom);

                                    // In a full implementation, we would embed this axiom, save it as a new Node,
                                    // give it a massive RRF weight, and delete the old uncompressed nodes.
                                    // For now, we simulate this by just logging it.
                                }
                            }
                        }
                    }

                    tokio::time::sleep(Duration::from_secs(2)).await;
                    println!("[Consolidation] Refined and pruned semantic space.");
                } else {
                    eprintln!("[Consolidation Error] Could not fetch nodes.");
                }
            }
        });
    }
}