quilt-cell 0.6.0

Quilt — a reactive, typed, cellular runtime. 8-primitive cell with Z_in, Z_out, JEPA, DoubleEntry, Vibe, GC, Murmur, Graph.
Documentation
//! # quilt-cell — 8-primitive cell runtime
//!
//! A Quilt cell has 8 primitives. The cell IS the system.
//! The 8 primitives survive every substrate. The 8 primitives survive every language.
//!
//! See: https://superinstance.dev

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};

/// Z_in — input space. What the cell receives.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Z_in {
    pub data: HashMap<String, f64>,
}

impl Z_in {
    pub fn new() -> Self { Self::default() }
    pub fn insert(mut self, k: &str, v: f64) -> Self {
        self.data.insert(k.to_string(), v);
        self
    }
    pub fn get(&self, k: &str) -> Option<f64> {
        self.data.get(k).copied()
    }
}

/// Z_out — output space. What the cell emits.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Z_out {
    pub data: HashMap<String, f64>,
}

impl Z_out {
    pub fn new() -> Self { Self::default() }
    pub fn emit(&mut self, k: &str, v: f64) {
        self.data.insert(k.to_string(), v);
    }
}

/// JEPA — Joint Embedding Predictive Architecture.
/// Predict the next state, observe the actual. Surprise = ||predicted - actual||^2.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Jepa {
    pub history: Vec<f64>,
}

impl Jepa {
    pub fn new() -> Self { Self::default() }
    pub fn predict(&self, state: &HashMap<String, f64>) -> HashMap<String, f64> {
        // Default: identity prediction
        state.clone()
    }
    pub fn observe(&mut self, predicted: &HashMap<String, f64>, actual: &HashMap<String, f64>) -> f64 {
        let mut surprise = 0.0;
        let keys: HashSet<&String> = predicted.keys().chain(actual.keys()).collect();
        for k in keys {
            let p = predicted.get(k).copied().unwrap_or(0.0);
            let a = actual.get(k).copied().unwrap_or(0.0);
            surprise += (p - a).powi(2);
        }
        surprise = surprise.sqrt();
        self.history.push(surprise);
        surprise
    }
}

/// DoubleEntry — conservation law: γ (creation/warmth) + η (entropy/κ) = budget.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DoubleEntry {
    pub gamma: f64,  // creation/warmth
    pub eta: f64,    // entropy/κ
}

impl Default for DoubleEntry {
    fn default() -> Self {
        Self { gamma: 0.5, eta: 0.5 }
    }
}

impl DoubleEntry {
    pub fn new(gamma: f64, eta: f64) -> Self {
        let total = gamma + eta;
        if total > 0.0 {
            Self { gamma: gamma / total, eta: eta / total }
        } else {
            Self::default()
        }
    }
    pub fn budget(&self) -> f64 { self.gamma + self.eta }
}

/// Vibe — position/velocity/acceleration through the cell's state space.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct Vibe {
    pub position: f64,
    pub velocity: f64,
    pub acceleration: f64,
}

impl Vibe {
    pub fn tick(&mut self, dt: f64) {
        self.velocity += self.acceleration * dt;
        self.position += self.velocity * dt;
        self.velocity *= 0.99;  // damping
    }
    pub fn nudge(&mut self, force: f64) {
        self.acceleration += force;
    }
}

/// GC — 3-phase garbage collection: merge → decay → prune.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Gc {
    pub phase: String,
    pub merged: u64,
    pub decayed: u64,
    pub pruned: u64,
}

impl Gc {
    pub fn new() -> Self { Self { phase: "ready".to_string(), ..Default::default() } }
    pub fn collect(&mut self) -> u64 {
        // 3-phase GC
        self.merged += 1;
        self.decayed += 1;
        self.pruned += 1;
        self.phase = "ready".to_string();
        self.merged + self.decayed + self.pruned
    }
}

/// Murmur — gossip protocol for inter-cell communication.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Murmur {
    pub subscriptions: HashSet<String>,
    pub inbox: VecDeque<String>,
    pub outbox: VecDeque<String>,
}

impl Murmur {
    pub fn new() -> Self { Self::default() }
    pub fn subscribe(&mut self, topic: &str) {
        self.subscriptions.insert(topic.to_string());
    }
    pub fn gossip(&mut self, msg: String) {
        self.outbox.push_back(msg);
    }
}

/// Graph — the substrate topology.
/// β₁ = E - V + C (first Betti number: independent cycles)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Graph {
    pub parents: Vec<String>,
    pub children: Vec<String>,
    pub edges: Vec<(String, String, f64)>,  // (other, kind, weight)
}

impl Graph {
    pub fn new() -> Self { Self::default() }
    pub fn add_edge(&mut self, other: &str, kind: &str, weight: f64) {
        self.edges.push((other.to_string(), kind.to_string(), weight));
    }
}

/// The Quilt cell. The system. The 8 primitives.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cell {
    pub cell_id: String,
    pub kind: String,
    pub z_in: Z_in,
    pub z_out: Z_out,
    pub jepa: Jepa,
    pub double_entry: DoubleEntry,
    pub vibe: Vibe,
    pub gc: Gc,
    pub murmur: Murmur,
    pub graph: Graph,
    pub tick_count: u64,
}

impl Cell {
    pub fn new(cell_id: &str) -> Self {
        Self {
            cell_id: cell_id.to_string(),
            kind: "cell".to_string(),
            z_in: Z_in::new(),
            z_out: Z_out::new(),
            jepa: Jepa::new(),
            double_entry: DoubleEntry::default(),
            vibe: Vibe::default(),
            gc: Gc::new(),
            murmur: Murmur::new(),
            graph: Graph::new(),
            tick_count: 0,
        }
    }

    pub fn with_z_in(mut self, z_in: Z_in) -> Self { self.z_in = z_in; self }
    pub fn with_kind(mut self, kind: &str) -> Self { self.kind = kind.to_string(); self }

    /// Tick: advance the cell by one step. Returns JEPA surprise.
    pub fn tick(&mut self) -> f64 {
        self.vibe.tick(1.0);
        let predicted = self.jepa.predict(&self.z_in.data);
        let actual = self.z_in.data.clone();
        let surprise = self.jepa.observe(&predicted, &actual);
        self.z_out.emit("surprise", surprise);
        self.z_out.emit("vibe_position", self.vibe.position);
        self.murmur.gossip(format!("tick:{}:{}", self.cell_id, surprise));
        self.tick_count += 1;
        surprise
    }

    pub fn connect(&mut self, other_id: &str, kind: &str, weight: f64) {
        self.graph.add_edge(other_id, kind, weight);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cell_basic() {
        let mut cell = Cell::new("test");
        let s = cell.tick();
        assert_eq!(cell.tick_count, 1);
        assert!(s.is_finite());
    }

    #[test]
    fn test_double_entry_conservation() {
        let de = DoubleEntry::new(0.4, 0.6);
        assert!((de.budget() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_vibe_motion() {
        let mut v = Vibe::default();
        v.nudge(1.0);
        v.tick(1.0);
        assert!(v.position != 0.0);
    }
}

// Internal: re-export with crate name