terminals-core 0.1.0

Core runtime primitives for Terminals OS: phase dynamics, AXON wire protocol, substrate engine, and sematonic types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! SubstrateEngine — Monomorphized API for WASM consumption.
//!
//! This module pins all generic substrate operations to concrete types
//! so the wasm-bindgen boundary only sees f32/u32/String. The engine
//! owns its atom buffer and exposes a tick-witness-extract loop:
//!
//!   JS: create → set embeddings → tick(audio) → read witness → extract sematon
//!
//! No wasm-bindgen dependency here — that lives in terminals-wasm.

use super::atom::ComputeAtom;
use super::coupling::{coupled_step, AudioMetrics};
use super::expert::ExpertProjection;
use super::fold::fold_to_json;
use super::graph::{GraphProjection, PadicAddr};
use super::kuramoto::KuramotoProjection;
use super::layout::ProjectionLayout;
use super::sematon::Sematon;
use super::splat::SplatProjection;
use super::witness::{compute_witness, ConvergenceWitness};
use crate::primitives::vector;

/// The substrate engine: N atoms, a layout, and physics parameters.
/// Single-owner — WASM is single-threaded so this is safe as a JS-side object.
pub struct SubstrateEngine {
    atoms: Vec<ComputeAtom>,
    layout: ProjectionLayout,
    step: u32,
    witness: ConvergenceWitness,
    k_base: f32,
    gravity_scale: f32,
}

impl SubstrateEngine {
    /// Create a new substrate with `n` atoms.
    /// `full_layout`: true = all 4 projections (1592 bytes/atom),
    ///                false = minimal Splat+Kuramoto (1548 bytes/atom).
    pub fn new(n: usize, full_layout: bool, k_base: f32, gravity_scale: f32) -> Self {
        let layout = if full_layout {
            ProjectionLayout::full()
        } else {
            ProjectionLayout::minimal()
        };
        let atoms = ComputeAtom::create_n(&layout, n);
        Self {
            atoms,
            layout,
            step: 0,
            witness: ConvergenceWitness::default(),
            k_base,
            gravity_scale,
        }
    }

    /// Run one physics step. Returns [R, entropy, converged (0.0/1.0), step].
    pub fn tick(&mut self, bass: f32, mid: f32, high: f32, entropy: f32, dt: f32) -> [f32; 4] {
        let audio = AudioMetrics {
            bass,
            mid,
            high,
            entropy,
        };

        coupled_step(
            &mut self.atoms,
            &audio,
            self.k_base,
            self.gravity_scale,
            dt,
        );

        self.step += 1;
        self.witness = compute_witness(&self.atoms, self.step);

        [
            self.witness.r,
            self.witness.entropy,
            if self.witness.converged { 1.0 } else { 0.0 },
            self.step as f32,
        ]
    }

    /// Read all Kuramoto phases as a flat f32 array.
    pub fn phases(&self) -> Vec<f32> {
        self.atoms
            .iter()
            .map(|a| {
                a.read_projection::<KuramotoProjection>()
                    .map(|k| k.theta)
                    .unwrap_or(0.0)
            })
            .collect()
    }

    /// Current witness as [R, entropy, converged, step].
    pub fn witness_array(&self) -> [f32; 4] {
        [
            self.witness.r,
            self.witness.entropy,
            if self.witness.converged { 1.0 } else { 0.0 },
            self.step as f32,
        ]
    }

    /// Set the 384-dim embedding for atom at `index`.
    /// Returns false if index out of bounds or embedding wrong length.
    pub fn set_embedding(&mut self, index: usize, embedding: &[f32]) -> bool {
        if index >= self.atoms.len() || embedding.len() != 384 {
            return false;
        }
        let mut splat = self.atoms[index]
            .read_projection::<SplatProjection>()
            .unwrap_or_default();
        splat.embedding.copy_from_slice(embedding);
        self.atoms[index].write_projection(&splat)
    }

    /// Set Kuramoto phase and natural frequency for atom at `index`.
    pub fn set_phase(&mut self, index: usize, theta: f32, omega: f32) -> bool {
        if index >= self.atoms.len() {
            return false;
        }
        let mut kp = self.atoms[index]
            .read_projection::<KuramotoProjection>()
            .unwrap_or_default();
        kp.theta = theta;
        kp.omega = omega;
        self.atoms[index].write_projection(&kp)
    }

    /// Set expert projection (intent routing) for atom at `index`.
    pub fn set_expert(&mut self, index: usize, intent: f32, activation: f32, gate: f32) -> bool {
        if index >= self.atoms.len() {
            return false;
        }
        if !self.layout.has(super::projection::ProjectionId::Expert) {
            return false;
        }
        let ep = ExpertProjection {
            intent,
            activation,
            gate,
        };
        self.atoms[index].write_projection(&ep)
    }

    /// Set graph neighbor at a slot for atom at `index`.
    pub fn set_neighbor(&mut self, index: usize, slot: usize, neighbor_index: u16) -> bool {
        if index >= self.atoms.len() || slot >= super::graph::MAX_NEIGHBORS {
            return false;
        }
        if !self.layout.has(super::projection::ProjectionId::Graph) {
            return false;
        }
        let mut gp = self.atoms[index]
            .read_projection::<GraphProjection>()
            .unwrap_or_default();
        gp.neighbors[slot] = neighbor_index;
        self.atoms[index].write_projection(&gp)
    }

    /// Number of atoms.
    pub fn atom_count(&self) -> usize {
        self.atoms.len()
    }

    /// Current step number.
    pub fn step_count(&self) -> u32 {
        self.step
    }

    /// Stride in bytes per atom.
    pub fn stride(&self) -> usize {
        self.layout.stride
    }

    /// Whether the substrate has converged (R >= 0.9).
    pub fn converged(&self) -> bool {
        self.witness.converged
    }

    /// Current order parameter R.
    pub fn order_parameter(&self) -> f32 {
        self.witness.r
    }

    /// All embeddings as a flat f32 array (n * 384 elements).
    pub fn embeddings_flat(&self) -> Vec<f32> {
        let mut out = Vec::with_capacity(self.atoms.len() * 384);
        for atom in &self.atoms {
            if let Some(splat) = atom.read_projection::<SplatProjection>() {
                out.extend_from_slice(&splat.embedding);
            } else {
                out.extend(std::iter::repeat(0.0f32).take(384));
            }
        }
        out
    }

    /// Compute the centroid embedding across all atoms.
    fn centroid_embedding(&self) -> Vec<f32> {
        let mut centroid = vec![0.0f32; 384];
        let mut count = 0usize;

        for atom in &self.atoms {
            if let Some(splat) = atom.read_projection::<SplatProjection>() {
                for (i, &v) in splat.embedding.iter().enumerate() {
                    centroid[i] += v;
                }
                count += 1;
            }
        }

        if count == 0 {
            return centroid;
        }

        let n = count as f32;
        for v in &mut centroid {
            *v /= n;
        }

        vector::normalize(&mut centroid);
        centroid
    }

    /// Extract a sematon from the current substrate state.
    /// Payload = centroid embedding. Returns JSON string of FoldedSematon.
    pub fn extract_sematon(&self, source: &str) -> String {
        let centroid = self.centroid_embedding();
        let address = PadicAddr {
            base: self.step,
            coeff0: self.atoms.len() as u16,
            coeff1: 0,
        };
        let sematon = Sematon::new(centroid, self.witness, address, source);
        fold_to_json(&sematon)
    }

    /// Read the shape hash for atom at `index`.
    pub fn atom_shape_hash(&self, index: usize) -> Option<u32> {
        self.atoms.get(index).map(|a| a.shape_hash)
    }

    /// Update coupling parameters (k_base, gravity_scale).
    pub fn set_coupling_params(&mut self, k_base: f32, gravity_scale: f32) {
        self.k_base = k_base;
        self.gravity_scale = gravity_scale;
    }
}

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

    #[test]
    fn test_engine_create_full() {
        let engine = SubstrateEngine::new(10, true, 1.0, 1.0);
        assert_eq!(engine.atom_count(), 10);
        assert_eq!(engine.stride(), 1612);
        assert_eq!(engine.step_count(), 0);
        assert!(!engine.converged());
    }

    #[test]
    fn test_engine_create_minimal() {
        let engine = SubstrateEngine::new(5, false, 1.0, 1.0);
        assert_eq!(engine.atom_count(), 5);
        assert_eq!(engine.stride(), 1548);
    }

    #[test]
    fn test_engine_set_and_read_embedding() {
        let mut engine = SubstrateEngine::new(3, true, 1.0, 1.0);
        let mut emb = vec![0.0f32; 384];
        emb[0] = 1.0;

        assert!(engine.set_embedding(0, &emb));
        assert!(engine.set_embedding(1, &emb));
        assert!(!engine.set_embedding(10, &emb)); // out of bounds
        assert!(!engine.set_embedding(0, &[1.0; 10])); // wrong length

        let flat = engine.embeddings_flat();
        assert_eq!(flat.len(), 3 * 384);
        assert!((flat[0] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_engine_set_phase() {
        let mut engine = SubstrateEngine::new(3, false, 1.0, 1.0);
        assert!(engine.set_phase(0, 1.5, 0.1));
        assert!(engine.set_phase(2, 3.0, 0.2));
        assert!(!engine.set_phase(5, 0.0, 0.0)); // out of bounds

        let phases = engine.phases();
        assert_eq!(phases.len(), 3);
        assert!((phases[0] - 1.5).abs() < 1e-6);
        assert!((phases[2] - 3.0).abs() < 1e-6);
    }

    #[test]
    fn test_engine_set_expert() {
        let mut engine = SubstrateEngine::new(2, true, 1.0, 1.0);
        assert!(engine.set_expert(0, 0.5, 0.8, 1.0));

        // Minimal layout doesn't have Expert
        let mut engine_min = SubstrateEngine::new(2, false, 1.0, 1.0);
        assert!(!engine_min.set_expert(0, 0.5, 0.8, 1.0));
    }

    #[test]
    fn test_engine_tick_returns_witness() {
        let mut engine = SubstrateEngine::new(6, false, 5.0, 1.0);

        // Set same embedding direction for all atoms (high coupling)
        let mut emb = vec![0.0f32; 384];
        emb[0] = 1.0;
        for i in 0..6 {
            engine.set_embedding(i, &emb);
            engine.set_phase(i, i as f32, 0.0);
        }

        // Tick once
        let w = engine.tick(0.5, 0.3, 0.2, 0.5, 0.01);
        assert_eq!(w.len(), 4);
        assert!(w[0] >= 0.0 && w[0] <= 1.0); // R in [0,1]
        assert_eq!(w[3], 1.0); // step = 1
        assert_eq!(engine.step_count(), 1);
    }

    #[test]
    fn test_engine_convergence_after_many_ticks() {
        let mut engine = SubstrateEngine::new(6, false, 5.0, 1.0);

        // Same embedding (high gravity coupling)
        let mut emb = vec![0.0f32; 384];
        emb[0] = 1.0;
        for i in 0..6 {
            engine.set_embedding(i, &emb);
            engine.set_phase(i, i as f32, 0.0);
        }

        // Run many ticks
        for _ in 0..1000 {
            engine.tick(0.5, 0.3, 0.2, 0.5, 0.01);
        }

        assert!(
            engine.order_parameter() > 0.9,
            "R = {} (expected > 0.9)",
            engine.order_parameter()
        );
        assert!(engine.converged());
    }

    #[test]
    fn test_engine_extract_sematon() {
        let mut engine = SubstrateEngine::new(4, false, 5.0, 1.0);

        let mut emb = vec![0.0f32; 384];
        emb[0] = 1.0;
        for i in 0..4 {
            engine.set_embedding(i, &emb);
        }

        // Tick to get a witness
        engine.tick(0.5, 0.3, 0.2, 0.5, 0.01);

        let json = engine.extract_sematon("test-surface");
        assert!(!json.is_empty());
        assert!(json.contains("test-surface"));
        assert!(json.contains("witness_r"));
    }

    #[test]
    fn test_engine_witness_array_matches_tick() {
        let mut engine = SubstrateEngine::new(3, false, 1.0, 1.0);
        let tick_w = engine.tick(0.0, 0.0, 0.0, 0.0, 0.01);
        let read_w = engine.witness_array();

        assert_eq!(tick_w[0], read_w[0]); // R
        assert_eq!(tick_w[1], read_w[1]); // entropy
        assert_eq!(tick_w[2], read_w[2]); // converged
        assert_eq!(tick_w[3], read_w[3]); // step
    }

    #[test]
    fn test_engine_set_coupling_params() {
        let mut engine = SubstrateEngine::new(2, false, 1.0, 1.0);
        engine.set_coupling_params(10.0, 2.0);
        // Just verify no panic — the effect shows in tick behavior
        engine.tick(0.5, 0.0, 0.0, 0.0, 0.01);
    }

    #[test]
    fn test_engine_empty() {
        let mut engine = SubstrateEngine::new(0, true, 1.0, 1.0);
        assert_eq!(engine.atom_count(), 0);
        let w = engine.tick(0.0, 0.0, 0.0, 0.0, 0.01);
        assert_eq!(w[0], 0.0); // R = 0 for empty
        assert!(engine.phases().is_empty());
    }

    #[test]
    fn test_engine_atom_shape_hash() {
        let mut engine = SubstrateEngine::new(2, false, 1.0, 1.0);
        let h1 = engine.atom_shape_hash(0).unwrap();

        engine.set_phase(0, 3.14, 1.0);
        let h2 = engine.atom_shape_hash(0).unwrap();

        assert_ne!(h1, h2); // Hash changed after write
        assert!(engine.atom_shape_hash(99).is_none()); // Out of bounds
    }
}