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
//! Governance Layer
//!
//! First-class, immutable, addressable governance objects for the Coherence Engine.
//!
//! This module implements ADR-CE-005: "Governance objects are first-class, immutable, addressable"
//!
//! # Core Invariants
//!
//! 1. **No action without witness**: Every gate decision must produce a `WitnessRecord`
//! 2. **No write without lineage**: Every authoritative write must have a `LineageRecord`
//! 3. **Policy immutability**: Once activated, a `PolicyBundle` cannot be modified
//! 4. **Multi-party approval**: Critical policies require multiple `ApprovalSignature`s
//! 5. **Witness chain integrity**: Each witness references its predecessor via Blake3 hash

mod lineage;
mod policy;
mod repository;
mod witness;

pub use policy::{
    ApprovalSignature, ApproverId, EscalationCondition, EscalationRule, PolicyBundle,
    PolicyBundleBuilder, PolicyBundleId, PolicyBundleRef, PolicyBundleStatus, PolicyError,
    ThresholdConfig,
};

pub use witness::{
    ComputeLane as WitnessComputeLane, EnergySnapshot, GateDecision,
    WitnessChainError, WitnessError, WitnessId, WitnessRecord,
};

pub use lineage::{EntityRef, LineageError, LineageId, LineageRecord, Operation};

pub use repository::{LineageRepository, PolicyRepository, WitnessRepository};

use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

/// Blake3 content hash (32 bytes)
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Hash(pub [u8; 32]);

impl Hash {
    /// Create a new hash from bytes
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Create a hash from a Blake3 hasher output
    #[must_use]
    pub fn from_blake3(hash: blake3::Hash) -> Self {
        Self(*hash.as_bytes())
    }

    /// Get the hash as bytes
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Create a zero hash (used as sentinel)
    #[must_use]
    pub const fn zero() -> Self {
        Self([0u8; 32])
    }

    /// Check if this is the zero hash
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.0 == [0u8; 32]
    }

    /// Convert to hex string
    #[must_use]
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }

    /// Parse from hex string
    ///
    /// # Errors
    ///
    /// Returns an error if the hex string is invalid or wrong length
    pub fn from_hex(s: &str) -> Result<Self, hex::FromHexError> {
        let bytes = hex::decode(s)?;
        if bytes.len() != 32 {
            return Err(hex::FromHexError::InvalidStringLength);
        }
        let mut arr = [0u8; 32];
        arr.copy_from_slice(&bytes);
        Ok(Self(arr))
    }
}

impl fmt::Debug for Hash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Hash({})", &self.to_hex()[..16])
    }
}

impl fmt::Display for Hash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Default for Hash {
    fn default() -> Self {
        Self::zero()
    }
}

impl From<blake3::Hash> for Hash {
    fn from(hash: blake3::Hash) -> Self {
        Self::from_blake3(hash)
    }
}

impl AsRef<[u8]> for Hash {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// Timestamp with nanosecond precision
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Timestamp {
    /// Seconds since Unix epoch
    pub secs: i64,
    /// Nanoseconds within the second
    pub nanos: u32,
}

impl Timestamp {
    /// Create a new timestamp
    #[must_use]
    pub const fn new(secs: i64, nanos: u32) -> Self {
        Self { secs, nanos }
    }

    /// Get the current timestamp
    #[must_use]
    pub fn now() -> Self {
        let dt = chrono::Utc::now();
        Self {
            secs: dt.timestamp(),
            nanos: dt.timestamp_subsec_nanos(),
        }
    }

    /// Create a timestamp from Unix epoch seconds
    #[must_use]
    pub const fn from_secs(secs: i64) -> Self {
        Self { secs, nanos: 0 }
    }

    /// Convert to Unix epoch milliseconds
    #[must_use]
    pub const fn as_millis(&self) -> i64 {
        self.secs * 1000 + (self.nanos / 1_000_000) as i64
    }

    /// Create from Unix epoch milliseconds
    #[must_use]
    pub const fn from_millis(millis: i64) -> Self {
        Self {
            secs: millis / 1000,
            nanos: ((millis % 1000) * 1_000_000) as u32,
        }
    }

    /// Convert to chrono DateTime
    #[must_use]
    pub fn to_datetime(&self) -> chrono::DateTime<chrono::Utc> {
        chrono::DateTime::from_timestamp(self.secs, self.nanos).unwrap_or_else(chrono::Utc::now)
    }
}

impl Default for Timestamp {
    fn default() -> Self {
        Self::now()
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.to_datetime().format("%Y-%m-%d %H:%M:%S%.3f UTC")
        )
    }
}

impl From<chrono::DateTime<chrono::Utc>> for Timestamp {
    fn from(dt: chrono::DateTime<chrono::Utc>) -> Self {
        Self {
            secs: dt.timestamp(),
            nanos: dt.timestamp_subsec_nanos(),
        }
    }
}

/// Semantic version for policy bundles
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Version {
    /// Major version (breaking changes)
    pub major: u32,
    /// Minor version (new features, backward compatible)
    pub minor: u32,
    /// Patch version (bug fixes)
    pub patch: u32,
}

impl Version {
    /// Create a new version
    #[must_use]
    pub const fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Initial version (1.0.0)
    #[must_use]
    pub const fn initial() -> Self {
        Self::new(1, 0, 0)
    }

    /// Increment patch version
    #[must_use]
    pub const fn bump_patch(self) -> Self {
        Self {
            major: self.major,
            minor: self.minor,
            patch: self.patch + 1,
        }
    }

    /// Increment minor version (resets patch)
    #[must_use]
    pub const fn bump_minor(self) -> Self {
        Self {
            major: self.major,
            minor: self.minor + 1,
            patch: 0,
        }
    }

    /// Increment major version (resets minor and patch)
    #[must_use]
    pub const fn bump_major(self) -> Self {
        Self {
            major: self.major + 1,
            minor: 0,
            patch: 0,
        }
    }
}

impl Default for Version {
    fn default() -> Self {
        Self::initial()
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

impl std::str::FromStr for Version {
    type Err = GovernanceError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() != 3 {
            return Err(GovernanceError::InvalidVersion(s.to_string()));
        }

        let major = parts[0]
            .parse()
            .map_err(|_| GovernanceError::InvalidVersion(s.to_string()))?;
        let minor = parts[1]
            .parse()
            .map_err(|_| GovernanceError::InvalidVersion(s.to_string()))?;
        let patch = parts[2]
            .parse()
            .map_err(|_| GovernanceError::InvalidVersion(s.to_string()))?;

        Ok(Self {
            major,
            minor,
            patch,
        })
    }
}

/// Top-level governance error
#[derive(Debug, Error)]
pub enum GovernanceError {
    /// Policy-related error
    #[error("Policy error: {0}")]
    Policy(#[from] PolicyError),

    /// Witness-related error
    #[error("Witness error: {0}")]
    Witness(#[from] WitnessError),

    /// Lineage-related error
    #[error("Lineage error: {0}")]
    Lineage(#[from] LineageError),

    /// Invalid version format
    #[error("Invalid version format: {0}")]
    InvalidVersion(String),

    /// Serialization error
    #[error("Serialization error: {0}")]
    Serialization(String),

    /// Repository error
    #[error("Repository error: {0}")]
    Repository(String),

    /// Invariant violation
    #[error("Invariant violation: {0}")]
    InvariantViolation(String),
}

// Hex encoding utilities (inline to avoid external dependency)
mod hex {
    pub use std::fmt::Write;

    #[derive(Debug)]
    pub enum FromHexError {
        InvalidStringLength,
        InvalidHexCharacter(char),
    }

    impl std::fmt::Display for FromHexError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::InvalidStringLength => write!(f, "invalid hex string length"),
                Self::InvalidHexCharacter(c) => write!(f, "invalid hex character: {c}"),
            }
        }
    }

    impl std::error::Error for FromHexError {}

    pub fn encode(bytes: impl AsRef<[u8]>) -> String {
        let bytes = bytes.as_ref();
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in bytes {
            write!(s, "{b:02x}").unwrap();
        }
        s
    }

    pub fn decode(s: &str) -> Result<Vec<u8>, FromHexError> {
        if s.len() % 2 != 0 {
            return Err(FromHexError::InvalidStringLength);
        }

        let mut bytes = Vec::with_capacity(s.len() / 2);
        let mut chars = s.chars();

        while let (Some(h), Some(l)) = (chars.next(), chars.next()) {
            let high = h.to_digit(16).ok_or(FromHexError::InvalidHexCharacter(h))? as u8;
            let low = l.to_digit(16).ok_or(FromHexError::InvalidHexCharacter(l))? as u8;
            bytes.push((high << 4) | low);
        }

        Ok(bytes)
    }
}

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

    #[test]
    fn test_hash_creation_and_display() {
        let bytes = [1u8; 32];
        let hash = Hash::from_bytes(bytes);

        assert_eq!(hash.as_bytes(), &bytes);
        assert!(!hash.is_zero());

        let hex = hash.to_hex();
        let parsed = Hash::from_hex(&hex).unwrap();
        assert_eq!(hash, parsed);
    }

    #[test]
    fn test_hash_zero() {
        let zero = Hash::zero();
        assert!(zero.is_zero());
        assert_eq!(zero.as_bytes(), &[0u8; 32]);
    }

    #[test]
    fn test_timestamp() {
        let ts = Timestamp::now();
        assert!(ts.secs > 0);

        let from_secs = Timestamp::from_secs(1700000000);
        assert_eq!(from_secs.secs, 1700000000);
        assert_eq!(from_secs.nanos, 0);

        let from_millis = Timestamp::from_millis(1700000000123);
        assert_eq!(from_millis.secs, 1700000000);
        assert_eq!(from_millis.nanos, 123_000_000);
    }

    #[test]
    fn test_version() {
        let v = Version::new(1, 2, 3);
        assert_eq!(v.to_string(), "1.2.3");

        let parsed: Version = "2.3.4".parse().unwrap();
        assert_eq!(parsed, Version::new(2, 3, 4));

        let bumped = Version::new(1, 2, 3).bump_patch();
        assert_eq!(bumped, Version::new(1, 2, 4));

        let minor_bump = Version::new(1, 2, 3).bump_minor();
        assert_eq!(minor_bump, Version::new(1, 3, 0));

        let major_bump = Version::new(1, 2, 3).bump_major();
        assert_eq!(major_bump, Version::new(2, 0, 0));
    }
}