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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Domain events for the Prime-Radiant coherence engine.
//!
//! All domain events are persisted to the event log for deterministic replay.
//! This enables:
//! - Temporal ordering of all decisions
//! - Tamper detection via content hashes
//! - Deterministic replay capability

use crate::types::{
    EdgeId, Hash, LineageId, NodeId, PolicyBundleId, ScopeId, Timestamp, WitnessId,
};
use serde::{Deserialize, Serialize};

// ============================================================================
// DOMAIN EVENT ENUM
// ============================================================================

/// All domain events in the coherence engine
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DomainEvent {
    // -------------------------------------------------------------------------
    // Substrate Events
    // -------------------------------------------------------------------------
    /// A new node was created in the sheaf graph
    NodeCreated {
        /// Node ID
        node_id: NodeId,
        /// Namespace
        namespace: String,
        /// State dimension
        dimension: usize,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// A node's state was updated
    NodeUpdated {
        /// Node ID
        node_id: NodeId,
        /// Previous state hash
        previous_hash: Hash,
        /// New state hash
        new_hash: Hash,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// A node was removed from the graph
    NodeRemoved {
        /// Node ID
        node_id: NodeId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// A new edge was created with restriction maps
    EdgeCreated {
        /// Edge ID
        edge_id: EdgeId,
        /// Source node
        source: NodeId,
        /// Target node
        target: NodeId,
        /// Edge weight
        weight: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// An edge was removed
    EdgeRemoved {
        /// Edge ID
        edge_id: EdgeId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Edge weight was updated
    EdgeWeightUpdated {
        /// Edge ID
        edge_id: EdgeId,
        /// Previous weight
        previous_weight: f32,
        /// New weight
        new_weight: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    // -------------------------------------------------------------------------
    // Coherence Computation Events
    // -------------------------------------------------------------------------
    /// Full coherence energy was computed
    EnergyComputed {
        /// Total energy value
        total_energy: f32,
        /// Number of edges computed
        edge_count: usize,
        /// Graph fingerprint
        fingerprint: Hash,
        /// Computation duration in microseconds
        duration_us: u64,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Incremental energy update was computed
    EnergyUpdated {
        /// Node that triggered update
        trigger_node: NodeId,
        /// Number of affected edges
        affected_edges: usize,
        /// New total energy
        new_energy: f32,
        /// Delta from previous energy
        energy_delta: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Spectral drift was detected
    DriftDetected {
        /// Drift magnitude
        magnitude: f32,
        /// Affected eigenvalue modes
        affected_modes: Vec<usize>,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// High-energy edge identified (hotspot)
    HotspotIdentified {
        /// Edge ID
        edge_id: EdgeId,
        /// Edge energy
        energy: f32,
        /// Energy rank (1 = highest)
        rank: usize,
        /// Event timestamp
        timestamp: Timestamp,
    },

    // -------------------------------------------------------------------------
    // Governance Events
    // -------------------------------------------------------------------------
    /// New policy bundle was created
    PolicyCreated {
        /// Policy bundle ID
        bundle_id: PolicyBundleId,
        /// Version
        version: String,
        /// Required approvals
        required_approvals: usize,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Policy bundle was signed by an approver
    PolicySigned {
        /// Policy bundle ID
        bundle_id: PolicyBundleId,
        /// Approver ID (as string for serialization)
        approver: String,
        /// Current signature count
        signature_count: usize,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Policy bundle reached required approvals
    PolicyApproved {
        /// Policy bundle ID
        bundle_id: PolicyBundleId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Policy bundle was activated
    PolicyActivated {
        /// Policy bundle ID
        bundle_id: PolicyBundleId,
        /// Previous active policy (if any)
        previous_policy: Option<PolicyBundleId>,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Policy bundle was deprecated
    PolicyDeprecated {
        /// Policy bundle ID
        bundle_id: PolicyBundleId,
        /// Replacement policy
        replacement: PolicyBundleId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Witness record was created
    WitnessCreated {
        /// Witness ID
        witness_id: WitnessId,
        /// Action hash
        action_hash: Hash,
        /// Energy at decision time
        energy: f32,
        /// Decision (allowed/denied)
        allowed: bool,
        /// Compute lane assigned
        lane: u8,
        /// Previous witness in chain
        previous_witness: Option<WitnessId>,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Lineage record was created
    LineageCreated {
        /// Lineage ID
        lineage_id: LineageId,
        /// Entity reference
        entity_ref: String,
        /// Operation type
        operation: String,
        /// Authorizing witness
        witness_id: WitnessId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    // -------------------------------------------------------------------------
    // Execution Events
    // -------------------------------------------------------------------------
    /// Action was allowed by the coherence gate
    ActionAllowed {
        /// Action hash
        action_hash: Hash,
        /// Scope
        scope: ScopeId,
        /// Compute lane used
        lane: u8,
        /// Energy at decision
        energy: f32,
        /// Witness ID
        witness_id: WitnessId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Action was denied by the coherence gate
    ActionDenied {
        /// Action hash
        action_hash: Hash,
        /// Scope
        scope: ScopeId,
        /// Reason for denial
        reason: String,
        /// Energy at decision
        energy: f32,
        /// Witness ID
        witness_id: WitnessId,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Escalation was triggered
    EscalationTriggered {
        /// Action hash
        action_hash: Hash,
        /// From lane
        from_lane: u8,
        /// To lane
        to_lane: u8,
        /// Reason
        reason: String,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Human review was requested
    HumanReviewRequested {
        /// Action hash
        action_hash: Hash,
        /// Scope
        scope: ScopeId,
        /// Energy at request
        energy: f32,
        /// Persistence duration in seconds
        persistence_secs: u64,
        /// Event timestamp
        timestamp: Timestamp,
    },

    // -------------------------------------------------------------------------
    // Threshold Tuning Events (SONA)
    // -------------------------------------------------------------------------
    /// Regime started for threshold learning
    RegimeStarted {
        /// Regime ID
        regime_id: String,
        /// Initial energy
        initial_energy: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Regime ended with outcome
    RegimeEnded {
        /// Regime ID
        regime_id: String,
        /// Final quality score
        quality: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Successful pattern was learned
    PatternLearned {
        /// Pattern type
        pattern_type: String,
        /// Quality score
        quality: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Threshold was adapted via Micro-LoRA
    ThresholdAdapted {
        /// Scope affected
        scope: ScopeId,
        /// Previous threshold
        previous_reflex: f32,
        /// New threshold
        new_reflex: f32,
        /// Trigger (energy spike magnitude)
        trigger: f32,
        /// Event timestamp
        timestamp: Timestamp,
    },

    // -------------------------------------------------------------------------
    // Tile Fabric Events
    // -------------------------------------------------------------------------
    /// Fabric tick completed
    FabricTickCompleted {
        /// Tick number
        tick: u32,
        /// Global energy
        global_energy: f32,
        /// Active tiles
        active_tiles: usize,
        /// Duration in microseconds
        duration_us: u64,
        /// Event timestamp
        timestamp: Timestamp,
    },

    /// Evidence threshold crossed in tile
    EvidenceThresholdCrossed {
        /// Tile ID
        tile_id: u8,
        /// E-value
        e_value: f64,
        /// Event timestamp
        timestamp: Timestamp,
    },
}

impl DomainEvent {
    /// Get the event type as a string
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::NodeCreated { .. } => "NodeCreated",
            Self::NodeUpdated { .. } => "NodeUpdated",
            Self::NodeRemoved { .. } => "NodeRemoved",
            Self::EdgeCreated { .. } => "EdgeCreated",
            Self::EdgeRemoved { .. } => "EdgeRemoved",
            Self::EdgeWeightUpdated { .. } => "EdgeWeightUpdated",
            Self::EnergyComputed { .. } => "EnergyComputed",
            Self::EnergyUpdated { .. } => "EnergyUpdated",
            Self::DriftDetected { .. } => "DriftDetected",
            Self::HotspotIdentified { .. } => "HotspotIdentified",
            Self::PolicyCreated { .. } => "PolicyCreated",
            Self::PolicySigned { .. } => "PolicySigned",
            Self::PolicyApproved { .. } => "PolicyApproved",
            Self::PolicyActivated { .. } => "PolicyActivated",
            Self::PolicyDeprecated { .. } => "PolicyDeprecated",
            Self::WitnessCreated { .. } => "WitnessCreated",
            Self::LineageCreated { .. } => "LineageCreated",
            Self::ActionAllowed { .. } => "ActionAllowed",
            Self::ActionDenied { .. } => "ActionDenied",
            Self::EscalationTriggered { .. } => "EscalationTriggered",
            Self::HumanReviewRequested { .. } => "HumanReviewRequested",
            Self::RegimeStarted { .. } => "RegimeStarted",
            Self::RegimeEnded { .. } => "RegimeEnded",
            Self::PatternLearned { .. } => "PatternLearned",
            Self::ThresholdAdapted { .. } => "ThresholdAdapted",
            Self::FabricTickCompleted { .. } => "FabricTickCompleted",
            Self::EvidenceThresholdCrossed { .. } => "EvidenceThresholdCrossed",
        }
    }

    /// Get the timestamp of the event
    pub fn timestamp(&self) -> Timestamp {
        match self {
            Self::NodeCreated { timestamp, .. }
            | Self::NodeUpdated { timestamp, .. }
            | Self::NodeRemoved { timestamp, .. }
            | Self::EdgeCreated { timestamp, .. }
            | Self::EdgeRemoved { timestamp, .. }
            | Self::EdgeWeightUpdated { timestamp, .. }
            | Self::EnergyComputed { timestamp, .. }
            | Self::EnergyUpdated { timestamp, .. }
            | Self::DriftDetected { timestamp, .. }
            | Self::HotspotIdentified { timestamp, .. }
            | Self::PolicyCreated { timestamp, .. }
            | Self::PolicySigned { timestamp, .. }
            | Self::PolicyApproved { timestamp, .. }
            | Self::PolicyActivated { timestamp, .. }
            | Self::PolicyDeprecated { timestamp, .. }
            | Self::WitnessCreated { timestamp, .. }
            | Self::LineageCreated { timestamp, .. }
            | Self::ActionAllowed { timestamp, .. }
            | Self::ActionDenied { timestamp, .. }
            | Self::EscalationTriggered { timestamp, .. }
            | Self::HumanReviewRequested { timestamp, .. }
            | Self::RegimeStarted { timestamp, .. }
            | Self::RegimeEnded { timestamp, .. }
            | Self::PatternLearned { timestamp, .. }
            | Self::ThresholdAdapted { timestamp, .. }
            | Self::FabricTickCompleted { timestamp, .. }
            | Self::EvidenceThresholdCrossed { timestamp, .. } => *timestamp,
        }
    }

    /// Compute content hash for integrity
    pub fn content_hash(&self) -> Hash {
        let serialized = serde_json::to_vec(self).unwrap_or_default();
        Hash::digest(&serialized)
    }
}

// ============================================================================
// EVENT METADATA
// ============================================================================

/// Metadata for an event in the event log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventMetadata {
    /// Sequence number in the log
    pub sequence: u64,
    /// Content hash for integrity
    pub content_hash: Hash,
    /// Signature (if signed)
    pub signature: Option<Vec<u8>>,
}

/// A complete event record with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventRecord {
    /// The domain event
    pub event: DomainEvent,
    /// Event metadata
    pub metadata: EventMetadata,
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_event_serialization() {
        let event = DomainEvent::NodeCreated {
            node_id: NodeId::new(),
            namespace: "test".to_string(),
            dimension: 64,
            timestamp: Timestamp::now(),
        };

        let json = serde_json::to_string(&event).unwrap();
        let decoded: DomainEvent = serde_json::from_str(&json).unwrap();

        assert_eq!(event.event_type(), decoded.event_type());
    }

    #[test]
    fn test_event_content_hash() {
        let event = DomainEvent::EnergyComputed {
            total_energy: 0.5,
            edge_count: 100,
            fingerprint: Hash::zero(),
            duration_us: 1000,
            timestamp: Timestamp::now(),
        };

        let h1 = event.content_hash();
        let h2 = event.content_hash();
        assert_eq!(h1, h2);
    }
}