cerebro 1.1.7

A blazing-fast AI memory layer that enables teams of specialized agents to collaborate through a shared cognitive architecture.
Documentation
//! # Multi-Dimensional Spatial Grid
//!
//! Experimental memory abstraction that maps semantic chunks into a 3D
//! coordinate system. Allows agents to navigate memories via spatial distance
//! rather than purely semantic cosine similarity.

use crate::models::Node;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Represents a 3D coordinate in the semantic spatial grid.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Coordinate {
    pub x: f32, // e.g., Complexity
    pub y: f32, // e.g., Subject Domain
    pub z: f32, // e.g., Temporal relevance
}

impl Coordinate {
    pub fn distance(&self, other: &Coordinate) -> f32 {
        ((self.x - other.x).powi(2) + (self.y - other.y).powi(2) + (self.z - other.z).powi(2))
            .sqrt()
    }
}

/// A spatial index for memories.
#[derive(Clone, Default)]
pub struct SpatialMemoryStore {
    grid: Arc<RwLock<HashMap<String, (Node, Coordinate)>>>,
}

impl SpatialMemoryStore {
    pub fn new() -> Self {
        Self {
            grid: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Insert a node at a specific coordinate.
    pub fn insert(&self, node: Node, coord: Coordinate) {
        if let Ok(mut grid) = self.grid.write() {
            grid.insert(node.id.clone(), (node, coord));
        }
    }

    /// Find the nearest K memories to a given coordinate using Euclidean distance.
    pub fn search_nearest(&self, center: Coordinate, k: usize) -> Vec<(Node, f32)> {
        let grid = match self.grid.read() {
            Ok(g) => g,
            Err(_) => return vec![],
        };

        let mut distances: Vec<(Node, f32)> = grid
            .values()
            .map(|(node, coord)| (node.clone(), center.distance(coord)))
            .collect();

        // Sort ascending by distance (closer is better)
        distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
        distances.truncate(k);
        distances
    }
}