prime-radiant 0.1.0

Universal coherence engine using sheaf Laplacian mathematics for AI safety, hallucination detection, and structural consistency verification in LLMs and distributed systems
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
416
417
418
419
//! Coherence fabric managing all 256 tiles.

use super::adapter::{TileAdapter, TileAdapterConfig};
use super::coordinator::{AggregatedWitness, CoherenceSummary, CoordinatorConfig, TileCoordinator};
use super::error::{TilesError, TilesResult};
use cognitum_gate_kernel::report::TileReport;
use serde::{Deserialize, Serialize};
use std::time::Instant;

/// Number of tiles in the fabric.
pub const NUM_TILES: usize = 256;

/// Configuration for the coherence fabric.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FabricConfig {
    /// Tile adapter configuration.
    pub tile_config: TileAdapterConfig,
    /// Coordinator configuration.
    pub coordinator_config: CoordinatorConfig,
    /// Enable parallel tick processing.
    pub parallel_ticks: bool,
    /// Auto-aggregate witnesses after each tick.
    pub auto_aggregate: bool,
    /// Target tick rate (ticks per second, 0 = unlimited).
    pub target_tick_rate: u32,
}

impl Default for FabricConfig {
    fn default() -> Self {
        Self {
            tile_config: TileAdapterConfig::default(),
            coordinator_config: CoordinatorConfig::default(),
            parallel_ticks: true,
            auto_aggregate: true,
            target_tick_rate: 10000, // 10K ticks/sec target
        }
    }
}

/// State of the coherence fabric.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FabricState {
    /// Fabric is uninitialized.
    Uninitialized,
    /// Fabric is initialized and ready.
    Ready,
    /// Fabric is running (processing ticks).
    Running,
    /// Fabric is paused.
    Paused,
    /// Fabric is in error state.
    Error,
}

/// Report from a fabric tick.
#[derive(Debug, Clone)]
pub struct FabricReport {
    /// Tick number.
    pub tick: u32,
    /// Global energy (sum of tile energies).
    pub global_energy: f64,
    /// Aggregated witness from all tiles.
    pub global_witness: AggregatedWitness,
    /// Per-tile reports.
    pub tile_reports: Vec<TileReport>,
    /// Processing time in microseconds.
    pub processing_time_us: u64,
    /// Number of tiles that processed deltas.
    pub active_tiles: u16,
    /// Total deltas processed this tick.
    pub total_deltas: u32,
}

/// Coherence fabric using 256 WASM-style tiles.
///
/// This is the main entry point for distributed coherence computation.
/// It manages all 256 tiles, distributes updates, and aggregates results.
pub struct CoherenceFabric {
    /// All tiles.
    tiles: Vec<TileAdapter>,
    /// Coordinator for tile communication.
    coordinator: TileCoordinator,
    /// Configuration.
    config: FabricConfig,
    /// Current state.
    state: FabricState,
    /// Current tick number.
    current_tick: u32,
    /// Total ticks processed.
    total_ticks: u64,
}

impl CoherenceFabric {
    /// Create a new coherence fabric with the given configuration.
    pub fn new(config: FabricConfig) -> TilesResult<Self> {
        let mut tiles = Vec::with_capacity(NUM_TILES);

        for i in 0..NUM_TILES {
            let adapter = TileAdapter::new(i as u8, config.tile_config.clone())?;
            tiles.push(adapter);
        }

        let coordinator = TileCoordinator::new(config.coordinator_config.clone());

        Ok(Self {
            tiles,
            coordinator,
            config,
            state: FabricState::Ready,
            current_tick: 0,
            total_ticks: 0,
        })
    }

    /// Create with default configuration.
    pub fn default_fabric() -> TilesResult<Self> {
        Self::new(FabricConfig::default())
    }

    /// Get the current fabric state.
    #[inline]
    pub fn state(&self) -> FabricState {
        self.state
    }

    /// Get the current tick number.
    #[inline]
    pub fn current_tick(&self) -> u32 {
        self.current_tick
    }

    /// Get total ticks processed.
    #[inline]
    pub fn total_ticks(&self) -> u64 {
        self.total_ticks
    }

    /// Get the coordinator.
    pub fn coordinator(&self) -> &TileCoordinator {
        &self.coordinator
    }

    /// Get a tile by ID.
    pub fn tile(&self, tile_id: u8) -> Option<&TileAdapter> {
        self.tiles.get(tile_id as usize)
    }

    /// Get a mutable tile by ID.
    pub fn tile_mut(&mut self, tile_id: u8) -> Option<&mut TileAdapter> {
        self.tiles.get_mut(tile_id as usize)
    }

    /// Distribute a node state update to the appropriate tile.
    pub fn distribute_state_update(&mut self, node_id: u64, energy: f32) -> TilesResult<()> {
        let tile_id = self.coordinator.tile_for_node(node_id);
        let tile = self
            .tiles
            .get_mut(tile_id as usize)
            .ok_or(TilesError::TileIdOutOfRange(tile_id as u16))?;
        tile.ingest_state_update(node_id, energy)
    }

    /// Distribute an edge addition.
    pub fn distribute_edge_add(
        &mut self,
        source_node: u64,
        target_node: u64,
        weight: u16,
    ) -> TilesResult<()> {
        // Edges go to the tile of the source node
        let tile_id = self.coordinator.tile_for_node(source_node);
        let tile = self
            .tiles
            .get_mut(tile_id as usize)
            .ok_or(TilesError::TileIdOutOfRange(tile_id as u16))?;

        // Convert node IDs to local vertex IDs (truncate for now)
        let source_local = (source_node % 65536) as u16;
        let target_local = (target_node % 65536) as u16;

        tile.ingest_edge_add(source_local, target_local, weight)
    }

    /// Distribute an edge removal.
    pub fn distribute_edge_remove(&mut self, source_node: u64, target_node: u64) -> TilesResult<()> {
        let tile_id = self.coordinator.tile_for_node(source_node);
        let tile = self
            .tiles
            .get_mut(tile_id as usize)
            .ok_or(TilesError::TileIdOutOfRange(tile_id as u16))?;

        let source_local = (source_node % 65536) as u16;
        let target_local = (target_node % 65536) as u16;

        tile.ingest_edge_remove(source_local, target_local)
    }

    /// Execute one tick across all tiles.
    ///
    /// This is the main processing function that:
    /// 1. Processes all buffered deltas in each tile
    /// 2. Updates evidence accumulators
    /// 3. Recomputes graph connectivity
    /// 4. Aggregates witness fragments
    pub fn tick(&mut self, tick_number: u32) -> TilesResult<FabricReport> {
        if self.state == FabricState::Uninitialized {
            return Err(TilesError::FabricNotStarted);
        }

        let start = Instant::now();
        self.state = FabricState::Running;
        self.current_tick = tick_number;

        // Process all tiles (sequential for now, parallel later)
        let mut tile_reports = Vec::with_capacity(NUM_TILES);
        let mut active_tiles = 0u16;
        let mut total_deltas = 0u32;

        for tile in &mut self.tiles {
            let report = tile.tick(tick_number)?;
            if report.deltas_processed > 0 {
                active_tiles += 1;
                total_deltas += report.deltas_processed as u32;
            }
            tile_reports.push(report);
        }

        // Aggregate witnesses
        let global_witness = if self.config.auto_aggregate {
            self.coordinator.aggregate_witnesses(&self.tiles)?
        } else {
            AggregatedWitness::empty()
        };

        // Compute global energy
        let global_energy = self.coordinator.compute_global_energy(&self.tiles);

        let processing_time_us = start.elapsed().as_micros() as u64;
        self.total_ticks += 1;
        self.state = FabricState::Ready;

        Ok(FabricReport {
            tick: tick_number,
            global_energy,
            global_witness,
            tile_reports,
            processing_time_us,
            active_tiles,
            total_deltas,
        })
    }

    /// Execute multiple ticks in sequence.
    pub fn tick_n(&mut self, count: u32) -> TilesResult<Vec<FabricReport>> {
        let mut reports = Vec::with_capacity(count as usize);
        for i in 0..count {
            let report = self.tick(self.current_tick + i)?;
            reports.push(report);
        }
        Ok(reports)
    }

    /// Get coherence summary across all tiles.
    pub fn coherence_summary(&self) -> CoherenceSummary {
        self.coordinator.coherence_summary(&self.tiles)
    }

    /// Get the last aggregated witness.
    pub fn last_witness(&self) -> Option<&AggregatedWitness> {
        self.coordinator.last_witness()
    }

    /// Check if any tile has pending deltas.
    pub fn has_pending_deltas(&self) -> bool {
        self.tiles.iter().any(|t| t.has_pending_deltas())
    }

    /// Get the number of tiles with pending deltas.
    pub fn pending_delta_count(&self) -> usize {
        self.tiles.iter().filter(|t| t.has_pending_deltas()).count()
    }

    /// Reset all tiles to initial state.
    pub fn reset(&mut self) {
        for tile in &mut self.tiles {
            tile.reset();
        }
        self.coordinator.clear_cache();
        self.current_tick = 0;
        self.total_ticks = 0;
        self.state = FabricState::Ready;
    }

    /// Pause the fabric.
    pub fn pause(&mut self) {
        self.state = FabricState::Paused;
    }

    /// Resume the fabric.
    pub fn resume(&mut self) {
        if self.state == FabricState::Paused {
            self.state = FabricState::Ready;
        }
    }

    /// Get fabric statistics.
    pub fn stats(&self) -> FabricStats {
        let mut total_vertices = 0u32;
        let mut total_edges = 0u32;
        let mut tiles_with_data = 0u16;

        for tile in &self.tiles {
            let graph_stats = tile.graph_stats();
            if graph_stats.num_vertices > 0 {
                total_vertices += graph_stats.num_vertices as u32;
                total_edges += graph_stats.num_edges as u32;
                tiles_with_data += 1;
            }
        }

        FabricStats {
            total_tiles: NUM_TILES as u16,
            tiles_with_data,
            total_vertices,
            total_edges,
            total_ticks: self.total_ticks,
            current_tick: self.current_tick,
            state: self.state,
        }
    }
}

impl std::fmt::Debug for CoherenceFabric {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CoherenceFabric")
            .field("state", &self.state)
            .field("current_tick", &self.current_tick)
            .field("total_ticks", &self.total_ticks)
            .field("pending_tiles", &self.pending_delta_count())
            .finish()
    }
}

/// Fabric statistics.
#[derive(Debug, Clone, Copy)]
pub struct FabricStats {
    /// Total number of tiles.
    pub total_tiles: u16,
    /// Tiles with graph data.
    pub tiles_with_data: u16,
    /// Total vertices across all tiles.
    pub total_vertices: u32,
    /// Total edges across all tiles.
    pub total_edges: u32,
    /// Total ticks processed.
    pub total_ticks: u64,
    /// Current tick number.
    pub current_tick: u32,
    /// Current fabric state.
    pub state: FabricState,
}

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

    #[test]
    fn test_fabric_creation() {
        let fabric = CoherenceFabric::default_fabric().unwrap();
        assert_eq!(fabric.state(), FabricState::Ready);
        assert_eq!(fabric.current_tick(), 0);
    }

    #[test]
    fn test_fabric_tick_empty() {
        let mut fabric = CoherenceFabric::default_fabric().unwrap();
        let report = fabric.tick(1).unwrap();
        assert_eq!(report.tick, 1);
        assert_eq!(report.active_tiles, 0);
    }

    #[test]
    fn test_fabric_distribute_and_tick() {
        let mut fabric = CoherenceFabric::default_fabric().unwrap();

        // Add some edges
        fabric.distribute_edge_add(0, 1, 100).unwrap();
        fabric.distribute_edge_add(1, 2, 100).unwrap();

        assert!(fabric.has_pending_deltas());

        let report = fabric.tick(1).unwrap();
        assert!(report.active_tiles > 0);
        assert!(report.total_deltas > 0);
    }

    #[test]
    fn test_fabric_reset() {
        let mut fabric = CoherenceFabric::default_fabric().unwrap();

        fabric.distribute_edge_add(0, 1, 100).unwrap();
        fabric.tick(1).unwrap();

        fabric.reset();

        assert_eq!(fabric.current_tick(), 0);
        assert_eq!(fabric.total_ticks(), 0);
        assert!(!fabric.has_pending_deltas());
    }

    #[test]
    fn test_fabric_stats() {
        let fabric = CoherenceFabric::default_fabric().unwrap();
        let stats = fabric.stats();

        assert_eq!(stats.total_tiles, 256);
        assert_eq!(stats.state, FabricState::Ready);
    }
}