Skip to main content

quilt_cell/
lib.rs

1//! # quilt-cell — 8-primitive cell runtime
2//!
3//! A Quilt cell has 8 primitives. The cell IS the system.
4//! The 8 primitives survive every substrate. The 8 primitives survive every language.
5//!
6//! See: https://superinstance.dev
7
8use serde::{Deserialize, Serialize};
9use std::collections::{HashMap, HashSet, VecDeque};
10
11/// Z_in — input space. What the cell receives.
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct Z_in {
14    pub data: HashMap<String, f64>,
15}
16
17impl Z_in {
18    pub fn new() -> Self { Self::default() }
19    pub fn insert(mut self, k: &str, v: f64) -> Self {
20        self.data.insert(k.to_string(), v);
21        self
22    }
23    pub fn get(&self, k: &str) -> Option<f64> {
24        self.data.get(k).copied()
25    }
26}
27
28/// Z_out — output space. What the cell emits.
29#[derive(Debug, Clone, Default, Serialize, Deserialize)]
30pub struct Z_out {
31    pub data: HashMap<String, f64>,
32}
33
34impl Z_out {
35    pub fn new() -> Self { Self::default() }
36    pub fn emit(&mut self, k: &str, v: f64) {
37        self.data.insert(k.to_string(), v);
38    }
39}
40
41/// JEPA — Joint Embedding Predictive Architecture.
42/// Predict the next state, observe the actual. Surprise = ||predicted - actual||^2.
43#[derive(Debug, Clone, Default, Serialize, Deserialize)]
44pub struct Jepa {
45    pub history: Vec<f64>,
46}
47
48impl Jepa {
49    pub fn new() -> Self { Self::default() }
50    pub fn predict(&self, state: &HashMap<String, f64>) -> HashMap<String, f64> {
51        // Default: identity prediction
52        state.clone()
53    }
54    pub fn observe(&mut self, predicted: &HashMap<String, f64>, actual: &HashMap<String, f64>) -> f64 {
55        let mut surprise = 0.0;
56        let keys: HashSet<&String> = predicted.keys().chain(actual.keys()).collect();
57        for k in keys {
58            let p = predicted.get(k).copied().unwrap_or(0.0);
59            let a = actual.get(k).copied().unwrap_or(0.0);
60            surprise += (p - a).powi(2);
61        }
62        surprise = surprise.sqrt();
63        self.history.push(surprise);
64        surprise
65    }
66}
67
68/// DoubleEntry — conservation law: γ (creation/warmth) + η (entropy/κ) = budget.
69#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
70pub struct DoubleEntry {
71    pub gamma: f64,  // creation/warmth
72    pub eta: f64,    // entropy/κ
73}
74
75impl Default for DoubleEntry {
76    fn default() -> Self {
77        Self { gamma: 0.5, eta: 0.5 }
78    }
79}
80
81impl DoubleEntry {
82    pub fn new(gamma: f64, eta: f64) -> Self {
83        let total = gamma + eta;
84        if total > 0.0 {
85            Self { gamma: gamma / total, eta: eta / total }
86        } else {
87            Self::default()
88        }
89    }
90    pub fn budget(&self) -> f64 { self.gamma + self.eta }
91}
92
93/// Vibe — position/velocity/acceleration through the cell's state space.
94#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
95pub struct Vibe {
96    pub position: f64,
97    pub velocity: f64,
98    pub acceleration: f64,
99}
100
101impl Vibe {
102    pub fn tick(&mut self, dt: f64) {
103        self.velocity += self.acceleration * dt;
104        self.position += self.velocity * dt;
105        self.velocity *= 0.99;  // damping
106    }
107    pub fn nudge(&mut self, force: f64) {
108        self.acceleration += force;
109    }
110}
111
112/// GC — 3-phase garbage collection: merge → decay → prune.
113#[derive(Debug, Clone, Default, Serialize, Deserialize)]
114pub struct Gc {
115    pub phase: String,
116    pub merged: u64,
117    pub decayed: u64,
118    pub pruned: u64,
119}
120
121impl Gc {
122    pub fn new() -> Self { Self { phase: "ready".to_string(), ..Default::default() } }
123    pub fn collect(&mut self) -> u64 {
124        // 3-phase GC
125        self.merged += 1;
126        self.decayed += 1;
127        self.pruned += 1;
128        self.phase = "ready".to_string();
129        self.merged + self.decayed + self.pruned
130    }
131}
132
133/// Murmur — gossip protocol for inter-cell communication.
134#[derive(Debug, Clone, Default, Serialize, Deserialize)]
135pub struct Murmur {
136    pub subscriptions: HashSet<String>,
137    pub inbox: VecDeque<String>,
138    pub outbox: VecDeque<String>,
139}
140
141impl Murmur {
142    pub fn new() -> Self { Self::default() }
143    pub fn subscribe(&mut self, topic: &str) {
144        self.subscriptions.insert(topic.to_string());
145    }
146    pub fn gossip(&mut self, msg: String) {
147        self.outbox.push_back(msg);
148    }
149}
150
151/// Graph — the substrate topology.
152/// β₁ = E - V + C (first Betti number: independent cycles)
153#[derive(Debug, Clone, Default, Serialize, Deserialize)]
154pub struct Graph {
155    pub parents: Vec<String>,
156    pub children: Vec<String>,
157    pub edges: Vec<(String, String, f64)>,  // (other, kind, weight)
158}
159
160impl Graph {
161    pub fn new() -> Self { Self::default() }
162    pub fn add_edge(&mut self, other: &str, kind: &str, weight: f64) {
163        self.edges.push((other.to_string(), kind.to_string(), weight));
164    }
165}
166
167/// The Quilt cell. The system. The 8 primitives.
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct Cell {
170    pub cell_id: String,
171    pub kind: String,
172    pub z_in: Z_in,
173    pub z_out: Z_out,
174    pub jepa: Jepa,
175    pub double_entry: DoubleEntry,
176    pub vibe: Vibe,
177    pub gc: Gc,
178    pub murmur: Murmur,
179    pub graph: Graph,
180    pub tick_count: u64,
181}
182
183impl Cell {
184    pub fn new(cell_id: &str) -> Self {
185        Self {
186            cell_id: cell_id.to_string(),
187            kind: "cell".to_string(),
188            z_in: Z_in::new(),
189            z_out: Z_out::new(),
190            jepa: Jepa::new(),
191            double_entry: DoubleEntry::default(),
192            vibe: Vibe::default(),
193            gc: Gc::new(),
194            murmur: Murmur::new(),
195            graph: Graph::new(),
196            tick_count: 0,
197        }
198    }
199
200    pub fn with_z_in(mut self, z_in: Z_in) -> Self { self.z_in = z_in; self }
201    pub fn with_kind(mut self, kind: &str) -> Self { self.kind = kind.to_string(); self }
202
203    /// Tick: advance the cell by one step. Returns JEPA surprise.
204    pub fn tick(&mut self) -> f64 {
205        self.vibe.tick(1.0);
206        let predicted = self.jepa.predict(&self.z_in.data);
207        let actual = self.z_in.data.clone();
208        let surprise = self.jepa.observe(&predicted, &actual);
209        self.z_out.emit("surprise", surprise);
210        self.z_out.emit("vibe_position", self.vibe.position);
211        self.murmur.gossip(format!("tick:{}:{}", self.cell_id, surprise));
212        self.tick_count += 1;
213        surprise
214    }
215
216    pub fn connect(&mut self, other_id: &str, kind: &str, weight: f64) {
217        self.graph.add_edge(other_id, kind, weight);
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn test_cell_basic() {
227        let mut cell = Cell::new("test");
228        let s = cell.tick();
229        assert_eq!(cell.tick_count, 1);
230        assert!(s.is_finite());
231    }
232
233    #[test]
234    fn test_double_entry_conservation() {
235        let de = DoubleEntry::new(0.4, 0.6);
236        assert!((de.budget() - 1.0).abs() < 1e-9);
237    }
238
239    #[test]
240    fn test_vibe_motion() {
241        let mut v = Vibe::default();
242        v.nudge(1.0);
243        v.tick(1.0);
244        assert!(v.position != 0.0);
245    }
246}
247
248// Internal: re-export with crate name